From e7bd5c0f76568b3c31d15d8815b9f8c027430eaf Mon Sep 17 00:00:00 2001 From: Mikhail Ilinsky Date: Thu, 22 Oct 2026 08:59:05 +1000 Subject: [PATCH] chore: Strip comments, internal tracker markers and .ai references --- rector.php | 5 - src/Builder/OpenApiValidatorBuilder.php | 187 +----------------- src/Cache/SchemaCache.php | 22 +-- src/Registry/SchemaRegistry.php | 30 --- src/Schema/Model/ArrayConstraints.php | 2 +- src/Schema/Model/Internal/ArrayFields.php | 2 +- .../Model/Internal/BoundSiblingMerger.php | 5 - .../Model/Internal/CompositionFields.php | 6 +- .../Internal/CompositionSiblingMerger.php | 5 - src/Schema/Model/Internal/ObjectFields.php | 8 +- src/Schema/Model/Internal/ScalarFields.php | 12 +- .../Model/Internal/ScalarSiblingMerger.php | 6 - src/Schema/Model/ObjectConstraints.php | 14 +- src/Schema/Model/Schema.php | 42 +--- src/Schema/Model/SchemaSiblingMerger.php | 2 - src/Schema/Parser/ComponentsBuilder.php | 2 - .../Internal/ArraySchemaKeywordParser.php | 1 - .../Parser/Internal/ComponentTreeBuilder.php | 2 - .../CompositionSchemaKeywordParser.php | 1 - .../Internal/ObjectSchemaKeywordParser.php | 2 - .../Parser/Internal/ResponseTreeBuilder.php | 2 - .../Internal/ScalarSchemaKeywordParser.php | 1 - .../Internal/SchemaKeywordAccumulator.php | 1 - src/Schema/Parser/YamlParser.php | 18 +- .../Internal/ArraySchemaSerializer.php | 1 - .../Internal/CompositionSchemaSerializer.php | 1 - .../Internal/ModelWireSerializer.php | 1 - .../Internal/ObjectSchemaSerializer.php | 1 - .../Serializer/SchemaToArrayConverter.php | 1 - src/Validator/BodyReader.php | 7 - src/Validator/Callback/CallbackValidator.php | 12 +- .../Coercion/IntegerStringNormalizer.php | 8 - .../Coercion/NumberStringNormalizer.php | 30 --- src/Validator/Error/ValidationContext.php | 43 ---- src/Validator/EventDispatchingTrait.php | 2 - src/Validator/Example/ExampleValidator.php | 1 - .../Exception/InvalidFormatException.php | 7 - .../InvalidMultipleOfSchemaException.php | 2 +- .../Exception/InvalidParameterException.php | 14 -- .../Exception/InvalidUtf8Exception.php | 6 - .../MissingSecurityCredentialsError.php | 35 ---- .../Exception/NestedValidationError.php | 6 - .../Exception/PregRuntimeException.php | 9 - .../Exception/SanitizableExceptionTrait.php | 3 - .../Exception/SpecTooLargeException.php | 6 - .../UnresolvableCallbackPathException.php | 12 -- .../UnsupportedSecuritySchemeException.php | 19 -- .../Exception/ValidationException.php | 6 - src/Validator/Format/FormatRegistry.php | 12 -- .../Internal/CandidatePrioritizer.php | 1 - src/Validator/Internal/LruCache.php | 2 - src/Validator/Internal/TrieBuilder.php | 3 +- src/Validator/Internal/TrieLookup.php | 6 +- src/Validator/JsonDepthLimit.php | 15 -- src/Validator/LibxmlSecuredContext.php | 37 +--- src/Validator/Link/Internal/RequestScope.php | 4 +- src/Validator/Link/Internal/ResponseScope.php | 6 +- src/Validator/Link/LinkContext.php | 25 +-- src/Validator/Link/LinkResolver.php | 1 - src/Validator/OpenApiValidator.php | 15 +- src/Validator/Operation.php | 3 +- src/Validator/PregExecutor.php | 44 +---- .../Request/BodyParser/XmlBodyParser.php | 1 - src/Validator/Request/CookieValidator.php | 5 - .../Internal/BracketNotationParser.php | 11 +- .../Request/Internal/DeepObjectParser.php | 3 - src/Validator/Request/MediaTypeMatcher.php | 11 +- src/Validator/Request/PathParser.php | 4 +- src/Validator/Request/PathRegexCache.php | 11 +- src/Validator/Request/QueryParser.php | 8 - src/Validator/Request/TypeCoercer.php | 12 -- .../StreamRecordTooLargeException.php | 6 - .../Exception/TooManyRecordsException.php | 6 - src/Validator/Response/Internal/SseParser.php | 4 - .../Response/Internal/StreamLineReader.php | 1 - .../Response/StreamingContentParser.php | 26 --- .../ExternalRefSecurityException.php | 10 - .../ExternalRefTooLargeException.php | 6 - .../Exception/UnresolvableRefException.php | 12 -- .../Schema/FileExternalRefResolver.php | 32 --- .../Schema/Internal/CompositionResolver.php | 7 +- .../Schema/Internal/DiscriminatorDetector.php | 9 - .../Schema/Internal/DocumentNavigator.php | 8 - src/Validator/Schema/Internal/UriResolver.php | 3 - src/Validator/Schema/RegexValidator.php | 2 - .../Schema/SchemaValueNormalizer.php | 9 - .../AdditionalPropertiesValidator.php | 5 +- .../SchemaValidator/ArrayLengthValidator.php | 1 - .../SchemaValidator/EnumScalarCache.php | 1 - .../Internal/ItemValidationExceptionTrait.php | 1 - .../SchemaValidator/ItemsValidator.php | 4 +- .../PatternPropertiesValidator.php | 7 +- .../UnevaluatedItemsValidator.php | 5 +- .../UnevaluatedPropertiesValidator.php | 6 +- src/Validator/Security/SecurityValidator.php | 1 - src/Validator/Server/ServerPathMatcher.php | 4 - src/Validator/Server/ServerUrlResolver.php | 11 -- src/Validator/Util/LogContextSanitizer.php | 6 - src/Validator/Util/Utf16.php | 8 - src/Validator/Validation/ValidationStack.php | 11 +- src/Validator/ValidatorPool.php | 37 +--- .../Builder/BuilderConfigurationTest.php | 9 - .../OpenApiValidatorBuilderCacheKeyTest.php | 44 +---- ...penApiValidatorBuilderLoggerWiringTest.php | 11 -- ...lidatorBuilderStringSpecFailClosedTest.php | 8 - .../OpenApiValidatorBuilderWithFormatTest.php | 4 - .../Builder/SecurityValidationBuilderTest.php | 13 -- .../Event/ValidationLifecycleTest.php | 8 +- tests/Functional/FullCycle/FixtureE2ETest.php | 3 - .../FullCycle/FullCycleEventsTest.php | 6 +- .../OpenApi32/AdditionalOperationsTest.php | 4 - .../DiscriminatorDefaultMappingTest.php | 4 - .../OpenApi32/JsonSchemaDialectTest.php | 8 - .../FullCycle/OpenApi32/SelfReferenceTest.php | 9 - .../FullCycle/OpenApi32/Webhook32Test.php | 4 - tests/Functional/FunctionalTestCase.php | 27 --- .../CoercionWholeFloatRegressionTest.php | 17 -- ...minatorNestedCompositionRegressionTest.php | 16 -- .../ExceptionInfoLeakRegressionTest.php | 13 -- .../NestedParameterCoercionRegressionTest.php | 9 - .../NestedRefInKeywordsRegressionTest.php | 11 -- .../NullableInCompositionRegressionTest.php | 15 -- .../SchemaCacheParseConfigRegressionTest.php | 18 +- ...eValidatorOffsetRequiredRegressionTest.php | 14 -- .../WithFormatOrderRegressionTest.php | 17 -- .../YamlBillionLaughsRegressionTest.php | 10 - .../Functional/Request/CookieCoercionTest.php | 51 +---- .../Request/CookieValidationTest.php | 90 +-------- .../Functional/Request/DuplicateKeysTest.php | 43 +--- tests/Functional/Request/HeaderArrayTest.php | 58 +----- .../Functional/Request/HeaderCoercionTest.php | 50 +---- .../Request/HeaderValidationTest.php | 4 - .../Request/MultipartUploadTest.php | 8 - .../Request/PathParameterEdgeCasesTest.php | 23 +-- .../Request/QueryParameterEdgeCasesTest.php | 140 ++----------- .../Request/RequestBodyMediaTypeTest.php | 8 - .../Response/NullableCompositionTest.php | 5 - .../Response/ResponseContentTypeTest.php | 12 -- .../Response/StatusCodeEdgeCasesTest.php | 38 ---- .../Schema/CompositionBranchErrorsTest.php | 7 - .../Schema/CompositionBranchOrderTest.php | 12 -- .../Schema/Parser/JsonParserTest.php | 23 --- .../Schema/RefResolutionInCompositionTest.php | 8 - .../Callback/CallbackValidatorTest.php | 11 -- .../Validator/PathFinderAccumulatorTest.php | 13 +- .../ResponseHeadersValidatorContextTest.php | 7 - .../Validator/Schema/JsonEqualsTest.php | 46 ----- .../NullableCompositionTest.php | 9 - .../Validation/CallbackValidatorTest.php | 11 -- .../Internal/ValidationGroupTest.php | 5 - .../Builder/ExternalRefAllowedRootTest.php | 45 +---- .../Builder/OpenApiValidatorBuilderTest.php | 1 - .../Integration/Cache/FileSpecUpdateTest.php | 53 +---- .../Cache/StringSpecConfinementCacheTest.php | 5 - .../Concurrency/RoadRunnerTest.php | 12 -- .../ValidationContextPerRequestTest.php | 12 -- .../Integration/ConcurrentValidationTest.php | 48 ----- tests/Integration/LibxmlEdgeCasesTest.php | 13 -- tests/Integration/LibxmlStateLeakageTest.php | 4 - .../PostRefactorBehavioralSnapshotTest.php | 34 ---- tests/Integration/Psr7/GuzzlePsr7Test.php | 9 - .../Integration/Psr7/LaminasDiactorosTest.php | 8 - tests/Integration/Psr7/StubPsr7Test.php | 10 - .../SchemaHelperIntegrationTest.php | 5 - .../Error/BreadcrumbIntegrationTest.php | 14 +- .../Error/ErrorHandlingIntegrationTest.php | 10 +- .../OpenApiValidatorResetCachesTest.php | 4 - .../Validator/OpenApiValidatorTest.php | 3 - .../Schema/DiscriminatorExternalRefTest.php | 62 +----- .../Schema/DiscriminatorValidatorTest.php | 4 +- .../Schema/ItemsValidatorWithContextTest.php | 17 -- .../PropertiesValidatorWithContextTest.php | 15 -- .../SchemaValidatorAdapterContextTest.php | 2 +- .../Webhook/WebhookSecurityCoercionTest.php | 9 - .../Performance/ConfinementCacheBenchTest.php | 5 - tests/Security/BillionLaughsTest.php | 23 --- .../CallbackRuntimeTemplateSecurityTest.php | 24 --- tests/Security/CompositionErrorCapTest.php | 7 +- .../ContainsValidatorDoSProtectionTest.php | 7 +- tests/Security/CookieOverflowSecurityTest.php | 9 - tests/Security/DeepNestingTest.php | 13 -- .../Security/LogInjectionSanitizationTest.php | 9 +- tests/Security/MemoryExhaustionTest.php | 29 --- tests/Security/PathFinderDepthLimitTest.php | 11 +- tests/Security/RedosFuzzTest.php | 8 - tests/Security/RefResolverInfoLeakTest.php | 10 +- tests/Security/SecurityE2ETest.php | 81 -------- .../Security/UniqueItemsDoSProtectionTest.php | 7 +- tests/Security/XmlBodySizeLimitTest.php | 8 +- tests/Support/Psr6ArrayCacheStub.php | 1 - tests/Support/StreamStubHelper.php | 7 - .../Builder/Internal/CacheKeyBuilderTest.php | 10 +- .../Internal/ExternalRefDetectorTest.php | 3 - .../Unit/Builder/Internal/SpecLoaderTest.php | 2 +- tests/Unit/Cache/SchemaCacheTest.php | 25 --- ...ArrayDispatcherStoppableRegressionTest.php | 19 -- .../SchemaRegistryPrecompiledTest.php | 8 - tests/Unit/Registry/SchemaRegistryTest.php | 41 ---- .../Model/Internal/BoundSiblingMergerTest.php | 6 - .../Internal/CompositionSiblingMergerTest.php | 7 - .../Internal/ScalarSiblingMergerTest.php | 3 - .../Model/SchemaConstraintGroupsTest.php | 10 - .../Schema/Model/SchemaWithOverridesTest.php | 20 -- .../Internal/InlineExampleResolverTest.php | 2 - .../Coercion/AbstractCoercerTest.php | 50 ----- .../Coercion/IntegerStringNormalizerTest.php | 6 - .../Coercion/NumberStringNormalizerTest.php | 22 --- .../Error/Formatter/FormatExceptionTest.php | 1 - .../Internal/ValidationContextInitTest.php | 2 - .../InvalidMultipleOfSchemaExceptionTest.php | 8 - .../Numeric/FloatDoubleValidatorTest.php | 5 - .../Format/String/DurationValidatorTest.php | 4 - .../Format/String/EmailValidatorTest.php | 7 - .../Format/String/UriValidatorTest.php | 38 +--- .../Format/String/UuidValidatorTest.php | 5 - .../Validator/LibxmlSecuredContextTest.php | 5 - .../Internal/LinkContextFromGroupsTest.php | 3 - .../Request/BodyParser/XmlBodyParserTest.php | 8 - .../Validator/Request/HeaderFinderTest.php | 6 - .../ParameterDeserializerExplodeLimitTest.php | 5 - .../Validator/Request/PathRegexCacheTest.php | 17 -- .../Validator/Request/QueryParserTest.php | 5 - .../ResponseBodyValidatorWithContextTest.php | 6 - .../Response/StreamingContentParserTest.php | 159 +-------------- .../Schema/AnnotationTrackingTest.php | 9 - .../Schema/CombineUrisRfc3986Test.php | 4 - .../CycleDetectionWeakMapRegressionTest.php | 5 - .../Schema/FileExternalRefResolverTest.php | 138 +------------ .../Internal/DiscriminatorDetectorTest.php | 15 -- .../Schema/Internal/DocumentNavigatorTest.php | 3 - .../Schema/Internal/UriResolverTest.php | 10 - .../Schema/NestedRefResolutionTest.php | 10 - .../Schema/RefResolverCachePerfTest.php | 9 +- .../Schema/RefResolverOverrideTest.php | 48 ----- .../Unit/Validator/Schema/RefResolverTest.php | 31 --- .../Validator/Schema/SchemaHelperTest.php | 11 -- ...aluatedPropertiesWithDiscriminatorTest.php | 9 - .../AdditionalPropertiesErrorCapTest.php | 4 - ...ionalPropertiesValidatorImplodeCapTest.php | 13 -- .../AdditionalPropertiesValidatorTest.php | 8 - .../AdditionalPropertyErrorTest.php | 11 -- .../ArrayLengthValidatorTest.php | 28 --- .../BooleanSchemaKeywordTest.php | 5 - ...CompositionBranchOrderIndependenceTest.php | 27 --- .../ContentMediaTypeValidatorTest.php | 41 ---- .../NumericRangeValidatorTest.php | 37 ---- .../PatternPropertiesNormalizeCacheTest.php | 8 - .../PropertiesValidatorTest.php | 6 - .../PropertyNamesValidatorTest.php | 6 - .../ScalarKeyEquivalencePairTest.php | 6 - .../StringLengthValidatorTest.php | 35 ---- .../UnevaluatedItemsValidatorTest.php | 20 -- .../UnevaluatedPropertiesValidatorTest.php | 21 -- .../ValidationExceptionErrorsTest.php | 12 -- .../Security/SecurityValidatorTest.php | 112 ----------- ...nsupportedSecuritySchemeRegressionTest.php | 52 ----- .../Server/ServerUrlResolverTest.php | 12 -- tests/Unit/Validator/Util/Utf16Test.php | 12 -- 258 files changed, 186 insertions(+), 3852 deletions(-) diff --git a/rector.php b/rector.php index 2ce40f1d..af02ac41 100644 --- a/rector.php +++ b/rector.php @@ -21,11 +21,6 @@ ArrowFunctionDelegatingCallToFirstClassCallableRector::class, ClosureDelegatingCallToFirstClassCallableRector::class, ClosureToArrowFunctionRector::class, - // PHPDoc-only @deprecated skips — the named-constructors below delegate to the - // deprecated constructors, so converting the PHPDoc to #[Deprecated] would - // trigger E_DEPRECATED on every internal call. ADRs: - // - adr-schema-constructor.md (Schema 11b) - // - adr-validator-signatures-and-dtos.md (ValidationStack, ValidationContext 18) DeprecatedAnnotationToDeprecatedAttributeRector::class => [ __DIR__ . '/src/Schema/Model/Schema.php', __DIR__ . '/src/Validator/Validation/ValidationStack.php', diff --git a/src/Builder/OpenApiValidatorBuilder.php b/src/Builder/OpenApiValidatorBuilder.php index f91cd945..d69fbef9 100644 --- a/src/Builder/OpenApiValidatorBuilder.php +++ b/src/Builder/OpenApiValidatorBuilder.php @@ -108,16 +108,6 @@ public function withLogger(LoggerInterface $logger): self return $this->with(new BuilderConfig(logger: $logger)); } - /** - * Enable verbose PSR-3 logging of caller-sensitive security and - * external-ref diagnostics (scheme names, parameter locations, - * resolved filesystem paths). Without this call, the security - * validator and the builtin FileExternalRefResolver use a - * NullLogger, so the only signal an unauthenticated caller can - * observe is a generic exception message. Pass a logger whose - * audience is trusted (operators / a sealed log pipeline) to - * surface the underlying details at debug level. - */ public function withSecurityVerboseLogging(LoggerInterface $logger): self { return $this->with(new BuilderConfig(securityVerboseLogger: $logger)); @@ -128,20 +118,6 @@ public function withErrorFormatter(ErrorFormatterInterface $formatter): self return $this->with(new BuilderConfig(errorFormatter: $formatter)); } - /** - * Configure the validator to use {@see DetailedFormatter}, optionally with - * sensitive values (such as the raw input that failed format validation) - * included in the rendered error output. - * - * Default is `false`: raw invalid inputs are omitted from formatter output - * to prevent accidental disclosure of credentials sent against - * `format: password`, `format: uuid`, etc. (CWE-532). Pass `true` only in - * trusted debugging contexts. - * - * When chained with {@see withErrorFormatter()}, the call order wins: a - * subsequent `withErrorFormatter()` overrides the formatter installed by - * this method, and vice versa. - */ public function withDetailedErrors(bool $includeSensitive = false): self { return $this->with(new BuilderConfig( @@ -165,17 +141,6 @@ public function enableCoercion(): self return $this->with(new BuilderConfig(coercion: true)); } - /** - * Disable strict coercion mode and fall back to the legacy non-strict - * coercion behaviour. - * - * Strict coercion is the default since SEC-13/SEC-14/SEC-15: it rejects - * arbitrary strings coerced to boolean (e.g. "admin" no longer silently - * becomes true), throws on float-to-integer overflow outside the int64 - * range, and rejects numeric strings that lose precision when cast to - * float. Call this method only when the application explicitly relies on - * the legacy lax coercion semantics. - */ public function disableStrictCoercion(): self { return $this->with(new BuilderConfig(strictCoercion: false)); @@ -201,21 +166,6 @@ public function withEventDispatcher(EventDispatcherInterface $dispatcher): self return $this->with(new BuilderConfig(eventDispatcher: $dispatcher)); } - /** - * Override the directory that external file:// $ref references must - * remain inside. The default is auto-derived from the spec file - * directory (dirname of the realpath of the path passed to - * fromYamlFile / fromJsonFile), which keeps external refs inside the - * spec directory. Use this method to widen or narrow that root, for - * example to allow references into a shared sibling components - * directory. Passing a path that does not exist throws BuilderException - * at call time so the failure surfaces before build(). - * - * Call this method AFTER fromYamlFile / fromJsonFile: the auto-derive - * step unconditionally sets the value, so a withExternalRefAllowedRoot - * call placed before fromYamlFile / fromJsonFile will be silently - * overwritten. - */ public function withExternalRefAllowedRoot(string $path): self { $realPath = realpath($path); @@ -226,111 +176,51 @@ public function withExternalRefAllowedRoot(string $path): self return $this->with(new BuilderConfig(externalRefAllowedRoot: $realPath)); } - /** - * Enable security scheme validation for requests - * - * When enabled, the validator checks that required security credentials - * are present in the request headers, query parameters, or cookies. - */ public function enableSecurityValidation(): self { return $this->with(new BuilderConfig(securityValidation: true)); } - /** - * Enable server path resolution for request validation - * - * When enabled, the validator strips the base path defined in server URLs - * from the request path before matching against OpenAPI path templates. - * This allows validation of requests routed through a reverse proxy - * that prefixes paths with a version segment (e.g., /v1/users). - */ public function enableServerPathResolution(): self { return $this->with(new BuilderConfig(serverPathResolution: true)); } - /** - * Enable strict format validation - * - * When enabled, unknown format values are rejected during validation - * instead of being silently skipped. - */ public function enableStrictFormats(): self { return $this->with(new BuilderConfig(strictFormats: true)); } - /** - * Enable reporting of deprecated schema elements - * - * When enabled, deprecated fields in the OpenAPI specification are logged - * through the configured PSR-3 logger. - */ public function enableReportDeprecated(): self { return $this->with(new BuilderConfig(reportDeprecated: true)); } - /** - * Override the maximum allowed size, in bytes, for non-multipart request - * and response bodies (JSON, XML, text). Bodies larger than this cap are - * rejected before being fully materialised in memory. - */ public function withMaxJsonBodySize(int $maxBytes): self { return $this->with(new BuilderConfig(maxJsonBodyBytes: $maxBytes)); } - /** - * Override the maximum allowed size, in bytes, for multipart request and - * response bodies. multipart payloads typically carry larger uploads, so - * the cap is kept independent from the JSON cap. - */ public function withMaxMultipartBodySize(int $maxBytes): self { return $this->with(new BuilderConfig(maxMultipartBodyBytes: $maxBytes)); } - /** - * Enable strict streaming mode. - * - * When enabled, malformed JSON records in NDJSON, SSE, and JSON Text - * Sequence streams raise a MalformedStreamRecordException instead of being - * logged and skipped. This is an opt-in behaviour and remains disabled by - * default for backward compatibility. - */ public function enableStrictStreaming(): self { return $this->with(new BuilderConfig(strictStreaming: true)); } - /** - * Disable strict streaming mode. - * - * Restores the default fail-open behaviour where malformed JSON records - * are logged and skipped rather than raised. - */ public function disableStrictStreaming(): self { return $this->with(new BuilderConfig(strictStreaming: false)); } - /** - * Override the defensive pcre.backtrack_limit applied to every preg_match - * call routed through the PregExecutor wrapper. Lowering this cap below the - * PHP default (1_000_000) bounds the worst-case CPU cost of catastrophic - * regular expressions on attacker-controlled input such as JSON-Schema - * "pattern" fields. - */ public function withMaxRegexBacktracks(int $maxBacktracks): self { return $this->with(new BuilderConfig(maxRegexBacktracks: $maxBacktracks)); } - /** - * Enable strict callback runtime template resolution. - */ #[Deprecated(message: <<<'TXT' since 1.x, will be removed in 2.0. Strict mode is now the default: callback expressions that use runtime templates @@ -347,38 +237,13 @@ public function enableStrictCallbackRuntimeTemplate(): self return $this; } - /** - * Disable strict callback runtime template resolution. - * - * SECURITY WARNING: When disabled, callback expressions that use runtime - * templates such as `{$request.body#/callback_url}` are treated as - * wildcards that accept any URL, and declared security checks on the - * callback pathItem still pass against an attacker-controlled URL. If - * the resolved URL is then used by the application for an outbound HTTP - * request, this enables SSRF via the callback parameter. - * - * Only use this method when the application validates callback URLs - * through another mechanism (allowlist, signed URLs, application-level - * allowlist of outbound destinations). The strict default is the - * fail-closed posture recommended for new code. - */ public function disableStrictCallbackRuntimeTemplate(): self { return $this->with(new BuilderConfig(strictCallbackRuntimeTemplate: false)); } /** - * Override the maximum allowed size, in bytes, for external file:// $ref - * payloads loaded by the builtin FileExternalRefResolver. Files larger - * than this cap are rejected before being fully materialised in memory, - * defending against DoS via attacker-controlled large files or special - * files like /dev/zero. The default is 10 MB - * (FileExternalRefResolver::DEFAULT_MAX_REF_BYTES). - * - * @param int $bytes Positive integer size in bytes; values <= 0 raise - * InvalidArgumentException because they would either - * reject every file (0) or compare nonsensically - * against read counts (negative). + * @param int $bytes */ public function withExternalRefMaxBytes(int $bytes): self { @@ -388,18 +253,7 @@ public function withExternalRefMaxBytes(int $bytes): self } /** - * Override the maximum number of records the streaming content parser - * (NDJSON, SSE, JSON Text Sequences) will accept from a single response - * before raising {@see TooManyRecordsException}. - * - * The default is 100_000 records, sufficient for typical streaming APIs - * while bounding the memory impact of validating an attacker-controlled - * response composed of a very large number of small records. - * - * @param int $max Positive integer record cap; values <= 0 raise - * InvalidArgumentException because they would either - * reject every record (0) or compare nonsensically - * against an accumulated count (negative). + * @param int $max */ public function withMaxStreamingRecords(int $max): self { @@ -409,19 +263,7 @@ public function withMaxStreamingRecords(int $max): self } /** - * Override the maximum allowed size, in bytes, for an OpenAPI spec - * payload parsed by `YamlParser` or `JsonParser`. Specs larger than - * this cap are rejected before YAML or JSON parsing begins, defending - * against OOM on attacker-controlled or accidentally oversized specs - * (CWE-400, CWE-770). The default is 1 MB - * (`YamlParser::DEFAULT_MAX_SPEC_BYTES` / `JsonParser::DEFAULT_MAX_SPEC_BYTES`, - * same value) and is sized to accept typical OpenAPI documents - * including the bundled petstore spec. - * - * @param int $bytes Positive integer size in bytes; values <= 0 raise - * InvalidArgumentException because they would either - * reject every spec (0) or compare nonsensically - * against content length (negative). + * @param int $bytes */ public function withMaxSpecSize(int $bytes): self { @@ -431,19 +273,7 @@ public function withMaxSpecSize(int $bytes): self } /** - * Override the maximum allowed nesting depth for an OpenAPI spec - * payload parsed by `YamlParser` or `JsonParser`. Specs whose - * nesting exceeds this cap are rejected after parsing, defending - * against billion-laughs-style YAML or deeply-nested JSON that can - * cause stack overflow or OOM (closes SEC-18 for YAML, extends the - * same protection to JSON). The default is 100 - * (`YamlParser::DEFAULT_MAX_SPEC_DEPTH`) and is sized to accept - * typical OpenAPI documents including the bundled petstore spec. - * - * @param int $depth Positive integer depth cap; values <= 0 raise - * InvalidArgumentException because they would either - * reject every spec (0) or compare nonsensically - * against depth (negative). + * @param int $depth */ public function withMaxSpecDepth(int $depth): self { @@ -452,15 +282,6 @@ public function withMaxSpecDepth(int $depth): self return $this->with(new BuilderConfig(maxSpecDepth: $depth)); } - /** - * Terminal method: materialises the spec via {@see SpecLoader}, asserts - * external `$ref` confinement via {@see ExternalRefDetector}, then wires - * the validator dependencies and returns an {@see OpenApiValidatorInterface}. - * - * Call order is significant: the loader runs first to surface the - * canonical parse error, then the confinement guard fail-closes on - * string-loaded specs that contain an external `$ref`. Do not reorder. - */ public function build(): OpenApiValidatorInterface { $document = $this->specLoader()->load(); diff --git a/src/Cache/SchemaCache.php b/src/Cache/SchemaCache.php index 1b6d8ed8..f55147c3 100644 --- a/src/Cache/SchemaCache.php +++ b/src/Cache/SchemaCache.php @@ -14,10 +14,8 @@ private TypedCacheDecorator $decorator; /** - * Create a new schema cache. - * - * @param CacheItemPoolInterface $pool PSR-6 cache pool - * @param int $ttl Time to live in seconds (default: TypedCacheDecorator::DEFAULT_TTL) + * @param CacheItemPoolInterface $pool + * @param int $ttl */ public function __construct( CacheItemPoolInterface $pool, @@ -27,10 +25,8 @@ public function __construct( } /** - * Retrieve cached OpenAPI document. - * - * @param string $key Cache key - * @return OpenApiDocument|null Cached document or null if not found + * @param string $key + * @return OpenApiDocument|null */ public function get(string $key): ?OpenApiDocument { @@ -62,10 +58,8 @@ public function has(string $key): bool } /** - * Retrieve cached confinement verdict. - * - * @param string $key Cache key - * @return ConfinementVerdict|null Cached verdict or null if not found + * @param string $key + * @return ConfinementVerdict|null */ public function getConfinement(string $key): ?ConfinementVerdict { @@ -77,9 +71,7 @@ public function getConfinement(string $key): ?ConfinementVerdict } /** - * Store the clean confinement verdict under the given cache key. - * - * @param string $key Cache key + * @param string $key */ public function setConfinement(string $key): void { diff --git a/src/Registry/SchemaRegistry.php b/src/Registry/SchemaRegistry.php index 98ad96d5..48b75aff 100644 --- a/src/Registry/SchemaRegistry.php +++ b/src/Registry/SchemaRegistry.php @@ -56,15 +56,6 @@ public function __construct( $this->sortedVersions = $sortedVersions; } - /** - * Register a new schema under the given name and version. - * - * Fails fast by throwing {@see SchemaAlreadyRegisteredException} when the - * name+version pair is already registered. Use {@see registerOrReplace()} - * for explicit overwrite semantics (hot-reload, immutable replacement). - * - * @throws SchemaAlreadyRegisteredException When the name+version pair is already registered. - */ public function register(string $name, string $version, OpenApiDocument $document): self { if (isset($this->schemas[$name][$version])) { @@ -74,12 +65,6 @@ public function register(string $name, string $version, OpenApiDocument $documen return $this->registerOrReplace($name, $version, $document); } - /** - * Register a schema, replacing any existing entry for the same name+version. - * - * Intended for explicit overwrite use cases such as hot-reloading a spec - * in development or replacing a placeholder document with a final one. - */ public function registerOrReplace(string $name, string $version, OpenApiDocument $document): self { $newSchemas = $this->schemas; @@ -97,15 +82,6 @@ public function get(string $name, ?string $version = null): ?OpenApiDocument return $this->schemas[$name][$version] ?? null; } - /** - * Returns the document for the given schema and version, or throws if missing. - * - * Use this method when a missing schema or version is a programming error that - * must fail fast. For graceful access (e.g. conditional presence checks), use - * {@see has()} followed by {@see get()}. - * - * @throws VersionNotFoundException When the schema name or the requested version is not registered. - */ public function getOrFail(string $name, ?string $version = null): OpenApiDocument { $document = $this->get($name, $version); @@ -142,17 +118,11 @@ public function getNames(): array return array_keys($this->schemas); } - /** - * Returns the number of distinct schema names registered. - */ public function countNames(): int { return count($this->schemas); } - /** - * Returns the total number of name+version pairs registered across all schemas. - */ public function countSchemas(): int { $total = 0; diff --git a/src/Schema/Model/ArrayConstraints.php b/src/Schema/Model/ArrayConstraints.php index b4ed4a95..6baaeb52 100644 --- a/src/Schema/Model/ArrayConstraints.php +++ b/src/Schema/Model/ArrayConstraints.php @@ -7,7 +7,7 @@ final readonly class ArrayConstraints { /** - * @param list|null $prefixItems + * @param list|null $prefixItems */ public function __construct( public Schema|bool|null $items = null, diff --git a/src/Schema/Model/Internal/ArrayFields.php b/src/Schema/Model/Internal/ArrayFields.php index 980918df..bc2330d6 100644 --- a/src/Schema/Model/Internal/ArrayFields.php +++ b/src/Schema/Model/Internal/ArrayFields.php @@ -12,7 +12,7 @@ final readonly class ArrayFields { /** - * @param list|null $prefixItems + * @param list|null $prefixItems */ public function __construct( public Schema|bool|null $items = null, diff --git a/src/Schema/Model/Internal/BoundSiblingMerger.php b/src/Schema/Model/Internal/BoundSiblingMerger.php index d5de1f3e..87ff6857 100644 --- a/src/Schema/Model/Internal/BoundSiblingMerger.php +++ b/src/Schema/Model/Internal/BoundSiblingMerger.php @@ -72,10 +72,8 @@ public function merge(SiblingMergeContext $context): array /** * @template T of int|float - * * @param T|null $resolved * @param T|null $sibling - * * @return T|null */ private function mergeLowerBound(int|float|null $resolved, int|float|null $sibling): int|float|null @@ -93,10 +91,8 @@ private function mergeLowerBound(int|float|null $resolved, int|float|null $sibli /** * @template T of int|float - * * @param T|null $resolved * @param T|null $sibling - * * @return T|null */ private function mergeUpperBound(int|float|null $resolved, int|float|null $sibling): int|float|null @@ -144,7 +140,6 @@ private function mergeSchemaOrBool(Schema|bool|null $resolved, Schema|bool|null /** * @param ?list $resolved * @param ?list $sibling - * * @return ?list */ private function mergePrefixItems(?array $resolved, ?array $sibling): ?array diff --git a/src/Schema/Model/Internal/CompositionFields.php b/src/Schema/Model/Internal/CompositionFields.php index 63279c61..7d418b0d 100644 --- a/src/Schema/Model/Internal/CompositionFields.php +++ b/src/Schema/Model/Internal/CompositionFields.php @@ -12,9 +12,9 @@ final readonly class CompositionFields { /** - * @param list|null $allOf - * @param list|null $anyOf - * @param list|null $oneOf + * @param list|null $allOf + * @param list|null $anyOf + * @param list|null $oneOf */ public function __construct( public ?array $allOf = null, diff --git a/src/Schema/Model/Internal/CompositionSiblingMerger.php b/src/Schema/Model/Internal/CompositionSiblingMerger.php index 91668c33..67082113 100644 --- a/src/Schema/Model/Internal/CompositionSiblingMerger.php +++ b/src/Schema/Model/Internal/CompositionSiblingMerger.php @@ -52,7 +52,6 @@ public function merge(SiblingMergeContext $context): array /** * @param list $ifThenElseAdditions - * * @return list|null */ private function mergeAllOf(Schema $resolved, Schema $sibling, array $ifThenElseAdditions): ?array @@ -89,7 +88,6 @@ private function mergeAllOf(Schema $resolved, Schema $sibling, array $ifThenElse /** * @param ?list $resolvedComposition * @param ?list $siblingComposition - * * @return ?list */ private function wrapCompositionInAllOf( @@ -116,7 +114,6 @@ private function wrapCompositionInAllOf( /** * @param ?list $resolvedComposition * @param ?list $siblingComposition - * * @return ?list */ private function mergeCompositionField(?array $resolvedComposition, ?array $siblingComposition): ?array @@ -177,7 +174,6 @@ private function collectCompositionFieldAdditions(Schema $resolved, Schema $sibl /** * @param ?list $resolved * @param ?list $sibling - * * @return ?list */ private function mergeSchemaList(?array $resolved, ?array $sibling): ?array @@ -196,7 +192,6 @@ private function mergeSchemaList(?array $resolved, ?array $sibling): ?array /** * @param ?array $resolved * @param ?array $sibling - * * @return ?array */ private function mergeSchemaMap(?array $resolved, ?array $sibling): ?array diff --git a/src/Schema/Model/Internal/ObjectFields.php b/src/Schema/Model/Internal/ObjectFields.php index 30645a77..bb0ae9be 100644 --- a/src/Schema/Model/Internal/ObjectFields.php +++ b/src/Schema/Model/Internal/ObjectFields.php @@ -12,10 +12,10 @@ final readonly class ObjectFields { /** - * @param array|null $properties - * @param list|null $required - * @param array|null $patternProperties - * @param array|null $dependentSchemas + * @param array|null $properties + * @param list|null $required + * @param array|null $patternProperties + * @param array|null $dependentSchemas */ public function __construct( public ?array $properties = null, diff --git a/src/Schema/Model/Internal/ScalarFields.php b/src/Schema/Model/Internal/ScalarFields.php index c943e290..b37ebc44 100644 --- a/src/Schema/Model/Internal/ScalarFields.php +++ b/src/Schema/Model/Internal/ScalarFields.php @@ -14,12 +14,12 @@ final readonly class ScalarFields { /** - * @param string|list|null $type - * @param string|int|float|bool|array|null $default - * @param string|int|float|bool|array|null $const - * @param string|int|float|bool|array|null $example - * @param list|null $enum - * @param array|null $examples + * @param string|list|null $type + * @param string|int|float|bool|array|null $default + * @param string|int|float|bool|array|null $const + * @param string|int|float|bool|array|null $example + * @param list|null $enum + * @param array|null $examples */ public function __construct( public ?string $ref = null, diff --git a/src/Schema/Model/Internal/ScalarSiblingMerger.php b/src/Schema/Model/Internal/ScalarSiblingMerger.php index c662de10..dfed0177 100644 --- a/src/Schema/Model/Internal/ScalarSiblingMerger.php +++ b/src/Schema/Model/Internal/ScalarSiblingMerger.php @@ -63,7 +63,6 @@ public function mergeFormat(?string $resolved, ?string $sibling): ?string /** * @param string|list|null $resolved * @param string|list|null $sibling - * * @return string|list|null */ public function mergeType(string|array|null $resolved, string|array|null $sibling): string|array|null @@ -90,7 +89,6 @@ public function mergeType(string|array|null $resolved, string|array|null $siblin /** * @param ?list $resolved * @param ?list $sibling - * * @return ?list */ public function mergeEnum(?array $resolved, ?array $sibling): ?array @@ -114,10 +112,8 @@ public function mergeEnum(?array $resolved, ?array $sibling): ?array /** * @template T - * * @param T|null $resolved * @param T|null $sibling - * * @return T|null */ public function mergeNullableIdentical(mixed $resolved, mixed $sibling): mixed @@ -136,7 +132,6 @@ public function mergeNullableIdentical(mixed $resolved, mixed $sibling): mixed /** * @param ?list $resolved * @param ?list $sibling - * * @return ?list */ public function mergeStringList(?array $resolved, ?array $sibling): ?array @@ -155,7 +150,6 @@ public function mergeStringList(?array $resolved, ?array $sibling): ?array /** * @param ?array $resolved * @param ?array $sibling - * * @return ?array */ public function mergeMixedMap(?array $resolved, ?array $sibling): ?array diff --git a/src/Schema/Model/ObjectConstraints.php b/src/Schema/Model/ObjectConstraints.php index c0d63f46..e6a597d8 100644 --- a/src/Schema/Model/ObjectConstraints.php +++ b/src/Schema/Model/ObjectConstraints.php @@ -7,13 +7,13 @@ final readonly class ObjectConstraints { /** - * @param array|null $properties - * @param list|null $required - * @param Schema|bool|null $additionalProperties - * @param Schema|bool|null $unevaluatedProperties - * @param array|null $patternProperties - * @param array|null $dependentSchemas - * @param Schema|bool|null $propertyNames + * @param array|null $properties + * @param list|null $required + * @param Schema|bool|null $additionalProperties + * @param Schema|bool|null $unevaluatedProperties + * @param array|null $patternProperties + * @param array|null $dependentSchemas + * @param Schema|bool|null $propertyNames */ public function __construct( public ?array $properties = null, diff --git a/src/Schema/Model/Schema.php b/src/Schema/Model/Schema.php index b231c96b..877388ef 100644 --- a/src/Schema/Model/Schema.php +++ b/src/Schema/Model/Schema.php @@ -12,22 +12,6 @@ use JsonSerializable; use Override; -/** - * OpenAPI 3.2 / JSON Schema 2020-12 schema object. - * - * The historical facade keeps flat promoted properties so the 35+ existing - * consumers (validators, ref resolver, tests) keep working. The - * 56-field enumeration that used to live in jsonSerialize and in - * OpenApiBuilder::buildSchema now lives exactly once in - * {@see SchemaFieldMetadata}, consumed by - * {@see SchemaToArrayConverter} and {@see SchemaFromArrayConverter}. - * - * Sub-DTO accessors ({@see stringConstraints()}, {@see numericConstraints()}, - * {@see arrayConstraints()}, {@see objectConstraints()}, - * {@see compositionConstraints()}) expose the same fields as typed value - * objects for new code and for downstream tasks that migrate consumers off the - * flat API. They are derived lazily and never mutate the facade. - */ final readonly class Schema implements JsonSerializable { /** @@ -54,10 +38,7 @@ * @param list|null $enum * @param array|null $examples * @param Xml|null $xml - * * @deprecated since 1.x, will be removed in 2.0. Use {@see fromConstraintGroups()} instead. - * PHPDoc-only deprecation (no {@see Deprecated} attribute) so {@see fromConstraintGroups()} - * can delegate without runtime E_DEPRECATED cascade. See `.ai/reports/adr-schema-constructor.md`. */ public function __construct( public ?string $ref = null, @@ -143,14 +124,7 @@ public function __construct( * @param list|null $enum * @param array|null $examples * @param Xml|null $xml - * * @deprecated since 1.x, will be removed in 2.0. Use {@see withOverrideGroups()} instead. - * PHPDoc-only deprecation (no {@see Deprecated} attribute) so the internal - * callers (CompositionResolver and the schema tests) can invoke it without - * triggering a runtime E_DEPRECATED cascade. The attribute will be re-added - * when all internal callers are migrated to {@see withOverrideGroups()}, - * or the method is removed in 2.0 — whichever comes first. See - * `.ai/reports/adr-schema-constructor.md`. */ public function withOverrides( ?string $ref = null, @@ -273,13 +247,7 @@ enum: $enum ?? $this->enum, } /** - * Named-constructor that groups the 57 constructor parameters into 4 typed - * value-objects ({@see ScalarFields}, {@see ArrayFields}, {@see ObjectFields}, - * {@see CompositionFields}) plus an explicit `nullable` modifier. - * - * Prefer this over the deprecated {@see __construct} for new code. - * - * @param ?bool $nullable when null, falls back to `false` (the historical default) + * @param ?bool $nullable */ public static function fromConstraintGroups( ScalarFields $scalar, @@ -349,14 +317,6 @@ enum: $scalar->enum, ); } - /** - * Override-grouping replacement for the deprecated {@see withOverrides()}. - * - * Each value-object's non-null field overrides the corresponding field on - * `$this`; null fields preserve the existing value (override semantics). - * The `nullable` parameter follows the same rule: when null, the existing - * `nullable` is preserved; otherwise it is replaced. - */ public function withOverrideGroups( ScalarFields $scalar, ArrayFields $array, diff --git a/src/Schema/Model/SchemaSiblingMerger.php b/src/Schema/Model/SchemaSiblingMerger.php index 15021bbb..f501c66b 100644 --- a/src/Schema/Model/SchemaSiblingMerger.php +++ b/src/Schema/Model/SchemaSiblingMerger.php @@ -93,7 +93,6 @@ enum: $scalar['enum'], /** * @param ?list $resolved * @param ?list $sibling - * * @return ?list */ private function mergeRequired(?array $resolved, ?array $sibling): ?array @@ -112,7 +111,6 @@ private function mergeRequired(?array $resolved, ?array $sibling): ?array /** * @param ?array $resolved * @param ?array $sibling - * * @return ?array */ private function mergeExamples(?array $resolved, ?array $sibling): ?array diff --git a/src/Schema/Parser/ComponentsBuilder.php b/src/Schema/Parser/ComponentsBuilder.php index 7246b21d..bc53b60b 100644 --- a/src/Schema/Parser/ComponentsBuilder.php +++ b/src/Schema/Parser/ComponentsBuilder.php @@ -224,9 +224,7 @@ public function buildMediaTypesComponents(array $data): array /** * @template T - * * @param Closure(mixed): T $builder - * * @return array */ private function mapByName(array $data, Closure $builder): array diff --git a/src/Schema/Parser/Internal/ArraySchemaKeywordParser.php b/src/Schema/Parser/Internal/ArraySchemaKeywordParser.php index baba11ac..f706d81e 100644 --- a/src/Schema/Parser/Internal/ArraySchemaKeywordParser.php +++ b/src/Schema/Parser/Internal/ArraySchemaKeywordParser.php @@ -14,7 +14,6 @@ /** * @param array $data * @param Closure(bool|array): Schema $recurse - * * @return array{ * items: Schema|bool|null, * prefixItems: ?list, diff --git a/src/Schema/Parser/Internal/ComponentTreeBuilder.php b/src/Schema/Parser/Internal/ComponentTreeBuilder.php index a0276a19..a298d84b 100644 --- a/src/Schema/Parser/Internal/ComponentTreeBuilder.php +++ b/src/Schema/Parser/Internal/ComponentTreeBuilder.php @@ -194,9 +194,7 @@ private function buildSchemaFromKey(array $data, string $key): ?Schema /** * @template T - * * @param Closure(array): T $builder - * * @return T|null */ private function nullable(array $data, string $key, Closure $builder): mixed diff --git a/src/Schema/Parser/Internal/CompositionSchemaKeywordParser.php b/src/Schema/Parser/Internal/CompositionSchemaKeywordParser.php index 13ff631c..e0afcd22 100644 --- a/src/Schema/Parser/Internal/CompositionSchemaKeywordParser.php +++ b/src/Schema/Parser/Internal/CompositionSchemaKeywordParser.php @@ -15,7 +15,6 @@ /** * @param array $data * @param Closure(bool|array): Schema $recurse - * * @return array{ * ref: ?string, * refSummary: ?string, diff --git a/src/Schema/Parser/Internal/ObjectSchemaKeywordParser.php b/src/Schema/Parser/Internal/ObjectSchemaKeywordParser.php index 0b0417c0..511a3544 100644 --- a/src/Schema/Parser/Internal/ObjectSchemaKeywordParser.php +++ b/src/Schema/Parser/Internal/ObjectSchemaKeywordParser.php @@ -16,7 +16,6 @@ /** * @param array $data * @param Closure(bool|array): Schema $recurse - * * @return array{ * required: ?list, * properties: ?array, @@ -57,7 +56,6 @@ public function build(array $data, Closure $recurse): array /** * @param array $data * @param Closure(bool|array): Schema $recurse - * * @return array */ private function buildProperties(array $data, Closure $recurse): array diff --git a/src/Schema/Parser/Internal/ResponseTreeBuilder.php b/src/Schema/Parser/Internal/ResponseTreeBuilder.php index ec2ffe25..98903397 100644 --- a/src/Schema/Parser/Internal/ResponseTreeBuilder.php +++ b/src/Schema/Parser/Internal/ResponseTreeBuilder.php @@ -100,9 +100,7 @@ public function buildCallbacksMap(array $data): Callbacks /** * @template T - * * @param Closure(array): T $builder - * * @return T|null */ private function nullable(array $data, string $key, Closure $builder): mixed diff --git a/src/Schema/Parser/Internal/ScalarSchemaKeywordParser.php b/src/Schema/Parser/Internal/ScalarSchemaKeywordParser.php index 628b32e2..c96232fe 100644 --- a/src/Schema/Parser/Internal/ScalarSchemaKeywordParser.php +++ b/src/Schema/Parser/Internal/ScalarSchemaKeywordParser.php @@ -29,7 +29,6 @@ public function __construct( /** * @param array $data - * * @return array{ * multipleOf: ?float, * maximum: ?float, diff --git a/src/Schema/Parser/Internal/SchemaKeywordAccumulator.php b/src/Schema/Parser/Internal/SchemaKeywordAccumulator.php index 52563759..0c53f4f0 100644 --- a/src/Schema/Parser/Internal/SchemaKeywordAccumulator.php +++ b/src/Schema/Parser/Internal/SchemaKeywordAccumulator.php @@ -51,7 +51,6 @@ public function schemaOrBoolOrNull(array $data, string $key): Schema|bool|null /** * @param array $data - * * @return ?list */ public function schemaList(array $data, string $key): ?array diff --git a/src/Schema/Parser/YamlParser.php b/src/Schema/Parser/YamlParser.php index 022489ff..222d9b2f 100644 --- a/src/Schema/Parser/YamlParser.php +++ b/src/Schema/Parser/YamlParser.php @@ -27,14 +27,6 @@ final class YamlParser extends OpenApiBuilder public const int DEFAULT_MAX_SPEC_DEPTH = SpecSizeGuard::DEFAULT_MAX_SPEC_DEPTH; - /** - * Conservative caps for YAML anchor/alias expansion bombs - * (billion-laughs attack, CWE-400, CWE-770). Real OpenAPI specs - * typically use fewer than 20 anchors and 50 aliases for schema - * deduplication; these caps allow legitimate deduplication while - * rejecting exponential blowup before the Symfony YAML parser - * materialises the expanded document. - */ public const int MAX_ANCHORS = 100; public const int MAX_ALIASES = 1000; @@ -127,7 +119,6 @@ private function estimateAliasNestingDepth(string $content): int /** * @param list $lines - * * @return array */ private function findAnchorDeclarations(array $lines): array @@ -155,9 +146,8 @@ private function findAnchorDeclarations(array $lines): array } /** - * @param list $lines + * @param list $lines * @param array $anchors - * * @return array> */ private function buildAnchorChainDag(array $lines, array $anchors): array @@ -194,7 +184,7 @@ private function buildAnchorChainDag(array $lines, array $anchors): array /** * @param array $anchors - * @param array{line: int, indent: int} $parent + * @param array{line: int, indent: int} $parent */ private function findValueRangeEnd(array $anchors, array $parent, int $lineCount): int { @@ -210,7 +200,7 @@ private function findValueRangeEnd(array $anchors, array $parent, int $lineCount /** * @param array> $dag - * @param list $nodes + * @param list $nodes */ private function computeMaxChainDepth(array $dag, array $nodes): int { @@ -228,7 +218,7 @@ private function computeMaxChainDepth(array $dag, array $nodes): int /** * @param array> $dag - * @param array $visiting + * @param array $visiting */ private function chainDepthDfs(string $node, array $dag, ChainDepthMemo $memo, array $visiting): int { diff --git a/src/Schema/Serializer/Internal/ArraySchemaSerializer.php b/src/Schema/Serializer/Internal/ArraySchemaSerializer.php index 58ed0f27..bcd6df4f 100644 --- a/src/Schema/Serializer/Internal/ArraySchemaSerializer.php +++ b/src/Schema/Serializer/Internal/ArraySchemaSerializer.php @@ -88,7 +88,6 @@ private function schemaOrBoolToArray( /** * @param ?list $schemas - * * @return ?list */ private function schemaListToArray( diff --git a/src/Schema/Serializer/Internal/CompositionSchemaSerializer.php b/src/Schema/Serializer/Internal/CompositionSchemaSerializer.php index 5e4f531e..b7d88375 100644 --- a/src/Schema/Serializer/Internal/CompositionSchemaSerializer.php +++ b/src/Schema/Serializer/Internal/CompositionSchemaSerializer.php @@ -93,7 +93,6 @@ private function schemaOrBoolToArray( /** * @param ?list $schemas - * * @return ?list */ private function schemaListToArray( diff --git a/src/Schema/Serializer/Internal/ModelWireSerializer.php b/src/Schema/Serializer/Internal/ModelWireSerializer.php index 25fa7c81..31c39ec6 100644 --- a/src/Schema/Serializer/Internal/ModelWireSerializer.php +++ b/src/Schema/Serializer/Internal/ModelWireSerializer.php @@ -11,7 +11,6 @@ { /** * @param list $fields - * * @return array */ public static function toArray(object $model, array $fields): array diff --git a/src/Schema/Serializer/Internal/ObjectSchemaSerializer.php b/src/Schema/Serializer/Internal/ObjectSchemaSerializer.php index f9bb7242..5d81cb5e 100644 --- a/src/Schema/Serializer/Internal/ObjectSchemaSerializer.php +++ b/src/Schema/Serializer/Internal/ObjectSchemaSerializer.php @@ -95,7 +95,6 @@ private function schemaOrBoolToArray( /** * @param array|null $schemas - * * @return array|null */ private function schemaMapToArray( diff --git a/src/Schema/Serializer/SchemaToArrayConverter.php b/src/Schema/Serializer/SchemaToArrayConverter.php index 93bce04f..86213612 100644 --- a/src/Schema/Serializer/SchemaToArrayConverter.php +++ b/src/Schema/Serializer/SchemaToArrayConverter.php @@ -74,7 +74,6 @@ public function toWireArray(Schema $schema): array /** * @param WeakMap $visited - * * @return array */ public function toSnapshotArray(Schema $schema, WeakMap $visited): array diff --git a/src/Validator/BodyReader.php b/src/Validator/BodyReader.php index a559feea..60113671 100644 --- a/src/Validator/BodyReader.php +++ b/src/Validator/BodyReader.php @@ -13,13 +13,6 @@ { private const int CHUNK_SIZE = 8192; - /** - * Enforces the byte cap on every chunk so that an attacker-controlled - * body is never fully materialised in memory before the limit applies, - * even when getSize() is unknown (chunked transfer-encoding). - * - * @throws BodyTooLargeException When the stream exceeds the configured cap. - */ public static function readSafely(StreamInterface $stream, int $maxBytes): string { $size = $stream->getSize(); diff --git a/src/Validator/Callback/CallbackValidator.php b/src/Validator/Callback/CallbackValidator.php index 5346ae24..8bbe5d00 100644 --- a/src/Validator/Callback/CallbackValidator.php +++ b/src/Validator/Callback/CallbackValidator.php @@ -50,16 +50,7 @@ ]; /** - * @param bool $strictCallbackRuntimeTemplate Defaults to true (fail-closed): - * callback expressions containing runtime templates - * (e.g. `{$request.body#/callback_url}`) that cannot be resolved by - * the validator throw {@see UnresolvableCallbackPathException} - * instead of being treated as wildcards that accept any URL. This - * matches the `OpenApiValidatorBuilder` default and prevents SSRF - * via attacker-controlled runtime templates when the resolved URL - * is used for an outbound HTTP request. Pass false explicitly only - * when callback URLs are validated at the application level (see - * README section "Callbacks" for the security implications). + * @param bool $strictCallbackRuntimeTemplate */ public function __construct( private readonly RequestValidatorInterface $requestValidator, @@ -154,7 +145,6 @@ private function getCallbackExpressions(Callbacks $callbacks, string $callbackNa /** * @param array $pathItems - * * @return array{0: Operation, 1: string} */ private function extractOperation( diff --git a/src/Validator/Coercion/IntegerStringNormalizer.php b/src/Validator/Coercion/IntegerStringNormalizer.php index 7efca87d..706eb8a4 100644 --- a/src/Validator/Coercion/IntegerStringNormalizer.php +++ b/src/Validator/Coercion/IntegerStringNormalizer.php @@ -11,14 +11,6 @@ { public const string INTEGER_PATTERN = '/^[+-]?\d+$/'; - /** - * Returns the canonical form of an integer string: optional leading minus, - * no leading plus, no leading zeros (except for the value zero itself). - * - * Used to detect silent overflow of `(int) $value` cast: a value that - * passes `/^[+-]?\d+$/` but whose canonical form does not equal - * `(string) (int) $value` is out of int64 range. - */ public static function canonicalize(string $value): string { $first = $value[0]; diff --git a/src/Validator/Coercion/NumberStringNormalizer.php b/src/Validator/Coercion/NumberStringNormalizer.php index 5f385a92..dd8856f3 100644 --- a/src/Validator/Coercion/NumberStringNormalizer.php +++ b/src/Validator/Coercion/NumberStringNormalizer.php @@ -27,18 +27,6 @@ private const int MAX_DOUBLE_EXPONENT = 320; - /** - * Returns the canonical decimal form of a numeric string, or null if the - * input is not a recognised integer/decimal/scientific value. - * - * Used to detect silent precision loss of `(float) $value` cast: a value - * that passes the coerceToNumber regex but whose canonical form does not - * equal the canonical form of the round-tripped float loses precision - * when coerced to float. - * - * @throws InvalidNumericStringException when a scientific-notation - * exponent exceeds the representable range of a double - */ public static function canonicalize(string $value): ?string { if (1 !== preg_match(self::NUMBER_PATTERN, $value)) { @@ -60,24 +48,6 @@ public static function canonicalize(string $value): ?string return self::normalizeDecimal($sign, $expanded); } - /** - * Casts a numeric string to float and rejects values that lose precision - * when round-tripped through IEEE-754 double. Detects precision loss - * visible at the string representation level (e.g., 17+ significant - * digits). Does NOT prevent magic-hash type-juggling collisions for the - * 0eNNN pattern (both inputs canonicalize to "0" and pass) - that - * requires strict equality in downstream comparisons, not coercion-time - * rejection. - * - * Also rejects scientific-notation values whose exponent exceeds the - * representable range of a double before their canonical expansion would - * allocate unbounded zero padding via str_repeat (e.g. `1e999999999` - * would allocate ~1 GB of zeros). - * - * @throws TypeMismatchError when the input cannot be represented as float - * without precision loss, or when its scientific-notation exponent - * exceeds the representable range of a double. - */ public static function castStringToFloatOrFail(string $value, string $dataPath = ''): float { $inputCanonical = self::canonicalizeOrThrow($value, $dataPath); diff --git a/src/Validator/Error/ValidationContext.php b/src/Validator/Error/ValidationContext.php index 69ad606d..d8e6e20d 100644 --- a/src/Validator/Error/ValidationContext.php +++ b/src/Validator/Error/ValidationContext.php @@ -12,30 +12,6 @@ use Duyler\OpenApi\Validator\ValidatorMode; use Duyler\OpenApi\Validator\ValidatorPool; -/** - * Per-validation mutable state: breadcrumb stack (dataPath assembly), - * recursion depth counter (MAX_DEPTH DoS guard), and JSON Schema 2020-12 - * annotation-state for unevaluatedProperties / unevaluatedItems tracking. - * - * Annotation contract (R3-SPEC-001..004): keywords that successfully - * evaluate portions of the instance — properties, patternProperties, - * additionalProperties, prefixItems, items, contains, and every - * successful branch of an in-place applicator (allOf, anyOf, oneOf, - * if/then/else, $ref) — register the evaluated property names / item - * indices here. unevaluatedProperties / unevaluatedItems read the - * resulting sets to decide what remains unevaluated. `not` registers - * nothing: per §10.3.4 it contributes an empty annotation set. - * - * Concurrency contract (P-062): one instance per validate() entry-point - * call. The instance MUST NOT be stored as a property on a shared - * validator — it is passed as a method argument through the recursion - * chain. Under prefork (PHP-FPM, RoadRunner) each request implicitly - * gets a fresh call stack. Under shared-validator runtimes (Swoole - * coroutines, FrankenPHP threaded workers) the same validator instance - * handles many sequential requests, but each validate() call creates a - * fresh context — coroutine A and coroutine B never observe each - * other's breadcrumbs, depth, or annotation state. - */ final class ValidationContext { public const int MAX_DEPTH = 64; @@ -48,8 +24,6 @@ final class ValidationContext /** * @deprecated since 1.x, will be removed in 2.0. Use {@see fromInit()} instead. - * PHPDoc-only deprecation (no {@see \Deprecated} attribute) so {@see fromInit()} - * can delegate without runtime E_DEPRECATED cascade. See `.ai/reports/adr-validator-signatures-and-dtos.md`. */ public function __construct( public readonly BreadcrumbManager $breadcrumbs, @@ -63,8 +37,6 @@ public function __construct( /** * @deprecated since 1.x, will be removed in 2.0. Use {@see fromInit()} instead. - * PHPDoc-only deprecation (no {@see \Deprecated} attribute) so internal callers - * keep working without runtime E_DEPRECATED cascade. See `.ai/reports/adr-validator-signatures-and-dtos.md`. */ public static function create( ValidatorPool $pool, @@ -161,27 +133,12 @@ public function hasItemBeenEvaluated(int $index): bool return isset($this->evaluatedItemIndices[$index]); } - /** - * Merges annotation state from a child branch context (composition - * sub-validation) into this context. Called after a successful - * sub-validation in AllOf / AnyOf / OneOf / If / Then / Else. - * - * Failed branches MUST NOT have their annotations merged — only - * successfully validated subschemas contribute to the evaluated set - * per JSON Schema 2020-12 §10.3.4 / §11.1.1.3. - */ public function mergeChildAnnotations(self $child): void { $this->evaluatedPropertyNames += $child->evaluatedPropertyNames; $this->evaluatedItemIndices += $child->evaluatedItemIndices; } - /** - * Creates a child context sharing breadcrumbs and depth with this - * context but starting with empty annotation state. Used by - * composition validators to isolate annotations of each branch - * from siblings until a branch succeeds. - */ public function forkForBranch(): self { return new self( diff --git a/src/Validator/EventDispatchingTrait.php b/src/Validator/EventDispatchingTrait.php index 61487f17..11d13170 100644 --- a/src/Validator/EventDispatchingTrait.php +++ b/src/Validator/EventDispatchingTrait.php @@ -22,9 +22,7 @@ private function dispatchValidationEvent(object $event): void /** * @template T - * * @param callable(): T $callback - * * @return T */ private function withValidationEvents( diff --git a/src/Validator/Example/ExampleValidator.php b/src/Validator/Example/ExampleValidator.php index 51b781a1..01f342c4 100644 --- a/src/Validator/Example/ExampleValidator.php +++ b/src/Validator/Example/ExampleValidator.php @@ -123,7 +123,6 @@ private function collectMediaTypeExamples(MediaType $mediaType): array /** * @param array $source * @param list $target - * * @return list */ private function extractExampleValues(array $source, array $target): array diff --git a/src/Validator/Exception/InvalidFormatException.php b/src/Validator/Exception/InvalidFormatException.php index 93b8141c..16328c71 100644 --- a/src/Validator/Exception/InvalidFormatException.php +++ b/src/Validator/Exception/InvalidFormatException.php @@ -20,13 +20,6 @@ public function __construct( ); } - /** - * Returns the validated value. Pass $reveal = true only from trusted - * operator code (security auditor, verbose logger with opt-in - * includeSensitiveValues); the default returns '' to - * prevent disclosure of credentials (passwords, tokens) through - * reflective serialization. - */ public function value(bool $reveal = false): mixed { return $reveal ? $this->value : ''; diff --git a/src/Validator/Exception/InvalidMultipleOfSchemaException.php b/src/Validator/Exception/InvalidMultipleOfSchemaException.php index 6452db2c..82e090b8 100644 --- a/src/Validator/Exception/InvalidMultipleOfSchemaException.php +++ b/src/Validator/Exception/InvalidMultipleOfSchemaException.php @@ -22,7 +22,7 @@ public static function forNonPositiveValue(float $multipleOf): self } #[Deprecated( - message: 'since R4-CORRECTNESS-008: NumericRangeValidator::isMultipleOf now ' + message: 'NumericRangeValidator::isMultipleOf now ' . 'uses pure-PHP decimal string modulus when bcmath is unavailable, ' . 'so this factory is no longer thrown from the validator. Retained ' . 'for backward compatibility with external callers; will be removed ' diff --git a/src/Validator/Exception/InvalidParameterException.php b/src/Validator/Exception/InvalidParameterException.php index 6d5df052..6e890643 100644 --- a/src/Validator/Exception/InvalidParameterException.php +++ b/src/Validator/Exception/InvalidParameterException.php @@ -7,14 +7,6 @@ use RuntimeException; use Throwable; -/** - * Carries attacker-controlled parameter metadata without leaking it into - * the rendered message. The constructor's $message argument is intentionally - * discarded — getMessage() always returns the static string - * 'Invalid parameter configuration' so a PSR-15 middleware cannot be - * turned into a reflective XSS or log-injection sink by a crafted - * parameter name (CWE-209, CWE-532). - */ final class InvalidParameterException extends RuntimeException { use SanitizableExceptionTrait; @@ -42,12 +34,6 @@ public static function malformedValue(string $parameterName, string $message, in return new self($parameterName, $message, $code, $previous); } - /** - * Returns the spec-defined parameter name. Pass $reveal = true only - * from trusted operator code; the default returns '' to - * prevent reflective serialization from leaking attacker probes - * verbatim into logs. - */ public function parameterName(bool $reveal = false): string { return $reveal ? $this->parameterName : ''; diff --git a/src/Validator/Exception/InvalidUtf8Exception.php b/src/Validator/Exception/InvalidUtf8Exception.php index 9f99ac00..51351fff 100644 --- a/src/Validator/Exception/InvalidUtf8Exception.php +++ b/src/Validator/Exception/InvalidUtf8Exception.php @@ -6,12 +6,6 @@ use RuntimeException; -/** - * Thrown when input that must be UTF-8 per RFC 8259 §8.1 contains byte - * sequences that are not valid UTF-8. PHP's json_decode() does not enforce - * UTF-8 validity by default, so JsonBodyParser and JsonParser reject such - * input via mb_check_encoding() before decoding. - */ final class InvalidUtf8Exception extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Exception/MissingSecurityCredentialsError.php b/src/Validator/Exception/MissingSecurityCredentialsError.php index 66b0dfd8..51c75d5f 100644 --- a/src/Validator/Exception/MissingSecurityCredentialsError.php +++ b/src/Validator/Exception/MissingSecurityCredentialsError.php @@ -4,23 +4,6 @@ namespace Duyler\OpenApi\Validator\Exception; -/** - * Thrown when a security scheme requirement is not satisfied by the - * incoming request. - * - * SEC-07 / CWE-209: the public exception message is intentionally - * generic so an unauthenticated caller cannot enumerate the API's - * security surface (scheme names, parameter locations, header names). - * The concrete scheme details are still available as readonly - * properties on this object for programmatic access by trusted - * operators, and the {@see SecurityValidator} forwards them to a - * PSR-3 logger at debug level when one is configured. - * - * SEC-032 / CWE-209 / CWE-497: scheme details are exposed only via - * explicit opt-in getters that require $reveal = true from trusted - * callers. Direct property access throws Error: Cannot access - * protected property. - */ final class MissingSecurityCredentialsError extends AbstractValidationError { public function __construct( @@ -37,34 +20,16 @@ public function __construct( ); } - /** - * Returns the security scheme name (e.g. 'bearerAuth'). Pass - * $reveal = true only from trusted operator code; the default - * returns '' to prevent disclosure of the API's security - * surface through reflective serialization. - */ public function schemeName(bool $reveal = false): string { return $reveal ? $this->schemeName : ''; } - /** - * Returns the security scheme type (e.g. 'http/bearer'). Pass - * $reveal = true only from trusted operator code; the default - * returns '' to prevent disclosure of the API's security - * surface through reflective serialization. - */ public function schemeType(bool $reveal = false): string { return $reveal ? $this->schemeType : ''; } - /** - * Returns the credential location description (e.g. 'Authorization - * header'). Pass $reveal = true only from trusted operator code; - * the default returns '' to prevent disclosure of the - * API's security surface through reflective serialization. - */ public function location(bool $reveal = false): string { return $reveal ? $this->location : ''; diff --git a/src/Validator/Exception/NestedValidationError.php b/src/Validator/Exception/NestedValidationError.php index 763e6699..1475dc7c 100644 --- a/src/Validator/Exception/NestedValidationError.php +++ b/src/Validator/Exception/NestedValidationError.php @@ -4,12 +4,6 @@ namespace Duyler\OpenApi\Validator\Exception; -/** - * Fallback validation error used when a nested validator throws a - * `ValidationException` without structured `errors`. The original - * message is preserved verbatim so the middleware can render a - * diagnostic without asserting a specific nested keyword. - */ final class NestedValidationError extends AbstractValidationError { public function __construct( diff --git a/src/Validator/Exception/PregRuntimeException.php b/src/Validator/Exception/PregRuntimeException.php index 929bcaed..6292f636 100644 --- a/src/Validator/Exception/PregRuntimeException.php +++ b/src/Validator/Exception/PregRuntimeException.php @@ -8,15 +8,6 @@ use function sprintf; -/** - * Thrown when a PCRE function reports a non-zero error via preg_last_error(). - * - * Such errors indicate that PCRE hit an internal limit (backtrack_limit, - * recursion_limit) or encountered a JIT stack overflow, and the return value - * of preg_match / preg_match_all cannot be trusted as a definitive answer. - * Validation cannot proceed reliably in this state, so the PregExecutor - * surfaces the failure rather than silently treating it as "no match". - */ final class PregRuntimeException extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Exception/SanitizableExceptionTrait.php b/src/Validator/Exception/SanitizableExceptionTrait.php index 4ebb7776..801f63d6 100644 --- a/src/Validator/Exception/SanitizableExceptionTrait.php +++ b/src/Validator/Exception/SanitizableExceptionTrait.php @@ -7,9 +7,6 @@ use Override; /** - * Prevents CWE-209 / CWE-497 leakage: overrides Exception::__toString() to return only - * the message, suppressing class name, file path, and stack trace in (string) $e casts. - * * @psalm-external-mutation-free */ trait SanitizableExceptionTrait diff --git a/src/Validator/Exception/SpecTooLargeException.php b/src/Validator/Exception/SpecTooLargeException.php index 114fedb2..180280db 100644 --- a/src/Validator/Exception/SpecTooLargeException.php +++ b/src/Validator/Exception/SpecTooLargeException.php @@ -9,12 +9,6 @@ use function sprintf; -/** - * Thrown when an OpenAPI spec payload exceeds the configured size or nesting - * depth limit (YamlParser). Defends against billion-laughs-style YAML that can - * cause stack overflow or OOM during parsing. The size check runs BEFORE parse - * so an attacker cannot force the parser to materialise an oversized document. - */ final class SpecTooLargeException extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Exception/UnresolvableCallbackPathException.php b/src/Validator/Exception/UnresolvableCallbackPathException.php index b229495d..ac762b43 100644 --- a/src/Validator/Exception/UnresolvableCallbackPathException.php +++ b/src/Validator/Exception/UnresolvableCallbackPathException.php @@ -5,21 +5,9 @@ namespace Duyler\OpenApi\Validator\Exception; use RuntimeException; -use Duyler\OpenApi\Builder\OpenApiValidatorBuilder; use function sprintf; -/** - * Thrown when a callback expression uses a runtime template (e.g. - * `{$request.body#/callback_url}`) and strict callback runtime template - * resolution is enabled. - * - * Strict mode is the default since the SEC-09 fix: the builder's - * `?? true` fallback in `OpenApiValidatorBuilder::build()` enables it - * unless {@see OpenApiValidatorBuilder::disableStrictCallbackRuntimeTemplate()} - * is called. The legacy {@see OpenApiValidatorBuilder::enableStrictCallbackRuntimeTemplate()} - * method is retained as a deprecated no-op. - */ final class UnresolvableCallbackPathException extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Exception/UnsupportedSecuritySchemeException.php b/src/Validator/Exception/UnsupportedSecuritySchemeException.php index 7eb69156..0021dc5e 100644 --- a/src/Validator/Exception/UnsupportedSecuritySchemeException.php +++ b/src/Validator/Exception/UnsupportedSecuritySchemeException.php @@ -8,25 +8,6 @@ use function sprintf; -/** - * Thrown when an OpenAPI security scheme uses a type that this package - * does not validate. The validator supports `http/bearer` and `apiKey` - * only; schemes such as `oauth2`, `openIdConnect`, `http/basic`, - * `http/digest`, and `mutualTLS` require an external token validator - * (introspection endpoint, JWT signature check, JWKS) and are rejected - * explicitly so consumers learn about the configuration error instead - * of seeing the scheme silently classified as "missing credentials". - * - * R4-SEC-010: misclassifying an unsupported scheme as a missing - * credential both misleads callers (who believe they only need to - * supply the credential) and breaks AND/OR semantics for mixed - * security requirements. - * - * This exception is a configuration-time signal: a spec that mixes - * supported and unsupported schemes is invalid under partial - * validation, so the validator fails closed rather than silently - * bypassing the unsupported requirement. - */ final class UnsupportedSecuritySchemeException extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Exception/ValidationException.php b/src/Validator/Exception/ValidationException.php index 19f45f5c..7a937dbc 100644 --- a/src/Validator/Exception/ValidationException.php +++ b/src/Validator/Exception/ValidationException.php @@ -8,12 +8,6 @@ use Throwable; /** - * Thrown when request, response, or schema validation fails. - * - * Subclasses MUST preserve the contract of getErrors() returning - * array so consumers can iterate the - * typed error list uniformly. - * * @api Public API: consumers may subclass to attach domain context. */ class ValidationException extends Exception diff --git a/src/Validator/Format/FormatRegistry.php b/src/Validator/Format/FormatRegistry.php index 9aeff682..3a35c503 100644 --- a/src/Validator/Format/FormatRegistry.php +++ b/src/Validator/Format/FormatRegistry.php @@ -4,8 +4,6 @@ namespace Duyler\OpenApi\Validator\Format; -use Duyler\OpenApi\Builder\OpenApiValidatorBuilder; - final readonly class FormatRegistry { /** @@ -36,16 +34,6 @@ public function hasFormat(string $type, string $format): bool return isset($this->validators[$type][$format]); } - /** - * Returns a new registry whose entries are the union of $base and - * the current registry's entries, with the current registry's - * entries overriding $base on (type, format) conflict. - * - * Used by {@see OpenApiValidatorBuilder::build()} - * to ensure builtin format validators share the configured - * PregExecutor even when the caller registered custom formats via - * withFormat() before withMaxRegexBacktracks(). - */ public function withBase(self $base): self { $merged = $base->validators; diff --git a/src/Validator/Internal/CandidatePrioritizer.php b/src/Validator/Internal/CandidatePrioritizer.php index 5aeaa03c..6e935ec3 100644 --- a/src/Validator/Internal/CandidatePrioritizer.php +++ b/src/Validator/Internal/CandidatePrioritizer.php @@ -22,7 +22,6 @@ public function compareByPlaceholderCount(array $a, array $b): int /** * @param array}> $candidates - * * @return array{0: Operation, 1: array} */ public function prioritize(array $candidates): array diff --git a/src/Validator/Internal/LruCache.php b/src/Validator/Internal/LruCache.php index 0eec87c6..e0612836 100644 --- a/src/Validator/Internal/LruCache.php +++ b/src/Validator/Internal/LruCache.php @@ -14,7 +14,6 @@ /** * @internal - * * @template K of string * @template V */ @@ -37,7 +36,6 @@ public function __construct(private readonly int $maxSize) /** * @param K $key - * * @return V|null */ public function get(string $key): mixed diff --git a/src/Validator/Internal/TrieBuilder.php b/src/Validator/Internal/TrieBuilder.php index cbd60116..2bc1fc8d 100644 --- a/src/Validator/Internal/TrieBuilder.php +++ b/src/Validator/Internal/TrieBuilder.php @@ -23,7 +23,6 @@ /** * @param array $paths - * * @return array{0: array, 1: array} */ public function buildTrie(array $paths): array @@ -53,7 +52,7 @@ private function insertTemplate(array $node, string $template, PathItem $pathIte /** * @param array $node - * @param list $segments + * @param list $segments */ private function insertSegments(array $node, array $segments, int $depth, string $template, PathItem $pathItem): array { diff --git a/src/Validator/Internal/TrieLookup.php b/src/Validator/Internal/TrieLookup.php index 3c20230c..b162e7e6 100644 --- a/src/Validator/Internal/TrieLookup.php +++ b/src/Validator/Internal/TrieLookup.php @@ -18,9 +18,9 @@ /** * @param array $node - * @param list $segments - * @param int<0, max> $depth - * @param TrieMatches $matches + * @param list $segments + * @param int<0, max> $depth + * @param TrieMatches $matches */ public function lookupTrie(array $node, array $segments, int $depth, TrieMatches $matches): void { diff --git a/src/Validator/JsonDepthLimit.php b/src/Validator/JsonDepthLimit.php index f2b7ff8d..9cf6cb3b 100644 --- a/src/Validator/JsonDepthLimit.php +++ b/src/Validator/JsonDepthLimit.php @@ -4,21 +4,6 @@ namespace Duyler\OpenApi\Validator; -/** - * JSON parsing depth limit, classified by threat model. - * - * Selecting a case is the only way to set the depth passed to json_decode(), - * which makes the rationale for the two distinct limits explicit at the type - * level and prevents silent alignment to a value that is unsafe for one path. - * - * Untrusted (128): for attacker-controlled input — HTTP request bodies - * (JsonBodyParser), JSON-encoded query parameter values (QueryParser), - * deepObject query parameter values (ParameterDeserializer), and user- - * controlled content validated through contentMediaType, where a deep - * payload is an inexpensive DoS vector. - * Trusted (512): for OpenAPI specifications and already-sanitised internal - * data, where deep nesting is expected and the input is not attacker-controlled. - */ enum JsonDepthLimit: int { case Untrusted = 128; diff --git a/src/Validator/LibxmlSecuredContext.php b/src/Validator/LibxmlSecuredContext.php index f53b3e1a..9d312d43 100644 --- a/src/Validator/LibxmlSecuredContext.php +++ b/src/Validator/LibxmlSecuredContext.php @@ -6,45 +6,12 @@ use Closure; -/** - * Hardened libxml runtime context for XXE-safe XML parsing. - * - * @danger NOT_THREAD_SAFE - * - * libxml_use_internal_errors and libxml_set_external_entity_loader are - * process-global. Under Swoole coroutines the capture/restore sequence - * in {@see run()} races with concurrent XML parsing in other - * coroutines, leaving the process either without an entity loader or - * silently bypassing XXE protection for an in-flight coroutine - * (O-006, S-011). See README "Unsafe classes and their contracts". - */ final readonly class LibxmlSecuredContext { /** - * Runs the given work with a hardened libxml configuration that prevents - * XML External Entity (XXE) attacks and isolates libxml global state from - * the surrounding process. - * - * Installs a deny-all external entity loader (so SYSTEM/PUBLIC references - * cannot resolve file://, http://, or any other scheme), enables internal - * error buffering, and restores both libxml_use_internal_errors and the - * previous external entity loader in finally — even if the work throws. - * This encapsulation is mandatory for long-running runtimes (RoadRunner, - * FrankenPHP, Swoole) where libxml state is shared across requests and - * coroutines, so adjacent XML parsing must not be left with a deny-all - * loader after this helper returns. - * - * The work closure is responsible only for the actual parsing call, - * including the LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING flags - * via the options named argument of simplexml_load_string. Never combine - * this with LIBXML_NOENT — entity substitution must stay off, otherwise - * the deny-all loader remains the only line of defense. - * * @template T - * - * @param Closure(): T $work work that performs the libxml parsing - * - * @return T whatever the work closure returns + * @param Closure(): T $work + * @return T */ public static function run(Closure $work): mixed { diff --git a/src/Validator/Link/Internal/RequestScope.php b/src/Validator/Link/Internal/RequestScope.php index 5d644cbb..9cb3a66d 100644 --- a/src/Validator/Link/Internal/RequestScope.php +++ b/src/Validator/Link/Internal/RequestScope.php @@ -8,8 +8,8 @@ final readonly class RequestScope { /** - * @param array $pathParams - * @param array $requestHeaders + * @param array $pathParams + * @param array $requestHeaders */ public function __construct( public readonly string $url = '', diff --git a/src/Validator/Link/Internal/ResponseScope.php b/src/Validator/Link/Internal/ResponseScope.php index 591d7aa6..915aa05e 100644 --- a/src/Validator/Link/Internal/ResponseScope.php +++ b/src/Validator/Link/Internal/ResponseScope.php @@ -8,9 +8,9 @@ final readonly class ResponseScope { /** - * @param array $body - * @param array $headers - * @param array $queryParams + * @param array $body + * @param array $headers + * @param array $queryParams */ public function __construct( public readonly array $body = [], diff --git a/src/Validator/Link/LinkContext.php b/src/Validator/Link/LinkContext.php index 1f234c90..7257f13e 100644 --- a/src/Validator/Link/LinkContext.php +++ b/src/Validator/Link/LinkContext.php @@ -7,21 +7,14 @@ use Duyler\OpenApi\Validator\Link\Internal\RequestScope; use Duyler\OpenApi\Validator\Link\Internal\ResponseScope; -/** - * Carries the runtime context required to evaluate OpenAPI 3.2 §6.19.2 - * Runtime Expressions inside Link parameters and request bodies. - * - * The same queryParams array backs both $request.query and $response.query - * expressions since the underlying query string is shared. - */ final readonly class LinkContext { /** - * @param array $body Response body data (decoded JSON or equivalent) - * @param array $headers Response headers (header name => value) - * @param array $queryParams Query string parameters shared by request and response scope - * @param array $pathParams Request path parameters (path template variable => value) - * @param array $requestHeaders Request headers (header name => value, case-insensitive lookup) + * @param array $body + * @param array $headers + * @param array $queryParams + * @param array $pathParams + * @param array $requestHeaders */ public function __construct( public array $body = [], @@ -35,14 +28,6 @@ public function __construct( public mixed $requestBody = null, ) {} - /** - * Type-safe named-constructor splitting the LinkContext fields into - * request-scope and response-scope. Prefer this over the constructor - * at call-sites that supply fields from both scopes; the constructor - * remains the canonical public API documented in the README. - * - * @see self::__construct() - */ public static function fromGroups(RequestScope $request, ResponseScope $response): self { return new self( diff --git a/src/Validator/Link/LinkResolver.php b/src/Validator/Link/LinkResolver.php index a8edfd08..41a2fcf2 100644 --- a/src/Validator/Link/LinkResolver.php +++ b/src/Validator/Link/LinkResolver.php @@ -38,7 +38,6 @@ public function resolve(Link $link, LinkContext $context): ResolvedLink /** * @param array|null $parameters - * * @return array */ private function resolveParameters(?array $parameters, LinkContext $context): array diff --git a/src/Validator/OpenApiValidator.php b/src/Validator/OpenApiValidator.php index 8e230670..7c524c22 100644 --- a/src/Validator/OpenApiValidator.php +++ b/src/Validator/OpenApiValidator.php @@ -108,13 +108,7 @@ public function validateCallback(ServerRequestInterface $request, string $callba } /** - * Resolve link parameters from response data. - * - * Limitation: this method only resolves component-level links - * (defined under components/links). Operation-level links defined - * inline within a response's links property are not supported. - * - * @param array $responseData Response body data to extract values from + * @param array $responseData */ #[Override] public function resolveLink(string $linkName, array $responseData): ResolvedLink @@ -124,13 +118,6 @@ public function resolveLink(string $linkName, array $responseData): ResolvedLink return $this->resolveLinkWithContext($linkName, $context); } - /** - * Resolves link parameters using full Runtime Expression context. - * - * Limitation: only component-level links (defined under - * components/links) are resolved. Operation-level links defined - * inline within a response's links property are not supported. - */ #[Override] public function resolveLinkWithContext(string $linkName, LinkContext $context): ResolvedLink { diff --git a/src/Validator/Operation.php b/src/Validator/Operation.php index 4e851f0d..4e4123ca 100644 --- a/src/Validator/Operation.php +++ b/src/Validator/Operation.php @@ -16,7 +16,7 @@ private readonly int $placeholderCount; /** - * @param array $pathParameters Resolved path parameter values keyed by placeholder name + * @param array $pathParameters */ public function __construct( public readonly string $path, @@ -25,7 +25,6 @@ public function __construct( public readonly array $pathParameters = [], public readonly ?SchemaOperation $schemaOperation = null, ) { - // §7 exemption: $matches[0] is the only way to access full preg_match_all matches. preg_match_all('/\{[^}]+\}/', $this->path, $matches); $this->placeholderCount = count($matches[0]); diff --git a/src/Validator/PregExecutor.php b/src/Validator/PregExecutor.php index 1968064f..b8259db5 100644 --- a/src/Validator/PregExecutor.php +++ b/src/Validator/PregExecutor.php @@ -16,35 +16,10 @@ use const E_WARNING; use const PREG_NO_ERROR; -/** - * Defensive wrapper around preg_match / preg_match_all that lowers the - * process-wide pcre.backtrack_limit and pcre.recursion_limit before each - * call and restores the previous values in a try/finally. Catastrophic - * backtracking (CWE-1333, CWE-400) on attacker-controlled JSON-Schema - * "pattern" fields is the dominant CPU cost factor; recursion_limit - * bounds C-stack exhaustion on deeply-nested patterns. PCRE compile - * warnings are swallowed and surfaced via the false return value; - * non-zero preg_last_error() raises PregRuntimeException instead of - * letting callers misread a runtime failure as "no match". - * - * @danger NOT_THREAD_SAFE - * - * Both pcre.* ini variables are PHP_INI_ALL (process-global). Under - * Swoole coroutines / threaded FrankenPHP the capture/restore in - * {@see match()} and {@see matchAll()} races with concurrent - * preg_match calls, and the ReDoS cap may be silently non-functional - * for an individual coroutine call (O-007, S-020). Prefork runtimes - * are unaffected. See README "Unsafe classes and their contracts". - */ final readonly class PregExecutor { public const int DEFAULT_MAX_BACKTRACKS = 10_000; - /** - * Default cap on PCRE recursion depth. PCRE2 reserves C-stack frames per - * recursion level; on typical 8 MB main stacks this leaves comfortable - * headroom while still bounding deeply-nested patterns like `(a|a)*b`. - */ public const int DEFAULT_MAX_RECURSION = 512; private const string BACKTRACK_LIMIT_FALLBACK = '1000000'; @@ -58,14 +33,10 @@ public function __construct( /** * @param non-empty-string $pattern - * @param array|null $matches populated by reference when present - * @param 0|256|512|768 $flags bitmask of PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL - * + * @param array|null $matches + * @param 0|256|512|768 $flags * @param-out array $matches - * - * @throws PregRuntimeException when preg_last_error() returns a non-zero code */ - // §7 exemption: Mirrors preg_match signature, documented via @param-out. public function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int|false { $previousBacktrack = $this->capturePreviousBacktrackLimit(); @@ -89,14 +60,10 @@ public function match(string $pattern, string $subject, ?array &$matches = null, /** * @param non-empty-string $pattern - * @param array|null $matches populated by reference when present - * @param int $flags bitmask of PREG_PATTERNORDER, PREG_SET_ORDER, PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL - * + * @param array|null $matches + * @param int $flags * @param-out array $matches - * - * @throws PregRuntimeException when preg_last_error() returns a non-zero code */ - // §7 exemption: Mirrors preg_match_all signature, documented via @param-out. public function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int|false { $previousBacktrack = $this->capturePreviousBacktrackLimit(); @@ -132,9 +99,6 @@ private function capturePreviousRecursionLimit(): string return false === $previous ? self::RECURSION_LIMIT_FALLBACK : $previous; } - /** - * @throws PregRuntimeException when preg_last_error() returns a non-zero code - */ private function assertNoPcreError(): void { $error = preg_last_error(); diff --git a/src/Validator/Request/BodyParser/XmlBodyParser.php b/src/Validator/Request/BodyParser/XmlBodyParser.php index 172e348b..b980e865 100644 --- a/src/Validator/Request/BodyParser/XmlBodyParser.php +++ b/src/Validator/Request/BodyParser/XmlBodyParser.php @@ -218,7 +218,6 @@ private static function elementToValue(SimpleXMLElement $element): array|string| /** * @param array $result - * * @return array */ private static function mergeChild(array $result, string $key, array|string|null $value): array diff --git a/src/Validator/Request/CookieValidator.php b/src/Validator/Request/CookieValidator.php index e0eb5b65..9c91db3e 100644 --- a/src/Validator/Request/CookieValidator.php +++ b/src/Validator/Request/CookieValidator.php @@ -40,11 +40,6 @@ public function __construct( } /** - * Cookie pairs without `=` (e.g. flag-style cookies) are preserved with an - * empty string value rather than dropped, for tolerant parsing of malformed - * Cookie headers. Per RFC 6265 §4.1.1 cookie-pair should contain `=`, but - * real-world clients sometimes send valueless cookies. - * * @return array */ public function parseCookies(string $cookieHeader): array diff --git a/src/Validator/Request/Internal/BracketNotationParser.php b/src/Validator/Request/Internal/BracketNotationParser.php index ecebdbf1..4c4550d8 100644 --- a/src/Validator/Request/Internal/BracketNotationParser.php +++ b/src/Validator/Request/Internal/BracketNotationParser.php @@ -20,7 +20,6 @@ /** * @param array $tree - * * @return array */ public function insertNested(array $tree, string $key, string $value): array @@ -48,9 +47,8 @@ public function insertNested(array $tree, string $key, string $value): array } /** - * @param array $node - * @param non-empty-list $segments - * + * @param array $node + * @param non-empty-list $segments * @return array */ public function assignSegments(array $node, array $segments, string $value): array @@ -114,9 +112,8 @@ private function extractSegments(string $rootName, string $rest): array } /** - * @param array $node - * @param list $remaining - * + * @param array $node + * @param list $remaining * @return array */ private function assignEmptySegment(array $node, array $remaining, string $value): array diff --git a/src/Validator/Request/Internal/DeepObjectParser.php b/src/Validator/Request/Internal/DeepObjectParser.php index a8430f32..6d87e4b4 100644 --- a/src/Validator/Request/Internal/DeepObjectParser.php +++ b/src/Validator/Request/Internal/DeepObjectParser.php @@ -25,7 +25,6 @@ /** * @param non-empty-list $groupPairs - * * @return string|array */ public function resolveGroup(string $baseKey, array $groupPairs, BracketNotationParser $bracketParser): string|array @@ -53,7 +52,6 @@ public function parseByMediaType(string $raw, string $mediaType, string $paramet /** * @param non-empty-list $groupPairs - * * @return string|array */ private function collectScalarValues(array $groupPairs): string|array @@ -68,7 +66,6 @@ private function collectScalarValues(array $groupPairs): string|array /** * @param non-empty-list $groupPairs - * * @return string|array */ private function buildNestedTree(array $groupPairs, string $baseKey, BracketNotationParser $bracketParser): string|array diff --git a/src/Validator/Request/MediaTypeMatcher.php b/src/Validator/Request/MediaTypeMatcher.php index e9ccb336..ecb4b850 100644 --- a/src/Validator/Request/MediaTypeMatcher.php +++ b/src/Validator/Request/MediaTypeMatcher.php @@ -6,18 +6,11 @@ use function count; -/** - * Matches a concrete request media type against the media types declared - * in an OpenAPI operation body, honouring RFC 7231 §3.1.1.1 wildcard - * patterns. The most specific declaration wins, from exact match through - * subtype wildcard to the universal wildcard. - */ final readonly class MediaTypeMatcher { /** - * @param list $specMediaTypes lower-cased keys declared in the spec - * - * @return string|null the matching spec key, or null when no declaration matches + * @param list $specMediaTypes + * @return string|null */ public static function findMatch(string $requestMediaType, array $specMediaTypes): ?string { diff --git a/src/Validator/Request/PathParser.php b/src/Validator/Request/PathParser.php index da419457..d51b0467 100644 --- a/src/Validator/Request/PathParser.php +++ b/src/Validator/Request/PathParser.php @@ -21,14 +21,14 @@ public function __construct( private readonly ?LoggerInterface $logger = null, ) {} - /** @return array Parameter values */ + /** @return array */ public function matchPath(string $requestPath, string $template): array { return $this->tryMatchPath($requestPath, $template) ?? throw new PathMismatchException($template, $requestPath); } - /** @return array|null Parameter values, or null if no match */ + /** @return array|null */ public function tryMatchPath(string $requestPath, string $template): ?array { /** @var non-empty-string $regex */ diff --git a/src/Validator/Request/PathRegexCache.php b/src/Validator/Request/PathRegexCache.php index 6bc9e929..a91ec0d8 100644 --- a/src/Validator/Request/PathRegexCache.php +++ b/src/Validator/Request/PathRegexCache.php @@ -19,13 +19,6 @@ use const PREG_OFFSET_CAPTURE; use const PREG_SET_ORDER; -/** - * Instance-scoped LRU cache of compiled path-template regular expressions. - * - * Thread-safety: NOT thread-safe. In Swoole coroutines or threaded FrankenPHP, - * each worker/coroutine must own its own instance (the default in - * OpenApiValidatorBuilder — one PathRegexCache per built document). - */ final readonly class PathRegexCache { private const int DEFAULT_MAX_SIZE = 256; @@ -42,9 +35,7 @@ private LruCache $cache; /** - * @param int|null $maxSize Maximum entries before LRU eviction. Null falls back to DEFAULT_MAX_SIZE. - * - * @throws InvalidArgumentException when $maxSize is less than 1 + * @param int|null $maxSize */ public function __construct(?int $maxSize = null) { diff --git a/src/Validator/Request/QueryParser.php b/src/Validator/Request/QueryParser.php index 4196a754..22c05a32 100644 --- a/src/Validator/Request/QueryParser.php +++ b/src/Validator/Request/QueryParser.php @@ -25,13 +25,6 @@ public function __construct( ) {} /** - * Uses an explicit segment-based parser (insertNested + assignSegments) instead - * of parse_str because parse_str converts dots in keys to underscores - * (e.g. `user.name` becomes `user_name`) and keeps only the last value for - * duplicate scalar keys. This parser preserves key names literally and - * collects duplicate scalars into indexed arrays to match the structure - * produced by RFC 6570 form-style explode expansion. - * * @return array */ public function parse(string $queryString): array @@ -76,7 +69,6 @@ public function parse(string $queryString): array /** * @param array $values - * * @return array|string */ public function handleExplode(array $values, bool $explode): array|string diff --git a/src/Validator/Request/TypeCoercer.php b/src/Validator/Request/TypeCoercer.php index cda7954a..7a5066c5 100644 --- a/src/Validator/Request/TypeCoercer.php +++ b/src/Validator/Request/TypeCoercer.php @@ -19,18 +19,6 @@ { /** * @return array|int|string|float|bool|null - * - * Coerce $value according to $param's schema. When $enabled is false or the - * schema has no type, the value is normalised without type conversion. - * - * Since TYPECOERCER-DEFAULT-STRICT the $strict argument defaults to true: - * arbitrary strings no longer silently cast to boolean, and integer - * overflow from string input is rejected. Internal callers always pass - * $strict explicitly via ParameterValidationConfig::strictCoercion. - * Third-party callers that want the legacy lax behaviour MUST pass false - * explicitly. Note: the SEC-14 float-to-int overflow guard and the - * SEC-15 numeric-string precision-loss guard run unconditionally in - * both strict and non-strict modes. */ public function coerce( mixed $value, diff --git a/src/Validator/Response/Exception/StreamRecordTooLargeException.php b/src/Validator/Response/Exception/StreamRecordTooLargeException.php index 072eb642..d7f67f97 100644 --- a/src/Validator/Response/Exception/StreamRecordTooLargeException.php +++ b/src/Validator/Response/Exception/StreamRecordTooLargeException.php @@ -9,12 +9,6 @@ use function sprintf; -/** - * Thrown when a single streamed line (NDJSON, SSE) or record (JSON Text - * Sequence) exceeds the configured size cap while reading a response body. - * Defends against memory exhaustion from attacker-controlled streaming - * responses that never terminate a record. - */ final class StreamRecordTooLargeException extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Response/Exception/TooManyRecordsException.php b/src/Validator/Response/Exception/TooManyRecordsException.php index c9fa3b55..bf2e441d 100644 --- a/src/Validator/Response/Exception/TooManyRecordsException.php +++ b/src/Validator/Response/Exception/TooManyRecordsException.php @@ -9,12 +9,6 @@ use function sprintf; -/** - * Thrown when a streaming content parser (NDJSON, SSE, JSON Text Sequence) - * accumulates more records than the configured maximum. Defends against - * memory exhaustion from attacker-controlled streaming responses that - * consist of a very large number of small records. - */ final class TooManyRecordsException extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Response/Internal/SseParser.php b/src/Validator/Response/Internal/SseParser.php index 3817e6f2..1b3306a4 100644 --- a/src/Validator/Response/Internal/SseParser.php +++ b/src/Validator/Response/Internal/SseParser.php @@ -56,7 +56,6 @@ public function parseStream(StreamInterface $stream): array /** * @param iterable $lines - * * @return list|scalar|null> */ private function parseLines(iterable $lines, RecordCollector $collector): array @@ -91,7 +90,6 @@ private function createCollector(): RecordCollector /** * @param array $currentEvent - * * @return array{0: array, 1: array|null} */ private function processLine(string $line, array $currentEvent, RecordCollector $collector): array @@ -125,7 +123,6 @@ private function processLine(string $line, array $currentEvent, RecordCollector /** * @param array $currentEvent - * * @return array */ private function applyField(array $currentEvent, string $field, string $value): array @@ -143,7 +140,6 @@ private function applyField(array $currentEvent, string $field, string $value): /** * @param array $event - * * @return array */ private function formatEvent(array $event, RecordCollector $collector): array diff --git a/src/Validator/Response/Internal/StreamLineReader.php b/src/Validator/Response/Internal/StreamLineReader.php index 22c60154..8ef5514a 100644 --- a/src/Validator/Response/Internal/StreamLineReader.php +++ b/src/Validator/Response/Internal/StreamLineReader.php @@ -29,7 +29,6 @@ public function __construct( /** * @param non-empty-string $splitPattern - * * @return Generator */ public function readLines(StreamInterface $stream, string $splitPattern): Generator diff --git a/src/Validator/Response/StreamingContentParser.php b/src/Validator/Response/StreamingContentParser.php index 10e22528..60147b28 100644 --- a/src/Validator/Response/StreamingContentParser.php +++ b/src/Validator/Response/StreamingContentParser.php @@ -14,19 +14,6 @@ use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; -/** - * Parses the three streaming response formats supported by the validator: - * NDJSON / JSON Lines (`application/jsonl`, `application/x-ndjson`), - * Server-Sent Events (`text/event-stream`), and JSON Text Sequences - * (`application/json-seq`, RFC 7464). - * - * Acts as a dispatcher: routes by Content-Type to one of three format - * parsers under StreamingFormatParser. Format-specific semantics (BOM - * handling, malformed-record policy, SSE event assembly, JSON-Seq record - * separator) live in the parsers; this class only owns the - * `strictStreaming` constructor flag, the record-count cap, and the - * per-format line/record size limits. - */ final readonly class StreamingContentParser { private const int DEFAULT_MAX_LINE_LENGTH = StreamLineReader::DEFAULT_MAX_LINE_LENGTH; @@ -68,9 +55,6 @@ public function __construct( } /** - * Resolve the format parser responsible for the given content type, - * using the same detection semantics as StreamingMediaTypeDetector. - * * @internal */ public function parserFor(string $contentType): ?StreamingFormatParser @@ -84,8 +68,6 @@ public function parserFor(string $contentType): ?StreamingFormatParser } /** - * Parse streaming content based on content type. - * * @return list|scalar|null> */ public function parse(string $body, string $contentType): array @@ -96,8 +78,6 @@ public function parse(string $body, string $contentType): array } /** - * Parse a PSR-7 stream in chunks without loading the entire body into memory. - * * @return list|scalar|null> */ public function parseStream(StreamInterface $stream, string $contentType): array @@ -112,8 +92,6 @@ public function parseStream(StreamInterface $stream, string $contentType): array } /** - * Parse JSON Lines (NDJSON) format. - * * @return list|scalar|null> */ public function parseJsonLines(string $body): array @@ -122,8 +100,6 @@ public function parseJsonLines(string $body): array } /** - * Parse Server-Sent Events format. - * * @return list|scalar|null> */ public function parseServerSentEvents(string $body): array @@ -132,8 +108,6 @@ public function parseServerSentEvents(string $body): array } /** - * Parse JSON Text Sequences (RFC 7464). - * * @return list|scalar|null> */ public function parseJsonSeq(string $body): array diff --git a/src/Validator/Schema/Exception/ExternalRefSecurityException.php b/src/Validator/Schema/Exception/ExternalRefSecurityException.php index f7dd865a..7686168a 100644 --- a/src/Validator/Schema/Exception/ExternalRefSecurityException.php +++ b/src/Validator/Schema/Exception/ExternalRefSecurityException.php @@ -9,10 +9,6 @@ use RuntimeException; use Throwable; -/** - * Thrown when an external $ref violates the builtin FileExternalRefResolver - * security policy (denied scheme, path traversal outside the allowed root). - */ final class ExternalRefSecurityException extends RuntimeException { use SanitizableExceptionTrait; @@ -32,12 +28,6 @@ public function __construct( parent::__construct($message, $code, $previous); } - /** - * Returns the retained $ref string. Pass $reveal = true only from - * trusted operator code (security auditor, verbose logger); the - * default returns '' to prevent disclosure through - * reflective serialization ((array) $e, Sentry SDK, etc.). - */ public function ref(bool $reveal = false): string { return $reveal ? $this->ref : ''; diff --git a/src/Validator/Schema/Exception/ExternalRefTooLargeException.php b/src/Validator/Schema/Exception/ExternalRefTooLargeException.php index 81c9d206..96894764 100644 --- a/src/Validator/Schema/Exception/ExternalRefTooLargeException.php +++ b/src/Validator/Schema/Exception/ExternalRefTooLargeException.php @@ -9,12 +9,6 @@ use function sprintf; -/** - * Thrown when an external $ref file exceeds the configured maximum size - * (FileExternalRefResolver::$maxBytes). Semantically a size / DoS error, - * not a security policy violation, so it extends RuntimeException directly - * rather than ExternalRefSecurityException. - */ final class ExternalRefTooLargeException extends RuntimeException { use SanitizableExceptionTrait; diff --git a/src/Validator/Schema/Exception/UnresolvableRefException.php b/src/Validator/Schema/Exception/UnresolvableRefException.php index c4326b4c..081d00a5 100644 --- a/src/Validator/Schema/Exception/UnresolvableRefException.php +++ b/src/Validator/Schema/Exception/UnresolvableRefException.php @@ -41,12 +41,6 @@ public function __construct( ); } - /** - * Returns the retained $ref string. Pass $reveal = true only from - * trusted operator code; the default returns '' to prevent - * disclosure of internal specification structure through reflective - * serialization. - */ public function ref(bool $reveal = false): string { return $reveal ? $this->ref : ''; @@ -57,12 +51,6 @@ public function reason(): string return $this->reason; } - /** - * Returns the internal navigation trace (e.g. the chain of visited - * $ref pointers). Pass $reveal = true only from trusted operator - * code; the default returns '' to prevent disclosure of - * internal specification structure through reflective serialization. - */ public function internalTrace(bool $reveal = false): ?string { return $reveal ? $this->internalTrace : ''; diff --git a/src/Validator/Schema/FileExternalRefResolver.php b/src/Validator/Schema/FileExternalRefResolver.php index 2fe58ec5..e44c8bd1 100644 --- a/src/Validator/Schema/FileExternalRefResolver.php +++ b/src/Validator/Schema/FileExternalRefResolver.php @@ -44,39 +44,8 @@ use const JSON_THROW_ON_ERROR; use const PATHINFO_EXTENSION; -/** - * Builtin external $ref resolver for file:// URIs and relative-path refs. - * - * Security policy: - * - Allows only the file:// scheme and scheme-less relative paths. Every - * other scheme is rejected with ExternalRefSecurityException. PHP - * registers dozens of stream wrappers (php://, phar://, data://, - * compress.zlib://, zip://, expect://, ssh2://, rar://, ogg://, glob:// - * and more) that would otherwise allow LFI, deserialization gadgets and - * inline schema injection. A whitelist is the only defence that does not - * lag behind newly registered wrappers. - * - When an optional allowedRoot is configured, refuses to read files whose - * realpath escapes that root (defends against ../ traversal and symlinks). - * - * SEC-08 / CWE-209: exception messages omit absolute paths and the - * configured allowedRoot so a Throwable surfaced by a PSR-15 middleware - * cannot leak the server filesystem layout. Concrete paths are forwarded - * to the optional PSR-3 logger at debug level instead. - * - * The resolver is a pure loader: it does not cache loaded schemas (that is the - * responsibility of RefResolver::$cache). It parses YAML and JSON payloads and - * supports an optional JSON Pointer suffix (e.g. 'user.yaml#/UserSchema'). - */ -// §6 exemption: Tightly coupled with RefResolver via ExternalRefResolverInterface; decomposition requires interface refactor pending 2.0. See ADR .ai/reports/adr-schema-constructor.md for pattern. final readonly class FileExternalRefResolver implements ExternalRefResolverInterface { - /** - * Default cap for external ref file size, defends against DoS via large - * attacker-controlled files (file:///dev/zero, multi-gigabyte payloads). - * Override via the $maxBytes constructor argument or the builder method - * withExternalRefMaxBytes(). Exposed as public so the builder can - * reference the canonical default without duplicating the literal. - */ public const int DEFAULT_MAX_REF_BYTES = 10_485_760; private const array ALLOWED_SCHEMES = [ @@ -328,7 +297,6 @@ private function parseContents(string $contents, string $filePath): array /** * @param array $fileData - * * @return mixed */ private function navigatePointer(array $fileData, string $pointer, string $absolutePath): mixed diff --git a/src/Validator/Schema/Internal/CompositionResolver.php b/src/Validator/Schema/Internal/CompositionResolver.php index 98148af0..d75bf19b 100644 --- a/src/Validator/Schema/Internal/CompositionResolver.php +++ b/src/Validator/Schema/Internal/CompositionResolver.php @@ -26,8 +26,6 @@ public function __construct( /** * @param WeakMap $visited - * - * @throws SchemaDepthExceededException */ public function resolveCompositionRefs(Schema $schema, WeakMap $visited): Schema { @@ -80,9 +78,8 @@ public function resolveCompositionRefs(Schema $schema, WeakMap $visited): Schema } /** - * @param list|null $schemas - * @param WeakMap $visited - * + * @param list|null $schemas + * @param WeakMap $visited * @return list|null */ private function resolveCompositionArray(?array $schemas, WeakMap $visited): ?array diff --git a/src/Validator/Schema/Internal/DiscriminatorDetector.php b/src/Validator/Schema/Internal/DiscriminatorDetector.php index ef399623..1dac5026 100644 --- a/src/Validator/Schema/Internal/DiscriminatorDetector.php +++ b/src/Validator/Schema/Internal/DiscriminatorDetector.php @@ -19,9 +19,6 @@ /** * @param WeakMap $visited * @param Closure(string, OpenApiDocument): Schema $resolver - * - * @throws SchemaDepthExceededException - * * @return array{bool, WeakMap} */ public function detectDiscriminator( @@ -57,7 +54,6 @@ public function detectDiscriminator( /** * @param WeakMap $visited * @param Closure(string, OpenApiDocument): Schema $resolver - * * @return array{bool, WeakMap} */ public function checkRefForDiscriminator( @@ -84,9 +80,6 @@ public function checkRefForDiscriminator( /** * @param WeakMap $visited - * - * @throws SchemaDepthExceededException - * * @return array{bool, WeakMap} */ public function detectRef(Schema $schema, WeakMap $visited, int $depth): array @@ -151,7 +144,6 @@ public function collectSingleSubSchemas(Schema $schema): array /** * @param WeakMap $visited * @param Closure(string, OpenApiDocument): Schema $resolver - * * @return array{bool, WeakMap} */ private function scanSubSchemasForDiscriminator( @@ -180,7 +172,6 @@ private function scanSubSchemasForDiscriminator( /** * @param WeakMap $visited - * * @return array{bool, WeakMap} */ private function scanSubSchemasForRef(Schema $schema, WeakMap $visited, int $depth): array diff --git a/src/Validator/Schema/Internal/DocumentNavigator.php b/src/Validator/Schema/Internal/DocumentNavigator.php index d175f120..53f6172e 100644 --- a/src/Validator/Schema/Internal/DocumentNavigator.php +++ b/src/Validator/Schema/Internal/DocumentNavigator.php @@ -41,10 +41,6 @@ public function __construct( /** * @param array $visited * @param WeakMap $cache - * - * @throws SchemaDepthExceededException - * @throws UnresolvableRefException - * * @return array{Schema|Parameter|RequestBody|Response, array} */ public function resolveRef( @@ -84,9 +80,6 @@ public function resolveRef( /** * @param array $parts - * - * @throws SchemaDepthExceededException - * @throws UnresolvableRefException */ public function navigate( object|array $current, @@ -201,7 +194,6 @@ private function storeCached(OpenApiDocument $document, string $ref, Schema|Para /** * @param array $visited - * * @return array{Schema|Parameter|RequestBody|Response, array} */ private function resolveExternalRef(string $ref, array $visited): array diff --git a/src/Validator/Schema/Internal/UriResolver.php b/src/Validator/Schema/Internal/UriResolver.php index b6cdfc51..93a947f3 100644 --- a/src/Validator/Schema/Internal/UriResolver.php +++ b/src/Validator/Schema/Internal/UriResolver.php @@ -17,7 +17,6 @@ /** * @internal - * * @psalm-type UriParts = array */ final readonly class UriResolver @@ -60,7 +59,6 @@ public function resolveRelativeAgainstBase(array $base, array $relative, string /** * @param UriParts $base * @param UriParts $relative - * * @return UriParts */ public function replaceQueryAndFragment(array $base, array $relative): array @@ -77,7 +75,6 @@ public function replaceQueryAndFragment(array $base, array $relative): array /** * @param UriParts $base * @param UriParts $relative - * * @return UriParts */ public function applyFragment(array $base, array $relative): array diff --git a/src/Validator/Schema/RegexValidator.php b/src/Validator/Schema/RegexValidator.php index 7292f8ca..aa5abc4c 100644 --- a/src/Validator/Schema/RegexValidator.php +++ b/src/Validator/Schema/RegexValidator.php @@ -8,7 +8,6 @@ use Duyler\OpenApi\Validator\Exception\PregRuntimeException; use Duyler\OpenApi\Validator\Internal\LruCache; use Duyler\OpenApi\Validator\PregExecutor; -use InvalidArgumentException; use function ctype_alnum; use function preg_match; @@ -31,7 +30,6 @@ /** @var LruCache */ private LruCache $normalizeCache; - /** @throws InvalidArgumentException */ public function __construct( ?int $maxSize = null, private PregExecutor $pregExecutor = new PregExecutor(), diff --git a/src/Validator/Schema/SchemaValueNormalizer.php b/src/Validator/Schema/SchemaValueNormalizer.php index fd4d000b..269d571d 100644 --- a/src/Validator/Schema/SchemaValueNormalizer.php +++ b/src/Validator/Schema/SchemaValueNormalizer.php @@ -19,8 +19,6 @@ final readonly class SchemaValueNormalizer { /** - * @throws InvalidDataTypeException - * * @return array|int|string|float|bool|null */ public static function normalize(mixed $value, bool $allowNull = false): array|int|string|float|bool|null @@ -56,13 +54,6 @@ public static function isNullableSchema(Schema $schema, bool $nullableAsType): b return $nullableAsType && $schema->nullable; } - /** - * Decides whether the pre-check may hand a null to $schema. - * - * A composition or $ref node carries neither type nor nullable of its - * own — both live in the branches or in the resolved target — so null - * is deferred to them instead of being rejected here. - */ public static function allowsNull(Schema $schema, bool $nullableAsType = true): bool { if (false === $nullableAsType) { diff --git a/src/Validator/SchemaValidator/AdditionalPropertiesValidator.php b/src/Validator/SchemaValidator/AdditionalPropertiesValidator.php index 05fb7274..ffa0633d 100644 --- a/src/Validator/SchemaValidator/AdditionalPropertiesValidator.php +++ b/src/Validator/SchemaValidator/AdditionalPropertiesValidator.php @@ -71,7 +71,6 @@ public function validate(mixed $data, Schema $schema, ?ValidationContext $contex /** * @param array $data - * * @return list */ private function computeAdditionalKeys(array $data, Schema $schema): array @@ -158,8 +157,8 @@ private function rejectAdditionalKeys(array $additionalKeys, string $dataPath): } /** - * @param array $data - * @param list $additionalKeys + * @param array $data + * @param list $additionalKeys */ private function validateAdditionalSchemas(array $data, Schema $additionalSchema, array $additionalKeys, ?ValidationContext $context): void { diff --git a/src/Validator/SchemaValidator/ArrayLengthValidator.php b/src/Validator/SchemaValidator/ArrayLengthValidator.php index 71d90229..ee3cece1 100644 --- a/src/Validator/SchemaValidator/ArrayLengthValidator.php +++ b/src/Validator/SchemaValidator/ArrayLengthValidator.php @@ -221,7 +221,6 @@ private function encodeArrayKey(array $item): string /** * @param array $item - * * @return array */ private function canonicalizeForEncoding(array $item): array diff --git a/src/Validator/SchemaValidator/EnumScalarCache.php b/src/Validator/SchemaValidator/EnumScalarCache.php index 29c1f263..2db53cf6 100644 --- a/src/Validator/SchemaValidator/EnumScalarCache.php +++ b/src/Validator/SchemaValidator/EnumScalarCache.php @@ -95,7 +95,6 @@ private function computeIsScalarEnum(array $enum): bool /** * @param list $enum - * * @return array */ private function buildScalarSet(array $enum): array diff --git a/src/Validator/SchemaValidator/Internal/ItemValidationExceptionTrait.php b/src/Validator/SchemaValidator/Internal/ItemValidationExceptionTrait.php index 9d9bd205..f167d7ab 100644 --- a/src/Validator/SchemaValidator/Internal/ItemValidationExceptionTrait.php +++ b/src/Validator/SchemaValidator/Internal/ItemValidationExceptionTrait.php @@ -22,7 +22,6 @@ trait ItemValidationExceptionTrait { /** * @param non-empty-string $schemaPath - * @throws Throwable */ private function wrapItemValidationException( Throwable $e, diff --git a/src/Validator/SchemaValidator/ItemsValidator.php b/src/Validator/SchemaValidator/ItemsValidator.php index 3fa8aa00..a70aaeef 100644 --- a/src/Validator/SchemaValidator/ItemsValidator.php +++ b/src/Validator/SchemaValidator/ItemsValidator.php @@ -56,8 +56,8 @@ public function validate(mixed $data, Schema $schema, ?ValidationContext $contex } /** - * @param array $data - * @param list|null $prefixItems + * @param array $data + * @param list|null $prefixItems */ private function validateSchemaItems(array $data, Schema $itemsSchema, ?array $prefixItems, ?ValidationContext $context): void { diff --git a/src/Validator/SchemaValidator/PatternPropertiesValidator.php b/src/Validator/SchemaValidator/PatternPropertiesValidator.php index 6ff884c5..ddced3af 100644 --- a/src/Validator/SchemaValidator/PatternPropertiesValidator.php +++ b/src/Validator/SchemaValidator/PatternPropertiesValidator.php @@ -39,7 +39,6 @@ public function validate(mixed $data, Schema $schema, ?ValidationContext $contex /** * @param array $patternProperties - * * @return array */ private function normalizePatterns(array $patternProperties): array @@ -63,9 +62,9 @@ private function normalizePatterns(array $patternProperties): array } /** - * @param array $data - * @param array $patternProperties - * @param array $normalizedPatterns + * @param array $data + * @param array $patternProperties + * @param array $normalizedPatterns */ private function applyPatterns(array $data, array $patternProperties, array $normalizedPatterns, ?ValidationContext $context): void { diff --git a/src/Validator/SchemaValidator/UnevaluatedItemsValidator.php b/src/Validator/SchemaValidator/UnevaluatedItemsValidator.php index 6f4ead37..5630d678 100644 --- a/src/Validator/SchemaValidator/UnevaluatedItemsValidator.php +++ b/src/Validator/SchemaValidator/UnevaluatedItemsValidator.php @@ -60,7 +60,7 @@ public function validate(mixed $data, Schema $schema, ?ValidationContext $contex /** * @param array $data - * @param list $unevaluatedIndices + * @param list $unevaluatedIndices */ private function rejectUnevaluatedItems(array $data, array $unevaluatedIndices, string $dataPath): void { @@ -89,7 +89,7 @@ private function rejectUnevaluatedItems(array $data, array $unevaluatedIndices, /** * @param array $data - * @param list $unevaluatedIndices + * @param list $unevaluatedIndices */ private function validateUnevaluatedItems(array $data, Schema $unevaluatedItems, array $unevaluatedIndices, ?ValidationContext $context): void { @@ -117,7 +117,6 @@ private function validateUnevaluatedItems(array $data, Schema $unevaluatedItems, /** * @param array $data - * * @return list */ private function getEvaluatedItemIndices(Schema $schema, array $data, ?ValidationContext $context): array diff --git a/src/Validator/SchemaValidator/UnevaluatedPropertiesValidator.php b/src/Validator/SchemaValidator/UnevaluatedPropertiesValidator.php index 0a0b2638..4ad699e7 100644 --- a/src/Validator/SchemaValidator/UnevaluatedPropertiesValidator.php +++ b/src/Validator/SchemaValidator/UnevaluatedPropertiesValidator.php @@ -64,8 +64,8 @@ public function validate(mixed $data, Schema $schema, ?ValidationContext $contex } /** - * @param array $data - * @param array $stringUnevaluatedProperties + * @param array $data + * @param array $stringUnevaluatedProperties */ private function validateUnevaluatedProperties(array $data, Schema $unevaluatedProperties, array $stringUnevaluatedProperties, ?ValidationContext $context): void { @@ -92,7 +92,6 @@ private function validateUnevaluatedProperties(array $data, Schema $unevaluatedP /** * @param array $data - * * @return list */ private function getEvaluatedProperties(Schema $schema, array $data, ?ValidationContext $context): array @@ -132,7 +131,6 @@ private function getEvaluatedProperties(Schema $schema, array $data, ?Validation /** * @param array $data - * * @return list */ private function collectPatternMatched(Schema $schema, array $data): array diff --git a/src/Validator/Security/SecurityValidator.php b/src/Validator/Security/SecurityValidator.php index aa2965ab..87bec010 100644 --- a/src/Validator/Security/SecurityValidator.php +++ b/src/Validator/Security/SecurityValidator.php @@ -79,7 +79,6 @@ public function validate(SecurityValidationContext $context): void /** * @param array> $requirementAlternatives * @param array $securitySchemes - * * @return list */ private function validateRequirement( diff --git a/src/Validator/Server/ServerPathMatcher.php b/src/Validator/Server/ServerPathMatcher.php index c25afbd7..59107574 100644 --- a/src/Validator/Server/ServerPathMatcher.php +++ b/src/Validator/Server/ServerPathMatcher.php @@ -31,9 +31,6 @@ public function __construct( $this->sortedServerPaths = $sortedServerPaths; } - /** - * Matches a request path against precompiled server base paths and strips the matched prefix. - */ public function matchPath(string $requestPath): ?ServerPathMatch { foreach ($this->sortedServerPaths as $entry) { @@ -54,7 +51,6 @@ public function matchPath(string $requestPath): ?ServerPathMatch /** * @param list $servers - * * @return list */ private function resolveServerBasePaths(array $servers): array diff --git a/src/Validator/Server/ServerUrlResolver.php b/src/Validator/Server/ServerUrlResolver.php index 73b31970..ef7d5a3d 100644 --- a/src/Validator/Server/ServerUrlResolver.php +++ b/src/Validator/Server/ServerUrlResolver.php @@ -22,12 +22,8 @@ private const string VARIABLE_PATTERN = '/\{(?' . self::VARNAME_PATTERN . ')\}/'; /** - * Resolves a server URL template by substituting variables with provided values. - * * @param Server $server * @param ServerVariableOverride ...$overrides - * - * @throws ServerVariableException If a required variable is missing */ public function resolve(Server $server, ServerVariableOverride ...$overrides): string { @@ -62,8 +58,6 @@ function (array $matches) use ($variables, $server): string { } /** - * Extracts variable names from a server URL template. - * * @return list */ public function extractVariableNames(Server $server): array @@ -75,12 +69,8 @@ public function extractVariableNames(Server $server): array } /** - * Validates that all template variables in the server URL have corresponding values. - * * @param Server $server * @param ServerVariableOverride ...$overrides - * - * @throws ServerVariableException If a variable is missing a value */ public function validateVariables(Server $server, ServerVariableOverride ...$overrides): void { @@ -102,7 +92,6 @@ public function validateVariables(Server $server, ServerVariableOverride ...$ove /** * @param array $overrides - * * @return array */ private function mergeVariables(Server $server, array $overrides): array diff --git a/src/Validator/Util/LogContextSanitizer.php b/src/Validator/Util/LogContextSanitizer.php index 4abaf7cf..570dd4c0 100644 --- a/src/Validator/Util/LogContextSanitizer.php +++ b/src/Validator/Util/LogContextSanitizer.php @@ -14,12 +14,6 @@ use const STR_PAD_LEFT; -/** - * Sanitizes attacker-controlled strings before they enter PSR-3 log context. - * Truncates to a bounded length and escapes control characters so that a - * plaintext logger (e.g. Monolog StreamHandler) cannot be injected with - * fake log lines via newline or other control bytes. - */ final readonly class LogContextSanitizer { private const int DEFAULT_MAX_LENGTH = 256; diff --git a/src/Validator/Util/Utf16.php b/src/Validator/Util/Utf16.php index 040b5f60..60c5f22e 100644 --- a/src/Validator/Util/Utf16.php +++ b/src/Validator/Util/Utf16.php @@ -7,14 +7,6 @@ use function ord; use function strlen; -/** - * Counts UTF-16 code units in a UTF-8 encoded string. - * - * Per JSON Schema 2020-12 §6.3.1: "The length of a string is the number - * of UTF-16 code units." Supplementary characters (U+10000 — U+10FFFF) - * are encoded as UTF-16 surrogate pairs and count as 2 code units, even - * though they occupy a single Unicode code point. - */ final readonly class Utf16 { private const int ASCII_BOUNDARY = 0x80; diff --git a/src/Validator/Validation/ValidationStack.php b/src/Validator/Validation/ValidationStack.php index 4242e1ab..fc8a0738 100644 --- a/src/Validator/Validation/ValidationStack.php +++ b/src/Validator/Validation/ValidationStack.php @@ -53,13 +53,10 @@ /** * @deprecated since 1.x, will be removed in 2.0. Use {@see fromGroup()} instead. - * PHPDoc-only deprecation (no {@see \Deprecated} attribute) so {@see fromGroup()} - * can delegate without runtime E_DEPRECATED cascade. See `.ai/reports/adr-validator-signatures-and-dtos.md`. - * - * @param int $maxJsonBodyBytes from {@see ValidatorConfiguration::DEFAULT_MAX_JSON_BODY_BYTES} - * @param int $maxMultipartBodyBytes from {@see ValidatorConfiguration::DEFAULT_MAX_MULTIPART_BODY_BYTES} - * @param int $maxRegexBacktracks from {@see PregExecutor::DEFAULT_MAX_BACKTRACKS} - * @param int $maxStreamingRecords from {@see ValidatorConfiguration::DEFAULT_MAX_STREAMING_RECORDS} + * @param int $maxJsonBodyBytes + * @param int $maxMultipartBodyBytes + * @param int $maxRegexBacktracks + * @param int $maxStreamingRecords */ public function __construct( public readonly OpenApiDocument $document, diff --git a/src/Validator/ValidatorPool.php b/src/Validator/ValidatorPool.php index aeb1a7c3..a7437400 100644 --- a/src/Validator/ValidatorPool.php +++ b/src/Validator/ValidatorPool.php @@ -10,18 +10,6 @@ use function assert; use function method_exists; -/** - * @danger NOT_THREAD_SAFE - * - * LRU cache of validator instances (default capacity 128). Prefork-safe - * (PHP-FPM, RoadRunner, FrankenPHP non-threaded); racy under shared state - * in Swoole coroutines / FrankenPHP threaded workers — pass a lock via - * the constructor or {@see forCoroutineRuntime()}. The factory passed to - * getOrCreate() must be non-blocking and non-recursive: Swoole\Lock is - * non-reentrant, so nested getOrCreate() calls on the same lock deadlock - * (O-004). See README "Validator Pool" and "Unsafe classes and their - * contracts" for the full concurrency contract. - */ final readonly class ValidatorPool { private const int DEFAULT_MAX_SIZE = 128; @@ -30,10 +18,8 @@ private LruCache $cache; /** - * @param int|null $maxSize Maximum entries before LRU eviction. Null falls back to DEFAULT_MAX_SIZE. - * @param object|null $lock Optional lock with lock()/unlock() methods (e.g. Swoole\Lock). Null keeps - * the pool prefork-safe; required for Swoole coroutines and threaded FrankenPHP. - * A non-null object must expose BOTH methods; otherwise the constructor throws. + * @param int|null $maxSize + * @param object|null $lock */ public function __construct(?int $maxSize = null, private ?object $lock = null) { @@ -47,17 +33,6 @@ public function __construct(?int $maxSize = null, private ?object $lock = null) } } - /** - * Construct a pool explicitly bound to a coroutine- or thread-safe lock. - * - * Use this factory when running under Swoole coroutines or FrankenPHP - * threaded workers. The lock MUST expose both lock() and unlock() methods - * (e.g. Swoole\Lock). The factory delegates to the constructor with the - * same validation, but the name signals the concurrency contract at the - * call site. - * - * @throws InvalidArgumentException when $lock is missing lock() or unlock() - */ public static function forCoroutineRuntime(object $lock, ?int $maxSize = null): self { return new self($maxSize, $lock); @@ -65,13 +40,7 @@ public static function forCoroutineRuntime(object $lock, ?int $maxSize = null): /** * @template T of object - * - * @param callable(): T $factory Must be non-blocking (no I/O) and non-recursive - * (no nested getOrCreate() calls). When a lock is configured, the lock is - * held for the entire duration of $factory; suspending inside $factory - * (e.g. Swoole coroutine I/O) or calling getOrCreate() recursively on the - * same key will deadlock. - * + * @param callable(): T $factory * @return T */ public function getOrCreate(string $key, callable $factory): object diff --git a/tests/Functional/Builder/BuilderConfigurationTest.php b/tests/Functional/Builder/BuilderConfigurationTest.php index ab0da7c8..b4e4a491 100644 --- a/tests/Functional/Builder/BuilderConfigurationTest.php +++ b/tests/Functional/Builder/BuilderConfigurationTest.php @@ -388,11 +388,6 @@ public function kitchen_sink_rejects_request_without_required_security_token(): } } - /** - * SEC-10: withMaxStreamingRecords rejects non-positive caps because a - * cap of 0 would reject every record and a negative cap would compare - * nonsensically against an accumulated count. - */ #[Test] public function with_max_streaming_records_rejects_zero(): void { @@ -414,10 +409,6 @@ public function with_max_streaming_records_rejects_negative(): void ->withMaxStreamingRecords(-1); } - /** - * SEC-10: A positive cap is accepted and does not interfere with the - * rest of the build pipeline. - */ #[Test] public function with_max_streaming_records_accepts_positive_cap(): void { diff --git a/tests/Functional/Builder/OpenApiValidatorBuilderCacheKeyTest.php b/tests/Functional/Builder/OpenApiValidatorBuilderCacheKeyTest.php index 19070d20..9ec96170 100644 --- a/tests/Functional/Builder/OpenApiValidatorBuilderCacheKeyTest.php +++ b/tests/Functional/Builder/OpenApiValidatorBuilderCacheKeyTest.php @@ -132,11 +132,6 @@ public function file_cache_key_uses_sha256_length(): void #[Test] public function file_cache_key_ignores_mtime_changes(): void { - // After R3-SEC-003 the cache key is keyed by realpath + content hash. - // mtime is intentionally NOT part of the key because it offered no - // defence once an attacker controls write access to the spec file - // (the `touch -r` workaround defeats metadata-only keys). The same - // content must therefore yield the same key regardless of mtime. $path = $this->writeTempSpec(self::MINIMAL_YAML); try { @@ -159,7 +154,7 @@ public function file_cache_key_ignores_mtime_changes(): void self::assertSame( $key1, $key2, - 'Cache key must ignore mtime after R3-SEC-003 content-hash fix (defends against touch -r cache-poisoning)', + 'Cache key must ignore mtime after content-hash fix (defends against touch -r cache-poisoning)', ); } finally { $this->safeUnlink($path); @@ -190,7 +185,7 @@ public function file_cache_key_changes_when_size_changes(): void ->build(); $key2 = $this->uniqueKeys($pool2->capturedKeys())[0]; - self::assertNotSame($key1, $key2, 'Cache key must change when file content changes (content-hash fix, R3-SEC-003)'); + self::assertNotSame($key1, $key2, 'Cache key must change when file content changes (content-hash fix)'); } finally { $this->safeUnlink($path); } @@ -216,7 +211,7 @@ public function file_cache_key_stable_across_rebuilds_with_unchanged_file(): voi ->build(); $key2 = $this->uniqueKeys($pool2->capturedKeys())[0]; - self::assertSame($key1, $key2, 'Same file content must produce identical cache key (content-hash fix, R3-SEC-003)'); + self::assertSame($key1, $key2, 'Same file content must produce identical cache key (content-hash fix)'); } finally { $this->safeUnlink($path); } @@ -243,14 +238,6 @@ public function file_cache_key_is_not_xxh64_length(): void } } - /** - * R4-SEC-008 anti-test (maxSpecDepth poisoning): caller A caches a - * spec under maxSpecDepth=10 (depth=6 fits), caller B with the - * stricter maxSpecDepth=5 must NOT receive the cached document — - * instead the cache-miss triggers a re-parse that rejects the spec. - * Without the parse-config fingerprint, caller B would silently - * bypass the depth limit and read the cached document. - */ #[Test] public function max_spec_depth_change_prevents_cache_poisoning(): void { @@ -293,18 +280,10 @@ public function max_spec_depth_change_prevents_cache_poisoning(): void $poisoningRejected, 'Caller B with stricter maxSpecDepth=5 must NOT receive the cached document ' . 'cached under maxSpecDepth=10. The fingerprint-based cache key must force a ' - . 're-parse that rejects the depth-6 spec (R4-SEC-008 cache-poisoning defence).', + . 're-parse that rejects the depth-6 spec (cache-poisoning defence).', ); } - /** - * R4-SEC-008 anti-test (externalRefAllowedRoot poisoning): two - * callers that differ only in externalRefAllowedRoot must get - * distinct cache keys. Without the fingerprint, caller B (root - * `/etc`) would receive the document cached by caller A (root - * `/safe`), bypassing its (presumably stricter) confinement - * boundary. - */ #[Test] public function external_ref_allowed_root_change_produces_distinct_cache_keys(): void { @@ -337,15 +316,10 @@ public function external_ref_allowed_root_change_produces_distinct_cache_keys(): $key1, $key2, 'externalRefAllowedRoot is part of the parse-config fingerprint and must ' - . 'produce a distinct cache key (R4-SEC-008 confinement poisoning defence).', + . 'produce a distinct cache key (confinement poisoning defence).', ); } - /** - * Stability: two callers with identical parse-config and identical - * spec content reuse the same cache key (cache-hit, single parse). - * Guards against accidental over-invalidation of the cache. - */ #[Test] public function identical_parse_config_and_content_reuse_cache_key(): void { @@ -374,13 +348,6 @@ public function identical_parse_config_and_content_reuse_cache_key(): void ); } - /** - * Unrelated-fields: runtime-validation toggles (coercion, - * nullableAsType, strictFormats, securityValidation, etc.) must - * NOT change the cache key. Two callers that differ only in - * runtime-validation flags reuse the cached parse result, because - * the parsed document is identical. - */ #[Test] public function runtime_validation_toggles_do_not_invalidate_cache(): void { @@ -415,7 +382,6 @@ public function runtime_validation_toggles_do_not_invalidate_cache(): void /** * @param list $keys - * * @return list */ private function uniqueKeys(array $keys): array diff --git a/tests/Functional/Builder/OpenApiValidatorBuilderLoggerWiringTest.php b/tests/Functional/Builder/OpenApiValidatorBuilderLoggerWiringTest.php index 8fa843cb..4e6c6e39 100644 --- a/tests/Functional/Builder/OpenApiValidatorBuilderLoggerWiringTest.php +++ b/tests/Functional/Builder/OpenApiValidatorBuilderLoggerWiringTest.php @@ -14,14 +14,6 @@ use function is_string; /** - * End-to-end coverage for the logger wiring introduced in task 02b: - * withLogger($logger) on the builder must propagate into the four - * silent-catch sites (PathParser, CallbackValidator, ServerPathMatcher, - * XmlBodyParser) so that PSR-3 records are produced on production paths. - * Verifies one wiring end-to-end (ServerPathMatcher) — the other three - * share the same $context->logger plumbing inside ValidatorDependencies, - * so this single assertion exercises the whole chain. - * * @internal */ final class OpenApiValidatorBuilderLoggerWiringTest extends TestCase @@ -66,9 +58,6 @@ public function with_logger_propagates_into_server_path_matcher_silent_catch(): $factory = new Psr17Factory(); $request = $factory->createServerRequest('GET', '/users'); - // ServerPathMatcher catches ServerVariableException for {unknown}, - // logs at debug, and falls back to the original request path so the - // path finder still matches '/users' and validateRequest returns. $operation = $validator->validateRequest($request); $this->assertSame('getUsers', $operation->operationId); diff --git a/tests/Functional/Builder/OpenApiValidatorBuilderStringSpecFailClosedTest.php b/tests/Functional/Builder/OpenApiValidatorBuilderStringSpecFailClosedTest.php index 4de2e811..a852c005 100644 --- a/tests/Functional/Builder/OpenApiValidatorBuilderStringSpecFailClosedTest.php +++ b/tests/Functional/Builder/OpenApiValidatorBuilderStringSpecFailClosedTest.php @@ -23,14 +23,6 @@ use const DIRECTORY_SEPARATOR; /** - * STRING-SPEC-FAILOPEN: specs loaded via fromYamlString() / - * fromJsonString() must fail closed at build() time when the spec - * contains an external `$ref` and withExternalRefAllowedRoot() has - * not been called. Without this guard the builtin FileExternalRefResolver - * runs with allowedRoot = null, which means assertPathWithinAllowedRoot - * is a no-op and an attacker-controlled spec can read arbitrary files - * via `file:///...` or relative-path `$ref` values. - * * @internal */ final class OpenApiValidatorBuilderStringSpecFailClosedTest extends TestCase diff --git a/tests/Functional/Builder/OpenApiValidatorBuilderWithFormatTest.php b/tests/Functional/Builder/OpenApiValidatorBuilderWithFormatTest.php index 2f75fcb0..6026c597 100644 --- a/tests/Functional/Builder/OpenApiValidatorBuilderWithFormatTest.php +++ b/tests/Functional/Builder/OpenApiValidatorBuilderWithFormatTest.php @@ -17,10 +17,6 @@ use ReflectionClass; /** - * Regression coverage for R4-SEC-009: builtin format validators must - * share the configured PregExecutor regardless of the order in which - * withFormat() and withMaxRegexBacktracks() are called. - * * @internal */ final class OpenApiValidatorBuilderWithFormatTest extends TestCase diff --git a/tests/Functional/Builder/SecurityValidationBuilderTest.php b/tests/Functional/Builder/SecurityValidationBuilderTest.php index cba18bf5..72c2c0ea 100644 --- a/tests/Functional/Builder/SecurityValidationBuilderTest.php +++ b/tests/Functional/Builder/SecurityValidationBuilderTest.php @@ -218,12 +218,6 @@ public function enable_security_validation_bearer_with_wrong_scheme_prefix_throw $this->assertTrue($caught, 'ValidationException should be thrown for wrong scheme prefix'); } - /** - * SEC-07 opt-in: withSecurityVerboseLogging() must propagate a PSR-3 - * logger through the builder DI chain so the security validator - * forwards scheme details at debug level when validation fails. The - * surfaced exception message stays generic regardless. - */ #[Test] public function with_security_verbose_logging_propagates_logger_through_builder(): void { @@ -246,15 +240,11 @@ public function with_security_verbose_logging_propagates_logger_through_builder( $this->assertCount(1, $errors); $this->assertInstanceOf(MissingSecurityCredentialsError::class, $errors[0]); - // SEC-07: surfaced message must remain generic despite verbose - // logging being enabled. Opt-in logging does not weaken the - // caller-safe contract. $this->assertSame( 'Authentication required: missing or invalid credentials', $errors[0]->getMessage(), ); - // Verbose logger must have received the concrete scheme details. $this->assertCount(1, $spy->records); $record = $spy->records[0]; $this->assertSame('debug', $record['level']); @@ -269,9 +259,6 @@ public function with_security_verbose_logging_propagates_logger_through_builder( } /** - * Minimal in-memory PSR-3 spy logger used to assert that - * withSecurityVerboseLogging() wires the logger end-to-end. - * * @internal */ final class SecurityVerboseSpyLogger implements LoggerInterface diff --git a/tests/Functional/Event/ValidationLifecycleTest.php b/tests/Functional/Event/ValidationLifecycleTest.php index ba935607..3b45019e 100644 --- a/tests/Functional/Event/ValidationLifecycleTest.php +++ b/tests/Functional/Event/ValidationLifecycleTest.php @@ -211,11 +211,11 @@ public function lifecycle_finished_duration_is_non_negative(): void } /** - * @param list $sequence - * @param ?ValidationStartedEvent $started + * @param list $sequence + * @param ?ValidationStartedEvent $started * @param ?ValidationFinishedEvent $finished - * @param ?ValidationErrorEvent $error - * @param ?ValidationWarningEvent $warning + * @param ?ValidationErrorEvent $error + * @param ?ValidationWarningEvent $warning */ private function createLifecycleDispatcher( array &$sequence, diff --git a/tests/Functional/FullCycle/FixtureE2ETest.php b/tests/Functional/FullCycle/FixtureE2ETest.php index 6e5a25f9..f06b66e1 100644 --- a/tests/Functional/FullCycle/FixtureE2ETest.php +++ b/tests/Functional/FullCycle/FixtureE2ETest.php @@ -304,9 +304,6 @@ public function boundary_values_fixture_rejects_integer_above_max(): void $caught = $e; } - // int32 format validator (registered per R3-SPEC-013) fires before - // the `maximum` keyword for values exceeding the int32 range. - // Either MaximumError or InvalidFormatException is a correct rejection. self::assertTrue( $caught instanceof MaximumError || $caught instanceof InvalidFormatException, 'Expected MaximumError or InvalidFormatException for int32_max above range', diff --git a/tests/Functional/FullCycle/FullCycleEventsTest.php b/tests/Functional/FullCycle/FullCycleEventsTest.php index 0e0b98ef..ec476a44 100644 --- a/tests/Functional/FullCycle/FullCycleEventsTest.php +++ b/tests/Functional/FullCycle/FullCycleEventsTest.php @@ -254,10 +254,10 @@ public function response_error_emits_started_finished_error_with_validation_exce } /** - * @param list $sequence - * @param ?ValidationStartedEvent $started + * @param list $sequence + * @param ?ValidationStartedEvent $started * @param ?ValidationFinishedEvent $finished - * @param ?ValidationErrorEvent $error + * @param ?ValidationErrorEvent $error */ private function buildLifecycleDispatcher( array &$sequence, diff --git a/tests/Functional/FullCycle/OpenApi32/AdditionalOperationsTest.php b/tests/Functional/FullCycle/OpenApi32/AdditionalOperationsTest.php index 41a8b9b5..0774ddcc 100644 --- a/tests/Functional/FullCycle/OpenApi32/AdditionalOperationsTest.php +++ b/tests/Functional/FullCycle/OpenApi32/AdditionalOperationsTest.php @@ -14,10 +14,6 @@ use function sprintf; -/** - * OA-02: OpenAPI 3.2 additionalOperations — non-standard HTTP methods (COPY, PURGE, etc.) - * defined inside PathItem via additionalOperations map. - */ final class AdditionalOperationsTest extends TestCase { private const string ADDITIONAL_OPERATIONS_SPEC = <<<'YAML' diff --git a/tests/Functional/FullCycle/OpenApi32/DiscriminatorDefaultMappingTest.php b/tests/Functional/FullCycle/OpenApi32/DiscriminatorDefaultMappingTest.php index 4234dc01..fda1e12d 100644 --- a/tests/Functional/FullCycle/OpenApi32/DiscriminatorDefaultMappingTest.php +++ b/tests/Functional/FullCycle/OpenApi32/DiscriminatorDefaultMappingTest.php @@ -12,10 +12,6 @@ use function sprintf; -/** - * OA-03: OpenAPI 3.2 discriminator.defaultMapping — unmapped discriminator values - * resolve to schema referenced by defaultMapping instead of throwing. - */ final class DiscriminatorDefaultMappingTest extends TestCase { private const string DISCRIMINATOR_WITH_DEFAULT_SPEC = <<<'YAML' diff --git a/tests/Functional/FullCycle/OpenApi32/JsonSchemaDialectTest.php b/tests/Functional/FullCycle/OpenApi32/JsonSchemaDialectTest.php index cad13a15..cdf81d2b 100644 --- a/tests/Functional/FullCycle/OpenApi32/JsonSchemaDialectTest.php +++ b/tests/Functional/FullCycle/OpenApi32/JsonSchemaDialectTest.php @@ -13,14 +13,6 @@ use function sprintf; -/** - * OA-04: OpenAPI 3.2 jsonSchemaDialect — declares JSON Schema dialect URL. - * - * Current behavior (documented): the field is parsed, stored on OpenApiDocument, - * and round-tripped through jsonSerialize. The validator pipeline does NOT switch - * validation rules based on the dialect value; the standard draft 2020-12 - * validator is always used. Tests pin this actual behavior. - */ final class JsonSchemaDialectTest extends TestCase { private const string JSON_SCHEMA_DIALECT_2020_12 = 'https://json-schema.org/draft/2020-12/schema'; diff --git a/tests/Functional/FullCycle/OpenApi32/SelfReferenceTest.php b/tests/Functional/FullCycle/OpenApi32/SelfReferenceTest.php index 23532c93..3308031e 100644 --- a/tests/Functional/FullCycle/OpenApi32/SelfReferenceTest.php +++ b/tests/Functional/FullCycle/OpenApi32/SelfReferenceTest.php @@ -16,15 +16,6 @@ use function sprintf; -/** - * OA-05: OpenAPI 3.2 $self reference — base URI for the document. - * - * Current behavior (documented): $self is parsed, validated as URL, stored on - * OpenApiDocument. RefResolver::getBaseUri() returns it; resolveRelativeRef() - * uses it as the base for combining relative refs and throws RefResolutionException - * when no $self is set. Recursive schemas referencing themselves resolve without - * infinite loops thanks to RefResolver's $visited map. - */ final class SelfReferenceTest extends TestCase { private const string SELF_BASE_URI = 'https://api.example.com/schemas/petstore.json'; diff --git a/tests/Functional/FullCycle/OpenApi32/Webhook32Test.php b/tests/Functional/FullCycle/OpenApi32/Webhook32Test.php index 75de6f9a..646381e1 100644 --- a/tests/Functional/FullCycle/OpenApi32/Webhook32Test.php +++ b/tests/Functional/FullCycle/OpenApi32/Webhook32Test.php @@ -19,10 +19,6 @@ use const JSON_THROW_ON_ERROR; -/** - * OA-06: OpenAPI 3.2 webhook with combined 3.2 features (jsonSchemaDialect, $self, - * recursive schema references in webhook body). - */ final class Webhook32Test extends TestCase { private const string WEBHOOK_WITH_DATE_TIME_FORMAT_SPEC = <<<'YAML' diff --git a/tests/Functional/FunctionalTestCase.php b/tests/Functional/FunctionalTestCase.php index 9acc14e9..c3709234 100644 --- a/tests/Functional/FunctionalTestCase.php +++ b/tests/Functional/FunctionalTestCase.php @@ -49,9 +49,6 @@ protected function setUp(): void $this->statelessValidators = new StatelessValidatorRegistry($this->pool, BuiltinFormats::create()); } - /** - * Create a validation context with specified formatter - */ protected function createContext(ErrorFormatterInterface $formatter = new SimpleFormatter()): ValidationContext { return new ValidationContext( @@ -61,9 +58,6 @@ protected function createContext(ErrorFormatterInterface $formatter = new Simple ); } - /** - * Create a validator instance - */ protected function createValidator(): SchemaValidatorWithContext { return new SchemaValidatorWithContext( @@ -77,9 +71,6 @@ protected function createValidator(): SchemaValidatorWithContext ); } - /** - * Validate data and expect ValidationException - */ protected function assertValidationError( callable $validationFn, string $expectedErrorClass, @@ -112,9 +103,6 @@ protected function assertValidationError( } } - /** - * Assert that validation passes without errors - */ protected function assertValidationPasses(callable $validationFn): void { try { @@ -133,9 +121,6 @@ protected function assertValidationPasses(callable $validationFn): void } } - /** - * Assert that multiple errors are present - */ protected function assertMultipleErrors( callable $validationFn, int $expectedCount, @@ -155,9 +140,6 @@ protected function assertMultipleErrors( } } - /** - * Get formatted errors as array - */ protected function getFormattedErrors(ValidationException $e, ErrorFormatterInterface $formatter): array { $errors = []; @@ -177,9 +159,6 @@ protected function getFormattedErrors(ValidationException $e, ErrorFormatterInte return $errors; } - /** - * Assert breadcrumb path in error - */ protected function assertBreadcrumb(string $expectedPath, ValidationException $e): void { $found = array_any($e->getErrors(), fn($error) => $error->dataPath() === $expectedPath); @@ -190,9 +169,6 @@ protected function assertBreadcrumb(string $expectedPath, ValidationException $e ); } - /** - * Get summary of error paths for debugging - */ protected function getErrorPathsSummary(ValidationException $e): string { $paths = []; @@ -203,9 +179,6 @@ protected function getErrorPathsSummary(ValidationException $e): string return implode(', ', $paths); } - /** - * Get all error types from exception - */ protected function getErrorTypes(ValidationException $e): array { $types = []; diff --git a/tests/Functional/Regression/CoercionWholeFloatRegressionTest.php b/tests/Functional/Regression/CoercionWholeFloatRegressionTest.php index 9a14f218..e5239af9 100644 --- a/tests/Functional/Regression/CoercionWholeFloatRegressionTest.php +++ b/tests/Functional/Regression/CoercionWholeFloatRegressionTest.php @@ -12,8 +12,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; -use Duyler\OpenApi\Validator\Coercion\AbstractCoercer; -use Duyler\OpenApi\Validator\Request\RequestBodyCoercer; use function json_encode; use function sprintf; @@ -21,21 +19,6 @@ use const JSON_THROW_ON_ERROR; /** - * Regression suite for R4-SPEC-005 / R4-TEST-008: strict type coercion - * accepts whole-valued floats (3.0) as integers per JSON Schema - * 2020-12 §4.2.3 and rejects fractional / non-finite floats. - * - * Anti-test: re-introducing the legacy rejection of any float (including - * whole-valued 3.0) in {@see AbstractCoercer::coerceToIntegerStrict()} - * makes tests 1–3 fail; loosening the strict guard to accept fractional - * floats makes tests 4–5 fail. - * - * Unlike the inline AbstractCoercerTest, this suite drives the - * coercion path through the public request body validator - * ({@see OpenApiValidatorBuilder::build()->validateRequest()}) so the - * regression also fires when {@see RequestBodyCoercer} - * is rewired. - * * @internal */ final class CoercionWholeFloatRegressionTest extends TestCase diff --git a/tests/Functional/Regression/DiscriminatorNestedCompositionRegressionTest.php b/tests/Functional/Regression/DiscriminatorNestedCompositionRegressionTest.php index 478c4ce8..03f6c69b 100644 --- a/tests/Functional/Regression/DiscriminatorNestedCompositionRegressionTest.php +++ b/tests/Functional/Regression/DiscriminatorNestedCompositionRegressionTest.php @@ -13,22 +13,6 @@ use function array_map; /** - * Regression suite for R4-CORRECTNESS-002 / R4-CORRECTNESS-005 / - * R4-TEST-005: DiscriminatorValidator nested-composition recursion - * and evaluated-property annotation propagation. - * - * Anti-test for the recursion fix: rolling back the early-return on - * a nested composition that throws UnknownDiscriminatorValueException - * (legacy behaviour) makes tests 1 and 2 throw instead of succeeding. - * Anti-test for the annotation-propagation fix: rolling back the - * mergeChildAnnotations call on the discriminator branch makes tests - * 3 and 4 raise unevaluatedProperties / unevaluatedItems errors on - * valid payloads. - * - * Unlike the inline DiscriminatorValidatorTest, this suite drives - * every case through the public builder path so the regression also - * fires when discriminator wiring is broken at the builder level. - * * @internal */ final class DiscriminatorNestedCompositionRegressionTest extends TestCase diff --git a/tests/Functional/Regression/ExceptionInfoLeakRegressionTest.php b/tests/Functional/Regression/ExceptionInfoLeakRegressionTest.php index fbb94944..e62e9f67 100644 --- a/tests/Functional/Regression/ExceptionInfoLeakRegressionTest.php +++ b/tests/Functional/Regression/ExceptionInfoLeakRegressionTest.php @@ -17,19 +17,6 @@ use function implode; /** - * Regression suite for R4-SEC-007a/b/c/d / R4-TEST-007: exception - * messages must not reflect attacker-controlled inputs (request path, - * method, media type, parameter name) when emitted from the public - * validator API. Anti-test: re-introducing the legacy behaviour that - * interpolates the attacker value into getMessage() makes the four - * structural assertions below fail. - * - * Unlike the inline exception tests that exercise the constructors - * in isolation, this suite drives every case through the public - * {@see OpenApiValidatorBuilder::build()} path so the regression also - * fires when an HTTP-side code path reconstructs the exception from - * raw input rather than through the public constructor. - * * @internal */ final class ExceptionInfoLeakRegressionTest extends TestCase diff --git a/tests/Functional/Regression/NestedParameterCoercionRegressionTest.php b/tests/Functional/Regression/NestedParameterCoercionRegressionTest.php index 4588399e..cb5cca9d 100644 --- a/tests/Functional/Regression/NestedParameterCoercionRegressionTest.php +++ b/tests/Functional/Regression/NestedParameterCoercionRegressionTest.php @@ -6,7 +6,6 @@ use Duyler\OpenApi\Builder\OpenApiValidatorBuilder; use Duyler\OpenApi\Builder\OpenApiValidatorInterface; -use Duyler\OpenApi\Validator\Request\TypeCoercer; use Nyholm\Psr7\Factory\Psr17Factory; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; @@ -18,14 +17,6 @@ use const PHP_URL_QUERY; /** - * Regression suite for issue #60: parameter coercion did not recurse into - * `object` properties or `array` items, so a nested `integer` / `number` / - * `boolean` was unsatisfiable — query, path, header and cookie values arrive - * as strings, and coercion was the only path to a non-string leaf. - * - * Anti-test: removing the `object` / `array` arms from - * {@see TypeCoercer::coerceToType()} makes every nested case below fail again. - * * @internal */ final class NestedParameterCoercionRegressionTest extends TestCase diff --git a/tests/Functional/Regression/NestedRefInKeywordsRegressionTest.php b/tests/Functional/Regression/NestedRefInKeywordsRegressionTest.php index b9d9076d..6aa699cf 100644 --- a/tests/Functional/Regression/NestedRefInKeywordsRegressionTest.php +++ b/tests/Functional/Regression/NestedRefInKeywordsRegressionTest.php @@ -15,17 +15,6 @@ use function sprintf; /** - * Regression suite for R4-CORRECTNESS-001 / R4-TEST-004: `$ref` - * resolution inside every schema-typed keyword. Anti-test: rolling - * back the fix (returning the legacy recursion engine without - * document context) makes the `{$ref: ...}` stub a no-op, so the - * invalid data passes validation silently and every dataset below - * fails to throw. - * - * Unlike the inline NestedRefResolutionTest, this suite drives every - * keyword through the public {@see OpenApiValidatorBuilder::build()} - * path so the regression also fires when the builder wiring breaks. - * * @internal */ final class NestedRefInKeywordsRegressionTest extends TestCase diff --git a/tests/Functional/Regression/NullableInCompositionRegressionTest.php b/tests/Functional/Regression/NullableInCompositionRegressionTest.php index dbcc4cc0..a63422e3 100644 --- a/tests/Functional/Regression/NullableInCompositionRegressionTest.php +++ b/tests/Functional/Regression/NullableInCompositionRegressionTest.php @@ -11,21 +11,6 @@ use PHPUnit\Framework\TestCase; /** - * Regression suite for issue #66: the `null` pre-check that runs before a - * property or array item is validated inspected only the immediate schema - * node. A composition node (`allOf`/`anyOf`/`oneOf`) carries neither `type` - * nor `nullable` — both live in its branches — so a permitted `null` was - * rejected by InvalidDataTypeException before a single branch ran. - * - * Anti-test: restoring the node-local `$allowNull` computation makes every - * composition case below throw instead of pass. - * - * A 3.0 `allOf: [{$ref: }]` is deliberately absent: it also - * trips the `$ref` sibling merge of issue #64, which discards the target's - * `nullable` before this pre-check ever runs. The `$ref` branch covered here - * reaches its nullability through a composition instead, so it exercises the - * deferral without depending on that separate fix. - * * @internal */ final class NullableInCompositionRegressionTest extends TestCase diff --git a/tests/Functional/Regression/SchemaCacheParseConfigRegressionTest.php b/tests/Functional/Regression/SchemaCacheParseConfigRegressionTest.php index 4b45ee69..2f3a6c37 100644 --- a/tests/Functional/Regression/SchemaCacheParseConfigRegressionTest.php +++ b/tests/Functional/Regression/SchemaCacheParseConfigRegressionTest.php @@ -18,21 +18,6 @@ use function str_starts_with; /** - * Regression suite for R4-SEC-008 / R4-TEST-011: the SchemaCache key - * must incorporate the parse-config fingerprint so a caller that - * tightens any of maxSpecSizeBytes / maxSpecDepth / externalRefMaxBytes - * never silently receives a document cached under looser limits. - * - * Anti-test: removing the buildParseConfigFingerprint() input makes - * the cache hit succeed in test 1 (caller B gets the cached document - * even though its tighter size limit would otherwise reject the spec) - * and makes the keys produced in tests 2 and 3 identical. - * - * Unlike the inline OpenApiValidatorBuilderCacheKeyTest that focuses - * on maxSpecDepth and externalRefAllowedRoot, this suite exercises - * the maxSpecSizeBytes and externalRefMaxBytes dimensions of the - * fingerprint. - * * @internal */ final class SchemaCacheParseConfigRegressionTest extends TestCase @@ -72,7 +57,7 @@ public function stricter_max_spec_size_with_shared_cache_forces_reject_on_cache_ $poisoningRejected, 'Caller B with stricter maxSpecSize=1 must NOT receive the document cached under ' . 'maxSpecSize=1048576. The fingerprint-based cache key must force a re-parse that ' - . 'rejects the (here) oversized spec (R4-SEC-008 size poisoning defence).', + . 'rejects the (here) oversized spec (size poisoning defence).', ); } @@ -121,7 +106,6 @@ public function identical_parse_config_reuses_same_cache_key(): void /** * @param callable(OpenApiValidatorBuilder): OpenApiValidatorBuilder $configure - * * @return list */ private function captureKeys(callable $configure): array diff --git a/tests/Functional/Regression/TimeValidatorOffsetRequiredRegressionTest.php b/tests/Functional/Regression/TimeValidatorOffsetRequiredRegressionTest.php index adfe6822..151741db 100644 --- a/tests/Functional/Regression/TimeValidatorOffsetRequiredRegressionTest.php +++ b/tests/Functional/Regression/TimeValidatorOffsetRequiredRegressionTest.php @@ -11,24 +11,10 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Duyler\OpenApi\Validator\Format\BuiltinFormats; -use Duyler\OpenApi\Validator\Format\String\TimeValidator; use function sprintf; /** - * Regression suite for R4-SPEC-006 / R4-TEST-009: the `time` format - * requires a UTC offset per RFC 3339 §5.6 (Z, +HH:MM, -HH:MM). - * - * Anti-test: re-introducing the `?` quantifier on the offset-group of - * {@see TimeValidator::TIME_PATTERN} - * makes every "rejected" dataset below silently pass. - * - * Unlike the inline TimeValidatorTest, this suite drives every value - * through the public builder path so the regression also fires when - * the {@see BuiltinFormats} registry - * stops wiring TimeValidator. - * * @internal */ final class TimeValidatorOffsetRequiredRegressionTest extends TestCase diff --git a/tests/Functional/Regression/WithFormatOrderRegressionTest.php b/tests/Functional/Regression/WithFormatOrderRegressionTest.php index f94771f7..0c15e697 100644 --- a/tests/Functional/Regression/WithFormatOrderRegressionTest.php +++ b/tests/Functional/Regression/WithFormatOrderRegressionTest.php @@ -15,23 +15,6 @@ use Throwable; /** - * Regression suite for R4-SEC-009 / R4-TEST-010: builtin format - * validators must share the configured PregExecutor regardless of - * the order in which withFormat() and withMaxRegexBacktracks() are - * chained, and a later withFormat('string','email',...) must - * override the builtin email validator regardless of order. - * - * Anti-test: re-introducing the legacy single-call-only wiring (where - * the second withFormat() or a later withMaxRegexBacktracks() would - * silently drop the configuration) makes the override assertions - * fail. - * - * Unlike the inline OpenApiValidatorBuilderWithFormatTest that uses - * reflection to assert on private state, this suite drives every - * case through validateSchema() so the regression also fires when - * the override mechanism is broken at the format-registry lookup - * level rather than at construction time. - * * @internal */ final class WithFormatOrderRegressionTest extends TestCase diff --git a/tests/Functional/Regression/YamlBillionLaughsRegressionTest.php b/tests/Functional/Regression/YamlBillionLaughsRegressionTest.php index 35124836..bbf76efb 100644 --- a/tests/Functional/Regression/YamlBillionLaughsRegressionTest.php +++ b/tests/Functional/Regression/YamlBillionLaughsRegressionTest.php @@ -10,16 +10,6 @@ use PHPUnit\Framework\TestCase; /** - * Regression suite for R4-SEC-012 / R4-TEST-006: YAML billion-laughs - * defence on the public builder path. Anti-test: removing the - * pre-parse `assertNoAnchorBomb()` scan lets the Symfony YAML parser - * materialise the exponentially-expanded document and the test - * either OOMs the CI runner or times out. - * - * Unlike the inline YamlParserTest, this suite drives every case - * through {@see OpenApiValidatorBuilder::build()} so the regression - * also fires when the builder skips the parser (e.g. via cache). - * * @internal */ final class YamlBillionLaughsRegressionTest extends TestCase diff --git a/tests/Functional/Request/CookieCoercionTest.php b/tests/Functional/Request/CookieCoercionTest.php index b26c9fa4..3b199d8b 100644 --- a/tests/Functional/Request/CookieCoercionTest.php +++ b/tests/Functional/Request/CookieCoercionTest.php @@ -9,33 +9,18 @@ use Duyler\OpenApi\Schema\Model\Schema; use Duyler\OpenApi\Validator\Exception\ConstError; use Duyler\OpenApi\Validator\Exception\TypeMismatchError; -use Duyler\OpenApi\Validator\Operation; use Duyler\OpenApi\Validator\Request\TypeCoercer; use Nyholm\Psr7\Factory\Psr17Factory; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; -/** - * TC-07: Cookie parameter type coercion. - * - * PSR-7 cookies are always delivered as strings (RFC 6265). When an OpenAPI - * parameter is declared `type: integer` and `enableCoercion()` is on, the - * validator's TypeCoercer converts the cookie string to int before schema - * validation. The coerced value is not exposed via Operation, so coercion is - * proven indirectly through schema constraints that can only be satisfied by - * the coerced integer form. - * - * CookieValidator invokes TypeCoercer with strict=true (consistent with - * HeadersValidator). In strict mode non-numeric strings are rejected with - * TypeMismatchError during coercion rather than silently coerced to 0. - */ final class CookieCoercionTest extends TestCase { private const string COOKIE_COERCION_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: TC-07 Cookie Coercion API + title: Cookie Coercion API version: 1.0.0 paths: /visit: @@ -59,12 +44,6 @@ protected function setUp(): void $this->psrFactory = new Psr17Factory(); } - /** - * Direct unit-level proof: TypeCoercer converts cookie string "42" to int. - * - * assertSame(42, ...) checks both value and type — this is the only place - * where the coerced integer is directly observable. - */ #[Test] public function tc_07_type_coercer_directly_converts_cookie_string_to_int(): void { @@ -77,14 +56,6 @@ public function tc_07_type_coercer_directly_converts_cookie_string_to_int(): voi $this->assertIsInt($result); } - /** - * Baseline: without coercion the cookie string "42" is left as a string - * and fails the const constraint. PHP's loose comparison keeps "42" - * through the type check, but strict `===` in ConstError rejects it. - * - * This baseline proves the next test passes specifically because of - * coercion, not because the validator is lenient about types. - */ #[Test] public function tc_07_cookie_without_coercion_fails_const_check_on_string_value(): void { @@ -111,14 +82,6 @@ public function tc_07_cookie_without_coercion_fails_const_check_on_string_value( $this->assertSame('42', $caught->params()['actual']); } - /** - * Positive: with coercion, cookie string "42" is converted to int 42 and - * passes both the type check and the const constraint. - * - * The const constraint can only match the integer literal 42 — the - * string "42" fails it (see baseline test above). Successful validation - * therefore proves coercion occurred end-to-end. - */ #[Test] public function tc_07_cookie_string_coerced_to_integer_passes_const_constraint(): void { @@ -135,13 +98,6 @@ public function tc_07_cookie_string_coerced_to_integer_passes_const_constraint() $this->assertSame('/visit', $operation->path); } - /** - * Negative: cookie string "abc" cannot be coerced to integer. - * - * CookieValidator invokes TypeCoercer with strict=true, so the coercer - * rejects non-numeric strings directly with TypeMismatchError during - * coercion (before the const constraint is evaluated). - */ #[Test] public function tc_07_cookie_non_numeric_string_throws_type_mismatch(): void { @@ -169,11 +125,6 @@ public function tc_07_cookie_non_numeric_string_throws_type_mismatch(): void $this->assertSame('abc', $caught->params()['actual']); } - /** - * Direct unit-level proof: in strict mode TypeCoercer rejects non-numeric - * strings with TypeMismatchError. CookieValidator passes strict=true, so - * this is the path exercised end-to-end by the test above. - */ #[Test] public function tc_07_type_coercer_strict_mode_rejects_non_numeric_cookie_with_type_mismatch(): void { diff --git a/tests/Functional/Request/CookieValidationTest.php b/tests/Functional/Request/CookieValidationTest.php index aee23251..efb75306 100644 --- a/tests/Functional/Request/CookieValidationTest.php +++ b/tests/Functional/Request/CookieValidationTest.php @@ -15,20 +15,6 @@ use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; -/** - * CK-01 / CK-02 / CK-03: Cookie parameter edge cases. - * - * - CK-01: integer cookie coercion with `enableCoercion()`. PSR-7 cookie - * values are always strings (RFC 6265); the TypeCoercer converts - * numeric strings to int when the schema declares `type: integer`. - * CookieValidator passes `strict=true` to the coercer, so non-numeric - * strings are rejected with TypeMismatchError during coercion. - * - CK-02: non-ASCII cookie values URL-encoded as `%XX` sequences. - * CookieValidator uses `rawurldecode` on the raw cookie value. - * - CK-03: `style: form + explode: true` for cookie arrays. Multiple - * cookies with the same name are collected into an indexed array - * via CookieHeaderParser::parseExplodedValues. - */ final class CookieValidationTest extends TestCase { private Psr17Factory $psrFactory; @@ -38,13 +24,6 @@ protected function setUp(): void $this->psrFactory = new Psr17Factory(); } - /** - * CK-01 unit-level: TypeCoercer converts cookie string "25" to int 25. - * - * `assertSame(25, $result)` checks both value and type — the only place - * where the coerced integer is directly observable end-to-end. - * CookieValidator passes strict=true to the coercer. - */ #[Test] public function ck_01_type_coercer_directly_converts_cookie_string_to_int_25(): void { @@ -57,21 +36,13 @@ public function ck_01_type_coercer_directly_converts_cookie_string_to_int_25(): $this->assertIsInt($result); } - /** - * CK-01 full-cycle positive: cookie "age=25" with `type: integer` and - * `const: 25`. The string "25" is coerced to int 25, satisfying the - * const constraint that only matches the integer literal. - * - * Without coercion (see CK-01 negative below), the same request fails - * because the cookie value remains a string. - */ #[Test] public function ck_01_cookie_integer_value_coerced_passes_const_constraint(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: CK-01 Cookie Coercion API + title: Cookie Coercion API version: 1.0.0 paths: /visit: @@ -100,17 +71,13 @@ public function ck_01_cookie_integer_value_coerced_passes_const_constraint(): vo $this->assertSame('GET', $operation->method); } - /** - * CK-01 baseline: without `enableCoercion()`, cookie string "25" is - * left as a string and fails the integer const constraint. - */ #[Test] public function ck_01_cookie_integer_without_coercion_fails_const_check(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: CK-01 Cookie Coercion API + title: Cookie Coercion API version: 1.0.0 paths: /visit: @@ -149,20 +116,13 @@ public function ck_01_cookie_integer_without_coercion_fails_const_check(): void $this->assertSame('25', $caught->params()['actual']); } - /** - * CK-01 negative: cookie "age=abc" cannot be coerced to integer. - * - * CookieValidator invokes TypeCoercer with strict=true, so the coercer - * rejects non-numeric strings directly with TypeMismatchError during - * coercion (before the const constraint is evaluated). - */ #[Test] public function ck_01_cookie_non_numeric_string_throws_type_mismatch(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: CK-01 Cookie Coercion API + title: Cookie Coercion API version: 1.0.0 paths: /visit: @@ -202,11 +162,6 @@ public function ck_01_cookie_non_numeric_string_throws_type_mismatch(): void $this->assertSame('abc', $caught->params()['actual']); } - /** - * CK-01 unit-level negative: direct TypeCoercer invocation in strict - * mode. `coerce('abc', integer, strict: true)` raises TypeMismatchError, - * which is the path exercised end-to-end by the test above. - */ #[Test] public function ck_01_type_coercer_strict_mode_rejects_non_numeric_string_with_type_mismatch(): void { @@ -230,19 +185,13 @@ public function ck_01_type_coercer_strict_mode_rejects_non_numeric_string_with_t $this->assertSame('abc', $caught->params()['actual']); } - /** - * CK-02 positive: URL-encoded UTF-8 cookie value. PSR-7 cookie "name" - * contains the raw encoded form `%D0%98%D0%B2%D0%B0%D0%BD`. - * CookieValidator::decodeValue applies `rawurldecode`, yielding the - * UTF-8 string "Иван". The decoded value satisfies `const: 'Иван'`. - */ #[Test] public function ck_02_cookie_url_encoded_utf8_value_decoded_to_string(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: CK-02 Cookie Non-ASCII API + title: Cookie Non-ASCII API version: 1.0.0 paths: /who: @@ -270,18 +219,13 @@ public function ck_02_cookie_url_encoded_utf8_value_decoded_to_string(): void $this->assertSame('GET', $operation->method); } - /** - * CK-02 negative: the same URL-encoded Cyrillic value with a different - * const constraint. The decoded value "Иван" does not match const - * "Петр", proving the value was decoded to UTF-8 before validation. - */ #[Test] public function ck_02_cookie_url_encoded_utf8_value_decoded_does_not_match_other_const(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: CK-02 Cookie Non-ASCII API + title: Cookie Non-ASCII API version: 1.0.0 paths: /who: @@ -320,12 +264,6 @@ public function ck_02_cookie_url_encoded_utf8_value_decoded_does_not_match_other $this->assertSame('Иван', $caught->params()['actual']); } - /** - * CK-02 unit-level: rawurldecode on the cookie raw value yields UTF-8. - * - * `%D0%98%D0%B2%D0%B0%D0%BD` is the UTF-8 byte sequence for "Иван" - * percent-encoded. rawurldecode reverses this losslessly. - */ #[Test] public function ck_02_raw_url_decode_of_cyrillic_cookie_value_yields_utf8(): void { @@ -334,21 +272,13 @@ public function ck_02_raw_url_decode_of_cyrillic_cookie_value_yields_utf8(): voi $this->assertSame('Иван', $decoded); } - /** - * CK-03 positive: `style: form + explode: true` for cookie arrays via - * multiple Cookie header values with the same name. The Cookie header - * `tags=php; tags=go` is parsed by CookieHeaderParser::parseExplodedValues - * into the array ["php", "go"]. - * - * The `minItems: 2` constraint proves two items were actually collected. - */ #[Test] public function ck_03_cookie_style_form_explode_collects_repeated_keys_into_array(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: CK-03 Cookie Explode API + title: Cookie Explode API version: 1.0.0 paths: /data: @@ -382,19 +312,13 @@ public function ck_03_cookie_style_form_explode_collects_repeated_keys_into_arra $this->assertSame('GET', $operation->method); } - /** - * CK-03 negative: explode:true with only one cookie value. The single - * cookie "tags=php" does not trigger the explode path (hasMultipleCookies - * returns false), so the value remains a string "php" rather than an - * array. The `type: array` schema then rejects the string form. - */ #[Test] public function ck_03_cookie_style_form_explode_single_value_fails_array_schema(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: CK-03 Cookie Explode API + title: Cookie Explode API version: 1.0.0 paths: /data: diff --git a/tests/Functional/Request/DuplicateKeysTest.php b/tests/Functional/Request/DuplicateKeysTest.php index 7e452683..b53d8ffa 100644 --- a/tests/Functional/Request/DuplicateKeysTest.php +++ b/tests/Functional/Request/DuplicateKeysTest.php @@ -18,23 +18,13 @@ use const JSON_THROW_ON_ERROR; -/** - * RB-11: JSON request body with duplicate keys. - * - * RFC 8259 §4 says object names "SHOULD be unique" (not MUST). When duplicates - * appear, the behaviour is implementation-defined. PHP json_decode implements - * "last value wins" semantics — the latest duplicate overrides earlier ones. - * This characterization test pins that behaviour end-to-end through the - * OpenAPI validator pipeline so any future change to the parser surfaces - * visibly. - */ #[CoversClass(JsonBodyParser::class)] final class DuplicateKeysTest extends TestCase { private const string DUPLICATE_KEYS_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: RB-11 Duplicate Keys API + title: Duplicate Keys API version: 1.0.0 paths: /data: @@ -55,13 +45,6 @@ final class DuplicateKeysTest extends TestCase description: Created YAML; - /** - * Sanity check: PHP's json_decode uses last value wins on duplicate keys. - * - * This is the underlying primitive that JsonBodyParser relies on. Pinning - * this in a unit-level assertion documents the source of the behaviour - * before the end-to-end test. - */ #[Test] public function rb_11_php_json_decode_last_value_wins_for_duplicate_keys(): void { @@ -70,16 +53,6 @@ public function rb_11_php_json_decode_last_value_wins_for_duplicate_keys(): void $this->assertSame(['value' => 2], $decoded); } - /** - * Positive: JSON body with duplicate keys is accepted; the last value - * wins and is validated against the schema. - * - * The schema declares `value` with `const: 2`. The body contains - * `{"value":1,"value":2}`. With last-value-wins semantics the parsed - * value is 2, which satisfies the const constraint and validation - * succeeds. If the parser were changed to first-value-wins (or to - * reject duplicates), this test would fail and surface the change. - */ #[Test] public function rb_11_duplicate_keys_last_value_wins_passes_validation(): void { @@ -95,14 +68,6 @@ public function rb_11_duplicate_keys_last_value_wins_passes_validation(): void $this->assertSame('/data', $operation->path); } - /** - * Negative: when the last value violates the schema, validation fails — - * proving the validator operates on the last duplicate, not the first. - * - * Body `{"value":2,"value":1}` parses to value=1 (last wins), which - * violates `const: 2`. The resulting ConstError surfaces the resolved - * value and expected value so we can confirm last-wins semantics. - */ #[Test] public function rb_11_duplicate_keys_negative_when_last_value_violates_schema(): void { @@ -137,12 +102,6 @@ public function rb_11_duplicate_keys_negative_when_last_value_violates_schema(): $this->assertSame(1, $params['actual'], 'Resolved value must be 1 (last duplicate wins).'); } - /** - * Round-trip: json_encode of the decoded body must not contain duplicates. - * - * After json_decode, the duplicate is collapsed into a single key in the - * PHP array, so any re-encoded form contains exactly one `value` entry. - */ #[Test] public function rb_11_decoded_body_round_trips_to_single_key(): void { diff --git a/tests/Functional/Request/HeaderArrayTest.php b/tests/Functional/Request/HeaderArrayTest.php index 8c6dad04..155a5b0e 100644 --- a/tests/Functional/Request/HeaderArrayTest.php +++ b/tests/Functional/Request/HeaderArrayTest.php @@ -12,24 +12,12 @@ use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; -/** - * HD-05: Header parameter with `type: array` schema. - * - * PSR-7 headers are delivered as `string[]` arrays per RFC 7230 §3.2.2. - * The RequestValidator normalizes each header into a single comma-joined - * string via `implode(', ', $values)`. The HeadersValidator then routes - * the value through `ParameterDeserializer::deserializeSimple`, which - * splits on the comma character and trims each item to produce the - * array form. Per RFC 7230 §3.2.3, optional whitespace around the list - * separator is allowed, so the comma-space join and comma split compose - * cleanly: split items never carry leading or trailing spaces. - */ final class HeaderArrayTest extends TestCase { private const string HEADER_ARRAY_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: HD-05 Header Array API + title: Header Array API version: 1.0.0 paths: /items: @@ -54,20 +42,13 @@ protected function setUp(): void $this->psrFactory = new Psr17Factory(); } - /** - * HD-05 positive: `X-Items: a,b,c` (single string, no spaces around commas) - * parses to the 3-element array ["a", "b", "c"] against `type: array`. - * - * The successful validation against `items.enum: [a, b, c]` proves the - * comma-separated string was split into individual items. - */ #[Test] public function hd_05_header_string_value_with_commas_parses_to_array(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: HD-05 Header Array API + title: Header Array API version: 1.0.0 paths: /items: @@ -97,13 +78,6 @@ enum: [a, b, c] $this->assertSame('GET', $operation->method); } - /** - * HD-05 positive (PSR-7 multi-value): `withHeader('X-Items', ['a', 'b', 'c'])` - * produces a clean array after split when each PSR-7 value contains a - * single token. The RequestValidator joins PSR-7 values with `, ` and - * ParameterDeserializer splits by `,` and trims each item, so the - * resulting items are clean regardless of the comma-space join. - */ #[Test] public function hd_05_header_psr7_array_value_parses_to_array(): void { @@ -121,13 +95,6 @@ public function hd_05_header_psr7_array_value_parses_to_array(): void $this->assertSame('GET', $operation->method); } - /** - * HD-05 negative: required header missing entirely. - * - * HeadersValidator::resolveValue returns null when no header with - * matching name (case-insensitive) is present. The required flag then - * raises MissingParameterException for the header location. - */ #[Test] public function hd_05_missing_required_header_throws_missing_parameter(): void { @@ -151,19 +118,13 @@ public function hd_05_missing_required_header_throws_missing_parameter(): void self::assertStringContainsString('header', $caught->getMessage()); } - /** - * HD-05 negative: too many items — `X-Items: a,b,c,d` against `maxItems: 3`. - * - * The 4-element split array exceeds the maxItems constraint and - * raises MaxItemsError with params `['maxItems' => 3, 'actual' => 4]`. - */ #[Test] public function hd_05_header_value_exceeding_max_items_throws_max_items_error(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: HD-05 Header Array API + title: Header Array API version: 1.0.0 paths: /items: @@ -202,24 +163,13 @@ public function hd_05_header_value_exceeding_max_items_throws_max_items_error(): self::assertSame(4, $caught->params()['actual']); } - /** - * HD-05 edge (fixed): PSR-7 array header values joined with `, ` - * (comma+space) by the RequestValidator are split and trimmed by - * `ParameterDeserializer::splitBySeparator`, so the resulting items - * carry no leading spaces. - * - * Before bugfix-20 the split produced `["a", " b", " c"]` and the - * enum constraint `[a, b, c]` rejected `" b"`. After the trim fix - * the split produces `["a", "b", "c"]` and the enum validation - * passes, proving the items are clean. - */ #[Test] public function hd_05_psr7_array_header_trims_split_items(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: HD-05 Header Array API + title: Header Array API version: 1.0.0 paths: /items: diff --git a/tests/Functional/Request/HeaderCoercionTest.php b/tests/Functional/Request/HeaderCoercionTest.php index d3cf99ca..ae8252bc 100644 --- a/tests/Functional/Request/HeaderCoercionTest.php +++ b/tests/Functional/Request/HeaderCoercionTest.php @@ -15,23 +15,12 @@ use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; -/** - * TC-08: Header parameter type coercion. - * - * PSR-7 headers are always delivered as strings. When an OpenAPI parameter - * is declared `type: integer` and `enableCoercion()` is on, the validator's - * TypeCoercer converts the header string to int before schema validation. - * - * HeadersValidator invokes TypeCoercer with strict=true (consistent with - * CookieValidator which also uses strict=true). In strict mode non-numeric - * strings and overflow values are rejected with TypeMismatchError. - */ final class HeaderCoercionTest extends TestCase { private const string HEADER_COERCION_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: TC-08 Header Coercion API + title: Header Coercion API version: 1.0.0 paths: /metrics: @@ -55,13 +44,6 @@ protected function setUp(): void $this->psrFactory = new Psr17Factory(); } - /** - * Direct unit-level proof: TypeCoercer converts header string "42" to int. - * - * assertSame(42, ...) checks both value and type — this is the only place - * where the coerced integer is directly observable. Header validation - * uses strict=true, so the assertion is performed with strict mode. - */ #[Test] public function tc_08_type_coercer_directly_converts_header_string_to_int(): void { @@ -74,14 +56,6 @@ public function tc_08_type_coercer_directly_converts_header_string_to_int(): voi $this->assertIsInt($result); } - /** - * Baseline: without coercion the header string "42" is left as a string - * and fails the const constraint. PHP's loose comparison keeps "42" - * through the type check, but strict `===` in ConstError rejects it. - * - * This baseline proves the next test passes specifically because of - * coercion, not because the validator is lenient about types. - */ #[Test] public function tc_08_header_without_coercion_fails_const_check_on_string_value(): void { @@ -108,14 +82,6 @@ public function tc_08_header_without_coercion_fails_const_check_on_string_value( $this->assertSame('42', $caught->params()['actual']); } - /** - * Positive: with coercion, header string "42" is converted to int 42 and - * passes both the type check and the const constraint. - * - * The const constraint can only match the integer literal 42 — the - * string "42" fails it (see baseline test above). Successful validation - * therefore proves coercion occurred end-to-end. - */ #[Test] public function tc_08_header_string_coerced_to_integer_passes_const_constraint(): void { @@ -132,12 +98,6 @@ public function tc_08_header_string_coerced_to_integer_passes_const_constraint() $this->assertSame('/metrics', $operation->path); } - /** - * Negative: header string "abc" cannot be coerced to integer. - * - * HeadersValidator uses strict=true, so TypeMismatchError is raised - * directly during coercion (before schema constraint validation). - */ #[Test] public function tc_08_header_non_numeric_string_fails_coercion_with_type_mismatch(): void { @@ -165,19 +125,13 @@ public function tc_08_header_non_numeric_string_fails_coercion_with_type_mismatc $this->assertSame('abc', $caught->params()['actual']); } - /** - * Negative: an overflow header value must fail coercion in strict mode. - * - * PHP's `(int) "99999999999999999999"` cannot represent the value - * faithfully, so the strict coercer rejects it as a type mismatch. - */ #[Test] public function tc_08_header_overflow_numeric_string_fails_coercion_with_type_mismatch(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: TC-08 Header Coercion Overflow API + title: Header Coercion Overflow API version: 1.0.0 paths: /metrics: diff --git a/tests/Functional/Request/HeaderValidationTest.php b/tests/Functional/Request/HeaderValidationTest.php index 85bc0470..163ba2d4 100644 --- a/tests/Functional/Request/HeaderValidationTest.php +++ b/tests/Functional/Request/HeaderValidationTest.php @@ -343,10 +343,6 @@ public function header_array_type_with_comma_separated_string_passes(): void $this->assertSame('/test', $operation->path); } - /** - * A lone value is a one item list, not a scalar, so the schema it fails - * is `minItems` rather than `type`. - */ #[Test] public function header_array_type_with_single_value_throws_min_items(): void { diff --git a/tests/Functional/Request/MultipartUploadTest.php b/tests/Functional/Request/MultipartUploadTest.php index b6cbfdae..e2e870b8 100644 --- a/tests/Functional/Request/MultipartUploadTest.php +++ b/tests/Functional/Request/MultipartUploadTest.php @@ -10,7 +10,6 @@ use Duyler\OpenApi\Validator\Exception\MaxItemsError; use Duyler\OpenApi\Validator\Exception\MinItemsError; use Duyler\OpenApi\Validator\Exception\RequiredError; -use Duyler\OpenApi\Validator\Exception\TypeMismatchError; use Duyler\OpenApi\Validator\Exception\ValidationException; use Duyler\OpenApi\Validator\Operation; use Nyholm\Psr7\Factory\Psr17Factory; @@ -19,13 +18,6 @@ use PHPUnit\Framework\TestCase; use Psr\Http\Message\ServerRequestInterface; -/** - * RB-12: multipart/form-data file upload — characterization tests for the - * multipart body parser behaviour. The parser returns a list of parts - * (each with "headers" and "content" keys) which is why a spec schema - * must use type: array to accept multipart bodies, while type: object - * is always rejected with a TypeMismatchError. - */ final class MultipartUploadTest extends TestCase { private const string MULTIPART_ARRAY_SCHEMA_SPEC = <<<'YAML' diff --git a/tests/Functional/Request/PathParameterEdgeCasesTest.php b/tests/Functional/Request/PathParameterEdgeCasesTest.php index 75fc7dc0..e8efe9c1 100644 --- a/tests/Functional/Request/PathParameterEdgeCasesTest.php +++ b/tests/Functional/Request/PathParameterEdgeCasesTest.php @@ -805,23 +805,13 @@ public function ambiguous_paths_chosen_template_value_passes_own_const(): void $this->assertSame('/{type}/info', $operation->path); } - /** - * RP-05: Path consisting only of a parameter `/{id}` (no static segments). - * - * The template compiles to regex `#^/(?P[^/]+)$#`. A single-segment - * value like `/123` matches and the parameter is extracted as "123". - * - * The extracted value is observed through a `const: '123'` constraint: - * successful validation proves the parameter was extracted with the - * expected value. - */ #[Test] public function rp_05_param_only_root_path_matches_single_segment_value(): void { $yaml = <<assertSame('GET', $operation->method); } - /** - * RP-05 negative: `GET /` (root, no segment for the parameter). - * - * The compiled regex `#^/(?P[^/]+)$#` requires at least one - * non-slash character after the leading slash. An empty path value - * fails to match, and the top-level validator raises - * `OperationNotFoundException` ("Operation not found") because no - * candidate template matches. - */ #[Test] public function rp_05_param_only_root_path_rejects_empty_value(): void { $yaml = <<validateRequest($request); } - /** - * QP-02: Duplicate scalar keys `?a=1&a=2` — actual behavior is form-style - * implode, NOT PHP's pre-8.5 last-value-wins and NOT array form. - * - * QueryParser collects duplicate scalar pairs into an indexed array - * `['1', '2']` (see QueryParser::resolveGroup allScalar branch). Then - * ParameterDeserializer::deserializeForm with explode=false implodes - * the array to the comma-separated string "1,2". The resulting string - * validates against `type: string`. - * - * This test documents the value via a `const: '1,2'` constraint: - * successful validation proves the duplicate keys were collapsed to - * the string "1,2" (form-style), not "2" (last-value) and not the - * array ["1","2"]. - */ #[Test] public function qp_02_duplicate_scalar_keys_collapse_to_form_imploded_string(): void { $yaml = <<assertSame('GET', $operation->method); } - /** - * QP-02 negative: const='2' (last-value semantics) — confirms the - * validator does NOT use last-value-wins. The actual stored value is - * "1,2" (comma-joined), not "2". - */ #[Test] public function qp_02_duplicate_scalar_keys_do_not_use_last_value_semantics(): void { $yaml = <<params()['expected']); } - /** - * QP-02 negative: type=array with duplicate keys. The form-style - * implode collapses the array back to a string "1,2", which fails - * the `type: array` check with TypeMismatchError. - */ #[Test] public function qp_02_duplicate_scalar_keys_with_array_schema_throws_type_mismatch(): void { $yaml = <<params()['actual']); } - /** - * QP-04: `style: form` with comma-separated value `?color=black,white` - * against `type: array` — ParameterDeserializer::deserializeForm splits - * the string into the array ["black", "white"], which then validates - * against the array schema. - * - * The actual split into array form is observed through `items.enum`: - * each split value must be in `[black, white]`. Successful validation - * proves the comma-separated value was deserialized to a 2-element - * array. - */ #[Test] public function qp_04_form_style_comma_separated_value_splits_to_array(): void { $yaml = <<assertSame('GET', $operation->method); } - /** - * QP-04 negative: comma-separated value contains an item not in the - * items.enum — EnumError on the offending item at items index 1. - */ #[Test] public function qp_04_form_style_invalid_item_value_throws_enum_error(): void { $yaml = <<params()['actual']); } - /** - * QP-04 negative: `style: form` against `type: object`. - * - * ParameterDeserializer splits the comma-separated value to an indexed - * array ["black", "white"]. JSON Schema treats indexed arrays and - * objects as distinct types, so `type: object` rejects the array form - * with TypeMismatchError. - * - * This documents the actual implementation: form-style object - * serialization is not supported by the deserializer. - */ #[Test] public function qp_04_form_style_against_object_schema_throws_type_mismatch(): void { $yaml = <<getQuery()`. The - * QueryParser decodes both `%XX` sequences and `+` (plus sign) to - * space. This is verified by `const` constraints that match the - * decoded form, not the raw form. - * - * @param non-empty-string $rawQueryValue the raw value placed in the URL (already URL-encoded where needed) - * @param non-empty-string $expectedDecodedValue the value the validator should see after URL-decoding + * @param non-empty-string $rawQueryValue + * @param non-empty-string $expectedDecodedValue */ #[Test] #[DataProvider('provideSpecialCharacterCases')] @@ -1206,7 +1146,7 @@ public function qp_06_special_characters_in_query_value_url_decoded_correctly( $yaml = <<assertSame('GET', $operation->method); } - /** - * QP-06 negative: raw encoded value does NOT satisfy a const that - * matches the raw (encoded) form. The validator sees the decoded - * form only, so a const against the encoded form must fail. - * - * Uses `?q=hello%20world` (encoded space) against `const: 'hello%20world'` - * (literal percent-twenty-zero). ConstError actual='hello world' - * (decoded) vs expected='hello%20world' (raw). - */ #[Test] public function qp_06_url_encoded_value_does_not_match_raw_const(): void { $yaml = <<assertSame(['q' => $expectedValue], $result); } - /** - * QP-07: Brackets in keys without `style: deepObject` — `?arr[0]=a`. - * - * QueryParser uses a segment-based parser (insertNested + assignSegments) - * for bracket keys (resolveGroup allScalar=false branch), producing - * `['arr' => ['a']]`. For a schema with `type: string`, - * ParameterDeserializer::deserializeForm implodes the single-element - * array to "a", which satisfies the `const: 'a'` constraint. - * - * This documents the actual behavior: bracket notation without - * deepObject is parsed to array form, then collapsed by form-style - * implode when the schema type is string. - */ #[Test] public function qp_07_bracket_key_without_deep_object_collapses_to_string(): void { $yaml = <<assertSame('GET', $operation->method); } - /** - * QP-07 detail: multiple indexed brackets `?arr[0]=a&arr[1]=b` - * collapse to the form-imploded string "a,b" against a string schema. - */ #[Test] public function qp_07_multiple_bracket_keys_collapse_to_form_imploded_string(): void { $yaml = <<assertSame('/search', $operation->path); } - /** - * QP-07 negative: bracket keys against `type: array` schema. - * - * The form-style implode collapses the array back to a string, which - * fails the `type: array` check. To use bracket notation for array - * query parameters, the schema must use `style: deepObject` or the - * request must use bracket-explode syntax `?arr[]=a` (covered by - * `form_explode_*` tests above). - */ #[Test] public function qp_07_bracket_keys_with_array_schema_throws_type_mismatch(): void { $yaml = <<params()['actual']); } - /** - * QP-07 unit-level: QueryParser parses bracket keys via segment-based - * parser (insertNested + assignSegments), producing nested array - * structures. This complements the full-cycle test by verifying the - * parser behavior in isolation. - */ #[Test] public function qp_07_query_parser_bracket_key_produces_nested_array(): void { @@ -1455,10 +1349,6 @@ public function qp_07_query_parser_bracket_key_produces_nested_array(): void $this->assertSame(['arr' => ['a']], $result); } - /** - * A non-exploded `form` array parameter -- the JSON:API `include` shape -- - * accepts any number of items, including one and none. - */ #[Test] #[DataProvider('provideFormArrayItemCounts')] public function form_array_accepts_any_item_count(string $uri): void diff --git a/tests/Functional/Request/RequestBodyMediaTypeTest.php b/tests/Functional/Request/RequestBodyMediaTypeTest.php index 87bd3b05..e27b329f 100644 --- a/tests/Functional/Request/RequestBodyMediaTypeTest.php +++ b/tests/Functional/Request/RequestBodyMediaTypeTest.php @@ -18,14 +18,6 @@ use Psr\Http\Message\ServerRequestInterface; use JsonException; -/** - * RB-08: vendor-specific media type (application/vnd.api+json) — JSON:API body - * parsing and content negotiation. - * - * RB-09: optional request body (required: false) — verifies the validator does - * not raise MissingRequestBodyException when the spec marks the body as optional - * and the client sends an empty body. - */ final class RequestBodyMediaTypeTest extends TestCase { private const string VENDOR_MEDIA_TYPE_STRING_SCHEMA_SPEC = <<<'YAML' diff --git a/tests/Functional/Response/NullableCompositionTest.php b/tests/Functional/Response/NullableCompositionTest.php index ab3d0046..8ee4d089 100644 --- a/tests/Functional/Response/NullableCompositionTest.php +++ b/tests/Functional/Response/NullableCompositionTest.php @@ -11,11 +11,6 @@ use PHPUnit\Framework\TestCase; /** - * Regression coverage for a JSON:API-shaped OAS 3.0 document where the nullable relationship is - * expressed as `allOf: [$ref]` plus `nullable: true`, reached through a nested `properties` chain. - * - * @see https://github.com/duyler/openapi/issues/50 - * * @internal */ final class NullableCompositionTest extends TestCase diff --git a/tests/Functional/Response/ResponseContentTypeTest.php b/tests/Functional/Response/ResponseContentTypeTest.php index 88376a04..b37f0437 100644 --- a/tests/Functional/Response/ResponseContentTypeTest.php +++ b/tests/Functional/Response/ResponseContentTypeTest.php @@ -18,18 +18,6 @@ use function sprintf; -/** - * RB-20: response with a Content-Type that does not match any declared - * media type — the response body validator skips validation (fail-open, - * documented in README), so malformed JSON bodies sneak through silently. - * Matching negative tests confirm that validation DOES run when the - * Content-Type matches the spec. - * - * RB-22: response spec declaring multiple Content-Types with different - * schemas. Each Content-Type is validated against its own schema. Unknown - * Content-Types silently skip validation (no UnsupportedMediaTypeException - * on the response side, in contrast to the request side). - */ final class ResponseContentTypeTest extends TestCase { private const string JSON_RESPONSE_SPEC = <<<'YAML' diff --git a/tests/Functional/Response/StatusCodeEdgeCasesTest.php b/tests/Functional/Response/StatusCodeEdgeCasesTest.php index 8e4c2f34..ec956880 100644 --- a/tests/Functional/Response/StatusCodeEdgeCasesTest.php +++ b/tests/Functional/Response/StatusCodeEdgeCasesTest.php @@ -13,12 +13,6 @@ use function sprintf; -/** - * Edge cases for response status code validation (SC-01, SC-02, SC-04, SC-05). - * - * Covers non-standard status codes (0, 999), range-based responses (1XX, 3XX) - * and fully out-of-range codes (6XX-9XX) that the spec does not declare. - */ final class StatusCodeEdgeCasesTest extends TestCase { private const string STANDARD_SPEC = <<<'YAML' @@ -78,12 +72,6 @@ protected function setUp(): void $this->psrFactory = new Psr17Factory(); } - /** - * SC-01: Status code 0 is non-standard and not declared in the spec. - * The Nyholm Response constructor permits status 0 (only withStatus() - * enforces the 100..599 range), so the validator receives 0 and must - * reject it because no "0XX" range is defined. - */ #[Test] public function status_code_zero_throws_undefined_response_exception(): void { @@ -108,10 +96,6 @@ public function status_code_zero_throws_undefined_response_exception(): void } } - /** - * SC-02: Status code 999 exceeds the standard HTTP range and is not - * declared in the spec, so the validator must reject it. - */ #[Test] public function status_code_999_throws_undefined_response_exception(): void { @@ -136,9 +120,6 @@ public function status_code_999_throws_undefined_response_exception(): void } } - /** - * SC-04 (positive): Status 102 falls under the declared 1XX range. - */ #[Test] public function status_code_102_matches_declared_1xx_range(): void { @@ -158,9 +139,6 @@ public function status_code_102_matches_declared_1xx_range(): void self::assertSame(102, $response->getStatusCode()); } - /** - * SC-04 (positive): Status 301 falls under the declared 3XX range. - */ #[Test] public function status_code_301_matches_declared_3xx_range(): void { @@ -180,10 +158,6 @@ public function status_code_301_matches_declared_3xx_range(): void self::assertSame(301, $response->getStatusCode()); } - /** - * SC-04 (negative): Status 200 is not covered by the RANGES_SPEC - * (only 1XX and 3XX are declared), so it must be rejected. - */ #[Test] public function status_code_200_not_covered_by_ranges_throws_exception(): void { @@ -204,9 +178,6 @@ public function status_code_200_not_covered_by_ranges_throws_exception(): void } /** - * SC-05: Fully out-of-range HTTP status codes (6XX-9XX) must be rejected - * when the spec only declares standard codes. - * * @return iterable */ public static function nonStandardStatusCodesProvider(): iterable @@ -227,9 +198,6 @@ public static function nonStandardStatusCodesProvider(): iterable } /** - * SC-05: 6XX-9XX codes are not part of any standard HTTP range. - * The spec declares only "200", so all of these must throw. - * * @dataProvider nonStandardStatusCodesProvider */ #[Test] @@ -259,12 +227,6 @@ public function non_standard_status_code_in_6xx_to_9xx_range_throws_exception(in } } - /** - * SC-05 (positive): The 6XX range works as a declared range. When the - * spec explicitly declares "6XX", status 600 must pass validation. - * This documents that the validator itself does not blacklist 6XX-9XX; - * rejection happens only because the spec did not declare them. - */ #[Test] public function status_code_600_passes_when_6xx_range_is_declared(): void { diff --git a/tests/Functional/Schema/CompositionBranchErrorsTest.php b/tests/Functional/Schema/CompositionBranchErrorsTest.php index fb59449e..b7c69a9c 100644 --- a/tests/Functional/Schema/CompositionBranchErrorsTest.php +++ b/tests/Functional/Schema/CompositionBranchErrorsTest.php @@ -9,7 +9,6 @@ use Duyler\OpenApi\Validator\Exception\ValidationException; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Duyler\OpenApi\Validator\Schema\OneOfValidatorWithContext; use function array_map; use function array_unique; @@ -121,12 +120,6 @@ public function all_of_counts_every_failing_branch(): void $this->assertNoDuplicates($exception); } - /** - * `oneOf` is deliberately excluded: it is dispatched to - * {@see OneOfValidatorWithContext}, which evaluates - * keyword groups in a different order, so it surfaces a different — but equally - * valid — violation of the same branch. See the "Related observation" in #52. - */ #[Test] public function all_of_and_any_of_report_the_same_errors_for_the_same_failing_branch(): void { diff --git a/tests/Functional/Schema/CompositionBranchOrderTest.php b/tests/Functional/Schema/CompositionBranchOrderTest.php index 24cb0f1c..4758dec1 100644 --- a/tests/Functional/Schema/CompositionBranchOrderTest.php +++ b/tests/Functional/Schema/CompositionBranchOrderTest.php @@ -15,16 +15,6 @@ use function array_filter; /** - * Regression for issue #54, driven through the public builder path with the - * shape that surfaced it in the wild: a JSON:API `included` array whose items - * are an anyOf over allOf-composed resource schemas. - * - * Each non-matching resource branch emits ~12 errors (a `type` enum miss plus - * an `additionalProperties: false` attribute object), so two branches ahead of - * the matching one exceed MAX_COMPOSITION_ERRORS. Before the fix the cap - * returned out of the branch loop, so `MatchingLast` failed while the - * identical `MatchingFirst` branch set passed. - * * @internal */ #[CoversClass(OpenApiValidatorBuilder::class)] @@ -144,8 +134,6 @@ private function validator(): OpenApiValidatorInterface } /** - * A single `flows` resource: matches the Flow schema and nothing else. - * * @return array> */ private function included(): array diff --git a/tests/Functional/Schema/Parser/JsonParserTest.php b/tests/Functional/Schema/Parser/JsonParserTest.php index eb5084e9..4b0f18fc 100644 --- a/tests/Functional/Schema/Parser/JsonParserTest.php +++ b/tests/Functional/Schema/Parser/JsonParserTest.php @@ -451,23 +451,18 @@ public function parse_with_components_schemas(): void #[Test] public function parse_rejects_json_spec_exceeding_default_size_cap(): void { - // Given: default JsonParser (1 MB cap) and an oversized payload. $parser = new JsonParser(); $oversized = str_repeat(' ', JsonParser::DEFAULT_MAX_SPEC_BYTES + 1); - // Then: size-cap violation surfaces with both bounds in the message. $this->expectException(SpecTooLargeException::class); $this->expectExceptionMessage((string) JsonParser::DEFAULT_MAX_SPEC_BYTES); - // When: parse attempts to consume the payload. $parser->parse($oversized); } #[Test] public function parse_accepts_json_spec_at_exact_default_size_cap(): void { - // Given: default JsonParser and a valid JSON padded with whitespace - // so strlen equals the cap exactly (boundary case). $parser = new JsonParser(); $payload = '{"openapi": "3.0.3", "info": {"title": "T", "version": "1.0.0"}, "paths": {}}'; $padding = str_repeat(' ', JsonParser::DEFAULT_MAX_SPEC_BYTES - strlen($payload)); @@ -475,32 +470,26 @@ public function parse_accepts_json_spec_at_exact_default_size_cap(): void $this->assertSame(JsonParser::DEFAULT_MAX_SPEC_BYTES, strlen($content)); - // When: parse runs against the boundary-sized content. $document = $parser->parse($content); - // Then: parsing succeeds and the document is constructed. $this->assertSame('3.0.3', $document->openapi); } #[Test] public function parse_rejects_json_spec_exceeding_custom_size_cap(): void { - // Given: JsonParser with a tight custom cap and an oversized payload. $parser = new JsonParser(maxSpecBytes: 100); $oversized = str_repeat(' ', 101); - // Then: the custom cap value appears in the rejection message. $this->expectException(SpecTooLargeException::class); $this->expectExceptionMessage('100'); - // When: parse attempts to consume the oversized payload. $parser->parse($oversized); } #[Test] public function parse_size_cap_does_not_affect_smaller_specs(): void { - // Given: default JsonParser and a small valid OpenAPI document. $parser = new JsonParser(); $json = <<<'JSON' { @@ -510,10 +499,8 @@ public function parse_size_cap_does_not_affect_smaller_specs(): void } JSON; - // When: parse runs against the small document. $document = $parser->parse($json); - // Then: the document is constructed without a size-cap exception. $this->assertSame('3.0.3', $document->openapi); $this->assertSame('Small API', $document->info->title); } @@ -521,32 +508,22 @@ public function parse_size_cap_does_not_affect_smaller_specs(): void #[Test] public function parse_size_cap_throws_before_decode_for_oversized_invalid_json(): void { - // Given: JsonParser with a tight custom cap and a payload that is - // both oversized AND invalid JSON. Size check must win so the - // attacker never reaches json_decode (which would throw JsonException). $parser = new JsonParser(maxSpecBytes: 100); $oversized = str_repeat('x', 10_000); - // Then: SpecTooLargeException (not JsonException / InvalidSchemaException). $this->expectException(SpecTooLargeException::class); - // When: parse attempts to consume the oversized invalid payload. $parser->parse($oversized); } #[Test] public function parse_size_cap_via_builder_with_max_spec_size(): void { - // Given: a JSON spec loaded via the builder with a tiny size cap - // and an oversized JSON payload that would otherwise parse. $json = '{"openapi": "3.0.3", "info": {"title": "T", "version": "1.0.0"}, "paths": {}}'; $oversized = str_repeat(' ', 101) . $json; - // Then: the builder surfaces the size-cap exception at build time. $this->expectException(SpecTooLargeException::class); - // When: build triggers parseSpec which constructs the JsonParser - // with the configured maxSpecSizeBytes. OpenApiValidatorBuilder::create() ->fromJsonString($oversized) ->withMaxSpecSize(100) diff --git a/tests/Functional/Schema/RefResolutionInCompositionTest.php b/tests/Functional/Schema/RefResolutionInCompositionTest.php index ee0e1751..4d4fd0fc 100644 --- a/tests/Functional/Schema/RefResolutionInCompositionTest.php +++ b/tests/Functional/Schema/RefResolutionInCompositionTest.php @@ -17,14 +17,6 @@ use function sprintf; /** - * Covers $ref resolution inside allOf/oneOf/anyOf subschemas. - * - * Before bugfix-from-testing/10, stateless composition validators created - * a stateless SchemaValidator without document context, so subschemas that - * used $ref silently passed — constraints from the referenced schema were - * never enforced. These tests verify that $ref is now pre-resolved in - * composition arrays so that the stateless validators see real constraints. - * * @internal */ #[CoversClass(OpenApiValidatorBuilder::class)] diff --git a/tests/Functional/Validator/Callback/CallbackValidatorTest.php b/tests/Functional/Validator/Callback/CallbackValidatorTest.php index 6dc83375..97bd5fd2 100644 --- a/tests/Functional/Validator/Callback/CallbackValidatorTest.php +++ b/tests/Functional/Validator/Callback/CallbackValidatorTest.php @@ -35,11 +35,6 @@ protected function setUp(): void $requestValidator = $this->createStub(RequestValidatorInterface::class); $requestValidator->method('validate'); - // Lax mode is opted into explicitly: the historical tests in this - // file exercise the routing/matching/resolution logic of the - // inner validator with runtime-template expressions treated as - // wildcards. Strict-mode defaults are covered separately by - // inner_constructor_defaults_to_strict_when_called_without_flag. $this->callbackValidator = new CallbackValidator( $requestValidator, new PathRegexCache(), @@ -54,8 +49,6 @@ public function inner_constructor_defaults_to_strict_when_called_without_flag(): $requestValidator = $this->createStub(RequestValidatorInterface::class); $requestValidator->method('validate'); - // Arrange: omit the third argument — the constructor must default - // to strict (fail-closed) to match OpenApiValidatorBuilder. $validator = new CallbackValidator( $requestValidator, new PathRegexCache(), @@ -73,7 +66,6 @@ public function inner_constructor_defaults_to_strict_when_called_without_flag(): $this->expectException(UnresolvableCallbackPathException::class); $this->expectExceptionMessage('{$request.body#/callback_url}'); - // Act + Assert: strict default throws on the runtime template. $validator->validate($request, 'myCallback', $document); } @@ -83,7 +75,6 @@ public function inner_constructor_allows_lax_when_strict_false_passed_explicitly $requestValidator = $this->createStub(RequestValidatorInterface::class); $requestValidator->method('validate'); - // Arrange: explicit opt-out of strict mode — legacy wildcard behaviour. $validator = new CallbackValidator( $requestValidator, new PathRegexCache(), @@ -99,10 +90,8 @@ public function inner_constructor_allows_lax_when_strict_false_passed_explicitly $request = $this->psrFactory->createServerRequest('POST', '/attacker-controlled-url'); - // Act: legacy wildcard accepts any path. $resolved = $validator->validate($request, 'myCallback', $document); - // Assert: runtime template falls through to wildcard match. $this->assertSame('myCallback', $resolved->operationId); } diff --git a/tests/Functional/Validator/PathFinderAccumulatorTest.php b/tests/Functional/Validator/PathFinderAccumulatorTest.php index 1e33f5ed..bb6d6a14 100644 --- a/tests/Functional/Validator/PathFinderAccumulatorTest.php +++ b/tests/Functional/Validator/PathFinderAccumulatorTest.php @@ -19,13 +19,6 @@ /** * @internal - * - * Anti-test for the §7 migration of the P-043 contract: TrieLookup::lookupTrie - * keeps its void return (no intermediate per-level arrays) and accumulates - * matches through a by-object TrieMatches accumulator instead of the former - * by-reference array parameter. Reverting lookupTrie to the spread-merge - * form (returns array) or reintroducing the by-reference array parameter - * breaks these reflection assertions. */ final class PathFinderAccumulatorTest extends TestCase { @@ -68,7 +61,7 @@ public function lookup_trie_accumulates_into_by_object_state(): void self::assertSame( 'void', $lookupTrie->getReturnType()?->getName(), - 'lookupTrie must return void (P-043): no intermediate arrays', + 'lookupTrie must return void: no intermediate arrays', ); $parameters = $lookupTrie->getParameters(); @@ -77,7 +70,7 @@ public function lookup_trie_accumulates_into_by_object_state(): void $accumulator = $parameters[3]; self::assertFalse( $accumulator->isPassedByReference(), - 'Fourth parameter of lookupTrie must be a by-object accumulator, not by-reference (§7)', + 'Fourth parameter of lookupTrie must be a by-object accumulator, not by-reference', ); $type = $accumulator->getType(); @@ -110,7 +103,7 @@ public function max_trie_depth_constant_exists(): void self::assertTrue( new ReflectionClass(TrieLookup::class)->hasConstant('MAX_TRIE_DEPTH'), - 'TrieLookup must define a MAX_TRIE_DEPTH guard constant (P-043)', + 'TrieLookup must define a MAX_TRIE_DEPTH guard constant', ); } diff --git a/tests/Functional/Validator/Response/ResponseHeadersValidatorContextTest.php b/tests/Functional/Validator/Response/ResponseHeadersValidatorContextTest.php index eed66fbe..ab92c1cc 100644 --- a/tests/Functional/Validator/Response/ResponseHeadersValidatorContextTest.php +++ b/tests/Functional/Validator/Response/ResponseHeadersValidatorContextTest.php @@ -102,13 +102,6 @@ public function allow_both_strategy_accepts_empty_header_for_array_schema(): voi $this->expectNotToPerformAssertions(); } - /** - * ResponseHeadersValidator::coerceValue coerces an empty header value - * into an empty array when the schema type is "object", which lets - * EmptyArrayStrategy::PreferObject treat the empty array as an empty - * object. Therefore PreferObject + empty header value + {type: object} - * is accepted end-to-end. - */ #[Test] public function prefer_object_strategy_empty_header_object_is_supported_by_coerce_value(): void { diff --git a/tests/Functional/Validator/Schema/JsonEqualsTest.php b/tests/Functional/Validator/Schema/JsonEqualsTest.php index 6e7500df..85d13fee 100644 --- a/tests/Functional/Validator/Schema/JsonEqualsTest.php +++ b/tests/Functional/Validator/Schema/JsonEqualsTest.php @@ -22,8 +22,6 @@ #[CoversClass(JsonEquals::class)] final class JsonEqualsTest extends TestCase { - // ---- Original tests retained / adjusted ---- - #[Test] public function equals_int_and_float_with_same_math_value(): void { @@ -96,25 +94,12 @@ public function equals_identical_arrays(): void self::assertTrue(JsonEquals::equals([1, 2, 3], [1, 2, 3])); } - /** - * JSON Schema 2020-12 §4.2.2: int 1 and float 1.0 are mathematically - * equal, so lists that differ only in scalar numeric representation - * MUST be equal. The previous implementation returned false here because - * PHP's `===` treats 1 and 1.0 as distinct types. - */ #[Test] public function equals_arrays_with_equivalent_numeric_representation(): void { self::assertTrue(JsonEquals::equals([1], [1.0])); } - // ---- SPEC-05: int64 precision ---- - - /** - * SPEC-05: casting distinct int64 values to float collapses them — - * 9223372036854775806 and 9223372036854775807 both round to - * 9.223372036854776E+18. JSON Schema treats them as distinct numbers. - */ #[Test] public function int64_equality_preserves_precision(): void { @@ -133,12 +118,6 @@ public function int64_neg_max_distinct_from_pos_max(): void self::assertFalse(JsonEquals::equals(-9223372036854775807 - 1, PHP_INT_MAX)); } - /** - * PHP_INT_MAX-FLOAT-BOUNDARY: `(float) PHP_INT_MAX` rounds to - * 9223372036854775808.0 (= PHP_INT_MAX + 1), so naive float equality - * would silently collapse two mathematically distinct values. The - * safe-integer-range guard rejects the comparison as false instead. - */ #[Test] public function equals_rejects_int64_max_and_float_int64_max(): void { @@ -175,8 +154,6 @@ public function equals_int_vs_int_unchanged_for_int64_max(): void self::assertTrue(JsonEquals::equals(PHP_INT_MAX, PHP_INT_MAX)); } - // ---- SPEC-04: bool vs int ---- - #[Test] public function bool_true_not_equal_int_1(): void { @@ -207,8 +184,6 @@ public function bool_distinct_values_not_equal(): void self::assertFalse(JsonEquals::equals(true, false)); } - // ---- SPEC-03: object order independence ---- - #[Test] public function object_order_independent(): void { @@ -277,12 +252,6 @@ public function list_with_different_length_not_equal(): void self::assertFalse(JsonEquals::equals([1, 2], [1, 2, 3])); } - // ---- Integration: uniqueItems / const / enum ---- - - /** - * SPEC-05 integration: `[PHP_INT_MAX - 1, PHP_INT_MAX]` MUST NOT trigger - * a false-positive DuplicateItemsError under `uniqueItems: true`. - */ #[Test] public function unique_items_int64_no_false_duplicate(): void { @@ -298,10 +267,6 @@ public function unique_items_int64_no_false_duplicate(): void $this->expectNotToPerformAssertions(); } - /** - * SPEC-03 integration: `const: {b: 2, a: 1}` MUST accept `{a: 1, b: 2}` - * (object key order independence). - */ #[Test] public function const_object_order_independent(): void { @@ -314,9 +279,6 @@ public function const_object_order_independent(): void $this->expectNotToPerformAssertions(); } - /** - * SPEC-03 integration: `enum: [{b: 2, a: 1}]` MUST accept `{a: 1, b: 2}`. - */ #[Test] public function enum_object_order_independent(): void { @@ -329,9 +291,6 @@ public function enum_object_order_independent(): void $this->expectNotToPerformAssertions(); } - /** - * SPEC-04 integration: `const: true` MUST reject int 1. - */ #[Test] public function const_bool_true_rejects_int_one(): void { @@ -352,10 +311,6 @@ public function const_bool_true_rejects_int_one(): void } } - /** - * SPEC-05 integration: `enum: [PHP_INT_MAX - 1, PHP_INT_MAX]` MUST accept - * `PHP_INT_MAX` and MUST reject `PHP_INT_MAX - 2`. - */ #[Test] public function enum_int64_lookup_matches_correct_value(): void { @@ -363,7 +318,6 @@ public function enum_int64_lookup_matches_correct_value(): void ->fromJsonString($this->specWithEnum([9223372036854775806, 9223372036854775807])) ->build(); - // Positive match — exact int64 value present in enum. $validator->validateSchema(9223372036854775807, '#/components/schemas/Enum'); $this->expectNotToPerformAssertions(); diff --git a/tests/Functional/Validator/SchemaValidator/NullableCompositionTest.php b/tests/Functional/Validator/SchemaValidator/NullableCompositionTest.php index 1ab8807b..a4936174 100644 --- a/tests/Functional/Validator/SchemaValidator/NullableCompositionTest.php +++ b/tests/Functional/Validator/SchemaValidator/NullableCompositionTest.php @@ -12,10 +12,6 @@ use PHPUnit\Framework\TestCase; /** - * OAS 3.0 has no way to attach `nullable` to a `$ref`, so the documented workaround is to - * wrap the reference in a single-branch composition and put `nullable: true` beside it. - * The keyword sits on the parent, not on the branch, and must be honored there. - * * @internal */ final class NullableCompositionTest extends TestCase @@ -255,11 +251,6 @@ public function oas_31_null_type_union_is_honored_inside_and_outside_composition $this->expectNotToPerformAssertions(); } - /** - * A `null` member of a `type` union is ordinary JSON Schema and keeps composing: `allOf` - * branches still have to match. Only OAS `nullable: true` — which the spec defines as - * "allows sending a null value for the defined schema" — waives them. - */ #[Test] public function oas_31_null_type_union_on_parent_does_not_waive_composition_branches(): void { diff --git a/tests/Functional/Validator/Validation/CallbackValidatorTest.php b/tests/Functional/Validator/Validation/CallbackValidatorTest.php index a3b42f5e..fc1159b2 100644 --- a/tests/Functional/Validator/Validation/CallbackValidatorTest.php +++ b/tests/Functional/Validator/Validation/CallbackValidatorTest.php @@ -42,17 +42,6 @@ protected function setUp(): void $this->psrFactory = new Psr17Factory(); } - /** - * Anti-test guard: build the outer validator without the third - * constructor argument. The constructor must default to strict - * (fail-closed) so that direct-instantiation callers — frameworks that - * use this library as a dependency and bypass OpenApiValidatorBuilder — - * receive the same SSRF protection as builder callers. To verify, - * temporarily revert the default in Validation\CallbackValidator - * from `= true` back to `= false` and re-run this test — it must fail - * because the validator would resolve the runtime expression as a - * wildcard instead of throwing. - */ #[Test] public function outer_constructor_defaults_to_strict_when_called_without_flag(): void { diff --git a/tests/Functional/Validator/Validation/Internal/ValidationGroupTest.php b/tests/Functional/Validator/Validation/Internal/ValidationGroupTest.php index a46104cd..ab218f5c 100644 --- a/tests/Functional/Validator/Validation/Internal/ValidationGroupTest.php +++ b/tests/Functional/Validator/Validation/Internal/ValidationGroupTest.php @@ -68,19 +68,16 @@ public function from_group_builds_dependencies_with_defaults(): void self::assertSame($group->root->formatRegistry, $deps->formatRegistry); self::assertSame($group->root->errorFormatter, $deps->errorFormatter); self::assertSame($group->root->refResolver, $deps->refResolver); - // Defaults from ValidatorOptions self::assertFalse($deps->coercion); self::assertTrue($deps->nullableAsType); self::assertSame(EmptyArrayStrategy::AllowBoth, $deps->emptyArrayStrategy); self::assertFalse($deps->reportDeprecated); self::assertFalse($deps->strictFormats); self::assertTrue($deps->strictCoercion); - // Defaults from BodyLimits self::assertSame(ValidatorConfiguration::DEFAULT_MAX_JSON_BODY_BYTES, $deps->maxJsonBodyBytes); self::assertSame(ValidatorConfiguration::DEFAULT_MAX_MULTIPART_BODY_BYTES, $deps->maxMultipartBodyBytes); self::assertSame(PregExecutor::DEFAULT_MAX_BACKTRACKS, $deps->maxRegexBacktracks); self::assertSame(ValidatorConfiguration::DEFAULT_MAX_STREAMING_RECORDS, $deps->maxStreamingRecords); - // Wired sub-services self::assertNotNull($deps->requestValidator); self::assertNotNull($deps->responseValidator); self::assertNotNull($deps->schemaValidatorWithContext); @@ -156,7 +153,6 @@ public function validator_options_to_configuration_round_trip(): void self::assertTrue($config->strictStreaming); self::assertFalse($config->strictCoercion); self::assertSame(7, $config->maxStreamingRecords); - // BodyLimits default through ValidatorConfiguration::DEFAULT_* constants self::assertSame(ValidatorConfiguration::DEFAULT_MAX_JSON_BODY_BYTES, $config->maxJsonBodyBytes); self::assertSame(ValidatorConfiguration::DEFAULT_MAX_MULTIPART_BODY_BYTES, $config->maxMultipartBodyBytes); } @@ -174,7 +170,6 @@ public function root_services_defaults_propagate(): void refResolver: new RefResolver(), ); - // Defaults are wired self::assertInstanceOf(PathRegexCache::class, $root->pathRegexCache); self::assertInstanceOf(RegexValidator::class, $root->regexValidator); self::assertInstanceOf(PregExecutor::class, $root->pregExecutor); diff --git a/tests/Integration/Builder/ExternalRefAllowedRootTest.php b/tests/Integration/Builder/ExternalRefAllowedRootTest.php index 49ec8282..5dee76cd 100644 --- a/tests/Integration/Builder/ExternalRefAllowedRootTest.php +++ b/tests/Integration/Builder/ExternalRefAllowedRootTest.php @@ -30,12 +30,6 @@ use const DIRECTORY_SEPARATOR; /** - * SEC-03: external file:// $ref references loaded through the builder - * must be confined to a real directory by default. The builder - * auto-derives allowedRoot from the spec file's realpath dirname so - * that a trusted spec cannot read arbitrary files such as - * /etc/passwd or composer.json via a crafted $ref. - * * @internal */ final class ExternalRefAllowedRootTest extends TestCase @@ -60,13 +54,6 @@ protected function tearDown(): void $this->removeDirectory($this->outsideDir); } - /** - * Default behaviour: fromYamlFile auto-derives allowedRoot from - * dirname(realpath($path)). An external $ref inside the spec - * directory resolves; an external $ref pointing outside is rejected - * with ExternalRefSecurityException (surfaced by RefResolver as - * UnresolvableRefException with the original exception as previous). - */ #[Test] public function from_yaml_file_sets_default_allowed_root(): void { @@ -98,7 +85,7 @@ public function from_yaml_file_sets_default_allowed_root(): void <<<'YAML' openapi: 3.2.0 info: - title: SEC-03 default root + title: default root version: 1.0.0 paths: {} components: @@ -130,11 +117,6 @@ public function from_yaml_file_sets_default_allowed_root(): void ); } - /** - * withExternalRefAllowedRoot explicitly overrides the auto-derived - * default. The user's choice wins; the spec directory is no longer - * the boundary. - */ #[Test] public function with_external_ref_allowed_root_overrides_default(): void { @@ -169,7 +151,7 @@ public function with_external_ref_allowed_root_overrides_default(): void <<<'YAML' openapi: 3.2.0 info: - title: SEC-03 override + title: override version: 1.0.0 paths: {} components: @@ -208,11 +190,6 @@ public function with_external_ref_allowed_root_overrides_default(): void } } - /** - * withExternalRefAllowedRoot must fail fast with a BuilderException - * when the supplied directory does not exist on disk, instead of - * silently allowing every path (the legacy null behaviour). - */ #[Test] public function with_external_ref_allowed_root_throws_when_path_missing(): void { @@ -224,12 +201,6 @@ public function with_external_ref_allowed_root_throws_when_path_missing(): void ->withExternalRefAllowedRoot('/nonexistent/sec03/path-' . uniqid('', true)); } - /** - * fromYamlFile must throw BuilderException at call time (not at - * build()) when the spec file does not exist. This surfaces the - * realpath failure before the auto-derived allowedRoot would be - * computed from a non-existent path. - */ #[Test] public function from_yaml_file_throws_when_spec_missing(): void { @@ -240,13 +211,6 @@ public function from_yaml_file_throws_when_spec_missing(): void ->fromYamlFile('/nonexistent/sec03/spec-' . uniqid('', true) . '.yaml'); } - /** - * BC: directly constructing RefResolver without a builder keeps - * the legacy behaviour where allowedRoot is null and the - * path-traversal check is disabled. This is the documented escape - * hatch and must remain working. Direct usage is dangerous and - * discouraged for trusted specs. - */ #[Test] public function explicit_null_allowed_root_disables_check_for_direct_resolver_usage(): void { @@ -267,11 +231,6 @@ public function explicit_null_allowed_root_disables_check_for_direct_resolver_us ); } - /** - * BC: RefResolver accepts an explicit FileExternalRefResolver and - * uses it as the builtin resolver. The builder relies on this - * constructor parameter to inject allowedRoot. - */ #[Test] public function ref_resolver_accepts_injected_builtin_file_resolver(): void { diff --git a/tests/Integration/Builder/OpenApiValidatorBuilderTest.php b/tests/Integration/Builder/OpenApiValidatorBuilderTest.php index de527ee5..b4698e73 100644 --- a/tests/Integration/Builder/OpenApiValidatorBuilderTest.php +++ b/tests/Integration/Builder/OpenApiValidatorBuilderTest.php @@ -675,7 +675,6 @@ public function with_detailed_errors_chains_before_with_error_formatter(): void { $yaml = "openapi: 3.0.3\ninfo:\n title: Test\n version: 1.0.0\npaths: []"; - // Per Oracle correction: withErrorFormatter wins when called after withDetailedErrors. $custom = new DetailedFormatter(); $validator = OpenApiValidatorBuilder::create() diff --git a/tests/Integration/Cache/FileSpecUpdateTest.php b/tests/Integration/Cache/FileSpecUpdateTest.php index bfa9acbf..fc6a30f5 100644 --- a/tests/Integration/Cache/FileSpecUpdateTest.php +++ b/tests/Integration/Cache/FileSpecUpdateTest.php @@ -34,16 +34,6 @@ use const JSON_THROW_ON_ERROR; /** - * P-098: cache invalidation on spec update. The validator keys its PSR-6 - * cache entry on sha256(realpath + mtime + size); a file modification that - * changes either dimension must produce a fresh cache key so the rebuilt - * validator picks up the new spec rather than serving the stale document. - * - * Each test writes a unique on-disk temp file so parallel PHPUnit workers - * do not race on a shared fixture path. The in-memory PSR-6 pool stub - * records every key it has seen so the test can assert that the second - * build hit a different cache key. - * * @internal */ final class FileSpecUpdateTest extends TestCase @@ -104,13 +94,9 @@ public function rebuild_picks_up_updated_spec_after_file_change(): void $firstOperation = $validatorV1->validateRequest($shortBody); self::assertSame('POST', $firstOperation->method); - // Bump minLength and rewrite the file with a different byte length - // so the cache key (which incorporates size) changes deterministically - // without depending on filesystem mtime granularity. $oldContents = (string) file_get_contents($tempPath); file_put_contents($tempPath, str_replace('minLength: 1', 'minLength: 50', $oldContents)); clearstatcache(true, $tempPath); - // Force a 1-second mtime bump for filesystems with 1-second mtime granularity. touch($tempPath, time() + 1); $validatorV2 = OpenApiValidatorBuilder::create() @@ -159,12 +145,8 @@ public function cache_miss_when_spec_hash_changes(): void ->withCache($cache) ->build(); - // Pad the spec with a trailing comment so size (and therefore the - // derived hash) changes deterministically regardless of mtime. file_put_contents($tempPath, (string) file_get_contents($tempPath) . "\n# cache-bust-v2\n"); clearstatcache(true, $tempPath); - // Force a 1-second mtime bump so filemtime() returns a different - // value on file systems with 1-second mtime granularity. touch($tempPath, time() + 1); OpenApiValidatorBuilder::create() @@ -186,14 +168,6 @@ public function cache_miss_when_spec_hash_changes(): void unlink($tempPath); } - /** - * R3-SEC-003 / S-003 reproducer: two specs that share byte-for-byte - * identical size AND an attacker-controlled identical mtime (via - * `touch -r`) but differ in content must produce different cache keys. - * A metadata-only key (path + mtime + size) collapses to the same - * digest and silently serves a cache-poisoned document. The content - * hash fix defeats this attack (OWASP ASVS V8.1.3, CWE-349, CWE-1023). - */ #[Test] public function rebuild_detects_spec_change_when_size_and_mtime_preserved(): void { @@ -208,21 +182,14 @@ public function rebuild_detects_spec_change_when_size_and_mtime_preserved(): voi ->withCache($cache) ->build(); - // Capture v1 mtime so v2 can be mtime-aligned with it (this is the - // `touch -r` step from the S-003 attack timeline). $v1Mtime = filemtime($tempPath); self::assertNotFalse($v1Mtime); $v1Size = filesize($tempPath); self::assertNotFalse($v1Size); - // Overwrite with a semantically different spec (minLength: 50 vs 99) - // that is byte-for-byte identical in length: both digits occupy the - // same character slot, so size is unchanged. This is the size- - // preserving spec tampering step from the S-003 attack timeline. file_put_contents($tempPath, $this->renderSpec(99)); clearstatcache(true, $tempPath); - // Restore the original mtime to defeat metadata-only cache keys. touch($tempPath, $v1Mtime); clearstatcache(true, $tempPath); @@ -231,12 +198,12 @@ public function rebuild_detects_spec_change_when_size_and_mtime_preserved(): voi self::assertSame( $v1Size, $v2Size, - 'Test precondition: v1 and v2 must be byte-for-byte identical in size (S-003 attack assumes size preservation).', + 'Test precondition: v1 and v2 must be byte-for-byte identical in size (attack assumes size preservation).', ); self::assertSame( $v1Mtime, filemtime($tempPath), - 'Test precondition: v1 and v2 must share an identical mtime (S-003 attack assumes mtime preservation via touch -r).', + 'Test precondition: v1 and v2 must share an identical mtime (attack assumes mtime preservation via touch -r).', ); OpenApiValidatorBuilder::create() @@ -248,13 +215,9 @@ public function rebuild_detects_spec_change_when_size_and_mtime_preserved(): voi self::assertGreaterThanOrEqual( 2, count($uniqueKeys), - 'Spec content change must produce a different cache key even when size and mtime are preserved (S-003 cache-poisoning defence, R3-SEC-003).', + 'Spec content change must produce a different cache key even when size and mtime are preserved (cache-poisoning defence).', ); - // Verify semantic difference: minLength 50 (v1) accepts a 70-char - // name, minLength 99 (v2) rejects it. The cached document must NOT - // be returned for the v2 build (cache-miss by content-hash), so the - // v2 validator enforces the v2 contract. $validatorV2 = OpenApiValidatorBuilder::create() ->fromYamlFile($tempPath) ->withCache($cache) @@ -276,15 +239,12 @@ public function rebuild_detects_spec_change_when_size_and_mtime_preserved(): voi self::assertTrue( $rejected, - 'minLength: 99 (v2) must reject a 70-char name. A cache-hit returning the v1 document (minLength: 50) is a cache-poisoning breach (S-003).', + 'minLength: 99 (v2) must reject a 70-char name. A cache-hit returning the v1 document (minLength: 50) is a cache-poisoning breach.', ); unlink($tempPath); } - /** - * Write a unique temp spec file and return its absolute path. - */ private function createTempSpec(int $minLength): string { $path = sys_get_temp_dir() . '/duyler-spec-' . uniqid(more_entropy: true) . '.yaml'; @@ -299,11 +259,8 @@ private function renderSpec(int $minLength): string } /** - * Build a PSR-6 pool that records every requested key into $requestedKeys - * and backs the cache with the shared $storage reference. - * * @param array $storage - * @param list $requestedKeys + * @param list $requestedKeys */ private function buildRecordingPool(array &$storage, array &$requestedKeys): CacheItemPoolInterface { diff --git a/tests/Integration/Cache/StringSpecConfinementCacheTest.php b/tests/Integration/Cache/StringSpecConfinementCacheTest.php index a75dc9a7..b7012ea4 100644 --- a/tests/Integration/Cache/StringSpecConfinementCacheTest.php +++ b/tests/Integration/Cache/StringSpecConfinementCacheTest.php @@ -16,11 +16,6 @@ use function strlen; /** - * End-to-end reproduction of issue #68: fromYamlString() + SchemaCache + - * repeated build() calls in one process. After the warm-up build the pool - * must serve every further build without new writes: the cached document - * and the cached confinement verdict are both reused. - * * @internal */ final class StringSpecConfinementCacheTest extends TestCase diff --git a/tests/Integration/Concurrency/RoadRunnerTest.php b/tests/Integration/Concurrency/RoadRunnerTest.php index 7b97611b..31ad532f 100644 --- a/tests/Integration/Concurrency/RoadRunnerTest.php +++ b/tests/Integration/Concurrency/RoadRunnerTest.php @@ -18,18 +18,6 @@ use const JSON_THROW_ON_ERROR; /** - * P-096: RoadRunner uses a prefork execution model (one worker per process), - * so the validator instance is implicitly isolated between workers. These - * tests document the prefork reuse contract: a single worker that reuses - * the validator instance across many requests does not accumulate state - * from previous requests, and reset() leaves the worker in a clean state. - * - * No special extension is required (RoadRunner ships as a binary that talks - * to PHP via the standard CGI/Worker protocol); the tests therefore run on - * every PHP 8.4+ runtime. They are grouped under Concurrency because they - * describe the long-running reuse contract rather than a single-shot - * request lifecycle. - * * @internal */ final class RoadRunnerTest extends TestCase diff --git a/tests/Integration/Concurrency/ValidationContextPerRequestTest.php b/tests/Integration/Concurrency/ValidationContextPerRequestTest.php index 134ea849..da7da2ce 100644 --- a/tests/Integration/Concurrency/ValidationContextPerRequestTest.php +++ b/tests/Integration/Concurrency/ValidationContextPerRequestTest.php @@ -17,18 +17,6 @@ use function json_encode; -/** - * CY-19 / P-062: per-request isolation for Error\ValidationContext. - * - * Error\ValidationContext carries mutable per-validation state: a depth - * counter (MAX_DEPTH DoS guard) and a BreadcrumbManager stack (dataPath - * assembly). Under prefork execution (PHP-FPM, RoadRunner) each request - * gets a fresh validator instance OR a fresh context. Under long-running - * shared-validator runtimes (Swoole coroutines, FrankenPHP threaded - * workers), the same validator instance handles many sequential requests - * — these tests prove that per-request state does not leak between - * requests on the same shared validator. - */ final class ValidationContextPerRequestTest extends TestCase { private const string NESTED_SCHEMA_YAML = <<<'YAML' diff --git a/tests/Integration/ConcurrentValidationTest.php b/tests/Integration/ConcurrentValidationTest.php index 4151d7f9..8e60614a 100644 --- a/tests/Integration/ConcurrentValidationTest.php +++ b/tests/Integration/ConcurrentValidationTest.php @@ -15,15 +15,6 @@ use function json_encode; -/** - * CY-07: Concurrent validation shared-state isolation. - * - * The validator instance is designed for reuse in long-running processes - * (RoadRunner, FrankenPHP, Swoole) where one validator handles many - * sequential requests. These tests prove that per-request state does not - * leak between requests on the same validator instance without calling - * reset(). - */ final class ConcurrentValidationTest extends TestCase { private const string CONCURRENT_SPEC = <<<'YAML' @@ -97,13 +88,6 @@ protected function setUp(): void $this->factory = new Psr17Factory(); } - /** - * CY-07: Two sequential requests with distinct paths and methods on - * the same validator instance (no reset()) must each return the - * correct Operation. A third request repeats the first path with a - * different body to prove Operation identity is path/method-driven, - * not affected by the prior request body. - */ #[Test] public function sequential_distinct_requests_return_expected_operations_without_reset(): void { @@ -131,11 +115,6 @@ public function sequential_distinct_requests_return_expected_operations_without_ $this->assertOperationEquals('POST', '/users', $operation3); } - /** - * CY-07: A validation error thrown by the first request must not - * prevent the second, valid request from passing. The validator must - * not carry forward a "failed" flag or any error state. - */ #[Test] public function error_in_first_request_does_not_leak_into_second_valid_request(): void { @@ -165,12 +144,6 @@ public function error_in_first_request_does_not_leak_into_second_valid_request() $this->assertOperationEquals('POST', '/items', $operation); } - /** - * CY-07: Validation errors must not accumulate between failing - * requests. Each failing request must throw its own error scoped to - * its own data path. The second request's error must reference - * /title, never /name — proving no leakage from the previous request. - */ #[Test] public function validation_errors_do_not_accumulate_between_failing_requests(): void { @@ -207,11 +180,6 @@ public function validation_errors_do_not_accumulate_between_failing_requests(): } } - /** - * CY-07: With coercion enabled, coerced values from the first request - * must not leak into the second request. Three sequential requests - * with different query-string values must each validate independently. - */ #[Test] public function coerced_attributes_do_not_leak_between_requests(): void { @@ -233,11 +201,6 @@ public function coerced_attributes_do_not_leak_between_requests(): void $this->assertOperationEquals('GET', '/search', $operation3); } - /** - * CY-07: A coercion failure (non-numeric query string cannot be - * coerced to integer) in the first request must not break subsequent - * requests. The validator must remain usable after a failed coercion. - */ #[Test] public function coercion_failure_in_first_request_does_not_break_second_request(): void { @@ -261,12 +224,6 @@ public function coercion_failure_in_first_request_does_not_break_second_request( $this->assertOperationEquals('GET', '/search', $operation); } - /** - * CY-07: The Operation returned for a later request must not equal - * the Operation of an earlier request when path or method differs. - * This proves the Operation context is built per-request from the - * matched path/method, not reused from a stale cache slot. - */ #[Test] public function operation_context_is_rebuilt_per_request_not_reused(): void { @@ -290,11 +247,6 @@ public function operation_context_is_rebuilt_per_request_not_reused(): void $this->assertNotSame((string) $operation1, (string) $operation2); } - /** - * CY-07: Mixing successful and failing requests on the same validator - * (no reset()) must keep every validation result scoped to its own - * request. Pattern: success → failure → success → failure → success. - */ #[Test] public function mixed_success_and_failure_sequence_isolates_each_request(): void { diff --git a/tests/Integration/LibxmlEdgeCasesTest.php b/tests/Integration/LibxmlEdgeCasesTest.php index 7119bfb6..fac24a76 100644 --- a/tests/Integration/LibxmlEdgeCasesTest.php +++ b/tests/Integration/LibxmlEdgeCasesTest.php @@ -22,14 +22,6 @@ use const LIBXML_NOWARNING; /** - * P-099 edge cases: complements LibxmlStateLeakageTest (which covers the - * reset() path) by exercising LibxmlSecuredContext::run() directly against - * malformed XML and repeated invocations. The deny-all external entity - * loader must be restored even when the work closure throws or when the - * XML body itself fails to parse — otherwise adjacent application code - * that parses XML after the validator returns inherits a deny-all loader - * and silently cannot resolve legitimate entities. - * * @internal */ final class LibxmlEdgeCasesTest extends TestCase @@ -104,15 +96,12 @@ public function no_libxml_state_leak_after_repeated_validations(): void #[Test] public function internal_errors_flag_restored_when_work_clears_it(): void { - // Caller turns internal errors on; the work closure must not flip - // the flag back off (or on) where the caller did not ask for it. libxml_use_internal_errors(true); LibxmlSecuredContext::run(static function (): void { simplexml_load_string('', options: LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING); }); - // libxml_use_internal_errors(null) reads without mutating. self::assertTrue( libxml_use_internal_errors(null), 'libxml_use_internal_errors flag must be restored to its caller-visible value after run().', @@ -122,8 +111,6 @@ public function internal_errors_flag_restored_when_work_clears_it(): void #[Test] public function libxml_errors_buffered_inside_run_does_not_leak_to_caller(): void { - // Caller has zero errors in the buffer. Work intentionally fails to - // parse; the secured context's finally block clears its own errors. libxml_clear_errors(); self::assertSame([], libxml_get_errors()); diff --git a/tests/Integration/LibxmlStateLeakageTest.php b/tests/Integration/LibxmlStateLeakageTest.php index 3a8b4d33..f264513c 100644 --- a/tests/Integration/LibxmlStateLeakageTest.php +++ b/tests/Integration/LibxmlStateLeakageTest.php @@ -15,10 +15,6 @@ use function simplexml_load_string; /** - * Verifies P-064 contract: OpenApiValidator::reset() must not mutate PHP-global - * libxml state. Consumer code that has accumulated libxml errors before calling - * reset() must still be able to read them afterwards. - * * @internal */ final class LibxmlStateLeakageTest extends TestCase diff --git a/tests/Integration/PostRefactorBehavioralSnapshotTest.php b/tests/Integration/PostRefactorBehavioralSnapshotTest.php index 98665122..e412a5f3 100644 --- a/tests/Integration/PostRefactorBehavioralSnapshotTest.php +++ b/tests/Integration/PostRefactorBehavioralSnapshotTest.php @@ -15,22 +15,8 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -/** - * Behavioral snapshot tests for the two highest-risk Partition 3 - * refactoring zones (Oracle recommendation R1). Locks down the observable - * behavior of SchemaSiblingMerger and RefResolver - * against the pre-refactor baseline commit f5b0eb9. - * - * Each test exercises one representative scenario end-to-end and asserts - * on actual output values (merged Schema fields, resolved Schema - * identity) — never just "no exception". - */ final class PostRefactorBehavioralSnapshotTest extends TestCase { - // --------------------------------------------------------------------- - // Zone 2: SchemaSiblingMerger — merge semantics - // --------------------------------------------------------------------- - #[Test] public function sibling_merger_nullable_widening_semantics_sibling_false_keeps_null(): void { @@ -39,9 +25,6 @@ public function sibling_merger_nullable_widening_semantics_sibling_false_keeps_n $merged = new SchemaSiblingMerger()->merge($resolved, $sibling); - // Widening semantics: a `nullable` sibling next to `$ref` can only add - // null to the target. `nullable: false` is indistinguishable from an - // omitted flag, so it never removes the target's nullability. self::assertTrue($merged->nullable); } @@ -64,7 +47,6 @@ public function sibling_merger_type_conflict_clears_type_and_wraps_in_all_of(): $merged = new SchemaSiblingMerger()->merge($resolved, $sibling); - // Disjoint types → type cleared, both constraints wrapped in allOf. self::assertNull($merged->type); self::assertNotNull($merged->allOf); self::assertCount(2, $merged->allOf); @@ -80,7 +62,6 @@ public function sibling_merger_format_conflict_clears_format_and_wraps_in_all_of $merged = new SchemaSiblingMerger()->merge($resolved, $sibling); - // Different formats → format cleared, both wrapped in allOf. self::assertNull($merged->format); self::assertNotNull($merged->allOf); self::assertCount(2, $merged->allOf); @@ -96,7 +77,6 @@ public function sibling_merger_compatible_type_arrays_intersect_to_single_value( $merged = new SchemaSiblingMerger()->merge($resolved, $sibling); - // Intersection is just 'string'. self::assertSame('string', $merged->type); self::assertNull($merged->allOf); } @@ -131,8 +111,6 @@ public function sibling_merger_any_of_on_both_sides_wraps_in_all_of_not_concaten $merged = new SchemaSiblingMerger()->merge($resolved, $sibling); - // anyOf is wrapped — both branches must hold (AND semantics), not - // concatenated (which would be OR over 4 alternatives). self::assertNull($merged->anyOf); self::assertNotNull($merged->allOf); self::assertCount(2, $merged->allOf); @@ -148,7 +126,6 @@ public function sibling_merger_numeric_bounds_take_stricter_of_both(): void $merged = new SchemaSiblingMerger()->merge($resolved, $sibling); - // AND of two ranges = stricter bounds win. self::assertSame(0.0, $merged->minimum); self::assertSame(50.0, $merged->maximum); } @@ -164,10 +141,6 @@ public function sibling_merger_required_unions_both_lists_dedup(): void self::assertSame(['id', 'name', 'email'], $merged->required); } - // --------------------------------------------------------------------- - // Zone 3: RefResolver — $ref resolution semantics - // --------------------------------------------------------------------- - #[Test] public function ref_resolver_resolves_simple_internal_schema_ref(): void { @@ -200,8 +173,6 @@ public function ref_resolver_resolves_ref_via_another_schema_property(): void self::assertSame('object', $userResolved->type); self::assertNotNull($userResolved->properties); self::assertArrayHasKey('address', $userResolved->properties); - // Property still holds the $ref pointer; resolve() itself returns - // the named schema unchanged — its siblings are not auto-resolved. self::assertSame('#/components/schemas/Address', $userResolved->properties['address']->ref); } @@ -291,7 +262,6 @@ public function ref_resolver_caches_resolved_schema_on_repeat_call(): void $first = $resolver->resolve('#/components/schemas/Cached', $document); $second = $resolver->resolve('#/components/schemas/Cached', $document); - // Same identity — cache returns the previously resolved instance. self::assertSame($first, $second); } @@ -306,10 +276,6 @@ public function ref_resolver_throws_unresolvable_for_missing_schema(): void $resolver->resolve('#/components/schemas/Missing', $document); } - // --------------------------------------------------------------------- - // Helpers - // --------------------------------------------------------------------- - /** * @param array $schemas */ diff --git a/tests/Integration/Psr7/GuzzlePsr7Test.php b/tests/Integration/Psr7/GuzzlePsr7Test.php index bac93861..c5ca2ba3 100644 --- a/tests/Integration/Psr7/GuzzlePsr7Test.php +++ b/tests/Integration/Psr7/GuzzlePsr7Test.php @@ -19,15 +19,6 @@ use const JSON_THROW_ON_ERROR; /** - * P-100: PSR-7 alternate implementation. The validator targets the PSR-7 - * interfaces (ServerRequestInterface, ResponseInterface, StreamInterface) - * and MUST work with any compliant implementation, not only nyholm/psr7. - * - * These tests build the validator once and exercise it with Guzzle PSR-7 - * request objects (guzzlehttp/psr7 ^2.6), proving that the public contract - * is implementation-agnostic. nyholm/psr7 remains the canonical test-time - * implementation; this suite documents the portability guarantee. - * * @internal */ final class GuzzlePsr7Test extends TestCase diff --git a/tests/Integration/Psr7/LaminasDiactorosTest.php b/tests/Integration/Psr7/LaminasDiactorosTest.php index 1b5d9d97..bf31a401 100644 --- a/tests/Integration/Psr7/LaminasDiactorosTest.php +++ b/tests/Integration/Psr7/LaminasDiactorosTest.php @@ -20,14 +20,6 @@ use const JSON_THROW_ON_ERROR; /** - * P-100: PSR-7 alternate implementation. The validator targets the PSR-7 - * interfaces (ServerRequestInterface, ResponseInterface, StreamInterface) - * and MUST work with any compliant implementation, not only nyholm/psr7. - * - * These tests build the validator once and exercise it with Laminas - * Diactoros request objects (laminas/laminas-diactoros ^3.3), proving - * that the public contract is implementation-agnostic. - * * @internal */ final class LaminasDiactorosTest extends TestCase diff --git a/tests/Integration/Psr7/StubPsr7Test.php b/tests/Integration/Psr7/StubPsr7Test.php index f6c3e8f6..9244248b 100644 --- a/tests/Integration/Psr7/StubPsr7Test.php +++ b/tests/Integration/Psr7/StubPsr7Test.php @@ -25,12 +25,6 @@ use const SEEK_SET; /** - * P-100 fallback: a minimal PSR-7 StreamInterface stub proves that the - * validator depends only on the PSR-7 contract, not on any concrete - * implementation. The validator must consume the body via the documented - * StreamInterface methods (getSize / isSeekable / rewind / eof / read) - * without downcasting to a specific class. - * * @internal */ final class StubPsr7Test extends TestCase @@ -108,8 +102,6 @@ public function surfaces_validation_error_with_stub_stream_interface(): void } /** - * Minimal ServerRequestInterface implementation backed by in-memory state. - * * @internal */ final readonly class StubServerRequest implements ServerRequestInterface @@ -285,8 +277,6 @@ public function withBody(StreamInterface $body): static } /** - * Simple in-memory StreamInterface backed by a string buffer. - * * @internal */ final class StubStream implements StreamInterface diff --git a/tests/Integration/SchemaHelperIntegrationTest.php b/tests/Integration/SchemaHelperIntegrationTest.php index 02c6117e..d2deb22a 100644 --- a/tests/Integration/SchemaHelperIntegrationTest.php +++ b/tests/Integration/SchemaHelperIntegrationTest.php @@ -60,11 +60,6 @@ public function invalid_types_in_real_scenario_throw_meaningful_exceptions(): vo } } - /** - * P-010: stdClass is now normalized to its property-view array, matching - * TypeCoercer::normalizeValue. Consumers using json_decode without the - * associative flag no longer need a manual conversion step. - */ #[Test] public function stdClass_is_normalized_to_array_in_real_scenario(): void { diff --git a/tests/Integration/Validator/Error/BreadcrumbIntegrationTest.php b/tests/Integration/Validator/Error/BreadcrumbIntegrationTest.php index d33e46af..3d764e09 100644 --- a/tests/Integration/Validator/Error/BreadcrumbIntegrationTest.php +++ b/tests/Integration/Validator/Error/BreadcrumbIntegrationTest.php @@ -64,7 +64,7 @@ public function track_breadcrumb_for_nested_properties(): void try { $validator->validateWithContext( - ['users' => ['name' => 'ab']], // Too short + ['users' => ['name' => 'ab']], $schema, $context, ); @@ -93,7 +93,7 @@ public function track_breadcrumb_for_array_indices(): void try { $validator->validateWithContext( - [['id' => 'invalid']], // Should be integer + [['id' => 'invalid']], $schema, $context, ); @@ -127,7 +127,7 @@ public function track_breadcrumb_for_complex_structure(): void try { $validator->validateWithContext( - ['users' => [['name' => 123]]], // Should be string + ['users' => [['name' => 123]]], $schema, $context, ); @@ -153,7 +153,7 @@ public function include_breadcrumb_in_exception(): void try { $validator->validateWithContext( - ['field' => 123], // Should be string + ['field' => 123], $schema, $context, ); @@ -195,7 +195,7 @@ public function maintain_breadcrumb_in_multiple_nesting_levels(): void try { $validator->validateWithContext( - ['level1' => ['level2' => ['level3' => 456]]], // Should be string + ['level1' => ['level2' => ['level3' => 456]]], $schema, $context, ); @@ -227,7 +227,7 @@ public function track_multiple_array_indices(): void try { $validator->validateWithContext( - ['matrix' => [[1, 2], [3, 'invalid']]], // Should be integer + ['matrix' => [[1, 2], [3, 'invalid']]], $schema, $context, ); @@ -264,7 +264,7 @@ public function breadcrumb_with_mixed_properties_and_arrays(): void try { $validator->validateWithContext( - ['data' => [['items' => ['valid', 123]]]], // Should be string + ['data' => [['items' => ['valid', 123]]]], $schema, $context, ); diff --git a/tests/Integration/Validator/Error/ErrorHandlingIntegrationTest.php b/tests/Integration/Validator/Error/ErrorHandlingIntegrationTest.php index f7c12d96..a53548fe 100644 --- a/tests/Integration/Validator/Error/ErrorHandlingIntegrationTest.php +++ b/tests/Integration/Validator/Error/ErrorHandlingIntegrationTest.php @@ -68,7 +68,7 @@ public function format_validation_error_with_simple_formatter(): void try { $validator->validateWithContext( - ['name' => 'ab'], // Too short + ['name' => 'ab'], $schema, $context, ); @@ -125,7 +125,7 @@ public function use_custom_formatter(): void minLength: 3, ); - $formatter = new JsonFormatter(); // Custom formatter + $formatter = new JsonFormatter(); $context = new ValidationContext( breadcrumbs: BreadcrumbManager::create(), pool: $this->pool, @@ -135,7 +135,7 @@ public function use_custom_formatter(): void try { $validator->validateWithContext( - 'ab', // Too short + 'ab', $schema, $context, ); @@ -179,7 +179,7 @@ public function context_maintains_formatter_through_validation_chain(): void try { $validator->validateWithContext( - ['user' => ['age' => 15]], // Too young + ['user' => ['age' => 15]], $schema, $context, ); @@ -288,7 +288,7 @@ public function detailed_formatter_provides_comprehensive_output(): void try { $validator->validateWithContext( - 5, // Below minimum + 5, $schema, $context, ); diff --git a/tests/Integration/Validator/OpenApiValidatorResetCachesTest.php b/tests/Integration/Validator/OpenApiValidatorResetCachesTest.php index 0ecc2d79..6f1040e8 100644 --- a/tests/Integration/Validator/OpenApiValidatorResetCachesTest.php +++ b/tests/Integration/Validator/OpenApiValidatorResetCachesTest.php @@ -19,10 +19,6 @@ use function sprintf; /** - * Verifies EI-008 contract: OpenApiValidator::reset() must clear all internal - * instance caches (PathRegexCache from EI-005 and RegexValidator from EI-006) - * so the validator is safe to reuse across requests in long-running workers. - * * @internal */ final class OpenApiValidatorResetCachesTest extends TestCase diff --git a/tests/Integration/Validator/OpenApiValidatorTest.php b/tests/Integration/Validator/OpenApiValidatorTest.php index 402489a4..04a2d2cf 100644 --- a/tests/Integration/Validator/OpenApiValidatorTest.php +++ b/tests/Integration/Validator/OpenApiValidatorTest.php @@ -188,9 +188,6 @@ public function validate_response_with_operation(): void $validator->validateResponse($response, $operation); } - /** - * Create a mock PSR-7 server request - */ private function createMockServerRequest(string $method, string $uri) { $request = $this->createStub(ServerRequestInterface::class); diff --git a/tests/Integration/Validator/Schema/DiscriminatorExternalRefTest.php b/tests/Integration/Validator/Schema/DiscriminatorExternalRefTest.php index 8deabdfe..8934d4e5 100644 --- a/tests/Integration/Validator/Schema/DiscriminatorExternalRefTest.php +++ b/tests/Integration/Validator/Schema/DiscriminatorExternalRefTest.php @@ -18,14 +18,6 @@ use function sprintf; -/** - * DI-08: Discriminator mapping with external $ref. - * - * OpenAPI 3.2 spec allows discriminator mapping values to be either local - * pointers ('#/components/schemas/Foo') or external references (URIs, file - * paths). This codebase only supports local pointer refs; external refs are - * rejected by RefResolver. - */ #[CoversClass(DiscriminatorValidator::class)] #[CoversClass(RefResolver::class)] final class DiscriminatorExternalRefTest extends TestCase @@ -33,7 +25,7 @@ final class DiscriminatorExternalRefTest extends TestCase private const string EXTERNAL_URL_MAPPING_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: DI-08 External URL Mapping API + title: External URL Mapping API version: 1.0.0 paths: {} components: @@ -77,7 +69,7 @@ enum: [dog] private const string RELATIVE_FILE_MAPPING_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: DI-08 Relative File Mapping API + title: Relative File Mapping API version: 1.0.0 paths: {} components: @@ -118,15 +110,6 @@ enum: [dog] type: string YAML; - /** - * Negative: a string-loaded spec whose discriminator mapping - * references an external https URL is rejected at `build()` time - * with `BuilderException` (STRING-SPEC-FAILOPEN fail-closed - * behaviour). The build never reaches `DiscriminatorValidator`, - * so no `UnresolvableRefException` is thrown; callers must remove - * the external mapping or load the spec via `fromYamlFile` / - * `withExternalRefAllowedRoot()` to opt into path-confinement. - */ #[Test] public function di_08_external_url_mapping_throws_builder_exception_at_build_time(): void { @@ -138,17 +121,6 @@ public function di_08_external_url_mapping_throws_builder_exception_at_build_tim ->build(); } - /** - * Negative: a string-loaded spec whose discriminator mapping - * references a relative file path is rejected at `build()` time - * with `BuilderException` (STRING-SPEC-FAILOPEN fail-closed - * behaviour). The build never reaches the discriminator - * resolution path that previously produced a `RuntimeException` - * when the referenced file did not exist relative to CWD; callers - * must remove the external mapping or load the spec via - * `fromYamlFile` / `withExternalRefAllowedRoot()` to opt into - * path-confinement. - */ #[Test] public function di_08_relative_file_mapping_throws_builder_exception_at_build_time(): void { @@ -160,19 +132,6 @@ public function di_08_relative_file_mapping_throws_builder_exception_at_build_ti ->build(); } - /** - * Negative: a string-loaded spec whose discriminator mapping - * contains an external URL is rejected at `build()` time with - * `BuilderException` (STRING-SPEC-FAILOPEN fail-closed - * behaviour) — even when the discriminator value eventually used - * at validation time would not have matched the external mapping - * key. The guard fails closed at build time and never reaches the - * previously-documented fail-late path where - * `UnknownDiscriminatorValueException` would have surfaced for - * absent values; callers must remove the external mapping or - * load the spec via `fromYamlFile` / - * `withExternalRefAllowedRoot()` to opt into path-confinement. - */ #[Test] public function di_08_external_mapping_with_value_absent_from_request_throws_builder_exception_at_build_time(): void { @@ -184,12 +143,6 @@ public function di_08_external_mapping_with_value_absent_from_request_throws_bui ->build(); } - /** - * RefResolutionException is thrown by RefResolver::resolveRelativeRef() - * when a relative reference cannot be resolved due to missing document - * $self. This is a different code path from external URL refs (which - * throw UnresolvableRefException). - */ #[Test] public function di_08_resolve_relative_ref_without_self_throws_ref_resolution_exception(): void { @@ -221,11 +174,6 @@ public function di_08_resolve_relative_ref_without_self_throws_ref_resolution_ex ); } - /** - * RefResolutionException is NOT thrown when document $self is set: the - * relative ref is combined into an absolute URI string. This documents - * that no actual external fetching happens — only URI composition. - */ #[Test] public function di_08_resolve_relative_ref_with_self_combines_uris(): void { @@ -245,17 +193,13 @@ public function di_08_resolve_relative_ref_with_self_combines_uris(): void ); } - /** - * Sanity check: local pointer mapping ('#/components/schemas/...') works - * as the only supported discriminator mapping shape. - */ #[Test] public function di_08_local_pointer_mapping_resolves_normally(): void { $yaml = <<<'YAML' openapi: 3.2.0 info: - title: DI-08 Local Mapping API + title: Local Mapping API version: 1.0.0 paths: {} components: diff --git a/tests/Integration/Validator/Schema/DiscriminatorValidatorTest.php b/tests/Integration/Validator/Schema/DiscriminatorValidatorTest.php index 55c09195..dbb4d0fb 100644 --- a/tests/Integration/Validator/Schema/DiscriminatorValidatorTest.php +++ b/tests/Integration/Validator/Schema/DiscriminatorValidatorTest.php @@ -43,7 +43,7 @@ final class DiscriminatorValidatorTest extends TestCase private const string DI_05_ALLOF_COMPOSITION_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: DI-05 Animal API + title: Animal API version: 1.0.0 paths: {} components: @@ -99,7 +99,7 @@ enum: [dog] private const string DI_06_NESTED_DISCRIMINATOR_SPEC = <<<'YAML' openapi: 3.2.0 info: - title: DI-06 Shape API + title: Shape API version: 1.0.0 paths: {} components: diff --git a/tests/Integration/Validator/Schema/ItemsValidatorWithContextTest.php b/tests/Integration/Validator/Schema/ItemsValidatorWithContextTest.php index 0e2057f2..7e507b80 100644 --- a/tests/Integration/Validator/Schema/ItemsValidatorWithContextTest.php +++ b/tests/Integration/Validator/Schema/ItemsValidatorWithContextTest.php @@ -618,12 +618,6 @@ public function validate_items_with_discriminator_routes_each_element_by_type(): #[Test] public function validate_items_with_ref_to_nullable_type_accepts_null(): void { - // Regression for B1 (items path): $ref stub to a target with - // type: ['string', 'null'] must accept null items. The pre-fix - // $allowNull calculation rejected null because the stub has no - // `nullable` and no `type`. Post-fix the ref check lets null - // through so the inner rootSchemaValidator can resolve $ref and - // accept null via the resolved target's type. $nullableTargetSchema = new Schema(type: ['string', 'null']); $schema = new Schema( @@ -660,11 +654,6 @@ public function validate_items_with_ref_to_nullable_type_accepts_null(): void #[Test] public function validate_items_with_ref_to_non_nullable_type_rejects_null(): void { - // Counter-regression (items path): $ref stub to a target with - // type: 'string' (non-nullable) must still reject null. The fix - // lets null past the pre-normalize step, but the inner - // rootSchemaValidator must resolve $ref and let TypeValidator - // reject null on the resolved target. $nonNullableTargetSchema = new Schema(type: 'string'); $schema = new Schema( @@ -701,9 +690,6 @@ public function validate_items_with_ref_to_non_nullable_type_rejects_null(): voi #[Test] public function validate_items_with_ref_and_sibling_nullable_accepts_null(): void { - // README workaround still works (items path): declare `nullable: true` - // as a sibling of $ref. Resolved target must also allow null per - // SchemaSiblingMerger AND semantics. $nullableTargetSchema = new Schema(type: ['string', 'null']); $schema = new Schema( @@ -740,9 +726,6 @@ public function validate_items_with_ref_and_sibling_nullable_accepts_null(): voi #[Test] public function validate_items_with_ref_continues_to_accept_non_null_values(): void { - // Non-regression (items path): non-null values for $ref items must - // continue to validate as before. The fix only affects the null- - // handling path. $nullableTargetSchema = new Schema(type: ['string', 'null']); $schema = new Schema( diff --git a/tests/Integration/Validator/Schema/PropertiesValidatorWithContextTest.php b/tests/Integration/Validator/Schema/PropertiesValidatorWithContextTest.php index 5b061f4b..1c49831d 100644 --- a/tests/Integration/Validator/Schema/PropertiesValidatorWithContextTest.php +++ b/tests/Integration/Validator/Schema/PropertiesValidatorWithContextTest.php @@ -627,12 +627,6 @@ public function validate_properties_with_custom_logger_and_event_dispatcher(): v #[Test] public function validate_properties_with_ref_to_nullable_type_accepts_null(): void { - // Regression for B1: $ref stub to a target with type: ['string', 'null'] - // must accept null. Pre-normalize step sees the unresolved stub; the - // pre-fix $allowNull calculation rejected null because the stub has no - // `nullable` and no `type`. Post-fix the ref check lets null through - // so the inner rootSchemaValidator can resolve $ref and accept null - // via the resolved target's type. $nullableTargetSchema = new Schema(type: ['string', 'null']); $schema = new Schema( @@ -671,10 +665,6 @@ public function validate_properties_with_ref_to_nullable_type_accepts_null(): vo #[Test] public function validate_properties_with_ref_to_non_nullable_type_rejects_null(): void { - // Counter-regression: $ref stub to a target with type: 'string' - // (non-nullable) must still reject null. The fix lets null past the - // pre-normalize step, but the inner rootSchemaValidator must resolve - // $ref and let TypeValidator reject null on the resolved target. $nonNullableTargetSchema = new Schema(type: 'string'); $schema = new Schema( @@ -713,9 +703,6 @@ public function validate_properties_with_ref_to_non_nullable_type_rejects_null() #[Test] public function validate_properties_with_ref_and_sibling_nullable_accepts_null(): void { - // README workaround still works: declare `nullable: true` as a sibling - // of $ref. Resolved target must also allow null per SchemaSiblingMerger - // AND semantics. $nullableTargetSchema = new Schema(type: ['string', 'null']); $schema = new Schema( @@ -754,8 +741,6 @@ public function validate_properties_with_ref_and_sibling_nullable_accepts_null() #[Test] public function validate_properties_with_ref_continues_to_accept_non_null_values(): void { - // Non-regression: non-null values for $ref properties must continue - // to validate as before. The fix only affects the null-handling path. $nullableTargetSchema = new Schema(type: ['string', 'null']); $schema = new Schema( diff --git a/tests/Integration/Validator/SchemaValidatorAdapterContextTest.php b/tests/Integration/Validator/SchemaValidatorAdapterContextTest.php index 837461b0..25b4fedf 100644 --- a/tests/Integration/Validator/SchemaValidatorAdapterContextTest.php +++ b/tests/Integration/Validator/SchemaValidatorAdapterContextTest.php @@ -96,7 +96,7 @@ private function buildSpec(): string return <<<'YAML' openapi: 3.2.0 info: - title: EI-009 regression + title: regression version: 1.0.0 paths: {} components: diff --git a/tests/Integration/Validator/Webhook/WebhookSecurityCoercionTest.php b/tests/Integration/Validator/Webhook/WebhookSecurityCoercionTest.php index b1e8a0ed..e1494744 100644 --- a/tests/Integration/Validator/Webhook/WebhookSecurityCoercionTest.php +++ b/tests/Integration/Validator/Webhook/WebhookSecurityCoercionTest.php @@ -14,10 +14,6 @@ use PHPUnit\Framework\TestCase; /** - * Covers webhook edge cases: - * - WH-04: webhook with security scheme (http/bearer) - * - WH-05: webhook with type coercion - * * @internal */ final class WebhookSecurityCoercionTest extends TestCase @@ -108,11 +104,6 @@ public function wh_04_webhook_with_valid_bearer_token_returns_operation(): void self::assertSame('POST', $operation->method); } - /** - * When enableSecurityValidation() is active and the spec declares a - * security scheme for a webhook, a request missing the required - * credentials must be rejected with a ValidationException. - */ #[Test] public function wh_04_webhook_without_authorization_throws_security_exception(): void { diff --git a/tests/Performance/ConfinementCacheBenchTest.php b/tests/Performance/ConfinementCacheBenchTest.php index 396d0f87..5a512c0e 100644 --- a/tests/Performance/ConfinementCacheBenchTest.php +++ b/tests/Performance/ConfinementCacheBenchTest.php @@ -19,11 +19,6 @@ use function strlen; /** - * Regression budget for issue #68: with a warm confinement verdict cache, - * build() for a string-loaded spec must skip the ExternalRefDetector - * re-parse, so the median cached build time on a ~300 KB spec stays well - * below the cost of a single raw parse (the pre-fix behaviour). - * * @internal */ final class ConfinementCacheBenchTest extends TestCase diff --git a/tests/Security/BillionLaughsTest.php b/tests/Security/BillionLaughsTest.php index 86efaa0f..52a5725c 100644 --- a/tests/Security/BillionLaughsTest.php +++ b/tests/Security/BillionLaughsTest.php @@ -19,29 +19,6 @@ use const JSON_THROW_ON_ERROR; /** - * P-097: real Billion Laughs attack. The existing XmlSecurityTest covers - * three entity levels; this test extends the contract to eight ENTITY - * declarations — a literal leaf plus seven multiplying levels of ten - * (10^7 = 10 million entity expansions at the leaf reference; a fully - * expanded tree would allocate ~30 MB for the lol-string) — and asserts - * that memory growth stays under 20 MB. The entity chain is currently - * inert due to a naming defect (see SEC-026 in the campaign backlog); - * the defence lines below are verified against a live chain. - * - * Defence lines for this payload, which declares internal entities only: - * libxml2's built-in entity-reference-loop detection aborts exponential - * internal entity expansion, and XmlBodyParser parses without LIBXML_NOENT - * and without LIBXML_PARSE_HUGE (entity substitution stays off); the - * deny-all external entity loader installed by LibxmlSecuredContext plus - * LIBXML_NONET guards XXE (SYSTEM/PUBLIC references) and is not invoked by - * internal entities. On top of the parser, the reject-or-bounded assertion - * pins the contract: the parser must either reject the document or return - * a result whose serialized form stays under 1 MB. - * - * Memory assertion is generous (20 MB) to stay stable on noisy CI workers - * while still detecting a regression that fully expanded the entity tree - * (~30 MB at these levels). - * * @internal */ final class BillionLaughsTest extends TestCase diff --git a/tests/Security/CallbackRuntimeTemplateSecurityTest.php b/tests/Security/CallbackRuntimeTemplateSecurityTest.php index 7f8381ad..be683900 100644 --- a/tests/Security/CallbackRuntimeTemplateSecurityTest.php +++ b/tests/Security/CallbackRuntimeTemplateSecurityTest.php @@ -23,22 +23,6 @@ use PHPUnit\Framework\TestCase; /** - * Security regression for P-029 / SEC-09: a callback expression like - * `{$request.body#/callback_url}` references the original triggering request - * and cannot be resolved by the validator, which makes path validation a - * wildcard that accepts any URL. When the runtime template is attacker- - * controlled, declared security checks on the callback pathItem still pass - * against an arbitrary URL. Strict mode is the default since the SEC-09 fix - * on three converging levels: (1) the `OpenApiValidatorBuilder::build()` - * `?? true` fallback; (2) the `Validation\CallbackValidator` constructor - * default (R3-SEC-009); (3) the inner `Callback\CallbackValidator` - * constructor default (R3-SEC-009). Legacy wildcard behaviour is opt-in via - * {@see OpenApiValidatorBuilder::disableStrictCallbackRuntimeTemplate()} or - * by passing `strictCallbackRuntimeTemplate: false` explicitly to either - * class constructor. The pre-fix opt-in method - * {@see OpenApiValidatorBuilder::enableStrictCallbackRuntimeTemplate()} is - * retained as a deprecated no-op for backward compatibility. - * * @internal */ final class CallbackRuntimeTemplateSecurityTest extends TestCase @@ -137,14 +121,6 @@ public function builder_strict_mode_is_default(): void $validator->validateCallback($request, 'myCallback'); } - /** - * Anti-test guard: this assertion proves strict mode is on by default. - * To verify, temporarily revert the fallback in - * `OpenApiValidatorBuilder::build()` from `?? true` back to `?? false` - * and re-run this test — it must fail because the validator would - * resolve the runtime expression as a wildcard instead of throwing. - * Restoring the `?? true` fallback makes it pass again. - */ #[Test] public function builder_unresolvable_runtime_expression_throws_by_default(): void { diff --git a/tests/Security/CompositionErrorCapTest.php b/tests/Security/CompositionErrorCapTest.php index be0bd385..471821be 100644 --- a/tests/Security/CompositionErrorCapTest.php +++ b/tests/Security/CompositionErrorCapTest.php @@ -19,11 +19,6 @@ use PHPUnit\Framework\TestCase; /** - * P-031 regression: composition validators must cap accumulated errors at - * 20 and emit a TooManyErrorsError summary rather than letting deeply - * nested allOf / anyOf / oneOf schemas produce unbounded error arrays - * that amplify response size and exhaust memory. - * * @internal */ final class CompositionErrorCapTest extends TestCase @@ -77,7 +72,7 @@ public function composition_validator_caps_errors_at_twenty_with_summary(): void self::assertTrue( $hasSummary, - 'Composition validator must emit a TooManyErrorsError summary when the cap is reached (P-031)', + 'Composition validator must emit a TooManyErrorsError summary when the cap is reached', ); self::assertSame(1, $summaryCount, 'Exactly one summary error must be appended'); } diff --git a/tests/Security/ContainsValidatorDoSProtectionTest.php b/tests/Security/ContainsValidatorDoSProtectionTest.php index d3c04e49..3ae61705 100644 --- a/tests/Security/ContainsValidatorDoSProtectionTest.php +++ b/tests/Security/ContainsValidatorDoSProtectionTest.php @@ -21,11 +21,6 @@ use function sprintf; /** - * P-032 regression: ContainsValidator must terminate after 10000 matching - * validations rather than walking a 100k-element attacker payload end to - * end. Without the cap, a spec like `contains: {complex schema}` without - * maxItems becomes a CPU-exhaustion vector. - * * @internal */ final class ContainsValidatorDoSProtectionTest extends TestCase @@ -64,7 +59,7 @@ public function contains_validator_terminates_after_ten_thousand_validations(): self::assertNotNull( $caught, - 'ContainsValidator must abort after the MAX_CONTAINS_VALIDATIONS cap (P-032)', + 'ContainsValidator must abort after the MAX_CONTAINS_VALIDATIONS cap', ); self::assertLessThan( 50 * 1024 * 1024, diff --git a/tests/Security/CookieOverflowSecurityTest.php b/tests/Security/CookieOverflowSecurityTest.php index 9f07c97a..bebbecf0 100644 --- a/tests/Security/CookieOverflowSecurityTest.php +++ b/tests/Security/CookieOverflowSecurityTest.php @@ -19,8 +19,6 @@ use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use Duyler\OpenApi\Validator\Request\BodyParser\MultipartBodyParser; -use Duyler\OpenApi\Validator\Request\QueryParser; use function implode; use function range; @@ -28,13 +26,6 @@ use function substr_count; /** - * Security regression for P-028: CookieValidator previously returned an empty - * array on overflow, silently dropping cookie state and bypassing security - * checks for optional cookie-based schemes. The validator now fails closed - * with {@see InvalidParameterException}, matching - * {@see QueryParser} and - * {@see MultipartBodyParser}. - * * @internal */ #[CoversClass(CookieValidator::class)] diff --git a/tests/Security/DeepNestingTest.php b/tests/Security/DeepNestingTest.php index cb92ccd2..a9f2fa81 100644 --- a/tests/Security/DeepNestingTest.php +++ b/tests/Security/DeepNestingTest.php @@ -18,17 +18,6 @@ use const JSON_THROW_ON_ERROR; /** - * P-097 / P-099: deep-nesting DoS defence. The validator enforces a hard - * MAX_DEPTH guard (64) via ValidationContext::incrementDepth(); a deeply - * nested payload that exceeds it must be rejected with - * SchemaDepthExceededException rather than blowing the PHP stack. - * - * These tests build a 100-level nested object in the request body — deep - * enough to exceed the schema depth guard (64) but shallow enough to pass - * the JSON parser depth limit (128, JsonDepthLimit::Untrusted). The payload - * therefore exercises the schema validator's depth counter, proving the DoS - * guard fires before PHP itself would crash with a stack overflow. - * * @internal */ final class DeepNestingTest extends TestCase @@ -75,8 +64,6 @@ public function rejects_excessive_schema_depth(): void ->fromYamlString(self::SPEC) ->build(); - // 100 levels — exceeds ValidationContext::MAX_DEPTH (64) while - // staying under the JsonBodyParser cap (JsonDepthLimit::Untrusted = 128). $payload = '{"child":' . str_repeat('{"child":', 100) . 'null' . str_repeat('}', 100) . '}'; $request = $this->factory diff --git a/tests/Security/LogInjectionSanitizationTest.php b/tests/Security/LogInjectionSanitizationTest.php index bbaf6f9c..f61ae112 100644 --- a/tests/Security/LogInjectionSanitizationTest.php +++ b/tests/Security/LogInjectionSanitizationTest.php @@ -13,11 +13,6 @@ use function strlen; /** - * P-037 regression: LogContextSanitizer must truncate long strings and - * escape control characters before they enter PSR-3 log context, so a - * plaintext logger (Monolog StreamHandler) cannot be injected with fake - * log lines via newline injection or buried content. - * * @internal */ final class LogInjectionSanitizationTest extends TestCase @@ -35,7 +30,7 @@ public function log_context_truncates_long_strings(): void self::assertLessThan( 400, strlen($sanitized), - 'Sanitized output must stay well under the original 1KB size (P-037)', + 'Sanitized output must stay well under the original 1KB size', ); self::assertStringContainsString('truncated', $sanitized); self::assertStringContainsString('1024 bytes total', $sanitized); @@ -51,7 +46,7 @@ public function log_context_escapes_control_chars(): void self::assertStringNotContainsString( "\n", $sanitized, - 'Newline must be escaped so the logger cannot be injected with fake lines (P-037)', + 'Newline must be escaped so the logger cannot be injected with fake lines', ); self::assertStringContainsString('\x0a', $sanitized); } diff --git a/tests/Security/MemoryExhaustionTest.php b/tests/Security/MemoryExhaustionTest.php index 9e7ba7bf..7494bc56 100644 --- a/tests/Security/MemoryExhaustionTest.php +++ b/tests/Security/MemoryExhaustionTest.php @@ -20,22 +20,7 @@ use const JSON_THROW_ON_ERROR; /** - * P-097: memory-exhaustion DoS. The validator enforces a hard cap on the - * size of request bodies (BodyReader::readSafely, default 10 MB JSON cap - * via ValidatorConfiguration::DEFAULT_MAX_JSON_BODY_BYTES) and on the - * uniqueItems deduplication work performed by the schema validator. - * - * These tests prove that pathological inputs either are rejected outright - * or stay within a bounded memory envelope, never growing to attacker- - * controlled size. - * * @internal - * - * Known limitation: withMaxJsonBodySize() propagates to RequestBodyValidatorWithContext - * and ResponseValidatorWithContext but NOT to the RequestValidator that owns - * BodyReader::readSafely. This is reported separately; the tests below - * exercise the DEFAULT 10 MB cap by sizing payloads above that threshold, - * which is sufficient to prove the DoS guard fires. */ final class MemoryExhaustionTest extends TestCase { @@ -78,17 +63,10 @@ protected function setUp(): void #[Test] public function rejects_oversized_uniqueitems_array(): void { - // A uniqueItems payload large enough to exceed the 10 MB default - // body cap and to detect a regression in the deduplication path. - // Built directly as a string (avoiding array materialisation) so - // the test itself does not exhaust PHP's memory limit before the - // validator gets a chance to reject it. $validator = OpenApiValidatorBuilder::create() ->fromYamlString(self::SPEC) ->build(); - // Each entry is "aaaaaa" (12 bytes including quotes and comma). - // ~900 000 entries -> ~10.8 MB, comfortably above the 10 MB cap. $payload = '{"tags":[' . str_repeat('"aaaaaa",', 900_000) . '"aaaaaa"]}'; $request = $this->factory @@ -116,9 +94,6 @@ public function memory_stays_bounded_on_uniqueitems_deduplication(): void ->fromYamlString(self::SPEC) ->build(); - // 50 000 entries — small enough to fit under the 10 MB body cap, - // large enough to detect a uniqueItems regression that materialised - // the full N^2 pairwise comparison. $large = []; foreach (range(1, 50_000) as $i) { $large[] = 'tag-' . $i; @@ -150,14 +125,10 @@ public function memory_stays_bounded_on_uniqueitems_deduplication(): void #[Test] public function rejects_payload_above_default_json_body_cap(): void { - // The default cap (ValidatorConfiguration::DEFAULT_MAX_JSON_BODY_BYTES) - // is 10 MB. A payload above that threshold must trip the - // BodyReader::readSafely guard. $validator = OpenApiValidatorBuilder::create() ->fromYamlString(self::SPEC) ->build(); - // 11 MB of payload, well above the 10 MB default cap. $oversized = '{"tags":["' . str_repeat('a', 11 * 1024 * 1024) . '"]}'; $request = $this->factory diff --git a/tests/Security/PathFinderDepthLimitTest.php b/tests/Security/PathFinderDepthLimitTest.php index de5e9eb4..2938c483 100644 --- a/tests/Security/PathFinderDepthLimitTest.php +++ b/tests/Security/PathFinderDepthLimitTest.php @@ -10,13 +10,6 @@ use ReflectionClass; /** - * P-034 regression: TrieLookup::lookupTrie must enforce a depth limit - * (MAX_TRIE_DEPTH = 32) to prevent algorithmic amplification on - * deeply-branched spec tries. Task 20 introduced the cap alongside the - * by-reference accumulator; task 17 moved it to TrieLookup without - * changing the contract. This test pins the contract so it cannot - * regress silently. - * * @internal */ final class PathFinderDepthLimitTest extends TestCase @@ -28,7 +21,7 @@ public function max_trie_depth_constant_exists_with_expected_value(): void self::assertTrue( $reflection->hasConstant('MAX_TRIE_DEPTH'), - 'TrieLookup must define MAX_TRIE_DEPTH (P-034)', + 'TrieLookup must define MAX_TRIE_DEPTH', ); $value = $reflection->getConstant('MAX_TRIE_DEPTH'); @@ -55,7 +48,7 @@ public function lookup_trie_method_accepts_depth_parameter(): void self::assertContains( 'depth', $parameterNames, - 'TrieLookup::lookupTrie must accept a $depth parameter so recursion can be bounded (P-034)', + 'TrieLookup::lookupTrie must accept a $depth parameter so recursion can be bounded', ); } } diff --git a/tests/Security/RedosFuzzTest.php b/tests/Security/RedosFuzzTest.php index 3a029ebc..41ab4089 100644 --- a/tests/Security/RedosFuzzTest.php +++ b/tests/Security/RedosFuzzTest.php @@ -29,14 +29,6 @@ use function str_repeat; /** - * PoC tests for ReDoS defenses (P-022, P-023, P-035). Each pathological input - * must terminate within a defensive bound, demonstrating that the - * PregExecutor wrapper caps pcre.backtrack_limit and that the urlencoded - * validator no longer relies on a catastrophic regular expression. - * - * Time-based assertions use a generous margin so they remain stable on loaded - * CI workers; the underlying guarantee is the runtime cap itself. - * * @internal */ #[CoversClass(PregExecutor::class)] diff --git a/tests/Security/RefResolverInfoLeakTest.php b/tests/Security/RefResolverInfoLeakTest.php index 57fd7f3e..6b84bc2f 100644 --- a/tests/Security/RefResolverInfoLeakTest.php +++ b/tests/Security/RefResolverInfoLeakTest.php @@ -15,12 +15,6 @@ use PHPUnit\Framework\TestCase; /** - * P-030 regression: UnresolvableRefException::getMessage() must NOT leak - * the internal reference traversal path. The path is preserved in a - * separate internalTrace property for logging only. A PSR-15 middleware - * that surfaces getMessage() to the client must not disclose internal - * ref names, file paths, or URLs. - * * @internal */ final class RefResolverInfoLeakTest extends TestCase @@ -51,12 +45,12 @@ public function circular_ref_exception_does_not_leak_path(): void self::assertStringNotContainsString( '#/components/schemas/B', $e->getMessage(), - 'getMessage() must not leak the path of the cycle (P-030)', + 'getMessage() must not leak the path of the cycle', ); self::assertStringNotContainsString( ' -> ', $e->getMessage(), - 'getMessage() must not leak the cycle path arrow notation (P-030)', + 'getMessage() must not leak the cycle path arrow notation', ); self::assertNotNull($e->internalTrace(reveal: true)); diff --git a/tests/Security/SecurityE2ETest.php b/tests/Security/SecurityE2ETest.php index 68b68b2d..fae05754 100644 --- a/tests/Security/SecurityE2ETest.php +++ b/tests/Security/SecurityE2ETest.php @@ -175,10 +175,6 @@ protected function setUp(): void $this->psrFactory = new Psr17Factory(); } - /** - * Negative: pattern with catastrophic backtracking must not hang. - * PCRE backtrack limit triggers InvalidPatternException. - */ #[Test] public function redos_pattern_does_not_hang_on_long_input(): void { @@ -199,9 +195,6 @@ public function redos_pattern_does_not_hang_on_long_input(): void $this->assertLessThan(1.0, $elapsed, 'ReDoS-vulnerable pattern must complete within 1 second'); } - /** - * Positive: matching input validates without exception. - */ #[Test] public function redos_pattern_with_matching_input_validates_successfully(): void { @@ -226,16 +219,6 @@ public function redos_pattern_with_matching_input_validates_successfully(): void $this->assertLessThan(1.0, $elapsed, 'Matching pattern must complete within 1 second'); } - /** - * Negative: XXE entity must NOT be expanded — file contents must not leak. - * - * XmlBodyParser uses libxml without LIBXML_NOENT flag, so external - * entities are never substituted. The empty entity reference produces - * null (recursive parser converts empty elements to null), causing - * ValidationException from SchemaValueNormalizer. If XXE protection - * failed and the entity expanded to file content, the keyword would be - * 'maxLength' instead (string passes type check but exceeds maxLength: 0). - */ #[Test] public function xxe_attack_does_not_read_system_files(): void { @@ -306,9 +289,6 @@ public function xxe_attack_does_not_read_system_files(): void } } - /** - * Positive: valid XML without XXE entities validates successfully. - */ #[Test] public function valid_xml_without_xxe_validates_successfully(): void { @@ -333,12 +313,6 @@ public function valid_xml_without_xxe_validates_successfully(): void $this->assertSame('/xml-accept', $operation->path); } - /** - * Negative: a chain of 200+ $ref pointers must throw SchemaDepthExceededException. - * - * RefResolver tracks depth during ref resolution. When depth exceeds - * ValidationContext::MAX_DEPTH (64), SchemaDepthExceededException is thrown. - */ #[Test] public function deep_ref_chain_exceeds_max_depth(): void { @@ -356,12 +330,6 @@ public function deep_ref_chain_exceeds_max_depth(): void $validator->validateRequest($request); } - /** - * Negative: deeply nested JSON data (200+ levels) must fail-closed at the - * JSON parser stage via the Untrusted depth limit, completing in well - * under one second. Before FU-018 the parser used Trusted (512) and the - * validator accepted the deep payload — that was an open DoS vector. - */ #[Test] public function deep_data_nesting_fail_closed_via_json_depth_limit(): void { @@ -396,18 +364,6 @@ public function deep_data_nesting_fail_closed_via_json_depth_limit(): void } } - /** - * Circular $ref (A→B→A) must not cause infinite recursion. - * - * No exception is expected here because the regular schema validator - * resolves only the top-level $ref once during request body validation - * setup and does not recurse into property-level $ref pointers. - * For discriminator-based schemas the context validator does recurse, - * but ValidationContext::MAX_DEPTH (64) and RefResolver's visited-ref - * tracking (UnresolvableRefException on direct circular chains) prevent - * infinite loops. This test confirms shallow data validates successfully - * without hanging. - */ #[Test] public function circular_ref_schema_does_not_cause_infinite_recursion(): void { @@ -438,9 +394,6 @@ public function circular_ref_schema_does_not_cause_infinite_recursion(): void $this->assertLessThan(1.0, $elapsed, 'Circular $ref schema validation must complete within 1 second'); } - /** - * A schema with 1000 enum values must not cause timeout. - */ #[Test] public function huge_enum_in_schema_does_not_cause_timeout(): void { @@ -499,11 +452,6 @@ enum: [{$enumList}] $this->assertLessThan(1.0, $elapsed, 'Huge enum schema must validate within 1 second'); } - /** - * SE-06 Positive: apiKey in cookie with session_id present must pass - * security validation and return the matched operation. The cookie - * value extracted via PSR-7 must match the value supplied. - */ #[Test] public function cookie_api_key_with_session_id_passes_security_validation(): void { @@ -523,12 +471,6 @@ public function cookie_api_key_with_session_id_passes_security_validation(): voi $this->assertSame('/protected', $operation->path); } - /** - * SE-06 Negative: request without the session_id cookie must fail - * security validation with a MissingSecurityCredentialsError wrapped - * in ValidationException. The error must reference the cookie location - * and the expected cookie name. - */ #[Test] public function cookie_api_key_without_session_id_throws_missing_credentials(): void { @@ -556,11 +498,6 @@ public function cookie_api_key_without_session_id_throws_missing_credentials(): } } - /** - * SE-06 Negative: empty session_id cookie must fail security - * validation. The PSR-7 layer returns an empty string, which the - * security validator treats as missing. - */ #[Test] public function cookie_api_key_with_empty_session_id_throws_missing_credentials(): void { @@ -587,11 +524,6 @@ public function cookie_api_key_with_empty_session_id_throws_missing_credentials( } } - /** - * SE-06 Negative: cookie with a different name must not satisfy the - * security scheme. Only the cookie declared in the scheme (session_id) - * is accepted. - */ #[Test] public function cookie_api_key_with_wrong_cookie_name_throws_missing_credentials(): void { @@ -618,11 +550,6 @@ public function cookie_api_key_with_wrong_cookie_name_throws_missing_credentials } } - /** - * SE-06 Default: when enableSecurityValidation() is not called, a - * missing cookie must not trigger any security error. This proves the - * opt-in nature of security validation. - */ #[Test] public function cookie_api_key_skipped_when_security_validation_disabled(): void { @@ -638,10 +565,6 @@ public function cookie_api_key_skipped_when_security_validation_disabled(): void $this->assertSame('/protected', $operation->path); } - /** - * Measures validation time, catching InvalidPatternException which is - * the expected exception when PCRE backtrack limit is triggered. - */ private function measureTime( OpenApiValidator $validator, ServerRequestInterface $request, @@ -656,10 +579,6 @@ private function measureTime( return microtime(true) - $startTime; } - /** - * Generates an OpenAPI spec with a chain of $depth $ref pointers. - * N0 → N1 → N2 → … → N(depth-1) where the last schema is concrete. - */ private function buildDeepRefChainSpec(int $depth): string { $yaml = "openapi: 3.1.0\n" diff --git a/tests/Security/UniqueItemsDoSProtectionTest.php b/tests/Security/UniqueItemsDoSProtectionTest.php index 736ed2d5..6bee2b4d 100644 --- a/tests/Security/UniqueItemsDoSProtectionTest.php +++ b/tests/Security/UniqueItemsDoSProtectionTest.php @@ -21,11 +21,6 @@ use function sprintf; /** - * P-033 regression: ArrayLengthValidator must abort the unique-items - * check after MAX_UNIQUE_CHECK (100000) unique entries with a fail-safe - * TooManyItemsForUniqueCheckError rather than accumulating a hash-table - * of unbounded size on attacker-controlled arrays without maxItems. - * * @internal */ final class UniqueItemsDoSProtectionTest extends TestCase @@ -60,7 +55,7 @@ public function uniqueitems_check_fails_safe_on_one_hundred_thousand_unique_item self::assertNotNull( $caught, - 'ArrayLengthValidator must abort the unique-items check after MAX_UNIQUE_CHECK entries (P-033)', + 'ArrayLengthValidator must abort the unique-items check after MAX_UNIQUE_CHECK entries', ); self::assertLessThan( 50 * 1024 * 1024, diff --git a/tests/Security/XmlBodySizeLimitTest.php b/tests/Security/XmlBodySizeLimitTest.php index 986766cc..33b048cd 100644 --- a/tests/Security/XmlBodySizeLimitTest.php +++ b/tests/Security/XmlBodySizeLimitTest.php @@ -14,12 +14,6 @@ use function str_repeat; /** - * P-036 regression: XmlBodyParser must reject bodies larger than 1MB by - * default to prevent libxml from being asked to ingest unbounded - * payloads. The billion-laughs entity expansion cap is per-entity, not - * per-document, so a document-size cap is a necessary first line of - * defense. - * * @internal */ final class XmlBodySizeLimitTest extends TestCase @@ -45,7 +39,7 @@ public function xml_body_parser_rejects_body_over_one_megabyte(): void self::assertNotNull( $caught, - 'XmlBodyParser must throw BodyTooLargeException on bodies > 1MB (P-036)', + 'XmlBodyParser must throw BodyTooLargeException on bodies > 1MB', ); self::assertSame(1_048_576, $caught->maxBytes); self::assertLessThan( diff --git a/tests/Support/Psr6ArrayCacheStub.php b/tests/Support/Psr6ArrayCacheStub.php index 0fd2e87e..07ade6fe 100644 --- a/tests/Support/Psr6ArrayCacheStub.php +++ b/tests/Support/Psr6ArrayCacheStub.php @@ -57,7 +57,6 @@ public function getItem(string $key): CacheItemInterface /** * @param list $keys - * * @return array */ #[Override] diff --git a/tests/Support/StreamStubHelper.php b/tests/Support/StreamStubHelper.php index 5205c48d..25795b96 100644 --- a/tests/Support/StreamStubHelper.php +++ b/tests/Support/StreamStubHelper.php @@ -12,13 +12,6 @@ use function str_split; use function strlen; -/** - * Stream stub helper for tests that exercise paths relying on the PSR-7 - * streaming read API (getSize / eof / read). PHPUnit createStub() returns - * neutral defaults that defeat chunked reading; this helper wires a stub to - * emit the configured body across 8192-byte chunks, matching BodyReader's - * contract. - */ trait StreamStubHelper { private function configureReadableStream(StreamInterface $stream, string $body): void diff --git a/tests/Unit/Builder/Internal/CacheKeyBuilderTest.php b/tests/Unit/Builder/Internal/CacheKeyBuilderTest.php index c5d8b3c4..069dc175 100644 --- a/tests/Unit/Builder/Internal/CacheKeyBuilderTest.php +++ b/tests/Unit/Builder/Internal/CacheKeyBuilderTest.php @@ -101,7 +101,7 @@ public function for_file_distinct_keys_for_distinct_content_same_path(): void self::assertNotSame( $keyForContentA, $keyForContentB, - 'Same path with different content must yield different cache keys (R3-SEC-003 content-hash fix)', + 'Same path with different content must yield different cache keys (content-hash fix)', ); } finally { $this->safeUnlink($path); @@ -173,7 +173,7 @@ public function max_spec_depth_change_produces_distinct_keys(): void self::assertNotSame( $keyDefault, $keyStrict, - 'maxSpecDepth change must produce a distinct cache key (R4-SEC-008 cache-poisoning defence).', + 'maxSpecDepth change must produce a distinct cache key (cache-poisoning defence).', ); } @@ -186,7 +186,7 @@ public function max_spec_size_change_produces_distinct_keys(): void self::assertNotSame( $keyDefault, $keyStrict, - 'maxSpecSizeBytes change must produce a distinct cache key (R4-SEC-008 cache-poisoning defence).', + 'maxSpecSizeBytes change must produce a distinct cache key (cache-poisoning defence).', ); } @@ -199,7 +199,7 @@ public function external_ref_allowed_root_change_produces_distinct_keys(): void self::assertNotSame( $keyWithoutRoot, $keyWithRoot, - 'externalRefAllowedRoot change must produce a distinct cache key (R4-SEC-008 confinement poisoning defence).', + 'externalRefAllowedRoot change must produce a distinct cache key (confinement poisoning defence).', ); } @@ -212,7 +212,7 @@ public function external_ref_max_bytes_change_produces_distinct_keys(): void self::assertNotSame( $keyDefault, $keyStrict, - 'externalRefMaxBytes change must produce a distinct cache key (R4-SEC-008 cache-poisoning defence).', + 'externalRefMaxBytes change must produce a distinct cache key (cache-poisoning defence).', ); } diff --git a/tests/Unit/Builder/Internal/ExternalRefDetectorTest.php b/tests/Unit/Builder/Internal/ExternalRefDetectorTest.php index 0f0fb13d..a77c0dc9 100644 --- a/tests/Unit/Builder/Internal/ExternalRefDetectorTest.php +++ b/tests/Unit/Builder/Internal/ExternalRefDetectorTest.php @@ -434,9 +434,6 @@ public function assert_confinement_security_anti_test_external_ref_outside_allow $ref: '../../../etc/passwd' YAML; - // The ExternalRefDetector's role is to fail-closed when externalRefAllowedRoot is null. - // When allowedRoot IS set, the FileExternalRefResolver (separate class) enforces the boundary at resolution time. - // This test pins the detector's contract: no allowedRoot + external $ref = exception, regardless of $ref shape. $detectorWithoutRoot = new ExternalRefDetector(new BuilderConfig( specContent: $yaml, specType: 'yaml', diff --git a/tests/Unit/Builder/Internal/SpecLoaderTest.php b/tests/Unit/Builder/Internal/SpecLoaderTest.php index c8b20751..c7948fae 100644 --- a/tests/Unit/Builder/Internal/SpecLoaderTest.php +++ b/tests/Unit/Builder/Internal/SpecLoaderTest.php @@ -251,7 +251,7 @@ public function load_with_distinct_fingerprint_misses_cache(): void cache: $cache, ))->load(); - self::assertSame(2, $pool->writeCount, 'Different parse-config fingerprint must produce cache-miss on the second call (R4-SEC-008).'); + self::assertSame(2, $pool->writeCount, 'Different parse-config fingerprint must produce cache-miss on the second call.'); } #[Test] diff --git a/tests/Unit/Cache/SchemaCacheTest.php b/tests/Unit/Cache/SchemaCacheTest.php index d9ac9043..81f1449c 100644 --- a/tests/Unit/Cache/SchemaCacheTest.php +++ b/tests/Unit/Cache/SchemaCacheTest.php @@ -313,12 +313,6 @@ public function set_uses_default_ttl_when_not_provided(): void $cache->set('test_key', $document); } - /** - * CA-01: Multiple keys are stored and retrieved independently. - * - * Verifies that storing two documents under different keys does not - * interfere — each key retrieves exactly the document stored under it. - */ #[Test] public function multiple_keys_are_stored_and_retrieved_independently(): void { @@ -359,9 +353,6 @@ public function multiple_keys_are_stored_and_retrieved_independently(): void self::assertNotSame($retrieved1, $retrieved2); } - /** - * CA-01: A miss on one key does not affect another key's hit. - */ #[Test] public function miss_on_one_key_does_not_affect_another_key(): void { @@ -395,10 +386,6 @@ public function miss_on_one_key_does_not_affect_another_key(): void self::assertSame($doc, $cache->get('stored_key')); } - /** - * CA-02: Setting the same key twice replaces the previously stored - * document — the second document becomes the one retrieved. - */ #[Test] public function overwrite_same_key_replaces_previous_document(): void { @@ -437,11 +424,6 @@ public function overwrite_same_key_replaces_previous_document(): void self::assertNotSame($docV1, $retrieved); } - /** - * CA-02: SchemaCache itself is a readonly class (immutable wrapper); - * the underlying pool state changes, but no setter exposes mutations - * on the SchemaCache instance. Verify readonly-by-construction. - */ #[Test] public function schema_cache_is_readonly_class(): void { @@ -453,10 +435,6 @@ public function schema_cache_is_readonly_class(): void self::assertTrue($reflection->isReadOnly()); } - /** - * CA-02: Calling set on one SchemaCache instance does not leak into - * another instance built on a different pool. - */ #[Test] public function set_on_one_cache_does_not_affect_other_cache_with_different_pool(): void { @@ -480,9 +458,6 @@ public function set_on_one_cache_does_not_affect_other_cache_with_different_pool } /** - * Build a PHPUnit mock that behaves like an in-memory cache pool backed - * by the given reference array. - * * @param array $storage */ private function buildInMemoryPool(array &$storage): CacheItemPoolInterface diff --git a/tests/Unit/Event/ArrayDispatcherStoppableRegressionTest.php b/tests/Unit/Event/ArrayDispatcherStoppableRegressionTest.php index a6896baf..87446659 100644 --- a/tests/Unit/Event/ArrayDispatcherStoppableRegressionTest.php +++ b/tests/Unit/Event/ArrayDispatcherStoppableRegressionTest.php @@ -16,21 +16,6 @@ use Duyler\OpenApi\Validator\Exception\ValidationException; /** - * Regression suite for R4-PSR-001 / R4-TEST-012: ArrayDispatcher must - * honour PSR-14 StoppableEventInterface by checking - * isPropagationStopped() before every listener invocation (including - * the first) and breaking the loop as soon as propagation is stopped. - * - * Anti-test: removing the `instanceof StoppableEventInterface` check - * (or removing the `break` statement) makes test 1 fail — the second - * listener is invoked even though the first stopped propagation. - * - * Unlike the inline ArrayDispatcherTest that uses anonymous classes in - * isolation, this suite registers listeners on real {@see ValidationStartedEvent}, - * {@see ValidationErrorEvent} and {@see ValidationFinishedEvent} classes - * so the regression also fires when those event classes are mutated to - * drop the StoppableEventInterface contract in custom wrappers. - * * @internal */ final class ArrayDispatcherStoppableRegressionTest extends TestCase @@ -143,10 +128,6 @@ static function () use (&$order): void { } /** - * Minimal stand-alone StoppableEventInterface implementation that lets - * the regression suite pin the PSR-14 contract without depending on - * internal event classes implementing the interface (they do not). - * * @internal */ final class StoppableMarker implements StoppableEventInterface diff --git a/tests/Unit/Registry/SchemaRegistryPrecompiledTest.php b/tests/Unit/Registry/SchemaRegistryPrecompiledTest.php index bc2fd7a7..c2141db8 100644 --- a/tests/Unit/Registry/SchemaRegistryPrecompiledTest.php +++ b/tests/Unit/Registry/SchemaRegistryPrecompiledTest.php @@ -12,14 +12,6 @@ /** * @internal - * - * Anti-test for P-053: asserts that SchemaRegistry precomputes the - * latest-version-per-schema and sorted-versions lists in the - * constructor, so get($name) without a version and getVersions($name) - * are O(1) lookups instead of per-call uksort. Reverting to the lazy - * uksort form removes both private properties, breaking the reflection - * assertions; get() still returns the right document but no longer in - * constant time. */ final class SchemaRegistryPrecompiledTest extends TestCase { diff --git a/tests/Unit/Registry/SchemaRegistryTest.php b/tests/Unit/Registry/SchemaRegistryTest.php index 29ec2115..5f39e6d0 100644 --- a/tests/Unit/Registry/SchemaRegistryTest.php +++ b/tests/Unit/Registry/SchemaRegistryTest.php @@ -427,13 +427,6 @@ public function version_not_found_exception_extends_runtime_exception(): void } } - /** - * RG-02: Pre-release versions follow semver ordering rules. - * - * Per semver 2.0.0 §9-10, pre-release versions have lower precedence - * than the associated normal version: 1.0.0-alpha < 1.0.0-beta < 1.0.0. - * version_compare() in PHP follows the same semantics. - */ #[Test] public function pre_release_versions_sorted_correctly(): void { @@ -457,10 +450,6 @@ public function pre_release_versions_sorted_correctly(): void ); } - /** - * RG-02: get('api') with no version returns the latest non-pre-release - * version (the highest semver), not the highest pre-release. - */ #[Test] public function get_latest_returns_stable_release_over_pre_release(): void { @@ -478,10 +467,6 @@ public function get_latest_returns_stable_release_over_pre_release(): void self::assertNotSame($docAlpha, $latest); } - /** - * RG-02: When only pre-release versions are registered, get('api') - * returns the highest pre-release. - */ #[Test] public function get_latest_returns_highest_pre_release_when_only_pre_releases_registered(): void { @@ -498,9 +483,6 @@ public function get_latest_returns_highest_pre_release_when_only_pre_releases_re self::assertSame($docBeta, $latest); } - /** - * RG-02: Specific pre-release version lookup works by explicit version. - */ #[Test] public function get_specific_pre_release_version(): void { @@ -516,10 +498,6 @@ public function get_specific_pre_release_version(): void self::assertSame($docRc, $registry->get('api', '2.0.0-rc.1')); } - /** - * RG-02: Immutability — registering a pre-release does not mutate - * the original instance. - */ #[Test] public function register_pre_release_returns_new_instance_and_preserves_original(): void { @@ -533,9 +511,6 @@ public function register_pre_release_returns_new_instance_and_preserves_original self::assertTrue($newRegistry->has('api', '1.0.0-alpha')); } - /** - * RG-02: Pre-release mixing with multiple stable versions. - */ #[Test] public function pre_release_mixed_with_multiple_stable_versions(): void { @@ -562,10 +537,6 @@ public function pre_release_mixed_with_multiple_stable_versions(): void self::assertSame(4, $registry->countVersions('api')); } - /** - * RG-03: countVersions returns 0 for a name that has never been - * registered, instead of throwing an exception. - */ #[Test] public function count_versions_returns_zero_for_nonexistent_name(): void { @@ -574,10 +545,6 @@ public function count_versions_returns_zero_for_nonexistent_name(): void self::assertSame(0, $registry->countVersions('nonexistent')); } - /** - * RG-03: countVersions returns 0 for a nonexistent name even when - * other schemas are registered. - */ #[Test] public function count_versions_returns_zero_for_nonexistent_name_when_others_registered(): void { @@ -592,10 +559,6 @@ public function count_versions_returns_zero_for_nonexistent_name_when_others_reg self::assertSame(0, $registry->countVersions('nonexistent')); } - /** - * RG-03: getVersions returns an empty array (not null) for a - * nonexistent name. - */ #[Test] public function get_versions_returns_empty_array_for_nonexistent_name(): void { @@ -606,10 +569,6 @@ public function get_versions_returns_empty_array_for_nonexistent_name(): void self::assertSame([], $versions); } - /** - * RG-03: get('nonexistent') with no version returns null and does - * not throw. - */ #[Test] public function get_returns_null_for_nonexistent_name_with_no_version(): void { diff --git a/tests/Unit/Schema/Model/Internal/BoundSiblingMergerTest.php b/tests/Unit/Schema/Model/Internal/BoundSiblingMergerTest.php index 0423fe54..b64430e4 100644 --- a/tests/Unit/Schema/Model/Internal/BoundSiblingMergerTest.php +++ b/tests/Unit/Schema/Model/Internal/BoundSiblingMergerTest.php @@ -142,8 +142,6 @@ public function merge_schema_or_bool_sibling_true_returns_resolved(): void $overrides = $this->merger->merge(new SiblingMergeContext($resolved, $sibling)); - // §3 fix: `is_bool($sibling) && $sibling` (was: `true === $sibling`) - // Must distinguish true from truthy non-bool (Schema instance is truthy too). self::assertSame($itemSchema, $overrides['items']); } @@ -156,7 +154,6 @@ public function merge_schema_or_bool_resolved_true_returns_sibling(): void $overrides = $this->merger->merge(new SiblingMergeContext($resolved, $sibling)); - // §3 fix: `is_bool($resolved) && $resolved` (was: `true === $resolved`) self::assertSame($itemSchema, $overrides['items']); } @@ -195,7 +192,6 @@ public function merge_schema_or_bool_both_schemas_recursively_merges(): void $merged = $overrides['items']; self::assertInstanceOf(Schema::class, $merged); self::assertSame('string', $merged->type); - // minLength takes stricter (5 > 2) self::assertSame(5, $merged->minLength); } @@ -246,9 +242,7 @@ public function merge_prefix_items_appends_leftover_from_longer_resolved(): void $prefixItems = $overrides['prefixItems']; self::assertCount(2, $prefixItems); - // Index 0 merged recursively (integer ∩ string → null type, but allOf has both) self::assertNotNull($prefixItems[0]->allOf); - // Index 1 appended from resolved (sibling had only 1) self::assertSame($resolvedSecond, $prefixItems[1]); } diff --git a/tests/Unit/Schema/Model/Internal/CompositionSiblingMergerTest.php b/tests/Unit/Schema/Model/Internal/CompositionSiblingMergerTest.php index fd7a5b9f..1aa2df34 100644 --- a/tests/Unit/Schema/Model/Internal/CompositionSiblingMergerTest.php +++ b/tests/Unit/Schema/Model/Internal/CompositionSiblingMergerTest.php @@ -58,9 +58,7 @@ public function merge_any_of_wraps_in_all_of_when_both_set(): void $overrides = $this->merger->merge(new SiblingMergeContext($resolved, $sibling)); - // anyOf becomes null when both sides set (deferred to allOf as wrapped composition) self::assertNull($overrides['anyOf']); - // allOf contains 2 wrapper schemas, each carrying its own anyOf list self::assertCount(2, $overrides['allOf']); self::assertSame([$resolvedA, $resolvedB], $overrides['allOf'][0]->anyOf); self::assertSame([$siblingC, $siblingD], $overrides['allOf'][1]->anyOf); @@ -158,7 +156,6 @@ public function merge_if_then_else_wraps_when_both_sides_set(): void $overrides = $this->merger->merge(new SiblingMergeContext($resolved, $sibling)); - // When both sides have if/then/else, fields are cleared and contributions go to allOf self::assertNull($overrides['if']); self::assertNull($overrides['then']); self::assertNull($overrides['else']); @@ -220,9 +217,6 @@ public function merge_dependent_schemas_concatenates(): void #[Test] public function merge_scalar_additions_appended_to_all_of_when_types_conflict(): void { - // resolved has type=string, sibling has type=integer → unmergeable types - // plus resolved has pattern=^a, sibling pattern=^b → unmergeable patterns - // All four should appear as separate allOf entries $resolved = new Schema(type: 'string', format: 'date-time', pattern: '^a', multipleOf: 2.0); $sibling = new Schema(type: 'integer', format: 'uuid', pattern: '^b', multipleOf: 3.0); @@ -230,7 +224,6 @@ public function merge_scalar_additions_appended_to_all_of_when_types_conflict(): $allOf = $overrides['allOf']; self::assertNotNull($allOf); - // 6 contributions: 2 type + 2 format + 2 multipleOf + 2 pattern = 8 (multipleOf+pattern via scalarMerger) self::assertCount(8, $allOf); } diff --git a/tests/Unit/Schema/Model/Internal/ScalarSiblingMergerTest.php b/tests/Unit/Schema/Model/Internal/ScalarSiblingMergerTest.php index ffde9496..13eb3af6 100644 --- a/tests/Unit/Schema/Model/Internal/ScalarSiblingMergerTest.php +++ b/tests/Unit/Schema/Model/Internal/ScalarSiblingMergerTest.php @@ -24,7 +24,6 @@ public function merge_returns_overrides_for_eight_scalar_fields(): void self::assertSame('string', $overrides['type']); self::assertSame('date-time', $overrides['format']); - // pattern: resolved has it, sibling does not → mergeNullableIdentical returns resolved value self::assertSame('^a', $overrides['pattern']); self::assertTrue($overrides['nullable']); self::assertFalse($overrides['hasConst']); @@ -140,8 +139,6 @@ public function merge_enum_uses_json_equals_intersection(): void $overrides = new ScalarSiblingMerger()->merge(new SiblingMergeContext($resolved, $sibling)); - // JSON equality: 1 === true is NOT equal in JsonEquals (different types). - // True (bool) is equal in both. So intersection is [1, true]. self::assertCount(2, $overrides['enum']); } diff --git a/tests/Unit/Schema/Model/SchemaConstraintGroupsTest.php b/tests/Unit/Schema/Model/SchemaConstraintGroupsTest.php index b628543e..8f9629ba 100644 --- a/tests/Unit/Schema/Model/SchemaConstraintGroupsTest.php +++ b/tests/Unit/Schema/Model/SchemaConstraintGroupsTest.php @@ -14,14 +14,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -/** - * Pins the named-constructor contract introduced in task 11b §10 - * (see `.ai/reports/adr-schema-constructor.md`). - * - * `Schema::fromConstraintGroups()` and `Schema::withOverrideGroups()` wrap the - * deprecated 57-parameter {@see Schema::__construct()} / {@see Schema::withOverrides()} - * behind 4 typed value-objects plus an explicit `nullable` modifier. - */ #[CoversClass(Schema::class)] final class SchemaConstraintGroupsTest extends TestCase { @@ -279,7 +271,6 @@ public function from_constraint_groups_equivalent_to_legacy_constructor(): void nullable: false, ); - // Field-for-field equivalent (but distinct immutable instances). self::assertNotSame($viaLegacy, $viaGroups); self::assertSame($viaLegacy->type, $viaGroups->type); self::assertSame($viaLegacy->title, $viaGroups->title); @@ -443,7 +434,6 @@ public function with_override_groups_overrides_composition_fields(): void ); self::assertSame($newOneOf, $result->oneOf); - // Original anyOf is preserved (null in the override group means "keep"). self::assertNotNull($result->anyOf); } } diff --git a/tests/Unit/Schema/Model/SchemaWithOverridesTest.php b/tests/Unit/Schema/Model/SchemaWithOverridesTest.php index 355e4fb7..671ebaff 100644 --- a/tests/Unit/Schema/Model/SchemaWithOverridesTest.php +++ b/tests/Unit/Schema/Model/SchemaWithOverridesTest.php @@ -11,15 +11,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -/** - * Pins the override-where-not-null contract of {@see Schema::withOverrides()}. - * - * `withOverrides` uses `$arg ?? $this->arg`, so for nullable parameters a - * passed `null` means "keep the original", while a non-null value replaces it. - * For booleans (typed `?bool` in withOverrides vs `bool` in __construct), an - * explicit `false` IS an override, not a fallback — this is the only way to - * flip a `true` back to `false` on an immutable DTO. - */ #[CoversClass(Schema::class)] final class SchemaWithOverridesTest extends TestCase { @@ -39,7 +30,6 @@ public function with_overrides_no_args_returns_equivalent_schema(): void $result = $original->withOverrides(); - // Equivalent field-for-field — but a distinct immutable instance. self::assertNotSame($original, $result); self::assertSame('object', $result->type); self::assertSame('User', $result->title); @@ -67,7 +57,6 @@ public function with_overrides_null_keeps_original_for_nullable_scalar(): void { $original = new Schema(type: 'string', title: 'Keep', pattern: '^[a-z]+$'); - // Explicit null on a nullable parameter means "no override". $result = $original->withOverrides(type: null, title: null, pattern: null); self::assertSame('string', $result->type); @@ -78,9 +67,6 @@ public function with_overrides_null_keeps_original_for_nullable_scalar(): void #[Test] public function with_overrides_false_flips_boolean_back_to_false(): void { - // Adversarial guard: `false ?? $this->x` evaluates to `false`, NOT to - // `$this->x`. If anyone "simplifies" withOverrides to use - // `func_get_args` or argument-count checks, this test catches it. $original = new Schema( deprecated: true, readOnly: true, @@ -119,7 +105,6 @@ public function with_overrides_null_keeps_true_boolean(): void nullable: true, ); - // null on ?bool means "no override" — `true` survives. $result = $original->withOverrides( deprecated: null, readOnly: null, @@ -221,10 +206,6 @@ public function with_overrides_replaces_discriminator_and_xml(): void #[Test] public function with_overrides_null_keeps_original_for_default_and_const(): void { - // Adversarial guard: even though `default` and `const` accept `null` - // as a valid value at construction, withOverrides uses `$x ?? $this->x`, - // and `??` treats null as "no override" regardless of parameter type. - // This pins the uniform ?? semantics: null never overrides. $original = new Schema( type: 'string', default: 'keep-default', @@ -250,7 +231,6 @@ public function with_overrides_replaces_default_with_explicit_value(): void hasDefault: true, ); - // A non-null value overrides, including empty string / empty array. $result = $original->withOverrides(default: '', hasDefault: false); self::assertSame('', $result->default); diff --git a/tests/Unit/Schema/Parser/Internal/InlineExampleResolverTest.php b/tests/Unit/Schema/Parser/Internal/InlineExampleResolverTest.php index f23a30d3..cb7d524a 100644 --- a/tests/Unit/Schema/Parser/Internal/InlineExampleResolverTest.php +++ b/tests/Unit/Schema/Parser/Internal/InlineExampleResolverTest.php @@ -157,7 +157,6 @@ public static function scalar_example_provider(): array /** * @param array $data - * * @return int|float|bool|string|array|null|stdClass|class-string */ private function mediaTypeOutcome(array $data): mixed @@ -171,7 +170,6 @@ private function mediaTypeOutcome(array $data): mixed /** * @param array $data - * * @return int|float|bool|string|array|null|stdClass|class-string */ private function parameterOutcome(array $data): mixed diff --git a/tests/Unit/Validator/Coercion/AbstractCoercerTest.php b/tests/Unit/Validator/Coercion/AbstractCoercerTest.php index 229597c2..4a435e97 100644 --- a/tests/Unit/Validator/Coercion/AbstractCoercerTest.php +++ b/tests/Unit/Validator/Coercion/AbstractCoercerTest.php @@ -491,15 +491,6 @@ public function coerce_to_string_returns_unknown_as_is(): void $this->assertSame([], $this->coercer->exposedCoerceToString([])); } - /** - * Anti-test: to verify this test guards against regression, temporarily - * remove the overflow check ($value > PHP_INT_MAX || $value < PHP_INT_MIN) - * in AbstractCoercer::coerceToInteger(). Without the guard, (int) 1e20 - * triggers a PHP deprecation notice ("not representable as int") and - * returns platform-dependent undefined behavior (commonly 0 or - * 7766279631452241920) instead of throwing TypeMismatchError. The same - * regression disables coerce_to_integer_throws_on_float_overflow_below_int_min. - */ #[Test] public function coerce_to_integer_throws_on_float_overflow_above_int_max(): void { @@ -518,19 +509,6 @@ public function coerce_to_integer_throws_on_float_overflow_below_int_min(): void $this->coercer->exposedCoerceToInteger(-1.0E+20); } - /** - * Anti-test: to verify this test guards against regression, temporarily - * restore the previous guard ($value > PHP_INT_MAX || $value < PHP_INT_MIN) - * in AbstractCoercer::coerceToInteger(). The previous float-vs-int - * comparison missed the bypass double (float) PHP_INT_MAX = - * 9223372036854775808.0 (= PHP_INT_MAX + 1) because PHP implicitly - * coerces PHP_INT_MAX to the same float, leaving `$value > PHP_INT_MAX` - * false at the boundary. The subsequent (int) cast then wrapped around - * to a non-int64 value with a PHP 8.4 deprecation warning (PHP 9.0 - * promotes this to TypeError). The same regression disables - * coerce_to_integer_rejects_float_just_below_php_int_max and - * coerce_to_integer_rejects_float_just_above_php_int_min. - */ #[Test] public function coerce_to_integer_rejects_float_at_php_int_max_boundary(): void { @@ -569,10 +547,6 @@ public function coerce_to_integer_accepts_whole_float_in_safe_range(): void #[Test] public function coerce_to_integer_accepts_large_whole_float_within_range(): void { - // 2^50 = 1125899906842624 is exactly representable as a double and - // well within int64 range. PHP_INT_MAX itself rounds to PHP_INT_MAX+1 - // when cast to float, so the int boundary is not exactly testable - // through float. $value = (float) (2 ** 50); $result = $this->coercer->exposedCoerceToInteger($value); @@ -598,14 +572,6 @@ public function coerce_to_integer_accepts_small_whole_float(): void $this->assertSame(42, $result); } - /** - * Anti-test for R4-SPEC-005: to verify this test guards against regression, - * temporarily restore the unconditional `is_float($value)` rejection in - * AbstractCoercer::coerceToIntegerStrict(). Without the JSON Schema 2020-12 - * §4.2.3 fix, a whole-valued float like 3.0 is rejected even though the - * runtime TypeValidator accepts it (asymmetric behavior between coercion - * enabled and coercion disabled). - */ #[Test] public function coerce_to_integer_strict_accepts_whole_float_3_0(): void { @@ -674,14 +640,6 @@ public function coerce_to_integer_strict_rejects_nan_with_reason(): void } } - /** - * Anti-test for R4-SPEC-005 safe-integer-range guard: 2^53 + 1 - * (9007199254740993.0) is silently rounded to 2^53 by IEEE-754 double - * precision, so fmod($value, 1.0) === 0.0 even though the value is no - * longer exactly representable. Without the |value| < 2^53 guard, the - * strict coercion would silently truncate 9007199254740993.0 to - * 9007199254740992 with no diagnostic. - */ #[Test] public function coerce_to_integer_strict_rejects_unsafe_whole_float_above_2_pow_53(): void { @@ -718,14 +676,6 @@ public function coerce_to_integer_strict_rejects_negative_unsafe_whole_float(): } } - /** - * Anti-test for R4-SEC-013 (strict variant): without the floatExceedsInt64Range - * guard in coerceToIntegerStrict, a whole-valued float that lands below the - * 2^53 safe-range check but exceeds int64 (e.g. (float) PHP_INT_MAX, which - * is 9223372036854775808.0 = PHP_INT_MAX + 1 due to IEEE-754 rounding) - * would be cast through (int) and wrap around to a negative int with a - * PHP 8.5 deprecation notice (TypeError in 9.0). - */ #[Test] public function coerce_to_integer_strict_rejects_float_at_php_int_max_boundary(): void { diff --git a/tests/Unit/Validator/Coercion/IntegerStringNormalizerTest.php b/tests/Unit/Validator/Coercion/IntegerStringNormalizerTest.php index 3a6df2c5..89020787 100644 --- a/tests/Unit/Validator/Coercion/IntegerStringNormalizerTest.php +++ b/tests/Unit/Validator/Coercion/IntegerStringNormalizerTest.php @@ -47,9 +47,6 @@ public function canonicalize_returns_expected_form(string $input, string $expect #[Test] public function canonicalize_round_trips_in_int64_range(): void { - // The SEC-15 contract: for any value matching /^[+-]?\d+$/ inside the - // int64 range, canonicalize($v) must equal (string) (int) $v. Equality - // is what AbstractCoercer relies on to accept the coerced int. foreach (['0', '42', '-42', '+42', '00042', (string) PHP_INT_MAX, (string) PHP_INT_MIN] as $value) { $this->assertSame( (string) (int) $value, @@ -62,9 +59,6 @@ public function canonicalize_round_trips_in_int64_range(): void #[Test] public function canonicalize_differs_from_cast_for_overflow(): void { - // The SEC-15 contract: a value outside int64 range canonicalizes to - // its literal form, which MUST differ from the (int)-cast string so - // AbstractCoercer can detect overflow and bail out. foreach (['99999999999999999999', '-99999999999999999999', '9223372036854775808'] as $value) { $this->assertNotSame( (string) (int) $value, diff --git a/tests/Unit/Validator/Coercion/NumberStringNormalizerTest.php b/tests/Unit/Validator/Coercion/NumberStringNormalizerTest.php index 1b7c10e0..87a52812 100644 --- a/tests/Unit/Validator/Coercion/NumberStringNormalizerTest.php +++ b/tests/Unit/Validator/Coercion/NumberStringNormalizerTest.php @@ -170,7 +170,6 @@ public function cast_string_to_float_returns_float_for_scientific_big_exponent() #[Test] public function cast_string_to_float_returns_float_for_representable_scientific_at_boundary(): void { - // 1e308 is representable (PHP_FLOAT_MAX ~ 1.8e308); exponent 308 < 320 DoS bound. $this->assertSame(1.0E+308, NumberStringNormalizer::castStringToFloatOrFail('1e308')); } @@ -194,25 +193,12 @@ public function cast_string_to_float_throws_on_negative_exponent_above_320(): vo #[Test] public function cast_string_to_float_rejects_at_exponent_boundary_320_with_inf_reason(): void { - // Exponent 320 does not trip the DoS guard (abs($exponent) > 320), but - // (float) '1e320' overflows the IEEE-754 double range to INF. R4-SEC-014: - // the explicit is_infinite check rejects the value with an informative - // 'overflows IEEE-754 double range (INF)' reason instead of relying on - // the misleading 'loses precision' path. $this->expectException(TypeMismatchError::class); $this->expectExceptionMessage('Numeric value overflows IEEE-754 double range (INF)'); NumberStringNormalizer::castStringToFloatOrFail('1e320'); } - /** - * Anti-test: to verify this test guards against regression, temporarily - * remove the is_infinite check after `(float) $value` in - * NumberStringNormalizer::castStringToFloatOrFail(). Without the guard, - * '1e309' overflows to INF and the precision-loss canonicalize path - * returns a misleading 'String value loses precision when converted to - * float' message that hides the actual INF overflow. - */ #[Test] public function cast_string_to_float_rejects_1e309_with_inf_reason(): void { @@ -289,9 +275,6 @@ public function cast_string_to_float_throws_on_php_int_max_string_precision_loss { $this->expectException(TypeMismatchError::class); - // PHP_INT_MAX as a string loses precision when cast to float: the round-trip - // canonical form differs (...807 → ...808) because IEEE-754 cannot represent - // 19 significant decimal digits. NumberStringNormalizer::castStringToFloatOrFail((string) PHP_INT_MAX); } @@ -309,11 +292,6 @@ public function cast_string_to_float_propagates_data_path_in_dos_exception(): vo #[Test] public function cast_string_to_float_passes_nan_string_through_as_zero(): void { - // 'NaN' does not match NUMBER_PATTERN, so canonicalize returns null and the - // precision-loss check is skipped. PHP 8.5's (float) cast of a non-numeric - // string yields 0.0 (deprecation-grade behavior). Locking the pass-through - // contract: this layer defends against precision loss on numeric strings, - // not against non-numeric input. Callers filter non-numeric strings upstream. $this->assertSame(0.0, NumberStringNormalizer::castStringToFloatOrFail('NaN')); } diff --git a/tests/Unit/Validator/Error/Formatter/FormatExceptionTest.php b/tests/Unit/Validator/Error/Formatter/FormatExceptionTest.php index 75094d9f..28f65edb 100644 --- a/tests/Unit/Validator/Error/Formatter/FormatExceptionTest.php +++ b/tests/Unit/Validator/Error/Formatter/FormatExceptionTest.php @@ -49,7 +49,6 @@ public function detailed_formatter_formats_exception(): void self::assertStringContainsString('Value must be a valid email address', $result); self::assertStringContainsString('email', $result); - // Default formatter must NOT expose the raw input value (SEC-06). self::assertStringNotContainsString('not-an-email', $result); } diff --git a/tests/Unit/Validator/Error/Internal/ValidationContextInitTest.php b/tests/Unit/Validator/Error/Internal/ValidationContextInitTest.php index bc7ead76..be029628 100644 --- a/tests/Unit/Validator/Error/Internal/ValidationContextInitTest.php +++ b/tests/Unit/Validator/Error/Internal/ValidationContextInitTest.php @@ -75,8 +75,6 @@ public function from_init_yields_equivalent_state_to_create_static_constructor() ), ); - // Equivalence: same field values as the deprecated create() - // (depth defaults to 0 in both paths, breadcrumbs are independent instances) self::assertSame($pool, $viaInit->pool); self::assertSame($formatter, $viaInit->errorFormatter); self::assertFalse($viaInit->nullableAsType); diff --git a/tests/Unit/Validator/Exception/InvalidMultipleOfSchemaExceptionTest.php b/tests/Unit/Validator/Exception/InvalidMultipleOfSchemaExceptionTest.php index 225f29b2..28770869 100644 --- a/tests/Unit/Validator/Exception/InvalidMultipleOfSchemaExceptionTest.php +++ b/tests/Unit/Validator/Exception/InvalidMultipleOfSchemaExceptionTest.php @@ -15,14 +15,6 @@ #[CoversClass(InvalidMultipleOfSchemaException::class)] final class InvalidMultipleOfSchemaExceptionTest extends TestCase { - /** - * Pins the deprecated BC factory retained since R4-CORRECTNESS-008. - * NumericRangeValidator no longer throws it; the factory survives only - * for external callers and will be removed in 2.0. The PHP 8.4 - * #[Deprecated] attribute emits E_DEPRECATED at the call site; the - * IgnoreDeprecations attribute keeps the pinned BC contract out of the - * suite-wide deprecation count so pipelines stay green. - */ #[Test] #[IgnoreDeprecations] public function deprecated_factory_for_large_integer_without_bcmath_includes_both_arguments_in_message(): void diff --git a/tests/Unit/Validator/Format/Numeric/FloatDoubleValidatorTest.php b/tests/Unit/Validator/Format/Numeric/FloatDoubleValidatorTest.php index 6474d761..53e6850d 100644 --- a/tests/Unit/Validator/Format/Numeric/FloatDoubleValidatorTest.php +++ b/tests/Unit/Validator/Format/Numeric/FloatDoubleValidatorTest.php @@ -88,11 +88,6 @@ public function throw_exception_for_invalid_format(): void } /** - * Special IEEE 754 float values: INF, -INF, NAN. - * - * JSON (RFC 8259 §6) does not support non-finite or NaN values, so the - * validator must reject them even though they are of type float in PHP. - * * @return array */ public static function specialFloatValuesProvider(): array diff --git a/tests/Unit/Validator/Format/String/DurationValidatorTest.php b/tests/Unit/Validator/Format/String/DurationValidatorTest.php index 329521ed..6f1c651c 100644 --- a/tests/Unit/Validator/Format/String/DurationValidatorTest.php +++ b/tests/Unit/Validator/Format/String/DurationValidatorTest.php @@ -204,10 +204,6 @@ public function rejects_weeks_without_number(): void } /** - * Weeks (W designator) edge cases per ISO 8601: the W designator is an - * alternative to Y/M/D + H/M/S. Weeks are exclusive — they cannot be - * combined with any other component. - * * @return array */ public static function weeksEdgeCasesProvider(): array diff --git a/tests/Unit/Validator/Format/String/EmailValidatorTest.php b/tests/Unit/Validator/Format/String/EmailValidatorTest.php index c9126d7e..5616299b 100644 --- a/tests/Unit/Validator/Format/String/EmailValidatorTest.php +++ b/tests/Unit/Validator/Format/String/EmailValidatorTest.php @@ -253,10 +253,6 @@ public function empty_string_email_rejection_carries_format_name_and_value(): vo } /** - * Email edge cases across the three validation layers: EMAIL_PATTERN - * regex (named groups local/domain, TLD >= 2), MAX_EMAIL=254 length cap, - * and filter_var as the final defence layer. - * * @return array */ public static function emailEdgeCasesProvider(): array @@ -285,9 +281,6 @@ public static function emailEdgeCasesProvider(): array #[Test] public function email_edge_cases_match_expected_result(string $email, bool $expectedValid): void { - // SMTPUTF8 addresses require ext-intl for IDNA conversion; without it - // the validator falls back to a permissive regex that may diverge from - // the expected result for non-ASCII inputs. if (!extension_loaded('intl') && 1 === preg_match('/[\x80-\xff]/', $email)) { self::markTestSkipped('ext-intl required for SMTPUTF8 (RFC 6531) validation'); } diff --git a/tests/Unit/Validator/Format/String/UriValidatorTest.php b/tests/Unit/Validator/Format/String/UriValidatorTest.php index c33fe302..c7f0e571 100644 --- a/tests/Unit/Validator/Format/String/UriValidatorTest.php +++ b/tests/Unit/Validator/Format/String/UriValidatorTest.php @@ -117,14 +117,6 @@ public function relative_path_uri_is_rejected(): void $this->validator->validate($uri); } - /** - * RFC 3986 §3 allows an empty reg-name in the authority, so an - * `http:///path` triple-slash URI is a syntactically valid URI - * even though the host is empty. The validator no longer rejects - * this shape; it accepts it per RFC 3986 generic syntax. The - * previous rejection was a side effect of the now-removed - * `filter_var(FILTER_VALIDATE_URL)` fallback. - */ #[Test] public function triple_slash_authority_is_valid_per_rfc_3986(): void { @@ -132,14 +124,6 @@ public function triple_slash_authority_is_valid_per_rfc_3986(): void $this->validator->validate('http:///example.com'); } - /** - * RFC 3986 §3.3 `path-rootless = segment-nz-nc *( "/" segment )` - * admits `(` and `)` via `sub-delims`, so `javascript:alert(1)` - * is a syntactically valid URI. Per JSON Schema 2020-12 §7.3.1 - * the `uri` format validates RFC 3986 generic syntax only; - * scheme-specific allowlisting is the application's responsibility - * (handled at the consumer layer, not the format validator). - */ #[Test] public function javascript_scheme_uri_is_valid_per_rfc_3986(): void { @@ -147,14 +131,6 @@ public function javascript_scheme_uri_is_valid_per_rfc_3986(): void $this->validator->validate('javascript:alert(1)'); } - /** - * RFC 3986 host reg-name permits non-ASCII characters; the - * validator accepts IDN hosts per RFC 3986 generic syntax. The - * previous `filter_var(FILTER_VALIDATE_URL)` fallback rejected - * bare UTF-8 hosts without Punycode conversion; that fallback - * has been removed (Task 10, Variant A). IDN-to-ASCII Punycode - * conversion remains explicitly out of scope. - */ #[Test] public function idn_host_uri_accepted_per_rfc_3986(): void { @@ -275,11 +251,6 @@ public function uri_without_colon_is_rejected(): void $this->validator->validate($uri); } - /** - * S-021: port-range error message must NOT interpolate the - * attacker-supplied port value or any other attacker-derived - * fragment (CWE-209). - */ #[Test] public function port_out_of_range_rejected_with_generic_message(): void { @@ -297,11 +268,6 @@ public function port_out_of_range_rejected_with_generic_message(): void $this->assertStringNotContainsString('99999', $exception->getMessage()); } - /** - * S-021: even when the attacker controls the scheme AND the port, - * the error message must not echo either back. The validator - * must use a generic message verbatim. - */ #[Test] public function error_message_does_not_disclose_scheme_in_port_range_error(): void { @@ -319,14 +285,12 @@ public function error_message_does_not_disclose_scheme_in_port_range_error(): vo $this->assertStringNotContainsString( 'javascript', $exception->getMessage(), - 'getMessage() must not disclose attacker-supplied scheme (S-021, CWE-209).', + 'getMessage() must not disclose attacker-supplied scheme (CWE-209).', ); $this->assertStringNotContainsString('99999', $exception->getMessage()); } /** - * URI edge cases across all four RFC 3986 §3 hier-part forms. - * * @return array */ public static function uriEdgeCasesProvider(): array diff --git a/tests/Unit/Validator/Format/String/UuidValidatorTest.php b/tests/Unit/Validator/Format/String/UuidValidatorTest.php index 8bfe8ddb..1330851e 100644 --- a/tests/Unit/Validator/Format/String/UuidValidatorTest.php +++ b/tests/Unit/Validator/Format/String/UuidValidatorTest.php @@ -216,11 +216,6 @@ public function uuid_short_string_is_rejected(): void } /** - * RFC 4122 + RFC 9562 (2024) UUID versions 1-8 are accepted by the - * validator regex `[1-8]` for the version nibble and `[89abAB]` for the - * variant nibble. Special UUIDs (nil per RFC 4122 §4.1.7 and max per RFC - * 9562 §5.4) are validated explicitly before applying the regex. - * * @return array */ public static function uuidVersionsAndSpecialCasesProvider(): array diff --git a/tests/Unit/Validator/LibxmlSecuredContextTest.php b/tests/Unit/Validator/LibxmlSecuredContextTest.php index 64332dd6..b68d93f3 100644 --- a/tests/Unit/Validator/LibxmlSecuredContextTest.php +++ b/tests/Unit/Validator/LibxmlSecuredContextTest.php @@ -60,11 +60,6 @@ public function run_restores_libxml_internal_errors_when_work_throws(): void self::assertFalse(libxml_use_internal_errors()); } - /** - * Integration: LibxmlSecuredContext + simplexml_load_string must block - * XXE file:// resolution. The deny-all loader installed by the helper - * is the invariant guard against external entity substitution. - */ #[Test] public function run_blocks_xxe_file_resolution(): void { diff --git a/tests/Unit/Validator/Link/Internal/LinkContextFromGroupsTest.php b/tests/Unit/Validator/Link/Internal/LinkContextFromGroupsTest.php index fec26996..8b9bb70e 100644 --- a/tests/Unit/Validator/Link/Internal/LinkContextFromGroupsTest.php +++ b/tests/Unit/Validator/Link/Internal/LinkContextFromGroupsTest.php @@ -35,13 +35,11 @@ public function from_groups_distributes_request_and_response_fields(): void $context = LinkContext::fromGroups($request, $response); - // Response scope self::assertSame(['id' => 42, 'name' => 'John'], $context->body); self::assertSame(['X-Total' => '1'], $context->headers); self::assertSame(['page' => 1], $context->queryParams); self::assertSame(200, $context->statusCode); - // Request scope self::assertSame('https://api.example.com/users/42', $context->url); self::assertSame('GET', $context->method); self::assertSame(['userId' => 42], $context->pathParams); @@ -84,7 +82,6 @@ public function from_groups_is_equivalent_to_constructor_named_args(): void pathParams: ['k' => 'v'], ); - // Equivalent across all fields (queryParams empty-by-default in both) self::assertSame($viaCtor->body, $viaGroups->body); self::assertSame($viaCtor->statusCode, $viaGroups->statusCode); self::assertSame($viaCtor->url, $viaGroups->url); diff --git a/tests/Unit/Validator/Request/BodyParser/XmlBodyParserTest.php b/tests/Unit/Validator/Request/BodyParser/XmlBodyParserTest.php index 45e0a16b..171451cc 100644 --- a/tests/Unit/Validator/Request/BodyParser/XmlBodyParserTest.php +++ b/tests/Unit/Validator/Request/BodyParser/XmlBodyParserTest.php @@ -506,14 +506,6 @@ public function libxml_internal_errors_state_restored_after_parse(): void $this->assertFalse(libxml_use_internal_errors()); } - /** - * Defense-in-depth anti-test: proves that the deny-all external entity - * loader blocks file:// resolution even if a future commit accidentally - * adds LIBXML_NOENT to PARSE_OPTIONS. Without LIBXML_NOENT XXE is - * already blocked by simplexml_load_string semantics; this test - * demonstrates that the loader itself is the invariant guard, so the - * protection no longer relies solely on the absence of a flag. - */ #[Test] public function deny_all_loader_blocks_file_resolution_even_with_noent_flag(): void { diff --git a/tests/Unit/Validator/Request/HeaderFinderTest.php b/tests/Unit/Validator/Request/HeaderFinderTest.php index e52c366b..ee1e4bf6 100644 --- a/tests/Unit/Validator/Request/HeaderFinderTest.php +++ b/tests/Unit/Validator/Request/HeaderFinderTest.php @@ -36,12 +36,6 @@ public function find_existing_header_as_array(): void self::assertSame('application/json,application/xml', $result); } - /** - * P-015: RFC 9110 §5.2 — multiple field lines with the same name are - * equivalent to a single line whose values are joined by a comma - * WITHOUT a space, so the merged value round-trips correctly through - * simple/pipeDelimited style explode which splits on the bare comma. - */ #[Test] public function merges_multi_value_headers_with_comma_no_space(): void { diff --git a/tests/Unit/Validator/Request/ParameterDeserializerExplodeLimitTest.php b/tests/Unit/Validator/Request/ParameterDeserializerExplodeLimitTest.php index 310debe9..cbada83c 100644 --- a/tests/Unit/Validator/Request/ParameterDeserializerExplodeLimitTest.php +++ b/tests/Unit/Validator/Request/ParameterDeserializerExplodeLimitTest.php @@ -100,9 +100,6 @@ public function simple_style_normal_comma_count_accepted(): void #[Test] public function matrix_style_explode_true_large_count_rejected(): void { - // Matrix explode=true uses the repeated-name separator ';tags=' which - // flows through splitBySeparator. Pins DoS guard on a path not - // previously exercised by the form/pipe/space/simple test set. $value = ';tags=a' . str_repeat(';tags=a', 1000); $this->expectException(InvalidParameterException::class); @@ -116,8 +113,6 @@ public function matrix_style_explode_true_large_count_rejected(): void #[Test] public function label_style_explode_true_large_count_rejected(): void { - // Label explode=true uses '.' as the separator (also via - // splitBySeparator). Pins DoS guard on the dot-separated path. $value = '.a' . str_repeat('.a', 1000); $this->expectException(InvalidParameterException::class); diff --git a/tests/Unit/Validator/Request/PathRegexCacheTest.php b/tests/Unit/Validator/Request/PathRegexCacheTest.php index 78b39ef1..b29bff45 100644 --- a/tests/Unit/Validator/Request/PathRegexCacheTest.php +++ b/tests/Unit/Validator/Request/PathRegexCacheTest.php @@ -365,10 +365,6 @@ public function custom_max_size_respected(): void self::assertSame(['/b/{x}'], $this->cacheKeys($cache)); } - /** - * P-008: RFC 6570 §2.3 permits the dot inside a variable name, so - * `/users/{user.id}` must compile without throwing. - */ #[Test] public function accepts_dot_in_path_parameter_name(): void { @@ -378,11 +374,6 @@ public function accepts_dot_in_path_parameter_name(): void self::assertSame(0, preg_match($regex, '/users/42/details')); } - /** - * P-008: The captured value is accessible via a named group. PCRE forbids - * the dot in subpattern names, so the group name is the varname with dots - * replaced by underscores. - */ #[Test] public function extracts_dot_dotted_parameter_value(): void { @@ -394,10 +385,6 @@ public function extracts_dot_dotted_parameter_value(): void self::assertSame('42', $matches['user_id']); } - /** - * P-008: Dotted varnames must also work with the RFC 6570 Level 2 - * reserved-expansion operator `{+name}`. - */ #[Test] public function accepts_dot_in_reserved_expansion_varname(): void { @@ -410,10 +397,6 @@ public function accepts_dot_in_reserved_expansion_varname(): void self::assertSame('img/logo.png', $matches['asset_id']); } - /** - * P-008: Multiple dotted varnames in the same template must capture - * independently into distinct underscore-named groups. - */ #[Test] public function multiple_dot_dotted_placeholders_capture_independently(): void { diff --git a/tests/Unit/Validator/Request/QueryParserTest.php b/tests/Unit/Validator/Request/QueryParserTest.php index 80bdfe54..46c297eb 100644 --- a/tests/Unit/Validator/Request/QueryParserTest.php +++ b/tests/Unit/Validator/Request/QueryParserTest.php @@ -271,11 +271,6 @@ public function parse_deeply_nested_key_above_max_depth_throws_exception(): void #[Test] public function parse_key_with_unclosed_brackets_above_max_depth_throws_exception(): void { - // 65 '[' chars with zero ']' would yield a single-segment parse - // (preg_match_all finds no valid [key] pairs, segments = ['a']), - // so the segment-count guard cannot fire. The raw substr_count - // guard in insertNested is the only defence against this vector - // and must reject the input outright. $key = 'a' . str_repeat('[', 65); $this->expectException(InvalidParameterException::class); diff --git a/tests/Unit/Validator/Response/ResponseBodyValidatorWithContextTest.php b/tests/Unit/Validator/Response/ResponseBodyValidatorWithContextTest.php index 006af5e0..0693324c 100644 --- a/tests/Unit/Validator/Response/ResponseBodyValidatorWithContextTest.php +++ b/tests/Unit/Validator/Response/ResponseBodyValidatorWithContextTest.php @@ -621,12 +621,6 @@ public function validate_sse_with_id_and_comments(): void self::assertSame(true, $succeeded); } - /** - * P-020: RFC 7231 §3.1.1.1 allows wildcards in media types. A response - * Content-Type of `application/json` MUST be validated against a spec - * declaring `application/*` so wildcard handling is symmetric with - * RequestBodyValidatorWithContext. - */ #[Test] public function wildcard_application_matches_json_response(): void { diff --git a/tests/Unit/Validator/Response/StreamingContentParserTest.php b/tests/Unit/Validator/Response/StreamingContentParserTest.php index 83f9c05f..9fbc918f 100644 --- a/tests/Unit/Validator/Response/StreamingContentParserTest.php +++ b/tests/Unit/Validator/Response/StreamingContentParserTest.php @@ -763,7 +763,7 @@ public function parse_stream_json_seq_throws_on_record_exceeding_custom_max_reco #[Test] public function parse_stream_json_seq_allows_record_at_default_max_record_length(): void { - $record = str_repeat('x', 1_572_864); // 1.5 MB — above old 1MB line limit, below new 10MB record limit + $record = str_repeat('x', 1_572_864); $body = "\x1E" . $record . "\x1E"; $factory = new Psr17Factory(); @@ -848,12 +848,6 @@ public function parse_stream_jsonl_allows_line_at_exact_max_length(): void self::assertNull($result[0]); } - /** - * ST-12: JSON-seq (RFC 7464) with optional newline after record separator. - * - * RFC 7464 §2.1: "The remainder of the record [...] MAY be terminated by - * a line feed (U+000A)." This verifies the parser handles both forms. - */ #[Test] public function parse_json_sequence_with_newline_after_record_separator(): void { @@ -866,9 +860,6 @@ public function parse_json_sequence_with_newline_after_record_separator(): void self::assertSame(['id' => '2'], $result[1]); } - /** - * ST-12: JSON-seq with newline after RS via parse() dispatcher. - */ #[Test] public function parse_json_sequence_with_newline_after_rs_via_parse_method(): void { @@ -881,10 +872,6 @@ public function parse_json_sequence_with_newline_after_rs_via_parse_method(): vo self::assertSame(['id' => '2'], $result[1]); } - /** - * ST-12: Behaviour parity — JSON-seq with newline must produce the same - * item count as JSON-seq without newline. - */ #[Test] public function parse_json_sequence_newline_and_no_newline_produce_same_count(): void { @@ -899,10 +886,6 @@ public function parse_json_sequence_newline_and_no_newline_produce_same_count(): self::assertSame($withoutNewline, $withNewline); } - /** - * ST-12: Mixed form — some records have a trailing newline, others don't. - * RFC 7464 allows both forms within the same sequence. - */ #[Test] public function parse_json_sequence_mixed_newline_and_no_newline(): void { @@ -916,9 +899,6 @@ public function parse_json_sequence_mixed_newline_and_no_newline(): void self::assertSame(['c' => 3], $result[2]); } - /** - * ST-12: CRLF after RS is also valid per RFC 7464 (newline can be \r\n). - */ #[Test] public function parse_json_sequence_with_crlf_after_record_separator(): void { @@ -931,9 +911,6 @@ public function parse_json_sequence_with_crlf_after_record_separator(): void self::assertSame(['id' => '2'], $result[1]); } - /** - * ST-12: Stream-based parser must also accept newline after RS. - */ #[Test] public function parse_stream_json_sequence_with_newline_after_rs_matches_parse(): void { @@ -952,9 +929,6 @@ public function parse_stream_json_sequence_with_newline_after_rs_matches_parse() self::assertSame(['id' => '2', 'value' => 'second'], $result[1]); } - /** - * EI-037: WHATWG HTML SSE §8.1.1 requires CRLF, LF, and CR line endings. - */ #[Test] public function parse_server_sent_events_with_crlf_line_endings(): void { @@ -967,9 +941,6 @@ public function parse_server_sent_events_with_crlf_line_endings(): void self::assertSame(['msg' => 'hello'], $result[0]['data']); } - /** - * EI-037: Legacy CR-only line endings must also be supported. - */ #[Test] public function parse_server_sent_events_with_cr_only_line_endings(): void { @@ -982,9 +953,6 @@ public function parse_server_sent_events_with_cr_only_line_endings(): void self::assertSame('hello', $result[0]['data']); } - /** - * EI-037: Mixed line endings within a single body. - */ #[Test] public function parse_server_sent_events_with_mixed_line_endings(): void { @@ -999,11 +967,6 @@ public function parse_server_sent_events_with_mixed_line_endings(): void self::assertSame('two', $result[1]['data']); } - /** - * EI-038: WHATWG HTML SSE §8.2.6 removes exactly one leading U+0020 SPACE. - * Multiple leading spaces preserve all but the first. Plaintext value is - * used to avoid JSON-decode masking the space preservation. - */ #[Test] public function parse_server_sent_events_preserves_extra_leading_space_in_value(): void { @@ -1015,9 +978,6 @@ public function parse_server_sent_events_preserves_extra_leading_space_in_value( self::assertSame(' indented text', $result[0]['data']); } - /** - * EI-038: Value without a leading space is left untouched. - */ #[Test] public function parse_server_sent_events_value_without_leading_space_unchanged(): void { @@ -1029,10 +989,6 @@ public function parse_server_sent_events_value_without_leading_space_unchanged() self::assertSame('value', $result[0]['data']); } - /** - * EI-038: A single leading space on each accumulated data line is removed, - * but subsequent spaces inside the value survive the multi-line join. - */ #[Test] public function parse_server_sent_events_multi_line_with_extra_spaces(): void { @@ -1044,9 +1000,6 @@ public function parse_server_sent_events_multi_line_with_extra_spaces(): void self::assertSame(" first\n second", $result[0]['data']); } - /** - * EI-037: Multi-line data-field accumulation must survive CRLF endings. - */ #[Test] public function parse_server_sent_events_crlf_multi_line_data_accumulation(): void { @@ -1058,9 +1011,6 @@ public function parse_server_sent_events_crlf_multi_line_data_accumulation(): vo self::assertSame("line1\nline2", $result[0]['data']); } - /** - * EI-037: Comment line with CRLF endings is ignored. - */ #[Test] public function parse_server_sent_events_crlf_comment_line_ignored(): void { @@ -1073,10 +1023,6 @@ public function parse_server_sent_events_crlf_comment_line_ignored(): void self::assertSame('value', $result[0]['data']); } - /** - * EI-037 + EI-038: Stream-based parser must match the string-based parser - * for CRLF endings and single-space removal. - */ #[Test] public function parse_stream_sse_crlf_matches_parse(): void { @@ -1094,9 +1040,6 @@ public function parse_stream_sse_crlf_matches_parse(): void self::assertSame(['msg' => 'hello'], $result[0]['data']); } - /** - * EI-037: Stream-based parser must support CR-only endings. - */ #[Test] public function parse_stream_sse_cr_only_matches_parse(): void { @@ -1113,10 +1056,6 @@ public function parse_stream_sse_cr_only_matches_parse(): void self::assertSame('hello', $result[0]['data']); } - /** - * EI-038: Stream-based parser must remove exactly one leading space. - * Plaintext value avoids JSON-decode masking the space preservation. - */ #[Test] public function parse_stream_sse_preserves_extra_leading_space_in_value(): void { @@ -1133,12 +1072,6 @@ public function parse_stream_sse_preserves_extra_leading_space_in_value(): void self::assertSame(' indented text', $result[0]['data']); } - /** - * P-003: WHATWG HTML §9.2.4 step 8 — a line without a U+003A COLON - * creates a field whose name is the whole line and whose value is the - * empty string. The compact form `data\n\n` must dispatch a default - * `message` event with empty data. - */ #[Test] public function processes_sse_line_without_colon_as_field_with_empty_value(): void { @@ -1149,10 +1082,6 @@ public function processes_sse_line_without_colon_as_field_with_empty_value(): vo self::assertSame('message', $result[0]['event']); } - /** - * P-003: Multiple no-colon lines in the same event accumulate as separate - * fields with empty values per WHATWG HTML §9.2.4 step 8. - */ #[Test] public function processes_multiple_no_colon_fields(): void { @@ -1163,12 +1092,6 @@ public function processes_multiple_no_colon_fields(): void self::assertSame('', $result[0]['event']); } - /** - * P-003: A no-colon `data` line followed by a regular `data: value` line - * behaves identically to `data:\ndata: value` — the empty value is - * replaced by the next `data` field, matching the existing accumulator - * semantics of `applySseField`. - */ #[Test] public function no_colon_field_followed_by_normal_field_dispatches_correctly(): void { @@ -1178,11 +1101,6 @@ public function no_colon_field_followed_by_normal_field_dispatches_correctly(): self::assertSame('hello', $result[0]['data']); } - /** - * SEC-10: Default max records cap is 100_000 — defends against memory - * exhaustion from attacker-controlled streaming responses composed of - * many tiny records. - */ #[Test] public function default_max_records_is_one_hundred_thousand(): void { @@ -1193,10 +1111,6 @@ public function default_max_records_is_one_hundred_thousand(): void self::assertSame(100_000, $maxRecords); } - /** - * SEC-10: NDJSON non-streaming parser enforces the default record cap. - * 100_001 records → TooManyRecordsException with max=100_000. - */ #[Test] public function ndjson_record_count_limit_enforced(): void { @@ -1208,10 +1122,6 @@ public function ndjson_record_count_limit_enforced(): void $this->parser->parseJsonLines($body); } - /** - * SEC-10: Exactly 100_000 records (the default cap) parse successfully. - * Boundary case for the off-by-one in the limit check. - */ #[Test] public function ndjson_record_count_under_limit(): void { @@ -1222,9 +1132,6 @@ public function ndjson_record_count_under_limit(): void self::assertCount(100_000, $result); } - /** - * SEC-10: SSE non-streaming parser enforces the default record cap. - */ #[Test] public function sse_record_count_limit_enforced(): void { @@ -1235,10 +1142,6 @@ public function sse_record_count_limit_enforced(): void $this->parser->parseServerSentEvents($body); } - /** - * SEC-10: JSON Text Sequence (RFC 7464) non-streaming parser enforces - * the default record cap. - */ #[Test] public function json_seq_record_count_limit_enforced(): void { @@ -1249,10 +1152,6 @@ public function json_seq_record_count_limit_enforced(): void $this->parser->parseJsonSeq($body); } - /** - * SEC-10: Custom max records via constructor — 11 records with max=10 - * raises TooManyRecordsException with max=10. - */ #[Test] public function custom_max_records(): void { @@ -1268,10 +1167,6 @@ public function custom_max_records(): void } } - /** - * SEC-10: Boundary — exactly `maxRecords` parses successfully; max=10, - * 10 records → no exception. - */ #[Test] public function custom_max_records_boundary_at_limit(): void { @@ -1283,9 +1178,6 @@ public function custom_max_records_boundary_at_limit(): void self::assertCount(10, $result); } - /** - * SEC-10: SSE custom limit enforced. - */ #[Test] public function custom_max_records_sse(): void { @@ -1297,9 +1189,6 @@ public function custom_max_records_sse(): void $parser->parseServerSentEvents($body); } - /** - * SEC-10: JSON-seq custom limit enforced. - */ #[Test] public function custom_max_records_json_seq(): void { @@ -1311,11 +1200,6 @@ public function custom_max_records_json_seq(): void $parser->parseJsonSeq($body); } - /** - * SEC-10: NDJSON streaming variant enforces the same cap as the - * non-streaming variant — defences against memory amplifier must hold - * for chunked stream parsing too. - */ #[Test] public function streaming_variant_enforces_limit_ndjson(): void { @@ -1330,9 +1214,6 @@ public function streaming_variant_enforces_limit_ndjson(): void $parser->parseStream($stream, 'application/jsonl'); } - /** - * SEC-10: SSE streaming variant enforces the cap. - */ #[Test] public function streaming_variant_enforces_limit_sse(): void { @@ -1347,9 +1228,6 @@ public function streaming_variant_enforces_limit_sse(): void $parser->parseStream($stream, 'text/event-stream'); } - /** - * SEC-10: JSON Text Sequence streaming variant enforces the cap. - */ #[Test] public function streaming_variant_enforces_limit_json_seq(): void { @@ -1364,15 +1242,10 @@ public function streaming_variant_enforces_limit_json_seq(): void $parser->parseStream($stream, 'application/json-seq'); } - /** - * SEC-10: SSE events are counted, not raw lines. A multi-line SSE event - * (`data:` lines accumulated into one event) counts as one record. - */ #[Test] public function sse_counts_events_not_lines(): void { $parser = new StreamingContentParser(maxRecords: 2); - // Two multi-line events, each composed of 3 data lines → 2 records. $body = "event: first\ndata: a\ndata: b\ndata: c\n\n" . "event: second\ndata: d\ndata: e\ndata: f\n\n"; @@ -1381,14 +1254,10 @@ public function sse_counts_events_not_lines(): void self::assertCount(2, $result); } - /** - * SEC-10: NDJSON empty lines do not count toward the cap. - */ #[Test] public function empty_lines_do_not_count_toward_limit(): void { $parser = new StreamingContentParser(maxRecords: 3); - // 3 records interleaved with blank lines — must succeed. $body = "{\"a\":1}\n\n\n{\"b\":2}\n\n{\"c\":3}\n"; $result = $parser->parseJsonLines($body); @@ -1396,10 +1265,6 @@ public function empty_lines_do_not_count_toward_limit(): void self::assertCount(3, $result); } - /** - * SEC-10: JSON-seq empty items (consecutive record separators) do not - * count toward the cap. - */ #[Test] public function json_seq_empty_items_do_not_count_toward_limit(): void { @@ -1411,18 +1276,10 @@ public function json_seq_empty_items_do_not_count_toward_limit(): void self::assertCount(3, $result); } - /** - * SEC-10: SSE with no trailing flush (event mid-assembly when cap hit - * by an earlier completed event) — limit is checked on completed events - * only, not on in-flight accumulation. - */ #[Test] public function sse_trailing_unflushed_event_counts_after_limit_check(): void { $parser = new StreamingContentParser(maxRecords: 2); - // 2 completed events (each terminated by blank line) + 1 trailing - // event without terminating blank line — the trailing flush must - // trip the cap. $body = "data: a\n\ndata: b\n\ndata: c"; $this->expectException(TooManyRecordsException::class); @@ -1430,15 +1287,10 @@ public function sse_trailing_unflushed_event_counts_after_limit_check(): void $parser->parseServerSentEvents($body); } - /** - * SEC-10: SSE comment lines and field-only lines (no event boundary) do - * not count toward the cap. - */ #[Test] public function sse_comments_do_not_count_toward_limit(): void { $parser = new StreamingContentParser(maxRecords: 2); - // 2 events with multiple comment lines around them — must succeed. $body = ": comment 1\ndata: a\n\n: comment 2\ndata: b\n\n: comment 3\n"; $result = $parser->parseServerSentEvents($body); @@ -1446,16 +1298,10 @@ public function sse_comments_do_not_count_toward_limit(): void self::assertCount(2, $result); } - /** - * SEC-10: SSE streaming variant also enforces the cap on the trailing - * unflushed event when the body ends without a terminating blank line. - */ #[Test] public function streaming_sse_trailing_unflushed_event_counts_after_limit_check(): void { $parser = new StreamingContentParser(maxRecords: 2); - // 2 completed events + 1 trailing event without terminating blank - // line — the trailing flush must trip the cap. $body = "data: a\n\ndata: b\n\ndata: c"; $factory = new Psr17Factory(); @@ -1466,9 +1312,6 @@ public function streaming_sse_trailing_unflushed_event_counts_after_limit_check( $parser->parseStream($stream, 'text/event-stream'); } - /** - * SEC-10: SSE streaming variant counts events, not lines. - */ #[Test] public function streaming_sse_counts_events_not_lines(): void { diff --git a/tests/Unit/Validator/Schema/AnnotationTrackingTest.php b/tests/Unit/Validator/Schema/AnnotationTrackingTest.php index 4336b938..42ddb672 100644 --- a/tests/Unit/Validator/Schema/AnnotationTrackingTest.php +++ b/tests/Unit/Validator/Schema/AnnotationTrackingTest.php @@ -22,15 +22,6 @@ use function sprintf; -/** - * End-to-end coverage for JSON Schema 2020-12 annotation passing - * through in-place applicators (R3-SPEC-001 / R3-SPEC-002 / - * R3-SPEC-003 / R3-SPEC-004). - * - * Each test drives a full SchemaValidatorWithContext validate() call - * so that the composition validators fork+merge child annotations and - * the unevaluated* validators observe them at decision time. - */ #[CoversClass(SchemaValidatorWithContext::class)] final class AnnotationTrackingTest extends TestCase { diff --git a/tests/Unit/Validator/Schema/CombineUrisRfc3986Test.php b/tests/Unit/Validator/Schema/CombineUrisRfc3986Test.php index 262b49a6..bf7560bf 100644 --- a/tests/Unit/Validator/Schema/CombineUrisRfc3986Test.php +++ b/tests/Unit/Validator/Schema/CombineUrisRfc3986Test.php @@ -10,10 +10,6 @@ use PHPUnit\Framework\TestCase; /** - * RFC 3986 §5.4 conformance for RefResolver::combineUris(). - * - * The base URI for the §5.4.1 / §5.4.2 examples is "http://a/b/c/d;p?q". - * * @internal */ final class CombineUrisRfc3986Test extends TestCase diff --git a/tests/Unit/Validator/Schema/CycleDetectionWeakMapRegressionTest.php b/tests/Unit/Validator/Schema/CycleDetectionWeakMapRegressionTest.php index d658f4a8..4e3bd335 100644 --- a/tests/Unit/Validator/Schema/CycleDetectionWeakMapRegressionTest.php +++ b/tests/Unit/Validator/Schema/CycleDetectionWeakMapRegressionTest.php @@ -20,11 +20,6 @@ use function gc_collect_cycles; -/** - * Regression tests for P-027: cycle detection must use identity-based - * WeakMap rather than spl_object_id() (which is recycled by PHP GC and - * caused cache-key collisions / spurious cycle detection). - */ final class CycleDetectionWeakMapRegressionTest extends TestCase { #[Test] diff --git a/tests/Unit/Validator/Schema/FileExternalRefResolverTest.php b/tests/Unit/Validator/Schema/FileExternalRefResolverTest.php index 8b916559..6473a8d9 100644 --- a/tests/Unit/Validator/Schema/FileExternalRefResolverTest.php +++ b/tests/Unit/Validator/Schema/FileExternalRefResolverTest.php @@ -107,13 +107,6 @@ public function resolves_json_ref(): void } } - /** - * SPEC-01 / RFC 6901 §3: external $ref JSON Pointer fragments must - * decode ~1 -> / and ~0 -> ~ before lookup. The fixture maps the - * path key "/user" (literal slash) and the ref encodes the slash as - * ~1; without decoding the resolver would look for the literal key - * "~1user" and fail with "JSON Pointer segment not found". - */ #[Test] public function resolves_external_ref_with_decoded_json_pointer(): void { @@ -139,18 +132,6 @@ public function resolves_external_ref_with_decoded_json_pointer(): void } /** - * SEC-01: every PHP stream wrapper outside the allowlist must be - * rejected with ExternalRefSecurityException. The previous blacklist - * only covered http/https/ftp/ftps/gopher/netcat and left php://, - * phar://, data://, compress.zlib://, zip://, expect://, ssh2://, - * rar://, ogg://, glob:// (and every future wrapper) reachable. - * - * Each sample is a real attack vector: php://filter reads any file via - * base64 conversion, phar:// triggers deserialization gadgets, data:// - * injects attacker-controlled JSON (SEC-24), compress.zlib:// reads - * files through zlib, zip:// reads entries inside archives, expect:// - * spawns interactive shells, ssh2:// reaches the network via SSH, etc. - * * @param non-empty-string $ref */ #[Test] @@ -191,12 +172,6 @@ public static function rejectedSchemeRefs(): array ]; } - /** - * SEC-08: exception message must NOT leak the original $ref (it can - * contain absolute paths or attacker secrets). The offending scheme - * is fine to surface because it is a fixed, attacker-controlled token - * from the allowlist check, not user-supplied file content. - */ #[Test] public function rejected_scheme_message_does_not_leak_original_ref(): void { @@ -211,7 +186,7 @@ public function rejected_scheme_message_does_not_leak_original_ref(): void $this->assertStringNotContainsString( $ref, $e->getMessage(), - 'Exception message must not leak the original $ref (SEC-08).', + 'Exception message must not leak the original $ref.', ); $this->assertStringNotContainsString( '/etc/passwd', @@ -287,16 +262,6 @@ public function denies_symlink_escape_when_allowed_root_set(): void $resolver->resolve($this->fixtureRoot . '/../ExternalRefSibling.yaml'); } - /** - * SEC-02: a sibling directory whose name shares a prefix with the - * allowedRoot must NOT bypass the path-traversal check. The previous - * implementation used bare str_starts_with($realFile, $realRoot), so - * allowedRoot='/var/specs' happily admitted '/var/specs-evil/x.yaml'. - * - * The canonical check is: realFile === realRoot OR realFile starts - * with realRoot . '/'. The trailing slash makes the prefix boundary - * explicit and rejects sibling-evil directories. - */ #[Test] public function denies_sibling_directory_bypass_with_prefix_match(): void { @@ -330,11 +295,6 @@ public function denies_sibling_directory_bypass_with_prefix_match(): void } } - /** - * SEC-02: strict descendant (file in a subdirectory of allowedRoot) - * must remain valid after the prefix-fix. Covers the - * str_starts_with($realFile, $realRoot . '/') branch. - */ #[Test] public function allows_strict_descendant_file_under_root(): void { @@ -367,11 +327,6 @@ public function allows_strict_descendant_file_under_root(): void } } - /** - * SEC-02: edge case where the file path is exactly the allowedRoot - * (root points at a file rather than a directory). The fixed - * implementation accepts this via the $realFile === $realRoot branch. - */ #[Test] public function allows_exact_root_match_when_path_equals_root(): void { @@ -465,8 +420,6 @@ public function throws_when_pointer_target_is_not_a_schema_object(): void $this->expectException(RuntimeException::class); $this->expectExceptionMessage('External ref target is not a schema object'); - // Existing fixture: user.yaml#/UserSchema/type resolves to the string - // 'object', which is not a schema array. $resolver->resolve($this->fixtureRoot . '/components/user.yaml#/UserSchema/type'); } @@ -505,13 +458,6 @@ public function schema_returned_is_well_formed_with_required_and_format(): void $this->assertSame('email', $email->format); } - /** - * SEC-04: TOCTOU between realpath and fopen must not let an attacker - * swap a regular file for a symlink that escapes allowedRoot. The - * builtin resolver resolves the path via realpath right before the - * path-traversal check, so a symlink replacement pointing outside - * allowedRoot is rejected at assertPathWithinAllowedRoot time. - */ #[Test] public function toctou_symlink_replacement_blocked_by_allowed_root_check(): void { @@ -527,7 +473,6 @@ public function toctou_symlink_replacement_blocked_by_allowed_root_check(): void file_put_contents($outsideFile, "type: string\n"); try { - // Swap the regular file for a symlink that escapes the root. unlink($insideFile); symlink($outsideFile, $insideFile); @@ -555,12 +500,6 @@ public function toctou_symlink_replacement_blocked_by_allowed_root_check(): void } } - /** - * SEC-05: file payload larger than the configured $maxBytes cap must - * be rejected with ExternalRefTooLargeException before being fully - * materialised in memory. Uses a small maxBytes for test speed; the - * production default (10 MB) is the same code path. - */ #[Test] public function size_limit_enforced_when_file_exceeds_max_bytes(): void { @@ -590,11 +529,6 @@ public function size_limit_enforced_when_file_exceeds_max_bytes(): void } } - /** - * SEC-05 boundary: a file whose size equals exactly $maxBytes must be - * accepted (the cap rejects strictly larger files). Uses a small - * maxBytes for test speed. - */ #[Test] public function file_exactly_at_max_bytes_is_allowed(): void { @@ -619,12 +553,6 @@ public function file_exactly_at_max_bytes_is_allowed(): void } } - /** - * SEC-05: special files (character devices like /dev/null, /dev/zero, - * FIFOs, sockets, directories) must be rejected at fstat time. Reading - * /dev/zero without a size cap is a textbook DoS vector. /dev/zero - * and /dev/null exist on every Linux and macOS test runner. - */ #[DataProvider('specialFileRefs')] #[Test] public function special_file_rejected_as_not_regular_file(string $specialPath): void @@ -648,14 +576,6 @@ public static function specialFileRefs(): array ]; } - /** - * SEC-04 hygiene: when parseContents throws (e.g. unsupported - * extension), the file handle acquired via fopen must still be - * released via the finally block in readFileWithLimit(). This test - * exercises that path and asserts the parseContents exception - * propagates — proving fopen → fstat → readWithLimit → parseContents - * → finally(fclose) all ran without fatal errors or FD leaks. - */ #[Test] public function file_handle_closed_when_parse_contents_throws(): void { @@ -670,20 +590,12 @@ public function file_handle_closed_when_parse_contents_throws(): void $resolver->resolve($tempFile); } finally { - // On Unix unlink succeeds regardless of open handles, but a - // clean unlink post-exception documents the expected lifecycle. if (file_exists($tempFile)) { unlink($tempFile); } } } - /** - * Builder wiring: withExternalRefMaxBytes() must propagate to the - * constructed FileExternalRefResolver. A spec loaded from string - * has no auto-derived allowedRoot, so the resolver's path policy is - * unrestricted and only the size cap governs the resolution. - */ #[Test] public function builder_with_external_ref_max_bytes_propagates_to_resolver(): void { @@ -714,17 +626,6 @@ public function builder_with_external_ref_max_bytes_propagates_to_resolver(): vo } } - /** - * Defensive guard: if fread() returns false inside readWithLimit() - * (signal interruption, stream filter error, FS corruption), the - * resolver must surface a RuntimeException rather than silently - * returning truncated content. We exercise this path directly with - * a custom stream wrapper whose stream_read() returns false, because - * regular files (verified via fstat S_IFREG) never return false from - * fread() in practice. readWithLimit() is invoked via reflection - * because the builtin resolver's scheme allowlist (SEC-01) blocks - * the custom wrapper scheme at resolve() entry. - */ #[Test] public function fread_returning_false_in_read_with_limit_raises_runtime_exception(): void { @@ -754,16 +655,8 @@ public function fread_returning_false_in_read_with_limit_raises_runtime_exceptio } /** - * SEC-08 / CWE-209: every exception message produced by the - * builtin FileExternalRefResolver must be free of absolute - * filesystem paths. The README's PSR-15 middleware example - * surfaces any Throwable message to the HTTP client, so paths - * such as /var/specs, /private/tmp, /Users/... would disclose - * the server's filesystem layout to an unauthenticated caller. - * - * @param non-empty-string $ref External ref to feed the resolver - * @param class-string $exception Expected exception class - * + * @param non-empty-string $ref + * @param class-string $exception * @dataProvider absolutePathLeakingRefs */ #[Test] @@ -801,11 +694,6 @@ public static function absolutePathLeakingRefs(): array ]; } - /** - * SEC-08 / CWE-209: a payload that is not a YAML/JSON mapping must - * raise an exception message that does NOT leak the temp-file path - * created on the test machine. - */ #[Test] public function non_mapping_payload_message_does_not_leak_temp_path(): void { @@ -830,12 +718,6 @@ public function non_mapping_payload_message_does_not_leak_temp_path(): void } } - /** - * SEC-08 opt-in: when a PSR-3 logger is supplied, the resolver - * forwards the absolute path at debug level so trusted operators - * can still locate the offending file — even though the surfaced - * RuntimeException stays generic. - */ #[Test] public function verbose_logger_receives_absolute_path_for_missing_file(): void { @@ -859,21 +741,11 @@ public function verbose_logger_receives_absolute_path_for_missing_file(): void } /** - * Minimal stream wrapper used by file_handle_tests to simulate a regular - * file whose fread() returns false. Reports S_IFREG via stream_stat() so - * the resolver's regular-file check passes, then returns false from - * stream_read() and false from stream_eof() so the read loop enters its - * body at least once before the guard fires. - * * @internal */ final class FailingReadStreamWrapper { /** - * Stream context resource set by the PHP engine when the wrapper is - * opened via stream_context_create(). Declared explicitly to avoid - * the dynamic-property deprecation in PHP 8.5+. - * * @var resource|null */ public $context = null; @@ -922,10 +794,6 @@ public function url_stat(string $path, int $flags) } /** - * Minimal in-memory PSR-3 spy logger used to assert that the resolver - * forwards absolute paths at debug level when verbose logging is - * enabled. Captures the level, message, and context of every call. - * * @internal */ final class SpyLogger implements LoggerInterface diff --git a/tests/Unit/Validator/Schema/Internal/DiscriminatorDetectorTest.php b/tests/Unit/Validator/Schema/Internal/DiscriminatorDetectorTest.php index fddbf6d4..f236419f 100644 --- a/tests/Unit/Validator/Schema/Internal/DiscriminatorDetectorTest.php +++ b/tests/Unit/Validator/Schema/Internal/DiscriminatorDetectorTest.php @@ -15,7 +15,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; use WeakMap; -use Duyler\OpenApi\Validator\Schema\RefResolver; use Closure; use function is_array; @@ -214,7 +213,6 @@ public function detect_discriminator_returns_false_when_ref_unresolvable(): void #[Test] public function detect_discriminator_short_circuits_on_visited_cycle(): void { - // Cycle via $ref: A -> B -> A. The visited WeakMap guard breaks it. $schemaA = new Schema(ref: '#/components/schemas/B'); $schemaB = new Schema(ref: '#/components/schemas/A'); $document = $this->documentWithSchemas(['A' => $schemaA, 'B' => $schemaB]); @@ -352,19 +350,11 @@ private function wrapInProperties(Schema $leaf, int $depth): Schema return $current; } - /** - * Returns a resolver callable that never actually resolves anything - * (used for tests that don't exercise ref-following). - */ private function nullResolver(): Closure { return static fn(string $ref, OpenApiDocument $d): Schema => new Schema(); } - /** - * Resolver that walks the document's components.schemas map - * (mirrors RefResolver::resolve for tests that need ref-following). - */ private function coordinateResolver(OpenApiDocument $document): Closure { return static function (string $ref) use ($document): Schema { @@ -384,11 +374,6 @@ private function coordinateResolver(OpenApiDocument $document): Closure }; } - /** - * Returns a resolver callable that always throws UnresolvableRefException, - * matching the behaviour of {@see RefResolver::resolve()} - * for refs that cannot be resolved against the document. - */ private function unresolvingResolver(): Closure { return static fn(string $ref, OpenApiDocument $d): Schema diff --git a/tests/Unit/Validator/Schema/Internal/DocumentNavigatorTest.php b/tests/Unit/Validator/Schema/Internal/DocumentNavigatorTest.php index 64ea92b5..6565e749 100644 --- a/tests/Unit/Validator/Schema/Internal/DocumentNavigatorTest.php +++ b/tests/Unit/Validator/Schema/Internal/DocumentNavigatorTest.php @@ -137,9 +137,6 @@ public function navigate_throws_when_value_is_null(): void #[Test] public function navigate_enforces_max_depth_bound_on_recursion(): void { - // 70-segment pointer through nested properties on the same schema - // cannot be constructed without recursion, so the bound check - // fires via the per-segment MAX_DEPTH guard. $leaf = new Schema(type: 'string'); $current = $leaf; for ($i = 0; $i < 70; ++$i) { diff --git a/tests/Unit/Validator/Schema/Internal/UriResolverTest.php b/tests/Unit/Validator/Schema/Internal/UriResolverTest.php index f0ef855a..8990430d 100644 --- a/tests/Unit/Validator/Schema/Internal/UriResolverTest.php +++ b/tests/Unit/Validator/Schema/Internal/UriResolverTest.php @@ -10,12 +10,6 @@ use PHPUnit\Framework\TestCase; /** - * RFC 3986 §5.4 conformance for {@see UriResolver}. - * - * Golden-master derived from the official RFC 3986 §5.4.1 / §5.4.2 - * test vectors published at https://datatracker.ietf.org/doc/html/rfc3986#section-5.4. - * Base URI for all RFC examples is "http://a/b/c/d;p?q". - * * @internal */ final class UriResolverTest extends TestCase @@ -293,10 +287,6 @@ public function replace_query_and_fragment_drops_query_when_absent(): void self::assertArrayNotHasKey('query', $result); } - /** - * Mirrors RefResolver::combineUris() — splits parse_url() guard logic - * then delegates to {@see UriResolver::resolveRelativeAgainstBase()}. - */ private function combineViaResolver(string $baseUri, string $relativeRef): string { if ('' === $relativeRef) { diff --git a/tests/Unit/Validator/Schema/NestedRefResolutionTest.php b/tests/Unit/Validator/Schema/NestedRefResolutionTest.php index cb94020e..251a9c85 100644 --- a/tests/Unit/Validator/Schema/NestedRefResolutionTest.php +++ b/tests/Unit/Validator/Schema/NestedRefResolutionTest.php @@ -20,16 +20,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -/** - * Regression coverage for R4-CORRECTNESS-001 / R4-SEC-001 / R4-ARCH-001: - * `$ref` inside schema-typed keywords must be resolved before recursion. - * - * Each test drives a full {@see SchemaValidatorWithContext::validate()} call - * so the stateless nested-keyword validators go through the same - * `AbstractSchemaValidator::createSchemaValidator()` funnel that - * previously returned a legacy recursion engine without document context — - * leaving stub `{$ref: '#/...'}` subschemas as no-ops. - */ final class NestedRefResolutionTest extends TestCase { private OpenApiDocument $document; diff --git a/tests/Unit/Validator/Schema/RefResolverCachePerfTest.php b/tests/Unit/Validator/Schema/RefResolverCachePerfTest.php index 1834b5ce..ebb7fb39 100644 --- a/tests/Unit/Validator/Schema/RefResolverCachePerfTest.php +++ b/tests/Unit/Validator/Schema/RefResolverCachePerfTest.php @@ -17,13 +17,6 @@ /** * @internal - * - * Anti-test for P-045: asserts that the WeakMap cache entry is a - * mutable RefCache container whose spl_object_id stays stable as - * additional $refs are resolved. Reverting to copy-on-write (storing - * plain arrays under the document key) breaks every assertion here: - * the value is no longer a RefCache, and re-writing the array on each - * resolve yields a different identity. */ final class RefResolverCachePerfTest extends TestCase { @@ -63,7 +56,7 @@ public function resolve_ref_does_not_copy_cache_array(): void self::assertInstanceOf( RefCache::class, $entry, - 'Cache entry must be a mutable RefCache container, not a plain array (P-045)', + 'Cache entry must be a mutable RefCache container, not a plain array', ); $idBefore = spl_object_id($entry); diff --git a/tests/Unit/Validator/Schema/RefResolverOverrideTest.php b/tests/Unit/Validator/Schema/RefResolverOverrideTest.php index 29a729fb..b3e3894c 100644 --- a/tests/Unit/Validator/Schema/RefResolverOverrideTest.php +++ b/tests/Unit/Validator/Schema/RefResolverOverrideTest.php @@ -244,12 +244,6 @@ public function resolve_schema_with_override_applies_ref_summary_as_title(): voi self::assertSame('Override Title', $result->title); } - /** - * SPEC-02 / JSON Schema 2020-12 §8.2.3: a sibling `minLength` next to - * `$ref` must be applied as an additional constraint on the resolved - * schema. Without sibling merge the constraint would be silently - * dropped, allowing shorter values through. - */ #[Test] public function resolve_schema_with_override_applies_sibling_min_length(): void { @@ -263,12 +257,6 @@ public function resolve_schema_with_override_applies_sibling_min_length(): void self::assertSame(5, $result->minLength); } - /** - * SPEC-02 / JSON Schema 2020-12 §8.2.3: sibling `properties` next to - * `$ref` are merged shallowly into the resolved schema's properties. - * Sibling-defined property schemas are added on top of the resolved - * ones; on key collision the sibling entry wins. - */ #[Test] public function resolve_schema_with_override_merges_sibling_properties(): void { @@ -292,12 +280,6 @@ public function resolve_schema_with_override_merges_sibling_properties(): void self::assertSame($siblingRoleSchema, $result->properties['role']); } - /** - * SPEC-02 / JSON Schema 2020-12 §8.2.3: a sibling `enum` and the - * referenced schema's `enum` both apply, so the merged schema must - * accept only the intersection. Without intersection logic either - * side would be silently dropped. - */ #[Test] public function resolve_schema_with_override_intersects_sibling_enum(): void { @@ -316,11 +298,6 @@ enum: [1, 2], self::assertSame([1, 2], $result->enum); } - /** - * SPEC-02: a pure `$ref` without siblings resolves unchanged — the - * resolved schema is returned as-is (only the `$ref` family is - * cleared because resolution is complete). - */ #[Test] public function resolve_schema_with_override_passthrough_without_siblings(): void { @@ -346,11 +323,6 @@ public function resolve_schema_with_override_passthrough_without_siblings(): voi self::assertArrayHasKey('name', $result->properties); } - /** - * SPEC-02: a sibling `title` overrides the resolved schema's title - * per the historical OpenAPI override semantics preserved by the - * merge strategy. - */ #[Test] public function resolve_schema_with_override_sibling_title_overrides_resolved(): void { @@ -369,10 +341,6 @@ public function resolve_schema_with_override_sibling_title_overrides_resolved(): self::assertSame('Sibling', $result->title); } - /** - * SPEC-02: resolved-only fields are preserved when the sibling does - * not declare them. The sibling wins only when it sets a value. - */ #[Test] public function resolve_schema_with_override_preserves_resolved_only_fields(): void { @@ -394,10 +362,6 @@ public function resolve_schema_with_override_preserves_resolved_only_fields(): v self::assertSame(10, $result->maxLength); } - /** - * SPEC-02: sibling `required` is unioned with the resolved schema's - * `required` so that both required lists apply. - */ #[Test] public function resolve_schema_with_override_unions_sibling_required(): void { @@ -419,12 +383,6 @@ public function resolve_schema_with_override_unions_sibling_required(): void self::assertSame(['name', 'role'], $required); } - /** - * SPEC-02 end-to-end: a sibling `minLength` next to `$ref` must be - * enforced against actual data after the merge. Without sibling merge - * the constraint would be silently dropped and short values would - * pass downstream validation. - */ #[Test] public function resolve_schema_with_override_validates_min_length_via_validator(): void { @@ -445,12 +403,6 @@ public function resolve_schema_with_override_validates_min_length_via_validator( } } - /** - * SPEC-02 end-to-end: a sibling `enum` next to `$ref` intersects with - * the resolved schema's `enum`, and the merged schema must reject - * values that were valid in the resolved enum but absent from the - * sibling enum. - */ #[Test] public function resolve_schema_with_override_validates_enum_intersection_via_validator(): void { diff --git a/tests/Unit/Validator/Schema/RefResolverTest.php b/tests/Unit/Validator/Schema/RefResolverTest.php index 54f71b3c..caf97583 100644 --- a/tests/Unit/Validator/Schema/RefResolverTest.php +++ b/tests/Unit/Validator/Schema/RefResolverTest.php @@ -199,11 +199,6 @@ public function resolve_ref_to_nested_property(): void $this->assertSame("Address", $resolved->title); } - /** - * SPEC-01 / RFC 6901 §3: ~1 must decode to / before lookup. - * The schema is keyed with the literal "/user" (contains slash); - * without decoding the resolver would look for the literal key "~1user". - */ #[Test] public function resolve_decodes_json_pointer_slash_escape(): void { @@ -227,11 +222,6 @@ public function resolve_decodes_json_pointer_slash_escape(): void $this->assertSame("User", $resolved->title); } - /** - * SPEC-01 / RFC 6901 §3: ~0 must decode to ~ before lookup. - * The property name is literal "~foo"; without decoding the resolver - * would look for the literal key "~0foo". - */ #[Test] public function resolve_decodes_json_pointer_tilde_escape(): void { @@ -261,10 +251,6 @@ public function resolve_decodes_json_pointer_tilde_escape(): void $this->assertSame("Tilde", $resolved->title); } - /** - * SPEC-01 / RFC 6901 §3: combined escapes decode a path-template key. - * Schema is keyed with "/user/{id}"; the ref encodes each / as ~1. - */ #[Test] public function resolve_decodes_json_pointer_combined_escape(): void { @@ -288,19 +274,6 @@ public function resolve_decodes_json_pointer_combined_escape(): void $this->assertSame("UserById", $resolved->title); } - /** - * SPEC-01 / RFC 6901 §3: decode order is critical. - * - * For the encoded segment "~01": - * - Direct order (~1 -> /, then ~0 -> ~): "~01" -> "~1" - * (correct: "~01" is the encoded form of literal "~1"). - * - Reverse order (~0 -> ~, then ~1 -> /): "~01" -> "~1" -> "/" - * (incorrect: would resolve to key "/", which is absent). - * - * The document contains both "~1" and "/1" as keys. With the correct - * order the ref resolves to the "~1" entry; with the wrong order it - * would resolve to neither. - */ #[Test] public function resolve_decodes_json_pointer_escape_order_matters(): void { @@ -326,10 +299,6 @@ public function resolve_decodes_json_pointer_escape_order_matters(): void $this->assertSame("TildeOne", $resolved->title); } - /** - * SPEC-01 / RFC 6901 §3: segments without escape sequences pass - * through unchanged. - */ #[Test] public function resolve_json_pointer_no_escape_passthrough(): void { diff --git a/tests/Unit/Validator/Schema/SchemaHelperTest.php b/tests/Unit/Validator/Schema/SchemaHelperTest.php index 36e1dd60..a24af32d 100644 --- a/tests/Unit/Validator/Schema/SchemaHelperTest.php +++ b/tests/Unit/Validator/Schema/SchemaHelperTest.php @@ -117,12 +117,6 @@ public function normalize_null_throws_exception(): void SchemaValueNormalizer::normalize(null); } - /** - * P-010: `\stdClass` is normalized to its public-property view via - * get_object_vars(), matching TypeCoercer::normalizeValue. This lets - * consumers using `json_decode` without the associative flag (or plain - * object casts) reach the validator without manual conversion. - */ #[Test] public function normalizes_stdClass_to_array(): void { @@ -143,11 +137,6 @@ public function normalizes_empty_stdClass_to_empty_array(): void self::assertSame([], $result); } - /** - * Documents the top-level-only limitation: nested stdClass instances - * inside the normalized array are NOT recursively converted. Consumers - * needing deep conversion must call normalize themselves. - */ #[Test] public function normalizes_stdClass_only_at_top_level(): void { diff --git a/tests/Unit/Validator/Schema/UnevaluatedPropertiesWithDiscriminatorTest.php b/tests/Unit/Validator/Schema/UnevaluatedPropertiesWithDiscriminatorTest.php index 13c1233d..ef6f7f25 100644 --- a/tests/Unit/Validator/Schema/UnevaluatedPropertiesWithDiscriminatorTest.php +++ b/tests/Unit/Validator/Schema/UnevaluatedPropertiesWithDiscriminatorTest.php @@ -29,15 +29,6 @@ use function sprintf; -/** - * Regression coverage for R4-CORRECTNESS-005 / R4-SPEC-015: - * discriminator-routed sub-validation must propagate evaluated-property / - * evaluated-item annotations to the parent ValidationContext via - * forkForBranch + mergeChildAnnotations so that adjacent - * unevaluatedProperties:false / unevaluatedItems:false constraints honour - * properties already validated by the discriminator target schema - * (JSON Schema 2020-12 §10.3.4 / §11.1.1.3). - */ #[CoversClass(DiscriminatorValidator::class)] final class UnevaluatedPropertiesWithDiscriminatorTest extends TestCase { diff --git a/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesErrorCapTest.php b/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesErrorCapTest.php index 6c7a8a85..3a20c445 100644 --- a/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesErrorCapTest.php +++ b/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesErrorCapTest.php @@ -18,10 +18,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -/** - * FU-008: regression tests for the DoS cap on AdditionalPropertyError objects - * emitted by AdditionalPropertiesValidator when additionalProperties is false. - */ #[CoversClass(AdditionalPropertiesValidator::class)] class AdditionalPropertiesErrorCapTest extends TestCase { diff --git a/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorImplodeCapTest.php b/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorImplodeCapTest.php index c9a65ad3..dedd6a75 100644 --- a/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorImplodeCapTest.php +++ b/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorImplodeCapTest.php @@ -19,19 +19,6 @@ use function strlen; -/** - * FU-017: regression tests for the residual DoS vector in the - * ValidationException message built by AdditionalPropertiesValidator. - * - * Before the fix the message was assembled with - * `implode(', ', $additionalKeys)` over the FULL set of additional keys, - * which allocated ~5MB for 100k properties even though the `$errors` - * array was already capped at MAX_ADDITIONAL_PROPERTY_ERRORS (FU-008). - * - * After the fix the message is assembled exclusively from the already - * capped `$errors` array (<= 101 elements including the truncation - * indicator), bounding the message allocation regardless of payload size. - */ #[CoversClass(AdditionalPropertiesValidator::class)] class AdditionalPropertiesValidatorImplodeCapTest extends TestCase { diff --git a/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorTest.php b/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorTest.php index 5a70dd9f..6736c815 100644 --- a/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/AdditionalPropertiesValidatorTest.php @@ -170,11 +170,6 @@ public function allow_multiple_additional_properties(): void $this->expectNotToPerformAssertions(); } - /** - * EI-054 + FU-006: additionalProperties: false must produce one AdditionalPropertyError - * per forbidden property instead of an empty errors array, and the keyword must be - * 'additionalProperties' (not 'unevaluatedProperties'). - */ #[Test] public function reject_additional_when_false_returns_additional_property_errors(): void { @@ -207,9 +202,6 @@ public function reject_additional_when_false_returns_additional_property_errors( self::assertSame('extra2', $errors[1]->params()['propertyName']); } - /** - * Regression: no extra properties must still pass when additionalProperties is false. - */ #[Test] public function allow_no_additional_properties_when_additional_properties_false(): void { diff --git a/tests/Unit/Validator/SchemaValidator/AdditionalPropertyErrorTest.php b/tests/Unit/Validator/SchemaValidator/AdditionalPropertyErrorTest.php index 820b7bf9..e375da48 100644 --- a/tests/Unit/Validator/SchemaValidator/AdditionalPropertyErrorTest.php +++ b/tests/Unit/Validator/SchemaValidator/AdditionalPropertyErrorTest.php @@ -19,11 +19,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -/** - * Regression tests for FU-006: `additionalProperties: false` violations must surface - * `AdditionalPropertyError` (keyword: 'additionalProperties') instead of the semantically - * wrong `UnevaluatedPropertyError` (keyword: 'unevaluatedProperties'). - */ #[CoversClass(AdditionalPropertiesValidator::class)] final class AdditionalPropertyErrorTest extends TestCase { @@ -120,12 +115,6 @@ public function additional_properties_false_returns_property_name_in_params(): v self::assertSame('foo', $caught->getErrors()[0]->params()['propertyName']); } - /** - * Anti-test: proves the semantic mismatch that existed before FU-006. - * `AdditionalPropertyError` must report keyword 'additionalProperties', - * while `UnevaluatedPropertyError` reports 'unevaluatedProperties' for the - * distinct `unevaluatedProperties` JSON Schema keyword. - */ #[Test] public function additional_property_error_differs_from_unevaluated_property_error(): void { diff --git a/tests/Unit/Validator/SchemaValidator/ArrayLengthValidatorTest.php b/tests/Unit/Validator/SchemaValidator/ArrayLengthValidatorTest.php index 4e77dd83..90f3edc8 100644 --- a/tests/Unit/Validator/SchemaValidator/ArrayLengthValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/ArrayLengthValidatorTest.php @@ -280,13 +280,6 @@ public function unique_items_treats_distinct_scalar_json_types_as_unique(): void self::assertSame(true, $succeeded); } - /** - * Regression for review finding on bugfix 18: int and float that are - * mathematically equal MUST be treated as duplicates per JSON Schema - * §4.2.3 (numeric equality). PHP's strict === returns false for - * 1 === 1.0 because the types differ, which previously caused - * uniqueItems to silently accept [1, 1.0] as having no duplicates. - */ #[Test] public function unique_items_detects_int_and_float_as_duplicate_when_mathematically_equal(): void { @@ -340,11 +333,6 @@ public function unique_items_accepts_distinct_scalars_and_arrays_and_objects(): } /** - * SV-06 (uniqueItems) parameterized cases covering distinct arrays that - * MUST pass validation. Complements the individual uniqueItems tests - * above (which carry specific assertions about error metadata and JSON - * type-aware equality semantics) with a single data-provider-driven sweep. - * * @return array}> */ public static function provideUniqueItemsCases(): array @@ -380,9 +368,6 @@ public function sv_06_unique_items_accepts_distinct_arrays(array $data): void } /** - * SV-06 (uniqueItems) parameterized cases covering duplicate arrays that - * MUST fail validation with DuplicateItemsError. - * * @return array}> */ public static function provideDuplicateItemsCases(): array @@ -414,10 +399,6 @@ public function sv_06_unique_items_rejects_duplicate_arrays(array $data): void self::assertSame('/uniqueItems', $caught->schemaPath()); } - /** - * EI-052: resources are not valid JSON values and must be rejected by - * uniqueItems comparison before any later json_encode call. - */ #[Test] public function unique_items_rejects_resource_items(): void { @@ -480,9 +461,6 @@ public function unique_items_accepts_distinct_sequential_arrays(): void $this->expectNotToPerformAssertions(); } - /** - * Regression: arrays without resources must continue to pass uniqueItems. - */ #[Test] public function unique_items_accepts_valid_scalars_without_resources(): void { @@ -493,12 +471,6 @@ public function unique_items_accepts_valid_scalars_without_resources(): void $this->expectNotToPerformAssertions(); } - /** - * P-007: JSON Schema 2020-12 §4.2.2 — NaN must NOT compare equal to NaN. - * Previously `(string)(float) NAN === 'NAN'` produced a duplicate key - * so two NaNs were treated as duplicates. Per spec, two NaN values are - * distinct and the array MUST pass uniqueItems. - */ #[Test] public function nan_values_treated_as_unique_in_unique_items(): void { diff --git a/tests/Unit/Validator/SchemaValidator/BooleanSchemaKeywordTest.php b/tests/Unit/Validator/SchemaValidator/BooleanSchemaKeywordTest.php index 78f6efb3..6e8fa802 100644 --- a/tests/Unit/Validator/SchemaValidator/BooleanSchemaKeywordTest.php +++ b/tests/Unit/Validator/SchemaValidator/BooleanSchemaKeywordTest.php @@ -198,11 +198,8 @@ public function if_true_routes_to_then_branch(): void else: new Schema(type: 'integer'), ); - // If-true → then activates; then:string accepts. $validator->validate('hello', $schema); - // If-true → then:string rejects integer (typed TypeMismatchError - // surfaces from the recursive validator, not a wrapped one). $this->expectException(TypeMismatchError::class); $validator->validate(42, $schema); } @@ -217,7 +214,6 @@ public function if_false_routes_to_else_branch(): void else: new Schema(type: 'integer'), ); - // If-false → else activates; else:integer accepts. $validator->validate(42, $schema); $this->expectNotToPerformAssertions(); @@ -233,7 +229,6 @@ public function if_false_then_string_rejects_with_else_active(): void else: new Schema(type: 'integer'), ); - // If-false → else:integer rejects string with typed TypeMismatchError. $this->expectException(TypeMismatchError::class); $validator->validate('hello', $schema); } diff --git a/tests/Unit/Validator/SchemaValidator/CompositionBranchOrderIndependenceTest.php b/tests/Unit/Validator/SchemaValidator/CompositionBranchOrderIndependenceTest.php index 9060d13a..f6961cbb 100644 --- a/tests/Unit/Validator/SchemaValidator/CompositionBranchOrderIndependenceTest.php +++ b/tests/Unit/Validator/SchemaValidator/CompositionBranchOrderIndependenceTest.php @@ -28,20 +28,6 @@ use function sprintf; /** - * Regression for issue #54: the MAX_COMPOSITION_ERRORS cap in - * AbstractCompositionalValidator::validateSchemas() must cap error - * *collection*, not branch *iteration*. - * - * Before the fix, reaching the cap returned from validateSchemas() - * mid-loop, so branches declared after the noisy ones were never - * evaluated and $validCount could not grow. anyOf then reported - * "none did" for data that a later branch matches, making the outcome - * depend on branch declaration order. - * - * Anti-test: restoring the `return` in place of the `capped` flag makes - * every ordering-sensitive case below fail while the two cap-shape cases - * keep passing — the cap itself is not what changed. - * * @internal */ #[CoversClass(AnyOfValidator::class)] @@ -49,9 +35,6 @@ #[CoversClass(AllOfValidator::class)] final class CompositionBranchOrderIndependenceTest extends TestCase { - /** - * Two of these exceed MAX_COMPOSITION_ERRORS (20) on their own. - */ private const int ERRORS_PER_NOISY_BRANCH = 12; private ValidatorPool $pool; @@ -70,12 +53,6 @@ protected function setUp(): void $this->allOf = new AllOfValidator($dependencies); } - /** - * The third noisy branch matters: it is the one that reaches the - * post-cap `continue`. A matching branch alone would short-circuit on - * `$outcome->matched` before the cap is ever consulted, so turning the - * `continue` back into a `break` would go unnoticed. - */ #[Test] public function any_of_passes_whatever_the_position_of_the_matching_branch(): void { @@ -201,7 +178,6 @@ private function failureErrors(Schema $schema): array /** * @param array $branches - * * @return array */ private function matchingFirst(array $branches): array @@ -212,9 +188,6 @@ private function matchingFirst(array $branches): array return [$last, ...$reordered]; } - /** - * Emits ERRORS_PER_NOISY_BRANCH errors against {@see self::data()}. - */ private function noisyBranch(string $prefix): Schema { $required = []; diff --git a/tests/Unit/Validator/SchemaValidator/ContentMediaTypeValidatorTest.php b/tests/Unit/Validator/SchemaValidator/ContentMediaTypeValidatorTest.php index b1c326b8..e97146f3 100644 --- a/tests/Unit/Validator/SchemaValidator/ContentMediaTypeValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/ContentMediaTypeValidatorTest.php @@ -110,14 +110,6 @@ public function throw_error_for_empty_json_media_type(): void $this->validator->validate('', $schema); } - /** - * Anti-test for EI-003: proves isValidJson is independent of the global - * json_last_error state. In long-running runtimes (Swoole coroutines, - * RoadRunner, FrankenPHP) the global error code is shared across requests - * and coroutines; an unrelated failed json_decode could otherwise corrupt - * the validator's verdict (false-positive "valid"). With JSON_THROW_ON_ERROR - * the check is atomic and immune to such pollution. - */ #[Test] public function json_validation_is_independent_of_global_json_error_state(): void { @@ -136,13 +128,6 @@ public function json_validation_is_independent_of_global_json_error_state(): voi self::assertSame(true, $succeeded); } - /** - * Anti-test for EI-051: proves the depth limit blocks DoS payloads with - * deeply-nested JSON. Default json_decode depth is 512; the validator - * enforces 128, which rejects a payload of depth 200 with - * InvalidContentMediaTypeException. Without the limit the parser could - * stack-overflow or burn CPU on a malicious payload. - */ #[Test] public function deeply_nested_json_above_max_depth_is_rejected(): void { @@ -155,10 +140,6 @@ public function deeply_nested_json_above_max_depth_is_rejected(): void $this->validator->validate($depthExceedingPayload, $schema); } - /** - * Boundary test for EI-051: proves JSON nested within the depth limit - * (depth 100, under the cap of 128) passes validation. - */ #[Test] public function deeply_nested_json_within_max_depth_is_accepted(): void { @@ -177,14 +158,6 @@ public function deeply_nested_json_within_max_depth_is_accepted(): void self::assertSame(true, $succeeded); } - /** - * Documents the exact depth cutoff: payloads nested at JSON_MAX_DEPTH - 1 - * (127 levels) pass validation, while JSON_MAX_DEPTH (128 levels) is - * rejected. PHP's json_decode depth parameter has an off-by-one — depth=N - * permits nesting up to N-1. This test locks the boundary so a future - * change to the constant or to the depth parameter is immediately - * detected. - */ #[Test] public function json_depth_boundary_is_enforced_at_max_depth_minus_one(): void { @@ -504,11 +477,6 @@ public function throw_error_for_invalid_multipart_form_data(): void $this->validator->validate('not multipart', $schema); } - /** - * P-013: RFC 7578 §4 requires both an opening boundary (`--boundary`) - * and a closing boundary (`--boundary--`) at the end. A payload with - * only an opening boundary MUST be rejected. - */ #[Test] public function rejects_only_opening_boundary(): void { @@ -661,15 +629,6 @@ public function libxml_internal_errors_state_restored_after_xml_validation(): vo self::assertFalse(libxml_use_internal_errors()); } - /** - * Defense-in-depth anti-test for the schema validator: proves that the - * deny-all external entity loader (installed by LibxmlSecuredContext) - * blocks file:// resolution even if a future commit accidentally adds - * LIBXML_NOENT to XML_PARSE_OPTIONS. Without LIBXML_NOENT XXE is already - * blocked by simplexml_load_string semantics; this test demonstrates - * that the loader itself is the invariant guard, so the protection no - * longer relies solely on the absence of a flag. - */ #[Test] public function deny_all_loader_blocks_file_resolution_even_with_noent_flag_in_xml_validation(): void { diff --git a/tests/Unit/Validator/SchemaValidator/NumericRangeValidatorTest.php b/tests/Unit/Validator/SchemaValidator/NumericRangeValidatorTest.php index e26fd9b8..02c23f4b 100644 --- a/tests/Unit/Validator/SchemaValidator/NumericRangeValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/NumericRangeValidatorTest.php @@ -504,11 +504,6 @@ public function valid_numeric_edge_case_passes(int|float $value, Schema $schema) self::assertSame(true, $succeeded); } - /** - * P-009: JSON per RFC 8259 §6 cannot represent NaN. NaN comparisons - * always return false in PHP, which previously caused the range - * validator to silently accept any range constraint. - */ #[Test] public function rejects_nan_for_numeric_range(): void { @@ -576,17 +571,6 @@ public function multiple_of_works_for_small_integers_with_float_step(): void self::assertSame(true, $succeeded); } - /** - * R4-CORRECTNESS-008: previously, integer data with non-integer - * multipleOf and a large quotient (> 1e15) failed closed with - * InvalidMultipleOfSchemaException when bcmath was not loaded. - * Since R4-CORRECTNESS-008 the pure-PHP decimal string modulus - * path handles the case without bcmath. The test exercises both - * runtime variants: when bcmath is loaded the validator takes the - * fast bcmath branch; when it is absent the pure-PHP slow path - * must produce the same result. The shared expectation (pass) - * holds for both branches. - */ #[Test] public function multiple_of_large_integer_with_float_step_passes_with_or_without_bcmath(): void { @@ -606,13 +590,6 @@ public function multiple_of_large_integer_with_float_step_passes_with_or_without self::expectNotToPerformAssertions(); } - /** - * Regression guard for R4-CORRECTNESS-008: the private helper - * isBigIntMultipleOfString is the pure-PHP slow path. Invoking it - * directly via reflection forces the slow path even when bcmath is - * loaded, so the test pins the contract regardless of the host's - * extension set. - */ #[Test] public function multiple_of_snowflake_id_passes_via_pure_php_string_modulus(): void { @@ -629,16 +606,6 @@ public function multiple_of_snowflake_id_passes_via_pure_php_string_modulus(): v self::assertFalse($method->invoke($this->validator, -7, 1.5)); } - /** - * Parity guard: the public validate() entry point must return the - * same verdict whether the request is served by the bcmath branch - * or the pure-PHP slow path. Runs as a plain test (no @requires - * annotation) so both runtimes contribute to coverage: in the - * bcmath-on host the test pins the bcmath branch; in the - * bcmath-off host it pins the pure-PHP branch. The expected - * verdicts are computed from the mathematical definition of - * multipleOf (x mod m == 0), independent of the implementation. - */ #[Test] public function multiple_of_snowflake_id_public_path_matches_mathematical_definition(): void { @@ -681,10 +648,6 @@ public function multiple_of_snowflake_id_public_path_matches_mathematical_defini /** * @requires extension bcmath - * - * Confirms the bcmath branch is taken when the extension is loaded - * and produces the same verdict as the pure-PHP slow path. Acts as - * a parity contract between the two branches. */ #[Test] public function multiple_of_snowflake_id_bcmath_path_parity_with_pure_php_path(): void diff --git a/tests/Unit/Validator/SchemaValidator/PatternPropertiesNormalizeCacheTest.php b/tests/Unit/Validator/SchemaValidator/PatternPropertiesNormalizeCacheTest.php index 99aa0b6c..bbf7f682 100644 --- a/tests/Unit/Validator/SchemaValidator/PatternPropertiesNormalizeCacheTest.php +++ b/tests/Unit/Validator/SchemaValidator/PatternPropertiesNormalizeCacheTest.php @@ -179,14 +179,6 @@ public function precompiled_patterns_match_correctness_for_overlapping_keys(): v $this->expectNotToPerformAssertions(); } - /** - * Anti-test: the precompile fix in PatternPropertiesValidator ensures - * `RegexValidator::normalize` is invoked exactly once per distinct - * schema pattern regardless of how many property names are matched. - * The visible side-effect that survives the optimization is the - * normalize-cache content: the cache contains each pattern exactly - * once, and never contains the empty pattern. - */ private function normalizeCache(): array { $reflection = new ReflectionClass(RegexValidator::class); diff --git a/tests/Unit/Validator/SchemaValidator/PropertiesValidatorTest.php b/tests/Unit/Validator/SchemaValidator/PropertiesValidatorTest.php index 132bfa9e..1f923069 100644 --- a/tests/Unit/Validator/SchemaValidator/PropertiesValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/PropertiesValidatorTest.php @@ -263,12 +263,6 @@ public function throw_error_for_nested_invalid_property(): void self::assertSame('type', $errors[0]->keyword()); } - /** - * P-010 changed SchemaValueNormalizer to normalize stdClass to its - * property-view array. A stdClass-typed property value therefore no - * longer triggers InvalidDataTypeException at the normalizer; it - * fails validation as a regular TypeMismatchError against the schema. - */ #[Test] public function validate_property_with_invalid_type_throws_meaningful_exception(): void { diff --git a/tests/Unit/Validator/SchemaValidator/PropertyNamesValidatorTest.php b/tests/Unit/Validator/SchemaValidator/PropertyNamesValidatorTest.php index ae6f782c..b357c42e 100644 --- a/tests/Unit/Validator/SchemaValidator/PropertyNamesValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/PropertyNamesValidatorTest.php @@ -169,12 +169,6 @@ public function throw_error_for_invalid_regex_pattern_in_property_names(): void $this->validator->validate(['name' => 'value'], $schema); } - /** - * P-005: JSON Schema 2020-12 §6.5.4 — propertyNames applies only to - * object instances. PHP integer-keyed lists (array_is_list === true) - * MUST NOT be validated, otherwise a `type: string` constraint would - * reject every list as a false-positive TypeMismatchError. - */ #[Test] public function does_not_validate_integer_keys_for_lists(): void { diff --git a/tests/Unit/Validator/SchemaValidator/ScalarKeyEquivalencePairTest.php b/tests/Unit/Validator/SchemaValidator/ScalarKeyEquivalencePairTest.php index d3e1f3e8..8bdf0a32 100644 --- a/tests/Unit/Validator/SchemaValidator/ScalarKeyEquivalencePairTest.php +++ b/tests/Unit/Validator/SchemaValidator/ScalarKeyEquivalencePairTest.php @@ -24,12 +24,6 @@ use const NAN; -/** - * §14 pairing test: uniqueItems (ArrayLengthValidator scalar keys) and - * enum (EnumScalarCache scalar keys) must answer the equivalence question - * identically for every scalar pair — both are backed by ScalarKeyCodec - * and must never drift apart again. - */ #[CoversClass(ArrayLengthValidator::class)] #[CoversClass(EnumScalarCache::class)] final class ScalarKeyEquivalencePairTest extends TestCase diff --git a/tests/Unit/Validator/SchemaValidator/StringLengthValidatorTest.php b/tests/Unit/Validator/SchemaValidator/StringLengthValidatorTest.php index 269d1bdd..b19a5c8d 100644 --- a/tests/Unit/Validator/SchemaValidator/StringLengthValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/StringLengthValidatorTest.php @@ -209,10 +209,6 @@ public function emoji_family_at_max_length_one_rejected_by_utf16_unit_count(): v #[Test] public function supplementary_cjk_at_max_length_one_rejected_by_utf16_unit_count(): void { - // U+20BB7 lives in the supplementary plane: 4 bytes in UTF-8, - // encoded as a UTF-16 surrogate pair (2 code units). Therefore - // it must be rejected by maxLength:1 even though it is a single - // Unicode code point. $cjk = "\xF0\xA0\xAE\xB7"; $schema = new Schema(type: 'string', maxLength: 1); @@ -248,12 +244,6 @@ public function ascii_single_char_at_min_length_two_rejected(): void self::assertSame(1, $caught->params()['actual']); } - /** - * P-011: JSON is always UTF-8 per RFC 8259 §8.1; the validator MUST - * count UTF-16 code units independent of any host application - * mb_internal_encoding override (e.g., ASCII) that would otherwise - * fall back to byte counting. - */ #[Test] public function counts_multibyte_utf8_under_overridden_internal_encoding(): void { @@ -281,12 +271,6 @@ public function counts_multibyte_utf8_under_overridden_internal_encoding(): void } } - /** - * SPEC-06: supplementary characters (U+10000+) occupy 2 UTF-16 code - * units via surrogate pairs. The byte-based counter must remain - * correct regardless of mb_internal_encoding, since JSON Schema - * 2020-12 §6.3.1 mandates UTF-16 unit counting. - */ #[Test] public function counts_emoji_as_two_utf16_units_under_ascii_internal_encoding(): void { @@ -304,11 +288,6 @@ public function counts_emoji_as_two_utf16_units_under_ascii_internal_encoding(): } } - /** - * SPEC-06 (anti-test): supplementary characters must be rejected - * when maxLength is below their UTF-16 unit count, regardless of - * the host's mb_internal_encoding setting. - */ #[Test] public function rejects_emoji_at_max_length_one_under_ascii_internal_encoding(): void { @@ -326,11 +305,6 @@ public function rejects_emoji_at_max_length_one_under_ascii_internal_encoding(): } } - /** - * SPEC-06: minLength counts UTF-16 code units, so a single emoji - * (2 units) satisfies minLength:2 — the exact case that the old - * mb_strlen($data, 'UTF-8') implementation rejected incorrectly. - */ #[Test] public function supplementary_emoji_passes_min_length_two(): void { @@ -341,11 +315,6 @@ public function supplementary_emoji_passes_min_length_two(): void $this->expectNotToPerformAssertions(); } - /** - * SPEC-06: minLength counts UTF-16 code units, so a single emoji - * (2 units) must be rejected by minLength:3 (which requires at - * least 3 UTF-16 units). - */ #[Test] public function supplementary_emoji_fails_min_length_three(): void { @@ -356,10 +325,6 @@ public function supplementary_emoji_fails_min_length_three(): void $this->validator->validate('😀', $schema); } - /** - * SPEC-06 boundary: two supplementary emojis (4 UTF-16 units) - * must satisfy maxLength:4 exactly. - */ #[Test] public function supplementary_pair_at_max_length_boundary(): void { diff --git a/tests/Unit/Validator/SchemaValidator/UnevaluatedItemsValidatorTest.php b/tests/Unit/Validator/SchemaValidator/UnevaluatedItemsValidatorTest.php index d8e46a09..ac988d02 100644 --- a/tests/Unit/Validator/SchemaValidator/UnevaluatedItemsValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/UnevaluatedItemsValidatorTest.php @@ -306,11 +306,6 @@ public function validate_unevaluated_items_all_evaluated(): void self::assertSame(true, $succeeded); } - /** - * C-002 regression: prefixItems + items together. Items schema - * evaluates every index >= prefixItems count, so the unevaluated - * set must be empty for data whose tail items all conform to items. - */ #[Test] public function unevaluated_items_with_prefix_items_and_items_schema_passes_tail(): void { @@ -336,12 +331,6 @@ public function unevaluated_items_with_prefix_items_and_items_schema_passes_tail self::assertSame(true, $succeeded); } - /** - * C-003 regression: contains annotations register matched indices, - * and unevaluatedItems reads them through ValidationContext. - * Indices 0,1 are marked evaluated via annotations; index 2 ("x") - * remains unevaluated and fails the boolean unevaluatedItems schema. - */ #[Test] public function unevaluated_items_with_contains_only_fails_unevaluated_index(): void { @@ -368,11 +357,6 @@ public function unevaluated_items_with_contains_only_fails_unevaluated_index(): self::assertNotNull($caught, 'Index 2 ("x") is unevaluated and fails the boolean unevaluatedItems schema'); } - /** - * C-003 anti-test seed: without annotations, all three indices are - * considered unevaluated; even valid items at 0,1 fail the boolean - * unevaluatedItems schema. - */ #[Test] public function unevaluated_items_without_contains_annotations_fails_on_all_indices(): void { @@ -395,10 +379,6 @@ public function unevaluated_items_without_contains_annotations_fails_on_all_indi self::assertNotNull($caught, 'Without annotations, integer items 1,2 fail the boolean unevaluatedItems schema'); } - /** - * C-004 regression: composition-validated items contribute - * evaluated indices via context annotations. - */ #[Test] public function unevaluated_items_uses_composition_annotations_from_context(): void { diff --git a/tests/Unit/Validator/SchemaValidator/UnevaluatedPropertiesValidatorTest.php b/tests/Unit/Validator/SchemaValidator/UnevaluatedPropertiesValidatorTest.php index 0ecd6751..86586b71 100644 --- a/tests/Unit/Validator/SchemaValidator/UnevaluatedPropertiesValidatorTest.php +++ b/tests/Unit/Validator/SchemaValidator/UnevaluatedPropertiesValidatorTest.php @@ -607,12 +607,6 @@ public function passes_when_no_additional_properties_and_property_defined(): voi self::assertSame(true, $succeeded); } - /** - * C-001 regression: properties validated by an in-place applicator - * (here simulated by directly marking them in context, as - * AllOfValidator would after a successful branch) must be treated - * as evaluated by unevaluatedProperties. - */ #[Test] public function unevaluated_properties_with_context_annotations_passes(): void { @@ -652,11 +646,6 @@ public function unevaluated_properties_with_partial_context_annotations_fails_on $this->validator->validate(['known' => 1, 'unknown' => 2], $schema, $context); } - /** - * C-004 regression: annotations from composition validators - * (allOf/anyOf/oneOf/if-then-else) merge with static analysis - * of properties / patternProperties. - */ #[Test] public function unevaluated_properties_merges_static_and_annotation_evaluated(): void { @@ -684,11 +673,6 @@ public function unevaluated_properties_merges_static_and_annotation_evaluated(): self::assertSame(true, $succeeded); } - /** - * C-001 regression: when a property is evaluated by an annotation - * AND present in patternProperties, both contribute to evaluated - * set; no double-counting issues. - */ #[Test] public function unevaluated_properties_with_pattern_properties_and_annotations(): void { @@ -762,11 +746,6 @@ public function unevaluated_properties_with_schema_uses_annotation_set(): void self::assertSame(true, $succeeded); } - /** - * C-001 regression: without context (legacy SchemaValidator path), - * the validator falls back to static analysis only. Properties not - * declared in static schema are flagged as unevaluated. - */ #[Test] public function unevaluated_properties_without_context_uses_static_analysis_only(): void { diff --git a/tests/Unit/Validator/SchemaValidator/ValidationExceptionErrorsTest.php b/tests/Unit/Validator/SchemaValidator/ValidationExceptionErrorsTest.php index d01b8319..d863dc4c 100644 --- a/tests/Unit/Validator/SchemaValidator/ValidationExceptionErrorsTest.php +++ b/tests/Unit/Validator/SchemaValidator/ValidationExceptionErrorsTest.php @@ -234,12 +234,6 @@ public function oneof_multiple_match_has_errors_array(): void self::assertSame('/oneOf', $errors[0]->schemaPath()); } - /** - * P-010: stdClass is now normalized to an array by SchemaValueNormalizer, - * so passing `[new stdClass()]` against `items.type: string` reports a - * TypeMismatchError with actual='array' instead of the prior - * InvalidDataTypeException-wrapped 'object'. - */ #[Test] public function items_validator_invalid_item_has_errors_array(): void { @@ -296,12 +290,6 @@ public function items_validator_validation_failure_propagates_errors(): void self::assertGreaterThan(0, count($caught->getErrors())); } - /** - * P-010: stdClass is now normalized to an array by SchemaValueNormalizer, - * so `[new stdClass()]` reaches the type validator as `[]` and the - * schemaPath is the type sub-field of the prefixItems entry rather than - * the entry itself (as was reported when normalize threw). - */ #[Test] public function prefix_items_validator_invalid_item_has_errors_array(): void { diff --git a/tests/Unit/Validator/Security/SecurityValidatorTest.php b/tests/Unit/Validator/Security/SecurityValidatorTest.php index 962af41a..ad4b42f6 100644 --- a/tests/Unit/Validator/Security/SecurityValidatorTest.php +++ b/tests/Unit/Validator/Security/SecurityValidatorTest.php @@ -48,11 +48,6 @@ public function http_bearer_with_valid_token_passes(): void $this->expectNotToPerformAssertions(); } - /** - * RFC 6750 §2.1: Bearer scheme is case-insensitive. SEC-16 - * anti-test: revert preg_match to str_starts_with('Bearer ') and - * every case-variant assertion below fails. - */ #[Test] public function http_bearer_uppercase_scheme_passes(): void { @@ -113,11 +108,6 @@ public function http_bearer_mixed_case_scheme_passes(): void $this->expectNotToPerformAssertions(); } - /** - * RFC 9110 OWS: one or more whitespace separators between scheme - * and token are valid. SEC-16 anti-test: regex with a literal - * single space (/\s/ removed) would reject this header. - */ #[Test] public function http_bearer_multiple_spaces_between_scheme_and_token_passes(): void { @@ -138,10 +128,6 @@ public function http_bearer_multiple_spaces_between_scheme_and_token_passes(): v $this->expectNotToPerformAssertions(); } - /** - * RFC 6750 §2.1 requires a non-empty b64token. SEC-16 anti-test: - * regex without the \S+ requirement would let this header through. - */ #[Test] public function http_bearer_with_trailing_space_only_rejected_as_missing_token(): void { @@ -171,11 +157,6 @@ public function http_bearer_with_trailing_space_only_rejected_as_missing_token() } } - /** - * SEC-16 anti-test: 'Bearer' alone (no separator, no token) must - * not satisfy the validation — the regex requires \s+ after the - * scheme word. - */ #[Test] public function http_bearer_scheme_word_without_token_rejected(): void { @@ -196,10 +177,6 @@ public function http_bearer_scheme_word_without_token_rejected(): void $this->validator->validate(new SecurityValidationContext(request: $request, path: '/users', method: 'GET', securityRequirements: $securityRequirements, securitySchemes: $securitySchemes)); } - /** - * SEC-16: a raw token without the Bearer scheme prefix must not be - * accepted as a valid Bearer credential. - */ #[Test] public function http_bearer_token_without_scheme_prefix_rejected(): void { @@ -220,10 +197,6 @@ public function http_bearer_token_without_scheme_prefix_rejected(): void $this->validator->validate(new SecurityValidationContext(request: $request, path: '/users', method: 'GET', securityRequirements: $securityRequirements, securitySchemes: $securitySchemes)); } - /** - * SEC-16: Basic auth must not satisfy a Bearer security - * requirement even though both share the Authorization header. - */ #[Test] public function http_bearer_basic_auth_credentials_rejected_for_bearer_requirement(): void { @@ -253,14 +226,6 @@ public function http_bearer_basic_auth_credentials_rejected_for_bearer_requireme } } - /** - * R4-SEC-016 anti-test: a multi-challenge Authorization header - * carrying a fake Bearer prefix followed by a Basic challenge must - * not satisfy the Bearer security requirement. Without the `$` - * end-anchor the previous regex `/^bearer\s+\S+/i` matched only the - * `Bearer fake` prefix and silently accepted the header, allowing - * downstream code to extract the Basic challenge as the credential. - */ #[Test] public function http_bearer_multi_challenge_with_basic_suffix_rejected(): void { @@ -290,12 +255,6 @@ public function http_bearer_multi_challenge_with_basic_suffix_rejected(): void } } - /** - * R4-SEC-016 anti-test: RFC 7235 §4.1 permits multiple challenges in - * a single Authorization header. Two Bearer challenges separated by - * a comma is still a multi-challenge header and must be rejected to - * prevent the validator from rubber-stamping a prefix. - */ #[Test] public function http_bearer_multi_challenge_with_duplicate_bearer_rejected(): void { @@ -316,12 +275,6 @@ public function http_bearer_multi_challenge_with_duplicate_bearer_rejected(): vo $this->validator->validate(new SecurityValidationContext(request: $request, path: '/users', method: 'GET', securityRequirements: $securityRequirements, securitySchemes: $securitySchemes)); } - /** - * RFC 7235 header-value semantics: trailing whitespace in the - * Authorization value is permitted and must not cause a valid - * Bearer credential to be rejected. Requires `\s*$` rather than a - * strict `$` anchor. - */ #[Test] public function http_bearer_with_trailing_whitespace_passes(): void { @@ -342,12 +295,6 @@ public function http_bearer_with_trailing_whitespace_passes(): void $this->expectNotToPerformAssertions(); } - /** - * RFC 6750 §2.1 defines `b64token` as a whitespace-free production. - * A second whitespace run inside the token area indicates either a - * malformed credential or an attempt to smuggle an additional - * value past the validator and must be rejected. - */ #[Test] public function http_bearer_with_internal_whitespace_in_token_rejected(): void { @@ -368,11 +315,6 @@ public function http_bearer_with_internal_whitespace_in_token_rejected(): void $this->validator->validate(new SecurityValidationContext(request: $request, path: '/users', method: 'GET', securityRequirements: $securityRequirements, securitySchemes: $securitySchemes)); } - /** - * R4-SEC-016 anti-test: the credential position must not be a - * vehicle for arbitrary payloads. Any suffix after the token that - * is not whitespace must cause rejection (end-anchored regex). - */ #[Test] public function http_bearer_with_payload_suffix_after_token_rejected(): void { @@ -703,17 +645,6 @@ public function api_key_in_header_with_valid_key_passes(): void $this->expectNotToPerformAssertions(); } - /** - * SEC-16 fail-closed anti-test: an apiKey scheme with an `in` - * value outside the {query, header, cookie} allowlist must - * resolve to MissingSecurityCredentialsError via the match - * default arm, NOT throw UnhandledMatchError. Reverting the - * `default => null` arm (or replacing the match with a strict - * dispatcher) breaks this — the error class changes to - * \Error, the location string leaks the raw `in` value, and - * the caller-visible exception is no longer the generic - * AuthenticationRequired message but a stack trace. - */ #[Test] public function api_key_with_unknown_in_value_fails_closed_with_missing_credentials_error(): void { @@ -839,17 +770,6 @@ public function missing_bearer_credentials_error_contains_correct_location(): vo } } - /** - * SEC-07 / CWE-209: the public exception message must be generic so - * an unauthenticated caller cannot enumerate the security surface - * (scheme names, parameter locations, header names). The message - * must NOT contain the scheme name, the scheme type, or the - * parameter location — only a fixed "Authentication required" - * notice. - * - * Anti-test: if MissingSecurityCredentialsError reverts to embedding - * scheme details in its message, this assertion fails. - */ #[Test] public function generic_security_message_to_caller_omits_scheme_details(): void { @@ -886,13 +806,6 @@ public function generic_security_message_to_caller_omits_scheme_details(): void } } - /** - * SEC-07 anti-circumvention: scheme details must also be absent - * from params(), because error formatters (DetailedFormatter, - * JsonFormatter) render params() directly into API responses via - * PSR-15 middleware. Only readonly properties retain the detail - * for programmatic access by trusted operators. - */ #[Test] public function generic_security_message_params_are_empty_for_caller_safety(): void { @@ -919,12 +832,6 @@ public function generic_security_message_params_are_empty_for_caller_safety(): v } } - /** - * SEC-07 BC: although the message is generic, scheme details must - * remain accessible as readonly properties on the error object so - * trusted operators can introspect which scheme failed without - * enabling verbose logging. - */ #[Test] public function scheme_properties_accessible_programmatically(): void { @@ -951,12 +858,6 @@ public function scheme_properties_accessible_programmatically(): void } } - /** - * SEC-07 opt-in: when a PSR-3 logger is supplied, the validator - * forwards the concrete scheme details at debug level so trusted - * operators can still diagnose which scheme failed — even though - * the surfaced message stays generic. - */ #[Test] public function verbose_logging_to_logger_when_logger_supplied(): void { @@ -990,18 +891,9 @@ public function verbose_logging_to_logger_when_logger_supplied(): void } } - /** - * SEC-07 default: without an explicit logger, the validator must - * NOT emit anything observable — NullLogger is the safe default so - * scheme details never end up in production logs via error_log(). - */ #[Test] public function default_null_logger_emits_nothing_without_opt_in(): void { - // Default-constructed validator uses NullLogger internally; the - // only observable effect is that the generic exception is - // raised. This test exists to lock that behaviour: any future - // change that introduces a default non-null sink breaks it. $validator = new SecurityValidator(); $request = $this->factory->createServerRequest('GET', '/users'); @@ -1022,10 +914,6 @@ public function default_null_logger_emits_nothing_without_opt_in(): void } /** - * Minimal in-memory PSR-3 spy logger used to assert that the security - * validator forwards scheme details at debug level when verbose logging - * is enabled. Captures the level, message, and context of every call. - * * @internal */ final class SpyLogger implements LoggerInterface diff --git a/tests/Unit/Validator/Security/UnsupportedSecuritySchemeRegressionTest.php b/tests/Unit/Validator/Security/UnsupportedSecuritySchemeRegressionTest.php index 7b69b053..7494d1ba 100644 --- a/tests/Unit/Validator/Security/UnsupportedSecuritySchemeRegressionTest.php +++ b/tests/Unit/Validator/Security/UnsupportedSecuritySchemeRegressionTest.php @@ -15,15 +15,6 @@ use Psr\Log\LoggerInterface; /** - * R4-SEC-010 / R4-SPEC-003 regression coverage. - * - * Anti-tests: revert the SecurityValidator default arm and the - * validateHttpScheme non-bearer arm to the previous - * MissingSecurityCredentialsError behaviour and every test below - * fails — the previous behaviour misclassified unsupported schemes - * as missing credentials, breaking AND/OR semantics for mixed - * requirements. - * * @internal */ final class UnsupportedSecuritySchemeRegressionTest extends TestCase @@ -154,13 +145,6 @@ public function mutual_tls_scheme_throws_unsupported_exception(): void )); } - /** - * AND semantics: spec `security: [{oauth2: [read], bearerAuth: []}]`. - * A valid Bearer token cannot rescue the requirement because the - * AND-list contains an unsupported scheme. The validator must fail - * closed with UnsupportedSecuritySchemeException rather than - * silently downgrading the requirement to bearer-only. - */ #[Test] public function and_list_with_unsupported_scheme_fails_closed_even_when_supported_sibling_passes(): void { @@ -193,12 +177,6 @@ public function and_list_with_unsupported_scheme_fails_closed_even_when_supporte } } - /** - * OR semantics: spec `security: [{oauth2: [read]}, {bearerAuth: []}]`. - * The second OR alternative (bearerAuth) is supported and the - * request carries a valid Bearer token, so the validator must - * succeed despite the unsupported oauth2 alternative. - */ #[Test] public function or_list_succeeds_when_supported_alternative_passes_and_unsupported_sibling_skipped(): void { @@ -225,13 +203,6 @@ public function or_list_succeeds_when_supported_alternative_passes_and_unsupport $this->expectNotToPerformAssertions(); } - /** - * OR semantics: same spec as the success case, but the request is - * missing the Bearer token. The validator must re-throw the - * captured UnsupportedSecuritySchemeException after exhausting all - * OR alternatives so the operator sees the spec-configuration - * error rather than a downstream credential error. - */ #[Test] public function or_list_rethrows_unsupported_exception_when_no_alternative_succeeds(): void { @@ -261,14 +232,6 @@ public function or_list_rethrows_unsupported_exception_when_no_alternative_succe } } - /** - * R4-SPEC-003: scopes declared on a security requirement must be - * preserved for diagnostic purposes. Today they are logged at - * debug level via PSR-3 (OAuth2 token scope validation is not - * implemented; the UnsupportedSecuritySchemeException is still - * raised because the oauth2 scheme type is unsupported). The - * scopes must reach the logger even though the scheme is rejected. - */ #[Test] public function oauth2_scopes_are_logged_at_debug_level_for_diagnostic_purposes(): void { @@ -306,10 +269,6 @@ public function oauth2_scopes_are_logged_at_debug_level_for_diagnostic_purposes( } } - /** - * Empty scopes (e.g. apiKey, http/bearer) must NOT trigger the - * scopes debug-log entry — they carry no diagnostic value. - */ #[Test] public function empty_scopes_do_not_trigger_scopes_debug_log_entry(): void { @@ -339,13 +298,6 @@ public function empty_scopes_do_not_trigger_scopes_debug_log_entry(): void $this->assertSame([], $scopeRecords); } - /** - * The exception message is operator-facing diagnostic content - * (spec configuration error, not request auth error), so it must - * disclose the scheme name and type. However `(string) $e` must - * not leak file paths or stack traces through the default - * Exception::__toString() — only the message itself. - */ #[Test] public function to_string_returns_message_only_without_paths_or_trace(): void { @@ -378,10 +330,6 @@ public function to_string_returns_message_only_without_paths_or_trace(): void } /** - * Minimal in-memory PSR-3 spy logger used to assert that OAuth2 scopes - * declared on a security requirement reach the debug log even when the - * scheme itself is rejected. - * * @internal */ final class ScopeSpyLogger implements LoggerInterface diff --git a/tests/Unit/Validator/Server/ServerUrlResolverTest.php b/tests/Unit/Validator/Server/ServerUrlResolverTest.php index 73d345b7..190fabc4 100644 --- a/tests/Unit/Validator/Server/ServerUrlResolverTest.php +++ b/tests/Unit/Validator/Server/ServerUrlResolverTest.php @@ -152,11 +152,6 @@ public function override_takes_precedence_over_default(): void $this->assertSame('https://dev.api.com', $result); } - /** - * P-008: RFC 6570 §2.3 permits the dot inside a variable name, so the - * server URL `https://api.example.com/{api.version}` must resolve when - * the dotted override key is supplied. - */ #[Test] public function resolves_server_url_with_dot_in_variable_name(): void { @@ -175,10 +170,6 @@ public function resolves_server_url_with_dot_in_variable_name(): void $this->assertSame('https://api.example.com/v2', $result); } - /** - * P-008: A dotted server-variable name must resolve using its declared - * default when no override is supplied. - */ #[Test] public function resolves_server_url_with_dot_in_variable_name_using_default(): void { @@ -194,9 +185,6 @@ public function resolves_server_url_with_dot_in_variable_name_using_default(): v $this->assertSame('https://api.example.com/v1', $result); } - /** - * P-008: Variable-name extraction must include the dot in each name. - */ #[Test] public function extracts_variable_names_with_dots(): void { diff --git a/tests/Unit/Validator/Util/Utf16Test.php b/tests/Unit/Validator/Util/Utf16Test.php index fc962598..19b96c4d 100644 --- a/tests/Unit/Validator/Util/Utf16Test.php +++ b/tests/Unit/Validator/Util/Utf16Test.php @@ -10,13 +10,6 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -/** - * Validates UTF-16 code-unit counting per JSON Schema 2020-12 §6.3.1. - * - * Supplementary plane characters (U+10000 — U+10FFFF) are represented - * as UTF-16 surrogate pairs and must count as 2 units — not 1, which - * is what naive mb_strlen($s, 'UTF-8') would return. - */ #[CoversClass(Utf16::class)] final class Utf16Test extends TestCase { @@ -71,8 +64,6 @@ public function cyrillic_bmp_length(): void #[Test] public function supplementary_cjk_length(): void { - // U+20BB7 (CJK Extension C) — encoded as 4 bytes in UTF-8, - // 2 UTF-16 code units via surrogate pair. $length = Utf16::length("\xF0\xA0\xAE\xB7"); self::assertSame(2, $length); @@ -81,9 +72,6 @@ public function supplementary_cjk_length(): void #[Test] public function zwj_emoji_sequence_length(): void { - // Family with ZWJ: 👨‍👩‍👧‍👦 = 4 supplementary emojis + 3 ZWJ joins. - // Each supplementary emoji = 2 UTF-16 units; each ZWJ (U+200D) = 1. - // Total: (2 * 4) + (1 * 3) = 11. $length = Utf16::length("\xF0\x9F\x91\xA8\xE2\x80\x8D\xF0\x9F\x91\xA9\xE2\x80\x8D\xF0\x9F\x91\xA7\xE2\x80\x8D\xF0\x9F\x91\xA6"); self::assertSame(11, $length);