From b785d709ee5014e0361ec555c2c5d13f35850be8 Mon Sep 17 00:00:00 2001 From: v1rtl Date: Tue, 29 Sep 2026 15:50:29 +0200 Subject: [PATCH 1/3] fix(graphql): expand inline fragments instead of resolving them as a field MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The parser encoded `... on T { … }` as a field named T with nothing to tell it apart from a real field, so the executor resolved it as an unknown field ("Domain": null) and every consumer had to guess from the name. Mark inline fragments explicitly; the executor splices their selections in like a named fragment, and complexity charges them at the spread's depth like one. --- src/api/introspection_projection.zig | 9 +------- src/lib/graphql/complexity.zig | 34 ++++++++++++++++------------ src/lib/graphql/parser.zig | 32 ++++++++++++++++---------- 3 files changed, 40 insertions(+), 35 deletions(-) diff --git a/src/api/introspection_projection.zig b/src/api/introspection_projection.zig index 3f97984..4019401 100644 --- a/src/api/introspection_projection.zig +++ b/src/api/introspection_projection.zig @@ -21,17 +21,10 @@ pub const Context = struct { fragments: []const parser.Fragment, }; -const INTROSPECTION_TYPES = [_][]const u8{ "__Schema", "__Type", "__Field", "__InputValue", "__EnumValue", "__Directive" }; - fn eql(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } -fn isIntrospectionTypeName(name: []const u8) bool { - for (INTROSPECTION_TYPES) |t| if (eql(t, name)) return true; - return false; -} - /// The introspection type reached through `field` of `parent` (drives `__typename`). fn childTypeName(parent: []const u8, field: []const u8) []const u8 { if (eql(parent, "__Schema")) return if (eql(field, "directives")) "__Directive" else "__Type"; @@ -66,7 +59,7 @@ pub fn findType(ctx: Context, name: []const u8) ?std.json.Value { } fn isFragmentLike(field: *const parser.Field) bool { - return field.fragment_spread != null or (isIntrospectionTypeName(field.name) and field.selections.len > 0 and field.arguments.len == 0); + return field.fragment_spread != null or field.inline_fragment; } /// True when the selection asks for anything beyond `name` / `__typename` diff --git a/src/lib/graphql/complexity.zig b/src/lib/graphql/complexity.zig index e5ccc30..98e9346 100644 --- a/src/lib/graphql/complexity.zig +++ b/src/lib/graphql/complexity.zig @@ -158,6 +158,23 @@ pub const ComplexityAnalyzer = struct { }; } + /// A fragment's selections, spliced in at the spread's own depth. + fn analyzeSpread(self: *ComplexityAnalyzer, selections: []const parser.Field, current_depth: u32) error{OutOfMemory}!ComplexityAnalysis { + var max_depth: u32 = current_depth; + var total_cost: u32 = 0; + for (selections) |*sel| { + const sub = try self.analyzeField(sel, current_depth); + max_depth = @max(max_depth, sub.depth); + total_cost +|= sub.cost; + } + return ComplexityAnalysis{ + .depth = max_depth, + .cost = total_cost, + .exceeded_depth = max_depth > self.limits.max_depth, + .exceeded_cost = total_cost > self.limits.max_cost, + }; + } + /// Analyze a field recursively. Fragment spreads are expanded inline so /// nested selections inside fragments contribute to depth & cost just like /// inline selections. @@ -166,23 +183,10 @@ pub const ComplexityAnalyzer = struct { // Fragment spread: charge the spread location as 0 cost (it's a syntactic // marker, not a real field) and recurse into the fragment's selections at // the SAME depth. Without this, `query { ...Frag }` reports depth 1 + cost 0. + if (field.inline_fragment) return self.analyzeSpread(field.selections, current_depth); if (field.fragment_spread) |frag_name| { for (self.fragments) |*frag| { - if (std.mem.eql(u8, frag.name, frag_name)) { - var max_depth: u32 = current_depth; - var total_cost: u32 = 0; - for (frag.selections) |*sel| { - const sub = try self.analyzeField(sel, current_depth); - max_depth = @max(max_depth, sub.depth); - total_cost +|= sub.cost; - } - return ComplexityAnalysis{ - .depth = max_depth, - .cost = total_cost, - .exceeded_depth = max_depth > self.limits.max_depth, - .exceeded_cost = total_cost > self.limits.max_cost, - }; - } + if (std.mem.eql(u8, frag.name, frag_name)) return self.analyzeSpread(frag.selections, current_depth); } // Unknown fragment — charge zero, mirroring executor's permissive behavior. return ComplexityAnalysis{ diff --git a/src/lib/graphql/parser.zig b/src/lib/graphql/parser.zig index cd6d578..04252aa 100644 --- a/src/lib/graphql/parser.zig +++ b/src/lib/graphql/parser.zig @@ -365,6 +365,8 @@ pub const Field = struct { fragment_spread: ?[]const u8, // If this is a fragment spread (...FragmentName), this is the fragment name directives: []Directive, // Field directives (e.g., @skip, @include) pos: usize = 0, // Byte offset of the field's first token in the source (alias when aliased) + /// `... on T { … }`: `name` holds the type condition, `selections` the body. + inline_fragment: bool = false, pub fn deinit(self: *Field, allocator: std.mem.Allocator) void { for (self.arguments) |*arg| { @@ -937,6 +939,7 @@ pub const Parser = struct { .fragment_spread = null, // Not a named fragment spread .directives = directives, .pos = start_pos, + .inline_fragment = true, }; } @@ -1576,18 +1579,23 @@ pub const Executor = struct { continue; } - if (field.fragment_spread) |frag_name| { - // This is a fragment spread - expand it - if (self.getFragment(frag_name)) |frag| { - const frag_fields = try self.expandSelections(frag.selections); - defer self.allocator.free(frag_fields); - expanded.appendSlice(self.allocator, frag_fields) catch |err| { - self.freeExpandedFieldContents(frag_fields); - return err; - }; - } else { - std.log.warn("Unknown fragment: {s}", .{frag_name}); - } + if (field.inline_fragment or field.fragment_spread != null) { + // Schema validation has already checked that the type condition + // is the enclosing type (the schema has no interfaces or unions), + // so the fragment's fields always apply here. + const frag_selections = if (field.fragment_spread) |frag_name| + (self.getFragment(frag_name) orelse { + std.log.warn("Unknown fragment: {s}", .{frag_name}); + continue; + }).selections + else + field.selections; + const frag_fields = try self.expandSelections(frag_selections); + defer self.allocator.free(frag_fields); + expanded.appendSlice(self.allocator, frag_fields) catch |err| { + self.freeExpandedFieldContents(frag_fields); + return err; + }; continue; } From 4e9fa62aff742162fcb45f7517005e7f24ff9115 Mon Sep 17 00:00:00 2001 From: v1rtl Date: Tue, 29 Sep 2026 15:50:29 +0200 Subject: [PATCH 2/3] fix(schema): declare the fields the API serves but the schema omitted Served with real handlers but absent from schema.graphql, so invisible to introspection and about to become hard errors once selections are validated: - Domain.namehash, Domain.domain, Domain.subdomainConnection(first), Domain.eventsConnection(first) - Registration.block, Registration.blockNumber, Registration.timestamp - ResolverDetail: the 17 Resolver fields resolver(id:) and resolversByOwner serve by delegating to the per-name builder at the zero node (the resolver-wide default record on record-model resolvers) The nested connections are declared with the `first` they honour and no `after`, which they have never supported. --- schema.graphql | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/schema.graphql b/schema.graphql index ac3c6d9..12af305 100644 --- a/schema.graphql +++ b/schema.graphql @@ -457,6 +457,18 @@ type Domain { """Wrapped owner (V1 NameWrapper EOA). Null when not wrapped.""" wrappedOwner: Account + + """The namehash (ERC-137 node) of this domain; the same value as `id`.""" + namehash: String! + + """This same domain; `domain { … }` on a Domain resolves to itself.""" + domain: Domain! + + """First page of direct subdomains as a connection, ordered by name: at most `first` (default 10, max 100) with `totalCount` and `pageInfo.hasNextPage`. There is no `after` here; page further with `subdomains(first, skip)`.""" + subdomainConnection(first: Int = 10): DomainConnection! + + """Most recent events for this domain as a connection: at most `first` (default 10, max 100) with `totalCount` and `pageInfo.hasNextPage`. There is no `after` here; page further with `events` or the root `eventConnection(where: { namehash })`.""" + eventsConnection(first: Int = 10): EventConnection! } """An Ethereum account (address)""" @@ -687,6 +699,15 @@ type Registration { """Timestamp when domain was registered""" registrationDate: Int! + """Block number of the registration event.""" + blockNumber: Int! + + """Block number of the registration event; the same value as `blockNumber`.""" + block: Int! + + """Timestamp of the registration event; the same value as `registrationDate`.""" + timestamp: Int! + """Timestamp when domain expires""" expiryDate: Int! @@ -1290,6 +1311,57 @@ type ResolverDetail { """Resource-name associations announced by this resolver (EAC resource naming; emitted on the first role grant per resource)""" namedResources: [NamedResourceEntry!]! + + """Canonical Domain associated with this resolver (first by namehash). Null when this resolver isn't bound to any name.""" + domain: Domain + + """True when the resolver announced itself as record-model (ResolverCreated).""" + recordModel: Boolean! + + """Address record for a coin type (default 60, ETH). ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + addr(coinType: Int = 60): String + + """All set addresses across coin types. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + addresses: [CoinAddress!] + + """All set coin types as decimal strings. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + coinTypes: [String!] + + """Content hash. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + contentHash: String + + """Text-record keys (keys only; read values with `text(key:)`). ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + texts: [String!] + + """A text record value by key. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + text(key: String!): String + + """Public key record. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + pubkey: Pubkey + + """ABI content types. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + abis: [Int!] + + """Reverse name record. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + reverseName: String + + """Interface implementations. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + interfaces: [InterfaceRecord!] + + """Version counter. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + version: Int + + """Record the zero node resolves through, as a decimal string. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + recordId: String + + """Names bound to the same record as the zero node. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + linkedNames: [LinkedName!] + + """ENSIP-24 data(key) record as 0x-hex bytes. ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + data(key: String!): String + + """ENSIP-24 data keys (keys only; read values with `data(key:)`). ResolverDetail has no name context, so this reads the zero node (0x0): on a record-model resolver that is the resolver-wide default record, on a legacy resolver it is usually empty.""" + dataKeys: [String!] } """An EAC resource id and the name/record it guards on a resolver. Legacy resolvers announce it per name (Named*Resource); record-model resolvers announce it per setter ARGUMENT (ResourceArgument): `name` is then empty, `recordKey` carries the argument (text/data key, or 0x-hex for interface ids), `coinType` its integer value (coin type or ABI content type), and `recordKind` is derived from the setter roles granted on the resource — one entry per kind, or `argument` before any grant is indexed.""" From 44a131fe8517c171cbd798160c76d0720a4bc1c7 Mon Sep 17 00:00:00 2001 From: v1rtl Date: Tue, 29 Sep 2026 15:50:29 +0200 Subject: [PATCH 3/3] fix(api): validate the whole selection set against the schema An unknown field in a selection set resolved to null, indistinguishable from a genuine absence, and arguments were only checked on root fields: { domains(where:{bogus:1}) } was a 400 while the same typo one level down silently dropped the filter. The validator now walks every operation at every depth, through named, inline and root-level fragments, and rejects unknown fields, unknown or missing arguments and unknown input-object fields (including inside lists) wherever they appear. Fragment type conditions must name the enclosing type, since the schema has no interfaces or unions. Named fragments are walked once per operation, and keys are built on the stack instead of allocated per selection. Also fixes a false rejection: a fragment spread at the root named after a root field was validated as that field and failed its required-arg check. Unknown root fields keep the executor's UnknownRootField. --- src/api/handler.zig | 25 +- src/api/schema_validator.zig | 429 +++++++++++++----- .../golden/err_fragment_wrong_type.json | 1 + .../conformance/golden/err_unknown_field.json | 1 + .../golden/err_unknown_fragment_field.json | 1 + .../golden/err_unknown_nested_argument.json | 1 + .../golden/err_unknown_nested_field.json | 1 + .../err_unknown_nested_where_field.json | 1 + .../err_unknown_root_fragment_field.json | 1 + .../golden/lenient_unknown_field.json | 1 - .../golden/ok_declared_domain_fields.json | 1 + .../ok_declared_registration_fields.json | 1 + .../ok_declared_resolver_detail_fields.json | 1 + .../conformance/golden/ok_root_fragment.json | 1 + .../golden/ok_typename_and_fragments.json | 1 + tests/conformance/runner.zig | 29 +- 16 files changed, 353 insertions(+), 143 deletions(-) create mode 100644 tests/conformance/golden/err_fragment_wrong_type.json create mode 100644 tests/conformance/golden/err_unknown_field.json create mode 100644 tests/conformance/golden/err_unknown_fragment_field.json create mode 100644 tests/conformance/golden/err_unknown_nested_argument.json create mode 100644 tests/conformance/golden/err_unknown_nested_field.json create mode 100644 tests/conformance/golden/err_unknown_nested_where_field.json create mode 100644 tests/conformance/golden/err_unknown_root_fragment_field.json delete mode 100644 tests/conformance/golden/lenient_unknown_field.json create mode 100644 tests/conformance/golden/ok_declared_domain_fields.json create mode 100644 tests/conformance/golden/ok_declared_registration_fields.json create mode 100644 tests/conformance/golden/ok_declared_resolver_detail_fields.json create mode 100644 tests/conformance/golden/ok_root_fragment.json create mode 100644 tests/conformance/golden/ok_typename_and_fragments.json diff --git a/src/api/handler.zig b/src/api/handler.zig index 35ba726..ce3b0d2 100644 --- a/src/api/handler.zig +++ b/src/api/handler.zig @@ -118,16 +118,14 @@ pub const GraphQLHandler = struct { self.introspection_parsed.deinit(); } - /// Walk the parsed operations and validate each root field against the - /// schema. The validator skips meta fields (`__typename`, `__schema`, …) - /// and unknown root field names (those are surfaced separately by the - /// executor as `UnknownRootField`). - fn validateDocumentArgs(self: *GraphQLHandler, document: *const parser.Document) schema_validator_mod.SchemaValidator.Error!void { + /// Validate every operation's selection set against the schema. The + /// validator skips meta fields (`__typename`, `__schema`, …) and unknown + /// root field names (those are surfaced separately by the executor as + /// `UnknownRootField`). + fn validateDocument(self: *GraphQLHandler, allocator: std.mem.Allocator, document: *const parser.Document) schema_validator_mod.SchemaValidator.Error!void { schema_validator_mod.clearDiag(); - for (document.operations) |op| { - for (op.fields) |*field| { - try self.schema_validator.validateRootField(field); - } + for (document.operations) |*op| { + try self.schema_validator.validateOperation(allocator, op, document.fragments); } } @@ -287,12 +285,13 @@ pub const GraphQLHandler = struct { std.log.debug("Query complexity: depth={d}, cost={d}", .{ analysis.depth, analysis.cost }); // Schema validation pass — runs against the parsed document before any - // resolver runs. Catches missing required args, unknown args, and - // unknown fields inside input objects. Replaces per-resolver manual + // resolver runs. Catches missing required args, unknown args, unknown + // fields in selection sets and input objects, and fragments on the + // wrong type, at every depth. Replaces per-resolver manual // checks for the generic-cases (specific InvalidAddress / TooManyNames // / etc. type errors stay in the resolvers — they need value-level // context that schema validation can't see). - if (self.validateDocumentArgs(&document)) {} else |val_err| { + if (self.validateDocument(request_alloc, &document)) {} else |val_err| { self.metrics.recordError(); // Stable message-family prefixes (external detectors match on them and // on extensions.code); the tail names the offending field/argument and @@ -302,6 +301,8 @@ pub const GraphQLHandler = struct { error.MissingRequiredArg => "Missing required argument", error.UnknownArgument => "Unknown argument", error.UnknownInputObjectField => "Unknown field in input object", + error.UnknownField => "Unknown field", + error.InvalidFragmentType => "Invalid fragment", else => "Query validation failed", }; var msg_buf: [280]u8 = undefined; diff --git a/src/api/schema_validator.zig b/src/api/schema_validator.zig index e749e1f..96d37a6 100644 --- a/src/api/schema_validator.zig +++ b/src/api/schema_validator.zig @@ -1,24 +1,30 @@ -/// Schema-driven argument validation for incoming GraphQL queries. +/// Schema-driven query validation for incoming GraphQL queries. /// /// Loads the introspection JSON once at handler-init time and uses it to -/// validate every request before it reaches the executor. Catches three -/// classes of bug that previously slipped through and degraded into -/// silent-null results: +/// validate every request before it reaches the executor. Walks every +/// operation's selection set — at every depth, through named and inline +/// fragments — and rejects what used to degrade into silent nulls or +/// silently dropped arguments: /// 1. **Missing required args** — e.g. `domain { name }` (no `id:` on a /// field declared as `id: String!`). -/// 2. **Unknown args on root fields** — e.g. `domains(badArg: 1)`. +/// 2. **Unknown args** — e.g. `domains(badArg: 1)`, or a nested +/// `subdomains(bogus: 1)`. /// 3. **Unknown fields inside input objects** — e.g. -/// `domains(where: { totallyBogus: 1 })`. This generalizes the manual -/// `UnknownFilterArg` check we had to thread through each resolver. +/// `domains(where: { totallyBogus: 1 })`, at any depth. +/// 4. **Unknown fields in a selection set** — e.g. `domains { notAField }`, +/// which used to resolve to null, indistinguishable from a genuine absence. +/// 5. **Fragments on the wrong type** — the schema has no interfaces or +/// unions, so a type condition must name the enclosing type exactly. /// /// The check is purely structural — it doesn't enforce scalar-type /// agreement (Int vs String etc.) because the runtime arg parser already /// surfaces type-mismatch as targeted errors (e.g. InvalidAddress). +/// Unknown root fields are left to the executor's `UnknownRootField`, and +/// `__`-prefixed meta fields to introspection. /// -/// Flat-key storage: composite keys like `"Query.domains.first"` and -/// `"DomainFilter.name_in"` keep ownership simple — one HashMap per kind, -/// freed wholesale in `deinit`. An earlier nested-HashMap version leaked -/// buckets on test teardown, so we keep it flat for clarity. +/// Flat-key storage: composite keys like `"Domain.subdomains"` and +/// `"Domain.subdomains.first"` keep ownership simple — one HashMap per kind, +/// freed wholesale in `deinit`. Lookups build the key on the stack. const std = @import("std"); const parser = @import("../lib/graphql/parser.zig"); @@ -63,25 +69,35 @@ pub fn clearDiag() void { pub const SchemaValidator = struct { allocator: std.mem.Allocator, - /// `"{root_field}.{arg}" → ArgSpec` for every (root field, arg) pair. - root_field_args: std.StringHashMap(ArgSpec), - /// All root-field names that *have at least one declared arg* — used - /// to know whether to also validate against `root_field_args`. - root_fields_present: std.StringHashMap(void), + /// `"{ObjectType}.{field}" → FieldSpec` for every OBJECT type, Query included. + fields: std.StringHashMap(FieldSpec), + /// `"{ObjectType}.{field}.{arg}" → ArgSpec` for every declared argument. + field_args: std.StringHashMap(ArgSpec), + /// All OBJECT type names: the composite types a selection set can apply to. + object_types: std.StringHashMap(void), /// `"{InputType}.{field}" → ArgSpec` for every (input type, field) pair. input_object_fields: std.StringHashMap(ArgSpec), /// All input-object type names we know about. If a type name isn't in /// here, we skip its validation (can't know what fields are allowed). input_object_types_present: std.StringHashMap(void), + /// Root operation type name, the entry point for selection validation. + query_type_name: []const u8, - /// Owned key buffers. Composite keys live on the heap (we allocPrint - /// them); freeing happens in bulk on deinit. + /// Owned key and name buffers, freed in bulk on deinit. owned_keys: std.ArrayList([]u8), + /// Owned `FieldSpec.required_args` slices. + owned_lists: std.ArrayList([][]const u8), + + pub const FieldSpec = struct { + /// Named type the field leads to, list and non-null wrappers stripped. + type_name: []const u8, + /// Declared arguments of non-null type. + required_args: []const []const u8, + }; pub const ArgSpec = struct { required: bool, - /// "SCALAR" / "ENUM" / "LIST" / "INPUT_OBJECT" / etc. — we only act - /// on INPUT_OBJECT to know whether to recurse. + /// "SCALAR" / "ENUM" / "INPUT_OBJECT" / etc. of the eventual leaf. inner_kind: []const u8, /// Type name of the eventual leaf, e.g. "DomainFilter". inner_type_name: []const u8, @@ -91,9 +107,13 @@ pub const SchemaValidator = struct { MissingRequiredArg, UnknownArgument, UnknownInputObjectField, + UnknownField, + InvalidFragmentType, OutOfMemory, }; + const KEY_MAX = 512; + pub fn init(allocator: std.mem.Allocator, introspection_json: []const u8) !SchemaValidator { var parsed = try std.json.parseFromSlice(std.json.Value, allocator, introspection_json, .{}); defer parsed.deinit(); @@ -105,14 +125,19 @@ pub const SchemaValidator = struct { var validator = SchemaValidator{ .allocator = allocator, - .root_field_args = std.StringHashMap(ArgSpec).init(allocator), - .root_fields_present = std.StringHashMap(void).init(allocator), + .fields = std.StringHashMap(FieldSpec).init(allocator), + .field_args = std.StringHashMap(ArgSpec).init(allocator), + .object_types = std.StringHashMap(void).init(allocator), .input_object_fields = std.StringHashMap(ArgSpec).init(allocator), .input_object_types_present = std.StringHashMap(void).init(allocator), + .query_type_name = "", .owned_keys = .empty, + .owned_lists = .empty, }; errdefer validator.deinit(); + validator.query_type_name = try validator.own(query_type_name); + for (types_arr.items) |type_item| { const type_obj = type_item.object; const kind = type_obj.get("kind").?.string; @@ -120,32 +145,17 @@ pub const SchemaValidator = struct { if (name_val != .string) continue; const type_name = name_val.string; - if (std.mem.eql(u8, kind, "OBJECT") and std.mem.eql(u8, type_name, query_type_name)) { - const fields = type_obj.get("fields").?.array; - for (fields.items) |field_item| { - const f = field_item.object; - const fname = f.get("name").?.string; - // Track that this root field exists with at least the - // ability to receive args (even if zero args declared). - const field_key = try allocator.dupe(u8, fname); - try validator.owned_keys.append(allocator, field_key); - try validator.root_fields_present.put(field_key, {}); - const args = f.get("args").?.array; - for (args.items) |arg_item| { - const a = arg_item.object; - const aname = a.get("name").?.string; - const spec = parseArgSpec(a.get("type").?, allocator, &validator.owned_keys); - const key = try std.fmt.allocPrint(allocator, "{s}.{s}", .{ fname, aname }); - try validator.owned_keys.append(allocator, key); - try validator.root_field_args.put(key, spec); - } + if (std.mem.eql(u8, kind, "OBJECT")) { + try validator.object_types.put(try validator.own(type_name), {}); + const fields_val = type_obj.get("fields") orelse continue; + if (fields_val != .array) continue; + for (fields_val.array.items) |field_item| { + try validator.addField(type_name, field_item.object); } } else if (std.mem.eql(u8, kind, "INPUT_OBJECT")) { const input_fields = type_obj.get("inputFields") orelse continue; if (input_fields != .array) continue; - const type_key = try allocator.dupe(u8, type_name); - try validator.owned_keys.append(allocator, type_key); - try validator.input_object_types_present.put(type_key, {}); + try validator.input_object_types_present.put(try validator.own(type_name), {}); for (input_fields.array.items) |field_item| { const f = field_item.object; const fname = f.get("name").?.string; @@ -159,70 +169,181 @@ pub const SchemaValidator = struct { return validator; } + fn own(self: *SchemaValidator, text: []const u8) ![]const u8 { + const copy = try self.allocator.dupe(u8, text); + errdefer self.allocator.free(copy); + try self.owned_keys.append(self.allocator, copy); + return copy; + } + + fn addField(self: *SchemaValidator, type_name: []const u8, f: std.json.ObjectMap) !void { + const fname = f.get("name").?.string; + // A field with no declared type still exists; an empty child type + // lets the name validate while recursion stops there. + const type_val = f.get("type") orelse std.json.Value{ .null = {} }; + const leaf = if (type_val == .object) parseArgSpec(type_val, self.allocator, &self.owned_keys).inner_type_name else ""; + + var required: std.ArrayList([]const u8) = .empty; + defer required.deinit(self.allocator); + if (f.get("args")) |args_val| { + if (args_val == .array) { + for (args_val.array.items) |arg_item| { + const a = arg_item.object; + const aname = try self.own(a.get("name").?.string); + const spec = parseArgSpec(a.get("type").?, self.allocator, &self.owned_keys); + const key = try std.fmt.allocPrint(self.allocator, "{s}.{s}.{s}", .{ type_name, fname, aname }); + try self.owned_keys.append(self.allocator, key); + try self.field_args.put(key, spec); + if (spec.required) try required.append(self.allocator, aname); + } + } + } + const required_owned = try required.toOwnedSlice(self.allocator); + errdefer self.allocator.free(required_owned); + try self.owned_lists.append(self.allocator, required_owned); + + const key = try std.fmt.allocPrint(self.allocator, "{s}.{s}", .{ type_name, fname }); + try self.owned_keys.append(self.allocator, key); + try self.fields.put(key, .{ .type_name = leaf, .required_args = required_owned }); + } + pub fn deinit(self: *SchemaValidator) void { - self.root_field_args.deinit(); - self.root_fields_present.deinit(); + self.fields.deinit(); + self.field_args.deinit(); + self.object_types.deinit(); self.input_object_fields.deinit(); self.input_object_types_present.deinit(); for (self.owned_keys.items) |k| self.allocator.free(k); self.owned_keys.deinit(self.allocator); + for (self.owned_lists.items) |l| self.allocator.free(l); + self.owned_lists.deinit(self.allocator); } - /// Validates one root field selection. Skips meta fields (`__typename` etc.) - /// and unknown root field names (those are surfaced separately by the - /// executor as `UnknownRootField`). - pub fn validateRootField(self: *SchemaValidator, field: *const parser.Field) Error!void { - if (std.mem.startsWith(u8, field.name, "__")) return; - if (!self.root_fields_present.contains(field.name)) return; - - // Each present arg: declared on the root field? - for (field.arguments) |arg| { - const composite = try std.fmt.allocPrint(self.allocator, "{s}.{s}", .{ field.name, arg.name }); - defer self.allocator.free(composite); - const spec = self.root_field_args.get(composite) orelse { - std.log.warn("validateRootField: `{s}` got unknown arg `{s}`", .{ field.name, arg.name }); - setDiag(arg.pos, "`{s}` has no argument `{s}`", .{ field.name, arg.name }); - return error.UnknownArgument; - }; - if (arg.value == .object) { - try self.validateInputObject(spec.inner_type_name, arg.value.object, arg.pos); + /// Validate one operation's whole selection set. `allocator` backs the + /// per-call fragment memo (the validator itself is shared across threads). + pub fn validateOperation(self: *const SchemaValidator, allocator: std.mem.Allocator, operation: *const parser.Operation, fragments: []const parser.Fragment) Error!void { + var walk = Walk{ .validator = self, .fragments = fragments, .validated = std.StringHashMap(void).init(allocator) }; + defer walk.validated.deinit(); + try walk.selectionSet(self.query_type_name, operation.fields); + } + + const Walk = struct { + validator: *const SchemaValidator, + fragments: []const parser.Fragment, + /// Named fragments already walked. A fragment's type condition is + /// fixed, so its body only needs checking once per operation; each + /// spread site still checks that the condition fits where it is used. + validated: std.StringHashMap(void), + + fn selectionSet(self: *Walk, type_name: []const u8, selections: []const parser.Field) Error!void { + for (selections) |*sel| { + if (sel.fragment_spread) |frag_name| { + // Undefined fragments are rejected earlier (query_validator). + const frag = self.findFragment(frag_name) orelse continue; + try self.typeCondition(type_name, frag.type_condition, sel.pos); + const gop = try self.validated.getOrPut(frag.name); + if (gop.found_existing) continue; + try self.selectionSet(frag.type_condition, frag.selections); + continue; + } + if (sel.inline_fragment) { + try self.typeCondition(type_name, sel.name, sel.pos); + try self.selectionSet(type_name, sel.selections); + continue; + } + try self.field(type_name, sel); } } - // Required args: each schema-required arg present? - var prefix_buf: [256]u8 = undefined; - const prefix = std.fmt.bufPrint(&prefix_buf, "{s}.", .{field.name}) catch return; - var it = self.root_field_args.iterator(); - while (it.next()) |entry| { - const key = entry.key_ptr.*; - if (!std.mem.startsWith(u8, key, prefix)) continue; - if (!entry.value_ptr.required) continue; - const arg_name = key[prefix.len..]; - if (!hasArg(field, arg_name)) { - std.log.warn("validateRootField: `{s}` requires arg `{s}`", .{ field.name, arg_name }); - setDiag(field.pos, "`{s}` requires argument `{s}`", .{ field.name, arg_name }); + fn field(self: *Walk, type_name: []const u8, sel: *const parser.Field) Error!void { + if (std.mem.startsWith(u8, sel.name, "__")) return; + const v = self.validator; + const is_root = std.mem.eql(u8, type_name, v.query_type_name); + + var key_buf: [KEY_MAX]u8 = undefined; + const key = std.fmt.bufPrint(&key_buf, "{s}.{s}", .{ type_name, sel.name }) catch null; + const spec = (if (key) |k| v.fields.get(k) else null) orelse { + if (is_root) return; + std.log.warn("schema validation: `{s}` has no field `{s}`", .{ type_name, sel.name }); + setDiag(sel.pos, "`{s}` has no field `{s}`", .{ type_name, sel.name }); + return error.UnknownField; + }; + + for (sel.arguments) |arg| { + var arg_buf: [KEY_MAX]u8 = undefined; + const arg_key = std.fmt.bufPrint(&arg_buf, "{s}.{s}.{s}", .{ type_name, sel.name, arg.name }) catch null; + const arg_spec = (if (arg_key) |k| v.field_args.get(k) else null) orelse { + std.log.warn("schema validation: `{s}.{s}` got unknown arg `{s}`", .{ type_name, sel.name, arg.name }); + if (is_root) { + setDiag(arg.pos, "`{s}` has no argument `{s}`", .{ sel.name, arg.name }); + } else { + setDiag(arg.pos, "`{s}.{s}` has no argument `{s}`", .{ type_name, sel.name, arg.name }); + } + return error.UnknownArgument; + }; + try v.validateInputValue(arg_spec.inner_type_name, arg.value, arg.pos); + } + for (spec.required_args) |arg_name| { + if (hasArg(sel, arg_name)) continue; + std.log.warn("schema validation: `{s}.{s}` requires arg `{s}`", .{ type_name, sel.name, arg_name }); + if (is_root) { + setDiag(sel.pos, "`{s}` requires argument `{s}`", .{ sel.name, arg_name }); + } else { + setDiag(sel.pos, "`{s}.{s}` requires argument `{s}`", .{ type_name, sel.name, arg_name }); + } return error.MissingRequiredArg; } + + // A subselection on a scalar is left to the executor, whose + // SubSelectionOnScalar message says more than "unknown field". + if (sel.selections.len > 0 and v.object_types.contains(spec.type_name)) { + try self.selectionSet(spec.type_name, sel.selections); + } + } + + fn typeCondition(self: *Walk, enclosing: []const u8, condition: []const u8, pos: usize) Error!void { + if (std.mem.eql(u8, enclosing, condition)) return; + if (!self.validator.object_types.contains(condition)) { + setDiag(pos, "unknown type `{s}` in a fragment type condition", .{condition}); + } else { + setDiag(pos, "a fragment on `{s}` cannot be spread where `{s}` is expected", .{ condition, enclosing }); + } + return error.InvalidFragmentType; + } + + fn findFragment(self: *Walk, name: []const u8) ?*const parser.Fragment { + for (self.fragments) |*frag| { + if (std.mem.eql(u8, frag.name, name)) return frag; + } + return null; + } + }; + + /// An argument value against its declared type: input objects are checked + /// field by field, including inside lists (`where: { or: [ { … } ] }`). + fn validateInputValue(self: *const SchemaValidator, type_name: []const u8, value: parser.Value, pos: usize) Error!void { + switch (value) { + .object => |obj| try self.validateInputObject(type_name, obj, pos), + .list => |items| for (items) |item| try self.validateInputValue(type_name, item, pos), + else => {}, } } /// `ctx_pos` — byte offset of the argument/field that holds this input /// object; anchors the missing-required-field error, which has no node /// of its own to point at. - fn validateInputObject(self: *SchemaValidator, type_name: []const u8, args: []parser.Argument, ctx_pos: usize) Error!void { + fn validateInputObject(self: *const SchemaValidator, type_name: []const u8, args: []parser.Argument, ctx_pos: usize) Error!void { if (!self.input_object_types_present.contains(type_name)) return; for (args) |a| { - const composite = try std.fmt.allocPrint(self.allocator, "{s}.{s}", .{ type_name, a.name }); - defer self.allocator.free(composite); - const spec = self.input_object_fields.get(composite) orelse { + var key_buf: [KEY_MAX]u8 = undefined; + const key = std.fmt.bufPrint(&key_buf, "{s}.{s}", .{ type_name, a.name }) catch null; + const spec = (if (key) |k| self.input_object_fields.get(k) else null) orelse { std.log.warn("validateInputObject: `{s}` has no field `{s}`", .{ type_name, a.name }); setDiag(a.pos, "`{s}` has no field `{s}`", .{ type_name, a.name }); return error.UnknownInputObjectField; }; - if (a.value == .object) { - try self.validateInputObject(spec.inner_type_name, a.value.object, a.pos); - } + try self.validateInputValue(spec.inner_type_name, a.value, a.pos); } var prefix_buf: [256]u8 = undefined; @@ -295,78 +416,138 @@ fn parseArgSpec(type_val: std.json.Value, allocator: std.mem.Allocator, owned_ke const testing = std.testing; -// Minimal introspection: `thing(id: String!, where: ThingFilter)` where -// ThingFilter declares `ok: Int` and `must: Int!` — enough to drive all four -// diagnostic paths without depending on the real schema. +// Minimal introspection: `thing(id: String!, where: ThingFilter)` returning +// Thing, whose nested fields carry arguments of their own; ThingFilter +// declares `ok: Int`, `must: Int!` and a recursive `or: [ThingFilter!]`. const TEST_INTROSPECTION = \\{"data":{"__schema":{"queryType":{"name":"Query"},"types":[ \\{"kind":"OBJECT","name":"Query","fields":[ - \\{"name":"thing","args":[ + \\{"name":"thing","type":{"kind":"OBJECT","name":"Thing"},"args":[ \\{"name":"id","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String"}}}, \\{"name":"where","type":{"kind":"INPUT_OBJECT","name":"ThingFilter"}}]}]}, + \\{"kind":"OBJECT","name":"Thing","fields":[ + \\{"name":"id","type":{"kind":"SCALAR","name":"String"},"args":[]}, + \\{"name":"texts","type":{"kind":"LIST","name":null,"ofType":{"kind":"SCALAR","name":"String"}},"args":[]}, + \\{"name":"text","type":{"kind":"SCALAR","name":"String"},"args":[ + \\{"name":"key","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"String"}}}]}, + \\{"name":"children","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"LIST","name":null,"ofType":{"kind":"OBJECT","name":"Thing"}}},"args":[ + \\{"name":"first","type":{"kind":"SCALAR","name":"Int"}}, + \\{"name":"where","type":{"kind":"INPUT_OBJECT","name":"ThingFilter"}}]}, + \\{"name":"child","type":{"kind":"OBJECT","name":"Thing"},"args":[]}]}, + \\{"kind":"OBJECT","name":"Other","fields":[ + \\{"name":"id","type":{"kind":"SCALAR","name":"String"},"args":[]}]}, \\{"kind":"INPUT_OBJECT","name":"ThingFilter","inputFields":[ \\{"name":"ok","type":{"kind":"SCALAR","name":"Int"}}, + \\{"name":"or","type":{"kind":"LIST","name":null,"ofType":{"kind":"NON_NULL","name":null,"ofType":{"kind":"INPUT_OBJECT","name":"ThingFilter"}}}}, \\{"name":"must","type":{"kind":"NON_NULL","name":null,"ofType":{"kind":"SCALAR","name":"Int"}}}]} \\]}}} ; -// Validate `query` against TEST_INTROSPECTION and assert the error, the -// diagnostic text, and that the diagnostic position lands on `anchor` -// (its first occurrence in the query source). -fn expectDiag(query: []const u8, expected_err: anyerror, expected_text: []const u8, anchor: []const u8) !void { +fn validate(query: []const u8) !void { var validator = try SchemaValidator.init(testing.allocator, TEST_INTROSPECTION); defer validator.deinit(); var doc = try parser.parseQuery(testing.allocator, query); defer doc.deinit(testing.allocator); clearDiag(); - try testing.expectError(expected_err, validator.validateRootField(&doc.operations[0].fields[0])); + for (doc.operations) |*op| try validator.validateOperation(testing.allocator, op, doc.fragments); +} + +// Assert the error, the diagnostic text, and that the diagnostic position +// lands on `anchor` (its first occurrence in the query source). +fn expectDiag(query: []const u8, expected_err: anyerror, expected_text: []const u8, anchor: []const u8) !void { + try testing.expectError(expected_err, validate(query)); try testing.expectEqualStrings(expected_text, lastDiagnostic().?); try testing.expectEqual(std.mem.indexOf(u8, query, anchor).?, lastDiagnosticPos().?); } +fn expectOk(query: []const u8) !void { + try validate(query); + try testing.expect(lastDiagnostic() == null); + try testing.expectEqual(@as(?usize, null), lastDiagnosticPos()); +} + test "unknown argument: diagnostic names it and anchors at the argument" { - try expectDiag( - "{ thing(id: \"x\", nope: 1) { id } }", - error.UnknownArgument, - "`thing` has no argument `nope`", - "nope", - ); + try expectDiag("{ thing(id: \"x\", nope: 1) { id } }", error.UnknownArgument, "`thing` has no argument `nope`", "nope"); } test "missing required root argument: anchors at the field" { - try expectDiag( - "{ thing(where: {ok: 1, must: 2}) { id } }", - error.MissingRequiredArg, - "`thing` requires argument `id`", - "thing", - ); + try expectDiag("{ thing(where: {ok: 1, must: 2}) { id } }", error.MissingRequiredArg, "`thing` requires argument `id`", "thing"); } test "unknown input-object field: anchors at the offending field" { - try expectDiag( - "{ thing(id: \"x\", where: {bogus: 1, must: 2}) { id } }", - error.UnknownInputObjectField, - "`ThingFilter` has no field `bogus`", - "bogus", - ); + try expectDiag("{ thing(id: \"x\", where: {bogus: 1, must: 2}) { id } }", error.UnknownInputObjectField, "`ThingFilter` has no field `bogus`", "bogus"); } test "missing required input-object field: anchors at the enclosing argument" { - try expectDiag( - "{ thing(id: \"x\", where: {ok: 1}) { id } }", - error.MissingRequiredArg, - "`ThingFilter` requires field `must`", - "where", - ); + try expectDiag("{ thing(id: \"x\", where: {ok: 1}) { id } }", error.MissingRequiredArg, "`ThingFilter` requires field `must`", "where"); +} + +test "input objects inside lists are checked" { + try expectDiag("{ thing(id: \"x\", where: {must: 1, or: [{must: 2}, {must: 3, bogus: 4}]}) { id } }", error.UnknownInputObjectField, "`ThingFilter` has no field `bogus`", "bogus"); } test "valid query leaves no diagnostic" { - var validator = try SchemaValidator.init(testing.allocator, TEST_INTROSPECTION); - defer validator.deinit(); - var doc = try parser.parseQuery(testing.allocator, "{ thing(id: \"x\", where: {ok: 1, must: 2}) { id } }"); - defer doc.deinit(testing.allocator); - clearDiag(); - try validator.validateRootField(&doc.operations[0].fields[0]); - try testing.expect(lastDiagnostic() == null); - try testing.expectEqual(@as(?usize, null), lastDiagnosticPos()); + try expectOk("{ thing(id: \"x\", where: {ok: 1, must: 2, or: [{must: 3}]}) { id } }"); +} + +test "unknown selection field: names the type and anchors at the field" { + try expectDiag("{ thing(id: \"x\") { nope } }", error.UnknownField, "`Thing` has no field `nope`", "nope"); +} + +test "unknown selection field is caught at depth" { + try expectDiag("{ thing(id: \"x\") { child { child { nope } } } }", error.UnknownField, "`Thing` has no field `nope`", "nope"); +} + +test "nested arguments get the same checks as root arguments" { + // The same typo must not be a 400 at the root and a silently dropped + // filter one level down. + try expectDiag("{ thing(id: \"x\") { children(bogus: 1) { id } } }", error.UnknownArgument, "`Thing.children` has no argument `bogus`", "bogus"); + try expectDiag("{ thing(id: \"x\") { children(where: {must: 1, bogus: 2}) { id } } }", error.UnknownInputObjectField, "`ThingFilter` has no field `bogus`", "bogus"); + try expectDiag("{ thing(id: \"x\") { child { text } } }", error.MissingRequiredArg, "`Thing.text` requires argument `key`", "text"); + try expectOk("{ thing(id: \"x\") { children(first: 2, where: {must: 1}) { text(key: \"k\") } } }"); +} + +test "unknown field inside a named fragment is caught against its type condition" { + try expectDiag("query Q { thing(id: \"x\") { ...F } } fragment F on Thing { nope }", error.UnknownField, "`Thing` has no field `nope`", "nope"); +} + +test "root-level fragment spreads are validated" { + try expectDiag("query Q { ...Root } fragment Root on Query { thing(id: \"x\") { nope } }", error.UnknownField, "`Thing` has no field `nope`", "nope"); + try expectDiag("query Q { ...Root } fragment Root on Query { thing { id } }", error.MissingRequiredArg, "`thing` requires argument `id`", "thing {"); + try expectOk("query Q { ...Root } fragment Root on Query { thing(id: \"x\") { id } }"); +} + +test "a fragment named after a root field is not mistaken for that field" { + try expectOk("query Q { ...thing } fragment thing on Query { thing(id: \"x\") { id } }"); +} + +test "fragment type conditions must name the enclosing type" { + try expectDiag("{ thing(id: \"x\") { ... on Other { id } } }", error.InvalidFragmentType, "a fragment on `Other` cannot be spread where `Thing` is expected", "..."); + try expectDiag("query Q { thing(id: \"x\") { ...F } } fragment F on Other { id }", error.InvalidFragmentType, "a fragment on `Other` cannot be spread where `Thing` is expected", "...F"); + try expectDiag("{ thing(id: \"x\") { ... on Nope { id } } }", error.InvalidFragmentType, "unknown type `Nope` in a fragment type condition", "..."); +} + +test "valid selections pass: nesting, aliases, __typename, fragments" { + try expectOk("{ thing(id: \"x\") { id child { id } } }"); + try expectOk("{ thing(id: \"x\") { __typename alias: id } }"); + try expectOk("query Q { thing(id: \"x\") { ...F child { ...F } } } fragment F on Thing { id child { id } }"); + try expectOk("{ thing(id: \"x\") { ... on Thing { id } } }"); + // An inline fragment is recognised by the parser, not guessed from its + // name, so an empty one is fine too. + try expectOk("{ thing(id: \"x\") { id ... on Thing { } } }"); +} + +test "a subselection on a scalar is left to the executor, not reported as unknown" { + // SubSelectionOnScalar carries a better message than "unknown field". + try expectOk("{ thing(id: \"x\") { texts { key } } }"); +} + +test "an unknown root field is left to the executor" { + // UnknownRootField has its own error text. + try expectOk("{ notARealRootField { nope } }"); +} + +test "an overlong field name is reported as unknown, not truncated into a match" { + const long = "a" ** 600; + try testing.expectError(error.UnknownField, validate("{ thing(id: \"x\") { " ++ long ++ " } }")); } diff --git a/tests/conformance/golden/err_fragment_wrong_type.json b/tests/conformance/golden/err_fragment_wrong_type.json new file mode 100644 index 0000000..1e4eb51 --- /dev/null +++ b/tests/conformance/golden/err_fragment_wrong_type.json @@ -0,0 +1 @@ +{"errors":[{"message":"Invalid fragment: a fragment on `Account` cannot be spread where `Domain` is expected.","locations":[{"line":1,"column":21}],"extensions":{"code":"VALIDATION_ERROR"}}],"data":null} \ No newline at end of file diff --git a/tests/conformance/golden/err_unknown_field.json b/tests/conformance/golden/err_unknown_field.json new file mode 100644 index 0000000..90ffb5c --- /dev/null +++ b/tests/conformance/golden/err_unknown_field.json @@ -0,0 +1 @@ +{"errors":[{"message":"Unknown field: `Domain` has no field `notARealField`.","locations":[{"line":1,"column":21}],"extensions":{"code":"VALIDATION_ERROR"}}],"data":null} \ No newline at end of file diff --git a/tests/conformance/golden/err_unknown_fragment_field.json b/tests/conformance/golden/err_unknown_fragment_field.json new file mode 100644 index 0000000..e955f71 --- /dev/null +++ b/tests/conformance/golden/err_unknown_fragment_field.json @@ -0,0 +1 @@ +{"errors":[{"message":"Unknown field: `Domain` has no field `notARealField`.","locations":[{"line":1,"column":61}],"extensions":{"code":"VALIDATION_ERROR"}}],"data":null} \ No newline at end of file diff --git a/tests/conformance/golden/err_unknown_nested_argument.json b/tests/conformance/golden/err_unknown_nested_argument.json new file mode 100644 index 0000000..5e8ac9b --- /dev/null +++ b/tests/conformance/golden/err_unknown_nested_argument.json @@ -0,0 +1 @@ +{"errors":[{"message":"Unknown argument: `Domain.subdomains` has no argument `bogus`.","locations":[{"line":1,"column":32}],"extensions":{"code":"VALIDATION_ERROR"}}],"data":null} \ No newline at end of file diff --git a/tests/conformance/golden/err_unknown_nested_field.json b/tests/conformance/golden/err_unknown_nested_field.json new file mode 100644 index 0000000..917c35e --- /dev/null +++ b/tests/conformance/golden/err_unknown_nested_field.json @@ -0,0 +1 @@ +{"errors":[{"message":"Unknown field: `Account` has no field `notARealField`.","locations":[{"line":1,"column":29}],"extensions":{"code":"VALIDATION_ERROR"}}],"data":null} \ No newline at end of file diff --git a/tests/conformance/golden/err_unknown_nested_where_field.json b/tests/conformance/golden/err_unknown_nested_where_field.json new file mode 100644 index 0000000..6e116eb --- /dev/null +++ b/tests/conformance/golden/err_unknown_nested_where_field.json @@ -0,0 +1 @@ +{"errors":[{"message":"Unknown field in input object: `EventFilter` has no field `bogus`.","locations":[{"line":1,"column":36}],"extensions":{"code":"VALIDATION_ERROR"}}],"data":null} \ No newline at end of file diff --git a/tests/conformance/golden/err_unknown_root_fragment_field.json b/tests/conformance/golden/err_unknown_root_fragment_field.json new file mode 100644 index 0000000..848d9df --- /dev/null +++ b/tests/conformance/golden/err_unknown_root_fragment_field.json @@ -0,0 +1 @@ +{"errors":[{"message":"Unknown field: `Domain` has no field `notARealField`.","locations":[{"line":1,"column":64}],"extensions":{"code":"VALIDATION_ERROR"}}],"data":null} \ No newline at end of file diff --git a/tests/conformance/golden/lenient_unknown_field.json b/tests/conformance/golden/lenient_unknown_field.json deleted file mode 100644 index f586222..0000000 --- a/tests/conformance/golden/lenient_unknown_field.json +++ /dev/null @@ -1 +0,0 @@ -{"data":{"domains":[{"notARealField":null}]}} \ No newline at end of file diff --git a/tests/conformance/golden/ok_declared_domain_fields.json b/tests/conformance/golden/ok_declared_domain_fields.json new file mode 100644 index 0000000..f495d91 --- /dev/null +++ b/tests/conformance/golden/ok_declared_domain_fields.json @@ -0,0 +1 @@ +{"data":{"domain":{"namehash":"0x787192fc5378cc32aa956ddfdedbf26b24e8d78e40109add0eea2c1a012c3dec","domain":{"name":"alice.eth"},"subdomainConnection":{"totalCount":1,"pageInfo":{"hasNextPage":false,"hasPreviousPage":false},"edges":[{"cursor":"0x74d7e317f83d8c977da609d1997d9b4e15e081392c4c5959c7bf3f42c9f857a0","node":{"name":"sub.alice.eth"}}]},"eventsConnection":{"totalCount":4,"pageInfo":{"hasNextPage":true,"hasPreviousPage":false},"edges":[{"cursor":"0x0000000000000000000000000000000000000000000000000000000000000000-9003","node":{"type":"Transfer"}},{"cursor":"0x0000000000000000000000000000000000000000000000000000000000000000-9002","node":{"type":"AddressChanged"}}]}}}} \ No newline at end of file diff --git a/tests/conformance/golden/ok_declared_registration_fields.json b/tests/conformance/golden/ok_declared_registration_fields.json new file mode 100644 index 0000000..32b1d6c --- /dev/null +++ b/tests/conformance/golden/ok_declared_registration_fields.json @@ -0,0 +1 @@ +{"data":{"registrations":[{"name":"alice.eth","block":100,"blockNumber":100,"timestamp":1700000000,"registrationDate":1700000000}]}} \ No newline at end of file diff --git a/tests/conformance/golden/ok_declared_resolver_detail_fields.json b/tests/conformance/golden/ok_declared_resolver_detail_fields.json new file mode 100644 index 0000000..56be981 --- /dev/null +++ b/tests/conformance/golden/ok_declared_resolver_detail_fields.json @@ -0,0 +1 @@ +{"data":{"resolver":{"address":"0xcccccccccccccccccccccccccccccccccccccccc","recordModel":false,"domain":{"name":"sub.alice.eth"},"texts":[],"coinTypes":[],"addr":null,"text":null}}} \ No newline at end of file diff --git a/tests/conformance/golden/ok_root_fragment.json b/tests/conformance/golden/ok_root_fragment.json new file mode 100644 index 0000000..dc4ae8e --- /dev/null +++ b/tests/conformance/golden/ok_root_fragment.json @@ -0,0 +1 @@ +{"data":{"domains":[{"name":"bob.eth"}]}} \ No newline at end of file diff --git a/tests/conformance/golden/ok_typename_and_fragments.json b/tests/conformance/golden/ok_typename_and_fragments.json new file mode 100644 index 0000000..708de41 --- /dev/null +++ b/tests/conformance/golden/ok_typename_and_fragments.json @@ -0,0 +1 @@ +{"data":{"domains":[{"__typename":"Domain","n":"bob.eth","id":"0xbe11069ec59144113f438b6ef59dd30497769fc2dce8e2b52e3ae71ac18e47c9","labelName":"bob"}]}} \ No newline at end of file diff --git a/tests/conformance/runner.zig b/tests/conformance/runner.zig index 2b3beb1..9db302a 100644 --- a/tests/conformance/runner.zig +++ b/tests/conformance/runner.zig @@ -366,6 +366,9 @@ test "conformance goldens" { defer a.free(exp_vars); const owner_vars = try std.fmt.allocPrint(a, "{{\"id\":\"{s}\"}}", .{owner_hex}); defer a.free(owner_vars); + var resolver_buf: [42]u8 = undefined; + const resolver_vars = try std.fmt.allocPrint(a, "{{\"id\":\"{s}\"}}", .{helpers.TEST_RESOLVER.toHexBuf(&resolver_buf)}); + defer a.free(resolver_vars); const ops = [_]Op{ .{ .name = "meta", .query = "{ _meta { block { number hash } hasIndexingErrors } }" }, @@ -458,12 +461,26 @@ test "conformance goldens" { .{ .name = "err_unknown_argument", .query = "{ domains(bogusArg: 1) { id } }" }, .{ .name = "err_unknown_where_field", .query = "{ domains(where: {totallyBogus: 1}) { id } }" }, .{ .name = "err_unknown_query", .query = "{ notARealQueryField { id } }" }, - // --- leniency ops: document (and lock) where zigens is LENIENT in non-strict - // mode rather than raising a validation error — an unknown field resolves to - // null, and an invalid orderBy enum is ignored (default order). These are - // intentional divergences from strict GraphQL; the goldens guard against a - // silent change either way. - .{ .name = "lenient_unknown_field", .query = "{ domains(first:1){ notARealField } }" }, + // Unknown selection fields, and unknown arguments below the root, used to + // resolve to null or be silently dropped; they now fail validation. + .{ .name = "err_unknown_field", .query = "{ domains(first:1){ notARealField } }" }, + .{ .name = "err_unknown_nested_field", .query = "{ domains(first:1){ owner { notARealField } } }" }, + .{ .name = "err_unknown_fragment_field", .query = "query Q { domains(first:1){ ...F } } fragment F on Domain { notARealField }" }, + .{ .name = "err_unknown_root_fragment_field", .query = "query Q { ...Root } fragment Root on Query { domains(first:1){ notARealField } }" }, + .{ .name = "err_unknown_nested_argument", .query = "{ domains(first:1){ subdomains(bogus: 1) { id } } }" }, + .{ .name = "err_unknown_nested_where_field", .query = "{ domains(first:1){ events(where: {bogus: 1}) { id } } }" }, + .{ .name = "err_fragment_wrong_type", .query = "{ domains(first:1){ ... on Account { id } } }" }, + // __typename, aliases, named and inline fragments (spliced in, not + // resolved as a field named after the type), and root-level fragments. + .{ .name = "ok_typename_and_fragments", .query = "query Q { domains(first:1){ __typename n: name ...F ... on Domain { labelName } } } fragment F on Domain { id }" }, + .{ .name = "ok_root_fragment", .query = "query Q { ...Root } fragment Root on Query { domains(first:1){ name } }" }, + // Served fields that were missing from the schema, now declared: they must + // keep answering rather than become validation errors. + .{ .name = "ok_declared_domain_fields", .query = "query($id:String!){ domain(id:$id){ namehash domain { name } subdomainConnection { totalCount pageInfo { hasNextPage } edges { node { name } } } eventsConnection(first: 2) { totalCount edges { node { type } } } } }", .vars = alice_vars }, + .{ .name = "ok_declared_registration_fields", .query = "{ registrations(first:1, orderBy: registrationDate, orderDirection: asc){ name block blockNumber timestamp registrationDate } }" }, + .{ .name = "ok_declared_resolver_detail_fields", .query = "query($id:String!){ resolver(id:$id){ address recordModel domain { name } texts coinTypes addr text(key: \"avatar\") } }", .vars = resolver_vars }, + // An invalid orderBy enum is ignored (default order): an intentional + // leniency, locked so it does not change silently. .{ .name = "lenient_invalid_orderby", .query = "{ domains(orderBy: notARealField){ id } }" }, // An empty selection set is spec-invalid but accepted; the fast path must // emit the namehash id like every other Domain serialization.