Files
aigen/tests/library-delete-harden.test.mjs

325 lines
11 KiB
JavaScript

import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import ts from 'typescript'
const source = readFileSync(new URL('../server/utils/library.ts', import.meta.url), 'utf8')
const ast = ts.createSourceFile('library.ts', source, ts.ScriptTarget.Latest, true)
const names = [
'removedEntries',
'pathRemains',
'stillFileRemains',
'unlinkVerified',
'stillIdAllowed',
'stillArtifactPaths',
'entryPaths',
'assertRemovedEntries',
'assertStillFilesGone',
'removeStillFiles',
'detachDraftStills',
'sameFolder',
'emptyFolderRows',
'pruneMissingStillMasters',
'catalogWithPrunedStills',
'deleteStill',
'deleteStillFamily',
'wipeFolderContents'
]
const functions = ast.statements
.filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text || ''))
.map(node => node.getText(ast).replace(/^export /, ''))
.join('\n')
const js = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
function harness() {
const files = new Set()
const thrown = new Set()
const invalidated = []
const catalogEpoch = new Map()
let writes = 0
let stored = null
function existsSync(path) {
const value = String(path)
if (files.has(value)) return true
const prefix = value.endsWith('/') ? value : `${value}/`
for (const file of files) {
if (String(file).startsWith(prefix)) return true
}
return false
}
function statSync(path) {
if (!existsSync(path)) {
const error = new Error('ENOENT')
error.code = 'ENOENT'
throw error
}
if (!files.has(String(path))) return { isFile: () => false, isDirectory: () => true }
return { isFile: () => true, isDirectory: () => false }
}
function readdirSync(dir) {
const prefix = String(dir).endsWith('/') ? String(dir) : `${dir}/`
const names = []
for (const file of files) {
const value = String(file)
if (!value.startsWith(prefix)) continue
const rest = value.slice(prefix.length)
if (!rest || rest.includes('/')) continue
names.push(rest)
}
return names
}
function readCatalog() { return stored }
function writeCatalog(_owner, catalog) {
stored = catalog === undefined ? _owner : catalog
writes += 1
}
function invalidateCatalogCache(owner) { invalidated.push(owner) }
const api = new Function(
'rmSync',
'existsSync',
'statSync',
'readdirSync',
'join',
'ownerRoot',
'libraryRoot',
'console',
'stillPath',
'stillThumbFile',
'stillPreviewFile',
'clipDir',
'trackDir',
'createError',
'stillsInSameFamily',
'mutate',
'readCatalog',
'writeCatalog',
'catalogEpoch',
'invalidateCatalogCache',
`${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents, emptyFolderRows, removeStillFiles };`
)(
(path) => {
if ([...thrown].some(id => String(path).includes(id))) {
const error = new Error('EPERM')
error.code = 'EPERM'
throw error
}
files.delete(path)
},
existsSync,
statSync,
readdirSync,
(...parts) => parts.map(part => String(part).replace(/^\/+|\/+$/g, '')).filter(Boolean).join('/'),
(owner) => owner,
() => 'legacy',
console,
(owner, id) => `${owner}/stills/${id}`,
(owner, id) => `${owner}/stills/${id}.thumb.jpg`,
(owner, id) => `${owner}/stills/${id}.preview.jpg`,
(owner, id) => `${owner}/clips/${id}`,
(owner, id) => `${owner}/tracks/${id}`,
(error) => Object.assign(new Error(error.statusMessage), error),
(catalog, still) => catalog.stills.filter(item => item.id === still.id || (still.familyId && item.familyId === still.familyId)),
async (_owner, fn) => {
const catalog = readCatalog()
const result = fn(catalog)
writeCatalog(catalog)
return result
},
readCatalog,
writeCatalog,
catalogEpoch,
invalidateCatalogCache
)
return {
api,
files,
thrown,
invalidated,
get writes() { return writes },
set writes(value) { writes = value },
load(catalog) { stored = catalog }
}
}
test('deleteStill does not write the catalog when the master file survives', async () => {
const h = harness()
h.thrown.add('locked')
h.files.add('owner/stills/locked')
h.files.add('owner/stills/locked.thumb.jpg')
const catalog = {
stills: [{ id: 'locked', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }],
drafts: [{ id: 'd', stillId: 'locked', stillFilename: 'locked.png' }],
clips: [],
tracks: [],
folders: [{ id: 'inbox' }]
}
h.load(catalog)
h.files.add('owner/stills/keep')
await assert.rejects(() => h.api.deleteStill('owner', 'locked'), /locked/)
assert.equal(h.writes, 0)
assert.deepEqual(catalog.stills.map(item => item.id), ['locked', 'keep'])
assert.equal(catalog.drafts[0].stillId, 'locked')
assert.equal(h.files.has('owner/stills/locked'), true)
assert.equal(h.files.has('owner/stills/keep'), true)
assert.deepEqual(h.invalidated, [])
})
test('deleteStill removes master, thumb, preview, siblings, and legacy names', async () => {
const h = harness()
const catalog = {
stills: [{ id: 'a', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }],
drafts: [{ id: 'd', stillId: 'a', stillFilename: 'a.png' }],
clips: [],
tracks: [],
folders: [{ id: 'inbox' }]
}
h.load(catalog)
for (const path of [
'owner/stills/a',
'owner/stills/a.thumb.jpg',
'owner/stills/a.preview.jpg',
'owner/stills/a.extra.png',
'legacy/files/a',
'legacy/stills/a.thumb.jpg',
'owner/stills/keep',
'owner/stills/keep.thumb.jpg'
]) h.files.add(path)
await h.api.deleteStill('owner', 'a')
assert.equal(h.writes, 1)
assert.deepEqual(catalog.stills.map(item => item.id), ['keep'])
assert.equal(catalog.drafts[0].stillId, undefined)
for (const path of [
'owner/stills/a',
'owner/stills/a.thumb.jpg',
'owner/stills/a.preview.jpg',
'owner/stills/a.extra.png',
'legacy/files/a',
'legacy/stills/a.thumb.jpg'
]) assert.equal(h.files.has(path), false, path)
assert.equal(h.files.has('owner/stills/keep'), true)
assert.equal(h.files.has('owner/stills/keep.thumb.jpg'), true)
assert.deepEqual(h.invalidated, ['owner'])
})
test('deleteStill unlinks leftover files when the catalog row is already gone', async () => {
const h = harness()
const catalog = {
stills: [{ id: 'keep', folderId: 'inbox' }],
drafts: [],
clips: [],
tracks: [],
folders: [{ id: 'inbox' }]
}
h.load(catalog)
h.files.add('owner/stills/orphan')
h.files.add('owner/stills/orphan.thumb.jpg')
h.files.add('owner/stills/orphan.preview.jpg')
h.files.add('legacy/stills/orphan')
h.files.add('owner/stills/keep')
await assert.rejects(() => h.api.deleteStill('owner', 'orphan'), /Image not found/)
assert.equal(h.writes, 0)
assert.deepEqual(catalog.stills.map(item => item.id), ['keep'])
assert.equal(h.files.has('owner/stills/orphan'), false)
assert.equal(h.files.has('owner/stills/orphan.thumb.jpg'), false)
assert.equal(h.files.has('owner/stills/orphan.preview.jpg'), false)
assert.equal(h.files.has('legacy/stills/orphan'), false)
assert.equal(h.files.has('owner/stills/keep'), true)
})
test('pruneMissingStillMasters drops the row and unlinks leftover files', async () => {
const h = harness()
const catalog = {
stills: [{ id: 'gone', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }],
drafts: [{ id: 'd', stillId: 'gone' }],
clips: [],
tracks: [],
folders: [{ id: 'inbox' }]
}
h.load(structuredClone(catalog))
h.files.add('owner/stills/keep')
h.files.add('owner/stills/gone.thumb.jpg')
h.files.add('owner/stills/gone.preview.jpg')
const page = h.api.catalogWithPrunedStills('owner')
assert.equal(h.writes, 1)
assert.deepEqual(page.stills.map(item => item.id), ['keep'])
assert.equal(page.drafts[0].stillId, undefined)
assert.equal(h.files.has('owner/stills/gone.thumb.jpg'), false)
assert.equal(h.files.has('owner/stills/gone.preview.jpg'), false)
assert.equal(h.files.has('owner/stills/keep'), true)
})
test('wipeFolderContents throws and keeps the catalog when a file survives', async () => {
const h = harness()
h.thrown.add('locked')
const catalog = {
stills: [{ id: 'locked', folderId: 'inbox' }],
clips: [{ id: 'clip', folderId: 'inbox' }],
tracks: [],
drafts: [],
folders: [{ id: 'inbox', name: 'Inbox' }]
}
h.load(catalog)
h.files.add('owner/stills/locked')
await assert.rejects(() => h.api.wipeFolderContents('owner', 'inbox'), /locked/)
assert.equal(h.writes, 0)
assert.equal(catalog.stills.length, 1)
assert.equal(catalog.clips.length, 1)
assert.equal(h.files.has('owner/stills/locked'), true)
assert.deepEqual(h.invalidated, [])
})
test('wipeFolderContents leaves zero rows for that folder and zero files for those ids', async () => {
const h = harness()
const catalog = {
stills: [
{ id: 'a', folderId: 'inbox' },
{ id: 'b', folderId: 'other' }
],
clips: [{ id: 'c', folderId: 'inbox' }],
tracks: [
{ id: 't', folderId: 'inbox' },
{ id: 'u', folderId: 'other' }
],
drafts: [],
folders: [{ id: 'inbox', name: 'Inbox' }, { id: 'other', name: 'Other' }]
}
h.load(catalog)
h.files.add('owner/stills/a')
h.files.add('owner/stills/a.thumb.jpg')
h.files.add('owner/stills/b')
h.files.add('owner/clips/c')
h.files.add('owner/tracks/t')
const result = await h.api.wipeFolderContents('owner', 'inbox')
assert.equal(result.deleted, 3)
assert.deepEqual(catalog.stills.map(item => item.id), ['b'])
assert.deepEqual(catalog.clips, [])
assert.deepEqual(catalog.tracks.map(item => item.id), ['u'])
assert.equal(h.files.has('owner/stills/a'), false)
assert.equal(h.files.has('owner/stills/a.thumb.jpg'), false)
assert.equal(h.files.has('owner/clips/c'), false)
assert.equal(h.files.has('owner/tracks/t'), false)
assert.equal(h.files.has('owner/stills/b'), true)
assert.deepEqual(h.invalidated, ['owner'])
})
test('pruneMissingStillMasters only drops and a second read does not put the still back', async () => {
const h = harness()
const catalog = {
stills: [{ id: 'gone', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }],
drafts: [],
clips: [],
tracks: [],
folders: [{ id: 'inbox' }]
}
h.load(catalog)
h.files.add('owner/stills/keep')
const before = new Set(catalog.stills.map(item => item.id))
const page = h.api.catalogWithPrunedStills('owner')
assert.deepEqual(page.stills.map(item => item.id), ['keep'])
for (const still of page.stills) assert.equal(before.has(still.id), true)
assert.ok(page.stills.length < before.size)
h.files.add('owner/stills/gone')
const again = h.api.catalogWithPrunedStills('owner')
assert.deepEqual(again.stills.map(item => item.id), ['keep'])
})