Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .changeset/22274-option-visible-when-members.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
"@objectstack/lint": minor
"@objectstack/metadata-protocol": minor
---

fix(lint)!: `os build` and the object save door refuse a select option's `visibleWhen` that reads a member of `ctx` or `os` the server's option check never binds, such as `os.org.id`, `os.env` or `ctx.locale` (#22274)

Clause-②: no (narrowing: a select option's `visibleWhen` that reads an unbound member of a bound root is refused at build and at the object save door)

A select option's `visibleWhen` is a gate the server enforces on write. The option check binds `record`, `previous` and the acting user, as `current_user` and its ADR-0068 aliases `user`, `ctx.user` and `os.user`. Under `ctx` and `os` it binds the `user` member and nothing else: it passes no organization and no environment. The build already refused a root the option check does not bind, such as `parent`, but it judged `ctx` and `os` as whole roots. So an option predicate that read `os.org.id != ''`, `os.env == 'prod'` or `ctx.locale == 'en'` passed `os build` and the object save door with no finding. On every write that picked the option the predicate then faulted (`No such key: org`, `env` or `locale`), the server logged "the option's gate was NOT enforced on this write", and the value was admitted.

The build's expression rule (`validateStackExpressions`) now judges the members of `ctx` and `os` in an option's `visibleWhen`, in the same verdict that judges its roots. A member other than `user` is refused at `error` and located at the option (`object 'NAME' · field 'FIELD' option 'VALUE' visibleWhen`). The message names the member, says that the option check binds only the `user` member under that root, and gives the remedy. Every spelling of the read is judged the same: `os.org`, `os.?org`, `os['org']` and `has(os.org)`. The object save door runs the same pass, so its verdict is the build's finding: the same rule id (`expression-invalid`), location, message and hint.

**BREAKING — what moves for consumers.**

- `os build`, `os validate` and `os lint` refuse an option `visibleWhen` that reads a member of `ctx` or `os` other than `user`, such as `os.org.id`, `os.org.tier`, `os.env` or `ctx.locale`.
- An object write in publish mode that carries such an option answered 200. It now answers `422 INVALID_METADATA`, with an `expression-invalid` issue located at that option. This covers `PUT /api/v1/meta/object/:name` (and `saveMetaItem` in publish mode), the promotion of a draft (`POST /api/v1/meta/object/:name/publish`, `publishMetaItem`), and a package draft publish (`publishPackageDrafts`).

**Remedy.**

- For the caller's organization, compare `current_user.organizationId`, which the option check does bind: it holds the acting user's organization id, or `null` when the caller acts outside an organization. `os.org.id != ''` becomes `current_user.organizationId != null`. No other organization fact, such as its tier, is available to an option predicate; read a column the object declares instead.
- `os.env`, `ctx.locale` and any other member: rewrite the predicate against `record.FIELD`, `previous.FIELD`, or the acting user as `current_user`.
- Saving the object as a draft (`mode: 'draft'`) is still allowed, because drafts are never gated; publishing that draft is judged.

**Unchanged.**

- The server's option check is unchanged. It binds what it bound before, and an option predicate that faults is still logged and admitted. If the runtime comes to bind a member such as `os.org` for an option, this refusal is lifted for that member in the same change.
- The acting user is still accepted under all four ADR-0068 spellings (`current_user`, `user`, `ctx.user`, `os.user`), and so are its fields (`current_user.positions`, `ctx.user.id`) and a grant check such as `current_user.can('OBJECT', 'edit')`.
- The same members are still accepted where they are bound, such as `os.org.id` in a `formula` field's `expression`. The refusal is the option slot's alone.
- A computed key such as `os[name]` names no member, so it is not judged.
- Stored rows are not migrated, and they are not refused on read. An object stored before this change keeps loading until it is next saved, and that save is judged.
- `OS_ALLOW_UNLINTED_METADATA_WRITES=1` still turns a refusal into a logged write.
- Measured before crossing: the objects this repository ships carry 5 option predicates, all on `showcase_cascade`, which read `record` (four) and `current_user` (one). None reads `ctx` or `os`. That holds over every object in its `*.object.ts` files and the two `app-multi-package` sub-stacks, and over the example stacks as `defineStack` composes them. They have 0 refusals at the build and at the door, before this change and after it.
- No public export or signature moves. `validateStackExpressions(stack)` keeps its signature, and no registry entry changes.

<!-- adr-0087: not-required (no-migration-prescription) a refusal at `os build` and at the object save door of a select option's visibleWhen predicate that reads a member of ctx or os the server's option check does not bind: no authorable key, spelling, export or stored shape moves, and no stored row is read, rewritten or converted. A stored object whose option predicate is refused keeps loading until it is next saved, and the repair is the author's rewrite of the predicate against what the option check binds, which no ledger entry can derive. The other categories are closed on facts: the package publishes (not unpublished); no ADR-0087 id covers this verdict (not already-registered); and the change is a build and door verdict, not a declaration (not runtime-interface-only or type-surface-only). -->
139 changes: 138 additions & 1 deletion packages/lint/src/validate-expressions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { describe, it, expect } from 'vitest';
// a copy of it: "a future `SCOPE_ROOTS` member is covered for free" is the whole
// argument for the allowlist, and a hand-copied list would go green on exactly
// the root the rule never saw.
import { SCOPE_ROOTS } from '@objectstack/formula';
import { SCOPE_ROOTS, buildScope, ExpressionEngine } from '@objectstack/formula';
import { EVALUATED_EXPRESSION_SOURCE_REQUIRED, ExpressionInputSchema, ObjectStackSchema } from '@objectstack/spec';
import { FieldSchema, ObjectSchema, SelectOptionSchema } from '@objectstack/spec/data';
import { SharingRuleSchema } from '@objectstack/spec/security';
Expand Down Expand Up @@ -2088,6 +2088,143 @@ describe('validateStackExpressions (ADR-0032 build-time)', () => {
});
});

/**
* ── The members of `ctx` / `os` the option check never fills (#22274) ───
*
* `ctx` and `os` pass the root verdict above, but the option check fills
* each with its `user` member only: `evaluateOptionVisibility` hands the
* evaluator `{ record, previous, user, permissions }`, and `buildScope`
* mounts `os.org` / `os.env` only from an `org` / `env` in that context.
* Measured through the built `evaluateValidationRules` with an
* authenticated caller, `os.org.id`, `os.env` and `ctx.locale` each fault
* (`No such key`) and the value is admitted, so the build refuses them.
*/
describe('a per-option `visibleWhen` member of `ctx` / `os` the option check does not bind is refused (#22274)', () => {
const detail = (visibleWhen: unknown, extra: Record<string, unknown> = {}) => ({
objects: [
{
name: 'fx_line',
fields: {
x: { type: 'text' },
locale: { type: 'text' },
tier: {
type: 'select',
options: [{ label: 'Standard', value: 'standard' }, { label: 'Gold', value: 'gold', visibleWhen }],
},
...extra,
},
},
],
});
const WHERE = "object 'fx_line' · field 'tier' option 'gold' visibleWhen";
/**
* The context the option check hands the evaluator, mirrored from its one
* call (`evaluateOptionVisibility` in ObjectQL's `rule-validator.ts`): the
* merged record, `previous`, the acting user as the engine builds it (with
* the caller's organization id) and the permission map. Nothing else.
*/
const OPTION_CHECK_CONTEXT = {
record: { x: 'a' },
previous: { x: 'a' },
user: { id: 'u1', positions: ['member'], organizationId: 'org_1' },
permissions: {},
};

it.each([
["os.org.id != ''", '`os.org`'],
["os.env == 'prod'", '`os.env`'],
["ctx.locale == 'en'", '`ctx.locale`'],
])('⭐ refuses %s at error, located at the option, naming the member and what is bound', (body, path) => {
const issues = validateStackExpressions(detail(body));
expect(issues, JSON.stringify(issues, null, 2)).toHaveLength(1);
expect(issues[0]).toMatchObject({ where: WHERE, severity: 'error', source: body });
expect(issues[0]!.message).toContain(`option 'gold' on field 'tier' reads ${path}`);
expect(issues[0]!.message).toContain('the `user` member and nothing else');
});

it('⭐ the `os.org` refusal names the bound replacement, and that replacement passes and evaluates', () => {
expect(validateStackExpressions(detail("os.org.id != ''"))[0]!.message).toContain('`current_user.organizationId`');
const body = "current_user.organizationId == 'org_1'";
expect(validateStackExpressions(detail(body))).toEqual([]);
expect(ExpressionEngine.evaluate({ dialect: 'cel', source: body }, OPTION_CHECK_CONTEXT)).toEqual({ ok: true, value: true });
});

it('⭐ CONTROL — the acting user under every ADR-0068 spelling, `record`, `previous` and `can` pass', () => {
for (const body of [
"current_user.id != ''",
"os.user.id != ''",
"'org_admin' in ctx.user.positions",
"user.id != ''",
"record.x == 'a'",
"previous.x == 'a'",
"current_user.can('fx_line', 'edit')",
// A `record` member merely spelled like a refused one.
"record.locale == 'en'",
]) {
expect(validateStackExpressions(detail(body)), body).toEqual([]);
}
});

it('⭐ POSITIVE CONTROL — the same `os.org.id` on a `formula` field, which binds `os.org`, is not refused', () => {
const atFormula = detail("record.x == 'a'", { in_org: { type: 'formula', expression: "os.org.id != ''" } });
expect(validateStackExpressions(atFormula)).toEqual([]);
});

it('judges every member spelling as one read: optional, indexed and `has()`', () => {
for (const body of ['has(os.org)', 'os.?org.orValue({}) == {}', "os['org'].id != ''", "has(ctx.locale)"]) {
const issues = validateStackExpressions(detail(body));
expect(issues, body).toHaveLength(1);
expect(issues[0]!.where, body).toBe(WHERE);
}
});

it('one finding per option: an unbound root before a member, then members in `SCOPE_ROOTS` order', () => {
const withRoot = validateStackExpressions(detail("ctx.locale == 'en' && input.k == 1"));
expect(withRoot).toHaveLength(1);
expect(withRoot[0]!.message).toContain('reads `input`');
const twoMembers = validateStackExpressions(detail("ctx.locale == 'en' && os.env == 'prod'"));
expect(twoMembers).toHaveLength(1);
expect(twoMembers[0]!.message).toContain('reads `os.env`');
});

/**
* The allowlist is derived from the code, both ways. The real
* `buildScope` and evaluator, given the option check's context: every
* member they mount under `ctx` / `os` is accepted and evaluates, and
* every member they mount there only when ALSO given an organization and
* an environment is refused and faults. A member `buildScope` starts
* mounting from the option check's context, or one the verdict accepts
* that it no longer mounts, turns this red.
*/
it('the accepted members are exactly the ones `buildScope` mounts for the option check', () => {
const optionScope = buildScope(OPTION_CHECK_CONTEXT);
const fullScope = buildScope({ ...OPTION_CHECK_CONTEXT, org: { id: 'org_1' }, env: 'prod' });
const accepted: string[] = [];
const refused: string[] = [];
for (const root of ['ctx', 'os']) {
const mounted = Object.keys(optionScope[root] as Record<string, unknown>);
for (const member of Object.keys(fullScope[root] as Record<string, unknown>)) {
const body = `${root}.${member} != null`;
const issues = validateStackExpressions(detail(body));
const evaluated = ExpressionEngine.evaluate({ dialect: 'cel', source: body }, OPTION_CHECK_CONTEXT);
if (mounted.includes(member)) {
expect(issues, body).toEqual([]);
expect(evaluated.ok, body).toBe(true);
accepted.push(body);
} else {
expect(issues, body).toHaveLength(1);
expect(evaluated.ok, body).toBe(false);
refused.push(body);
}
}
}
expect({ accepted, refused }).toEqual({
accepted: ['ctx.user != null', 'os.user != null'],
refused: ['os.org != null', 'os.env != null'],
});
});
});

it('flags a bare-field sharing-rule condition', () => {
const issues = validateStackExpressions({
objects: [{ name: 'crm_account', fields: { region: { type: 'text' } } }],
Expand Down
Loading
Loading