Просмотр исходного кода

Refuse an uploaded backup whose record ids cannot sit in a link (#672)

* Refuse an uploaded backup whose record ids cannot sit in a link

* Show a refused restore in the viewer's language

* Refuse an empty record id in an uploaded backup too
Bernt Christian Egeland 4 дней назад
Родитель
Сommit
f620cbda54

+ 1 - 0
src/__tests__/app/api/restore-freeze-routes.test.ts

@@ -34,6 +34,7 @@ vi.mock('@/features/integrations/Lib/backup', () => ({
 vi.mock('@/lib/backup/engine', () => ({ backupLockHolder: vi.fn(() => null) }))
 vi.mock('@/lib/backup/engine', () => ({ backupLockHolder: vi.fn(() => null) }))
 vi.mock('@/lib/backup/tenancy', () => ({
 vi.mock('@/lib/backup/tenancy', () => ({
   RestoreRefusedError: class RestoreRefusedError extends Error {},
   RestoreRefusedError: class RestoreRefusedError extends Error {},
+  assertUrlSafeIds: vi.fn(),
   restoreLockHolder: vi.fn(() => null),
   restoreLockHolder: vi.fn(() => null),
 }))
 }))
 vi.mock('@/lib/backup/import', () => ({
 vi.mock('@/lib/backup/import', () => ({

+ 44 - 0
src/__tests__/lib/backup/import-tenancy.test.ts

@@ -168,6 +168,50 @@ describe("a file that reuses another workshop's ids", () => {
   })
   })
 })
 })
 
 
+describe('a file with ids that cannot sit in a link', () => {
+  it('is refused before anything is written, naming the record', async () => {
+    const data = file()
+    data.customers[0].id = '{11111111-2222-3333-4444-555555555555}'
+    const response = await importJson(data)
+    expect(response.status).toBe(400)
+    expect(await response.json()).toEqual({
+      error:
+        'The file holds a Customer id that cannot be used in a link: {11111111-2222-3333-4444-555555555555}',
+      code: 'unsafe_ids',
+    })
+    expect(state.calls).toEqual([])
+  })
+
+  it('is refused for a child row too', async () => {
+    const data = file()
+    data.vehicles[0].serviceRecords[0].partItems[0].id = 'part/a'
+    const response = await importJson(data)
+    expect(response.status).toBe(400)
+    expect((await response.json()).code).toBe('unsafe_ids')
+    expect(writes()).toEqual([])
+  })
+
+  it('is refused for an empty id', async () => {
+    const data = file()
+    data.customers[0].id = ''
+    const response = await importJson(data)
+    expect(response.status).toBe(400)
+    expect(await response.json()).toEqual({
+      error: 'The file holds a Customer with an empty id',
+      code: 'unsafe_ids',
+    })
+    expect(state.calls).toEqual([])
+  })
+
+  it('accepts ids from another system that are safe in a link', async () => {
+    const data = file()
+    data.customers[0].id = '11111111222233334444555555555555'
+    data.vehicles[0].customerId = '11111111222233334444555555555555'
+    const response = await importJson(data)
+    expect(response.status).toBe(200)
+  })
+})
+
 describe('a file whose foreign keys point at another workshop', () => {
 describe('a file whose foreign keys point at another workshop', () => {
   it('never writes one of those ids', async () => {
   it('never writes one of those ids', async () => {
     const response = await importJson(file())
     const response = await importJson(file())

+ 5 - 1
src/app/(authenticated)/settings/data/data-settings.tsx

@@ -249,7 +249,11 @@ export function DataSettings({
       if (!res.ok) {
       if (!res.ok) {
         const body = await res.json()
         const body = await res.json()
         // A refusal names its reason; the sentence for it is in the workshop's language.
         // A refusal names its reason; the sentence for it is in the workshop's language.
-        const code = typeof body.code === 'string' ? body.code : ''
+        // The code is snake_case (`foreign_ids`), the message key camelCase (`foreignIds`).
+        const code =
+          typeof body.code === 'string'
+            ? body.code.replace(/_([a-z])/g, (_: string, c: string) => c.toUpperCase())
+            : ''
         throw new Error(
         throw new Error(
           code && t.has(`data.restoreRefused.${code}`)
           code && t.has(`data.restoreRefused.${code}`)
             ? t(`data.restoreRefused.${code}`)
             ? t(`data.restoreRefused.${code}`)

+ 2 - 1
src/app/api/protected/backup/import/route.ts

@@ -6,7 +6,7 @@ import { isRestoring, RESTORE_IN_PROGRESS_MESSAGE } from '@/lib/backup/freeze'
 import { isDemoMode } from '@/lib/demo'
 import { isDemoMode } from '@/lib/demo'
 import { canRestoreBackups } from '@/features/integrations/Lib/backup'
 import { canRestoreBackups } from '@/features/integrations/Lib/backup'
 import { backupLockHolder } from '@/lib/backup/engine'
 import { backupLockHolder } from '@/lib/backup/engine'
-import { RestoreRefusedError, restoreLockHolder } from '@/lib/backup/tenancy'
+import { RestoreRefusedError, assertUrlSafeIds, restoreLockHolder } from '@/lib/backup/tenancy'
 import {
 import {
   type BackupData,
   type BackupData,
   assertSupportedBackup,
   assertSupportedBackup,
@@ -130,6 +130,7 @@ export async function POST(request: NextRequest) {
   }
   }
 
 
   try {
   try {
+    assertUrlSafeIds(backup.data)
     const { redactedSettings } = await restoreBackup(
     const { redactedSettings } = await restoreBackup(
       ctx,
       ctx,
       backup,
       backup,

+ 25 - 1
src/lib/backup/tenancy.ts

@@ -17,7 +17,7 @@ import { TENANCY_SCHEMA } from './tenancy-schema'
  * reaches the database.
  * reaches the database.
  */
  */
 
 
-export type RestoreRefusal = 'foreign_ids' | 'busy' | 'owner_only'
+export type RestoreRefusal = 'foreign_ids' | 'unsafe_ids' | 'busy' | 'owner_only'
 
 
 /** A refusal with a reason the browser can name, as opposed to a failure. */
 /** A refusal with a reason the browser can name, as opposed to a failure. */
 export class RestoreRefusedError extends Error {
 export class RestoreRefusedError extends Error {
@@ -36,6 +36,8 @@ const UNCHECKED_TARGETS = new Set(['User', 'Organization'])
 
 
 const CHUNK = 5000
 const CHUNK = 5000
 
 
+const URL_SAFE_ID = /^[A-Za-z0-9_-]+$/
+
 function add(map: IdsByModel, model: string, id: string): void {
 function add(map: IdsByModel, model: string, id: string): void {
   let set = map.get(model)
   let set = map.get(model)
   if (!set) {
   if (!set) {
@@ -209,6 +211,28 @@ export async function assertNoForeignRows(
   }
   }
 }
 }
 
 
+/**
+ * Refuses an uploaded file with a row id that cannot sit in a URL as it is.
+ * Detail pages look a row up by the id in their path and links carry it
+ * unencoded, so such a row would restore and then never open. An empty id
+ * is one of them: the link ends at the list. Restore points skip this: a
+ * workshop's own backup must always come back.
+ */
+export function assertUrlSafeIds(data: Row): void {
+  walkBackup(data, (model, row) => {
+    const id = row.id
+    if (typeof id === 'string' && !URL_SAFE_ID.test(id)) {
+      throw new RestoreRefusedError(
+        'unsafe_ids',
+        id === ''
+          ? `The file holds a ${model} with an empty id`
+          : `The file holds a ${model} id that cannot be used in a link: ${id.slice(0, 60)}`
+      )
+    }
+    return 'keep'
+  })
+}
+
 /** Of the candidate ids, the ones that are rows of this workshop already. */
 /** Of the candidate ids, the ones that are rows of this workshop already. */
 export async function lookupOwnIds(
 export async function lookupOwnIds(
   tx: unknown,
   tx: unknown,