diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3954ef3..276ae2a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ permissions: env: # The canonical conformance release this SDK is vendored from (ADR-0032). - BQ_CONFORMANCE_VERSION: "1.10.0" + BQ_CONFORMANCE_VERSION: "1.11.0" # sha256 of that release's fetch.sh: the script runs on the runner, so it is pinned rather than # trusted from a mutable tag. Bump together with BQ_CONFORMANCE_VERSION. BQ_FETCH_SH_SHA256: 8bb6ba567b288fb0ac71a70fd17041b2503df119e01998d76fdad372570bf849 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 05a6951..0873d4e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,7 @@ jobs: runs-on: ubuntu-latest env: # The pinned conformance release (ADR-0032). Keep identical to ci.yml. - BQ_CONFORMANCE_VERSION: "1.10.0" + BQ_CONFORMANCE_VERSION: "1.11.0" BQ_FETCH_SH_SHA256: 8bb6ba567b288fb0ac71a70fd17041b2503df119e01998d76fdad372570bf849 steps: - uses: actions/checkout@v7 diff --git a/CHANGELOG.md b/CHANGELOG.md index cf6833f..cdfe727 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,28 @@ The envelope wire format is versioned separately by `meta.schema_version` ## [Unreleased] +## [1.30.0] - 2026-11-22 + +Implements ADR-0040 (open `lang` tag): the producer schema's closed `lang` enum is replaced by the pattern +`^[a-z][a-z0-9-]*$` on both `meta.lang` and `dead_letter.lang`, so a new SDK (e.g. Rust) can emit its own tag without a +contract change. Nothing on the wire changes and the envelope stays at `schema_version: 1`; consumers were already +tolerant of any `lang` value (decode and re-emit are untouched). + +### Added +- `SchemaValidator` supports the Draft-07 `pattern` keyword. A string that does not match is reported as + `: pattern` (`SchemaValidator::REASON_PATTERN_MISMATCH`). The pattern is read with JSON Schema / ECMA-262 + semantics (unanchored search; `^`/`$` inside the pattern are the anchors, and `$` does not match before a trailing + newline). A pattern that cannot be compiled is a schema defect and throws a `LogicException` instead of silently + accepting or rejecting every value. + +### Changed +- Bundled `message-envelope.schema.json` and the vendored conformance suite are updated to conformance **1.11.0** + (`unknown-lang` now passes the producer schema; new `malformed-lang` case). CI and release pin + `BQ_CONFORMANCE_VERSION` to `1.11.0`. +- `SchemaValidator`: `lang: "rust"` (or any well-formed tag) is now valid; `"Rust 1"` is rejected with reason `pattern` + rather than `not_in_enum`. Code that matched on `REASON_NOT_IN_ENUM` for `meta.lang` / `dead_letter.lang` must expect + `REASON_PATTERN_MISMATCH`. + ## [1.29.0] - 2026-11-11 Brings the opt-in payload validator (ADR-0024) to the K-17 Draft-07 subset behaviour pinned by conformance diff --git a/src/Validation/SchemaValidator.php b/src/Validation/SchemaValidator.php index 3e2aaa4..bc31f7c 100644 --- a/src/Validation/SchemaValidator.php +++ b/src/Validation/SchemaValidator.php @@ -15,7 +15,7 @@ * tolerates the `urn` inbound alias and ignores fields it does not need), this * answers "does this match the wire contract exactly as a producer must emit * it?" — required `job` (no `urn` alias), the full required `meta` block, - * UUID-shaped ids, the `lang` enum, `schema_version` const, and the optional + * UUID-shaped ids, the `lang` tag pattern, `schema_version` const, and the optional * `dead_letter` block when present. It is the in-process echo of the schema diff * CI runs against the conformance suite, usable by an app at runtime without any * network access or a JSON-Schema library. @@ -26,8 +26,15 @@ * * Kept to a hand-rolled structural check (GR-7: zero heavy dependencies): it * enforces the subset of Draft-07 the envelope actually uses — `type`, - * `required`, `enum`, `const`, `minLength`, `minimum`, `format: uuid` — not the - * whole specification. + * `required`, `enum`, `const`, `minLength`, `minimum`, `pattern`, + * `format: uuid` — not the whole specification. + * + * `pattern` is read as a JSON Schema / ECMA-262 regular expression: unanchored + * search semantics, with `^` and `$` inside the pattern marking the anchors + * (`$` matches only at the very end, never before a trailing newline). It is run + * through `preg_match` in Unicode mode; only the plain regular subset the + * envelope schema uses (character classes, quantifiers, anchors) is guaranteed + * to mean the same thing in both dialects. */ final class SchemaValidator { @@ -39,6 +46,10 @@ final class SchemaValidator public const REASON_NOT_IN_ENUM = 'not_in_enum'; public const REASON_WRONG_CONST = 'wrong_const'; public const REASON_BELOW_MINIMUM = 'below_minimum'; + public const REASON_PATTERN_MISMATCH = 'pattern'; + + /** Candidate `preg_match` delimiters; the first one absent from a pattern is used. */ + private const PATTERN_DELIMITERS = ['~', '#', '%', '@', '!', '`', ';', ',']; /** RFC 4122 textual UUID, as the schema's `format: uuid` requires. */ private const UUID_PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i'; @@ -191,7 +202,7 @@ private static function matchesType(string $type, mixed $value): bool } /** - * `minLength` and `format: uuid` string constraints. + * `minLength`, `pattern` and `format: uuid` string constraints. * * @param array $schema */ @@ -201,6 +212,10 @@ private static function checkString(array $schema, string $value, string $path): return self::violation($path, self::REASON_EMPTY_STRING); } + if (isset($schema['pattern']) && is_string($schema['pattern']) && ! self::matchesPattern($schema['pattern'], $value)) { + return self::violation($path, self::REASON_PATTERN_MISMATCH); + } + if (($schema['format'] ?? null) === 'uuid' && preg_match(self::UUID_PATTERN, $value) !== 1) { return self::violation($path, self::REASON_NOT_UUID); } @@ -208,6 +223,42 @@ private static function checkString(array $schema, string $value, string $path): return null; } + /** + * Whether `$value` matches the ECMA-262 style `$pattern` (search semantics). + * + * The `u` flag makes the pattern operate on code points; `D` keeps `$` from + * matching before a trailing newline, as it does in ECMA-262. A subject that + * is not valid UTF-8 cannot match. A pattern that does not compile is a defect + * in the schema, not in the envelope, so it throws rather than silently + * accepting (or rejecting) every value. + * + * @throws \LogicException when the pattern cannot be compiled + */ + private static function matchesPattern(string $pattern, string $value): bool + { + $delimiter = null; + foreach (self::PATTERN_DELIMITERS as $candidate) { + if (! str_contains($pattern, $candidate)) { + $delimiter = $candidate; + break; + } + } + + if ($delimiter === null) { + throw new \LogicException(sprintf('Schema pattern %s cannot be delimited for preg_match.', json_encode($pattern))); + } + + $regex = $delimiter . $pattern . $delimiter . 'uD'; + + // preg_match() warns on a malformed pattern; the empty-subject probe tells + // a compile failure (false) apart from a plain non-match (0). + if (@preg_match($regex, '') === false) { + throw new \LogicException(sprintf('Schema pattern %s is not a valid regular expression.', json_encode($pattern))); + } + + return preg_match($regex, $value) === 1; + } + /** * `required` keys, then recurse into each declared `properties` entry that is * present. Unknown keys are allowed (`additionalProperties: true`). diff --git a/src/Validation/message-envelope.schema.json b/src/Validation/message-envelope.schema.json index cdfaff7..b1f1e5e 100644 --- a/src/Validation/message-envelope.schema.json +++ b/src/Validation/message-envelope.schema.json @@ -46,7 +46,7 @@ }, "lang": { "type": "string", - "enum": ["php", "go", "python", "java", "dotnet", "node"], + "pattern": "^[a-z][a-z0-9-]*$", "description": "Producer language tag." }, "schema_version": { @@ -101,7 +101,7 @@ }, "lang": { "type": "string", - "enum": ["php", "go", "python", "java", "dotnet", "node"], + "pattern": "^[a-z][a-z0-9-]*$", "description": "Language of the SDK that dead-lettered the message." } } diff --git a/tests/SchemaValidatorTest.php b/tests/SchemaValidatorTest.php index 0f78212..1b74f18 100644 --- a/tests/SchemaValidatorTest.php +++ b/tests/SchemaValidatorTest.php @@ -14,7 +14,7 @@ * * Where {@see EnvelopeValidatorTest} covers the lenient consumer gate, this * pins the strict wire contract: required `job` (no `urn` alias), the full - * `meta` block, UUID-shaped ids, the `lang` enum, the `schema_version` const, + * `meta` block, UUID-shaped ids, the `lang` tag pattern, the `schema_version` const, * and the optional `dead_letter` block — all without a JSON-Schema library. */ final class SchemaValidatorTest extends TestCase @@ -135,8 +135,8 @@ public static function violations(): array $emptyQueue = self::base(); $emptyQueue['meta']['queue'] = ''; - $unknownLang = self::base(); - $unknownLang['meta']['lang'] = 'rust'; + $malformedLang = self::base(); + $malformedLang['meta']['lang'] = 'Rust 1'; $wrongSchemaVersion = self::base(); $wrongSchemaVersion['meta']['schema_version'] = 2; @@ -168,6 +168,15 @@ public static function violations(): array 'attempts' => 3, ]; + $malformedDeadLetterLang = self::base(); + $malformedDeadLetterLang['dead_letter'] = [ + 'reason' => 'failed', + 'failed_at' => 1749132728000, + 'original_queue' => 'orders', + 'attempts' => 3, + 'lang' => 'Rust 1', + ]; + return [ 'missing job' => [$missingJob, 'job: ' . SchemaValidator::REASON_MISSING_REQUIRED], 'empty job' => [$emptyJob, 'job: ' . SchemaValidator::REASON_EMPTY_STRING], @@ -178,7 +187,8 @@ public static function violations(): array 'missing meta.id' => [$missingMetaId, 'meta.id: ' . SchemaValidator::REASON_MISSING_REQUIRED], 'meta.id not a uuid' => [$metaIdNotUuid, 'meta.id: ' . SchemaValidator::REASON_NOT_UUID], 'empty meta.queue' => [$emptyQueue, 'meta.queue: ' . SchemaValidator::REASON_EMPTY_STRING], - 'unknown meta.lang' => [$unknownLang, 'meta.lang: ' . SchemaValidator::REASON_NOT_IN_ENUM], + 'malformed meta.lang' => [$malformedLang, 'meta.lang: ' . SchemaValidator::REASON_PATTERN_MISMATCH], + 'malformed dead_letter.lang' => [$malformedDeadLetterLang, 'dead_letter.lang: ' . SchemaValidator::REASON_PATTERN_MISMATCH], 'wrong schema_version' => [$wrongSchemaVersion, 'meta.schema_version: ' . SchemaValidator::REASON_WRONG_CONST], 'created_at not an integer' => [$createdAtNotInt, 'meta.created_at: ' . SchemaValidator::REASON_WRONG_TYPE], 'negative created_at' => [$negativeCreatedAt, 'meta.created_at: ' . SchemaValidator::REASON_BELOW_MINIMUM], @@ -199,6 +209,192 @@ public function test_check_reports_the_first_violation_with_its_path(array $enve $this->assertFalse(SchemaValidator::isValid($envelope)); } + /** + * @return array + */ + public static function acceptedLangTags(): array + { + return [ + 'rust (ADR-0040)' => ['rust'], + 'php' => ['php'], + 'go' => ['go'], + 'python' => ['python'], + 'java' => ['java'], + 'dotnet' => ['dotnet'], + 'node' => ['node'], + 'hyphenated' => ['common-lisp'], + 'digit after the first letter' => ['k8s'], + ]; + } + + #[DataProvider('acceptedLangTags')] + public function test_an_open_but_well_formed_meta_lang_conforms(string $lang): void + { + $envelope = self::base(); + $envelope['meta']['lang'] = $lang; + + $this->assertNull(SchemaValidator::check($envelope)); + } + + #[DataProvider('acceptedLangTags')] + public function test_an_open_but_well_formed_dead_letter_lang_conforms(string $lang): void + { + $envelope = self::base(); + $envelope['dead_letter'] = [ + 'reason' => 'failed', + 'failed_at' => 1749132728000, + 'original_queue' => 'orders', + 'attempts' => 3, + 'lang' => $lang, + ]; + + $this->assertNull(SchemaValidator::check($envelope)); + $this->assertTrue(SchemaValidator::isValid($envelope)); + } + + /** + * @return array + */ + public static function rejectedLangTags(): array + { + return [ + 'upper case and space' => ['Rust 1'], + 'empty' => [''], + 'leading digit' => ['1go'], + 'leading hyphen' => ['-go'], + 'upper case' => ['PHP'], + 'underscore' => ['dot_net'], + 'trailing newline ($ is not "before a final newline")' => ["rust\n"], + 'embedded newline' => ["ru\nst"], + 'non-ASCII letter' => ['rüst'], + 'invalid UTF-8' => ["rust\xff"], + ]; + } + + #[DataProvider('rejectedLangTags')] + public function test_a_malformed_lang_tag_is_a_pattern_violation(string $lang): void + { + $envelope = self::base(); + $envelope['meta']['lang'] = $lang; + + $this->assertSame('meta.lang: ' . SchemaValidator::REASON_PATTERN_MISMATCH, SchemaValidator::check($envelope)); + $this->assertFalse(SchemaValidator::isValid($envelope)); + } + + public function test_the_unknown_lang_fixture_conforms_and_malformed_lang_does_not(): void + { + $unknown = $this->fixture('unknown-lang'); + $malformed = $this->fixture('malformed-lang'); + + $this->assertSame('cobol', $unknown['meta']['lang']); + $this->assertNull(SchemaValidator::check($unknown)); + $this->assertSame('meta.lang: ' . SchemaValidator::REASON_PATTERN_MISMATCH, SchemaValidator::check($malformed)); + } + + /** + * The bundled validator must reach the same producer-side verdict as the + * conformance manifest: a roundtrip case is producer-schema valid unless it + * says `producer_schema_valid: false`. + */ + public function test_every_roundtrip_fixture_gets_the_verdict_the_manifest_declares(): void + { + /** @var array $manifest */ + $manifest = json_decode((string) file_get_contents(__DIR__ . '/conformance/manifest.json'), true, 512, JSON_THROW_ON_ERROR); + /** @var list> $cases */ + $cases = $manifest['roundtrip']['cases']; + $this->assertNotEmpty($cases); + + foreach ($cases as $case) { + $fixture = json_decode((string) file_get_contents(__DIR__ . '/conformance/' . $case['file']), true, 512, JSON_THROW_ON_ERROR); + $this->assertIsArray($fixture); + + $this->assertSame( + ($case['producer_schema_valid'] ?? true) === true, + SchemaValidator::isValid($fixture), + sprintf('roundtrip case "%s": %s', $case['name'], (string) SchemaValidator::check($fixture)), + ); + } + } + + public function test_the_bundled_schema_carries_the_lang_pattern_and_no_lang_enum(): void + { + $schema = SchemaValidator::schema(); + + foreach ([$schema['properties']['meta']['properties']['lang'], $schema['properties']['dead_letter']['properties']['lang']] as $lang) { + $this->assertSame('^[a-z][a-z0-9-]*$', $lang['pattern']); + $this->assertArrayNotHasKey('enum', $lang); + } + } + + public function test_pattern_is_searched_unanchored_unless_the_pattern_anchors_itself(): void + { + $this->assertNull($this->checkWithSchema(['type' => 'string', 'pattern' => 'ab'], 'xxabxx')); + $this->assertSame('v: ' . SchemaValidator::REASON_PATTERN_MISMATCH, $this->checkWithSchema(['type' => 'string', 'pattern' => '^ab$'], 'xxabxx')); + $this->assertNull($this->checkWithSchema(['type' => 'string', 'pattern' => '^ab$'], 'ab')); + } + + public function test_a_pattern_containing_the_first_delimiter_candidate_still_works(): void + { + $this->assertNull($this->checkWithSchema(['type' => 'string', 'pattern' => '^a~b$'], 'a~b')); + $this->assertSame('v: ' . SchemaValidator::REASON_PATTERN_MISMATCH, $this->checkWithSchema(['type' => 'string', 'pattern' => '^a/b$'], 'a-b')); + $this->assertNull($this->checkWithSchema(['type' => 'string', 'pattern' => '^a/b$'], 'a/b')); + } + + public function test_pattern_does_not_apply_to_non_strings(): void + { + $this->assertSame('v: ' . SchemaValidator::REASON_WRONG_TYPE, $this->checkWithSchema(['type' => 'string', 'pattern' => '^a$'], 5)); + } + + public function test_an_uncompilable_pattern_is_a_schema_defect_and_throws(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('is not a valid regular expression'); + + $this->checkWithSchema(['type' => 'string', 'pattern' => '^[a-z'], 'abc'); + } + + public function test_a_pattern_that_cannot_be_delimited_is_a_schema_defect_and_throws(): void + { + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('cannot be delimited'); + + $this->checkWithSchema(['type' => 'string', 'pattern' => '~#%@!`;,'], 'abc'); + } + + /** + * Validate `$value` as property `v` against a substitute bundled schema whose + * only property is `$node`, restoring the real schema afterwards. + * + * @param array $node + */ + private function checkWithSchema(array $node, mixed $value): ?string + { + $schema = ['type' => 'object', 'properties' => ['v' => $node]]; + $property = new \ReflectionProperty(SchemaValidator::class, 'schema'); + $previous = $property->getValue(); + $property->setValue(null, $schema); + + try { + return SchemaValidator::check(['v' => $value]); + } finally { + $property->setValue(null, $previous); + } + } + + /** + * @return array + */ + private function fixture(string $name): array + { + /** @var array */ + return json_decode( + (string) file_get_contents(__DIR__ . '/conformance/fixtures/' . $name . '.json'), + true, + 512, + JSON_THROW_ON_ERROR, + ); + } + public function test_a_non_object_envelope_is_rejected_at_the_root(): void { // A list (JSON array) is not a JSON object at the root. @@ -208,13 +404,13 @@ public function test_a_non_object_envelope_is_rejected_at_the_root(): void public function test_validate_throws_carrying_the_violation_and_envelope(): void { $envelope = self::base(); - $envelope['meta']['lang'] = 'rust'; + $envelope['meta']['lang'] = 'Rust 1'; try { SchemaValidator::validate($envelope); $this->fail('Expected an InvalidEnvelopeException.'); } catch (InvalidEnvelopeException $e) { - $this->assertSame('meta.lang: ' . SchemaValidator::REASON_NOT_IN_ENUM, $e->reason()); + $this->assertSame('meta.lang: ' . SchemaValidator::REASON_PATTERN_MISMATCH, $e->reason()); $this->assertSame($envelope, $e->envelope()); } } diff --git a/tests/conformance/CONFORMANCE_VERSION b/tests/conformance/CONFORMANCE_VERSION index 81c871d..1cac385 100644 --- a/tests/conformance/CONFORMANCE_VERSION +++ b/tests/conformance/CONFORMANCE_VERSION @@ -1 +1 @@ -1.10.0 +1.11.0 diff --git a/tests/conformance/fixtures/malformed-lang.json b/tests/conformance/fixtures/malformed-lang.json new file mode 100644 index 0000000..790edfd --- /dev/null +++ b/tests/conformance/fixtures/malformed-lang.json @@ -0,0 +1,15 @@ +{ + "job": "urn:babel:orders:created", + "trace_id": "7b3f9c2a-e41d-4f88-9b2a-1c0d5e6f7a8b", + "data": { + "order_id": 1042 + }, + "meta": { + "id": "f1e2d3c4-b5a6-4789-90ab-cdef01234567", + "queue": "orders", + "lang": "Rust 1", + "schema_version": 1, + "created_at": 1749132727000 + }, + "attempts": 0 +} diff --git a/tests/conformance/manifest.json b/tests/conformance/manifest.json index 637f8dd..a8e5b1e 100644 --- a/tests/conformance/manifest.json +++ b/tests/conformance/manifest.json @@ -1,6 +1,6 @@ { "schema_version": 1, - "conformance_version": "1.10.0", + "conformance_version": "1.11.0", "sections": { "cases": { "scope": "core" @@ -626,13 +626,22 @@ { "name": "unknown-lang", "file": "fixtures/unknown-lang.json", - "description": "A meta.lang outside the known language list (a future/community SDK) is decoded without error and re-emitted unchanged — a consumer MUST NOT reject or rewrite it.", - "producer_schema_valid": false, + "description": "A meta.lang outside the built-in language list (a future/community SDK) is decoded without error and re-emitted unchanged — a consumer MUST NOT reject or rewrite it. Since 1.11.0 (ADR-0040) the tag 'cobol' matches the open pattern ^[a-z][a-z0-9-]*$, so this fixture passes the producer JSON Schema.", "expect_attempts": 1, "expect_preserved": { "/meta/lang": "cobol" } }, + { + "name": "malformed-lang", + "file": "fixtures/malformed-lang.json", + "description": "A meta.lang that does not match the open tag pattern ^[a-z][a-z0-9-]*$ (upper case and a space) is a producer-side violation, but a consumer is tolerant (ADR-0040): it is decoded without error and re-emitted unchanged — a consumer MUST NOT reject or rewrite it.", + "producer_schema_valid": false, + "expect_attempts": 1, + "expect_preserved": { + "/meta/lang": "Rust 1" + } + }, { "name": "empty-data-roundtrip", "file": "fixtures/empty-data-roundtrip.json", diff --git a/tests/conformance/schema/message-envelope.schema.json b/tests/conformance/schema/message-envelope.schema.json index cdfaff7..b1f1e5e 100644 --- a/tests/conformance/schema/message-envelope.schema.json +++ b/tests/conformance/schema/message-envelope.schema.json @@ -46,7 +46,7 @@ }, "lang": { "type": "string", - "enum": ["php", "go", "python", "java", "dotnet", "node"], + "pattern": "^[a-z][a-z0-9-]*$", "description": "Producer language tag." }, "schema_version": { @@ -101,7 +101,7 @@ }, "lang": { "type": "string", - "enum": ["php", "go", "python", "java", "dotnet", "node"], + "pattern": "^[a-z][a-z0-9-]*$", "description": "Language of the SDK that dead-lettered the message." } } diff --git a/tests/conformance/schema/results.example.json b/tests/conformance/schema/results.example.json index d8caff0..12fb1e1 100644 --- a/tests/conformance/schema/results.example.json +++ b/tests/conformance/schema/results.example.json @@ -1,7 +1,7 @@ { "sdk": "example-sdk/redis", "version": "1.9.0", - "conformance_version": "1.10.0", + "conformance_version": "1.11.0", "generated_at": "2026-10-18T09:30:00Z", "bindings": [ "redis",