fix(salary): surface employee-save failures and a typed 503 for the missing encryption key (#1996) (#2009)
* fix(salary): surface employee-save failures in the dialog and type the missing encryption key (#1996) Pressing Spara in "Ny anställd" could fail without any feedback: a thrown fetch or a non-JSON 5xx body escaped handleSubmit before setSaving(false) ran, leaving the button stuck on "Sparar..." and the dialog silent. Even when the toast did fire, the Radix modal aria-hides the root-layout Toaster, so assistive tech (and the E2E driver that found this) heard nothing, and the requestId support needs was never shown anywhere. - NewEmployeeDialog: fetch + parse run in a never-throwing helper, saving is released in finally, the body is parsed with json().catch(() => null) so an HTML/plain-text error page still maps through the HTTP-status map, and the failure is rendered inline (role="alert" in the footer) with "Ärende-id: <requestId>" next to the single destructive toast. - personnummer.ts: the production "key missing" throw now carries the registry code PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED, and the SALARY registry gains a 503 entry naming PERSONNUMMER_ENCRYPTION_KEY with a "contact support" message and a remediation hint. withRouteContext emits the typed envelope automatically instead of INTERNAL_ERROR 500, which read as transient and invited retries that can never succeed. - Tests for the route (401, 400, 503 with requestId and no insert), the key guard, the registry entry, errorResponse dispatch on a coded Error, and getErrorMessage locale handling of the new envelope. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna * fix(salary): address review findings (#1996) - NewEmployeeDialog: fall back to the X-Request-Id response header when the body carries no error.requestId. The route hand-builds its 409 (duplicate personnummer) and generic insert-failure 500 bodies as flat strings, so the inline "Ärende-id" line was hidden for exactly the DB-failure class the issue names; withRouteContext sets the header on every response. - Route tests pin that the 409 and 500 insert-error arms carry X-Request-Id. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015nAd8XJ2RPCmG2eKoLBdna --------- Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
Jakob Wennberg
parent
89ce837947
commit
ca93ef3fb6
@@ -12,7 +12,7 @@
|
||||
* The route now runs through the withRouteContext wrapper, so we mock its
|
||||
* auth/company/write dependencies and inject the Supabase client via requireAuth.
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
@@ -232,4 +232,93 @@ describe('POST /api/salary/employees', () => {
|
||||
jamkning_valid_to: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
vi.mocked(requireAuth).mockResolvedValue({
|
||||
user: null,
|
||||
supabase: null,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
} as never)
|
||||
|
||||
const res = await POST(postRequest(CREATE_BASE), params)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on a personnummer that fails the checksum, without inserting', async () => {
|
||||
const { supabase, insert } = supabaseWithInsert({ id: 'emp-new' })
|
||||
authed(supabase)
|
||||
|
||||
const res = await POST(postRequest({ ...CREATE_BASE, personnummer: '199001019803' }), params)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(insert).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// #1996: the route hand-builds the 409 and generic insert-failure 500 bodies
|
||||
// as flat strings (no error.requestId), so the dialog falls back to the
|
||||
// X-Request-Id header for its "Ärende-id" line. Pin that the header is there.
|
||||
describe('insert failures carry X-Request-Id for support correlation', () => {
|
||||
function supabaseWithInsertError(error: { code: string; message: string }) {
|
||||
const single = vi.fn(() => Promise.resolve({ data: null, error }))
|
||||
const select = vi.fn(() => ({ single }))
|
||||
const insert = vi.fn(() => ({ select }))
|
||||
return { from: vi.fn(() => ({ insert })) }
|
||||
}
|
||||
|
||||
it('409 duplicate personnummer: flat error body plus X-Request-Id header', async () => {
|
||||
authed(supabaseWithInsertError({ code: '23505', message: 'duplicate key value' }))
|
||||
|
||||
const res = await POST(postRequest(CREATE_BASE), params)
|
||||
|
||||
expect(res.status).toBe(409)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe('En anställd med detta personnummer finns redan')
|
||||
expect(res.headers.get('X-Request-Id')).toMatch(/^req_/)
|
||||
})
|
||||
|
||||
it('500 generic insert error: flat error body plus X-Request-Id header', async () => {
|
||||
authed(supabaseWithInsertError({ code: '57014', message: 'canceling statement due to statement timeout' }))
|
||||
|
||||
const res = await POST(postRequest(CREATE_BASE), params)
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
const body = await res.json()
|
||||
expect(typeof body.error).toBe('string')
|
||||
expect(res.headers.get('X-Request-Id')).toMatch(/^req_/)
|
||||
})
|
||||
})
|
||||
|
||||
// #1996: the deployment that filed the issue had no PERSONNUMMER_ENCRYPTION_KEY.
|
||||
// The encrypt helper used to throw a bare Error, which the wrapper answered
|
||||
// with the generic INTERNAL_ERROR 500 ("try again later") even though no
|
||||
// retry can ever succeed. It now carries a registry code, so the envelope
|
||||
// names the configuration gap, points at support, and keeps the requestId.
|
||||
describe('missing PERSONNUMMER_ENCRYPTION_KEY in production', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('answers 503 PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED with a requestId and no insert', async () => {
|
||||
vi.stubEnv('NODE_ENV', 'production')
|
||||
vi.stubEnv('PERSONNUMMER_ENCRYPTION_KEY', '')
|
||||
const { supabase, insert } = supabaseWithInsert({ id: 'emp-new' })
|
||||
authed(supabase)
|
||||
|
||||
const res = await POST(postRequest(CREATE_BASE), params)
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
const body = await res.json()
|
||||
expect(body.error.code).toBe('PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED')
|
||||
expect(body.error.message).toContain('PERSONNUMMER_ENCRYPTION_KEY')
|
||||
expect(body.error.message).toMatch(/Kontakta supporten/)
|
||||
expect(body.error.message_en).toContain('PERSONNUMMER_ENCRYPTION_KEY')
|
||||
expect(body.error.requestId).toMatch(/^req_/)
|
||||
expect(res.headers.get('X-Request-Id')).toBe(body.error.requestId)
|
||||
// The failure happens before the database is touched: nothing to clean up.
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
expect(insert).not.toHaveBeenCalled()
|
||||
// The personnummer itself must never leak into the error envelope.
|
||||
expect(JSON.stringify(body)).not.toContain(NEW_PNR)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user