Skip to content
Merged
13 changes: 13 additions & 0 deletions .changeset/20338-draft-read-builder-gate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
"@objectstack/rest": patch
"@objectstack/runtime": patch
---

**Pending metadata drafts are now served only to a caller with an authoring capability — the check `GET /api/v1/meta/_drafts` already made.** A pending draft is unpublished authoring work. Until now, every door that reads one, other than `/meta/_drafts`, served it to any signed-in caller who could open the item. The draft access that the `previewDrafts` / `state` request declarations, ADR-0106 D4 and ADR-0037 described as admin-gated upstream is now gated.

Clause-②: no

- **The doors:** `GET /api/v1/meta/:type/:name?state=draft` and `?preview=draft`, `GET /api/v1/meta/:type?preview=draft`, and `POST /api/v1/analytics/dataset/query` with `previewDrafts: true` or `?preview=draft` on `RestServer`, plus the runtime dispatcher's `/meta` item and list `?preview=draft`.
- **Who may read drafts:** a system context, or a caller holding `studio.access`, `setup.access` or `manage_metadata`. This is the same predicate `/meta/_drafts` asks, not a second rule.
- **Everyone else gets the read as if the draft switch were absent.** They receive the published version, pruned for them as the plain read prunes it. For a name that has nothing published, they receive that door's own absence answer: `404` on the item read, `404 NOT_FOUND` for a dataset by name, and the item simply missing from a list. The answer is byte-identical to the plain read, so it does not reveal whether a draft exists. For example, `?state=draft` on an app with no pending draft answers such a caller with the published app, not `404 NO_DRAFT`. A dataset preview run by such a caller uses live rows, never a pending seed draft's rows.
- **Unchanged:** callers with an authoring capability read exactly what they read before. Whoever may save an app reads its `?state=draft` whole, and everyone else pruned per caller. `/meta/_drafts` still answers `403` to a caller without the capability, because it lists drafts and has no published answer to fall back to. `/diff` and `/history` are not changed by this release.
7 changes: 6 additions & 1 deletion content/docs/ui/apps.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,12 @@ them, left out as the single-app read leaves them out, on every layer, in the
draft, and on both sides of a diff. These doors apply no per-deployment gate:
an entry whose `requiresService` names a service this deployment lacks is part
of the stored version, for every caller. The exemption lifts no whole refusal:
an app an author may not open is refused on these doors too.
an app an author may not open is refused on these doors too. Reading a
*pending* draft at all — `?state=draft`, and the `?preview=draft` preview —
needs an authoring capability (`studio.access`, `setup.access` or
`manage_metadata`: the check `GET /api/v1/meta/_drafts` makes). A caller
without one is answered as if the parameter were absent: the published app,
or `404` for an app that has never been published.

`visible` did **not** move server-side with them, and that asymmetry is
deliberate: CEL is evaluated in the browser because server-side evaluation needs
Expand Down
61 changes: 59 additions & 2 deletions packages/rest/src/meta-alternate-door-read-gates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@
* The exemption is a CALLER property, honoured by these four doors and by
* no other: the rendered plain read (`?preview=draft` included) and
* `/published` still prune for an author.
*
* [#20338] The draft door serves the draft only to a caller who may read
* drafts at all — the authoring capability `GET /meta/_drafts` asks
* (`readsDrafts` below). Anyone else is never handed one: `?state=draft`
* answers them what the plain read answers them, byte for byte.
* - **`/history` and `/audit` serve events, never a body**: they refuse where
* the plain read refuses the item whole, and otherwise serve the events.
* - **`/references`** is declared exempt: it serves the identities of OTHER
Expand Down Expand Up @@ -164,19 +169,27 @@ interface Caller {
* call a caller an author the save door refuses, or the reverse.
*/
savesApps: boolean;
/**
* [#20338] Does `GET /meta/_drafts` admit this caller? DECLARED here and
* checked against that door below: every draft door asks the predicate it
* asks, so a caller it refuses is never served a draft by `?state=draft`.
*/
readsDrafts: boolean;
}
const CALLERS: Record<'reader' | 'non-reader' | 'author' | 'anonymous', Caller> = {
reader: {
ctx: { userId: 'u_reader', systemPermissions: ['finance.access', 'payroll.access', 'studio.access'] },
holdings: ['crm_admin'],
readableFields: ['amount', 'secret_margin'],
savesApps: false,
readsDrafts: true,
},
'non-reader': {
ctx: { userId: 'u_member', systemPermissions: [] },
holdings: [],
readableFields: ['amount'],
savesApps: false,
readsDrafts: false,
},
// An author the plain read serves only PART of `crm`: they may write
// metadata, but hold neither `finance.access` nor `crm_admin`. And no
Expand All @@ -187,8 +200,9 @@ const CALLERS: Record<'reader' | 'non-reader' | 'author' | 'anonymous', Caller>
holdings: [],
readableFields: ['amount'],
savesApps: true,
readsDrafts: true,
},
anonymous: { holdings: [], readableFields: [], savesApps: false },
anonymous: { holdings: [], readableFields: [], savesApps: false, readsDrafts: false },
};
type CallerName = keyof typeof CALLERS;

Expand Down Expand Up @@ -269,6 +283,8 @@ function setup(who: CallerName | Caller) {
}),
// The save door's protocol call — reached only past its admission.
saveMetaItem: vi.fn(async ({ type, name }: any) => ({ success: true, type: singular(type), name })),
// [#20338] `GET /meta/_drafts` — reached only past its admission.
listDrafts: vi.fn(async () => ({ items: [] })),
findReferencesToMeta: vi.fn(async () => ({ references: [] })),
findData: vi.fn().mockResolvedValue([]),
};
Expand Down Expand Up @@ -311,6 +327,15 @@ async function save(rest: any, type: string, name: string, item: any) {
return res;
}

/** [#20338] `GET /meta/_drafts` — the door whose admission IS `readsDrafts`. */
async function listDrafts(rest: any) {
const route = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === `${META}/_drafts`);
if (!route) throw new Error(`GET ${META}/_drafts is not registered`);
const res = makeRes();
await route.handler({ method: 'GET', path: `${META}/_drafts`, params: {}, query: {}, body: {}, headers: {} }, res);
return res;
}

/** The ADR-0112 minimum: the status and the machine code, never the prose. */
const envelope = (res: any) => ({ status: res.statusCode, code: res.body?.code ?? res.body?.error?.code });
const text = (res: any): string => JSON.stringify(res.body ?? null);
Expand Down Expand Up @@ -581,6 +606,24 @@ describe(`[#20156 · #20290] ruling ${AUTHOR_EXEMPTION.ruling} — the author ex
}
}
});

it('[#20338] `readsDrafts` is exactly who `GET /meta/_drafts` admits — the predicate every draft door asks', async () => {
for (const callerName of Object.keys(CALLERS) as CallerName[]) {
const { rest, protocol } = setup(callerName);
const res = await listDrafts(rest);
if (CALLERS[callerName].readsDrafts) {
expect(res.statusCode, callerName).toBe(200);
expect(protocol.listDrafts, callerName).toHaveBeenCalledTimes(1);
} else {
expect(envelope(res), callerName).toEqual(
CALLERS[callerName].ctx
? { status: 403, code: 'FORBIDDEN' }
: { status: 401, code: 'UNAUTHENTICATED' },
);
expect(protocol.listDrafts, callerName).not.toHaveBeenCalled();
}
}
});
});

describe(`[#20156] every alternate door answers what the plain read answers, or refuses — save the author exemption of ruling ${AUTHOR_EXEMPTION.ruling}`, () => {
Expand All @@ -601,11 +644,22 @@ describe(`[#20156] every alternate door answers what the plain read answers, or
const res = await drive(rest, door.suffix, subject.type, subject.name, door.query);
const stored = find(subject.type, subject.name);
if (door.serves === 'draft' && CALLERS[callerName].ctx) {
const asked = protocol.getMetaItem.mock.calls.map(([r]: any[]) => r?.state);
if (!CALLERS[callerName].readsDrafts) {
// [#20338] A caller who may not read drafts is
// never handed one: the protocol is not asked for
// the draft row, and the door answers what the
// plain read answers them, byte for byte.
expect(asked).not.toContain('draft');
expect(envelope(res)).toEqual(envelope(plain));
expect(res.body).toEqual(plain.body);
return;
}
// [#20290] The cell measured the draft branch: the
// protocol was asked for the draft row. (An anonymous
// caller is refused by the `/meta` auth gate before
// any read, on every door alike.)
expect(protocol.getMetaItem.mock.calls.map(([r]: any[]) => r?.state)).toContain('draft');
expect(asked).toContain('draft');
}

if (exempt) {
Expand Down Expand Up @@ -759,6 +813,9 @@ describe('[#20156] edges', () => {
holdings: [],
readableFields: ['amount'],
savesApps: false,
// [#20338] No authoring capability either, so `?state=draft`
// serves them the published app — pruned, as below.
readsDrafts: false,
};
const { rest, protocol } = setup(presenter);

Expand Down
13 changes: 9 additions & 4 deletions packages/rest/src/meta-draft-read-author-exemption.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,13 @@ const CALLERS = {
financeAuthor: { userId: 'u_finance_author', systemPermissions: ['manage_metadata', 'finance.access'] },
/** The card's author: may save the app, but holds no `finance.access`. */
author: { userId: 'u_author', systemPermissions: ['manage_metadata'] },
/** May open the app, may not save it. */
member: { userId: 'u_member', systemPermissions: [] },
/**
* May open the app and read drafts (a Studio builder), may not save it.
* [#20338] A caller who may not read drafts at all is never served one —
* they read the published app (`meta-draft-read-builder-gate.test.ts`) — so
* the "may not save" control is a caller who may still read the draft.
*/
builder: { userId: 'u_builder', systemPermissions: ['studio.access'] },
} as const;
type CallerName = keyof typeof CALLERS;

Expand Down Expand Up @@ -189,14 +194,14 @@ describe('[#20290] the draft read serves an app author the stored draft whole',

it('a caller who may not save the app reads the draft pruned per caller (the control) — no per-deployment gate either, as on /layers', async () => {
const { call } = await boot();
const res = await call('member', 'GET', '', 'atlas', { state: 'draft' });
const res = await call('builder', 'GET', '', 'atlas', { state: 'draft' });

expect(res.statusCode).toBe(200);
expect(res.body?.item?.label).toBe('Atlas (draft)');
expect(navIds(res.body?.item)).toEqual(['nav_leads', 'nav_org_directory']);
expect(JSON.stringify(res.body)).not.toContain('nav_finance');
// The same per-caller answer the stored-version doors give them.
const layers = await call('member', 'GET', '/layers', 'atlas');
const layers = await call('builder', 'GET', '/layers', 'atlas');
expect(navIds(layers.body?.effective)).toEqual(['nav_leads', 'nav_org_directory']);
}, 60_000);

Expand Down
Loading
Loading