|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// `POST /data/:object/:id/clone` on a record whose file fields are set, end to |
| 4 | +// end through the real stack: REST clone door → `cloneData` → ObjectQL insert |
| 5 | +// → the storage service's field-reference copy-on-claim hooks, with real bytes |
| 6 | +// on a local adapter. |
| 7 | +// |
| 8 | +// ── What this pins ────────────────────────────────────────────────────────── |
| 9 | +// |
| 10 | +// A clone with no body answers 201, and every file-class field of the copy |
| 11 | +// references the source's file the way any write naming an already-owned |
| 12 | +// `sys_file` id does (ADR-0104 D3 wave 2, exclusive ownership): the bytes are |
| 13 | +// copied into a fresh `sys_file`, the copy is owned by the clone's slot, and |
| 14 | +// the source keeps its own file. Covered: a single `file`, a `multiple: true` |
| 15 | +// `file`, and an `image` — the multi-capable pair and one more member of |
| 16 | +// `FILE_REFERENCE_TYPES`. |
| 17 | +// |
| 18 | +// The defect this guards: `cloneData` read the source through the caller's |
| 19 | +// expanded read, which serves a file field as the `{ id, name, size, mimeType, |
| 20 | +// url }` object, and re-inserted that object; the media value-shape check |
| 21 | +// refused it with 400 "… has an invalid file value: … expected string, |
| 22 | +// received object". |
| 23 | +// |
| 24 | +// ── Why each assertion is load-bearing ────────────────────────────────────── |
| 25 | +// |
| 26 | +// The CONTROL is the `overrides` workaround — the same clone naming the |
| 27 | +// source's ids explicitly — which answered 201 before the fix. The plain |
| 28 | +// clone is held to the SAME reference rule the control demonstrates (a new |
| 29 | +// id, owned by the clone, same bytes), so the pin cannot pass by inventing a |
| 30 | +// second ownership rule. |
| 31 | +// |
| 32 | +// The READ-BACK of the stored form (`RAW_FILE_VALUES_CONTEXT_KEY`) and of |
| 33 | +// `sys_file`'s ownership columns, under a system context: the 201 body alone |
| 34 | +// would not show which file the clone's slot holds. |
| 35 | +// |
| 36 | +// `overrides` still wins: a file field named in `overrides` takes the |
| 37 | +// override, not the source's file. |
| 38 | + |
| 39 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 40 | +import { promises as fs, mkdtempSync } from 'node:fs'; |
| 41 | +import { join } from 'node:path'; |
| 42 | +import { tmpdir } from 'node:os'; |
| 43 | +import { bootStack, type VerifyStack } from '@objectstack/verify'; |
| 44 | +import { defineStack } from '@objectstack/spec'; |
| 45 | +import { ObjectSchema, Field, RAW_FILE_VALUES_CONTEXT_KEY, isFileIdToken } from '@objectstack/spec/data'; |
| 46 | +import { StorageServicePlugin } from '@objectstack/service-storage'; |
| 47 | +import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; |
| 48 | + |
| 49 | +const SYS = { isSystem: true } as const; |
| 50 | +const RAW = { ...SYS, [RAW_FILE_VALUES_CONTEXT_KEY]: true } as const; |
| 51 | +const OBJECT = 'cff_doc'; |
| 52 | + |
| 53 | +const CffDoc = ObjectSchema.create({ |
| 54 | + name: OBJECT, |
| 55 | + label: 'Clone File Document', |
| 56 | + fields: { |
| 57 | + name: Field.text({ label: 'Name' }), |
| 58 | + report: Field.file({ label: 'Report' }), |
| 59 | + papers: Field.file({ label: 'Papers', multiple: true }), |
| 60 | + cover: Field.image({ label: 'Cover' }), |
| 61 | + }, |
| 62 | +}); |
| 63 | + |
| 64 | +const cffStack = defineStack({ |
| 65 | + manifest: { |
| 66 | + id: 'com.dogfood.clone-file-field-reference', |
| 67 | + namespace: 'cff', |
| 68 | + version: '0.0.0', |
| 69 | + type: 'app', |
| 70 | + name: 'Clone File Field Reference Fixture', |
| 71 | + description: 'An object with single, multiple and image file fields, cloned through the data API.', |
| 72 | + }, |
| 73 | + objects: [CffDoc], |
| 74 | +}); |
| 75 | + |
| 76 | +describe('POST /data/:object/:id/clone on a record whose file fields are set', () => { |
| 77 | + let stack: VerifyStack; |
| 78 | + let rootDir: string; |
| 79 | + let token: string; |
| 80 | + let ql: any; |
| 81 | + |
| 82 | + /** Upload real bytes through presign → PUT → complete; returns the `sys_file` id. */ |
| 83 | + async function upload(name: string, body: string, mimeType: string): Promise<string> { |
| 84 | + const auth = { Authorization: `Bearer ${token}` }; |
| 85 | + const presign = await stack.api('/storage/upload/presigned', { |
| 86 | + method: 'POST', |
| 87 | + headers: { 'Content-Type': 'application/json', ...auth }, |
| 88 | + body: JSON.stringify({ filename: name, mimeType, size: body.length, scope: 'user' }), |
| 89 | + }); |
| 90 | + expect(presign.status, 'presign').toBe(200); |
| 91 | + const { data } = (await presign.json()) as any; |
| 92 | + const put = await stack.raw(String(data.uploadUrl).replace(/^https?:\/\/[^/]+/, ''), { |
| 93 | + method: 'PUT', |
| 94 | + headers: data.headers ?? { 'content-type': mimeType }, |
| 95 | + body, |
| 96 | + }); |
| 97 | + expect(put.status, 'raw PUT').toBeLessThan(300); |
| 98 | + const complete = await stack.api('/storage/upload/complete', { |
| 99 | + method: 'POST', |
| 100 | + headers: { 'Content-Type': 'application/json', ...auth }, |
| 101 | + body: JSON.stringify({ fileId: data.fileId }), |
| 102 | + }); |
| 103 | + expect(complete.status, 'complete').toBe(200); |
| 104 | + return String(data.fileId); |
| 105 | + } |
| 106 | + |
| 107 | + const call = async (method: 'POST', path: string, body?: unknown) => { |
| 108 | + const res = await stack.apiAs(token, method, path, body); |
| 109 | + return { status: res.status, body: (await res.json()) as any }; |
| 110 | + }; |
| 111 | + |
| 112 | + /** The record's file fields in their STORED form, read above every access layer. */ |
| 113 | + const stored = async (id: string) => ql.findOne(OBJECT, { where: { id }, context: RAW }); |
| 114 | + |
| 115 | + /** A `sys_file` row's owner and bytes, read above every access layer. */ |
| 116 | + const fileState = async (id: string) => { |
| 117 | + const row = await ql.findOne('sys_file', { where: { id }, context: SYS }); |
| 118 | + expect(row, `sys_file ${id} exists`).toBeTruthy(); |
| 119 | + const bytes = await fs.readFile(join(rootDir, String(row.key)), 'utf8'); |
| 120 | + return { owner: [row.ref_object, String(row.ref_id), row.ref_field], bytes }; |
| 121 | + }; |
| 122 | + |
| 123 | + /** Create a source record through the data door with every file field set. */ |
| 124 | + async function sourceRecord(tag: string) { |
| 125 | + const files = { |
| 126 | + report: await upload(`${tag}-report.txt`, `${tag} report`, 'text/plain'), |
| 127 | + papers: [ |
| 128 | + await upload(`${tag}-a.txt`, `${tag} paper a`, 'text/plain'), |
| 129 | + await upload(`${tag}-b.txt`, `${tag} paper b`, 'text/plain'), |
| 130 | + ], |
| 131 | + cover: await upload(`${tag}-cover.png`, `${tag} cover`, 'image/png'), |
| 132 | + }; |
| 133 | + const created = await call('POST', `/data/${OBJECT}`, { name: tag, ...files }); |
| 134 | + expect(created.status, JSON.stringify(created.body)).toBe(201); |
| 135 | + const id = String(created.body.id ?? created.body.data?.id ?? created.body.record?.id); |
| 136 | + // The source owns every file it names. |
| 137 | + expect((await fileState(files.report)).owner).toEqual([OBJECT, id, 'report']); |
| 138 | + expect((await fileState(files.papers[0])).owner).toEqual([OBJECT, id, 'papers']); |
| 139 | + expect((await fileState(files.cover)).owner).toEqual([OBJECT, id, 'cover']); |
| 140 | + return { id, files }; |
| 141 | + } |
| 142 | + |
| 143 | + /** The clone's id from a 201 clone answer. */ |
| 144 | + const cloneIdOf = (body: any) => String(body.id ?? body.data?.id ?? body.record?.id); |
| 145 | + |
| 146 | + /** |
| 147 | + * Every file field of the clone holds a NEW `sys_file` id, owned by the |
| 148 | + * clone's slot, carrying the source file's bytes — and the source still owns |
| 149 | + * its own file. The exclusive-ownership copy rule, per value. |
| 150 | + */ |
| 151 | + async function expectCopiedPerReferenceRule(source: { id: string; files: any }, cloneId: string) { |
| 152 | + const copy = await stored(cloneId); |
| 153 | + const pairs: Array<[string, string, string]> = [ |
| 154 | + ['report', source.files.report, copy.report], |
| 155 | + ['papers', source.files.papers[0], copy.papers?.[0]], |
| 156 | + ['papers', source.files.papers[1], copy.papers?.[1]], |
| 157 | + ['cover', source.files.cover, copy.cover], |
| 158 | + ]; |
| 159 | + expect(Array.isArray(copy.papers) ? copy.papers.length : copy.papers).toBe(2); |
| 160 | + for (const [field, srcId, copyId] of pairs) { |
| 161 | + expect(isFileIdToken(copyId), `${field}: the clone stores a file id, got ${JSON.stringify(copyId)}`).toBe(true); |
| 162 | + expect(copyId, `${field}: the clone references its own copy, not the source's file`).not.toBe(srcId); |
| 163 | + const src = await fileState(srcId); |
| 164 | + const dst = await fileState(copyId); |
| 165 | + expect(src.owner, `${field}: the source keeps its file`).toEqual([OBJECT, source.id, field]); |
| 166 | + expect(dst.owner, `${field}: the copy is owned by the clone's slot`).toEqual([OBJECT, cloneId, field]); |
| 167 | + expect(dst.bytes, `${field}: the copy carries the source's bytes`).toBe(src.bytes); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + beforeAll(async () => { |
| 172 | + rootDir = mkdtempSync(join(tmpdir(), 'cff-dogfood-')); |
| 173 | + stack = await bootStack(cffStack, { |
| 174 | + extraPlugins: [ |
| 175 | + // The `sys_migration` flag ledger (#4243): a store created by this boot |
| 176 | + // attests its file migration, so the media value-shape check enforces. |
| 177 | + new PlatformObjectsPlugin(), |
| 178 | + new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }), |
| 179 | + ], |
| 180 | + }); |
| 181 | + token = await stack.signIn(); |
| 182 | + ql = await stack.kernel.getServiceAsync('objectql'); |
| 183 | + }, 120_000); |
| 184 | + |
| 185 | + afterAll(async () => { |
| 186 | + await stack?.stop(); |
| 187 | + }); |
| 188 | + |
| 189 | + it('CONTROL: a clone whose overrides name the source file ids answers 201 and copies every file', async () => { |
| 190 | + const source = await sourceRecord('ctl'); |
| 191 | + const r = await call('POST', `/data/${OBJECT}/${source.id}/clone`, { overrides: { ...source.files } }); |
| 192 | + |
| 193 | + expect(r.status, JSON.stringify(r.body)).toBe(201); |
| 194 | + await expectCopiedPerReferenceRule(source, cloneIdOf(r.body)); |
| 195 | + }); |
| 196 | + |
| 197 | + it('a clone with no body answers 201, and its file fields follow the same copy rule', async () => { |
| 198 | + const source = await sourceRecord('bare'); |
| 199 | + const r = await call('POST', `/data/${OBJECT}/${source.id}/clone`); |
| 200 | + |
| 201 | + expect(r.status, JSON.stringify(r.body)).toBe(201); |
| 202 | + const cloneId = cloneIdOf(r.body); |
| 203 | + expect(cloneId).not.toBe(source.id); |
| 204 | + await expectCopiedPerReferenceRule(source, cloneId); |
| 205 | + }); |
| 206 | + |
| 207 | + it('a file field named in overrides takes the override, not the source file', async () => { |
| 208 | + const source = await sourceRecord('ovr'); |
| 209 | + const replacement = await upload('ovr-replacement.txt', 'replacement', 'text/plain'); |
| 210 | + const r = await call('POST', `/data/${OBJECT}/${source.id}/clone`, { |
| 211 | + overrides: { report: replacement, papers: null }, |
| 212 | + }); |
| 213 | + |
| 214 | + expect(r.status, JSON.stringify(r.body)).toBe(201); |
| 215 | + const cloneId = cloneIdOf(r.body); |
| 216 | + const copy = await stored(cloneId); |
| 217 | + // An unowned upload is claimed by the clone's slot as it stands — no copy. |
| 218 | + expect(copy.report).toBe(replacement); |
| 219 | + expect((await fileState(replacement)).owner).toEqual([OBJECT, cloneId, 'report']); |
| 220 | + expect(copy.papers ?? null).toBeNull(); |
| 221 | + // The field the overrides left alone still follows the copy rule. |
| 222 | + expect(isFileIdToken(copy.cover)).toBe(true); |
| 223 | + expect(copy.cover).not.toBe(source.files.cover); |
| 224 | + expect((await fileState(copy.cover)).owner).toEqual([OBJECT, cloneId, 'cover']); |
| 225 | + // The source is untouched. |
| 226 | + expect((await fileState(source.files.report)).owner).toEqual([OBJECT, source.id, 'report']); |
| 227 | + }); |
| 228 | +}); |
0 commit comments