feat(mcp): personal_number on gnubok_update_customer (#1876) (#1890)

gnubok_create_customer takes a personnummer (encrypted before approval)
but gnubok_update_customer did not, so an existing customer whose
personnummer sat in the org-number field could not be corrected via MCP.
The REST PATCH already supports it; this closes the MCP/pending-operations
gap across its three layers:

- tool inputSchema: personal_number (string or null) on the strict
  whitelist. The tool validates the plaintext before any DB read and
  mirrors the REST PATCH semantics: masked echo (********-1234 or
  ********-????) = leave unchanged, explicit null = clear, absent =
  untouched. Setting is refused unless the row ends up as an individual
  (GDPR art. 5.1 c), including via a simultaneous type change.
- CustomerChangesSchema: personal_number_encrypted (nullable, ciphertext
  shape per customers_personal_number_check 20260726110000). The
  plaintext key stays forbidden by .strict() and staging-pii-guard.
- update executor: maps the staged ciphertext onto customers
  .personal_number (set/clear/leave), re-checks the individual-only rule
  against a tampered row, and returns only personal_number_masked.

PII handling: the personnummer is encrypted at staging time
(AES-256-GCM, same path as create); pending_operations params carry only
the ciphertext and the approval preview only the masked form. Idempotency
hashing switches to the masked preview for personnummer-bearing updates
(random-IV ciphertext would break retries); other updates keep their
previous hash identity.

catalogVisibility stays 'search': tools/list is at its 59.95K token
ceiling with zero headroom (see DECISIONS.md).

Fixes #1876

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-25 14:35:02 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent d80103a2f5
commit 77cacdcf34
7 changed files with 595 additions and 9 deletions
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { PendingOperation } from '@/types'
import { createQueuedMockSupabase } from '@/tests/helpers'
import { encryptPersonnummer } from '@/lib/salary/personnummer'
import { commitPendingOperation } from '../commit'
import { validateVatNumber } from '@/lib/vat/vies-client'
@@ -250,3 +251,179 @@ describe('commitPendingOperation: update_customer', () => {
expect(supabase.from).toHaveBeenCalledTimes(2)
})
})
// ── personal_number (#1876) ───────────────────────────────────────────
//
// Synthetic personnummer, never a real one. Staging encrypts, so the
// executor only ever sees personal_number_encrypted: ciphertext sets the
// column, explicit null clears it, absent leaves it untouched.
const PERSONAL_NUMBER = '19900101-1234'
function individualRow(overrides: Record<string, unknown> = {}) {
return {
id: CUSTOMER_ID,
name: 'Anna Andersson',
customer_type: 'individual',
customer_number: null,
email: null,
phone: null,
address_line1: null,
address_line2: null,
postal_code: null,
city: null,
country: 'Sweden',
org_number: null,
vat_number: null,
vat_number_validated: false,
language: 'sv',
default_payment_terms: 30,
notes: null,
personal_number: null,
...overrides,
}
}
describe('commitPendingOperation: update_customer personal_number', () => {
it('stores the staged ciphertext as the customer personal_number and returns only the mask', async () => {
const encrypted = encryptPersonnummer(PERSONAL_NUMBER)
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-customer-1' } }) // CAS claim
enqueue({ data: { customer_type: 'individual' } }) // current read
enqueue({ data: individualRow({ personal_number: encrypted }) }) // update returning
enqueue({ data: null }) // dispatcher update
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({
customer_id: CUSTOMER_ID,
changes: { personal_number_encrypted: encrypted },
}),
)
expect(result.status).toBe('committed')
const updatePayload = findCall('customers', 'update')?.[0] as Record<string, unknown>
expect(updatePayload).toMatchObject({ personal_number: encrypted })
expect(updatePayload).not.toHaveProperty('personal_number_encrypted')
expect(result.data).toMatchObject({
customer_id: CUSTOMER_ID,
personal_number_masked: '********-1234',
})
// result_data is persisted and rendered in approval UIs: never the
// plaintext, never the raw ciphertext.
const serialized = JSON.stringify(result)
expect(serialized).not.toContain(PERSONAL_NUMBER)
expect(serialized).not.toContain(encrypted)
})
it('clears the stored personnummer on explicit null', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-customer-1' } })
enqueue({ data: { customer_type: 'individual' } })
enqueue({ data: individualRow() })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({
customer_id: CUSTOMER_ID,
changes: { personal_number_encrypted: null },
}),
)
expect(result.status).toBe('committed')
const updatePayload = findCall('customers', 'update')?.[0] as Record<string, unknown>
expect(updatePayload).toHaveProperty('personal_number', null)
expect(result.data).toMatchObject({ personal_number_masked: null })
})
it('leaves the stored personnummer untouched when the field is absent', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-customer-1' } })
enqueue({ data: { customer_type: 'individual' } })
enqueue({ data: individualRow({ city: 'New City' }) })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({
customer_id: CUSTOMER_ID,
changes: { city: 'New City' },
}),
)
expect(result.status).toBe('committed')
const updatePayload = findCall('customers', 'update')?.[0] as Record<string, unknown>
expect(updatePayload).not.toHaveProperty('personal_number')
})
it('refuses a staged personnummer on a business customer without writing', async () => {
const encrypted = encryptPersonnummer(PERSONAL_NUMBER)
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-customer-1' } })
enqueue({ data: { customer_type: 'swedish_business' } })
enqueue({ data: null }) // dispatcher's reject update
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({
customer_id: CUSTOMER_ID,
changes: { personal_number_encrypted: encrypted },
}),
)
expect(result.status).toBe('failed')
expect(result.http_status).toBe(400)
expect(result.error).toMatch(/individual/)
expect(findCall('customers', 'update')).toBeUndefined()
})
it('rejects a tampered plaintext personal_number key in changes', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-customer-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({
customer_id: CUSTOMER_ID,
changes: { personal_number: PERSONAL_NUMBER },
}),
)
expect(result.status).toBe('failed')
expect(result.http_status).toBe(400)
expect(result.error).toMatch(/unrecognized key/i)
expect(findCall('customers', 'update')).toBeUndefined()
})
it('rejects a tampered plaintext value under personal_number_encrypted', async () => {
const { supabase, enqueue, findCall } = createQueuedMockSupabase()
enqueue({ data: { id: 'op-customer-1' } })
enqueue({ data: null })
const result = await commitPendingOperation(
supabase as never,
'user-1',
'company-1',
makePendingOp({
customer_id: CUSTOMER_ID,
changes: { personal_number_encrypted: PERSONAL_NUMBER },
}),
)
expect(result.status).toBe('failed')
expect(result.http_status).toBe(400)
expect(result.error).toMatch(/encrypted personal number/i)
expect(findCall('customers', 'update')).toBeUndefined()
})
})
+29 -3
View File
@@ -33,7 +33,10 @@ import {
normalizeReroutedPersonalNumber,
orgNumberHoldsPersonalNumber,
} from '@/lib/customers/personal-number-shape'
import { encryptCustomerPersonalNumber } from '@/lib/customers/protect-personal-number'
import {
encryptCustomerPersonalNumber,
maskStoredCustomerPersonalNumber,
} from '@/lib/customers/protect-personal-number'
import { resolveDefaultPaymentTerms } from '@/lib/customers/default-payment-terms'
import {
normalizeVatRateToDecimal,
@@ -483,11 +486,31 @@ async function commitUpdateCustomer(
if (currentError) return { error: currentError.message, status: 500 }
if (!current) return { error: 'Customer not found', status: 404 }
const updateData: Record<string, unknown> = { ...changes }
// personal_number never travels in plaintext: staging validated the input
// and stored AES-256-GCM ciphertext under personal_number_encrypted (see
// CustomerChangesSchema). Map it onto the customers.personal_number column
// with the REST PATCH semantics: ciphertext sets the value, explicit null
// clears it, absent leaves the stored value untouched (a masked echo was
// already dropped at staging and never reaches this executor).
const { personal_number_encrypted: personalNumberEncrypted, ...columnChanges } = changes
const updateData: Record<string, unknown> = { ...columnChanges }
if (changes.customer_number !== undefined) {
updateData.customer_number = changes.customer_number || null
}
const effectiveType = changes.customer_type ?? current.customer_type
if (personalNumberEncrypted !== undefined) {
// Same guard as staging and the REST PATCH route: only individual rows
// get their identifiers masked on read (GDPR art. 5.1 c), so a
// personnummer on a business customer is refused, not stored. Re-checked
// here so a tampered pending_operations row cannot slip past it.
if (personalNumberEncrypted !== null && effectiveType !== 'individual') {
return {
error: 'personal_number is only allowed for customer_type "individual"',
status: 400,
}
}
updateData.personal_number = personalNumberEncrypted
}
if (changes.customer_type !== undefined && effectiveType !== 'individual') {
updateData.personal_number = null
}
@@ -518,7 +541,7 @@ async function commitUpdateCustomer(
.update(updateData)
.eq('id', customerId)
.eq('company_id', companyId)
.select('id, name, customer_type, customer_number, email, phone, address_line1, address_line2, postal_code, city, country, org_number, vat_number, vat_number_validated, language, default_payment_terms, notes')
.select('id, name, customer_type, customer_number, email, phone, address_line1, address_line2, postal_code, city, country, org_number, vat_number, vat_number_validated, language, default_payment_terms, notes, personal_number')
.maybeSingle()
if (error) {
@@ -548,6 +571,9 @@ async function commitUpdateCustomer(
language: data.language ?? 'sv',
default_payment_terms: data.default_payment_terms,
notes: data.notes ?? null,
// Never the stored ciphertext, and never plaintext: result_data is
// persisted on the pending operation and rendered in approval UIs.
personal_number_masked: maskStoredCustomerPersonalNumber(data.personal_number),
},
}
}
@@ -0,0 +1,52 @@
import { describe, it, expect } from 'vitest'
import { encryptPersonnummer } from '@/lib/salary/personnummer'
import { UpdateCustomerParamsSchema } from '../customer'
const CUSTOMER_ID = '11111111-1111-4111-8111-111111111111'
const wrap = (changes: Record<string, unknown>) => ({
customer_id: CUSTOMER_ID,
changes,
})
// Synthetic personnummer, never a real one.
const PERSONAL_NUMBER = '19900101-1234'
describe('UpdateCustomerParamsSchema: personal_number_encrypted (#1876)', () => {
it('accepts AES-256-GCM ciphertext', () => {
const encrypted = encryptPersonnummer(PERSONAL_NUMBER)
const parsed = UpdateCustomerParamsSchema.parse(
wrap({ personal_number_encrypted: encrypted }),
)
expect(parsed.changes.personal_number_encrypted).toBe(encrypted)
})
it('accepts explicit null (clears the stored value at commit)', () => {
const parsed = UpdateCustomerParamsSchema.parse(
wrap({ personal_number_encrypted: null }),
)
expect(parsed.changes.personal_number_encrypted).toBeNull()
})
it('rejects a plaintext personnummer under personal_number_encrypted', () => {
expect(() =>
UpdateCustomerParamsSchema.parse(wrap({ personal_number_encrypted: PERSONAL_NUMBER })),
).toThrow(/encrypted personal number/i)
})
it('rejects the plaintext personal_number key (strict schema)', () => {
expect(() =>
UpdateCustomerParamsSchema.parse(wrap({ personal_number: PERSONAL_NUMBER })),
).toThrow(/unrecognized key/i)
})
it('still rejects unknown fields', () => {
expect(() =>
UpdateCustomerParamsSchema.parse(wrap({ company_id: 'other-company' })),
).toThrow(/unrecognized key/i)
})
it('still requires at least one changed field', () => {
expect(() => UpdateCustomerParamsSchema.parse(wrap({}))).toThrow(/at least one/i)
})
})
@@ -18,6 +18,19 @@ const CustomerChangesSchema = z
language: UpdateCustomerSchema.shape.language,
default_payment_terms: UpdateCustomerSchema.shape.default_payment_terms,
notes: UpdateCustomerSchema.shape.notes,
// The personnummer, already encrypted at staging time: the MCP tool
// validates the plaintext (REST semantics: a masked echo is dropped
// before it gets here) and stores only AES-256-GCM ciphertext, because
// staging-pii-guard.ts forbids the plaintext personal_number key in
// pending_operations payloads. Ciphertext shape mirrors
// customers_personal_number_check (20260726110000). At commit: string
// sets the stored value, explicit null clears it, absent leaves it
// untouched.
personal_number_encrypted: z
.string()
.regex(/^[0-9a-f]{76,255}$/, 'Invalid encrypted personal number')
.nullable()
.optional(),
})
.strict()
.superRefine((changes, ctx) => {