Skip to content

Commit ba35dfd

Browse files
feat(service-storage): the uploader removes an attachment they uploaded, through an own-row door (#33322)
<!-- claude-projects-attribution: {"github_login":"os-elon-musk"} --> _Requested by **Elon** · [project thread](https://claude.ai/code/project/chan_01WedDzV26nniwxv7jC88B9D?thread=cmsg_01WedDzV26nniwxv7jC88B9DU5CHkeh2msc49m4dh6kwEt)_ Fixes #33010 Area-lease pilot #33059, area A3. Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:新增 `DELETE /api/v1/attachments/:id`,成员可删除自己上传的附件;成员授权(`storage_attachment_member`)仍只有读与建,不加删除位,数据门 `DELETE /data/sys_attachment/:id` 对成员仍是 403。 - 为什么改:成员挂错文件后无法撤回,只有管理员能删;维护者裁决(评论 6879388034)允许"仅限本人上传"的删除。 - 风险与回滚:新路由只认 `uploaded_by` 等于调用者的行,以调用者身份读、以系统上下文删;回滚即 revert 本 PR,数据门行为未改。 - 先看:`attachment-removal-routes.ts`(门的定义,所有者列 `uploaded_by`)、`storage-service-plugin.ts` 的 `mountAttachmentRemovalDoor`(挂载与调用方解析)、`member-attachment-baseline.dogfood.test.ts`(真栈钉子)。 - 两分钟验证:`pnpm --filter @objectstack/service-storage exec vitest run src/attachment-removal-routes.integration.test.ts`,预期全绿:本人删除 200 且行消失,他人 403 `PERMISSION_DENIED` 行仍在。 - 需要你做的:无,席位落地。 ## What changes Ruling (comment 6879388034 on the card): a member may delete an attachment they uploaded themselves, own uploads only, and the member grant carries no wider delete bit. - **The door.** `DELETE /api/v1/attachments/:id` is `@objectstack/core`'s own-row delete door (`own-row-delete-routes.ts`, the one the unreact and personal-view doors use) for `sys_attachment`, owner column `uploaded_by`. It resolves the caller through the platform's one request-to-context composition, reads the row AS the caller (object grant, organization wall, attachment read visibility), refuses a row whose `uploaded_by` names anyone else (`403 PERMISSION_DENIED`, the row stays), answers a row the caller cannot read as an unknown id (`404 RECORD_NOT_FOUND`), and only then removes it under a system context attributed to the caller, so the lifecycle tombstones the file it pointed at. `uploaded_by` is stamped from the session by the attach rule and is read-only after insert, so a caller cannot make another user's row their own. - **Mounted by `StorageServicePlugin`** at `kernel:ready`, beside the storage family and outside it (fixed route, its own ledger `attachment-removal-route-ledger.ts`, one `gap` row: the SDK has no method yet; the storage ledger's zero-gap ratchet is untouched). - **The member grant is unchanged**: read and create on `sys_attachment`, nothing else. The data door's delete still needs an explicit grant; an administrator keeps deleting any attachment there. A member who can edit the record but did not upload the attachment is refused by the door. - Docblocks of `attachment-member-grant.ts` and the write rule (`attachment-access-hooks.ts`) say where the uploader's removal is served. ## Tests Recorded at open as NOT MEASURED: local runs follow on this branch and are reported in the dev report (storage package suite, the new integration file, the ledger conformance, the dogfood attachment file, typecheck, eslint, the ADR-0087 registration check, one ablation of the mount). ## Acceptance notes - The Console's record Attachments panel still deletes through the data door and offers the button only to a holder of the delete grant; moving it to this door for the uploader's own rows is the console half (follow-up, not in this PR). - The host door `mountStorageRoutes` (cloud's per-environment kernels) does not carry this route: it calls the registration half `get`/`post`/`put` only. Carrying it there is a separate change. - The ADR-0090 D5 sentence that keeps delete off `everyone`-bound sets gets its matching line in a separate docs PR (governed surface), filed by the area thread. ## Verification See Tests. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_016WV4d1D3AzXvEhBbz79Pmi --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9499dcc commit ba35dfd

14 files changed

Lines changed: 684 additions & 11 deletions
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/service-storage': patch
3+
---
4+
5+
feat(service-storage): the uploader removes an attachment they uploaded, through an own-row door, with no delete bit on the member grant
6+
7+
Clause-②: yes (widening) — one route is added: `DELETE /api/v1/attachments/:id` removes a `sys_attachment` row whose `uploaded_by` is the caller, answering `{ id, deleted: true }` (200), and refuses `UNAUTHENTICATED` (401), `VALIDATION_ERROR` (400), `RECORD_NOT_FOUND` (404, an attachment the caller cannot read answers as one that does not exist) and `PERMISSION_DENIED` (403, any caller who is not the uploader, an administrator included). The package's exports are unchanged: `StorageServicePlugin` mounts the door wherever it mounts its routes on the kernel's HTTP server. Every existing answer is as before: the member grant `storage_attachment_member` still carries read and create only, so the data API's delete on `sys_attachment` stays refused to a member who holds only the baseline, and an administrator's delete there is unchanged.
8+
Metadata-protocol: none
9+
Skills-docs: `content/docs/permissions/attachments-access.mdx` documents the removal door, its refusals and its row in the enforcement summary. `skills/**` teaches nothing of deleting an attachment.
10+
11+
A member could attach a file to a record they edit, but could not take it back: the member grant carries no delete bit (ADR-0090 D5 keeps delete off every set the `everyone` position holds), so the data API refused their own upload `PERMISSION_DENIED`. The storage service now mounts the platform's own-row delete door for attachments beside its routes. It reads the row as the caller, so every attachment read rule applies first; it admits only when `uploaded_by` names the caller, which the attach rule stamps from the session and no caller can rewrite; and it removes the row on the caller's behalf, attributed to them, so the file behind it is released as on any delete. Removing someone else's attachment, as a parent editor or an administrator, still goes through the data API with an explicit delete grant.

‎content/docs/permissions/attachments-access.mdx‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,8 +55,11 @@ The set reaches no one else:
5555

5656
The set carries **no edit and no delete** (ADR-0090 D5: a set every member holds
5757
carries no delete bit). Editing or deleting attachments still needs an explicit
58-
grant on `sys_attachment` (see Delete below). An app can also grant read and
59-
create explicitly, as before; the baseline set adds nothing to such a grant.
58+
grant on `sys_attachment` (see Delete below). The one removal a member makes
59+
without it is of an attachment they uploaded themselves, through the storage
60+
service's removal door (see [The uploader's removal door](#the-uploaders-removal-door)).
61+
An app can also grant read and create explicitly, as before; the baseline set
62+
adds nothing to such a grant.
6063

6164
## The opt-in gate — `enable.files`
6265

@@ -203,13 +206,36 @@ floor binds still cannot edit another user's attachment row
203206
The member baseline (the `everyone` anchor: `member_default` and the storage
204207
service's `storage_attachment_member`) grants **read and create** on
205208
`sys_attachment` and **no edit or delete** (ADR-0090 D5 — delete is not a
206-
baseline right). Managing attachments — editing or deleting them — is therefore
207-
enabled by an ordinary, position-distributed permission set that grants edit
208-
and delete on `sys_attachment`. Until a member holds such a set, a delete is
209-
refused by RBAC (`PERMISSION_DENIED`) before the attachment-level gate above is
210-
even consulted.
209+
baseline right). Managing attachments — editing them, or deleting another
210+
user's — is therefore enabled by an ordinary, position-distributed permission
211+
set that grants edit and delete on `sys_attachment`. Until a member holds such
212+
a set, a delete through the data API is refused by RBAC (`PERMISSION_DENIED`)
213+
before the attachment-level gate above is even consulted. Withdrawing one's own
214+
upload needs no such set: it goes through the removal door below.
211215
</Callout>
212216

217+
### The uploader's removal door
218+
219+
`DELETE /api/v1/attachments/:id` removes one attachment **the caller uploaded**,
220+
with no delete grant on `sys_attachment`. The storage service mounts it beside
221+
its other routes, so wherever it serves uploads a member can withdraw them.
222+
223+
| Code | Status | When |
224+
| --- | --- | --- |
225+
| `UNAUTHENTICATED` | 401 | No session |
226+
| `VALIDATION_ERROR` | 400 | The request carries query parameters, or names no id: the door removes exactly one attachment, by its id in the path |
227+
| `RECORD_NOT_FOUND` | 404 | The caller cannot read the attachment (its parent record is out of their sight), or the id names none: the two answer alike |
228+
| `PERMISSION_DENIED` | 403 | The attachment's `uploaded_by` is not the caller — another member, a parent editor and an administrator alike. The row stays |
229+
230+
The door reads the attachment as the caller, so every read rule above applies
231+
first; it then admits only the uploader, and removes the row on their behalf,
232+
answering `{ id, deleted: true }` (200). The file behind it is released as on
233+
any delete. It grants nothing wider: the member baseline gains no delete bit,
234+
the data API's delete (`DELETE /api/v1/data/sys_attachment/:id`) stays refused
235+
to a member who holds only the baseline, and removing someone else's
236+
attachment — as a parent editor or an administrator — still goes through the
237+
data API with an explicit delete grant.
238+
213239
## Download — authenticated & parent-scoped
214240

215241
For **`scope: 'attachments'`** files (those created through the Attachments
@@ -295,7 +321,8 @@ can be shared across records). Reclamation is handled by the platform LifecycleS
295321
Every operation also needs its object grant on `sys_attachment`, refused
296322
`PERMISSION_DENIED` (403) without it. Read and create come with the member
297323
baseline (`storage_attachment_member`, where every attachment gate is
298-
present); edit and delete need an explicit grant.
324+
present); edit and delete need an explicit grant, except that the uploader
325+
withdraws their own attachment through the removal door without one.
299326

300327
| Operation | Requirement | Deny code |
301328
| --- | --- | --- |
@@ -304,6 +331,7 @@ present); edit and delete need an explicit grant.
304331
| Attach (create), re-point | a by-id update of the parent record by the caller would be admitted | `ATTACHMENT_PARENT_ACCESS` (403); `OBJECT_NOT_FOUND` (404) when the parent object is not registered |
305332
| List / read | inherits parent read visibility | *(filtered out)* |
306333
| Delete | uploader or parent editor (+ an explicit delete grant) | `ATTACHMENT_DELETE_DENIED` (403); `PERMISSION_DENIED` (403) when the parent is not readable or no delete grant is held |
334+
| Withdraw one's own upload (`DELETE /api/v1/attachments/:id`) | the row's `uploaded_by` is the caller, and the caller reads it; no delete grant | `UNAUTHENTICATED` (401) / `RECORD_NOT_FOUND` (404) / `PERMISSION_DENIED` (403) |
307335
| Download | session + owner-or-parent-read (attachments scope); session only for a file with no parent; none for `acl: 'public_read'` | `AUTH_REQUIRED` (401) / `ATTACHMENT_DOWNLOAD_DENIED` (403) |
308336

309337
## See also

‎packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@
2929
// service and the security plugin alone hands the grant out, with the opt-in
3030
// (`enable.files`) still refusing: every gate the grant relies on is the
3131
// storage service's own.
32+
//
33+
// The set carries no delete. The uploader withdraws an attachment they
34+
// uploaded through the storage service's removal door
35+
// (`DELETE /api/v1/attachments/:id`), which admits only the row's
36+
// `uploaded_by`: another member is refused even on a record they edit, the
37+
// data door's delete stays refused to a member, and an administrator still
38+
// deletes through it.
3239

3340
import { createHash, randomBytes } from 'node:crypto';
3441
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
@@ -354,6 +361,79 @@ describe('a member attaches to the records they edit and sees the files of the r
354361
expect([out.status, out.body.error?.code]).toEqual([403, 'FILES_DISABLED']);
355362
expect(await linksOn(nofilesId)).toEqual([]);
356363
});
364+
365+
// The uploader withdraws an attachment they uploaded (maintainer ruling
366+
// 6879388034): own uploads only, through the storage service's removal door
367+
// (`DELETE /api/v1/attachments/:id`), and with no delete bit on the member
368+
// grant — the data door's delete stays what it was, refused to a member and
369+
// served to an administrator.
370+
describe('the uploader withdraws their own attachment through the removal door, and nobody else\'s', () => {
371+
const OTHER_EMAIL = 'att-baseline-other-member@verify.test';
372+
let otherTok: string;
373+
374+
const row = (id: string) => ql.findOne('sys_attachment', { where: { id }, context: SYS });
375+
const answerOf = async (res: Response) => {
376+
const body = (await res.json()) as any;
377+
return { status: res.status, code: (body?.error?.code ?? body?.code) as string | undefined, body };
378+
};
379+
const removeAs = async (token: string, id: string) => answerOf(await stack.apiAs(token, 'DELETE', `/attachments/${id}`));
380+
const dataDeleteAs = async (token: string, id: string) => answerOf(await stack.apiAs(token, 'DELETE', `/data/sys_attachment/${id}`));
381+
/** The member attaches a file to their case, through the panel's door: the row's uploader is the member. */
382+
const memberAttachment = async () => {
383+
const out = await completeOnto(memberTok, 'att_case', caseId);
384+
expect(out.status, JSON.stringify(out.body)).toBe(200);
385+
const id = String(out.body.data.attachmentId);
386+
expect((await row(id))?.uploaded_by).toBe(memberId);
387+
return id;
388+
};
389+
390+
beforeAll(async () => {
391+
otherTok = await stack.signUp(OTHER_EMAIL, MEMBER_PASSWORD);
392+
});
393+
394+
it('the uploader removes their own attachment through the door: 200, and the row is gone', async () => {
395+
const id = await memberAttachment();
396+
const answer = await removeAs(memberTok, id);
397+
expect(answer.status, JSON.stringify(answer.body)).toBe(200);
398+
expect(answer.body).toEqual({ success: true, data: { id, deleted: true } });
399+
expect(await row(id)).toBeNull();
400+
});
401+
402+
it('CONTROL: the member grant gains no delete bit — the data door still refuses the uploader, and read and create are unchanged', async () => {
403+
const id = await memberAttachment();
404+
expect(await dataDeleteAs(memberTok, id)).toMatchObject({ status: 403, code: 'PERMISSION_DENIED' });
405+
expect(await row(id)).toMatchObject({ id, uploaded_by: memberId });
406+
const explain = async (operation: string) =>
407+
((await (await stack.apiAs(memberTok, 'GET', `/security/explain?object=sys_attachment&operation=${operation}`)).json()) as any).allowed;
408+
expect({ read: await explain('read'), create: await explain('create'), delete: await explain('delete') }).toEqual({
409+
read: true,
410+
create: true,
411+
delete: false,
412+
});
413+
expect((await stack.apiAs(memberTok, 'GET', `/data/sys_attachment/${id}`)).status).toBe(200);
414+
});
415+
416+
it('another member is refused on the door and on the data door, and the row stays — though they can edit the record it is on', async () => {
417+
const id = await memberAttachment();
418+
// The other member edits the case: their own attach to it is admitted.
419+
const theirs = await completeOnto(otherTok, 'att_case', caseId);
420+
expect(theirs.status, JSON.stringify(theirs.body)).toBe(200);
421+
422+
expect(await removeAs(otherTok, id)).toMatchObject({ status: 403, code: 'PERMISSION_DENIED' });
423+
expect(await dataDeleteAs(otherTok, id)).toMatchObject({ status: 403, code: 'PERMISSION_DENIED' });
424+
expect(await row(id)).toMatchObject({ id, uploaded_by: memberId });
425+
});
426+
427+
it('an administrator still deletes any attachment through the data door; the door grants them nothing more', async () => {
428+
const id = await memberAttachment();
429+
expect(await removeAs(adminTok, id)).toMatchObject({ status: 403, code: 'PERMISSION_DENIED' });
430+
expect(await row(id)).toMatchObject({ id, uploaded_by: memberId });
431+
432+
const answer = await dataDeleteAs(adminTok, id);
433+
expect(answer.status, JSON.stringify(answer.body)).toBeLessThan(300);
434+
expect(await row(id)).toBeNull();
435+
});
436+
});
357437
});
358438

359439
// A host that composes `sys_attachment` WITHOUT the storage service: the object

‎packages/qa/dogfood/test/route-ledger-live-mount-parity.dogfood.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ import { PRINT_ROUTE_LEDGER } from '../../../services/service-print/src/print-ro
7575
import { MESSAGING_ROUTE_LEDGER } from '../../../services/service-messaging/src/messaging-route-ledger.js';
7676
import { PERSONAL_VIEW_ROUTE_LEDGER } from '../../../plugins/plugin-auth/src/personal-view-route-ledger.js';
7777
import { SHARING_ROUTE_LEDGER } from '../../../plugins/plugin-sharing/src/sharing-route-ledger.js';
78+
import { ATTACHMENT_REMOVAL_ROUTE_LEDGER } from '../../../services/service-storage/src/attachment-removal-route-ledger.js';
7879

7980
/** One ledger row, normalized to a wire pattern this gate can probe. */
8081
interface LedgerRow {
@@ -117,6 +118,9 @@ function collectLedgerRows(): LedgerRow[] {
117118
for (const r of PERSONAL_VIEW_ROUTE_LEDGER) add('plugin-auth/personal-view-route-ledger.ts', r.route, '');
118119
// [#30209] SharingServicePlugin's shareable-objects list, on the IHttpServer port.
119120
for (const r of SHARING_ROUTE_LEDGER) add('plugin-sharing/sharing-route-ledger.ts', r.route, '');
121+
// StorageServicePlugin's own-row removal door for an attachment its caller
122+
// uploaded, on the IHttpServer port beside the storage family.
123+
for (const r of ATTACHMENT_REMOVAL_ROUTE_LEDGER) add('service-storage/attachment-removal-route-ledger.ts', r.route, '');
120124
return rows;
121125
}
122126

‎packages/services/service-storage/src/attachment-access-hooks.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ import { findReferenceableFile, unreadableFileMessage, type FileReferenceReadAut
7575
* reaches this handler through the `dispatchUnscopedMultiWrite`
7676
* whole-operation dispatch its registration declares (#9719) — the
7777
* per-row dispatch alone can never deliver the shape it refuses.
78+
* The uploader limb is also served without the object's delete grant, by
79+
* the removal door (`attachment-removal-routes.ts`, maintainer ruling
80+
* 6879388034): it reads the row as the caller, admits it only when
81+
* `uploaded_by` names the caller, and removes it under a system context
82+
* attributed to the caller, which this gate does not judge again. The
83+
* parent-editor limb has no such door.
7884
*
7985
* ## Parent EDIT — one question, four limbs
8086
*

‎packages/services/service-storage/src/attachment-member-grant.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,14 @@ import type { AttachmentLifecycleLogger } from './attachment-lifecycle.js';
3232
* What the set is, and is not:
3333
* - READ and CREATE on `sys_attachment`, nothing else. No edit and no delete:
3434
* a set every member holds through the `everyone` anchor carries no delete
35-
* bit (ADR-0090 D5). Managing attachments (detaching, re-pointing) stays an
36-
* explicit grant.
35+
* bit (ADR-0090 D5). Managing attachments (detaching another user's,
36+
* re-pointing) stays an explicit grant.
37+
* - The one removal a member makes without that grant is of an attachment
38+
* they uploaded themselves (maintainer ruling 6879388034), and it is no bit
39+
* of this set: the removal door (`DELETE /api/v1/attachments/:id`,
40+
* `attachment-removal-routes.ts`) admits a row whose `uploaded_by` names
41+
* the caller, and that row only. The data door's delete stays refused to a
42+
* member holding this set alone.
3743
* - It reaches the members of a deployment that declares a member baseline,
3844
* and no one else: an external member resolves its own baseline instead, an
3945
* agent principal's own leg resolves none, and a deployment that declares
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Attachment-removal route-ledger conformance — the package-local guard every
5+
* `*-route-ledger.ts` pairs with. `registerAttachmentRemovalRoutes` is a
6+
* standalone, synchronous function that calls `http.delete` and touches neither
7+
* argument before a request arrives, so a capturing mock `IHttpServer`
8+
* enumerates its real surface (the seam the comment-reaction, personal-view,
9+
* print, storage and settings ledgers use), and the two directions fail here by
10+
* name on every `pnpm test` of this package.
11+
*/
12+
13+
import { describe, it, expect, vi } from 'vitest';
14+
import { registerAttachmentRemovalRoutes } from './attachment-removal-routes.js';
15+
import { ATTACHMENT_REMOVAL_ROUTE_LEDGER } from './attachment-removal-route-ledger.js';
16+
17+
function createMockServer() {
18+
return {
19+
get: vi.fn(),
20+
post: vi.fn(),
21+
put: vi.fn(),
22+
delete: vi.fn(),
23+
patch: vi.fn(),
24+
use: vi.fn(),
25+
listen: vi.fn().mockResolvedValue(undefined),
26+
close: vi.fn().mockResolvedValue(undefined),
27+
};
28+
}
29+
30+
function enumerateRoutes(): Set<string> {
31+
const server = createMockServer();
32+
registerAttachmentRemovalRoutes(server as any, {} as any);
33+
const keys = new Set<string>();
34+
for (const verb of ['get', 'post', 'put', 'patch', 'delete'] as const) {
35+
for (const call of server[verb].mock.calls) keys.add(`${verb.toUpperCase()} ${call[0]}`);
36+
}
37+
return keys;
38+
}
39+
40+
const ledgerKeys = (): Set<string> => new Set(ATTACHMENT_REMOVAL_ROUTE_LEDGER.map((e) => e.route));
41+
42+
describe('attachment-removal route ledger ↔ registerAttachmentRemovalRoutes enumeration', () => {
43+
it('every mounted route has a ledger entry', () => {
44+
const ledger = ledgerKeys();
45+
const missing = [...enumerateRoutes()].filter((k) => !ledger.has(k));
46+
expect(missing, `attachment-removal routes with no ledger entry: ${missing.join(', ')}`).toEqual([]);
47+
});
48+
49+
it('every ledger entry is really mounted by the registrar', () => {
50+
const live = enumerateRoutes();
51+
const stale = [...ledgerKeys()].filter((k) => !live.has(k));
52+
expect(stale, `attachment-removal ledger entries the registrar no longer mounts: ${stale.join(', ')}`).toEqual([]);
53+
});
54+
55+
it('the ledger is compared against a real enumeration, not an empty one', () => {
56+
const live = enumerateRoutes();
57+
expect(live.size).toBeGreaterThan(0);
58+
expect(live.size).toBe(ledgerKeys().size);
59+
expect(ATTACHMENT_REMOVAL_ROUTE_LEDGER.every((e) => e.disposition === 'sdk' || (e.note ?? '').length > 0)).toBe(true);
60+
});
61+
});

0 commit comments

Comments
 (0)