diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index acc33a0..7fe1af6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -33,6 +33,9 @@ jobs: - name: Build run: dotnet build --configuration Release --no-restore + - name: Test + run: dotnet test ../backend.Tests --configuration Release + publish-backend: name: Push Yale Access Backend Docker Image runs-on: ubuntu-latest @@ -83,6 +86,10 @@ jobs: working-directory: packages/frontend runtime: node@22 + - name: Test + working-directory: ./packages/frontend + run: pnpm run test + - name: Build working-directory: ./packages/frontend run: pnpm run build diff --git a/packages/backend.Tests/.gitignore b/packages/backend.Tests/.gitignore new file mode 100644 index 0000000..cd42ee3 --- /dev/null +++ b/packages/backend.Tests/.gitignore @@ -0,0 +1,2 @@ +bin/ +obj/ diff --git a/packages/backend.Tests/AuthenticationTests.cs b/packages/backend.Tests/AuthenticationTests.cs new file mode 100644 index 0000000..52bef16 --- /dev/null +++ b/packages/backend.Tests/AuthenticationTests.cs @@ -0,0 +1,101 @@ +using System.Net; +using System.Net.Http.Json; + +namespace YaleAccess.Tests; + +public class AuthenticationTests +{ + [Fact] + public async Task Protected_endpoints_return_401_without_a_login() + { + using var app = new TestApp(); + var client = app.CreateClient(); + + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/Yale/codes")).StatusCode); + } + + [Fact] + public async Task Health_endpoint_is_anonymous() + { + using var app = new TestApp(); + var response = await app.CreateClient().GetAsync("/api/Health"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Wrong_password_is_rejected_and_sets_no_cookie() + { + using var app = new TestApp(); + var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", "wrong"); + + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.False(response.Headers.Contains("Set-Cookie")); + var body = await response.ReadApiAsync(); + Assert.False(body.GetProperty("success").GetBoolean()); + Assert.Equal("Incorrect password.", body.GetProperty("error").GetString()); + } + + [Fact] + public async Task Correct_password_sets_a_strict_httponly_cookie_and_grants_access() + { + using var app = new TestApp(); + var client = app.CreateClient(); + + var login = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password); + Assert.Equal(HttpStatusCode.OK, login.StatusCode); + + var cookie = Assert.Single(login.Headers.GetValues("Set-Cookie")); + Assert.Contains("samesite=strict", cookie, StringComparison.OrdinalIgnoreCase); + Assert.Contains("httponly", cookie, StringComparison.OrdinalIgnoreCase); + + Assert.Equal(HttpStatusCode.OK, (await client.GetAsync("/api/People")).StatusCode); + } + + [Fact] + public async Task Passwords_containing_quotes_and_backslashes_work() + { + const string password = "pa\"ss\\word"; + using var app = new TestApp(password); + var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", password); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Logout_ends_the_session() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + Assert.Equal(HttpStatusCode.OK, (await client.PostAsync("/api/Authentication/logout", null)).StatusCode); + Assert.Equal(HttpStatusCode.Unauthorized, (await client.GetAsync("/api/People")).StatusCode); + } + + [Fact] + public async Task Login_is_refused_when_no_password_is_configured() + { + using var app = new TestApp(password: ""); + var response = await app.CreateClient().PostAsJsonAsync("/api/Authentication/login", ""); + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + } + + [Fact] + public async Task Login_attempts_are_rate_limited() + { + using var app = new TestApp(); + var client = app.CreateClient(); + + for (int i = 0; i < 5; i++) + { + var attempt = await client.PostAsJsonAsync("/api/Authentication/login", "wrong"); + Assert.Equal(HttpStatusCode.Unauthorized, attempt.StatusCode); + } + + // Even the right password is blocked once the limit is hit + var limited = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password); + Assert.Equal(HttpStatusCode.TooManyRequests, limited.StatusCode); + var body = await limited.ReadApiAsync(); + Assert.False(body.GetProperty("success").GetBoolean()); + Assert.Contains("Too many", body.GetProperty("error").GetString()); + } +} diff --git a/packages/backend.Tests/PeopleTests.cs b/packages/backend.Tests/PeopleTests.cs new file mode 100644 index 0000000..f8ccffb --- /dev/null +++ b/packages/backend.Tests/PeopleTests.cs @@ -0,0 +1,77 @@ +using System.Net; +using System.Net.Http.Json; + +namespace YaleAccess.Tests; + +public class PeopleTests +{ + [Fact] + public async Task Create_list_and_delete_a_person() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var created = await client.PostAsJsonAsync("/api/People", new { name = " Alex ", phoneNumber = "+61400000001" }); + Assert.Equal(HttpStatusCode.OK, created.StatusCode); + var person = (await created.ReadApiAsync()).GetProperty("data"); + Assert.Equal("Alex", person.GetProperty("name").GetString()); // trimmed + int id = person.GetProperty("id").GetInt32(); + + var list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data"); + Assert.Single(list.EnumerateArray()); + + Assert.Equal(HttpStatusCode.OK, (await client.DeleteAsync($"/api/People/{id}")).StatusCode); + list = (await (await client.GetAsync("/api/People")).ReadApiAsync()).GetProperty("data"); + Assert.Empty(list.EnumerateArray()); + } + + [Theory] + [InlineData("0400000000")] // no country code + [InlineData("+61 400 000 001")] // spaces + [InlineData("+0123456789")] // leading zero after + + [InlineData("+12345")] // too short + [InlineData("")] + public async Task Invalid_phone_numbers_are_rejected(string phone) + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsJsonAsync("/api/People", new { name = "Alex", phoneNumber = phone }); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Contains("international format", (await response.ReadApiAsync()).GetProperty("error").GetString()); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public async Task A_name_is_required(string name) + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsJsonAsync("/api/People", new { name, phoneNumber = "+61400000001" }); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task Names_over_100_characters_are_rejected() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsJsonAsync("/api/People", new { name = new string('a', 101), phoneNumber = "+61400000001" }); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task Deleting_a_missing_person_returns_404() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.DeleteAsync("/api/People/9999"); + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.Equal("Person not found.", (await response.ReadApiAsync()).GetProperty("error").GetString()); + } +} diff --git a/packages/backend.Tests/TestSupport.cs b/packages/backend.Tests/TestSupport.cs new file mode 100644 index 0000000..15d72a0 --- /dev/null +++ b/packages/backend.Tests/TestSupport.cs @@ -0,0 +1,107 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using System.Net.Http.Json; +using System.Text.Json; +using YaleAccess.Models; +using YaleAccess.Services.Interfaces; + +namespace YaleAccess.Tests; + +public static class TestConstants +{ + public const string Password = "test-password"; + public const int HomeCode = 1; +} + +/// +/// In-memory stand-in for the Z-Wave lock. +/// +public class FakeYaleAccessor : IYaleAccessor +{ + public Dictionary Codes { get; } = new() + { + [1] = new() { Id = 1, Code = "1111", Status = UserCodeStatus.ENABLED }, + [2] = new() { Id = 2, Code = "2222", Status = UserCodeStatus.ENABLED }, + [3] = new() { Id = 3, Code = "", Status = UserCodeStatus.AVAILABLE }, + }; + + public bool FailWrites { get; set; } + public bool ThrowOnRead { get; set; } + + public Task GetCodeInformationAsync(int userCodeId) + { + if (ThrowOnRead) throw new InvalidOperationException("Lock unavailable"); + var c = Codes[userCodeId]; + return Task.FromResult(new YaleUserCode { Id = c.Id, Code = c.Code, Status = c.Status }); + } + + public Task SetUserCode(int userCodeId, string code) + { + if (FailWrites) return Task.FromResult(false); + Codes[userCodeId].Code = code; + Codes[userCodeId].Status = UserCodeStatus.ENABLED; + return Task.FromResult(true); + } + + public Task SetCodeAsAvailable(int userCode) + { + if (FailWrites) return Task.FromResult(false); + Codes[userCode].Code = ""; + Codes[userCode].Status = UserCodeStatus.AVAILABLE; + return Task.FromResult(true); + } +} + +/// +/// Boots the real app with a throwaway SQLite database and a fake lock. +/// Use a fresh instance per test: the login rate limiter is per app instance. +/// +public class TestApp : WebApplicationFactory +{ + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"yale-test-{Guid.NewGuid():N}.db"); + private readonly string _password; + + public FakeYaleAccessor Lock { get; } = new(); + + public TestApp(string password = TestConstants.Password) => _password = password; + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + // Development keeps the auth cookie non-Secure, so it works over the test server's plain HTTP + builder.UseEnvironment("Development"); + builder.UseSetting("UseMockDevelopmentMode", "false"); + builder.UseSetting("ConnectionStrings:YaleContext", $"Data Source={_dbPath}"); + builder.UseSetting("Authentication:Password", _password); + builder.UseSetting("Codes:Home", TestConstants.HomeCode.ToString()); + builder.UseSetting("Codes:GuestCodeRangeStart", "2"); + builder.UseSetting("Codes:GuestCodeRangeCount", "2"); + + builder.ConfigureTestServices(services => + { + services.AddSingleton(Lock); + }); + } + + public async Task LoggedInClientAsync() + { + var client = CreateClient(); + var response = await client.PostAsJsonAsync("/api/Authentication/login", TestConstants.Password); + response.EnsureSuccessStatusCode(); + return client; + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + try { File.Delete(_dbPath); } catch { /* best effort */ } + } +} + +public static class HttpExtensions +{ + public static async Task ReadApiAsync(this HttpResponseMessage response) + => await response.Content.ReadFromJsonAsync(); +} diff --git a/packages/backend.Tests/YaleAccess.Tests.csproj b/packages/backend.Tests/YaleAccess.Tests.csproj new file mode 100644 index 0000000..f13e4b4 --- /dev/null +++ b/packages/backend.Tests/YaleAccess.Tests.csproj @@ -0,0 +1,26 @@ + + + + net10.0 + enable + enable + false + true + + + + + + + + + + + + + + + + + + diff --git a/packages/backend.Tests/YaleTests.cs b/packages/backend.Tests/YaleTests.cs new file mode 100644 index 0000000..0eebb8e --- /dev/null +++ b/packages/backend.Tests/YaleTests.cs @@ -0,0 +1,143 @@ +using System.Net; +using System.Net.Http.Json; +using YaleAccess.Models; +using YaleAccess.Services; + +namespace YaleAccess.Tests; + +public class YaleCodeValidationTests +{ + [Theory] + [InlineData("1234")] + [InlineData("12345")] + [InlineData("123456")] + [InlineData("0000")] + public void Valid_codes_pass(string code) => Assert.Equal(string.Empty, YaleAccessor.ValidateCode(code)); + + [Theory] + [InlineData("")] + [InlineData("123")] + [InlineData("1234567")] + public void Wrong_length_is_rejected(string code) => Assert.NotEqual(string.Empty, YaleAccessor.ValidateCode(code)); + + [Theory] + [InlineData("12a4")] + [InlineData("+123")] + [InlineData("-123")] + [InlineData(" 123")] + [InlineData("12.4")] + [InlineData("١٢٣٤")] // Arabic-Indic digits, not ASCII + public void Non_digit_codes_are_rejected(string code) => Assert.Equal("The code must be numeric.", YaleAccessor.ValidateCode(code)); + + [Fact] + public void The_home_code_cannot_be_cleared() + { + Assert.NotEqual(string.Empty, YaleAccessor.ValidateClearCode(1, 1)); + Assert.Equal(string.Empty, YaleAccessor.ValidateClearCode(2, 1)); + } +} + +public class YaleEndpointTests +{ + [Fact] + public async Task Codes_list_includes_guest_codes_and_flags_the_home_code() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var data = (await (await client.GetAsync("/api/Yale/codes")).ReadApiAsync()).GetProperty("data"); + var codes = data.EnumerateArray().ToList(); + + Assert.Equal(3, codes.Count); // 2 guest codes + home + Assert.Equal(new[] { 1 }, codes.Where(c => c.GetProperty("isHome").GetBoolean()).Select(c => c.GetProperty("id").GetInt32())); + } + + [Fact] + public async Task Setting_a_valid_code_updates_the_lock() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsJsonAsync("/api/Yale/code/3", "4321"); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("4321", app.Lock.Codes[3].Code); + Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[3].Status); + } + + [Theory] + [InlineData("12a4")] + [InlineData("+123")] + [InlineData("12")] + public async Task Invalid_codes_are_rejected_without_touching_the_lock(string code) + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsJsonAsync("/api/Yale/code/2", code); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal("2222", app.Lock.Codes[2].Code); + } + + [Fact] + public async Task A_failed_lock_write_returns_502() + { + using var app = new TestApp(); + app.Lock.FailWrites = true; + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsJsonAsync("/api/Yale/code/2", "4321"); + Assert.Equal(HttpStatusCode.BadGateway, response.StatusCode); + } + + [Fact] + public async Task Clearing_a_guest_code_makes_it_available() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsync("/api/Yale/code/2/status", null); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(UserCodeStatus.AVAILABLE, app.Lock.Codes[2].Status); + } + + [Fact] + public async Task The_home_code_cannot_be_cleared_via_the_api() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsync("/api/Yale/code/1/status", null); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal(UserCodeStatus.ENABLED, app.Lock.Codes[1].Status); + } + + [Fact] + public async Task Sending_an_unset_code_is_rejected() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + + var response = await client.PostAsJsonAsync("/api/Yale/code/3/send", "+61400000001"); + + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Fact] + public async Task Unexpected_errors_become_a_json_500_without_leaking_details() + { + using var app = new TestApp(); + var client = await app.LoggedInClientAsync(); + app.Lock.ThrowOnRead = true; + + var response = await client.GetAsync("/api/Yale/codes"); + + Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); + var body = await response.ReadApiAsync(); + Assert.False(body.GetProperty("success").GetBoolean()); + Assert.Equal("An unexpected error occurred.", body.GetProperty("error").GetString()); + } +} diff --git a/packages/frontend/.nuxtrc b/packages/frontend/.nuxtrc new file mode 100644 index 0000000..7fe0c55 --- /dev/null +++ b/packages/frontend/.nuxtrc @@ -0,0 +1 @@ +setups.@nuxt/test-utils="4.4.0" \ No newline at end of file diff --git a/packages/frontend/test/LoginForm.test.ts b/packages/frontend/test/LoginForm.test.ts new file mode 100644 index 0000000..666bd0f --- /dev/null +++ b/packages/frontend/test/LoginForm.test.ts @@ -0,0 +1,66 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { flushPromises } from '@vue/test-utils' +import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime' +import LoginForm from '~/components/LoginForm.vue' + +const { api, navigateToMock } = vi.hoisted(() => ({ + api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() }, + navigateToMock: vi.fn() +})) +mockNuxtImport('useApi', () => () => api) +mockNuxtImport('navigateTo', () => navigateToMock) + +describe('LoginForm', () => { + beforeEach(() => { + api.post.mockReset() + navigateToMock.mockReset() + useCookie('authenticated').value = false + }) + + it('disables the login button until a password is entered', async () => { + const wrapper = await mountSuspended(LoginForm) + const button = wrapper.find('button[type="submit"]') + expect(button.attributes('disabled')).toBeDefined() + + await wrapper.find('input').setValue('secret') + expect(button.attributes('disabled')).toBeUndefined() + }) + + it('logs in with the password, sets the cookie and goes home', async () => { + api.post.mockResolvedValue({ success: true, data: true }) + const wrapper = await mountSuspended(LoginForm) + + await wrapper.find('input').setValue('pa"ss') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(api.post).toHaveBeenCalledWith('/api/Authentication/login', 'pa"ss') + expect(useCookie('authenticated').value).toBe(true) + expect(navigateToMock).toHaveBeenCalledWith('/') + }) + + it('shows the error and stays on the page when the login fails', async () => { + api.post.mockResolvedValue({ success: false, error: 'Incorrect password.' }) + const wrapper = await mountSuspended(LoginForm) + + await wrapper.find('input').setValue('wrong') + await wrapper.find('form').trigger('submit') + await flushPromises() + + expect(wrapper.text()).toContain('Incorrect password.') + expect(useCookie('authenticated').value).toBe(false) + expect(navigateToMock).not.toHaveBeenCalled() + }) + + it('can reveal and hide the password', async () => { + const wrapper = await mountSuspended(LoginForm) + const input = wrapper.find('input') + expect(input.attributes('type')).toBe('password') + + await wrapper.find('button[aria-label="Show password"]').trigger('click') + expect(input.attributes('type')).toBe('text') + + await wrapper.find('button[aria-label="Hide password"]').trigger('click') + expect(input.attributes('type')).toBe('password') + }) +}) diff --git a/packages/frontend/test/PeopleList.test.ts b/packages/frontend/test/PeopleList.test.ts new file mode 100644 index 0000000..68f64b7 --- /dev/null +++ b/packages/frontend/test/PeopleList.test.ts @@ -0,0 +1,101 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { mockNuxtImport } from '@nuxt/test-utils/runtime' +import PeopleList from '~/components/PeopleList.vue' +import { click, inBody, mountInApp, setInput, settle, submitForm } from './helpers' + +const { api } = vi.hoisted(() => ({ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() } })) +mockNuxtImport('useApi', () => () => api) + +const mountList = async () => { + const wrapper = await mountInApp(PeopleList) + await settle() + return wrapper +} + +const openAddModal = async (wrapper: Awaited>) => { + const add = wrapper.findAll('button').find(b => b.text().includes('Add Person')) + await click(add!.element) +} + +const fillAndSubmit = async (name: string, phone: string) => { + const [nameInput, phoneInput] = document.body.querySelectorAll('#add-person input') + await setInput(nameInput!, name) + await setInput(phoneInput!, phone) + await submitForm(inBody('#add-person')!) +} + +describe('PeopleList', () => { + beforeEach(() => { + api.get.mockReset() + api.post.mockReset() + api.delete.mockReset() + api.get.mockResolvedValue({ success: true, data: [{ id: 1, name: 'Alex', phoneNumber: '+61400000001' }] }) + document.body.innerHTML = '' + }) + + it('lists the people', async () => { + const wrapper = await mountList() + const row = wrapper.find('tbody tr') + + expect(row.text()).toContain('Alex') + expect(row.text()).toContain('+61400000001') + }) + + it('shows an empty state', async () => { + api.get.mockResolvedValue({ success: true, data: [] }) + const wrapper = await mountList() + expect(wrapper.text()).toContain('No people yet.') + }) + + it('requires a name and an international phone number before saving', async () => { + const wrapper = await mountList() + await openAddModal(wrapper) + + await fillAndSubmit('', '0400 000 000') + + expect(document.body.textContent).toContain('Name is required') + expect(document.body.textContent).toContain('Use international format') + expect(api.post).not.toHaveBeenCalled() + }) + + it('adds a person and shows them in the table', async () => { + api.post.mockResolvedValue({ success: true, data: { id: 2, name: 'Sam', phoneNumber: '+61400000002' } }) + const wrapper = await mountList() + await openAddModal(wrapper) + + await fillAndSubmit('Sam', '+61400000002') + + expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/People', { id: 0, name: 'Sam', phoneNumber: '+61400000002' }) + expect(wrapper.findAll('tbody tr')).toHaveLength(2) + expect(wrapper.text()).toContain('Sam') + }) + + it('keeps the list unchanged when the API rejects the new person', async () => { + api.post.mockResolvedValue({ success: false, error: 'nope' }) + const wrapper = await mountList() + await openAddModal(wrapper) + + await fillAndSubmit('Sam', '+61400000002') + + expect(wrapper.findAll('tbody tr')).toHaveLength(1) + }) + + it('deletes a person', async () => { + api.delete.mockResolvedValue({ success: true, data: { id: 1 } }) + const wrapper = await mountList() + + await click(wrapper.find('button[aria-label="Delete Alex"]').element) + + expect(api.delete).toHaveBeenCalledExactlyOnceWith('/api/People/1') + expect(wrapper.text()).not.toContain('+61400000001') + }) + + it('keeps the person when the delete fails', async () => { + api.delete.mockResolvedValue({ success: false, error: 'Person not found.' }) + const wrapper = await mountList() + + await click(wrapper.find('button[aria-label="Delete Alex"]').element) + + expect(wrapper.text()).toContain('Alex') + }) +}) diff --git a/packages/frontend/test/UserCodeList.test.ts b/packages/frontend/test/UserCodeList.test.ts new file mode 100644 index 0000000..859896f --- /dev/null +++ b/packages/frontend/test/UserCodeList.test.ts @@ -0,0 +1,135 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { mockNuxtImport } from '@nuxt/test-utils/runtime' +import UserCodeList from '~/components/UserCodeList.vue' +import { UserCodeStatus } from '~/types/yale' +import { click, inBody, mountInApp, setInput, settle, submitForm } from './helpers' + +const { api } = vi.hoisted(() => ({ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() } })) +mockNuxtImport('useApi', () => () => api) + +const codes = [ + { id: 4, code: '9999', status: UserCodeStatus.ENABLED, isHome: true }, + { id: 2, code: '2222', status: UserCodeStatus.ENABLED, isHome: false }, + { id: 3, code: '', status: UserCodeStatus.AVAILABLE, isHome: false } +] + +const mountList = async () => { + const wrapper = await mountInApp(UserCodeList) + await settle() + return wrapper +} + +const rows = (wrapper: Awaited>) => wrapper.findAll('tbody tr') +const buttonLabels = (row: { findAll: (s: string) => { attributes: (n: string) => string | undefined }[] }) => + row.findAll('button').map(b => b.attributes('aria-label')) + +describe('UserCodeList', () => { + beforeEach(() => { + api.get.mockReset() + api.post.mockReset() + api.get.mockImplementation(async (path: string) => + path === '/api/Yale/codes' + ? { success: true, data: structuredClone(codes) } + : { success: true, data: [{ id: 1, name: 'Alex', phoneNumber: '+61400000001' }] }) + api.post.mockResolvedValue({ success: true, data: true }) + document.body.innerHTML = '' + }) + + it('lists the codes sorted by id with their status', async () => { + const wrapper = await mountList() + const r = rows(wrapper) + + expect(r).toHaveLength(3) + expect(r.map(x => x.findAll('td')[0]!.text())).toEqual(['2', '3', '4']) + expect(r[0]!.text()).toContain('Enabled') + expect(r[1]!.text()).toContain('Available') + }) + + it('only offers show and edit for the home code, and marks it with the home icon', async () => { + const wrapper = await mountList() + const home = rows(wrapper)[2]! + + expect(buttonLabels(home)).toEqual(['Show code', 'Edit code']) + expect(home.find('[aria-label="Home code"]').exists()).toBe(true) + }) + + it('disables show, send and delete for an available (unset) code', async () => { + const wrapper = await mountList() + const available = rows(wrapper)[1]! + + for (const label of ['Show code', 'Send code', 'Delete code']) { + expect(available.find(`button[aria-label="${label}"]`).attributes('disabled')).toBeDefined() + } + expect(available.find('button[aria-label="Edit code"]').attributes('disabled')).toBeUndefined() + }) + + it('shows the code in a modal', async () => { + const wrapper = await mountList() + await click(rows(wrapper)[0]!.find('button[aria-label="Show code"]').element) + + expect(document.body.textContent).toContain('User Code #2') + expect(document.body.textContent).toContain('2222') + }) + + it('rejects a code that is not 4-6 digits without calling the API', async () => { + const wrapper = await mountList() + await click(rows(wrapper)[0]!.find('button[aria-label="Edit code"]').element) + + await setInput(inBody('input')!, '12') + await submitForm(inBody('#edit-code')!) + + expect(document.body.textContent).toContain('Code must be 4, 5 or 6 digits long') + expect(api.post).not.toHaveBeenCalled() + }) + + it('updates a code through the API and reflects it in the table', async () => { + const wrapper = await mountList() + await click(rows(wrapper)[1]!.find('button[aria-label="Edit code"]').element) // available code #3 + + await setInput(inBody('input')!, '123456') + await submitForm(inBody('#edit-code')!) + + expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/Yale/code/3', '123456') + expect(rows(wrapper)[1]!.text()).toContain('Enabled') + }) + + it('warns before editing the home code', async () => { + const wrapper = await mountList() + await click(rows(wrapper)[2]!.find('button[aria-label="Edit code"]').element) + + expect(document.body.textContent).toContain('You are about to edit the home code') + }) + + it('does not change the table when the API rejects the update', async () => { + api.post.mockResolvedValue({ success: false, error: 'An error occurred setting the code.' }) + const wrapper = await mountList() + await click(rows(wrapper)[1]!.find('button[aria-label="Edit code"]').element) + + await setInput(inBody('input')!, '4321') + await submitForm(inBody('#edit-code')!) + + expect(rows(wrapper)[1]!.text()).toContain('Available') + }) + + it('deletes a code after confirmation and marks it available', async () => { + const wrapper = await mountList() + await click(rows(wrapper)[0]!.find('button[aria-label="Delete code"]').element) // code #2 + + expect(document.body.textContent).toContain('Are you sure you want to delete this code?') + expect(api.post).not.toHaveBeenCalled() + + const confirm = [...document.body.querySelectorAll('button')].find(b => b.textContent?.trim() === 'Delete Code') + await click(confirm ?? null) + + expect(api.post).toHaveBeenCalledExactlyOnceWith('/api/Yale/code/2/status') + expect(rows(wrapper)[0]!.text()).toContain('Available') + }) + + it('keeps the send button disabled until a person is chosen', async () => { + const wrapper = await mountList() + await click(rows(wrapper)[0]!.find('button[aria-label="Send code"]').element) + + const send = [...document.body.querySelectorAll('button')].find(b => b.textContent?.trim() === 'Send Code') + expect(send?.hasAttribute('disabled')).toBe(true) + }) +}) diff --git a/packages/frontend/test/authentication.middleware.test.ts b/packages/frontend/test/authentication.middleware.test.ts new file mode 100644 index 0000000..3d726f0 --- /dev/null +++ b/packages/frontend/test/authentication.middleware.test.ts @@ -0,0 +1,47 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { mockNuxtImport } from '@nuxt/test-utils/runtime' +import middleware from '~/middleware/authentication.global' + +// Returning false aborts the navigation. (Returning a path would make the real router follow it, and +// since this mock also applies to the app's own startup navigation, that could redirect forever.) +const { navigateToMock } = vi.hoisted(() => ({ navigateToMock: vi.fn(() => false) })) +mockNuxtImport('navigateTo', () => navigateToMock) + +// The middleware only reads `to.path` +const run = (path: string) => (middleware as (to: unknown, from: unknown) => unknown)({ path }, { path: '/' }) + +describe('authentication middleware', () => { + describe('when logged out', () => { + beforeEach(() => { + useCookie('authenticated').value = false + navigateToMock.mockClear() + }) + + it.each(['/', '/people'])('redirects %s to the login page', (path) => { + run(path) + expect(navigateToMock).toHaveBeenCalledExactlyOnceWith('/login') + }) + + it.each(['/login', '/health'])('allows anonymous access to %s', (path) => { + expect(run(path)).toBeUndefined() + expect(navigateToMock).not.toHaveBeenCalled() + }) + }) + + describe('when logged in', () => { + beforeEach(() => { + useCookie('authenticated').value = true + navigateToMock.mockClear() + }) + + it.each(['/', '/people', '/health'])('allows %s', (path) => { + expect(run(path)).toBeUndefined() + expect(navigateToMock).not.toHaveBeenCalled() + }) + + it('skips the login page', () => { + run('/login') + expect(navigateToMock).toHaveBeenCalledExactlyOnceWith('/') + }) + }) +}) diff --git a/packages/frontend/test/helpers.ts b/packages/frontend/test/helpers.ts new file mode 100644 index 0000000..5f69a4e --- /dev/null +++ b/packages/frontend/test/helpers.ts @@ -0,0 +1,37 @@ +import { expect } from 'vitest' +import { defineComponent, h, nextTick, type Component } from 'vue' +import { flushPromises } from '@vue/test-utils' +import { mountSuspended } from '@nuxt/test-utils/runtime' +import { UApp } from '#components' + +/** Mounts a component inside , which modals and toasts need. */ +export const mountInApp = (component: Component) => + mountSuspended(defineComponent({ render: () => h(UApp, null, { default: () => h(component) }) })) + +/** Lets promises, reactivity and (async) form validation settle. */ +export const settle = async () => { + for (let i = 0; i < 4; i++) { + await flushPromises() + await nextTick() + } +} + +/** Modals render in a portal, so query the whole document. */ +export const inBody = (selector: string) => document.body.querySelector(selector) + +export const setInput = async (input: HTMLInputElement, value: string) => { + input.value = value + input.dispatchEvent(new Event('input', { bubbles: true })) + await settle() +} + +export const submitForm = async (form: HTMLFormElement) => { + form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })) + await settle() +} + +export const click = async (el: Element | null) => { + expect(el, 'element to click').not.toBeNull() + ;(el as HTMLElement).click() + await settle() +} diff --git a/packages/frontend/test/useApi.test.ts b/packages/frontend/test/useApi.test.ts new file mode 100644 index 0000000..cbf0b0d --- /dev/null +++ b/packages/frontend/test/useApi.test.ts @@ -0,0 +1,98 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { mockNuxtImport, registerEndpoint } from '@nuxt/test-utils/runtime' +import { createError, defineEventHandler, getHeader, readBody, setResponseStatus } from 'h3' +import { useApi } from '~/composables/useApi' + +const { navigateToMock } = vi.hoisted(() => ({ navigateToMock: vi.fn() })) +mockNuxtImport('navigateTo', () => navigateToMock) + +// Each test registers its own endpoint, with an empty base URL (see vitest.config.ts) so requests hit it directly +const respond = (path: string, status: number, body: unknown, method: 'GET' | 'POST' | 'DELETE' = 'GET') => + registerEndpoint(path, { + method, + handler: defineEventHandler((event) => { + setResponseStatus(event, status) + return body + }) + }) + +describe('useApi', () => { + beforeEach(() => { + navigateToMock.mockReset() + useCookie('authenticated').value = true + }) + + it('returns the API response on success', async () => { + respond('/api/test/ok', 200, { success: true, data: [1, 2] }) + expect(await useApi().get('/api/test/ok')).toEqual({ success: true, data: [1, 2] }) + }) + + it('JSON-encodes bare string bodies so quotes and backslashes survive', async () => { + const password = 'pa"ss\\word' + let received: unknown + let contentType: string | undefined + registerEndpoint('/api/test/echo', { + method: 'POST', + handler: defineEventHandler(async (event) => { + contentType = getHeader(event, 'content-type') + received = await readBody(event) + return { success: true } + }) + }) + + await useApi().post('/api/test/echo', password) + + expect(contentType).toContain('application/json') + expect(received).toBe(password) + }) + + it('sends DELETE requests', async () => { + respond('/api/test/delete', 200, { success: true, data: { id: 3 } }, 'DELETE') + expect((await useApi().delete('/api/test/delete')).success).toBe(true) + }) + + it('passes through the API error message for failed requests', async () => { + respond('/api/test/bad', 400, { success: false, error: 'The code must be numeric.' }, 'POST') + + const result = await useApi().post('/api/test/bad', 'abcd') + + expect(result).toEqual({ success: false, error: 'The code must be numeric.' }) + expect(navigateToMock).not.toHaveBeenCalled() + }) + + it('does not treat a wrong-password 401 as an expired session', async () => { + respond('/api/test/login', 401, { success: false, error: 'Incorrect password.' }, 'POST') + + const result = await useApi().post('/api/test/login', 'nope') + + expect(result.error).toBe('Incorrect password.') + expect(navigateToMock).not.toHaveBeenCalled() + expect(useCookie('authenticated').value).toBe(true) + }) + + it('sends the user to the login page when the session has expired (empty 401)', async () => { + registerEndpoint('/api/test/expired', () => { + throw createError({ statusCode: 401, data: undefined }) + }) + + const result = await useApi().get('/api/test/expired') + + expect(result.success).toBe(false) + expect(result.error).toMatch(/session has expired/i) + expect(navigateToMock).toHaveBeenCalledWith('/login') + expect(useCookie('authenticated').value).toBe(false) + }) + + it('surfaces rate limiting (429) messages', async () => { + respond('/api/test/limited', 429, { success: false, error: 'Too many login attempts.' }, 'POST') + expect((await useApi().post('/api/test/limited', 'x')).error).toBe('Too many login attempts.') + }) + + it('falls back to a generic message when the server cannot be reached', async () => { + // Nothing is registered at this path and the request is aborted by the network layer + const result = await useApi().get('http://127.0.0.1:1/unreachable') + + expect(result).toEqual({ success: false, error: 'Unable to reach the server.' }) + expect(navigateToMock).not.toHaveBeenCalled() + }) +}) diff --git a/packages/frontend/vitest.config.ts b/packages/frontend/vitest.config.ts new file mode 100644 index 0000000..b2b61e5 --- /dev/null +++ b/packages/frontend/vitest.config.ts @@ -0,0 +1,20 @@ +import { defineVitestConfig } from '@nuxt/test-utils/config' + +export default defineVitestConfig({ + test: { + environment: 'nuxt', + include: ['test/**/*.test.ts'], + // Booting the Nuxt environment can be slow on a cold start (and in CI) + hookTimeout: 60_000, + testTimeout: 30_000, + environmentOptions: { + nuxt: { + domEnvironment: 'happy-dom', + // Empty base URL so $fetch calls hit endpoints registered with registerEndpoint() + overrides: { + runtimeConfig: { public: { apiBaseUrl: '' } } + } + } + } + } +})