feat(KAN-37): rebuild security and application key settings

This commit is contained in:
2026-09-15 09:17:27 +02:00
parent 1377ee8510
commit 7e483d0b58
13 changed files with 1814 additions and 824 deletions
+52
View File
@@ -6,6 +6,7 @@ use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Inertia\Testing\AssertableInertia as Assert;
use Laravel\Fortify\Contracts\TwoFactorAuthenticationProvider;
use Laravel\Fortify\Features;
use Tests\TestCase;
@@ -249,4 +250,55 @@ class SecurityTest extends TestCase
$this->assertTrue(Hash::check('password', $user->fresh()->password));
}
public function test_two_factor_setup_requires_a_valid_code_before_protection_is_enabled(): void
{
$user = User::factory()->create();
$this->actingAs($user)->withSession(['auth.password_confirmed_at' => time()])
->from(route('security.edit'))
->post(route('two-factor.enable'))->assertSessionHasNoErrors();
$this->assertNotNull($user->refresh()->two_factor_secret);
$this->assertFalse($user->hasEnabledTwoFactorAuthentication());
$this->getJson(route('two-factor.secret-key'))->assertOk()->assertJsonStructure(['secretKey']);
$this->getJson(route('two-factor.qr-code'))->assertOk()->assertJsonStructure(['svg']);
$this->mock(TwoFactorAuthenticationProvider::class, function ($mock): void {
$mock->shouldReceive('verify')->withArgs(fn ($secret, $code) => $code === '000000')->once()->andReturn(false);
$mock->shouldReceive('verify')->withArgs(fn ($secret, $code) => $code === '123456')->once()->andReturn(true);
});
$this->post(route('two-factor.confirm'), ['code' => '000000'])
->assertSessionHasErrors('code', errorBag: 'confirmTwoFactorAuthentication');
$this->assertFalse($user->refresh()->hasEnabledTwoFactorAuthentication());
$this->post(route('two-factor.confirm'), ['code' => '123456'])->assertSessionHasNoErrors();
$this->assertTrue($user->refresh()->hasEnabledTwoFactorAuthentication());
}
public function test_recovery_codes_can_be_retrieved_regenerated_and_removed_with_two_factor(): void
{
$user = User::factory()->withTwoFactor()->create();
$this->actingAs($user)->withSession(['auth.password_confirmed_at' => time()]);
$oldCodes = $this->getJson(route('two-factor.recovery-codes'))->assertOk()->json();
$this->assertSame($user->recoveryCodes(), $oldCodes);
$this->post(route('two-factor.regenerate-recovery-codes'))->assertSessionHasNoErrors();
$newCodes = $this->getJson(route('two-factor.recovery-codes'))->assertOk()->json();
$this->assertCount(8, $newCodes);
$this->assertEmpty(array_intersect($oldCodes, $newCodes));
$this->delete(route('two-factor.disable'))->assertSessionHasNoErrors();
$this->assertNull($user->refresh()->two_factor_secret);
$this->assertNull($user->two_factor_recovery_codes);
$this->assertFalse($user->hasEnabledTwoFactorAuthentication());
}
public function test_sensitive_two_factor_endpoints_reject_expired_password_confirmation(): void
{
$user = User::factory()->withTwoFactor()->create();
$this->actingAs($user);
foreach (['two-factor.qr-code', 'two-factor.secret-key', 'two-factor.recovery-codes'] as $route) {
$this->getJson(route($route))->assertStatus(423);
}
$this->deleteJson(route('two-factor.disable'))->assertStatus(423);
$this->postJson(route('two-factor.regenerate-recovery-codes'))->assertStatus(423);
$this->assertTrue($user->refresh()->hasEnabledTwoFactorAuthentication());
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace Tests\Feature\Settings;
use Symfony\Component\Process\Process;
use Tests\TestCase;
class SecurityUiTest extends TestCase
{
public function test_security_and_application_key_rendering(): void
{
$process = new Process(['node', 'tests/Fixtures/security.mjs'], base_path());
$process->setTimeout(60);
$process->run();
$this->assertTrue($process->isSuccessful(), $process->getOutput().$process->getErrorOutput());
$this->assertStringContainsString('Security UI rendering checks passed.', $process->getOutput());
}
}
+25 -1
View File
@@ -25,7 +25,9 @@ class UserApplicationTest extends TestCase
->assertInertia(fn (Assert $page) => $page
->component('settings/Applications')
->where('applications.0.name', 'Claude Desktop')
->where('applicationKey', null),
->where('applicationKey', null)
->missing('applications.0.key_hash')
->missing('applications.0.plain_text_key'),
);
}
@@ -100,4 +102,26 @@ class UserApplicationTest extends TestCase
'id' => $application->id,
]);
}
public function test_application_list_only_contains_the_current_users_keys(): void
{
$user = User::factory()->create();
UserApplication::factory()->for($user)->create(['name' => 'Own tool']);
UserApplication::factory()->create(['name' => 'Foreign tool']);
$this->actingAs($user)->get(route('applications.edit'))
->assertInertia(fn (Assert $page) => $page
->has('applications', 1)
->where('applications.0.name', 'Own tool')
->where('applicationKey', null));
}
public function test_invalid_application_name_does_not_issue_a_key(): void
{
$user = User::factory()->create();
$this->actingAs($user)->from(route('applications.edit'))
->post(route('applications.store'), ['name' => ''])
->assertSessionHasErrors('name')
->assertSessionMissing('applicationKey');
$this->assertDatabaseCount('user_applications', 0);
}
}
+316
View File
@@ -0,0 +1,316 @@
import assert from 'node:assert/strict';
import process from 'node:process';
const { chromium } = await import(
process.env.PLAYWRIGHT_MODULE ?? 'playwright'
);
const browser = await chromium.launch({ channel: 'chrome', headless: true });
const base = 'http://127.0.0.1:4185';
const context = await browser.newContext({
viewport: { width: 1440, height: 1000 },
permissions: ['clipboard-read', 'clipboard-write'],
});
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
page.on('dialog', (dialog) => dialog.accept());
const result = (value) =>
context.addCookies([{ name: 'security_test_result', value, url: base }]);
const enabled = (value) =>
context.addCookies([
{ name: 'security_enabled', value: String(value), url: base },
]);
const button = (name) => page.getByRole('button', { name, exact: true });
const dialog = () => page.getByRole('dialog');
let recoveryFetches = 0;
page.on('request', (request) => {
if (
request.url().endsWith('/user/two-factor-recovery-codes') &&
request.method() === 'GET'
) {
recoveryFetches++;
}
});
try {
for (const width of [1440, 390, 320]) {
await page.setViewportSize({ width, height: 1000 });
for (const theme of ['light', 'dark']) {
await page.emulateMedia({ colorScheme: theme });
for (const path of ['security', 'applications']) {
await page.goto(`${base}/settings/${path}`);
await page
.getByRole('heading', {
name:
path === 'security'
? 'Update password'
: 'Applications',
exact: true,
})
.waitFor();
assert.equal(
await page.evaluate(
() =>
document.documentElement.scrollWidth <=
window.innerWidth,
),
true,
`${path} overflow at ${width}/${theme}`,
);
assert.equal(
await page
.locator('html')
.evaluate((el) => el.classList.contains('dark')),
theme === 'dark',
);
assert.ok(
(await page.locator('section').first().boundingBox())
.width <= width,
`${path} content is clipped at ${width}/${theme}`,
);
}
await page.goto(`${base}/settings/security`);
await button('Enable 2FA').click();
await page.getByLabel('Manual setup key').waitFor();
assert.equal(
await page.getByLabel('Manual setup key').inputValue(),
'MANUALSETUPTESTKEY',
);
assert.equal(
await dialog().evaluate(
(el) => el.scrollWidth <= el.clientWidth,
),
true,
);
await button('Continue').click();
const code = page.getByLabel('Authentication code', {
exact: true,
});
await code.waitFor();
assert.equal(await code.getAttribute('inputmode'), 'numeric');
assert.equal(
await code.getAttribute('autocomplete'),
'one-time-code',
);
await code.focus();
await page.keyboard.press('Tab');
assert.equal(
await button('Back').evaluate(
(el) => el === document.activeElement,
),
true,
);
await page.keyboard.press('Escape');
await dialog().waitFor({ state: 'hidden' });
assert.equal(await page.getByLabel('Manual setup key').count(), 0);
assert.match(
await page.locator('body').innerText(),
/Awaiting confirmation/,
);
}
}
await page.setViewportSize({ width: 390, height: 1000 });
await button('Continue setup').click();
await button('Continue').click();
await result('validation');
await page
.getByLabel('Authentication code', { exact: true })
.fill('000000');
await button('Confirm').click();
await page
.getByText('The provided two factor authentication code was invalid.', {
exact: true,
})
.waitFor();
assert.equal(
await page
.getByLabel('Authentication code', { exact: true })
.getAttribute('aria-invalid'),
'true',
);
assert.equal(
await page
.getByLabel('Authentication code', { exact: true })
.inputValue(),
'',
);
await result('success');
await page
.getByLabel('Authentication code', { exact: true })
.fill('123456');
await button('Confirm').click();
await dialog().waitFor({ state: 'hidden' });
await button('Disable 2FA').waitFor();
assert.equal(
recoveryFetches,
0,
'Recovery codes are fetched only on request',
);
await button('View recovery codes').click();
await page.getByText('old-code-0001', { exact: true }).waitFor();
await button('Hide recovery codes').click();
assert.equal(
await page.getByText('old-code-0001', { exact: true }).count(),
0,
);
await button('View recovery codes').click();
await page.getByText('old-code-0001', { exact: true }).waitFor();
assert.equal(recoveryFetches, 2);
await button('Regenerate codes').click();
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(
await page.getByText('old-code-0001', { exact: true }).count(),
1,
);
await button('Regenerate codes').click();
await dialog()
.getByRole('button', { name: 'Regenerate codes', exact: true })
.click();
await dialog().waitFor({ state: 'hidden' });
await page.getByText('old-code-0001', { exact: true }).waitFor();
assert.equal(recoveryFetches, 3);
await button('Hide recovery codes').click();
await page.route('**/user/two-factor-recovery-codes', async (route) => {
if (route.request().method() === 'GET') {
await new Promise((resolve) => setTimeout(resolve, 350));
await route.fulfill({ json: ['late-secret-code'] });
} else {
await route.continue();
}
});
await button('View recovery codes').click();
await button('Hide recovery codes').click();
await page.waitForTimeout(450);
assert.equal(
await page.getByText('late-secret-code', { exact: true }).count(),
0,
);
await page.unroute('**/user/two-factor-recovery-codes');
await page.route('**/user/two-factor-recovery-codes', (route) =>
route.fulfill({ status: 423, json: {} }),
);
await button('View recovery codes').click();
await page
.getByText(
'Your session or password confirmation has expired. Reload this page and confirm your password to continue.',
{ exact: true },
)
.waitFor();
await page.unroute('**/user/two-factor-recovery-codes');
await button('Try again').click();
await page.getByText('old-code-0001', { exact: true }).waitFor();
await button('Disable 2FA').click();
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
await button('Disable 2FA').click();
await dialog()
.getByRole('button', { name: 'Disable 2FA', exact: true })
.click();
await dialog().waitFor({ state: 'hidden' });
await button('Enable 2FA').waitFor();
assert.equal(
await page.getByText('old-code-0001', { exact: true }).count(),
0,
);
await page.route('**/user/two-factor-secret-key', (route) => route.abort());
await button('Enable 2FA').click();
await page
.getByText(
'Authenticator setup could not be loaded. Please try again.',
{ exact: true },
)
.waitFor();
assert.equal(await button('Continue').count(), 0);
await page.unroute('**/user/two-factor-secret-key');
await button('Try again').click();
await page.getByLabel('Manual setup key').waitFor();
await page.locator('[data-slot="dialog-close"]').click();
await dialog().waitFor({ state: 'hidden' });
await page.getByLabel('Current password', { exact: true }).fill('wrong');
await page.getByLabel('New password', { exact: true }).fill('new-password');
await page
.getByLabel('Confirm password', { exact: true })
.fill('new-password');
await result('validation');
await button('Save password').click();
await page
.getByText('The password is incorrect.', { exact: true })
.waitFor();
assert.equal(
await page.getByLabel('Current password', { exact: true }).inputValue(),
'',
);
assert.equal(
await page.getByLabel('New password', { exact: true }).inputValue(),
'',
);
assert.equal(
await page
.getByLabel('Current password', { exact: true })
.getAttribute('aria-invalid'),
'true',
);
assert.doesNotMatch(
await page.evaluate(() => JSON.stringify(history.state)),
/MANUALSETUPTESTKEY|123456|new-password/,
);
await result('success');
await page.goto(`${base}/settings/applications`);
assert.equal(await button('Copy key').count(), 0);
await page.getByLabel('Application name').fill('My tool');
await page.route('**/settings/applications', (route) =>
route.request().method() === 'POST' ? route.abort() : route.continue(),
);
await button('Create application').click();
await page.locator('[data-form-state="network"]').waitFor();
assert.equal(
await page.getByLabel('Application name').inputValue(),
'My tool',
);
await page.unroute('**/settings/applications');
await button('Try again').click();
await page.getByLabel('API key', { exact: true }).waitFor();
assert.ok(
(await page.locator('section').first().boundingBox()).width <= 390,
'One-time key content is clipped on mobile',
);
await button('Copy key').click();
assert.equal(
await page.evaluate(() => navigator.clipboard.readText()),
'kg_app_one_time_test_key',
);
await page.reload();
assert.equal(await button('Copy key').count(), 0);
assert.equal(await page.getByLabel('API key', { exact: true }).count(), 0);
await page
.getByRole('button', { name: 'Delete Desktop tool', exact: true })
.click();
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
await page
.getByRole('button', { name: 'Delete Desktop tool', exact: true })
.click();
await result('expired');
await dialog().getByRole('button', { name: 'Delete', exact: true }).click();
await dialog()
.getByText('Your session has expired', { exact: true })
.waitFor();
assert.equal(
await page.locator('button[aria-label="Delete Desktop tool"]').count(),
1,
);
await dialog().getByRole('button', { name: 'Cancel', exact: true }).click();
await result('success');
await page
.getByRole('button', { name: 'Delete Desktop tool', exact: true })
.click();
await dialog().getByRole('button', { name: 'Delete', exact: true }).click();
await page
.getByText('No applications have been created yet.', { exact: true })
.waitFor();
assert.deepEqual(errors, []);
console.log(
'Security browser behavior checks passed: 2FA setup, confirmation, cancellation, recovery hiding and regeneration, late responses, errors, password reset, one-time key copy, deletion, keyboard, mobile and both themes.',
);
} finally {
await browser.close();
}
+17
View File
@@ -0,0 +1,17 @@
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import '../../resources/css/app.css';
import Security from '../../resources/js/pages/settings/Security.vue';
import Applications from '../../resources/js/pages/settings/Applications.vue';
import { createAppearance } from '../../resources/js/composables/useAppearance';
import { createLocalization } from '../../resources/js/lib/localization';
createInertiaApp({
resolve: (name) => (name === 'Security' ? Security : Applications),
setup: ({ el, App, props, plugin }) =>
createApp({ render: () => h(App, props) })
.use(plugin)
.use(createLocalization())
.use(createAppearance())
.mount(el),
});
+238
View File
@@ -0,0 +1,238 @@
import assert from 'node:assert/strict';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import vue from '@vitejs/plugin-vue';
import tailwind from '@tailwindcss/vite';
import { createServer } from 'vite';
import { createSSRApp, h } from 'vue';
import { renderToString } from 'vue/server-renderer';
import { createInertiaApp } from '@inertiajs/vue3';
const serve = process.argv.includes('--serve');
const server = await createServer({
configFile: false,
cacheDir: 'node_modules/.vite/security-fixture',
plugins: [vue(), ...(serve ? [tailwind()] : [])],
resolve: {
alias: {
'@': fileURLToPath(new URL('../../resources/js', import.meta.url)),
},
},
server: serve
? { host: '127.0.0.1', port: 4185, strictPort: true, hmr: false }
: { middlewareMode: true, hmr: false, watch: null },
appType: 'custom',
});
const application = {
id: 1,
name: 'Desktop tool',
created_at: '2026-09-14T00:00:00Z',
last_used_at: null,
};
const key = 'kg_app_one_time_test_key';
function makePage(url, extra = {}) {
return {
component: url.startsWith('/settings/security')
? 'Security'
: 'Applications',
url,
version: null,
clearHistory: false,
encryptHistory: false,
props: {
name: 'KanbanGit',
errors: {},
sidebarOpen: true,
appearance: 'system',
canManageTwoFactor: true,
requiresConfirmation: true,
twoFactorEnabled: false,
applications: [application],
applicationKey: null,
auth: {
user: {
id: 1,
name: 'Alex Morgan',
email: 'alex@example.test',
avatar: null,
avatar_color: '#10B981',
avatar_is_generated: true,
},
permissions: {
globalAdmin: false,
projectCreate: false,
canManageTeams: false,
},
},
navigation: { project: null },
...extra,
},
};
}
if (serve) {
server.middlewares.use(async (request, response, next) => {
const path = new URL(request.url, 'http://localhost').pathname;
if (!path.startsWith('/settings') && !path.startsWith('/user/')) {
return next();
}
const result =
request.headers.cookie?.match(/security_test_result=(\w+)/)?.[1] ??
'success';
const mutation = request.method !== 'GET';
if (mutation && ['server', 'expired'].includes(result)) {
response.statusCode = result === 'expired' ? 419 : 503;
response.end('Simulated failure');
return;
}
let body = '';
if (mutation) {
for await (const chunk of request) {
body += chunk;
}
}
const submitted = body ? JSON.parse(body) : {};
const cookies = request.headers.cookie ?? '';
let enabled = cookies.includes('security_enabled=true');
let extra = { twoFactorEnabled: enabled };
let url = path;
if (path.startsWith('/user/two-factor-') && !mutation) {
response.setHeader('Content-Type', 'application/json');
response.end(
JSON.stringify(
path.endsWith('qr-code')
? {
svg: '<svg viewBox="0 0 100 100"><rect width="100" height="100" fill="black"/></svg>',
}
: path.endsWith('secret-key')
? { secretKey: 'MANUALSETUPTESTKEY' }
: ['old-code-0001', 'old-code-0002'],
),
);
return;
}
if (mutation) {
url = path.startsWith('/settings/applications')
? '/settings/applications'
: '/settings/security';
if (result === 'validation') {
extra.errors = path.includes('confirmed-two-factor')
? {
confirmTwoFactorAuthentication: {
code: 'The provided two factor authentication code was invalid.',
},
}
: path.includes('applications')
? { name: 'The name field is required.' }
: { current_password: 'The password is incorrect.' };
} else if (path.includes('confirmed-two-factor')) {
enabled = true;
response.setHeader(
'Set-Cookie',
'security_enabled=true; Path=/',
);
} else if (
path === '/user/two-factor-authentication' &&
request.method === 'DELETE'
) {
enabled = false;
response.setHeader(
'Set-Cookie',
'security_enabled=false; Path=/',
);
} else if (
path === '/settings/applications' &&
request.method === 'POST'
) {
extra.applicationKey = key;
extra.applications = [{ ...application, name: submitted.name }];
} else if (
path.startsWith('/settings/applications/') &&
request.method === 'DELETE'
) {
extra.applications = [];
}
extra.twoFactorEnabled = enabled;
}
const page = makePage(url, extra);
response.setHeader('Vary', 'X-Inertia');
if (request.headers['x-inertia']) {
response.setHeader('X-Inertia', 'true');
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(page));
return;
}
const escaped = JSON.stringify(page)
.replaceAll('&', '&amp;')
.replaceAll('"', '&quot;')
.replaceAll('<', '&lt;');
response.setHeader('Content-Type', 'text/html');
response.end(
await server.transformIndexHtml(
request.url,
'<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head><body><div id="app" data-page="' +
escaped +
'"></div><script type="module" src="/tests/Fixtures/security-preview.mjs"></script></body></html>',
),
);
});
await server.listen();
console.log('Security fixture ready.');
} else {
try {
const { createLocalization } = await server.ssrLoadModule(
'/resources/js/lib/localization.ts',
);
const { createAppearance } = await server.ssrLoadModule(
'/resources/js/composables/useAppearance.ts',
);
const Security = (
await server.ssrLoadModule(
'/resources/js/pages/settings/Security.vue',
)
).default;
const Applications = (
await server.ssrLoadModule(
'/resources/js/pages/settings/Applications.vue',
)
).default;
const render = async (url, component, extra = {}) =>
(
await createInertiaApp({
page: makePage(url, extra),
resolve: () => component,
render: renderToString,
setup: ({ App, props, plugin }) =>
createSSRApp({ render: () => h(App, props) })
.use(plugin)
.use(createLocalization())
.use(createAppearance()),
})
).body;
const security = await render('/settings/security', Security);
assert.match(security, /autocomplete="current-password"/);
assert.match(security, /Enable 2FA/);
assert.doesNotMatch(
await render('/settings/security', Security, {
canManageTwoFactor: false,
}),
/Enable 2FA/,
);
const enabled = await render('/settings/security', Security, {
twoFactorEnabled: true,
});
assert.match(enabled, /View recovery codes/);
assert.doesNotMatch(enabled, /old-code/);
const hidden = await render('/settings/applications', Applications);
assert.doesNotMatch(hidden, /id="application-key"/);
assert.doesNotMatch(hidden, /Copy key/);
const shown = await render('/settings/applications', Applications, {
applicationKey: key,
});
assert.match(shown, /id="application-key"/);
assert.match(shown, /Copy key/);
assert.match(shown, /kg_app_one_time_test_key/);
console.log('Security UI rendering checks passed.');
} finally {
await server.close();
}
}