From 13205e0d620c76040d50045cf93b92701ccec148 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:11:34 -0500 Subject: [PATCH 1/3] fix(csharp): strip credentials from the {rows,total} envelope under any key spelling; declare a shared enum no sibling entry declares B1: the credential-omitting result found the envelope's rows with env["rows"], which a strict host (PropertyNameCaseInsensitive = false) misses when an upper-case policy writes ROWS, so the rows went out unstripped. One helper, SerializerKeys.StripBody, now serves the generated CredentialOmittingResult and ReportExportHttp.Json: it reads the rows key from the envelope's own serializer contract and refuses (throws) when the key or the array cannot be found. SnakeCaseUpper and KebabCaseUpper strict-host variants join the live host test and the SerializerKeys unit tests. B2: a narrowed EntityGenerator entry skips a shared enum only when another EntityGenerator entry of the same run accepts the enum's home; a single narrowed entry declares it, so its output compiles on its own. L1: origin.function, @union, @unionAll, @grain and @grainOrdinal carry implementedIn ["typescript", "csharp"] (registry manifest, embeds and the metamodel-docs fixture regenerated). L2: with a rename beyond case, the C# sort allowlist accepts the field name as well as the resolved property name. L7: the C# sized @dbColumnType pattern ends at \z, so a trailing newline is refused. CHANGELOG: the credential entry names exactly what is stripped, the G2 and sort entries match the new behaviour, and a computed field reading its own name is listed as refused at load. --- CHANGELOG.md | 41 ++++++---- .../metamodel-docs/expected/types/origin.md | 2 + .../expected-registry.json | 20 +++++ .../GeneratorIncludeTests.cs | 30 +++++++- .../Golden/pre-rc22-propname/GizmoRoutes.g.cs | 5 +- .../pre-rc22-propname/VehicleRoutes.g.cs | 5 +- .../PackageKeyedOutputTests.cs | 19 +++-- .../PropertyNamingEmitSitesTests.cs | 12 ++- .../SerializerKeysTests.cs | 71 +++++++++++++++++ .../Generators/EntityGenerator.cs | 18 ++++- .../Generators/RoutesGenerator.cs | 66 +++++++++------- .../Runtime/ReportExportHttp.cs | 5 +- .../Runtime/SerializerKeys.cs | 36 +++++++++ .../R6Plan2LoaderTests.cs | 14 ++++ .../ApiContractCredentialHostVariantsTest.cs | 76 ++++++++++++------- .../MetaObjects/Persistence/Db/DbConstants.cs | 2 +- .../MetaObjects/SpecMetamodel/object.json | 8 +- .../MetaObjects/SpecMetamodel/origin.json | 1 + .../metaobjects/spec_metamodel/object.json | 8 +- .../metaobjects/spec_metamodel/origin.json | 1 + .../core/object/object-definition.embedded.ts | 16 ++++ .../origin/origin-definition.embedded.ts | 4 + spec/metamodel/object.json | 8 +- spec/metamodel/origin.json | 1 + 24 files changed, 359 insertions(+), 110 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2667ad5c34..bc3b11affc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,13 +184,20 @@ Each item below is described in full under Security, Added, Changed or Fixed; th the same way under any policy. Only single-word credentials, or a host with the default camelCase policy and no rename, were safe. 1.3.0 fixes it: the omit list and the PATCH and PUT key lookup read the key from the serializer's own contract (`JsonSerializerOptions.GetTypeInfo`), - so a naming policy, a rename or an attribute cannot escape them. Stripping **fails closed**: when - the contract cannot be read (a custom converter for the row type, a custom type-info resolver or a + so a naming policy, a rename or an attribute cannot escape them. What is stripped, exactly: each + top-level credential property of the entity (and, on a TPH route, of every subtype), under the key + the host's serializer writes for it, from the single row of a read, create, PATCH or PUT response, + from each row of a list or M:N response, from each row under the `rows` key of a `?withCount=` + `{ rows, total }` envelope, and from each row of the JSON report export. The envelope's own + `rows` key is read from the same contract, so an upper-case policy (`ROWS`) on a host that sets + `PropertyNameCaseInsensitive = false` is stripped too. A key in those rows that spells the + credential ignoring case, `_` and `-` is also removed. Stripping **fails closed**: when the + contract cannot be read (a custom converter for the row type, a custom type-info resolver or a modifier that leaves a property without its reflection member, a contract that lacks the credential), the generated route mapping throws at startup, and a response that reaches - `CredentialOmittingResult` anyway is refused with an exception naming the type and the credential - property (never a value), instead of being sent unstripped. A key that spells the credential - ignoring case, `_` and `-` is also removed. A host that sets a custom `TypeInfoResolver` or a + `CredentialOmittingResult` anyway (or an envelope whose `rows` key or array cannot be found) is + refused with an exception naming the type and the credential property (never a value), instead + of being sent unstripped. A host that sets a custom `TypeInfoResolver` or a source-generated `JsonSerializerContext` must give the entity properties their reflection member (the default reflection resolver does), or the app will not start. The write side of the released 1.2.0, 1.2.2 and 1.2.3 was not exploitable: a PATCH or PUT body key that missed the deny list also missed @@ -294,7 +301,9 @@ Each item below is described in full under Security, Added, Changed or Fixed; th - the loaders refuse what a view cannot lower: a `now` whose value is not an ISO-8601 duration or whose `startOf` is not day, week or month (`error-origin-computed-now-bad-duration`); a searched `case` whose `when` is not boolean (`error-origin-computed-case-non-boolean-when`); - computed fields that refer to each other in a cycle (`error-origin-computed-cycle`); and a + computed fields that refer to each other in a cycle (`error-origin-computed-cycle`), and a + computed field that reads its own name, which loaded before and is now `ERR_INVALID_ORIGIN` at + load (it never lowered to valid SQL; `meta gen` recursed on it until the stack ran out); and a malformed relative date in a view host's `@filter` (`error-relative-date-view-host-malformed`), or one on a field that is not a `field.date` or `field.timestamp`, where a projection's key names its own field and an origin's names a field of its `@of` entity or `@via` terminal @@ -1396,13 +1405,14 @@ Each item below is described in full under Security, Added, Changed or Fixed; th metadata package builds its sandbox under `$DEV_SCRATCH` (the system temp directory when unset) and stops its test runners with it. Contributor steps are in [CONTRIBUTING.md](CONTRIBUTING.md). -- **Behaviour change, C#: with a property rename beyond case, the accepted `?sort=` key is the - resolved property name (rc.22).** The sort allowlist, `@sortableDefaultOrder` keys and the +- **Fix, C#: with a property rename beyond case, `?sort=` accepts the field name and the resolved + property name (rc.22).** The sort allowlist, `@sortableDefaultOrder` keys and the `EF.Property` names carry the resolved name (EF matches the model's property name, so before - this any rename made a sort return 500). A project with no resolver, or one whose rename differs - only in case, is unchanged (the key is matched case-insensitively). With `ownerRef` spelled - `OwnerKey`, `?sort=ownerRef` becomes `400 invalid_sort` and `?sort=OwnerKey` is accepted. - `?filter[]` keeps the field name. + this any rename made a sort return 500). With a rename beyond case the allowlist also accepts the + field name, the key `?filter[]` takes, so a client built from the metadata's field names + sorts and filters with the same key. A project with no resolver, or one whose rename differs only + in case, is unchanged (the key is matched case-insensitively). With `ownerRef` spelled `OwnerKey`, + `?sort=ownerRef` and `?sort=OwnerKey` both sort by it. - **Behaviour change, C#: a `PropertyName` hook that disagrees with `GenConfig.PropertyNaming` is refused (rc.22).** `EntityGenerator.PropertyName` and `DbContextGenerator.PropertyName` default to @@ -2188,9 +2198,10 @@ Each item below is described in full under Security, Added, Changed or Fixed; th entry splitting the model declared all of them (`CS0101` where two outputs build together). A narrowed entry now declares only the enums used by the objects it accepts and the value objects it emits beyond them, and an enum several entries use is declared by one: the entry that emits its - first consumer by resolution key. Each entry reaches that answer from the model alone, in its own - run. An enum whose first consumer no entry emits is declared by none; give that object an entry, - or use an un-narrowed entry, which declares every enum as before. Placing an enum in a project of + first consumer by resolution key. Each entry reaches that answer in its own run, from the model and + the run's entry list: an entry leaves the enum to another only when another `EntityGenerator` + entry of the same run accepts that first consumer, and declares it itself otherwise, so a single + narrowed entry still builds on its own. An un-narrowed entry declares every enum, as before. Placing an enum in a project of its own choosing is G3, not built. - **Fix, TypeScript docs: an identity reference's target links to its page (G4).** The Identity diff --git a/fixtures/metamodel-docs/expected/types/origin.md b/fixtures/metamodel-docs/expected/types/origin.md index 04485083ae..8e0708bb83 100644 --- a/fixtures/metamodel-docs/expected/types/origin.md +++ b/fixtures/metamodel-docs/expected/types/origin.md @@ -98,6 +98,8 @@ A value computed by a database function the project owns (rc.21): @function name **Owning provider:** metaobjects-core-types +**Implemented in:** csharp, typescript so far — every port loads and type-checks it; the others do not act on it yet. + **When to use:** A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql. **Attributes** diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json index 1b4addf961..42273dbdf7 100644 --- a/fixtures/registry-conformance/expected-registry.json +++ b/fixtures/registry-conformance/expected-registry.json @@ -3607,6 +3607,10 @@ "valueType": "string", "isArray": false, "required": false, + "implementedIn": [ + "csharp", + "typescript" + ], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, { @@ -3614,6 +3618,10 @@ "valueType": "string", "isArray": false, "required": false, + "implementedIn": [ + "csharp", + "typescript" + ], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { @@ -3642,6 +3650,10 @@ "valueType": "string", "isArray": true, "required": false, + "implementedIn": [ + "csharp", + "typescript" + ], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, { @@ -3649,6 +3661,10 @@ "valueType": "boolean", "isArray": false, "required": false, + "implementedIn": [ + "csharp", + "typescript" + ], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." } ], @@ -4052,6 +4068,10 @@ { "type": "origin", "subType": "function", + "implementedIn": [ + "csharp", + "typescript" + ], "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "attrs": [ diff --git a/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs b/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs index f39524545a..ba436503ea 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/GeneratorIncludeTests.cs @@ -187,13 +187,15 @@ public void An_enum_both_narrowed_entries_use_is_declared_once() var r = new MetaDataLoader().Load([new InMemoryStringSource(BothUse, id: "both.json")]); Assert.Empty(r.Errors); // One run, one claim registry, as two entries of one generator list share. + var orderEntry = new EntityGenerator { Include = o => o.Name is "Order" }; + var customerEntry = new EntityGenerator { Include = o => o.Name is "Customer" }; var ctx = new GenContext { - Entities = r.Root.Objects(), Root = r.Root, + Entities = r.Root.Objects(), Root = r.Root, Generators = [orderEntry, customerEntry], Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, }; - var orders = new EntityGenerator { Include = o => o.Name is "Order" }.Generate(ctx).ToList(); - var customers = new EntityGenerator { Include = o => o.Name is "Customer" }.Generate(ctx).ToList(); + var orders = orderEntry.Generate(ctx).ToList(); + var customers = customerEntry.Generate(ctx).ToList(); // Customer sorts first (acme::Customer < acme::Order), so its entry declares Level. Assert.Contains(customers, f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); Assert.DoesNotContain(orders, f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); @@ -204,5 +206,27 @@ public void An_enum_both_narrowed_entries_use_is_declared_once() // Un-narrowed, it is declared as before. Assert.Single(new EntityGenerator().Generate(ctx), f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); } + // B2: a single narrowed entry whose Include does not accept the enum's home (Customer) still declares + // the enum, because no other entry of the run will; its output builds on its own. + [Theory] + [InlineData(true)] + [InlineData(false)] + public void A_single_narrowed_entry_declares_a_shared_enum_whose_home_it_does_not_emit(bool listed) + { + var r = new MetaDataLoader().Load([new InMemoryStringSource(BothUse, id: "both.json")]); + Assert.Empty(r.Errors); + var orderEntry = new EntityGenerator { Include = o => o.Name is "Order" }; + // Another kind of entry accepting the home does not declare entity enums, so it does not count. + var routes = new RoutesGenerator { Include = o => o.Name is "Customer" }; + var ctx = new GenContext + { + Entities = r.Root.Objects(), Root = r.Root, Generators = listed ? [orderEntry, routes] : [], + Config = new GenConfig { OutDir = "/tmp", Namespace = "Acme.Generated", OutputLayout = OutputLayout.Package, PackageNamespacesFromMetadata = true }, + }; + var orders = orderEntry.Generate(ctx).ToList(); + Assert.Single(orders, f => f.Path.EndsWith("Level.g.cs", StringComparison.Ordinal)); + var errors = PackageNamespaceTests.CompileErrors(orders); + Assert.True(errors.Count == 0, "a single narrowed entry's output should build on its own, but got:\n" + string.Join("\n", errors)); + } } diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs index dc726e1a64..7330aabfdf 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/GizmoRoutes.g.cs @@ -301,9 +301,8 @@ public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http) http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); - // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. - SerializerKeys.Strip(_envelope && node is System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); + // The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names. + SerializerKeys.StripBody(node, _value, _envelope, opts, _names); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs index 73941c624c..7ba89aa8ee 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/Golden/pre-rc22-propname/VehicleRoutes.g.cs @@ -479,9 +479,8 @@ public async System.Threading.Tasks.Task ExecuteAsync(HttpContext http) http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!) .Value.SerializerOptions; var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts); - // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names. - SerializerKeys.Strip(_envelope && node is System.Text.Json.Nodes.JsonObject env ? env["rows"] : node, - SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names); + // The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names. + SerializerKeys.StripBody(node, _value, _envelope, opts, _names); http.Response.StatusCode = _status; if (_location is not null) http.Response.Headers.Location = _location; await http.Response.WriteAsJsonAsync(node, opts); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs index fdfe14a8a8..dc0f85d753 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PackageKeyedOutputTests.cs @@ -174,13 +174,18 @@ private static MetaRoot SharedEnumModel() => Load(""" public void An_enum_used_by_several_narrowed_entries_is_declared_by_exactly_one_of_them() { var root = SharedEnumModel(); - var ctx = Ctx(root, package: false); - string[] Declared(Func include) => - new EntityGenerator { Include = include }.Generate(ctx).Where(f => f.Path == "Enums.g.cs").Select(f => f.Path).ToArray(); - - var withAccount = Declared(o => o.Name == "Account"); - var withPlan = Declared(o => o.Name == "Plan"); - var withOther = Declared(o => o.Name == "Other"); + // The three entries of one run: each sees the others through the run's entry list. + var account = new EntityGenerator { Include = o => o.Name == "Account" }; + var plan = new EntityGenerator { Include = o => o.Name == "Plan" }; + var other = new EntityGenerator { Include = o => o.Name == "Other" }; + var flat = Ctx(root, package: false); + var ctx = new GenContext { Entities = flat.Entities, Root = flat.Root, Config = flat.Config, Generators = [account, plan, other] }; + string[] Declared(EntityGenerator entry) => + entry.Generate(ctx).Where(f => f.Path == "Enums.g.cs").Select(f => f.Path).ToArray(); + + var withAccount = Declared(account); + var withPlan = Declared(plan); + var withOther = Declared(other); Assert.Equal(1, withAccount.Length + withPlan.Length); Assert.Empty(withOther); diff --git a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs index 8463be2d5b..cc9d72d98e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/PropertyNamingEmitSitesTests.cs @@ -260,10 +260,10 @@ public void A_renamed_credential_is_stripped_from_every_response_and_refused_on_ var vehicle = One(files, "VehicleRoutes.g.cs"); // The credential is named by its CLR property; the JSON key is the serializer's, read at run time - // (SerializerKeys.KeysOf), never spelled here. + // (SerializerKeys.StripBody), never spelled here. Assert.Contains("new string[] { \"XPinHash\", \"pinHash\" }", gizmo); Assert.Contains("new string[] { \"XVinHash\", \"vinHash\" }", vehicle); - Assert.Contains("SerializerKeys.KeysOf(_value, _envelope, opts, _names)", gizmo); + Assert.Contains("SerializerKeys.StripBody(node, _value, _envelope, opts, _names);", gizmo); Assert.DoesNotContain("OrdinalIgnoreCase))\n o.Remove", gizmo); // No response shape bypasses the stripping result: read, list, list-with-count, create, PATCH. @@ -312,7 +312,13 @@ public void Sort_and_EF_property_names_are_the_resolved_names_at_every_site() Assert.Contains("[\"XTitle\"] = true", gizmo); // @sortableDefaultOrder keys Assert.DoesNotContain("\"Title\"", gizmo); Assert.Contains("EF.Property(x!, \"XPlate\")", vehicle); // TPH base - Assert.Contains("\"XSeatCount\",", vehicle); // per-subtype sort allowlist + Assert.Contains("[\"XSeatCount\"] = \"XSeatCount\",", vehicle); // per-subtype sort allowlist + // A rename beyond case: ?sort= also takes the field name (the key ?filter[...] takes), resolved to the property. + Assert.Contains("Dictionary SortAllowlist", gizmo); + Assert.Contains("[\"title\"] = \"XTitle\",", gizmo); + Assert.Contains("[\"XTitle\"] = \"XTitle\",", gizmo); + Assert.Contains("[\"seatCount\"] = \"XSeatCount\",", vehicle); + Assert.Contains("[\"plate\"] = \"XPlate\",", vehicle); Assert.DoesNotContain("\"Plate\"", vehicle); // M:N junction: the FK properties and the target key, by their resolved names. Assert.Contains("EF.Property(j, \"XVehicleId\")", vehicle); diff --git a/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs index 124a8ecdfe..20b75b761e 100644 --- a/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs +++ b/server/csharp/MetaObjects.Codegen.Tests/SerializerKeysTests.cs @@ -94,4 +94,75 @@ public void Strip_also_removes_a_key_that_spells_the_credential_ignoring_case_an SerializerKeys.Strip(node, [], Names); Assert.Equal("""{"id":1,"name":"n"}""", node.ToJsonString()); } + // B1: under an upper-case policy the envelope's own key is ROWS; a strict host (PropertyNameCaseInsensitive + // = false) finds nothing under "rows", so the key must come from the envelope's contract. + public static IEnumerable UpperPolicies() => + [ + ["SnakeCaseUpper", "ROWS", "PIN_HASH"], + ["KebabCaseUpper", "ROWS", "PIN-HASH"], + ]; + + private static JsonNamingPolicy PolicyNamed(string name) => + name == "SnakeCaseUpper" ? JsonNamingPolicy.SnakeCaseUpper : JsonNamingPolicy.KebabCaseUpper; + + [Theory] + [MemberData(nameof(UpperPolicies))] + public void The_envelope_rows_are_stripped_under_an_upper_case_policy_on_a_strict_host(string policy, string rowsKey, string credentialKey) + { + var opts = new JsonSerializerOptions + { + PropertyNamingPolicy = PolicyNamed(policy), PropertyNameCaseInsensitive = false, + TypeInfoResolver = new DefaultJsonTypeInfoResolver(), + }; + var rows = new List { new() { Id = 1, PinHash = "SECRET" } }; + var body = new { rows, total = 1 }; + var node = JsonSerializer.SerializeToNode(body, body.GetType(), opts)!; + Assert.Contains(credentialKey, node.ToJsonString()); // the probe: the key really is written this way + + SerializerKeys.StripBody(node, body, true, opts, Names); + + Assert.DoesNotContain("SECRET", node.ToJsonString()); + Assert.Single(node[rowsKey]!.AsArray()); + } + + [Theory] + [MemberData(nameof(UpperPolicies))] + public void A_row_list_and_a_single_row_are_stripped_under_an_upper_case_policy_on_a_strict_host(string policy, string _, string credentialKey) + { + var opts = new JsonSerializerOptions + { + PropertyNamingPolicy = PolicyNamed(policy), PropertyNameCaseInsensitive = false, + TypeInfoResolver = new DefaultJsonTypeInfoResolver(), + }; + foreach (object body in new object[] { new List { new() { PinHash = "SECRET" } }, new Row { PinHash = "SECRET" } }) + { + var node = JsonSerializer.SerializeToNode(body, body.GetType(), opts)!; + Assert.Contains(credentialKey, node.ToJsonString()); + SerializerKeys.StripBody(node, body, false, opts, Names); + Assert.DoesNotContain("SECRET", node.ToJsonString()); + } + } + + [Fact] + public void An_envelope_whose_rows_key_is_not_in_its_contract_is_refused() + { + // A modifier that drops the envelope's rows property: the credential could not be found, so refuse. + var resolver = new DefaultJsonTypeInfoResolver(); + resolver.Modifiers.Add(ti => { foreach (var p in ti.Properties.Where(p => p.Name == "rows").ToList()) ti.Properties.Remove(p); }); + var opts = new JsonSerializerOptions { TypeInfoResolver = resolver }; + var body = new { rows = new List { new() { PinHash = "SECRET" } }, total = 1 }; + var node = JsonSerializer.SerializeToNode(body, body.GetType(), opts)!; + var ex = Assert.Throws(() => SerializerKeys.StripBody(node, body, true, opts, Names)); + Assert.Contains("refused", ex.Message); + Assert.DoesNotContain("SECRET", ex.Message); + } + + [Fact] + public void An_envelope_whose_rows_are_not_an_array_is_refused() + { + var opts = new JsonSerializerOptions { TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + var body = new { rows = new List { new() { PinHash = "SECRET" } }, total = 1 }; + var node = System.Text.Json.Nodes.JsonNode.Parse("""{"rows":{"pinHash":"SECRET"},"total":1}"""); + Assert.Throws(() => SerializerKeys.StripBody(node, body, true, opts, Names)); + } } diff --git a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs index 5b5b68fa06..00826f27ad 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/EntityGenerator.cs @@ -1138,11 +1138,13 @@ protected virtual IEnumerable EmitSharedEnumFiles(GenContext ctx, I foreach (var e in Fr019SharedEnum.MaterializedSharedEnums(ctx.Root, reached, ctx.Scope)) { // An enum two narrowed entries both use is declared by ONE of them, so the entries' - // outputs build together. Decided from the model alone, so each entry reaches the same - // answer in its own run: the enum's home is its first consumer by resolution key, and - // the entry that emits that object declares it. + // outputs build together. Decided from the model and the run's entry list, so each entry + // reaches the same answer in its own run: the enum's home is its first consumer by + // resolution key, and the entry that emits that object declares it. An entry skips the + // enum only when ANOTHER entity entry of this run accepts the home; with no such entry + // (a single narrowed entry, or a home another tool generates) it declares the enum itself. if (ctx.Scope is { } scope && SharedEnumHome(ctx, e, importedShapes) is { } home - && !scope(home) && !valueShapes.Contains(home)) + && !scope(home) && !valueShapes.Contains(home) && AnotherEntryEmits(ctx, home)) continue; var ns = Fr019SharedEnum.MaterializedNamespace(e, ctx.Config); ctx.Claim($"the C# namespace {ns}", e.Name, e.Declaration?.ResolutionKey() ?? e.Name, @@ -1199,6 +1201,14 @@ protected virtual IEnumerable EmitSharedEnumFiles(GenContext ctx, I return [new EmittedFile("Enums.g.cs", flat.ToString()) { WholeModel = true }]; } + /// + /// Whether another entity entry of this run () accepts + /// , so that entry declares the shared enum homed there. A run that does not + /// list its entries answers false, and the enum is declared here. + /// + private bool AnotherEntryEmits(GenContext ctx, MetaObject home) => + ctx.Generators.OfType().Any(g => !ReferenceEquals(g, this) && (g.Include is null || g.Include(home))); + /// /// The object a narrowed run's shared enum is declared beside: the first, by resolution key, of /// every object this project generates (and every imported value object this run emits) that has diff --git a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs index 7ffffa0cc6..7bd48d4ce8 100644 --- a/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs +++ b/server/csharp/MetaObjects.Codegen/Generators/RoutesGenerator.cs @@ -301,13 +301,13 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte // EF.Property(x, "") as any other field; the row maps the enum with // HasConversion() (or to its integer under @intValueMap), so the ORDER BY is // over the stored column. - var sortFields = entity.Fields() + var sortFieldNodes = entity.Fields() .Where(f => (CSharpNaming.ScalarFor(f.SubType) is not null || (isReport && f.SubType == FIELD_SUBTYPE_ENUM)) && !f.ResolvedIsArray() && !(isReport && IsCredentialField(f))) // a credential column would be a sort oracle - .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); + var sortFields = sortFieldNodes.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); // ADR-0019 Amendment 1 (W4): SQLite refuses `ORDER BY` over a decimal expression, and its // NUMERIC column is a double anyway, so on SQLite a decimal sorts by its double. Every @@ -338,12 +338,7 @@ protected virtual EmittedFile GenerateStandardRoutes(MetaObject entity, GenConte sb.AppendLine("{"); // Static sort allowlist (case-insensitive) so the qs ?sort=field:dir // is gated against the entity's scalar fields. - sb.Append(" private static readonly System.Collections.Generic.HashSet SortAllowlist ="); - sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); - sb.AppendLine(" {"); - foreach (var name in sortFields) sb.AppendLine($" \"{name}\","); - sb.AppendLine(" };"); - sb.AppendLine(); + AppendSortAllowlist(sb, "SortAllowlist", sortFieldNodes, ctx.Config); AppendSortDefaultOrder(sb, entity, "SortDefaultDesc", ctx.Config); if (writable) AppendKnownFields(sb, [entity], ctx.Root); AppendUnauthenticatedRoutesDoc(sb, cls, isProjection); @@ -632,10 +627,10 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t .Distinct(StringComparer.Ordinal).ToList(); // Sortable base scalar fields (the polymorphic list sorts on base columns). - var sortFields = baseEntity.Fields() + var sortFieldNodes = baseEntity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) - .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); + var sortFields = sortFieldNodes.Select(f => CSharpNaming.PropertyName(f, ctx.Config)).ToList(); var sb = new StringBuilder(); sb.AppendLine("// "); @@ -656,12 +651,7 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t sb.AppendLine("{"); // Polymorphic sort allowlist over the base scalar columns. - sb.Append(" private static readonly System.Collections.Generic.HashSet SortAllowlist ="); - sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); - sb.AppendLine(" {"); - foreach (var name in sortFields) sb.AppendLine($" \"{name}\","); - sb.AppendLine(" };"); - sb.AppendLine(); + AppendSortAllowlist(sb, "SortAllowlist", sortFieldNodes, ctx.Config); AppendSortDefaultOrder(sb, baseEntity, "SortDefaultDesc", ctx.Config); // One known set for the whole hierarchy: a sibling subtype's column is declared, so it is not unknown. AppendKnownFields(sb, tph.Subtypes.Select(st => st.Entity).Prepend(baseEntity), ctx.Root); @@ -676,14 +666,8 @@ protected virtual EmittedFile GenerateTphRoutes(MetaObject baseEntity, TphPlan t var subClsName = CSharpNaming.Pascal(st.Entity.Name); var subSortFields = st.Entity.Fields() .Where(f => CSharpNaming.ScalarFor(f.SubType) is not null && !f.ResolvedIsArray()) - .Select(f => CSharpNaming.PropertyName(f, ctx.Config)) .ToList(); - sb.Append($" private static readonly System.Collections.Generic.HashSet {subClsName}SortAllowlist ="); - sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); - sb.AppendLine(" {"); - foreach (var name in subSortFields) sb.AppendLine($" \"{name}\","); - sb.AppendLine(" };"); - sb.AppendLine(); + AppendSortAllowlist(sb, $"{subClsName}SortAllowlist", subSortFields, ctx.Config); AppendSortDefaultOrder(sb, st.Entity, $"{subClsName}SortDefaultDesc", ctx.Config); } @@ -885,7 +869,7 @@ private static List WireKeys(MetaField f, GenConfig config) => .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); // The CLR property names of an entity's credentials. The JSON key each is written under is not - // derived here: the generated result asks the host's serializer (SerializerKeys.KeysOf). + // derived here: the generated result asks the host's serializer (SerializerKeys.StripBody). private static List CredentialNames(MetaObject entity, GenConfig config) => entity.Fields().Where(IsCredentialField).SelectMany(f => CredentialSpellings(f, config)).ToList(); @@ -899,6 +883,35 @@ private static IEnumerable CredentialSpellings(MetaField f, GenConfig co private static string KeyMatch(IEnumerable keys) => string.Join(" || ", keys.Select(k => $"string.Equals(prop.Name, \"{k}\", System.StringComparison.OrdinalIgnoreCase)")); + // A sort allowlist (case-insensitive): `TryGetValue(key, out var resolved)` gives the CLR property to + // sort on. Without a rename beyond case it is the set of property names (the field name matches one + // ignoring case), as ever. When a resolver renamed a property beyond case it is a map that accepts the + // field name too, so `?sort=` takes the same key as `?filter[...]` (which keys on the field name) + // and the property name a client may have read from a response. + private static void AppendSortAllowlist(StringBuilder sb, string name, IReadOnlyList fields, GenConfig config) + { + var pairs = fields.Select(f => (Field: f.Name, Prop: CSharpNaming.PropertyName(f, config))).ToList(); + if (pairs.All(p => string.Equals(p.Field, p.Prop, StringComparison.OrdinalIgnoreCase))) + { + sb.Append($" private static readonly System.Collections.Generic.HashSet {name} ="); + sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); + sb.AppendLine(" {"); + foreach (var p in pairs) sb.AppendLine($" \"{p.Prop}\","); + sb.AppendLine(" };"); + sb.AppendLine(); + return; + } + sb.Append($" private static readonly System.Collections.Generic.Dictionary {name} ="); + sb.AppendLine(" new(System.StringComparer.OrdinalIgnoreCase)"); + sb.AppendLine(" {"); + // Property names first, so a field name that spells another field's property never shadows it. + var keys = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var p in pairs) if (keys.Add(p.Prop)) sb.AppendLine($" [\"{p.Prop}\"] = \"{p.Prop}\","); + foreach (var p in pairs) if (keys.Add(p.Field)) sb.AppendLine($" [\"{p.Field}\"] = \"{p.Prop}\","); + sb.AppendLine(" };"); + sb.AppendLine(); + } + // The extra argument that hands the filter dispatch the allowlist's field-to-property map: only // when a resolver renamed a property beyond case (the allowlist emits the map on the same test). private static string FilterMapArg(string allowlistRef, MetaObject entity, GenConfig config) => @@ -946,9 +959,8 @@ private static void AppendOmitResultClass(StringBuilder sb) sb.AppendLine(" http.RequestServices.GetService(typeof(Microsoft.Extensions.Options.IOptions))!)"); sb.AppendLine(" .Value.SerializerOptions;"); sb.AppendLine(" var node = System.Text.Json.JsonSerializer.SerializeToNode(_value, _value.GetType(), opts);"); - sb.AppendLine(" // The keys are the serializer's own for these properties (naming policy, rename, attribute), never guessed from names."); - sb.AppendLine($" SerializerKeys.Strip(_envelope && node is System.Text.Json.Nodes.JsonObject env ? env[\"rows\"] : node,"); - sb.AppendLine($" SerializerKeys.KeysOf(_value, _envelope, opts, _names), _names);"); + sb.AppendLine(" // The keys are the serializer's own for these properties and the envelope's rows (naming policy, rename, attribute), never guessed from names."); + sb.AppendLine(" SerializerKeys.StripBody(node, _value, _envelope, opts, _names);"); sb.AppendLine(" http.Response.StatusCode = _status;"); sb.AppendLine(" if (_location is not null) http.Response.Headers.Location = _location;"); sb.AppendLine(" await http.Response.WriteAsJsonAsync(node, opts);"); diff --git a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs index 954d5b6312..cac15e692b 100644 --- a/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs +++ b/server/csharp/MetaObjects.Codegen/Runtime/ReportExportHttp.cs @@ -78,9 +78,8 @@ is Microsoft.Extensions.Options.IOptions type.Name + "." + c))} from a response: {why}. " + "Credential stripping reads the serializer's reflection-visible contract; the response is refused rather than sent unstripped."); + /// + /// Strip the credential properties named from , the + /// serialized form of under : from the row, from each row of + /// a list, or, with , from each row under the rows key of a + /// { rows, total } envelope. Every credential-omitting response goes through here. The envelope's + /// rows key is the serializer's own (a naming policy may write it ROWS), read from the + /// envelope's contract, never assumed. Fails closed: a credential key that cannot be read (see + /// ), an envelope whose rows key cannot be read from its contract, or a node + /// under that key that is not an array THROWS, so the response is refused rather than sent unstripped. + /// + public static void StripBody(JsonNode? node, object? body, bool envelope, JsonSerializerOptions options, IReadOnlyCollection clrNames) + { + var keys = KeysOf(body, envelope, options, clrNames); + Strip(envelope ? EnvelopeRows(node, body, options) : node, keys, clrNames); + } + + // The rows array of a serialized { rows, total } envelope, found under the key the serializer's contract + // gives the envelope's `rows` member. Throws when the key or the array cannot be found. + private static JsonArray EnvelopeRows(JsonNode? node, object? body, JsonSerializerOptions options) + { + const string Rows = "rows"; + static InvalidOperationException Refused(string why) => + new($"cannot strip credentials from a {{ rows, total }} response: {why}. The response is refused rather than sent unstripped."); + if (body is null || node is not JsonObject env) throw Refused("the body did not serialize to a JSON object"); + JsonTypeInfo info; + try { info = options.GetTypeInfo(body.GetType()); } + catch (NotSupportedException e) { throw Refused("the serializer has no contract for the envelope (" + e.GetType().Name + ")"); } + var key = info.Kind == JsonTypeInfoKind.Object + ? info.Properties.FirstOrDefault(p => p.AttributeProvider is MemberInfo m && m.Name == Rows)?.Name + : null; + if (key is null) throw Refused("the serializer's contract for the envelope has no rows property"); + if (!env.TryGetPropertyValue(key, out var rows) || rows is not JsonArray array) + throw Refused($"the envelope has no array under its rows key \"{key}\""); + return array; + } + /// /// Remove every key in from the object, or from each object of the array, and, as a /// second line of defence, every key that spells one of ignoring case, _ and diff --git a/server/csharp/MetaObjects.Conformance.Tests/R6Plan2LoaderTests.cs b/server/csharp/MetaObjects.Conformance.Tests/R6Plan2LoaderTests.cs index 6f5f955dc7..12bce96629 100644 --- a/server/csharp/MetaObjects.Conformance.Tests/R6Plan2LoaderTests.cs +++ b/server/csharp/MetaObjects.Conformance.Tests/R6Plan2LoaderTests.cs @@ -137,6 +137,20 @@ public void DbColumnType_unknown_value_is_ERR_BAD_ATTR_VALUE() Assert.Contains("allowed", err.Message); } + // L7: .NET's `$` also matches before a final newline; the sized pattern ends at `\z`, so a sized + // spelling followed by a newline is not a legal value (it would otherwise emit a sized column). + [Theory] + [InlineData("varchar(10)")] + [InlineData("character varying(10)")] + [InlineData("character(3)")] + public void A_sized_DbColumnType_with_a_trailing_newline_is_ERR_BAD_ATTR_VALUE(string sized) + { + Assert.NotNull(ParseDbColumnType(sized)); + Assert.Null(ParseDbColumnType(sized + "\n")); + var res = LoadJson(Pairing(FIELD_SUBTYPE_STRING, sized + "\\n")); // a JSON-escaped newline + Assert.Contains(res.Errors, e => e.Code == ErrorCode.ERR_BAD_ATTR_VALUE && e.Message.Contains("dbColumnType")); + } + // ------------------------------------------------------------------------ // Phase 1 slim-and-derive: uuid_array + text_array are removed values. // They now fall through Rule 1 (unknown value) → ERR_BAD_ATTR_VALUE. diff --git a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs index b6e40cc3dd..a6d075b781 100644 --- a/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs +++ b/server/csharp/MetaObjects.IntegrationTests/Api/ApiContractCredentialHostVariantsTest.cs @@ -7,7 +7,9 @@ // (SerializerKeys), so these variants must all hold: // 1. a property renamed beyond case, default (camelCase) host; // 2. the same rename under JsonNamingPolicy.SnakeCaseLower; -// 3. no rename under SnakeCaseLower (the leak that predates the resolver: pinHash -> pin_hash). +// 3. no rename under SnakeCaseLower (the leak that predates the resolver: pinHash -> pin_hash); +// 4. an upper-case policy (SnakeCaseUpper, KebabCaseUpper) with PropertyNameCaseInsensitive = false, where +// even the { rows, total } envelope's own key is written ROWS and must be found from the contract. // Plus a credential declared on a TPH SUBTYPE, through the polymorphic list and the per-subtype routes. // // A response may not carry the credential under any key; a PATCH or PUT body naming it under any @@ -47,12 +49,29 @@ public static IEnumerable Hosts() => ["rename", "camel"], ["rename", "snake"], ["plain", "snake"], + ["plain", "snakeUpper"], + ["rename", "kebabUpper"], ]; + private static JsonNamingPolicy Policy(string policy) => policy switch + { + "snake" => JsonNamingPolicy.SnakeCaseLower, + "snakeUpper" => JsonNamingPolicy.SnakeCaseUpper, + "kebabUpper" => JsonNamingPolicy.KebabCaseUpper, + _ => JsonNamingPolicy.CamelCase, + }; + + // The upper-case hosts are strict: JSON keys are matched exactly, so nothing finds "rows" under "ROWS". + private static Action? Strictness(string policy) => + policy.EndsWith("Upper", StringComparison.Ordinal) ? o => o.PropertyNameCaseInsensitive = false : null; + + // The key the host writes (and a client echoes) for a property whose camelCase name is given. + private static string Wire(string policy, string camelName) => Policy(policy).ConvertName(camelName); + private static SecretFieldsHost AccountHost(string naming, string policy) => new( PropertyNaming: naming == "rename" ? AccountSpelling : null, - JsonPolicy: policy == "snake" ? JsonNamingPolicy.SnakeCaseLower : JsonNamingPolicy.CamelCase, - MetaJson: AccountMeta(), ExtraDdl: AccountDdl); + JsonPolicy: Policy(policy), + MetaJson: AccountMeta(), ExtraDdl: AccountDdl, ConfigureJson: Strictness(policy)); // A key is a credential key iff it spells the credential (or its resolved name) ignoring case and `_`/`-`. private static readonly string[] CredentialKeys = ["pinhash", "pinsecret", "permitsecret"]; @@ -107,14 +126,19 @@ private static void AssertNoCredential(JsonNode? node, string where) } // Every spelling a client could send for the denied fields: the field name, the resolved property name - // under the camel and the snake host, and their capitalized forms. - private static Dictionary ForgedBody(string name) => new() + // under the camel and the snake host, their capitalized forms, and the host's own key for each. + private static Dictionary ForgedBody(string name, string policy) { - ["name"] = name, - ["pinHash"] = "forged", ["tokenHash"] = "forged", ["role"] = "admin", - ["pinSecret"] = "forged", ["PinSecret"] = "forged", ["pin_secret"] = "forged", ["apiToken"] = "forged", ["ApiToken"] = "forged", - ["pin_hash"] = "forged", ["token_hash"] = "forged", ["api_token"] = "forged", - }; + var body = new Dictionary + { + [Wire(policy, "name")] = name, + ["pinHash"] = "forged", ["tokenHash"] = "forged", ["role"] = "admin", + ["pinSecret"] = "forged", ["PinSecret"] = "forged", ["pin_secret"] = "forged", ["apiToken"] = "forged", ["ApiToken"] = "forged", + ["pin_hash"] = "forged", ["token_hash"] = "forged", ["api_token"] = "forged", + }; + foreach (var k in new[] { "pinHash", "tokenHash", "pinSecret", "apiToken" }) body[Wire(policy, k)] = "forged"; + return body; + } [Theory] [MemberData(nameof(Hosts))] @@ -137,28 +161,24 @@ public async Task A_credential_is_never_returned_and_never_written_whatever_the_ var counted = await SendAsync(client, "GET", "/api/accounts?withCount=1&sort=id:asc"); Assert.Equal(200, counted.Status); AssertNoCredential(counted.Body, "GET list withCount"); - Assert.Equal(2, counted.Body!["rows"]!.AsArray().Count); + Assert.Equal(2, counted.Body![Wire(policy, "rows")]!.AsArray().Count); // Writes: PATCH and PUT with the denied fields under every spelling are ignored; the multi-word // ordinary field is applied under the host's own key for it. // The key a client echoes is the serializer's: the policy over the (possibly renamed) property. - var displayKey = (naming, policy) switch - { - ("rename", "snake") => "shown_as", ("rename", _) => "shownAs", - (_, "snake") => "display_name", _ => "displayName", - }; + var displayKey = Wire(policy, naming == "rename" ? "shownAs" : "displayName"); foreach (var (method, id) in new[] { ("PATCH", 1), ("PUT", 2) }) { - var body = ForgedBody($"{method}-probe"); + var body = ForgedBody($"{method}-probe", policy); body[displayKey] = $"{method}-shown"; var res = await SendAsync(client, method, $"/api/accounts/{id}", body); Assert.Equal(200, res.Status); AssertNoCredential(res.Body, method); - Assert.Equal($"{method}-probe", res.Body!["name"]!.GetValue()); + Assert.Equal($"{method}-probe", res.Body![Wire(policy, "name")]!.GetValue()); } // Creates: the denied fields are ignored (stored null), the response carries no credential. - var created = await SendAsync(client, "POST", "/api/accounts", ForgedBody("Grace Hopper")); + var created = await SendAsync(client, "POST", "/api/accounts", ForgedBody("Grace Hopper", policy)); Assert.Equal(201, created.Status); AssertNoCredential(created.Body, "POST"); @@ -196,6 +216,8 @@ public static IEnumerable TphHosts() => ["rename", "snake"], ["plain", "snake"], ["rename", "camel"], + ["plain", "snakeUpper"], + ["rename", "kebabUpper"], ]; [Theory] @@ -205,8 +227,8 @@ public async Task A_subtype_credential_is_never_returned_or_written_on_the_polym await using var pg = await PostgresContainer.StartAsync(); var host = new TphHost( PropertyNaming: naming == "rename" ? TphSpelling : null, - JsonPolicy: policy == "snake" ? JsonNamingPolicy.SnakeCaseLower : JsonNamingPolicy.CamelCase, - MetaJson: TphMeta(), ExtraDdl: TphDdl); + JsonPolicy: Policy(policy), + MetaJson: TphMeta(), ExtraDdl: TphDdl, ConfigureJson: Strictness(policy)); await using var server = await TphGeneratedServerFactory.StartAsync(pg, host); await server.ApplySeedAsync(); await using (var c = new Npgsql.NpgsqlConnection(pg.ConnectionString)) @@ -226,25 +248,21 @@ public async Task A_subtype_credential_is_never_returned_or_written_on_the_polym } Assert.DoesNotContain("permit-secret", (await SendAsync(client, "GET", "/api/auths")).Body!.ToJsonString()); - var noteKey = (naming, policy) switch - { - ("rename", "snake") => "permit_memo", ("rename", _) => "permitMemo", - (_, "snake") => "permit_note", _ => "permitNote", - }; + var noteKey = Wire(policy, naming == "rename" ? "permitMemo" : "permitNote"); foreach (var method in new[] { "PATCH", "PUT" }) { var res = await SendAsync(client, method, "/api/auths/permit/3", new Dictionary { - ["approver"] = $"{method}-approver", [noteKey] = $"{method}-note", + [Wire(policy, "approver")] = $"{method}-approver", [noteKey] = $"{method}-note", ["pinHash"] = "forged", ["pin_hash"] = "forged", ["permitSecret"] = "forged", ["PermitSecret"] = "forged", ["permit_secret"] = "forged", }); Assert.Equal(200, res.Status); AssertNoCredential(res.Body, method + " permit"); - Assert.Equal($"{method}-approver", res.Body!["approver"]!.GetValue()); + Assert.Equal($"{method}-approver", res.Body![Wire(policy, "approver")]!.GetValue()); } var created = await SendAsync(client, "POST", "/api/auths/permit", new Dictionary { - ["reference"] = "REF-NEW", ["approver"] = "Dr. New", ["pinHash"] = "forged", ["pin_hash"] = "forged", ["permitSecret"] = "forged", ["permit_secret"] = "forged", + [Wire(policy, "reference")] = "REF-NEW", [Wire(policy, "approver")] = "Dr. New", ["pinHash"] = "forged", ["pin_hash"] = "forged", ["permitSecret"] = "forged", ["permit_secret"] = "forged", }); Assert.Equal(201, created.Status); AssertNoCredential(created.Body, "POST permit"); diff --git a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs index d202e03457..9798106005 100644 --- a/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs +++ b/server/csharp/MetaObjects/Persistence/Db/DbConstants.cs @@ -109,7 +109,7 @@ public static class DbConstants public sealed record ParsedDbColumnType(string Kind, int? Length); private static readonly System.Text.RegularExpressions.Regex SizedDbColumnType = - new(@"^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)$", System.Text.RegularExpressions.RegexOptions.CultureInvariant); + new(@"^(varchar|character varying|character)\(([1-9][0-9]{0,8})\)\z", System.Text.RegularExpressions.RegexOptions.CultureInvariant); /// /// rc.21 part B (U2): parse a @dbColumnType value, or null for one that is not legal. diff --git a/server/csharp/MetaObjects/SpecMetamodel/object.json b/server/csharp/MetaObjects/SpecMetamodel/object.json index d169a02544..eb44fedc67 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/object.json +++ b/server/csharp/MetaObjects/SpecMetamodel/object.json @@ -54,10 +54,10 @@ "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, - { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, - { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, - { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, - { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] }, diff --git a/server/csharp/MetaObjects/SpecMetamodel/origin.json b/server/csharp/MetaObjects/SpecMetamodel/origin.json index e8cfe7e735..e2539d6d66 100644 --- a/server/csharp/MetaObjects/SpecMetamodel/origin.json +++ b/server/csharp/MetaObjects/SpecMetamodel/origin.json @@ -45,6 +45,7 @@ { "type": "origin", "subType": "function", + "implementedIn": ["typescript", "csharp"], "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ diff --git a/server/python/src/metaobjects/spec_metamodel/object.json b/server/python/src/metaobjects/spec_metamodel/object.json index d169a02544..eb44fedc67 100644 --- a/server/python/src/metaobjects/spec_metamodel/object.json +++ b/server/python/src/metaobjects/spec_metamodel/object.json @@ -54,10 +54,10 @@ "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, - { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, - { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, - { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, - { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] }, diff --git a/server/python/src/metaobjects/spec_metamodel/origin.json b/server/python/src/metaobjects/spec_metamodel/origin.json index e8cfe7e735..e2539d6d66 100644 --- a/server/python/src/metaobjects/spec_metamodel/origin.json +++ b/server/python/src/metaobjects/spec_metamodel/origin.json @@ -45,6 +45,7 @@ { "type": "origin", "subType": "function", + "implementedIn": ["typescript", "csharp"], "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ diff --git a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts index a69583af2a..56c86f361f 100644 --- a/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/core/object/object-definition.embedded.ts @@ -190,6 +190,10 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "isArray": true, "min": 0, "max": 1, + "implementedIn": [ + "typescript", + "csharp" + ], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, { @@ -198,6 +202,10 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "name": "unionAll", "min": 0, "max": 1, + "implementedIn": [ + "typescript", + "csharp" + ], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, { @@ -206,6 +214,10 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "name": "grain", "min": 0, "max": 1, + "implementedIn": [ + "typescript", + "csharp" + ], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, { @@ -214,6 +226,10 @@ export const OBJECT_DEFINITION: ProviderDefinition = { "name": "grainOrdinal", "min": 0, "max": 1, + "implementedIn": [ + "typescript", + "csharp" + ], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { diff --git a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts index 6541892303..acb5529821 100644 --- a/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts +++ b/server/typescript/packages/metadata/src/persistence/origin/origin-definition.embedded.ts @@ -141,6 +141,10 @@ export const ORIGIN_DEFINITION: ProviderDefinition = { { "type": "origin", "subType": "function", + "implementedIn": [ + "typescript", + "csharp" + ], "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ diff --git a/spec/metamodel/object.json b/spec/metamodel/object.json index d169a02544..eb44fedc67 100644 --- a/spec/metamodel/object.json +++ b/spec/metamodel/object.json @@ -54,10 +54,10 @@ "rules": "object.projection is a derived read-only representation: every field is extends-bound, origin-derived, or self-declared-under-external-assembly, and all are read-only at the subtype level. Identity is optional and, when present, MUST extend an entity identity. Sources are restricted to read-only @kinds. The declared field set IS the exposure — an inclusive list, fail-closed. A projection NEVER declares relationships (derivation is expressed via @via, not a relationship child) and NEVER co-locates templates — hence its child set omits both relationship and template. The assembly origins (origin.aggregate / origin.computed / origin.first) live HERE, not on object.value; a SOURCELESS projection is the legal shape for a wire-assembled read model, and a template-level @payloadRef/@responseRef may target one (#210). See ADR-0028 (object taxonomy, projection).", "children": [ { "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row-scope predicate (a portable attr.filter object: eq/ne/gt/gte/lt/lte/like/in/isNull with and/or, desugared to { field: { op: value } } at parse time) selecting which rows the view returns — lowered to an outer SQL WHERE. A key names one of the projection's own fields, else a field of its base entity the view need not output, else a PATH of to-one hops (identity.reference or @cardinality one relationship names) from the base then a field of the entity reached ('orderId.customerId.hasActiveMembership'), joined but not output. A reached entity field may itself be derived (entity-derived: an origin.computed or origin.first declared on the entity, inlined where the filter reaches it). An aggregate-derived field is not addressable (fail-closed); a to-many hop is refused. A value may be a relative date ({ now: \"\", startOf? }) on a date or timestamp field (rc.19)." }, - { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, - { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, - { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, - { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, + { "type": "attr", "subType": "string", "name": "union", "isArray": true, "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view is this projection's rows UNIONed with each named projection's rows. Each named projection has the same effective fields as this one, in order: names, subtypes, array-ness and physical column names (ERR_BAD_ATTR_VALUE otherwise); its own @filter, joins and base apply to its rows. Usually this projection extends one branch and names the others. A named projection may be abstract and sourceless." }, + { "type": "attr", "subType": "boolean", "name": "unionAll", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @union, keep duplicate rows (UNION ALL). Absent or false: duplicates are removed (UNION), SQL's own default." }, + { "type": "attr", "subType": "string", "name": "grain", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: the view has one row per element of this base-entity field, a field.object array stored as jsonb; a base row with no element has no row. A field whose origin.passthrough @from names the field's @objectRef value object (Address.city) reads that member of the element; the base's own fields read the parent row as usual. An origin.aggregate is refused on such a projection." }, + { "type": "attr", "subType": "string", "name": "grainOrdinal", "min": 0, "max": 1, "implementedIn": ["typescript", "csharp"], "description": "rc.21: with @grain, the name of a field.int or field.long of this projection (with no origin) that holds the element's 1-based position in the array." }, { "type": "attr", "subType": "string", "name": "collectionName", "min": 0, "max": 1, "description": "The name of this object's collection, in the object's own casing (e.g. 'CaseHistory', 'Queues'): the REST collection segment (snake_cased) in every port, the reverse-finder names in C#, TypeScript and Python, the C# DbSet property, and the TypeScript list function, list hook and Drizzle table variable. It need not be a grammatical plural. Absent, the project's pluralizer derives it from the object's name (naming.collections in .metaobjects/config.json; built in: standard, none; an application may register its own)." } ] }, diff --git a/spec/metamodel/origin.json b/spec/metamodel/origin.json index e8cfe7e735..e2539d6d66 100644 --- a/spec/metamodel/origin.json +++ b/spec/metamodel/origin.json @@ -45,6 +45,7 @@ { "type": "origin", "subType": "function", + "implementedIn": ["typescript", "csharp"], "description": "A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.", "whenToUse": "A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.", "children": [ From 51788e60ee3f970779a29a9ae4e74ac3ba8b87b0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:35:20 -0500 Subject: [PATCH 2/3] no-mistakes(document): cover rc.21 implementedIn and narrowed enum rule --- docs/CONFORMANCE.md | 5 +++++ docs/ports/csharp.md | 7 +++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index e0f40a99eb..16e6366afd 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -169,6 +169,11 @@ canonical (`fixtures/registry-conformance/expected-registry.json`). - `view.image`, and its `@accept`, `@aspectRatio`, `@maxBytes`, `@maxEdge`, `@store` - *Implemented in Java only* (`implementedIn: ["java"]`): `object.* @object` (ADR-0001), the native class an object binds to. Java's runtime acts on it; Java's own behaviour is unchanged. +- *Implemented in TypeScript and C#* (`implementedIn: ["typescript", "csharp"]`): the rc.21 + view vocabulary — `origin.function` and the `object.projection` attrs `@union`, `@unionAll`, + `@grain`, `@grainOrdinal`. The TypeScript view emitter lowers them; the C# loader validates + them (mirroring the TypeScript checks message for message); the other ports load them strictly + and do not act on them yet. - *Loads strictly in every port.* Each port registers the `metaobjects-ui-web` provider (`view.textarea @rows`, the `view.image` attrs) and `@object` / `@objectAdapter` on `object.*`, loads all three fixtures strictly, and emits `implementedIn` in its manifest, which diff --git a/docs/ports/csharp.md b/docs/ports/csharp.md index bf128e5071..23a333b1e4 100644 --- a/docs/ports/csharp.md +++ b/docs/ports/csharp.md @@ -281,8 +281,11 @@ and sits in its package's namespace. An extract-tier private mapper may carry th member name (`FromAcmeAlphaNoteExtracted`), because it is private to its class. Each package's shared enum is its own `/.g.cs` under the package layout, with its `@intValueMap` integers as member values and `@description` as its XML doc; the flat layout keeps -the one `Enums.g.cs`. An entry narrowed with `Include` declares only the shared enums it uses, and -an enum several narrowed entries use is declared by exactly one of them. +the one `Enums.g.cs`. An entry narrowed with `Include` leaves a shared enum to another `entity` +entry of the same run only when that entry accepts the enum's home object (its first consumer by +resolution key), and declares the enum itself otherwise — so a single narrowed entry declares +every enum its objects use and its output builds on its own, and an enum several narrowed entries +use is still declared by exactly one of them. With that, `dotnet meta gen` writes there, `dotnet meta verify --codegen` diffs against it, and a plain `dotnet meta verify` in CI runs the codegen gate with no flags. `--out ` still works From 95dd9badadaecc0c967dba4f645b0652710e6472 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Wed, 18 Nov 2026 13:36:47 -0500 Subject: [PATCH 3/3] no-mistakes(lint): regen site-reference/types/origin.html for origin.function implementedIn --- site-reference/types/origin.html | 1 + 1 file changed, 1 insertion(+) diff --git a/site-reference/types/origin.html b/site-reference/types/origin.html index d05225a155..c0525d7233 100644 --- a/site-reference/types/origin.html +++ b/site-reference/types/origin.html @@ -239,6 +239,7 @@

origin.first

origin.function

A value computed by a database function the project owns (rc.21): @function names it, @schema its schema (absent: public), and @args the fields passed to it, in order. On an entity an argument is one of its fields; on a projection, one of its own fields (not an aggregate) or a field of its base entity. @params declares each argument's type and @returns the result's: an argument must have its parameter's type (cast it through an origin.computed field otherwise), @returns must be the carrying field's subtype, and the view casts the call to the field's full column type (the one its table column would have: length or @dbColumnType spelling, precision and scale, a local or zoned timestamp), so the call is checked, never free SQL. The signature is a declaration: meta verify --db reads the function from pg_proc and fails on a parameter or return type that differs. MetaObjects never creates the function: it is owned SQL, created before the view. Declared on an entity, it is entity-derived: a projection reaching the entity reads it like any derived field. Postgres only; the SQLite view emitter refuses it.

Owning provider: metaobjects-core-types

+

Implemented in: csharp, typescript so far — every port loads and type-checks it; the others do not act on it yet.

When to use: A view column is the result of a function the database already holds (a PL/pgSQL state machine, a legacy computation) and cannot be expressed in @expr. Declare the call instead of hand-writing the view's @sql.

Attributes