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
@@ -1323,5 +1323,6 @@ One line per decision: `[YYYY-MM-DD] <decision>: <why>`. Appended by agents and
|
||||
[2026-08-28] AR-PDF minus fix uses ASCII hyphen formatting, not font embedding: registering a Unicode TTF for react-pdf would change the whole document's typography and bundle size to fix one glyph; formatPdfKronor keeps built-in Helvetica and sidesteps WinAnsi's missing U+2212.
|
||||
[2026-08-28] Same-bank warning limited to observed one-session banks (SEB only): prod shows Handelsbanken tolerates 4 concurrent sessions, and the generic warning made a user abandon a legitimate renewal. Planned sync-death visibility work was dropped: already shipped via #1271 (health probe), #1727 (stale state), #1969 (cron unstarve).
|
||||
[2026-08-28] Same-bank warning revised to three tiers after skeptic refutation: hard warn SEB, silent/calm only for verified multi-session banks (Handelsbanken, 4 distinct session_ids observed), legacy hedged warning for unknown banks (fail closed), shared-session siblings exempt (fan-out carries them).
|
||||
[2026-08-28] Employee-save failure reported inline (role=alert in the dialog footer, carrying the requestId) in addition to the single destructive toast, and a missing PERSONNUMMER_ENCRYPTION_KEY typed as 503 PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED rather than INTERNAL_ERROR (#1996): the Radix modal aria-hides the root-layout Toaster while the dialog is open, so the toast is invisible to assistive tech and E2E drivers; TOAST_LIMIT is 1, so a second toast is not an option; and the missing key is a permanent configuration gap where "try again later" is wrong and "contact support" is right (same reasoning as CUSTOMER_PERSONAL_NUMBER_UNREADABLE and INVOICE_SEND_EMAIL_NOT_CONFIGURED). The shared postAction helper was not extended (it takes no body and exposes no requestId): keeping the change local to the dialog avoids widening a helper other panels rely on.
|
||||
[2026-08-28] /migrate SIE guard extended to every provider (Fortnox exemption removed) as "a completed SIE import must exist for the company", not "must be part of this run", plus a wizard hint that disables Start when SIE is unchecked and never imported; chose this over forcing the checkbox on because the route is the only seam a direct API call or a stale client cannot bypass, and "must exist" keeps entities-only re-runs after a full migration working (#2000).
|
||||
[2026-08-28] /migrate SIE guard skips company-info-only runs (all entity flags false) and the wizard derives "SIE already imported" from the preview OR this session's successful /import-sie results: company info writes no accounts, balances or subledger rows, so the BFL rationale does not apply; and the one-shot preview went stale after phase 1 succeeded and phase 2 failed, falsely blocking an entities-only retry (#2000 review).
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { useCompanySettings } from '@/lib/reference-data/hooks'
|
||||
import {
|
||||
Dialog,
|
||||
@@ -15,7 +16,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { Save } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
validateEmployeeBankAccount,
|
||||
isValidClearing,
|
||||
@@ -100,11 +101,72 @@ export default function NewEmployeeDialog({ open, onOpenChange, onCreated }: Pro
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a failed save is reported twice (toast AND an inline line): the dialog
|
||||
* is a Radix modal, which aria-hides everything outside DialogContent while
|
||||
* it is open, including the root-layout Toaster. The toast is visible on
|
||||
* screen but absent from the accessibility tree, so a screen reader (and the
|
||||
* E2E driver that filed #1996) hears nothing. The inline role="alert" line
|
||||
* lives inside the dialog and persists until the next attempt, and it is the
|
||||
* one place the support reference (requestId) is shown.
|
||||
*/
|
||||
interface SubmitError {
|
||||
message: string
|
||||
requestId: string | null
|
||||
}
|
||||
|
||||
function readRequestId(body: unknown): string | null {
|
||||
if (typeof body !== 'object' || body === null) return null
|
||||
const inner = (body as { error?: unknown }).error
|
||||
if (typeof inner !== 'object' || inner === null) return null
|
||||
const id = (inner as { requestId?: unknown }).requestId
|
||||
return typeof id === 'string' && id.trim() ? id : null
|
||||
}
|
||||
|
||||
/**
|
||||
* POST the employee and describe the failure, if any, in one sentence.
|
||||
* Returns null on success. Never throws: every arm (non-2xx envelope, a
|
||||
* non-JSON body such as Vercel's plain-text FUNCTION_INVOCATION_FAILED or a
|
||||
* 413 HTML page, a fetch that never completed) ends in a SubmitError so the
|
||||
* caller has exactly one thing to report.
|
||||
*/
|
||||
async function submitEmployee(body: unknown, locale: ErrorLocale): Promise<SubmitError | null> {
|
||||
try {
|
||||
const res = await fetch('/api/salary/employees', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
if (res.ok) return null
|
||||
|
||||
// A body that is not JSON leaves null: getErrorMessage then falls back to
|
||||
// the HTTP status map, still in the user's language.
|
||||
const result: unknown = await res.json().catch(() => null)
|
||||
// The route hand-builds its 409 (duplicate personnummer) and generic
|
||||
// insert-failure 500 bodies as flat strings, so only the typed envelopes
|
||||
// carry error.requestId. withRouteContext sets X-Request-Id on every
|
||||
// response, so fall back to the header: those DB-failure arms are exactly
|
||||
// the ones support needs a correlation id for.
|
||||
return {
|
||||
message: getErrorMessage(result, { context: 'salary', statusCode: res.status, locale }),
|
||||
requestId: readRequestId(result) ?? res.headers.get('X-Request-Id'),
|
||||
}
|
||||
} catch (err) {
|
||||
return {
|
||||
message: getErrorMessage(err, { context: 'salary', locale }),
|
||||
requestId: null,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Inner component so form state resets whenever the dialog reopens (Radix
|
||||
// unmounts DialogContent children on close).
|
||||
function NewEmployeeForm({ onCreated, onCancel }: { onCreated: () => void; onCancel: () => void }) {
|
||||
const t = useTranslations('employees')
|
||||
const locale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [submitError, setSubmitError] = useState<SubmitError | null>(null)
|
||||
const [employmentType, setEmploymentType] = useState('employee')
|
||||
const [salaryType, setSalaryType] = useState('monthly')
|
||||
const [personnummer, setPersonnummer] = useState('')
|
||||
@@ -157,6 +219,7 @@ function NewEmployeeForm({ onCreated, onCancel }: { onCreated: () => void; onCan
|
||||
}
|
||||
|
||||
setSaving(true)
|
||||
setSubmitError(null)
|
||||
|
||||
const form = new FormData(e.currentTarget)
|
||||
const body = {
|
||||
@@ -193,25 +256,31 @@ function NewEmployeeForm({ onCreated, onCancel }: { onCreated: () => void; onCan
|
||||
default_dimensions: dimensions,
|
||||
}
|
||||
|
||||
const res = await fetch('/api/salary/employees', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (res.ok) {
|
||||
toast({ title: 'Anställd skapad' })
|
||||
onCreated()
|
||||
} else {
|
||||
const result = await res.json()
|
||||
toast({
|
||||
title: 'Kunde inte skapa anställd',
|
||||
description: getErrorMessage(result, { context: 'salary', statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
// `saving` is released in finally no matter how the request ends: a
|
||||
// thrown fetch (offline, connection reset) used to escape this handler
|
||||
// before setSaving(false) ran, leaving the dialog silent with Spara stuck
|
||||
// on "Sparar..." forever. #1996
|
||||
let failure: SubmitError | null
|
||||
try {
|
||||
failure = await submitEmployee(body, locale)
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
|
||||
setSaving(false)
|
||||
if (!failure) {
|
||||
toast({ title: 'Anställd skapad' })
|
||||
onCreated()
|
||||
return
|
||||
}
|
||||
|
||||
// One toast per attempt (TOAST_LIMIT is 1, a second would evict it) plus
|
||||
// the inline line that the modal's aria-hiding cannot swallow.
|
||||
setSubmitError(failure)
|
||||
toast({
|
||||
title: 'Kunde inte skapa anställd',
|
||||
description: failure.message,
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
|
||||
const bankName = lookupBankByClearing(clearing)
|
||||
@@ -426,8 +495,21 @@ function NewEmployeeForm({ onCreated, onCancel }: { onCreated: () => void; onCan
|
||||
|
||||
{/* Solid footer outside the scroll area: always visible, never overlaps
|
||||
content (the body above scrolls independently). */}
|
||||
<div className="flex justify-end gap-3 border-t border-border bg-background px-6 py-4">
|
||||
<Button type="button" variant="outline" onClick={onCancel}>
|
||||
<div className="flex items-center gap-3 border-t border-border bg-background px-6 py-4">
|
||||
{submitError && (
|
||||
<p role="alert" className="min-w-0 flex-1 text-sm text-destructive">
|
||||
{submitError.message}
|
||||
{submitError.requestId && (
|
||||
<>
|
||||
{' '}
|
||||
<span className="tabular-nums text-muted-foreground">
|
||||
{t('save_error_request_id', { id: submitError.requestId })}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<Button type="button" variant="outline" className="ml-auto" onClick={onCancel}>
|
||||
Avbryt
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving}>
|
||||
|
||||
@@ -411,6 +411,28 @@ describe('getErrorMessage: API response body vs new Error(body.error)', () => {
|
||||
)
|
||||
})
|
||||
|
||||
// #1996: the envelope a missing PERSONNUMMER_ENCRYPTION_KEY now produces.
|
||||
it('a typed configuration-gap envelope yields the registry text per locale', () => {
|
||||
const configGap = {
|
||||
error: {
|
||||
code: 'PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED',
|
||||
message:
|
||||
'Lönemodulen är inte konfigurerad: krypteringsnyckeln för personnummer (PERSONNUMMER_ENCRYPTION_KEY) saknas i driftmiljön. Kontakta supporten.',
|
||||
message_en:
|
||||
'Payroll is not configured: the personal-number encryption key (PERSONNUMMER_ENCRYPTION_KEY) is missing from the deployment environment. Contact support.',
|
||||
requestId: 'req_00000000-0000-4000-8000-000000000001',
|
||||
},
|
||||
}
|
||||
const sv = getErrorMessage(configGap, { context: 'salary', statusCode: 503, locale: 'sv' })
|
||||
expect(sv).toBe(configGap.error.message)
|
||||
const en = getErrorMessage(configGap, { context: 'salary', statusCode: 503, locale: 'en' })
|
||||
expect(en).toBe(configGap.error.message_en)
|
||||
// Neither locale falls back to the generic 503 "temporarily unavailable"
|
||||
// text: this failure is permanent until an operator sets the variable.
|
||||
expect(sv).not.toMatch(/tillfälligt/i)
|
||||
expect(en).not.toMatch(/temporarily/i)
|
||||
})
|
||||
|
||||
it('the same call handles an unparseable body via statusCode', () => {
|
||||
// `await response.json().catch(() => null)` on an HTML 403 page.
|
||||
expect(getErrorMessage(null, { statusCode: 403 })).toBe(
|
||||
|
||||
@@ -58,6 +58,18 @@ describe('structured-errors registry', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('registers PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED as a 503 configuration gap (#1996)', () => {
|
||||
const entry = getErrorEntry('PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED')
|
||||
expect(entry).toBeDefined()
|
||||
expect(entry?.httpStatus).toBe(503)
|
||||
expect(entry?.message_sv).toContain('PERSONNUMMER_ENCRYPTION_KEY')
|
||||
expect(entry?.message_sv).toMatch(/Kontakta supporten/)
|
||||
expect(entry?.message_en).toContain('PERSONNUMMER_ENCRYPTION_KEY')
|
||||
expect(entry?.remediation?.description).toContain('PERSONNUMMER_ENCRYPTION_KEY')
|
||||
// Retrying without the variable fails identically: never mark it transient.
|
||||
expect(entry?.retryable).toBeFalsy()
|
||||
})
|
||||
|
||||
it('listErrorCodes returns at least the bookkeeping + generic + provider codes', () => {
|
||||
const codes = listErrorCodes()
|
||||
expect(codes.length).toBeGreaterThan(20)
|
||||
@@ -73,6 +85,23 @@ describe('structured-errors registry', () => {
|
||||
})
|
||||
|
||||
describe('errorResponse', () => {
|
||||
it('maps a plain Error carrying a registry code to that code, status and requestId', async () => {
|
||||
// The shape lib/salary/personnummer.ts throws when the key is unset in
|
||||
// production: an Error with a `code` own-property, no class hierarchy.
|
||||
const err = Object.assign(new Error('PERSONNUMMER_ENCRYPTION_KEY is required in production'), {
|
||||
code: 'PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED',
|
||||
})
|
||||
const res = errorResponse(err, noopLogger, { requestId: 'req_1996' })
|
||||
expect(res.status).toBe(503)
|
||||
expect(res.headers.get('X-Request-Id')).toBe('req_1996')
|
||||
const body = await readEnvelope(res)
|
||||
expect(body.error.code).toBe('PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED')
|
||||
expect(body.error.message).toMatch(/PERSONNUMMER_ENCRYPTION_KEY/)
|
||||
expect(body.error.requestId).toBe('req_1996')
|
||||
// The raw English Error.message must not replace the registry message.
|
||||
expect(body.error.message).not.toBe(err.message)
|
||||
})
|
||||
|
||||
it('maps BookkeepingError to its code + structured details + Swedish message', async () => {
|
||||
const err = new JournalEntryNotBalancedError(100, 90)
|
||||
const res = errorResponse(err, noopLogger, { requestId: 'req_1' })
|
||||
|
||||
@@ -2841,6 +2841,24 @@ const SALARY: Record<string, StructuredErrorEntry> = {
|
||||
message_sv: 'En anställd med samma personnummer finns redan.',
|
||||
message_en: 'An employee with that personnummer already exists.',
|
||||
},
|
||||
// A production deployment without PERSONNUMMER_ENCRYPTION_KEY: every
|
||||
// employee create (and every decrypt-on-read) throws before touching the
|
||||
// database. Deliberately not INTERNAL_ERROR: it is a configuration gap, not
|
||||
// transient, and retrying never helps, so the user should hear "contact
|
||||
// support" rather than "try again later". 503 like
|
||||
// INVOICE_SEND_EMAIL_NOT_CONFIGURED: the service is unavailable until an
|
||||
// operator sets the variable. #1996
|
||||
PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED: {
|
||||
httpStatus: 503,
|
||||
message_sv:
|
||||
'Lönemodulen är inte konfigurerad: krypteringsnyckeln för personnummer (PERSONNUMMER_ENCRYPTION_KEY) saknas i driftmiljön. Kontakta supporten.',
|
||||
message_en:
|
||||
'Payroll is not configured: the personal-number encryption key (PERSONNUMMER_ENCRYPTION_KEY) is missing from the deployment environment. Contact support.',
|
||||
remediation: {
|
||||
description:
|
||||
'Set PERSONNUMMER_ENCRYPTION_KEY in the deployment environment and redeploy. Retrying the request without it will fail identically.',
|
||||
},
|
||||
},
|
||||
SALARY_RUN_DUPLICATE_PERIOD: {
|
||||
httpStatus: 409,
|
||||
message_sv: 'En lönekörning för perioden finns redan.',
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { afterEach, describe, it, expect, vi } from 'vitest'
|
||||
import {
|
||||
PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED,
|
||||
validatePersonnummer,
|
||||
extractLast4,
|
||||
extractBirthDate,
|
||||
@@ -307,6 +308,47 @@ describe('encryption roundtrip', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('encryption key configuration guard (#1996)', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('throws a coded error in production when PERSONNUMMER_ENCRYPTION_KEY is unset', () => {
|
||||
vi.stubEnv('NODE_ENV', 'production')
|
||||
vi.stubEnv('PERSONNUMMER_ENCRYPTION_KEY', '')
|
||||
|
||||
let thrown: unknown
|
||||
try {
|
||||
encryptPersonnummer('199001019802')
|
||||
} catch (err) {
|
||||
thrown = err
|
||||
}
|
||||
expect(thrown).toBeInstanceOf(Error)
|
||||
// The code is what withRouteContext -> errorResponse() dispatches on, so
|
||||
// the route answers 503 with the registry message instead of a generic 500.
|
||||
expect((thrown as { code?: unknown }).code).toBe(PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED)
|
||||
expect(PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED).toBe('PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED')
|
||||
})
|
||||
|
||||
it('decrypt is guarded the same way (genuine ciphertext, no key, production)', () => {
|
||||
const ciphertext = encryptPersonnummer('199001019802')
|
||||
vi.stubEnv('NODE_ENV', 'production')
|
||||
vi.stubEnv('PERSONNUMMER_ENCRYPTION_KEY', '')
|
||||
|
||||
expect(() => decryptPersonnummer(ciphertext)).toThrow(
|
||||
expect.objectContaining({ code: PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED }),
|
||||
)
|
||||
})
|
||||
|
||||
it('falls back to the deterministic dev key outside production', () => {
|
||||
vi.stubEnv('NODE_ENV', 'test')
|
||||
vi.stubEnv('PERSONNUMMER_ENCRYPTION_KEY', '')
|
||||
|
||||
const encrypted = encryptPersonnummer('199001019802')
|
||||
expect(decryptPersonnummer(encrypted)).toBe('199001019802')
|
||||
})
|
||||
})
|
||||
|
||||
describe('decryptPersonnummer tolerance for unencrypted rows', () => {
|
||||
it('passes a raw 12-digit personnummer through unchanged (no crash)', () => {
|
||||
// A row stored unencrypted (pre-fix v1 create, or a seed) would otherwise
|
||||
|
||||
@@ -7,6 +7,16 @@ const TAG_LENGTH = 16
|
||||
|
||||
const logger = createLogger('salary/personnummer')
|
||||
|
||||
/**
|
||||
* Registry code (lib/errors/structured-errors.ts) for a production deployment
|
||||
* that never set PERSONNUMMER_ENCRYPTION_KEY. Carried on the thrown Error so
|
||||
* withRouteContext -> errorResponse() answers with the typed 503 envelope
|
||||
* ("krypteringsnyckel saknas, kontakta supporten") instead of the generic
|
||||
* INTERNAL_ERROR 500, which reads as a transient failure and invites retries
|
||||
* that can never succeed. #1996
|
||||
*/
|
||||
export const PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED = 'PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED'
|
||||
|
||||
/**
|
||||
* Get the encryption key from environment.
|
||||
* Falls back to a dev-only key for local development.
|
||||
@@ -15,7 +25,9 @@ function getEncryptionKey(): Buffer {
|
||||
const envKey = process.env.PERSONNUMMER_ENCRYPTION_KEY
|
||||
if (!envKey) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('PERSONNUMMER_ENCRYPTION_KEY is required in production')
|
||||
throw Object.assign(new Error('PERSONNUMMER_ENCRYPTION_KEY is required in production'), {
|
||||
code: PERSONNUMMER_ENCRYPTION_NOT_CONFIGURED,
|
||||
})
|
||||
}
|
||||
// Dev-only deterministic key (NOT safe for production)
|
||||
return scryptSync('dev-only-key', 'gnubok-dev-salt', 32)
|
||||
|
||||
+2
-1
@@ -1169,7 +1169,8 @@
|
||||
"hourly_suffix": "/hr",
|
||||
"employment_employee": "Employee",
|
||||
"employment_company_owner": "Company owner",
|
||||
"employment_board_member": "Board member"
|
||||
"employment_board_member": "Board member",
|
||||
"save_error_request_id": "Reference: {id}"
|
||||
},
|
||||
"register": {
|
||||
"subtitle": "Create an account to get started",
|
||||
|
||||
+2
-1
@@ -1169,7 +1169,8 @@
|
||||
"hourly_suffix": "/tim",
|
||||
"employment_employee": "Anställd",
|
||||
"employment_company_owner": "Företagsledare",
|
||||
"employment_board_member": "Styrelseledamot"
|
||||
"employment_board_member": "Styrelseledamot",
|
||||
"save_error_request_id": "Ärende-id: {id}"
|
||||
},
|
||||
"register": {
|
||||
"subtitle": "Skapa ett konto för att komma igång",
|
||||
|
||||
Reference in New Issue
Block a user