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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1801,6 +1801,22 @@ Each item below is described in full under Security, Added, Changed or Fixed; th
sub-corpus of the api-contract conformance corpus, in the generated lane of all five ports, and by
`tph-sibling-credential` in `secret-fields/tph/` for the shared-column case.

- **A credential is never a generated grid column, initial sort or filter preset.** The generated
forms skipped a credential (a field that declares a `view.password`), but the grids did not: a
`layout.dataGrid` whose `@columns` named one, or that listed no `@columns` at all, emitted a column
for it in the TanStack `<Entity>.columns.tsx` and the Angular grid component, and a
`@defaultSortField` naming one became the grid's initial sort in the grid const, the grid hook and
the Angular grid config. The column is now dropped and the initial sort resolves to none, in every
generated tier; on a single-table (TPH) base's polymorphic grid a subtype-only column, and a column any
subtype marks as a credential, counts too. The runtime grid builder (`buildGrid()` in
`@metaobjectsdev/runtime-web`) drops a credential the same way, but it sees only the field's own
`view.password`, not a TPH sibling's mark, because it has no model root. A `@filter` preset over a credential, at any depth of its
`and` / `or`, now fails `meta gen` naming the layout and the field rather than being emitted, because
the server refuses that filter on every request and dropping the clause would silently change which
rows the grid shows: remove the clause. The agent UI page marks a credential as excluded from the form
and leaves it out of a grid's columns and default sort. Regenerate a grid over a model with a
credential; the generated `<Entity>.meta` descriptor is unchanged.

- **A numeric key is read only from canonical decimal text, in the TypeScript, Java and Python
ObjectManagers.** A path parameter or ref string for an integer, long, decimal, double or float
primary key went through the language's own number parser, which reads `0x1`, `1e0`, `0b1`, `+1`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ So the minimum to get a grid is a `layout.dataGrid` on the entity:
// ...fields...
{ "layout.dataGrid": {
"name": "default",
"@columns": ["name", "email", "createdAt"], // ordered; omit for every field
"@columns": ["name", "email", "createdAt"], // ordered; omit for every field but a credential
"@pageSize": 25,
"@defaultSortField": "createdAt",
"@defaultSortOrder": "desc"
Expand Down
14 changes: 12 additions & 2 deletions client/web/packages/runtime-web/src/grid-from-metadata.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
LAYOUT_DATA_GRID_ATTR_FILTERABLE,
FIELD_ATTR_SORTABLE_DEFAULT_ORDER,
DOC_ATTR_TITLE,
VIEW_SUBTYPE_PASSWORD,
} from "@metaobjectsdev/metadata/constants";
import type { GridConfig } from "./fetcher.js";

Expand Down Expand Up @@ -62,6 +63,13 @@ function firstView(field: MetaFieldRead): MetaViewRead | undefined {
return field.views()[0];
}

// A credential (a field declaring or inheriting `view.password`) is never a grid column or
// initial sort: the server's filter and sort allowlists refuse it. A TPH sibling subtype's
// credential mark on a shared column is not visible here without a model root.
function isCredential(field: MetaFieldRead): boolean {
return field.views().some((v) => v.subType === VIEW_SUBTYPE_PASSWORD);
}

function header(field: MetaFieldRead): string {
// DOC_ATTR_TITLE, not the literal "label". `@label` is registered by NO provider in
// any port — `@title` is the documentation commonAttr chartered as the display label
Expand Down Expand Up @@ -130,11 +138,13 @@ export function buildGrid(meta: MetaRead, gridName?: string): MetaGrid {

const columns: MetaColumn[] = names
.map((n) => fieldsByName.get(n))
.filter((f): f is MetaFieldRead => f !== undefined)
.filter((f): f is MetaFieldRead => f !== undefined && !isCredential(f))
.map((f) => ({ field: f.name, header: header(f), viewKind: viewKind(f) }));

const pageSizeAttr = layout?.attr(LAYOUT_DATA_GRID_ATTR_PAGE_SIZE);
const sortField = layout?.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD);
const sortFieldAttr = layout?.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD);
const sortFieldMeta = typeof sortFieldAttr === "string" ? fieldsByName.get(sortFieldAttr) : undefined;
const sortField = sortFieldMeta !== undefined && isCredential(sortFieldMeta) ? undefined : sortFieldAttr;
const sortOrder = layout?.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER);

const config: GridConfig = {
Expand Down
36 changes: 36 additions & 0 deletions client/web/packages/runtime-web/test/grid-from-metadata.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,4 +192,40 @@ describe("a declared @title reaches the column header", () => {
const { columns } = buildGrid(obj);
expect(columns.find((c) => c.field === "firstName")?.header).toBe("Given Name");
});
describe("credential fields (view.password)", () => {
const withPin = (grid: unknown) => SUBSCRIBER([
{ "field.string": { name: "pinHash", children: [{ "view.password": {} }] } },
grid,
]);

test("no @columns: credential is not a column", async () => {
const meta = await loadObject(withPin({ "layout.dataGrid": { name: "default" } }), "Subscriber");
const { columns } = buildGrid(meta);
expect(columns.map((c) => c.field)).toEqual(["id", "firstName", "subscribed", "status"]);
});

test("@columns naming the credential: credential is dropped", async () => {
const meta = await loadObject(
withPin({ "layout.dataGrid": { name: "default", "@columns": ["firstName", "pinHash"] } }),
"Subscriber",
);
expect(buildGrid(meta).columns.map((c) => c.field)).toEqual(["firstName"]);
});

test("@defaultSortField naming the credential gives no initial sort", async () => {
const meta = await loadObject(
withPin({ "layout.dataGrid": { name: "default", "@defaultSortField": "pinHash" } }),
"Subscriber",
);
expect(buildGrid(meta).config.defaultSort).toBeUndefined();
});

test("@defaultSortField naming an ordinary field still sorts", async () => {
const meta = await loadObject(
withPin({ "layout.dataGrid": { name: "default", "@defaultSortField": "firstName" } }),
"Subscriber",
);
expect(buildGrid(meta).config.defaultSort).toEqual({ field: "firstName", order: "asc" });
});
});
});
11 changes: 11 additions & 0 deletions docs/features/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,13 @@ set (`@mutability: writeOnce` on PATCH, the TPH discriminator, `@autoSet: onCrea
a generated edit form submits every field it was given, so a `400` would fail every save. A required field
that is also ignored can never be created through the API, so mark such a field optional.

The generated TypeScript client tier follows the same marks. The React and Angular forms render no control
for a credential or a `@formExclude` field. The TanStack and Angular grids never emit a column for a
credential, even when a `layout.dataGrid`'s `@columns` names it, and a `@defaultSortField` naming one gives
the grid no initial sort. A `@filter` preset over a credential fails `meta gen`, because the server would
refuse that filter on every request. On a single-table (TPH) base's grid, a column that any subtype marks as
a credential counts. The agent UI page (`agent/ui.md`) lists a grid's columns and default sort on the same terms.

The same rule covers every key a client never sets, in every port, on the plain and the TPH per-subtype
routes:

Expand Down Expand Up @@ -689,6 +696,10 @@ and its order leaks it): the allowlist is built without it, so a request that na
the allowlist does not hold (`400` `invalid_filter_field` or `invalid_sort`, naming the field). On a single-table (TPH) hierarchy the mark holds for the shared column: a column one subtype marks as a credential is on no allowlist of the base or of any subtype. To return a credential from a route, hand-write that
route; the generated one will not. Generated forms and the api docs omit both kinds of field as well.

**Known limit:** a credential (`view.password`) declared on a value-object member is not listed, checked or
stripped. Only an entity's top-level fields count, and stripping does not recurse into nested objects. Declare
credentials as top-level entity fields.

A served report is covered too. A report column is derived from its `@of` field, and a derived column keeps
that field's credential mark, so a report that groups by a credential (or takes its `min` or `max`) never
returns the column, its `report-export` output has no column for it, and it is neither filterable nor sortable
Expand Down
3 changes: 2 additions & 1 deletion docs/features/metadata-driven-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ What each component takes from the model:
| `view.textarea` `@rows` | | a textarea |
| `@required`, `@maxLength`, `validator.numeric` `@min`/`@max`, `@default` | | required marks, input limits, starting values |
| `relationship.*` with `@cardinality: many` | | the related rows listed beside the row being edited |
| `view.password`, `@formExclude` | | no control: no request may set the field |
| `view.password` | no column, and no first sort; a TPH sibling's credential mark on a shared column is not seen here | no control: no request may set the field |
| `@formExclude` | | no control: no request may set the field |

## Run it

Expand Down
3 changes: 2 additions & 1 deletion docs/ports/typescript-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,8 @@ on `Author`):
- `<entity><Grid>Columns` — array of TanStack `ColumnDef<T>`, one per
column key, each carrying `meta.view` (resolved from the field's
`view.*` child) for the renderer registry. Omit `@columns` and every
field on the entity becomes a column.
field on the entity becomes a column, except a credential (`view.password`), which is never a column
([api-contract.md](../features/api-contract.md#credentials-and-excluded-fields)).
- `<entity><Grid>Grid` — the config const carrying
`{ name, pageSize, defaultSort?, filterable }` — shape declared as
`GridConfig` in `@metaobjectsdev/runtime-web`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,11 @@ export interface GridDefaultSort {
* disagree: the endpoint returns the field's declared order while the grid that
* queries it renders the opposite.
*
* Returns undefined when the layout names no field — a grid with no initial sort.
* Returns undefined when the layout names no field — a grid with no initial sort — and when
* the field it names is a credential (`credentialFieldNames`): the sort allowlist never holds
* one, so the endpoint would refuse the grid's very first request, and the order of a secret
* leaks it. Pass `root` (the loaded model) so a column a TPH sibling declares as a credential
* counts too.
*
* The field lookup cannot miss on a LOADED model: `validateDataGridSortFields`
* refuses `@defaultSortField` naming a field the entity does not have
Expand All @@ -130,10 +134,12 @@ export interface GridDefaultSort {
export function resolveGridDefaultSort(
entity: MetaObject,
layout: MetaData,
root?: MetaRoot,
): GridDefaultSort | undefined {
// ADR-0039: resolving — a layout may inherit its grid attrs via extends.
const fieldName = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD);
if (typeof fieldName !== "string" || fieldName === "") return undefined;
if (credentialFieldNames(entity, root).has(fieldName)) return undefined;

const declared = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER);
if (declared === "asc" || declared === "desc") return { field: fieldName, order: declared };
Expand Down
8 changes: 7 additions & 1 deletion examples/showcase/codegen/templates/filter-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,11 @@ export interface GridDefaultSort {
* disagree: the endpoint returns the field's declared order while the grid that
* queries it renders the opposite.
*
* Returns undefined when the layout names no field — a grid with no initial sort.
* Returns undefined when the layout names no field — a grid with no initial sort — and when
* the field it names is a credential (`credentialFieldNames`): the sort allowlist never holds
* one, so the endpoint would refuse the grid's very first request, and the order of a secret
* leaks it. Pass `root` (the loaded model) so a column a TPH sibling declares as a credential
* counts too.
*
* The field lookup cannot miss on a LOADED model: `validateDataGridSortFields`
* refuses `@defaultSortField` naming a field the entity does not have
Expand All @@ -130,10 +134,12 @@ export interface GridDefaultSort {
export function resolveGridDefaultSort(
entity: MetaObject,
layout: MetaData,
root?: MetaRoot,
): GridDefaultSort | undefined {
// ADR-0039: resolving — a layout may inherit its grid attrs via extends.
const fieldName = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_FIELD);
if (typeof fieldName !== "string" || fieldName === "") return undefined;
if (credentialFieldNames(entity, root).has(fieldName)) return undefined;

const declared = layout.attr(LAYOUT_DATA_GRID_ATTR_DEFAULT_SORT_ORDER);
if (declared === "asc" || declared === "desc") return { field: fieldName, order: declared };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ So the minimum to get a grid is a `layout.dataGrid` on the entity:
// ...fields...
{ "layout.dataGrid": {
"name": "default",
"@columns": ["name", "email", "createdAt"], // ordered; omit for every field
"@columns": ["name", "email", "createdAt"], // ordered; omit for every field but a credential
"@pageSize": 25,
"@defaultSortField": "createdAt",
"@defaultSortOrder": "desc"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ So the minimum to get a grid is a `layout.dataGrid` on the entity:
// ...fields...
{ "layout.dataGrid": {
"name": "default",
"@columns": ["name", "email", "createdAt"], // ordered; omit for every field
"@columns": ["name", "email", "createdAt"], // ordered; omit for every field but a credential
"@pageSize": 25,
"@defaultSortField": "createdAt",
"@defaultSortOrder": "desc"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
// header + meta.view) but in Angular-native shape (EntityGridColumn[]).

import { code, imp } from "@metaobjectsdev/codegen-ts";
import type { MetaField, MetaObject } from "@metaobjectsdev/metadata";
import type { MetaField, MetaObject, MetaRoot } from "@metaobjectsdev/metadata";
import {
LAYOUT_SUBTYPE_DATA_GRID,
LAYOUT_DATA_GRID_ATTR_PAGE_SIZE,
Expand All @@ -20,6 +20,7 @@ import {
viewForContext,
VIEW_CONTEXT_GRID,
resolveGridDefaultSort,
credentialFieldNames,
type GridDefaultSort,
effectivePackage,
} from "@metaobjectsdev/codegen-ts";
Expand Down Expand Up @@ -70,8 +71,9 @@ function fieldLabel(field: MetaField): string {
return humanize(field.name);
}

function extractGrids(entity: MetaObject): GridSpec[] {
function extractGrids(entity: MetaObject, root: MetaRoot): GridSpec[] {
const fieldsByName = new Map(entity.fields().map((f) => [f.name, f] as const));
const credentials = credentialFieldNames(entity, root);
const out: GridSpec[] = [];
for (const layout of entity.layouts()) {
if (layout.subType !== LAYOUT_SUBTYPE_DATA_GRID) continue;
Expand All @@ -83,14 +85,18 @@ function extractGrids(entity: MetaObject): GridSpec[] {
const columns: ColumnSpec[] = columnNames.flatMap((name) => {
const f = fieldsByName.get(name);
if (!f) return [];
// A credential (a `view.password` on any declaration of the column) is never a column,
// even when @columns names it — the same rule as the TanStack tier and the generated forms.
if (credentials.has(name)) return [];
const viewKind = fieldViewKind(f);
// #355 — `view.hidden` means "not rendered"; drop the column rather than emit one
// that prints the value. Same rule as the TanStack tier, which renders the same
// surface (see columns-file.ts for the full reasoning).
if (viewKind === VIEW_SUBTYPE_HIDDEN) return [];
return [{ id: name, header: fieldLabel(f), viewKind }];
});
const defaultSort = resolveGridDefaultSort(entity, layout);
// A @defaultSortField naming a credential resolves to no initial sort.
const defaultSort = resolveGridDefaultSort(entity, layout, root);
const grid: GridSpec = {
name: layout.name || "default",
pageSize: (layout.attr(LAYOUT_DATA_GRID_ATTR_PAGE_SIZE) as number | undefined) ?? 25,
Expand All @@ -110,7 +116,7 @@ function renderColumnLiteral(col: ColumnSpec): string {
export function renderGridFile(entity: MetaObject, ctx: RenderContext): string {
const entityName = entity.name;
const lcEntity = entityName.charAt(0).toLowerCase() + entityName.slice(1);
const grids = extractGrids(entity);
const grids = extractGrids(entity, ctx.loadedRoot);

const ComponentSym = imp("Component@@angular/core");
const signalSym = imp("signal@@angular/core");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// A credential (a field that declares `view.password`) is never an Angular grid column or
// initial sort — the same rule as the TanStack tier and the generated forms. The server never
// returns its value and keeps it off the sort and filter allowlists.

import { describe, test, expect } from "bun:test";
import { angularGridFile } from "../src/index.js";
import { makeRenderContext, buildPkMap, buildRelationMap } from "@metaobjectsdev/codegen-ts";
import type { GenContext } from "@metaobjectsdev/codegen-ts";
import { MetaDataLoader, InMemoryStringSource } from "@metaobjectsdev/metadata";

async function render(grid: Record<string, unknown>): Promise<string> {
const json = JSON.stringify({
"metadata.root": {
children: [{
"object.entity": {
name: "Account",
children: [
{ "source.rdb": { "@table": "account" } },
{ "field.long": { name: "id" } },
{ "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } },
{ "field.string": { name: "email", "@filterable": true } },
{
"field.string": {
name: "pinHash", "@filterable": true, "@sortable": true,
children: [{ "view.password": {} }],
},
},
{ "layout.dataGrid": { name: "default", ...grid } },
],
},
}],
},
});
const { root, errors } = await new MetaDataLoader({ strict: true })
.load([new InMemoryStringSource(json, { id: "account.json" })]);
expect(errors.map((e) => e.message)).toEqual([]);
const renderContext = makeRenderContext({
dialect: "sqlite", loadedRoot: root, outDir: "/tmp",
dbImport: "../db", extStyle: "none",
pkMap: buildPkMap(root), relationMap: buildRelationMap(root),
});
const ctx: GenContext = {
entities: root.objects(),
loadedRoot: root,
matches: () => true,
config: { outDir: "/tmp", extStyle: "none", dbImport: "../db", dialect: "sqlite" },
renderContext,
warn: () => {},
};
const files = await angularGridFile().generate(ctx);
const file = files.find((f) => f.path.includes("Account"));
if (file === undefined) throw new Error(`no grid emitted; got ${files.map((f) => f.path).join(", ")}`);
return file.content;
}

describe("a credential is not an Angular grid column", () => {
test("dropped when @columns names it explicitly", async () => {
const out = await render({ "@columns": ["email", "pinHash"] });
expect(out).toContain('id: "email"');
expect(out).not.toContain("pinHash");
});

test("dropped when @columns is omitted and every field becomes a column", async () => {
const out = await render({});
expect(out).toContain('id: "email"');
expect(out).not.toContain("pinHash");
});

test("a @defaultSortField naming it gives no initial sort", async () => {
const out = await render({ "@columns": ["email"], "@defaultSortField": "pinHash" });
expect(out).not.toContain("defaultSort");
expect(out).not.toContain("pinHash");
});
});
2 changes: 1 addition & 1 deletion server/typescript/packages/codegen-ts-tanstack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ TanStack codegen for MetaObjects. Provides `tanstackQuery()` (per-entity `<Entit
{ "layout.dataGrid": { "name": "default", "@columns": ["name", "email"] } }
```

`@columns` is an ordered list; omit it to get every field. Each `layout.dataGrid` yields a `<entity><Grid>Columns` + `<entity><Grid>Grid` pair from `tanstackGrid()` and a `use<Entity><Grid>Grid()` from `tanstackGridHook()`.
`@columns` is an ordered list; omit it to get every field except a credential (`view.password`), which is never a column. Each `layout.dataGrid` yields a `<entity><Grid>Columns` + `<entity><Grid>Grid` pair from `tanstackGrid()` and a `use<Entity><Grid>Grid()` from `tanstackGridHook()`.

### M:N collection hooks (FR-018)

Expand Down
Loading
Loading