Version in base suite: 6.4.50+dfsg-0+deb13u1 Base version: symfony_6.4.50+dfsg-0+deb13u1 Target version: symfony_6.4.51+dfsg-0+deb13u1 Base file: /srv/ftp-master.debian.org/ftp/pool/main/s/symfony/symfony_6.4.50+dfsg-0+deb13u1.dsc Target file: /srv/ftp-master.debian.org/policy/pool/main/s/symfony/symfony_6.4.51+dfsg-0+deb13u1.dsc .agents/skills/security-triage/SKILL.md | 175 -- .agents/skills/symfony-security-review/SKILL.md | 2 .codespellrc | 3 .github/workflows/integration-tests.yml | 10 .github/workflows/unit-tests.yml | 4 .github/workflows/windows.yml | 11 .github/workflows/zizmor.yml | 2 CHANGELOG-6.4.md | 289 ++++ debian/changelog | 56 debian/patches/Adapt-conflict-to-Debian-expectations.patch | 11 debian/patches/Assume-php-async-aws-sqs-2.patch | 4 debian/patches/Cache-Disable-Test-failing-tests-Error-Class-not-found.patch | 461 ------ debian/patches/Cache-Skip-test-currently-failing.patch | 22 debian/patches/DependencyInjection-Don-t-override-final-method-PHPUnit-F.patch | 2 debian/patches/Drop-composer-runtime-api-that-confuses-phpabtpl.patch | 2 debian/patches/Drop-test-currently-failing-on-buildd.patch | 4 debian/patches/Group-nophpunit11-for-tests-failing-with-PHPUnit-11.patch | 20 debian/patches/HttpClient-Skip-test-currently-failing.patch | 22 debian/patches/HttpClient-Skip-tests-currently-failing.patch | 36 debian/patches/HttpClient-Skip-tests-relying-on-amphp-http-client.patch | 4 debian/patches/Lock-Drop-test-currently-failing-on-buildd.patch | 4 debian/patches/Remove-calls-to-getExpectedException.patch | 6 debian/patches/Scheduler-Skip-test-currently-failing.patch | 22 debian/patches/Use-installed-files-for-CI.patch | 2 debian/patches/Yaml-Drop-data-set-currently-failing-on-i386.patch | 4 debian/patches/group-network-for-test-failing-without-network.patch | 2 debian/patches/series | 5 debian/php-symfony-cache.autoload.php.tpl | 1 src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php | 22 src/Symfony/Bridge/Doctrine/Tests/DoctrineTestHelper.php | 4 src/Symfony/Bridge/Doctrine/Tests/Security/RememberMe/DoctrineTokenProviderTest.php | 86 + src/Symfony/Bridge/PhpUnit/Tests/SimplePhpunitTest.php | 34 src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php | 35 src/Symfony/Bridge/PsrHttpMessage/Factory/UploadedFile.php | 2 src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php | 27 src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig | 2 src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig | 3 src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_5_layout.html.twig | 3 src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_base_layout.html.twig | 2 src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig | 2 src/Symfony/Bridge/Twig/Resources/views/Form/foundation_5_layout.html.twig | 4 src/Symfony/Bridge/Twig/Resources/views/Form/tailwind_2_layout.html.twig | 2 src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionChoiceLabelTest.php | 108 + src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php | 10 src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php | 2 src/Symfony/Bundle/FrameworkBundle/Resources/config/test.php | 3 src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php | 3 src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php | 14 src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php | 40 src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php | 11 src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableCompiledUrlMatcherTest.php | 40 src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php | 60 src/Symfony/Bundle/SecurityBundle/Debug/TraceableFirewallListener.php | 14 src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php | 4 src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator.php | 1 src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator_remember_me.php | 2 src/Symfony/Bundle/SecurityBundle/Resources/config/security_debug.php | 1 src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php | 61 src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php | 84 + src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php | 28 src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/RememberMeBundle/Controller/StatelessController.php | 22 src/Symfony/Bundle/SecurityBundle/Tests/Functional/RememberMeTest.php | 42 src/Symfony/Bundle/SecurityBundle/Tests/Functional/SecurityTest.php | 12 src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/lazy_config.yml | 8 src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/routing.yml | 5 src/Symfony/Bundle/SecurityBundle/Tests/Impersonate/ImpersonateUrlGeneratorTest.php | 59 src/Symfony/Bundle/SecurityBundle/composer.json | 4 src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/http_client.html.twig | 2 src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/_request_summary.html.twig | 2 src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig | 53 src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_redirect.html.twig | 4 src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php | 51 src/Symfony/Bundle/WebProfilerBundle/Tests/Functional/WebProfilerBundleKernel.php | 17 src/Symfony/Component/AssetMapper/ImportMap/ImportMapAuditor.php | 11 src/Symfony/Component/AssetMapper/ImportMap/ImportMapUpdateChecker.php | 18 src/Symfony/Component/AssetMapper/ImportMap/ImportMapVersionChecker.php | 41 src/Symfony/Component/AssetMapper/Tests/Factory/CachedMappedAssetFactoryTest.php | 1 src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapAuditorTest.php | 7 src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapUpdateCheckerTest.php | 72 + src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapVersionCheckerTest.php | 8 src/Symfony/Component/BrowserKit/AbstractBrowser.php | 10 src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php | 25 src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php | 2 src/Symfony/Component/Cache/Adapter/ChainAdapter.php | 19 src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php | 42 src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php | 34 src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php | 20 src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php | 1 src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php | 91 + src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php | 80 + src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php | 1 src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php | 4 src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php | 1 src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareAdapterTest.php | 16 src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareClusterAdapterTest.php | 13 src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php | 1 src/Symfony/Component/Cache/Tests/Fixtures/StrictKeysRedis.php | 38 src/Symfony/Component/Cache/Tests/Traits/RedisProxiesTest.php | 10 src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php | 62 src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php | 2 src/Symfony/Component/Cache/Traits/RedisClusterNodeProxy.php | 2 src/Symfony/Component/Cache/Traits/RedisTrait.php | 36 src/Symfony/Component/Cache/Traits/Relay/Relay62Trait.php | 102 + src/Symfony/Component/Cache/Traits/RelayProxy.php | 11 src/Symfony/Component/Cache/Traits/ValueWrapper.php | 8 src/Symfony/Component/Config/Definition/BaseNode.php | 8 src/Symfony/Component/Config/Definition/EnumNode.php | 10 src/Symfony/Component/Config/Definition/NumericNode.php | 3 src/Symfony/Component/Config/Resource/DirectoryResource.php | 9 src/Symfony/Component/Config/Resource/GlobResource.php | 2 src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php | 20 src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php | 38 src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php | 11 src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php | 9 src/Symfony/Component/Console/Application.php | 4 src/Symfony/Component/Console/Formatter/OutputFormatter.php | 8 src/Symfony/Component/Console/Helper/FormatterHelper.php | 2 src/Symfony/Component/Console/Helper/Helper.php | 28 src/Symfony/Component/Console/Helper/OutputWrapper.php | 62 src/Symfony/Component/Console/Helper/Table.php | 12 src/Symfony/Component/Console/Tests/ApplicationTest.php | 15 src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php | 9 src/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.php | 2 src/Symfony/Component/Console/Tests/Helper/OutputWrapperTest.php | 119 + src/Symfony/Component/Console/Tests/Helper/TableTest.php | 25 src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php | 17 src/Symfony/Component/DependencyInjection/Loader/FileLoader.php | 10 src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php | 10 src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php | 5 src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php | 8 src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php | 12 src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php | 6 src/Symfony/Component/ExpressionLanguage/Node/ConditionalNode.php | 20 src/Symfony/Component/ExpressionLanguage/Parser.php | 7 src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php | 21 src/Symfony/Component/ExpressionLanguage/Tests/Node/ConditionalNodeTest.php | 3 src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php | 8 src/Symfony/Component/Finder/Glob.php | 16 src/Symfony/Component/Finder/Tests/GlobTest.php | 42 src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php | 22 src/Symfony/Component/Form/Resources/translations/validators.ar.xlf | 6 src/Symfony/Component/Form/Resources/translations/validators.bg.xlf | 24 src/Symfony/Component/Form/Resources/translations/validators.ca.xlf | 30 src/Symfony/Component/Form/Resources/translations/validators.cs.xlf | 26 src/Symfony/Component/Form/Resources/translations/validators.eu.xlf | 54 src/Symfony/Component/Form/Resources/translations/validators.he.xlf | 28 src/Symfony/Component/Form/Resources/translations/validators.hu.xlf | 26 src/Symfony/Component/Form/Resources/translations/validators.mk.xlf | 24 src/Symfony/Component/Form/Resources/translations/validators.pt.xlf | 32 src/Symfony/Component/Form/Resources/translations/validators.sq.xlf | 28 src/Symfony/Component/Form/Resources/translations/validators.tg.xlf | 147 ++ src/Symfony/Component/Form/Resources/translations/validators.tl.xlf | 52 src/Symfony/Component/Form/Resources/translations/validators.uz.xlf | 30 src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php | 4 src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php | 42 src/Symfony/Component/Form/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php | 21 src/Symfony/Component/HtmlSanitizer/HtmlSanitizerConfig.php | 4 src/Symfony/Component/HtmlSanitizer/Reference/W3CReference.php | 32 src/Symfony/Component/HtmlSanitizer/Tests/HtmlSanitizerCustomTest.php | 169 ++ src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/LinkTargetAttributeSanitizer.php | 53 src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/MetaRefreshAttributeSanitizer.php | 32 src/Symfony/Component/HttpClient/AmpHttpClient.php | 6 src/Symfony/Component/HttpClient/CachingHttpClient.php | 2 src/Symfony/Component/HttpClient/Chunk/ServerSentEvent.php | 8 src/Symfony/Component/HttpClient/CurlHttpClient.php | 12 src/Symfony/Component/HttpClient/HttpClientTrait.php | 52 src/Symfony/Component/HttpClient/Internal/AmpBody.php | 2 src/Symfony/Component/HttpClient/Internal/ArrayBodyCaster.php | 46 src/Symfony/Component/HttpClient/NativeHttpClient.php | 5 src/Symfony/Component/HttpClient/NoPrivateNetworkHttpClient.php | 44 src/Symfony/Component/HttpClient/Response/CurlResponse.php | 2 src/Symfony/Component/HttpClient/Response/MockResponse.php | 16 src/Symfony/Component/HttpClient/Response/TraceableResponse.php | 19 src/Symfony/Component/HttpClient/RetryableHttpClient.php | 65 src/Symfony/Component/HttpClient/ScopingHttpClient.php | 14 src/Symfony/Component/HttpClient/Tests/AmpHttpClientTest.php | 18 src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php | 18 src/Symfony/Component/HttpClient/Tests/Chunk/ServerSentEventTest.php | 25 src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php | 94 + src/Symfony/Component/HttpClient/Tests/Fixtures/proxy-url/index.php | 42 src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php | 128 + src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php | 125 + src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php | 209 +++ src/Symfony/Component/HttpClient/Tests/Response/MockResponseTest.php | 42 src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php | 213 +++ src/Symfony/Component/HttpClient/Tests/ScopingHttpClientTest.php | 51 src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php | 36 src/Symfony/Component/HttpClient/composer.json | 1 src/Symfony/Component/HttpFoundation/IpUtils.php | 25 src/Symfony/Component/HttpFoundation/JsonResponse.php | 2 src/Symfony/Component/HttpFoundation/Request.php | 27 src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php | 3 src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php | 17 src/Symfony/Component/HttpFoundation/Tests/RequestTest.php | 8 src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php | 15 src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php | 5 src/Symfony/Component/HttpFoundation/Tests/UrlHelperTest.php | 1 src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php | 2 src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php | 17 src/Symfony/Component/HttpKernel/HttpCache/Store.php | 52 src/Symfony/Component/HttpKernel/HttpCache/SubRequestHandler.php | 21 src/Symfony/Component/HttpKernel/Kernel.php | 6 src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php | 42 src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php | 41 src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php | 6 src/Symfony/Component/HttpKernel/Tests/Fixtures/WakingPayload.php | 30 src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php | 24 src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php | 4 src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php | 105 + src/Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.php | 28 src/Symfony/Component/HttpKernel/Tests/HttpCache/SubRequestHandlerTest.php | 60 src/Symfony/Component/HttpKernel/composer.json | 2 src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php | 10 src/Symfony/Component/Lock/Store/DoctrineDbalPostgreSqlStore.php | 8 src/Symfony/Component/Lock/Store/DoctrineDbalStore.php | 5 src/Symfony/Component/Lock/Store/MemcachedStore.php | 49 src/Symfony/Component/Lock/Store/MongoDbStore.php | 2 src/Symfony/Component/Lock/Store/PdoStore.php | 5 src/Symfony/Component/Lock/Store/PostgreSqlStore.php | 8 src/Symfony/Component/Lock/Store/RedisStore.php | 10 src/Symfony/Component/Lock/Tests/KeyTest.php | 3 src/Symfony/Component/Lock/Tests/Store/AbstractRedisStoreTestCase.php | 31 src/Symfony/Component/Lock/Tests/Store/DoctrineDbalPostgreSqlStoreTest.php | 74 + src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php | 26 src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php | 89 + src/Symfony/Component/Lock/Tests/Store/MongoDbStoreTest.php | 2 src/Symfony/Component/Lock/Tests/Store/MysqlDaylightSavingTimeTestTrait.php | 81 + src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php | 25 src/Symfony/Component/Lock/Tests/Store/PostgreSqlStoreTest.php | 42 src/Symfony/Component/Lock/Tests/Store/PredisStoreWithoutExceptionsTest.php | 60 src/Symfony/Component/Mailer/Tests/Transport/Smtp/SmtpTransportTest.php | 17 src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php | 3 src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php | 28 src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php | 8 src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php | 175 ++ src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php | 34 src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php | 27 src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineIntegrationTest.php | 33 src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrinePostgreSqlNotifyIntegrationTest.php | 187 ++ src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/PostgreSqlConnectionTest.php | 17 src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php | 8 src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php | 34 src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/ConnectionTest.php | 51 src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php | 8 src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php | 7 src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php | 5 src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php | 46 src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRemoveCommandTest.php | 5 src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php | 23 src/Symfony/Component/Messenger/Tests/Stamp/DelayStampTest.php | 7 src/Symfony/Component/Mime/Crypto/SMime.php | 12 src/Symfony/Component/Mime/Tests/AddressTest.php | 6 src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php | 18 src/Symfony/Component/Notifier/Bridge/Brevo/BrevoTransport.php | 2 src/Symfony/Component/Notifier/Bridge/Brevo/Tests/BrevoTransportTest.php | 15 src/Symfony/Component/Notifier/Bridge/Engagespot/EngagespotOptions.php | 2 src/Symfony/Component/Notifier/Bridge/Engagespot/README.md | 2 src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsOptions.php | 6 src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsTransport.php | 2 src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/README.md | 14 src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/Tests/MicrosoftTeamsTransportTest.php | 6 src/Symfony/Component/Notifier/Bridge/Ntfy/NtfyTransportFactory.php | 6 src/Symfony/Component/Notifier/Bridge/Ntfy/Tests/NtfyTransportFactoryTest.php | 20 src/Symfony/Component/Notifier/Bridge/Plivo/README.md | 2 src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransportFactory.php | 2 src/Symfony/Component/Notifier/Bridge/SpotHit/Tests/SpotHitTransportFactoryTest.php | 4 src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php | 36 src/Symfony/Component/PropertyAccess/PropertyAccessor.php | 69 - src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php | 70 + src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php | 47 src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php | 48 src/Symfony/Component/PropertyInfo/PhpStan/NameScopeFactory.php | 2 src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php | 32 src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpStanExtractorTest.php | 55 src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyParentImportingDummy.php | 22 src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitImportingDummy.php | 22 src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitInAnotherNamespace.php | 45 src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyImportingDummy.php | 26 src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTrait.php | 30 src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTraitWithUseDocBlock.php | 35 src/Symfony/Component/RateLimiter/CompoundLimiter.php | 24 src/Symfony/Component/RateLimiter/Policy/SlidingWindow.php | 52 src/Symfony/Component/RateLimiter/Policy/SlidingWindowLimiter.php | 7 src/Symfony/Component/RateLimiter/Policy/TokenBucketLimiter.php | 5 src/Symfony/Component/RateLimiter/RateLimit.php | 8 src/Symfony/Component/RateLimiter/Tests/CompoundLimiterTest.php | 82 + src/Symfony/Component/RateLimiter/Tests/Policy/SlidingWindowLimiterTest.php | 76 + src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php | 34 src/Symfony/Component/RateLimiter/Tests/RateLimitTest.php | 10 src/Symfony/Component/Routing/Generator/UrlGenerator.php | 40 src/Symfony/Component/Routing/Loader/Configurator/RoutingConfigurator.php | 1 src/Symfony/Component/Routing/Loader/Configurator/Traits/GlobResourceTrait.php | 38 src/Symfony/Component/Routing/Loader/PhpFileLoader.php | 3 src/Symfony/Component/Routing/Loader/XmlFileLoader.php | 6 src/Symfony/Component/Routing/Loader/YamlFileLoader.php | 3 src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php | 24 src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php | 13 src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php | 5 src/Symfony/Component/Routing/RouteCompiler.php | 3 src/Symfony/Component/Routing/Tests/Fixtures/dumper/compiled_url_matcher13.php | 4 src/Symfony/Component/Routing/Tests/Fixtures/glob/import_exclude.xml | 10 src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php | 204 ++ src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php | 13 src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php | 12 src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php | 3 src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php | 35 src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php | 133 + src/Symfony/Component/Routing/Tests/RouteCompilerTest.php | 11 src/Symfony/Component/Scheduler/Generator/Checkpoint.php | 28 src/Symfony/Component/Scheduler/Generator/MessageGenerator.php | 34 src/Symfony/Component/Scheduler/RecurringMessage.php | 3 src/Symfony/Component/Scheduler/Tests/Generator/CheckpointTest.php | 63 src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php | 162 ++ src/Symfony/Component/Scheduler/Tests/RecurringMessageTest.php | 5 src/Symfony/Component/Scheduler/Tests/Trigger/CronExpressionTriggerTest.php | 16 src/Symfony/Component/Scheduler/Tests/Trigger/PeriodicalTriggerTest.php | 36 src/Symfony/Component/Scheduler/Trigger/CronExpressionTrigger.php | 3 src/Symfony/Component/Scheduler/Trigger/PeriodicalTrigger.php | 23 src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php | 10 src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php | 8 src/Symfony/Component/Security/Core/Resources/translations/security.ar.xlf | 18 src/Symfony/Component/Security/Core/Resources/translations/security.eu.xlf | 6 src/Symfony/Component/Security/Core/Resources/translations/security.pt.xlf | 10 src/Symfony/Component/Security/Core/Resources/translations/security.pt_BR.xlf | 8 src/Symfony/Component/Security/Core/Resources/translations/security.tg.xlf | 83 + src/Symfony/Component/Security/Core/Resources/translations/security.uk.xlf | 2 src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php | 77 + src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php | 56 src/Symfony/Component/Security/Http/Authenticator/RemoteUserAuthenticator.php | 6 src/Symfony/Component/Security/Http/Authenticator/X509Authenticator.php | 21 src/Symfony/Component/Security/Http/EventListener/LoginThrottlingListener.php | 48 src/Symfony/Component/Security/Http/HttpUtils.php | 14 src/Symfony/Component/Security/Http/Impersonate/ImpersonateUrlGenerator.php | 9 src/Symfony/Component/Security/Http/RateLimiter/DefaultLoginRateLimiter.php | 41 src/Symfony/Component/Security/Http/Tests/Authenticator/RemoteUserAuthenticatorTest.php | 21 src/Symfony/Component/Security/Http/Tests/Authenticator/X509AuthenticatorTest.php | 15 src/Symfony/Component/Security/Http/Tests/EventListener/LoginThrottlingListenerTest.php | 293 ++++ src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php | 61 src/Symfony/Component/Security/Http/composer.json | 1 src/Symfony/Component/Semaphore/Store/RedisStore.php | 37 src/Symfony/Component/Semaphore/Tests/Store/AbstractRedisStoreTestCase.php | 34 src/Symfony/Component/Semaphore/Tests/Store/AbstractStoreTestCase.php | 15 src/Symfony/Component/Semaphore/Tests/Store/PredisStoreWithoutExceptionsTest.php | 90 + src/Symfony/Component/Serializer/Encoder/CsvEncoder.php | 23 src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php | 19 src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php | 135 + src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php | 2 src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php | 62 src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php | 48 src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php | 42 src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php | 686 ++++++++++ src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php | 12 src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php | 4 src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php | 267 +++ src/Symfony/Component/Serializer/Tests/SerializerTest.php | 8 src/Symfony/Component/Templating/PhpEngine.php | 9 src/Symfony/Component/Templating/Tests/PhpEngineTest.php | 26 src/Symfony/Component/Translation/Resources/bin/translation-status.php | 44 src/Symfony/Component/Translation/Resources/schemas/LICENSE.txt | 184 ++ src/Symfony/Component/Validator/Constraints/IbanValidator.php | 22 src/Symfony/Component/Validator/Constraints/IpValidator.php | 1 src/Symfony/Component/Validator/Constraints/NotCompromisedPasswordValidator.php | 2 src/Symfony/Component/Validator/Resources/bin/sync-iban-formats.php | 47 src/Symfony/Component/Validator/Resources/translations/validators.ca.xlf | 34 src/Symfony/Component/Validator/Resources/translations/validators.cs.xlf | 46 src/Symfony/Component/Validator/Resources/translations/validators.el.xlf | 4 src/Symfony/Component/Validator/Resources/translations/validators.eu.xlf | 142 +- src/Symfony/Component/Validator/Resources/translations/validators.he.xlf | 56 src/Symfony/Component/Validator/Resources/translations/validators.hu.xlf | 44 src/Symfony/Component/Validator/Resources/translations/validators.mn.xlf | 2 src/Symfony/Component/Validator/Resources/translations/validators.pt.xlf | 70 - src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf | 28 src/Symfony/Component/Validator/Resources/translations/validators.tg.xlf | 651 +++++++++ src/Symfony/Component/Validator/Resources/translations/validators.uz.xlf | 62 src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php | 10 src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php | 5 src/Symfony/Component/VarDumper/Caster/Caster.php | 11 src/Symfony/Component/VarDumper/Caster/LinkStub.php | 4 src/Symfony/Component/VarDumper/Dumper/CliDumper.php | 3 src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php | 4 src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php | 20 src/Symfony/Component/VarDumper/Tests/Dumper/HtmlDumperTest.php | 37 src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php | 3 src/Symfony/Component/Workflow/Tests/Dumper/GraphvizDumperTest.php | 18 src/Symfony/Component/Workflow/Tests/RegistryTest.php | 8 src/Symfony/Component/Yaml/Inline.php | 47 src/Symfony/Component/Yaml/Parser.php | 28 src/Symfony/Component/Yaml/ParserState.php | 18 src/Symfony/Component/Yaml/Tests/InlineTest.php | 69 + src/Symfony/Component/Yaml/Tests/ParserTest.php | 165 ++ src/Symfony/Contracts/HttpClient/Test/Fixtures/web/index.php | 5 391 files changed, 11695 insertions(+), 1944 deletions(-) dpkg-source: warning: cannot verify inline signature for /srv/release.debian.org/tmp/tmpbe38ocpp/symfony_6.4.50+dfsg-0+deb13u1.dsc: no acceptable signature found dpkg-source: warning: cannot verify inline signature for /srv/release.debian.org/tmp/tmpbe38ocpp/symfony_6.4.51+dfsg-0+deb13u1.dsc: no acceptable signature found diff -Nru symfony-6.4.50+dfsg/.agents/skills/security-triage/SKILL.md symfony-6.4.51+dfsg/.agents/skills/security-triage/SKILL.md --- symfony-6.4.50+dfsg/.agents/skills/security-triage/SKILL.md 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/.agents/skills/security-triage/SKILL.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,175 +0,0 @@ ---- -name: security-triage -description: > - Triage a reported security finding into a disposition: a private CVE - (coordinated disclosure + advisory), a public hardening PR (fix in the open, - no CVE), or not-a-security-issue (reply to reporter). Assigns severity and - affected maintained branches, and routes to the next step. Use when the user - says "does this need a CVE", "CVE or hardening", "triage this report", "is - this a security issue", "classify this finding", or "how should we disclose this". ---- - -# Symfony Security Triage - -Decides how a finding is handled, not whether the code is wrong. It complements -`symfony-security-review` (which finds missing hardening) by making the disclosure -call on a report. - -The three dispositions and the conventions that record them: - -| Disposition | Label | Branch prefix | Process | -|---|---|---|---| -| **CVE** | `Has CVE` + severity | `cve-*` | Private fix, GHSA/CVE, credit, blog post, coordinated release | -| **Public hardening** | none / `Not a security issue` | `harden-*`, `hardening-*`, `pin-*`, `fix-*` | Normal open PR, changelog, no embargo | -| **Not a security issue** | `Not a security issue` / `Won't fix` | n/a or `fix-*` | Reply to reporter; optionally a doc/robustness PR | - -This skill produces a recommendation. The final call belongs to the Symfony security -team; treat its output as a structured argument, and defer to `symfony.com/security` -for the authoritative "what is not a vulnerability" list. - -## Progress checklist - -- [ ] Step 0: Establish the facts (reproduce, scope, trust model) -- [ ] Step 1: Apply the disposition decision tree -- [ ] Step 2: Assign severity and affected maintained branches -- [ ] Step 3: Route (branch prefix, labels, next workflow, reporter reply) - -## Confirmation rule - -Whenever this skill says **"Wait for confirmation"**, treat anything other than an -explicit affirmative as **no**: stop and ask the user how they want to proceed. - ---- - -## Step 0 — Establish the facts - -Before classifying, pin down four things. Guessing any of them produces a wrong call. - -1. **Reachability**: is the vulnerable code on a path reachable from untrusted input in - a default configuration, or does it need opt-in/insecure config? -2. **Actor and precondition**: what must the attacker already have? Unauthenticated and - remote is the worst case; "already controls the serialized bytes" or "already has the - app secret" usually means the precondition is itself game-over. -3. **Impact**: RCE, auth/authz bypass, SSRF to internal, signature/secret bypass that - accepts forged input, XSS on a default-rendered surface, secret disclosure, open - redirect, session fixation, or "only" DoS / info of low value. -4. **Contract**: is the component meant to defend this boundary (router, - HttpFoundation/HttpClient, Security, webhook verification, HtmlSanitizer, Mime - parsing), or is the unsafe behaviour documented as the caller's responsibility - (deserializing untrusted bytes, a trusted-channel feature such as ESI, - `template_from_string`)? - -Reproduce if at all possible; an unreproducible report is not yet triable. - -## Step 1 — Disposition decision tree - -Apply in order. The first matching bucket wins. - -### It is **not a security issue** if any of these hold -- **Pure DoS / resource exhaustion.** Generally excluded from the CVE pipeline. Fix as - hardening with a limit if cheap, but no CVE. -- **Requires misuse contrary to documentation**, with no default-config attack. The - component is not contracted to defend this (e.g. deserializing untrusted bytes through - an API documented as trusted-only; using a trusted-channel feature to reach internal hosts). -- **Dev-only tooling** (profiler, debug, web-profiler) manifesting only in a dev environment. -- **Precondition is already game-over** (attacker already holds the app secret, controls - the deserialized input contract, or has local/physical access). -- **Not reproducible**, or rooted in a third-party dependency outside Symfony's control. -- **Not a realistic bypass** (a comparison nuance with no working exploit, etc.). - -### It is a **CVE** only if **all** of these hold -1. **Default-reachable**: exploitable against a default or documented-safe config. -2. **Expected actor**: the attacker is at or below the trust level the boundary is - meant to enforce (typically unauthenticated/remote, or a lower-privileged user - escalating), with no game-over precondition. -3. **Contracted boundary**: the component is meant to defend this (see Step 0.4). -4. **Real impact**: RCE, auth/authz bypass, SSRF to internal, sanitizer/signature - bypass accepting forged input on a sensitive sink, stored/reflected XSS on a default - surface, secret disclosure, or open redirect with meaningful reach. -5. **Maintained**: the vulnerable code ships in a maintained version. - -### Otherwise it is **public hardening** -A genuine improvement where a CVE condition fails. Typical shapes: -- **Defense-in-depth** on top of an existing control, or that only matters once another - bug already holds (an `__unserialize` `__toString` trampoline guard needs a pre-existing - untrusted `unserialize()` entry to matter). -- **Safer-default change** where the old default was not a vulnerability under the - threat model (adding a webhook IP allowlist, pinning the HMAC algorithm). -- **Limited impact or exposure** even though a boundary is technically crossed (a forged - webhook against an opt-in endpoint with a user-configured secret injects only a - delivery-status event). -- **Robustness** improvements (input-length caps, broader sanitizer coverage). - -## Step 2 — Severity and affected branches - -**Severity** (match the `low`/`medium`/`high` labels; CVSS is a sanity check, not the goal): -- **high**: unauthenticated RCE, auth bypass, full sanitizer bypass enabling stored XSS, SSRF reaching internal services. -- **medium**: reflected XSS, open redirect, signature bypass with bounded impact, info disclosure of non-trivial data. -- **low**: defense-in-depth, narrow-config or low-impact issues, most hardening. - -**Affected branches**: find the oldest version where the vulnerable code exists, intersect -with `maintained_versions` from `https://symfony.com/releases.json`. Fix on the lowest -maintained affected branch, then merge up (see the `merge-up` skill). Record the -oldest exposure even if it predates maintained versions. - -## Step 3 — Route - -State the recommendation as: **disposition + severity + affected maintained branches + -the one-line rationale (which decision-tree conditions decided it)**, then route: - -- **CVE**: name the branch `cve--`; apply `Has CVE` + severity; the fix is - prepared privately and goes through the coordinated-disclosure process (request a - GHSA/CVE, credit the reporter, prepare the security release and blog post). Do **not** - open a public PR or push to a public remote before release. **Wait for confirmation** - before any outward step. -- **Public hardening**: name the branch `harden-`/`hardening-`/`pin-`/`fix-`; open a - normal PR with a CHANGELOG entry; use `symfony-security-review` to confirm the fix and - `hardening-rule` to add a durable gate where the class recurs. -- **Not a security issue**: draft a short, factual reply to the reporter explaining why - (cite the contract/threat-model reason), and optionally a doc clarification or - low-priority robustness PR. Apply `Not a security issue` / `Won't fix`. - -In every case, the fix follows TDD, component-scoped tests, no em-dashes, -no Claude/Anthropic credit, comments sparingly, no issue references in code. - ---- - -## Worked examples (abstracted patterns) - -| Finding shape | Disposition | Deciding factor | -|---|---|---| -| SSRF filter (private-network client) bypassed in a default configuration | **CVE** | default control bypassed, unauthenticated reach | -| HTML sanitizer lets a `javascript:` URL through on a default profile | **CVE** | sanitizer's core contract bypassed, stored XSS | -| URL generator emits a path that crosses a routing boundary by default | **CVE** | boundary crossed in default use | -| A signed transport decodes the payload before verifying its MAC | **CVE candidate, high** | pre-auth RCE if signing is meant to defend a malicious broker; confirm the trust model | -| Webhook signature compared with `!==`, or the secret is ignored | **Hardening** | opt-in endpoint, user-configured secret, bounded impact | -| `__unserialize` assigns a string property without a `\Stringable` guard | **Hardening** | needs a pre-existing untrusted `unserialize()` entry (game-over precondition) | -| Input-length cap / broader sanitizer coverage added | **Hardening** | robustness, not a default-exploitable bypass | -| Unbounded recursion / regex backtracking / cache growth on input | **Hardening, low** | pure DoS, excluded from the CVE pipeline | -| Deserializing bytes through an API documented as trusted-only | **Not a security issue** | documented contract, caller's responsibility | -| A trusted-channel feature (e.g. ESI/SSI) used to reach internal hosts | **Not a security issue** | trusted by design | -| Case-insensitive host allowlist with no working bypass | **Not a security issue** | not a realistic bypass | - -## Gotchas - -- **"Boundary crossed" does not imply CVE.** Impact and exposure decide it. A forged - webhook against an opt-in, user-secret endpoint is hardening; an SSRF filter bypass in - default use is a CVE. -- **DoS is the most common miscategorisation.** Resource exhaustion is hardening/low, - not a CVE, even when trivially triggerable. -- **Defense-in-depth tells.** If exploiting the finding requires another, already-present - vulnerability or a leaked secret, it is hardening. -- **Trust-model questions are for the maintainer.** A signed-transport verify-order case - turns on whether the broker is trusted; surface the question, do not assume. -- **Embargo discipline.** Never name a CVE-bound finding, push a `cve-*` branch, or open a - public PR for a CVE-class finding before the coordinated release. **Wait for confirmation.** -- **Defer to authority.** `symfony.com/security` is the source of truth for what is not a - vulnerability; this skill encodes observed practice, not policy. - -## Error handling - -- If reachability or trust model is unknown, say so and triage as needs-human-judgement; - do not force a disposition. -- Security reports are handled privately. Do not echo report contents into public - artifacts, commit messages, or branch names that leak the vulnerability before release. -- Never push to a public remote during CVE triage. Stop and hand back to the user. diff -Nru symfony-6.4.50+dfsg/.agents/skills/symfony-security-review/SKILL.md symfony-6.4.51+dfsg/.agents/skills/symfony-security-review/SKILL.md --- symfony-6.4.50+dfsg/.agents/skills/symfony-security-review/SKILL.md 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/.agents/skills/symfony-security-review/SKILL.md 2026-11-25 09:18:34.000000000 +0000 @@ -179,7 +179,7 @@ - **Low**: DoS / resource exhaustion / defense-in-depth only. - **Not a finding**: excluded by a decision boundary (say which one). -When a finding moves on to `security-triage`, Critical and High both map to its +When a finding goes to the security team, Critical and High both map to the `high` label; Medium and Low map to `medium` and `low`. For each real finding, state whether a **hardening regression test** is required so diff -Nru symfony-6.4.50+dfsg/.codespellrc symfony-6.4.51+dfsg/.codespellrc --- symfony-6.4.50+dfsg/.codespellrc 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/.codespellrc 2026-11-25 09:18:34.000000000 +0000 @@ -6,4 +6,5 @@ # "ser" is the $ser variable of Config's ResourceCheckerConfigCache # "atleast" is PHPUnit's TestCase::atLeast() # "grigorian" is the name of an author of Console's Table helper -ignore-words-list = smove,hastable,signall,caf,ser,atleast,grigorian +# "truncat" is the expected output of FormatterHelper::truncate() in Console's FormatterHelperTest +ignore-words-list = smove,hastable,signall,caf,ser,atleast,grigorian,truncat diff -Nru symfony-6.4.50+dfsg/.github/workflows/integration-tests.yml symfony-6.4.51+dfsg/.github/workflows/integration-tests.yml --- symfony-6.4.50+dfsg/.github/workflows/integration-tests.yml 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/.github/workflows/integration-tests.yml 2026-11-25 09:18:34.000000000 +0000 @@ -251,6 +251,11 @@ php .github/sync-translations.php git diff --exit-code src/ || (echo '::error::Run "php .github/sync-translations.php" to fix XLIFF files.' && exit 1) + - name: Start MySQL + run: | + sudo systemctl start mysql.service + mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -h127.0.0.1 -uroot -proot mysql + - name: Run tests run: ./phpunit --group integration -v env: @@ -269,12 +274,15 @@ KAFKA_BROKER: 127.0.0.1:9092 POSTGRES_HOST: localhost PGBOUNCER_HOST: localhost:6432 + MYSQL_HOST: 127.0.0.1 + MYSQL_USERNAME: root + MYSQL_PASSWORD: root #- name: Run HTTP push tests # if: matrix.php == '8.1' # run: | # [ -d .phpunit ] && mv .phpunit .phpunit.bak - # wget -q https://github.com/symfony/binary-utils/releases/download/v0.1/vulcain_0.1.3_Linux_x86_64.tar.gz -O - | tar xz && mv vulcain /usr/local/bin + # wget -q https://github.com/symfony-tools/binary-utils/releases/download/v0.1/vulcain_0.1.3_Linux_x86_64.tar.gz -O - | tar xz && mv vulcain /usr/local/bin # docker run --rm -e COMPOSER_ROOT_VERSION -v $(pwd):/app -v $(which composer):/usr/local/bin/composer -v $(which vulcain):/usr/local/bin/vulcain -w /app php:8.1-alpine ./phpunit src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php --filter testHttp2Push # sudo rm -rf .phpunit # [ -d .phpunit.bak ] && mv .phpunit.bak .phpunit diff -Nru symfony-6.4.50+dfsg/.github/workflows/unit-tests.yml symfony-6.4.51+dfsg/.github/workflows/unit-tests.yml --- symfony-6.4.50+dfsg/.github/workflows/unit-tests.yml 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/.github/workflows/unit-tests.yml 2026-11-25 09:18:34.000000000 +0000 @@ -116,7 +116,7 @@ # For the highest branch, in high-deps mode, the version before it is checked out and tested with the locally patched components if [[ "${{ matrix.mode }}" = high-deps ]]; then - SYMFONY_VERSIONS=$(git ls-remote -q --heads "$GIT_REMOTE" | cut -f2 | grep -o '/[1-9][0-9]*\.[0-9].*' | sort -V) + SYMFONY_VERSIONS=$(git ls-remote -q --heads "$GIT_REMOTE" | cut -f2 | grep -o '/[1-9][0-9]*\.[0-9][0-9]*$' | sort -V) if [[ $SYMFONY_VERSION = $(echo "$SYMFONY_VERSIONS" | tail -n 1 | sed s/.//) ]]; then echo FLIP='^' >> $GITHUB_ENV @@ -249,7 +249,7 @@ run: | mkdir build cd build - wget -q https://github.com/symfony/binary-utils/releases/download/v0.1/php-8.1.2-pcntl-sigchild.tar.bz2 + wget -q https://github.com/symfony-tools/binary-utils/releases/download/v0.1/php-8.1.2-pcntl-sigchild.tar.bz2 tar -xjf php-8.1.2-pcntl-sigchild.tar.bz2 cd .. diff -Nru symfony-6.4.50+dfsg/.github/workflows/windows.yml symfony-6.4.51+dfsg/.github/workflows/windows.yml --- symfony-6.4.50+dfsg/.github/workflows/windows.yml 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/.github/workflows/windows.yml 2026-11-25 09:18:34.000000000 +0000 @@ -26,6 +26,7 @@ SYMFONY_DEPRECATIONS_HELPER: 'strict' ANSICON: '121x90 (121x90)' SYMFONY_PHPUNIT_DISABLE_RESULT_CACHE: '1' + SYMFONY_PHPUNIT_MAX_PARALLEL: '12' steps: - name: Setup Git @@ -44,14 +45,14 @@ run: | $env:Path = 'c:\php;' + $env:Path mkdir c:\php && cd c:\php - iwr -outf php.zip https://github.com/symfony/binary-utils/releases/download/v0.1/php-8.1.0-Win32-vs16-x86.zip + iwr -MaximumRetryCount 5 -RetryIntervalSec 10 -outf php.zip https://github.com/symfony-tools/binary-utils/releases/download/v0.1/php-8.1.0-Win32-vs16-x86.zip 7z x php.zip -y >nul cd ext - iwr -outf php_apcu.zip https://github.com/symfony/binary-utils/releases/download/v0.1/php_apcu-5.1.21-8.1-ts-vs16-x86.zip + iwr -MaximumRetryCount 5 -RetryIntervalSec 10 -outf php_apcu.zip https://github.com/symfony-tools/binary-utils/releases/download/v0.1/php_apcu-5.1.21-8.1-ts-vs16-x86.zip 7z x php_apcu.zip -y >nul - iwr -outf php_igbinary.zip https://github.com/symfony/binary-utils/releases/download/v0.1/php_igbinary-3.2.16-8.1-ts-vs16-x86.zip + iwr -MaximumRetryCount 5 -RetryIntervalSec 10 -outf php_igbinary.zip https://github.com/symfony-tools/binary-utils/releases/download/v0.1/php_igbinary-3.2.16-8.1-ts-vs16-x86.zip 7z x php_igbinary.zip -y >nul - iwr -outf php_redis.zip https://github.com/symfony/binary-utils/releases/download/v0.1/php_redis-5.3.7-8.1-ts-vs16-x86.zip + iwr -MaximumRetryCount 5 -RetryIntervalSec 10 -outf php_redis.zip https://github.com/symfony-tools/binary-utils/releases/download/v0.1/php_redis-5.3.7-8.1-ts-vs16-x86.zip 7z x php_redis.zip -y >nul cd .. Copy php.ini-development php.ini-min @@ -81,7 +82,7 @@ "intl.error_level=0" >> php.ini-max Copy php.ini-max php.ini cd ${{ github.workspace }} - iwr -outf composer.phar https://getcomposer.org/download/latest-stable/composer.phar + iwr -MaximumRetryCount 5 -RetryIntervalSec 10 -outf composer.phar https://getcomposer.org/download/latest-stable/composer.phar - name: Install dependencies id: setup diff -Nru symfony-6.4.50+dfsg/.github/workflows/zizmor.yml symfony-6.4.51+dfsg/.github/workflows/zizmor.yml --- symfony-6.4.50+dfsg/.github/workflows/zizmor.yml 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/.github/workflows/zizmor.yml 2026-11-25 09:18:34.000000000 +0000 @@ -28,7 +28,7 @@ persist-credentials: false - name: Run zizmor - uses: zizmorcore/zizmor-action@53290badfa369cb0bf7ad16342cb62c2fa47ac7b # v0.8.0 + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 with: advanced-security: false annotations: true diff -Nru symfony-6.4.50+dfsg/CHANGELOG-6.4.md symfony-6.4.51+dfsg/CHANGELOG-6.4.md --- symfony-6.4.50+dfsg/CHANGELOG-6.4.md 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/CHANGELOG-6.4.md 2026-11-25 09:18:34.000000000 +0000 @@ -7,6 +7,295 @@ To get the diff for a specific change, go to https://github.com/symfony/symfony/commit/XXX where XXX is the change hash To get the diff between two versions, go to https://github.com/symfony/symfony/compare/v6.4.0...v6.4.1 +## 6.4.51 (2026-11-25) + +### AssetMapper + + * bug #68081 [AssetMapper] Fix comparing 0.x and pre-release versions in `importmap:outdated` and `importmap:audit` (nicolas-grekas) + * bug #68076 [AssetMapper] Compare pre-releases in importmap:outdated (Amoifr) + * minor #68056 [AssetMapper] Backdate the meta file too in `CachedMappedAssetFactoryTest` (nicolas-grekas) + +### BrowserKit + + * bug #68061 [BrowserKit][HttpClient] Don't send credentials to other origins on redirects (nicolas-grekas) + +### Cache + + * bug #68361 [Cache] Add support for relay 0.62 (nicolas-grekas) + * bug #68123 [Cache] Check cache keys even when assertions are disabled (nicolas-grekas) + * bug #68091 [Cache] Fix ChainAdapter losing the expiry of items propagated from FilesystemAdapter (skybleak333) + * bug #68090 [Cache] Fix items without expiry read back as expiring in 2090 (skybleak333) + * bug #68113 [Cache][Messenger][Notifier] Fix AMQP, Memcached, Ntfy and Spot-Hit misreading DSN option values (nicolas-grekas) + * bug #68039 [Cache][Messenger] Fix Redis connections and Messenger transports misreading integer and boolean options (nicolas-grekas) + * bug #68038 [Cache][HttpFoundation][Lock] Fix memcached items with a TTL ending after 2038 expiring at once (nicolas-grekas) + * bug #67850 [Cache] Declare the temporary tag set as KEYS[2] in RedisTagAwareAdapter::doInvalidate() (srebb) + * bug #67864 [Cache] Fix fetching long keys with MemcachedAdapter::getItems() (lazerg) + * minor #68223 [Cache] Fix dead phpredis and predis links in comments (farisbasha) + +### Config + + * bug #67977 [Config][Routing] Fix excluded paths in XML route imports and in `GlobResource` ids (nicolas-grekas) + * bug #67952 [Config] Fix DirectoryResource checking the parent directory on Windows (nicolas-grekas) + * bug #67927 [Config] Fix EnumNode error messages for INF, NAN and enum cases without a backing value (nicolas-grekas) + * bug #67911 [Config] Do not treat NAN as a placeholder (haraldpdl) + +### Console + + * bug #67934 [Console] Fix formatting and wrapping text with escaped tag delimiters (nicolas-grekas) + * bug #67903 [Console] Fix wrapping escaped tags and text wider than 138 columns (nicolas-grekas) + * bug #67897 [Console] Fix the width of tags and URLs when wrapping text (nicolas-grekas) + * bug #67890 [Console] Count wide characters as two columns when wrapping and truncating (b84330808) + +### DependencyInjection + + * bug #67976 [DependencyInjection][Routing] Track the glob resource of `import()` so new files are detected (abp002) + +### DoctrineBridge + + * security #cve-2026-133759 [DoctrineBridge] Refuse the copies of previous remember-me tokens as series, and delete them with their token (nicolas-grekas) + * minor #68104 [DoctrineBridge] Use the schema editor API of Doctrine ORM in tests (nicolas-grekas) + +### ExpressionLanguage + + * security #cve-2026-133760 [ExpressionLanguage] Check the nesting level of short ternaries in linear time (nicolas-grekas) + +### Finder + + * bug #67926 [Finder] Fix Glob::toRegex() when the delimiter is a slash (nicolas-grekas) + * bug #67915 [Finder] Fix three bracket expressions Glob::toRegex() gets wrong (KalimeroMK) + +### Form + + * bug #68372 [Form][Security] Fix inaccurate Arabic translations (malekkadri) + * bug #67962 [Form] Review Macedonian (mk) translations (KalimeroMK) + * bug #67865 [Form] Let a validation_groups callable return false to disable validation (KalimeroMK) + * minor #68412 [Form][Security][Validator] Add Tajik (tg) translations (ismoil77) + * minor #68407 [Form] Update Tagalog (tl) validator translations (edmer664) + * minor #68329 [Form][Security][Translation][Validator] Move the mixed-alphabet check to translation-status.php (nicolas-grekas) + * minor #68296 [Form][Security][Validator] Fix letters from another alphabet in el, mn and uk translations (bardrop, nicolas-grekas) + * minor #68319 [Form][Validator] Refine Czech validation messages (hrabosh) + * minor #68289 [Form][Validator] Review Hebrew (he) translations (oriko9) + * minor #68269 [Form][Security][Validator] Review Basque (eu) translations (ikerib) + * minor #68222 [Form][Security][Validator] Review Portuguese (pt) translations (TiagoCruz1224) + * minor #68151 [Form][Validator] Review Uzbek (uz) translations (turgunovabb) + * minor #68071 [Form][Validator] Review Hungarian translations (connorhu) + * minor #67989 [Form][Validator] Review Catalan (ca) translations (Victor-369) + * minor #67866 [Form] Review Bulgarian (bg) translations (alkinbg) + +### FrameworkBundle + + * security #cve-2026-133745 [FrameworkBundle][Routing] Don't let router redirects send paths that start with // to another host (nicolas-grekas) + * bug #68112 [FrameworkBundle] Give the test session listener the same services as the real one (nicolas-grekas) + * bug #68065 [FrameworkBundle][HttpClient] Match scopes against the URL without its userinfo (nicolas-grekas) + +### HtmlSanitizer + + * security #cve-2026-133756 [HtmlSanitizer] Strip the whitespace that browsers skip before the time of a meta refresh (nicolas-grekas) + * bug #67886 [HtmlSanitizer] Don't treat elements and attributes that act on the page as safe (nicolas-grekas) + * bug #67885 [HtmlSanitizer] Block `html` and `body` in `allowSafeElements()` and don't let links expose `window.opener` (nicolas-grekas) + * bug #67879 [HtmlSanitizer] Don't treat `link`, `meta`, `plaintext` and `referrerpolicy` as safe (nicolas-grekas) + +### HttpClient + + * security #cve-2026-134792 [HttpClient] Read HTTP_PROXY from the environment, not from $_SERVER, on the CLI (nicolas-grekas) + * security #cve-2026-133758 [HttpClient] Let the client decorated by NoPrivateNetworkHttpClient apply its own default options (nicolas-grekas) + * security #cve-2026-133757 [HttpClient] Don't let decorated clients add their default credentials to cross-origin redirects of NoPrivateNetworkHttpClient (nicolas-grekas) + * bug #68406 [HttpClient] Set redirect_url on mocked redirect responses (nicolas-grekas) + * bug #68248 [HttpClient] Don't send the fragment of URLs to proxies with NativeHttpClient (nicolas-grekas) + * bug #68131 [HttpClient] Fix parsing an SSE event with an empty type or an empty first data line (skybleak333) + * bug #68120 [HttpClient] Don't report the user info of URLs (nicolas-grekas) + * bug #68114 [HttpClient] Fix AmpHttpClient sending `Content-Length: 0` for pipe bodies (nicolas-grekas) + * bug #68095 [HttpClient] Fix sending an empty body when a stream body is sent again (skybleak333, nicolas-grekas) + * bug #68093 [HttpClient] Fix CachingHttpClient::stream() yielding a stream instead of its chunks (skybleak333) + * bug #67925 [HttpClient] Keep the response decorated by TraceableResponse usable until it is freed (lazerg) + * bug #67859 [HttpClient] Reject `CURLOPT_COOKIE` and `CURLOPT_UNRESTRICTED_AUTH` in `extra.curl` (nicolas-grekas) + * bug #67842 [HttpClient][Validator] Add the deprecated IPv6 site-local range to the private subnets (nicolas-grekas) + * bug #67849 [HttpClient] Fix a typo in NoPrivateNetworkHttpClient (Jontsa) + * bug #67858 [HttpClient] Use the first `Location` header in CurlHttpClient, like curl does (nicolas-grekas) + * minor #68245 [HttpClient] Fix a max_duration test that fails on slow machines (nicolas-grekas) + * minor #68202 [HttpClient] Pause the max-duration test well past its limit, so that a slow machine is not taken for a wait on the pause (phcorp) + * minor #68102 [HttpClient] Document that the proxy must block private destinations behind NoPrivateNetworkHttpClient (nicolas-grekas) + * minor #68119 [HttpClient] Fix testing redirects with user info on libcurl < 8.23 (nicolas-grekas) + +### HttpFoundation + + * security #cve-2026-133748 [HttpFoundation] Match IPv4-mapped addresses against IPv4 subnets in IpUtils::checkIp() (nicolas-grekas) + * security #cve-2026-133743 [HttpFoundation][HttpKernel] Trust 127.0.0.1 only for the requests built by SubRequestHandler (nicolas-grekas) + * bug #67921 [HttpFoundation] Check IPv4-mapped, 6to4, Teredo and NAT64 addresses as their IPv4 address in IpUtils::isPrivateIp() (nicolas-grekas) + * bug #67874 [HttpFoundation] Cap the size of the cache of IpUtils (nicolas-grekas) + * minor #68227 [HttpFoundation] Fix the dead OWASP cheat sheet link in JsonResponse (farisbasha) + +### HttpKernel + + * bug #67950 [HttpKernel] Fix HttpCache serving must-revalidate responses stale while another process revalidates them (nicolas-grekas) + * bug #67949 [HttpKernel] Fix the HttpCache lock being released when another process stores the same URL (nicolas-grekas) + * bug #67946 [HttpKernel] Fix HttpCache serving a 503 after validating a no-cache entry when the cache is locked (nicolas-grekas) + * bug #67944 [HttpKernel] Release the cache lock when a revalidated response is not stored (KalimeroMK) + * minor #68321 [HttpKernel] Fix transient failure of InlineFragmentRendererTest (clfer) + * minor #68249 [HttpKernel] Fix transient failures in ResponseCacheStrategyTest (nicolas-grekas) + * minor #68244 [HttpKernel][SecurityBundle] Make time-dependent tests independent of second boundaries (nicolas-grekas) + +### Lock + + * bug #68197 [Lock] Fix the Oracle clock of DoctrineDbalStore and PdoStore counting the time of day twice (nicolas-grekas) + * bug #68174 [Lock] Fix the MySQL clock of DoctrineDbalStore and PdoStore jumping an hour when DST ends (jack-worman) + * bug #68041 [Lock] Fix MemcachedStore with keys that memcached rejects (nicolas-grekas) + * bug #68037 [Lock][Semaphore] Fix RedisStore taking Predis error replies for a success (nicolas-grekas) + * bug #68029 [Lock] Fix RedisStore taking Predis error replies for a success (skybleak333) + * bug #68028 [Lock] Fix MemcachedStore locks with a TTL longer than 30 days expiring at once (skybleak333) + * bug #68027 [Lock] Fix MongoDbStore::exists() failing before the store connected (skybleak333) + * bug #67996 [Lock] Fix the PostgreSQL stores inheriting the locks of freed connections (nicolas-grekas) + * bug #67994 [Lock] Fix DoctrineDbalPostgreSqlStore refusing locks after the session is lost (skybleak333) + * minor #68080 [Lock] Freeze the clock in `KeyTest` (nicolas-grekas) + +### Mailer + + * bug #67980 [Mailer] Don't take a word of the SMTP reply as the message id (nicolas-grekas) + +### Messenger + + * bug #68013 [Messenger] Fix LISTEN/NOTIFY with the DBAL pgsql driver (FluffyDiscord) + * bug #67912 [Messenger] Stop the worker when a signal arrives before it is created (haraldpdl) + +### Mime + + * bug #67871 [Mime] Fix SMimeSigner splitting a CRLF across chunk boundaries (w3dev-dk) + * minor #68325 [Mime] Fix AddressTest with egulias/email-validator 4.0.5 (phcorp) + +### Notifier + + * bug #68105 [Notifier][Brevo] Use the non-deprecated transactionalSMS/send endpoint (amenophis) + * bug #68103 [Notifier][MicrosoftTeams] Fix text-only messages sent to Workflows webhooks and document their setup (nicolas-grekas) + * minor #68220 [Notifier] Update dead Engagespot and Plivo documentation links (farisbasha) + +### PhpUnitBridge + + * minor #68211 [PhpUnitBridge] Limit how many suites run at once on the Windows CI (nicolas-grekas) + +### PropertyAccess + + * bug #67902 [PropertyAccess] Limit the caches that grow with the input (nicolas-grekas) + +### PropertyInfo + + * bug #68294 [PropertyInfo] Limit the caches that grow with the input (nicolas-grekas) + * bug #67958 [PropertyInfo] Fix reading the PHPDoc of abstract trait methods after a docblock on the `use` statement (nicolas-grekas) + * bug #67956 [PropertyInfo] Fix reading the PHPDoc of trait members and of inherited promoted properties (nicolas-grekas) + * bug #67948 [PropertyInfo] Fix resolving the PHPDoc types of trait methods and of classes using traits (nicolas-grekas) + +### PsrHttpMessageBridge + + * bug #68364 [PsrHttpMessageBridge] Don't read the stream of an uploaded file that has an upload error (vasikmansuri) + +### RateLimiter + + * bug #68057 [RateLimiter] Fix `RateLimit::wait()` for delays over 35 minutes on 32-bit platforms (nicolas-grekas) + * bug #68040 [RateLimiter] Fix CompoundLimiter telling to retry before all its limiters accept the hit again (nicolas-grekas) + * bug #68021 [RateLimiter] Fix SlidingWindowLimiter letting reservations through faster than the limit (skybleak333) + * bug #68019 [RateLimiter] Fix TokenBucketLimiter counting the wait for the next tokens from now (skybleak333) + * bug #68016 [RateLimiter] Fix CompoundLimiter accepting a hit that one limiter refused (skybleak333) + +### Routing + + * security #cve-2026-133754 [Routing] Reject host parameters that contain forbidden characters (nicolas-grekas) + * security #cve-2026-133746 [Routing] Don't let generated URLs point to another host (nicolas-grekas) + * bug #68018 [Routing] Fix compiled matchers accepting extra trailing slashes on static routes (nicolas-grekas) + * bug #68003 [Routing] Use the host value of variables that are both in the host and the path in compiled matchers (nicolas-grekas) + * bug #68014 [Routing] Fix the order of routes with host variables in compiled matchers (nicolas-grekas) + * bug #68002 [Routing] Make named groups in requirements non-capturing, like unnamed ones (nicolas-grekas) + * bug #67929 [Routing] Prevent `{_route}` host placeholders from matching the path in compiled matchers (nicolas-grekas) + +### Scheduler + + * bug #68323 [Scheduler] Fix the "nth weekday" cron syntax being treated as a hashed expression (thejesh23) + * bug #68089 [Scheduler] Fix a message added to a running schedule running all its earlier slots at once (skybleak333) + * bug #68034 [Scheduler] Fix losing or repeating runs, and truncating float intervals (nicolas-grekas) + * bug #68026 [Scheduler] Fix ISO 8601 intervals with days, weeks or months being counted as a fixed number of seconds (skybleak333) + * bug #68025 [Scheduler] Fix cron triggers without a timezone taking the one of the last run after a restart (skybleak333) + * bug #68030 [Scheduler] Fix the worker crashing when its lock expired during a long run (skybleak333) + +### Security + + * security #cve-2026-134790 [Security] Parse the host of redirect targets like browsers do (nicolas-grekas) + * security #cve-2026-133753 [Security] Require every attribute to be granted with the unanimous strategy (nicolas-grekas) + * security #cve-2026-133749 [Security] Run the checkPostAuth() method of user checkers in GuardAuthenticatorHandler::authenticateUserAndHandleSuccess() (nicolas-grekas) + * bug #68359 [Security][Validator] Review Brazilian Portuguese (pt_BR) translations (andretorresdg) + * bug #68078 [Security][SecurityBundle] Fix profiles listing the access decisions of previous requests (nicolas-grekas) + * bug #68008 [Security] Count login attempts before checking their credentials (nicolas-grekas) + * bug #68010 [Security] Limit login attempts of IPv6 clients by their /64 network (nicolas-grekas) + * bug #68007 [Security] Keep the IP limit of login throttling on successful logins (nicolas-grekas) + * bug #67991 [Security] Remove accents and invisible characters from login throttling keys (nicolas-grekas) + * bug #67845 [Security] Fix the login throttling message announcing one minute too many (lazerg) + * bug #67875 [Security] Reject X509 DNs whose identifier attribute appears more than once (nicolas-grekas) + * bug #67876 [Security] Clear the pre-authenticated token when REMOTE_USER is empty (nicolas-grekas) + +### SecurityBundle + + * bug #68098 [SecurityBundle] Avoid unintended session usage with remember-me on stateless routes (isihussain) + * bug #68075 [SecurityBundle] Put the listeners of a lazy firewall context back after tracing them (Amoifr) + +### Semaphore + + * bug #68042 [Semaphore] Fix RedisStore expiring semaphores too early (nicolas-grekas) + +### Serializer + + * security #cve-2026-133761 [Serializer] Limit the nesting depth of CSV headers (jack-worman) + * security #cve-2026-133752 [Serializer] Compute the allowed attributes for the class being denormalized (nicolas-grekas) + * bug #68293 [Serializer] Limit the caches that grow with each nesting path (nicolas-grekas) + * bug #68292 [Serializer] Don't ask PropertyInfo about each case variant of an attribute name (nicolas-grekas) + * bug #67913 [Serializer] Refuse an object where an array of objects is expected (haraldpdl) + * bug #67883 [Serializer] Don't read untyped attributes with deep_object_to_populate (nicolas-grekas) + * bug #67878 [Serializer] Don't call methods named after the attributes being denormalized (nicolas-grekas) + * bug #67887 [Serializer][Templating] Limit more caches that grow with the input (nicolas-grekas) + * bug #67888 [Serializer] Limit the caches that grow with unknown keys (nicolas-grekas) + * bug #67884 [Serializer][Templating] Limit the caches that grow with each input value (nicolas-grekas) + * bug #67882 [Serializer] Apply ignored attributes to setter and adder aliases (nicolas-grekas) + * bug #67877 [Serializer] Ignore undeclared property paths with brackets (nicolas-grekas) + +### Translation + + * minor #67957 [Translation] Add the license terms of the XML schemas (nicolas-grekas) + +### TwigBridge + + * bug #68086 [TwigBridge] Remove required class from expanded choice option labels (X-Coder264) + +### Validator + + * bug #68360 [Validator] Fix the Portuguese (pt) translation of the Currency constraint message (andretorresdg) + * bug #68097 [Validator] Fix the IBAN formats sync script and synchronize formats (egbavou) + * bug #67984 [Validator] Fix IBAN format for Côte d'Ivoire (egbavou) + * minor #68226 [Validator] Fix the dead Have I Been Pwned API link (farisbasha) + +### VarDumper + + * bug #68060 [VarDumper] Don't turn object property names into dump attributes and link only to http(s) URLs (nicolas-grekas) + * bug #68058 [VarDumper] Escape the content type of images in HtmlDumper (nicolas-grekas) + +### WebProfilerBundle + + * bug #68059 [WebProfilerBundle] Ignore debug headers of cross-origin responses and only link to http(s) URLs (nicolas-grekas) + +### Workflow + + * bug #68082 [Workflow] Escape backslashes in Graphviz HTML labels (fabpot) + +### Yaml + + * bug #68077 [Yaml] Fix anchors, aliases and unsupported entries in flow mapping keys (nicolas-grekas) + * bug #68069 [Yaml] Keep spaces in plain flow mapping keys (eyupcanakman) + * bug #68024 [Yaml] Fix block scalars losing their trailing newline after leading comments (eyupcanakman) + * bug #67881 [Yaml] Don't copy long nested blocks at each nesting level (nicolas-grekas) + * bug #67880 [Yaml] Bound the number of nodes that collection aliases expand to (nicolas-grekas) + +### Other + + * minor #68250 Limit how many suites run at once on the Windows CI of 5.4 (nicolas-grekas) + * minor #68238 Download CI binaries from symfony-tools/binary-utils (nicolas-grekas) + * minor #68229 Remove the security-triage skill (nicolas-grekas) + * minor #68085 Missing translations for Albanian (sq) (isihussain) + ## 6.4.50 (2026-11-04) ### AssetMapper diff -Nru symfony-6.4.50+dfsg/debian/changelog symfony-6.4.51+dfsg/debian/changelog --- symfony-6.4.50+dfsg/debian/changelog 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/changelog 2026-11-26 10:46:41.000000000 +0000 @@ -1,3 +1,50 @@ +symfony (6.4.51+dfsg-0+deb13u1) trixie-security; urgency=medium + + [ Fabien Potencier ] + * Update VERSION for 6.4.51 + + [ Nicolas Grekas ] + * [Security] Require every attribute to be granted with the unanimous strategy + [CVE-2026-133753] + * [HttpFoundation][HttpKernel] Trust 127.0.0.1 only for the requests built by + SubRequestHandler [CVE-2026-133743] + * [HttpClient] Let the client decorated by NoPrivateNetworkHttpClient apply + its own default options [CVE-2026-133758] + * [Security] Parse the host of redirect targets like browsers do + [CVE-2026-134790] + * [DoctrineBridge] Reject the copies of previous remember-me tokens when + they're used as series, and delete them with their token [CVE-2026-133759] + * [HttpClient] Read HTTP_PROXY from the environment, not from $_SERVER, on the + CLI [CVE-2026-134792] + * [ExpressionLanguage] Check the nesting level of short ternaries in linear + time [CVE-2026-133760] + * [FrameworkBundle][Routing] Don't let router redirects send paths that start + with // to another host [CVE-2026-133745] + * [HttpFoundation] Match IPv4-mapped addresses against IPv4 subnets in + IpUtils::checkIp() [CVE-2026-133748] + * [Security] Run the checkPostAuth() method of user checkers in + GuardAuthenticatorHandler::authenticateUserAndHandleSuccess() + [CVE-2026-133749] + * [Routing] Don't let generated URLs point to another host [CVE-2026-133746] + * [Routing] Reject host parameters that contain forbidden characters + [CVE-2026-133754] + * [Serializer] Compute the allowed attributes for the class being denormalized + [CVE-2026-133752] + * [HtmlSanitizer] Strip the whitespace that browsers skip before the time of a + meta refresh [CVE-2026-133756] + * [HttpClient] Don't let decorated clients add their default credentials to + cross-origin redirects of NoPrivateNetworkHttpClient [CVE-2026-133757] + + [ Jack Worman ] + * [Serializer] Limit the nesting depth of CSV headers [CVE-2026-133761] + + [ David Prévot ] + * Document more CVEs in previous changelog entry + * Refresh patches + * [Cache] Load Traits/ValueWrapper.php + + -- David Prévot Thu, 26 Nov 2026 11:46:41 +0100 + symfony (6.4.50+dfsg-0+deb13u1) trixie-security; urgency=medium [ Fabien Potencier ] @@ -30,11 +77,11 @@ * [HttpFoundation] Add the list of private ranges usable as trusted proxies (GHSA-xg2q-4rrq-657q) * [HttpKernel] Restore the router context of the parent request after a - sub-request (GHSA-wg5q-m2ww-f3c9) + sub-request (GHSA-wg5q-m2ww-f3c9) [CVE-2026-123339] * [Routing] Prevent host placeholders from matching the path in compiled matchers [CVE-2026-118516] * [Filesystem] Only treat a valid URI scheme as the root of a path - (GHSA-6prc-h956-hxjq) + (GHSA-6prc-h956-hxjq) [CVE-2026-135803] * [Yaml] Fix exponential and quadratic parse times (GHSA-hwfg-qwvh-2wfx) [CVE-2026-123792] * [Serializer] Ignore undeclared property paths when denormalizing @@ -42,11 +89,12 @@ * [HttpFoundation] Match HEAD requests when GET is listed in a RequestMatcher [CVE-2026-118514] * [HttpFoundation] Don't let Request::getBaseUrl() start with a host chosen by - the client (GHSA-5mx8-mwrp-5693) + the client (GHSA-5mx8-mwrp-5693) [CVE-2026-135802] [ Jack Worman ] * [HttpFoundation] Don't match the script name in Request::getBaseUrl() when - it's only the start of a path segment (GHSA-3h27-hjv7-fqjx) + it's only the start of a path segment + (GHSA-3h27-hjv7-fqjx) [CVE-2026-135801] [ David Prévot ] * Refresh patches diff -Nru symfony-6.4.50+dfsg/debian/patches/Adapt-conflict-to-Debian-expectations.patch symfony-6.4.51+dfsg/debian/patches/Adapt-conflict-to-Debian-expectations.patch --- symfony-6.4.50+dfsg/debian/patches/Adapt-conflict-to-Debian-expectations.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Adapt-conflict-to-Debian-expectations.patch 2026-11-26 10:46:41.000000000 +0000 @@ -13,11 +13,11 @@ src/Symfony/Component/Mime/composer.json | 4 ++-- src/Symfony/Component/PropertyInfo/composer.json | 4 ++-- src/Symfony/Component/Security/Core/composer.json | 2 +- - src/Symfony/Component/Security/Http/composer.json | 2 +- + src/Symfony/Component/Security/Http/composer.json | 4 ++-- src/Symfony/Component/Validator/composer.json | 2 +- src/Symfony/Contracts/Service/composer.json | 2 +- src/Symfony/Contracts/composer.json | 2 +- - 14 files changed, 27 insertions(+), 27 deletions(-) + 14 files changed, 28 insertions(+), 28 deletions(-) diff --git a/composer.json b/composer.json index b1915ef..1aca9bd 100644 @@ -205,18 +205,21 @@ }, "autoload": { diff --git a/src/Symfony/Component/Security/Http/composer.json b/src/Symfony/Component/Security/Http/composer.json -index d5b3a50..f5fd177 100644 +index a2022ff..e620ec4 100644 --- a/src/Symfony/Component/Security/Http/composer.json +++ b/src/Symfony/Component/Security/Http/composer.json -@@ -40,7 +40,7 @@ +@@ -40,9 +40,9 @@ }, "conflict": { "symfony/clock": "<6.3", - "symfony/event-dispatcher": "<5.4.9|>=6,<6.0.9", + "symfony/event-dispatcher": "<6.0.9", "symfony/http-client-contracts": "<3.0", +- "symfony/rate-limiter": "<6.4.33|>=7,<7.4.5", ++ "symfony/rate-limiter": "<6.4.33", "symfony/security-bundle": "<5.4", "symfony/security-csrf": "<5.4" + }, diff --git a/src/Symfony/Component/Validator/composer.json b/src/Symfony/Component/Validator/composer.json index ece01e2..b38c3f8 100644 --- a/src/Symfony/Component/Validator/composer.json diff -Nru symfony-6.4.50+dfsg/debian/patches/Assume-php-async-aws-sqs-2.patch symfony-6.4.51+dfsg/debian/patches/Assume-php-async-aws-sqs-2.patch --- symfony-6.4.50+dfsg/debian/patches/Assume-php-async-aws-sqs-2.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Assume-php-async-aws-sqs-2.patch 2026-11-26 10:46:41.000000000 +0000 @@ -10,10 +10,10 @@ 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php -index d9add5b..b45553d 100644 +index 5dc9267..5bd00f4 100644 --- a/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php +++ b/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php -@@ -631,8 +631,6 @@ class ConnectionTest extends TestCase +@@ -659,8 +659,6 @@ class ConnectionTest extends TestCase private function isAsyncAwsSqsVersion2Installed(): bool { diff -Nru symfony-6.4.50+dfsg/debian/patches/Cache-Disable-Test-failing-tests-Error-Class-not-found.patch symfony-6.4.51+dfsg/debian/patches/Cache-Disable-Test-failing-tests-Error-Class-not-found.patch --- symfony-6.4.50+dfsg/debian/patches/Cache-Disable-Test-failing-tests-Error-Class-not-found.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Cache-Disable-Test-failing-tests-Error-Class-not-found.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,461 +0,0 @@ -From: =?utf-8?q?David_Pr=C3=A9vot?= -Date: Wed, 24 May 2023 14:51:30 +0200 -Subject: =?utf-8?q?=5BCache=5D_Disable_Test_failing_tests_=28Error=3A_Class?= - =?utf-8?q?_=22=EF=BF=BD=22_not_found=29?= - -To be investigated ---- - .../Cache/Tests/Adapter/AdapterTestCase.php | 12 + - .../Cache/Tests/Adapter/TagAwareAdapterTest.php | 272 --------------------- - .../TagAwareAndProxyAdapterIntegrationTest.php | 1 + - .../Cache/Tests/Adapter/TagAwareTestTrait.php | 9 + - .../Messenger/EarlyExpirationDispatcherTest.php | 1 + - .../Tests/Messenger/EarlyExpirationHandlerTest.php | 5 + - 6 files changed, 28 insertions(+), 272 deletions(-) - delete mode 100644 src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php - -diff --git a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php -index ae84039..e5ff801 100644 ---- a/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php -+++ b/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php -@@ -25,6 +25,16 @@ abstract class AdapterTestCase extends CachePoolTest - { - parent::setUp(); - -+ $this->skippedTests['testGet'] = -+ $this->skippedTests['testRecursiveGet'] = -+ $this->skippedTests['testDontSaveWhenAskedNotTo'] = -+ $this->skippedTests['testDefaultLifeTime'] = -+ $this->skippedTests['testExpiration'] = -+ $this->skippedTests['testNotUnserializable'] = -+ $this->skippedTests['testClearPrefix'] = -+ $this->skippedTests['testWeirdDataMatchingMetadataWrappedValues'] = -+ $this->skippedTests['testGetMetadata'] = 'Test failing on current Debian (Error: Class "�" not found).'; -+ - if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createCachePool() instanceof PruneableInterface) { - $this->skippedTests['testPrune'] = 'Not a pruneable cache pool.'; - } -@@ -378,6 +388,7 @@ abstract class AdapterTestCase extends CachePoolTest - - public function testNullByteInKey() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $cache = $this->createCachePool(0, __FUNCTION__); - - $cache->save($cache->getItem("a\0b")->set(123)); -@@ -387,6 +398,7 @@ abstract class AdapterTestCase extends CachePoolTest - - public function testNumericKeysWorkAfterMemoryLeakPrevention() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $cache = $this->createCachePool(0, __FUNCTION__); - $cache->save($cache->getItem('50')->set('value-50')); - -diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php -deleted file mode 100644 -index de9aaf2..0000000 ---- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php -+++ /dev/null -@@ -1,272 +0,0 @@ -- -- * -- * For the full copyright and license information, please view the LICENSE -- * file that was distributed with this source code. -- */ -- --namespace Symfony\Component\Cache\Tests\Adapter; -- --use PHPUnit\Framework\MockObject\MockObject; --use Psr\Cache\CacheItemPoolInterface; --use Symfony\Component\Cache\Adapter\AdapterInterface; --use Symfony\Component\Cache\Adapter\ArrayAdapter; --use Symfony\Component\Cache\Adapter\FilesystemAdapter; --use Symfony\Component\Cache\Adapter\TagAwareAdapter; --use Symfony\Component\Cache\PruneableInterface; --use Symfony\Component\Cache\Tests\Fixtures\PrunableAdapter; --use Symfony\Component\Filesystem\Filesystem; -- --/** -- * @group time-sensitive -- */ --class TagAwareAdapterTest extends AdapterTestCase --{ -- use TagAwareTestTrait; -- -- public function createCachePool($defaultLifetime = 0): CacheItemPoolInterface -- { -- return new TagAwareAdapter(new FilesystemAdapter('', $defaultLifetime)); -- } -- -- public static function tearDownAfterClass(): void -- { -- (new Filesystem())->remove(sys_get_temp_dir().'/symfony-cache'); -- } -- -- public function testPrune() -- { -- $cache = new TagAwareAdapter($this->getPruneableMock()); -- $this->assertTrue($cache->prune()); -- -- $cache = new TagAwareAdapter($this->createStub(AdapterInterface::class)); -- $this->assertFalse($cache->prune()); -- -- $cache = new TagAwareAdapter($this->getFailingPruneableMock()); -- $this->assertFalse($cache->prune()); -- } -- -- public function testKnownTagVersionsTtl() -- { -- $itemsPool = new FilesystemAdapter('', 10); -- $tagsPool = new ArrayAdapter(); -- -- $pool = new TagAwareAdapter($itemsPool, $tagsPool, 10); -- -- $item = $pool->getItem('foo'); -- $item->tag(['baz']); -- $item->expiresAfter(100); -- -- $tag = $tagsPool->getItem('baz'.TagAwareAdapter::TAGS_PREFIX); -- $tagsPool->save($tag->set(10)); -- -- $pool->save($item); -- $this->assertTrue($pool->getItem('foo')->isHit()); -- -- $tagsPool->deleteItem('baz'.TagAwareAdapter::TAGS_PREFIX); // tag invalidation -- -- $this->assertTrue($pool->getItem('foo')->isHit()); // known tag version is used -- -- sleep(10); -- -- $this->assertTrue($pool->getItem('foo')->isHit()); // known tag version is still used -- -- sleep(1); -- -- $this->assertFalse($pool->getItem('foo')->isHit()); // known tag version has expired -- } -- -- public function testGetItemsWithNumericStringKeys() -- { -- $adapter = new TagAwareAdapter(new ArrayAdapter()); -- -- $item = $adapter->getItem('123'); -- $item->set('foo-val'); -- $adapter->save($item); -- -- $keys = []; -- foreach ($adapter->getItems(['123', '456']) as $key => $item) { -- $keys[] = $key; -- $this->assertSame($key, $item->getKey()); -- } -- -- $this->assertSame(['123', '456'], $keys); -- } -- -- public function testInvalidateTagsWithArrayAdapter() -- { -- $adapter = new TagAwareAdapter(new ArrayAdapter()); -- -- $item = $adapter->getItem('foo'); -- -- $this->assertFalse($item->isHit()); -- -- $item->tag('bar'); -- $item->expiresAfter(100); -- $adapter->save($item); -- -- $this->assertTrue($adapter->getItem('foo')->isHit()); -- -- $adapter->invalidateTags(['bar']); -- -- $this->assertFalse($adapter->getItem('foo')->isHit()); -- } -- -- private function getPruneableMock(): PruneableInterface&MockObject -- { -- $pruneable = $this->createMock(PrunableAdapter::class); -- -- $pruneable -- ->expects($this->atLeastOnce()) -- ->method('prune') -- ->willReturn(true); -- -- return $pruneable; -- } -- -- private function getFailingPruneableMock(): PruneableInterface&MockObject -- { -- $pruneable = $this->createMock(PrunableAdapter::class); -- -- $pruneable -- ->expects($this->atLeastOnce()) -- ->method('prune') -- ->willReturn(false); -- -- return $pruneable; -- } -- -- /** -- * @doesNotPerformAssertions -- */ -- public function testToleranceForStringsAsTagVersionsCase1() -- { -- $pool = $this->createCachePool(); -- $adapter = new FilesystemAdapter(); -- -- $itemKey = 'foo'; -- $tag = $adapter->getItem('bar'.TagAwareAdapter::TAGS_PREFIX); -- $adapter->save($tag->set("\x00abc\xff")); -- $item = $pool->getItem($itemKey); -- $pool->save($item->tag('bar')); -- $pool->hasItem($itemKey); -- $pool->getItem($itemKey); -- } -- -- /** -- * @doesNotPerformAssertions -- */ -- public function testToleranceForStringsAsTagVersionsCase2() -- { -- $pool = $this->createCachePool(); -- $adapter = new FilesystemAdapter(); -- -- $itemKey = 'foo'; -- $tag = $adapter->getItem('bar'.TagAwareAdapter::TAGS_PREFIX); -- $adapter->save($tag->set("\x00abc\xff")); -- $item = $pool->getItem($itemKey); -- $pool->save($item->tag('bar')); -- sleep(100); -- $pool->getItem($itemKey); -- $pool->hasItem($itemKey); -- } -- -- /** -- * @doesNotPerformAssertions -- */ -- public function testToleranceForStringsAsTagVersionsCase3() -- { -- $pool = $this->createCachePool(); -- $adapter = new FilesystemAdapter(); -- -- $itemKey = 'foo'; -- $adapter->deleteItem('bar'.TagAwareAdapter::TAGS_PREFIX); -- $item = $pool->getItem($itemKey); -- $pool->save($item->tag('bar')); -- $pool->getItem($itemKey); -- -- $tag = $adapter->getItem('bar'.TagAwareAdapter::TAGS_PREFIX); -- $adapter->save($tag->set("\x00abc\xff")); -- -- $pool->hasItem($itemKey); -- $pool->getItem($itemKey); -- sleep(100); -- $pool->getItem($itemKey); -- $pool->hasItem($itemKey); -- } -- -- /** -- * @doesNotPerformAssertions -- */ -- public function testToleranceForStringsAsTagVersionsCase4() -- { -- $pool = $this->createCachePool(); -- $adapter = new FilesystemAdapter(); -- -- $itemKey = 'foo'; -- $tag = $adapter->getItem('bar'.TagAwareAdapter::TAGS_PREFIX); -- $adapter->save($tag->set('abcABC')); -- -- $item = $pool->getItem($itemKey); -- $pool->save($item->tag('bar')); -- -- $tag = $adapter->getItem('bar'.TagAwareAdapter::TAGS_PREFIX); -- $adapter->save($tag->set('001122')); -- -- $pool->invalidateTags(['bar']); -- $pool->getItem($itemKey); -- } -- -- /** -- * @doesNotPerformAssertions -- */ -- public function testToleranceForStringsAsTagVersionsCase5() -- { -- $pool = $this->createCachePool(); -- $pool2 = $this->createCachePool(); -- $adapter = new FilesystemAdapter(); -- -- $itemKey1 = 'foo'; -- $item = $pool->getItem($itemKey1); -- $pool->save($item->tag('bar')); -- -- $tag = $adapter->getItem('bar'.TagAwareAdapter::TAGS_PREFIX); -- $adapter->save($tag->set('abcABC')); -- -- $itemKey2 = 'baz'; -- $item = $pool2->getItem($itemKey2); -- $pool2->save($item->tag('bar')); -- foreach ($pool->getItems([$itemKey1, $itemKey2]) as $item) { -- // run generator -- } -- } -- -- public function testResetClearsInternalStateEvenOnCommitFailure() -- { -- $pool = new class extends ArrayAdapter { -- public function commit(): bool -- { -- return false; -- } -- }; -- -- $adapter = new TagAwareAdapter($pool); -- $item = $adapter->getItem('foo'); -- $item->set('bar'); -- $adapter->saveDeferred($item); -- -- // Simulate some known tag versions -- $propertyTags = new \ReflectionProperty($adapter, 'knownTagVersions'); -- $propertyTags->setValue($adapter, ['tag1' => 1]); -- -- $adapter->reset(); -- -- $propertyDeferred = new \ReflectionProperty($adapter, 'deferred'); -- $this->assertEmpty($propertyDeferred->getValue($adapter), 'The deferred items must be cleared even if commit fails.'); -- $this->assertEmpty($propertyTags->getValue($adapter), 'The known tag versions must be cleared even if commit fails.'); -- } --} -diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php -index 4af199d..68168f6 100644 ---- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php -+++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAndProxyAdapterIntegrationTest.php -@@ -25,6 +25,7 @@ class TagAwareAndProxyAdapterIntegrationTest extends TestCase - */ - public function testIntegrationUsingProxiedAdapter(CacheItemPoolInterface $proxiedAdapter) - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $cache = new TagAwareAdapter(new ProxyAdapter($proxiedAdapter)); - - $item = $cache->getItem('foo'); -diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php -index 3bc4544..370ee47 100644 ---- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php -+++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php -@@ -32,6 +32,7 @@ trait TagAwareTestTrait - - public function testInvalidateTags() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $pool = $this->createCachePool(); - - $i0 = $pool->getItem('i0'); -@@ -69,6 +70,7 @@ trait TagAwareTestTrait - - public function testInvalidateCommits() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $pool = $this->createCachePool(); - - $foo = $pool->getItem('foo'); -@@ -86,6 +88,7 @@ trait TagAwareTestTrait - - public function testTagsAreCleanedOnSave() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $pool = $this->createCachePool(); - - $i = $pool->getItem('k'); -@@ -100,6 +103,7 @@ trait TagAwareTestTrait - - public function testTagsAreCleanedOnDelete() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $pool = $this->createCachePool(); - - $i = $pool->getItem('k'); -@@ -136,6 +140,7 @@ trait TagAwareTestTrait - - public function testTagItemExpiry() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - if (isset($this->skippedTests[__FUNCTION__])) { - $this->markTestSkipped($this->skippedTests[__FUNCTION__]); - } -@@ -157,6 +162,8 @@ trait TagAwareTestTrait - - public function testGetMetadata() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); -+ - $pool = $this->createCachePool(); - - $i = $pool->getItem('k'); -@@ -170,6 +177,8 @@ trait TagAwareTestTrait - - public function testRefreshAfterExpires() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); -+ - $pool = $this->createCachePool(); - $pool->clear(); - -diff --git a/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationDispatcherTest.php b/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationDispatcherTest.php -index fc61143..e4a7eac 100644 ---- a/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationDispatcherTest.php -+++ b/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationDispatcherTest.php -@@ -145,6 +145,7 @@ class EarlyExpirationDispatcherTest extends TestCase - */ - public function testSynchronousEarlyExpirationReturnsNullAndSkipsDuplicates() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $pool = new class extends FilesystemAdapter { - public bool $failSave = false; - -diff --git a/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationHandlerTest.php b/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationHandlerTest.php -index 76fdb31..49bba02 100644 ---- a/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationHandlerTest.php -+++ b/src/Symfony/Component/Cache/Tests/Messenger/EarlyExpirationHandlerTest.php -@@ -53,6 +53,7 @@ class EarlyExpirationHandlerTest extends TestCase - - public function testHandle() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $pool = new FilesystemAdapter(); - $item = $pool->getItem('foo'); - $item->set(234); -@@ -122,6 +123,7 @@ class EarlyExpirationHandlerTest extends TestCase - - public function testWorkerRetriesFailedCallbacks() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - foreach ([new \RuntimeException('Failed computation.'), new \Error('Failed computation.')] as $failure) { - $calls = 0; - $currentRetry = 0; -@@ -184,6 +186,7 @@ class EarlyExpirationHandlerTest extends TestCase - - public function testFailureDoesNotClearReplacementComputation() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - foreach ([false, true] as $evictOriginal) { - $calls = 0; - $handler = $replacement = null; -@@ -262,6 +265,7 @@ class EarlyExpirationHandlerTest extends TestCase - - public function testExpiredMessageIsSkippedAfterFailure() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $calls = 0; - $callback = static function () use (&$calls) { - if (1 === ++$calls) { -@@ -287,6 +291,7 @@ class EarlyExpirationHandlerTest extends TestCase - - public function testFailureWithoutMetadataCanBeRetried() - { -+ $this->markTestSkipped('Test failing on current Debian (Error: Class "�" not found).'); - $calls = 0; - $callback = static function () use (&$calls) { - if (1 === ++$calls) { diff -Nru symfony-6.4.50+dfsg/debian/patches/Cache-Skip-test-currently-failing.patch symfony-6.4.51+dfsg/debian/patches/Cache-Skip-test-currently-failing.patch --- symfony-6.4.50+dfsg/debian/patches/Cache-Skip-test-currently-failing.patch 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Cache-Skip-test-currently-failing.patch 2026-11-26 10:46:41.000000000 +0000 @@ -0,0 +1,22 @@ +From: =?utf-8?q?David_Pr=C3=A9vot?= +Date: Thu, 26 Nov 2026 13:14:00 +0100 +Subject: [Cache] Skip test currently failing + +To be investigated. +--- + src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php +index de9aaf2..f08e826 100644 +--- a/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php ++++ b/src/Symfony/Component/Cache/Tests/Adapter/TagAwareAdapterTest.php +@@ -52,6 +52,8 @@ class TagAwareAdapterTest extends AdapterTestCase + + public function testKnownTagVersionsTtl() + { ++ $this->markTestSkipped('Test currently failing on Debian.'); ++ + $itemsPool = new FilesystemAdapter('', 10); + $tagsPool = new ArrayAdapter(); + diff -Nru symfony-6.4.50+dfsg/debian/patches/DependencyInjection-Don-t-override-final-method-PHPUnit-F.patch symfony-6.4.51+dfsg/debian/patches/DependencyInjection-Don-t-override-final-method-PHPUnit-F.patch --- symfony-6.4.50+dfsg/debian/patches/DependencyInjection-Don-t-override-final-method-PHPUnit-F.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/DependencyInjection-Don-t-override-final-method-PHPUnit-F.patch 2026-11-26 10:46:41.000000000 +0000 @@ -9,7 +9,7 @@ 1 file changed, 9 deletions(-) diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php -index 62569d7..df1f92f 100644 +index 57b330e..e858c76d 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -96,15 +96,6 @@ class PhpDumperTest extends TestCase diff -Nru symfony-6.4.50+dfsg/debian/patches/Drop-composer-runtime-api-that-confuses-phpabtpl.patch symfony-6.4.51+dfsg/debian/patches/Drop-composer-runtime-api-that-confuses-phpabtpl.patch --- symfony-6.4.50+dfsg/debian/patches/Drop-composer-runtime-api-that-confuses-phpabtpl.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Drop-composer-runtime-api-that-confuses-phpabtpl.patch 2026-11-26 10:46:41.000000000 +0000 @@ -34,7 +34,7 @@ "symfony/cache": "^5.4|^6.0|^7.0", "symfony/config": "^6.1|^7.0", diff --git a/src/Symfony/Bundle/SecurityBundle/composer.json b/src/Symfony/Bundle/SecurityBundle/composer.json -index 511e2cc..835249e 100644 +index 8e48e76..6c143d0 100644 --- a/src/Symfony/Bundle/SecurityBundle/composer.json +++ b/src/Symfony/Bundle/SecurityBundle/composer.json @@ -17,7 +17,6 @@ diff -Nru symfony-6.4.50+dfsg/debian/patches/Drop-test-currently-failing-on-buildd.patch symfony-6.4.51+dfsg/debian/patches/Drop-test-currently-failing-on-buildd.patch --- symfony-6.4.50+dfsg/debian/patches/Drop-test-currently-failing-on-buildd.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Drop-test-currently-failing-on-buildd.patch 2026-11-26 10:46:41.000000000 +0000 @@ -7,10 +7,10 @@ 1 file changed, 39 deletions(-) diff --git a/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php b/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php -index cf17e3c..dfdce3a 100644 +index 5721b09..5f3540a 100644 --- a/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php +++ b/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php -@@ -120,45 +120,6 @@ class HttpClientTraitTest extends TestCase +@@ -122,45 +122,6 @@ class HttpClientTraitTest extends TestCase $this->assertSame($expected, $result); } diff -Nru symfony-6.4.50+dfsg/debian/patches/Group-nophpunit11-for-tests-failing-with-PHPUnit-11.patch symfony-6.4.51+dfsg/debian/patches/Group-nophpunit11-for-tests-failing-with-PHPUnit-11.patch --- symfony-6.4.50+dfsg/debian/patches/Group-nophpunit11-for-tests-failing-with-PHPUnit-11.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Group-nophpunit11-for-tests-failing-with-PHPUnit-11.patch 2026-11-26 10:46:41.000000000 +0000 @@ -570,10 +570,10 @@ - } -} diff --git a/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php -index 43eff8f..6e0fb2a 100644 +index a4837bb..4af2a83 100644 --- a/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php -@@ -71,6 +71,7 @@ class NoPrivateNetworkHttpClientTest extends TestCase +@@ -81,6 +81,7 @@ class NoPrivateNetworkHttpClientTest extends TestCase /** * @dataProvider getExcludeIpData * @@ -581,7 +581,7 @@ * @group dns-sensitive */ public function testExcludeByIp(string $ipAddr, $subnets, bool $mustThrow) -@@ -109,6 +110,7 @@ class NoPrivateNetworkHttpClientTest extends TestCase +@@ -119,6 +120,7 @@ class NoPrivateNetworkHttpClientTest extends TestCase /** * @dataProvider getExcludeHostData * @@ -589,7 +589,7 @@ * @group dns-sensitive */ public function testExcludeByHost(string $ipAddr, $subnets, bool $mustThrow) -@@ -145,6 +147,7 @@ class NoPrivateNetworkHttpClientTest extends TestCase +@@ -155,6 +157,7 @@ class NoPrivateNetworkHttpClientTest extends TestCase } /** @@ -626,20 +626,20 @@ { $response = new Response(); diff --git a/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php b/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php -index 42355f7..f65338f 100644 +index 408da0a..b4e1bd1 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php -@@ -23,6 +23,9 @@ use Symfony\Component\HttpFoundation\Test\Constraint\ResponseFormatSame; - */ - class ResponseFormatSameTest extends TestCase - { +@@ -28,6 +28,9 @@ class ResponseFormatSameTest extends TestCase + (new \ReflectionProperty(Request::class, 'formats'))->setValue(null, null); + } + + /** + * @group nophpunit11 + */ public function testConstraint() { $request = new Request(); -@@ -43,6 +46,9 @@ class ResponseFormatSameTest extends TestCase +@@ -48,6 +51,9 @@ class ResponseFormatSameTest extends TestCase $this->fail(); } diff -Nru symfony-6.4.50+dfsg/debian/patches/HttpClient-Skip-test-currently-failing.patch symfony-6.4.51+dfsg/debian/patches/HttpClient-Skip-test-currently-failing.patch --- symfony-6.4.50+dfsg/debian/patches/HttpClient-Skip-test-currently-failing.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/HttpClient-Skip-test-currently-failing.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -From: =?utf-8?q?David_Pr=C3=A9vot?= -Date: Thu, 29 Oct 2026 10:16:57 +0100 -Subject: [HttpClient] Skip test currently failing - -To be investigated. ---- - src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php | 2 ++ - 1 file changed, 2 insertions(+) - -diff --git a/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php -index da8a34e..587d1a8 100644 ---- a/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php -+++ b/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php -@@ -299,6 +299,8 @@ class RetryableHttpClientTest extends TestCase - - public function testRetryAfterLongerThanMaxDuration() - { -+ $this->markTestSkipped('Test currently failing on Debian.'); -+ - TestHttpServer::start(); - - $client = new RetryableHttpClient(HttpClient::create()); diff -Nru symfony-6.4.50+dfsg/debian/patches/HttpClient-Skip-tests-currently-failing.patch symfony-6.4.51+dfsg/debian/patches/HttpClient-Skip-tests-currently-failing.patch --- symfony-6.4.50+dfsg/debian/patches/HttpClient-Skip-tests-currently-failing.patch 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/HttpClient-Skip-tests-currently-failing.patch 2026-11-26 10:46:41.000000000 +0000 @@ -0,0 +1,36 @@ +From: =?utf-8?q?David_Pr=C3=A9vot?= +Date: Thu, 29 Oct 2026 10:16:57 +0100 +Subject: [HttpClient] Skip tests currently failing + +To be investigated. +--- + src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php | 2 ++ + src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php | 2 ++ + 2 files changed, 4 insertions(+) + +diff --git a/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php b/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php +index 5f3540a..7a768f5 100644 +--- a/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php ++++ b/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php +@@ -466,6 +466,8 @@ class HttpClientTraitTest extends TestCase + + public function testHttpProxyIsIgnoredOnOtherSapis() + { ++ self::markTestSkipped('Test currently failing on Debian'); ++ + $finder = new PhpExecutableFinder(); + $env = ['HTTP_PROXY' => 'http://env.example:3128', 'http_proxy' => false, 'https_proxy' => false, 'HTTPS_PROXY' => false, 'all_proxy' => false, 'ALL_PROXY' => false]; + $process = new Process(array_merge([$finder->find(false)], $finder->findArguments(), ['-dopcache.enable=0', '-dvariables_order=EGPCS', '-S', '127.0.0.1:8098']), __DIR__.'/Fixtures/proxy-url', $env); +diff --git a/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php +index 970fbea..6d4fe0c 100644 +--- a/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php ++++ b/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php +@@ -494,6 +494,8 @@ class RetryableHttpClientTest extends TestCase + + public function testRetryAfterLongerThanMaxDuration() + { ++ $this->markTestSkipped('Test currently failing on Debian.'); ++ + TestHttpServer::start(); + + $client = new RetryableHttpClient(HttpClient::create()); diff -Nru symfony-6.4.50+dfsg/debian/patches/HttpClient-Skip-tests-relying-on-amphp-http-client.patch symfony-6.4.51+dfsg/debian/patches/HttpClient-Skip-tests-relying-on-amphp-http-client.patch --- symfony-6.4.50+dfsg/debian/patches/HttpClient-Skip-tests-relying-on-amphp-http-client.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/HttpClient-Skip-tests-relying-on-amphp-http-client.patch 2026-11-26 10:46:41.000000000 +0000 @@ -8,10 +8,10 @@ 2 files changed, 14 insertions(+) diff --git a/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php b/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php -index 91c7205..f8f4fa9 100644 +index 8c220e8..3a18e0b 100644 --- a/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php +++ b/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php -@@ -36,6 +36,13 @@ The vulcain binary can be found at https://github.com/symfony/binary-utils/relea +@@ -38,6 +38,13 @@ The vulcain binary can be found at https://github.com/symfony-tools/binary-utils abstract class HttpClientTestCase extends BaseHttpClientTestCase { diff -Nru symfony-6.4.50+dfsg/debian/patches/Lock-Drop-test-currently-failing-on-buildd.patch symfony-6.4.51+dfsg/debian/patches/Lock-Drop-test-currently-failing-on-buildd.patch --- symfony-6.4.50+dfsg/debian/patches/Lock-Drop-test-currently-failing-on-buildd.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Lock-Drop-test-currently-failing-on-buildd.patch 2026-11-26 10:46:41.000000000 +0000 @@ -8,10 +8,10 @@ 1 file changed, 1 deletion(-) diff --git a/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php b/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php -index 8ad7265..74bc3e0 100644 +index 51dcdd3..ba2c0c3 100644 --- a/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php +++ b/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php -@@ -273,7 +273,6 @@ class DoctrineDbalStoreTest extends AbstractStoreTestCase +@@ -285,7 +285,6 @@ class DoctrineDbalStoreTest extends AbstractStoreTestCase yield [\Doctrine\DBAL\Platforms\PostgreSQL94Platform::class]; } diff -Nru symfony-6.4.50+dfsg/debian/patches/Remove-calls-to-getExpectedException.patch symfony-6.4.51+dfsg/debian/patches/Remove-calls-to-getExpectedException.patch --- symfony-6.4.50+dfsg/debian/patches/Remove-calls-to-getExpectedException.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Remove-calls-to-getExpectedException.patch 2026-11-26 10:46:41.000000000 +0000 @@ -8,7 +8,7 @@ 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php -index a8bfc17..7c5f8c8 100644 +index 3ad7ffb..be5d78f 100644 --- a/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php +++ b/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php @@ -445,7 +445,7 @@ class UrlMatcherTest extends TestCase @@ -38,7 +38,7 @@ $coll = new RouteCollection(); $coll->add('foo', new Route('/foo')); -@@ -479,7 +479,7 @@ class UrlMatcherTest extends TestCase +@@ -522,7 +522,7 @@ class UrlMatcherTest extends TestCase public function testSchemeRequirement() { @@ -47,7 +47,7 @@ $coll = new RouteCollection(); $coll->add('foo', new Route('/foo', [], [], [], '', ['https'])); $matcher = $this->getUrlMatcher($coll); -@@ -488,7 +488,7 @@ class UrlMatcherTest extends TestCase +@@ -531,7 +531,7 @@ class UrlMatcherTest extends TestCase public function testSchemeRequirementForNonSafeMethod() { diff -Nru symfony-6.4.50+dfsg/debian/patches/Scheduler-Skip-test-currently-failing.patch symfony-6.4.51+dfsg/debian/patches/Scheduler-Skip-test-currently-failing.patch --- symfony-6.4.50+dfsg/debian/patches/Scheduler-Skip-test-currently-failing.patch 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Scheduler-Skip-test-currently-failing.patch 2026-11-26 10:46:41.000000000 +0000 @@ -0,0 +1,22 @@ +From: =?utf-8?q?David_Pr=C3=A9vot?= +Date: Thu, 26 Nov 2026 12:21:17 +0100 +Subject: [Scheduler] Skip test currently failing + +To be investigated. +--- + .../Component/Scheduler/Tests/Generator/MessageGeneratorTest.php | 2 ++ + 1 file changed, 2 insertions(+) + +diff --git a/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php b/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php +index 6cc024d..fb9e292 100644 +--- a/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php ++++ b/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php +@@ -542,6 +542,8 @@ class MessageGeneratorTest extends TestCase + + public function testRestartAfterARunWhenTheClocksGoForward() + { ++ $this->markTestSkipped('Test currently failing on Debian.'); ++ + $clock = new MockClock('2027-03-28 01:50:00', 'Europe/Paris'); + $nightly = (object) ['id' => 'nightly']; + $later = (object) ['id' => 'later']; diff -Nru symfony-6.4.50+dfsg/debian/patches/Use-installed-files-for-CI.patch symfony-6.4.51+dfsg/debian/patches/Use-installed-files-for-CI.patch --- symfony-6.4.50+dfsg/debian/patches/Use-installed-files-for-CI.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Use-installed-files-for-CI.patch 2026-11-26 10:46:41.000000000 +0000 @@ -7,7 +7,7 @@ 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php -index 771e645..9ff76e9 100644 +index 2641c63..0d0b39f 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php @@ -1296,7 +1296,7 @@ abstract class FrameworkExtensionTestCase extends TestCase diff -Nru symfony-6.4.50+dfsg/debian/patches/Yaml-Drop-data-set-currently-failing-on-i386.patch symfony-6.4.51+dfsg/debian/patches/Yaml-Drop-data-set-currently-failing-on-i386.patch --- symfony-6.4.50+dfsg/debian/patches/Yaml-Drop-data-set-currently-failing-on-i386.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/Yaml-Drop-data-set-currently-failing-on-i386.patch 2026-11-26 10:46:41.000000000 +0000 @@ -7,7 +7,7 @@ 1 file changed, 2 deletions(-) diff --git a/src/Symfony/Component/Yaml/Tests/InlineTest.php b/src/Symfony/Component/Yaml/Tests/InlineTest.php -index 28ab52f..925efd6 100644 +index 03c9108..e57f861 100644 --- a/src/Symfony/Component/Yaml/Tests/InlineTest.php +++ b/src/Symfony/Component/Yaml/Tests/InlineTest.php @@ -425,7 +425,6 @@ class InlineTest extends TestCase @@ -18,7 +18,7 @@ ['"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''], ["'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''], -@@ -510,7 +509,6 @@ class InlineTest extends TestCase +@@ -511,7 +510,6 @@ class InlineTest extends TestCase ['2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)], ['2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)], ['1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)], diff -Nru symfony-6.4.50+dfsg/debian/patches/group-network-for-test-failing-without-network.patch symfony-6.4.51+dfsg/debian/patches/group-network-for-test-failing-without-network.patch --- symfony-6.4.50+dfsg/debian/patches/group-network-for-test-failing-without-network.patch 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/group-network-for-test-failing-without-network.patch 2026-11-26 10:46:41.000000000 +0000 @@ -10,7 +10,7 @@ 4 files changed, 21 insertions(+) diff --git a/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php b/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php -index b891ebe..98fc0c1 100644 +index 268c196..2a04745 100644 --- a/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php +++ b/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php @@ -95,6 +95,7 @@ class RedisTraitTest extends TestCase diff -Nru symfony-6.4.50+dfsg/debian/patches/series symfony-6.4.51+dfsg/debian/patches/series --- symfony-6.4.50+dfsg/debian/patches/series 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/patches/series 2026-11-26 10:46:41.000000000 +0000 @@ -9,7 +9,6 @@ Drop-tests-data-throwing-a-RuntimeException-outside-a-Com.patch Drop-test-failing-outside-Composer-environment.patch Finder-Add-system-path-to-open_basedir-for-tests.patch -Cache-Disable-Test-failing-tests-Error-Class-not-found.patch Config-Skip-tests-currently-failing.patch Console-Skip-currently-failing-assertion.patch DependencyInjection-Drop-parts-of-expectated-output.patch @@ -44,5 +43,7 @@ Revert-Mailer-Sendgrid-Verify-the-webhook-signature-befor.patch Revert-Mailer-Notifier-Reject-Mailgun-SendGrid-and-Vonage.patch Revert-PhpUnitBridge-Honor-stderr-for-listener-output.patch -HttpClient-Skip-test-currently-failing.patch +HttpClient-Skip-tests-currently-failing.patch +Scheduler-Skip-test-currently-failing.patch +Cache-Skip-test-currently-failing.patch # DEP-8/Tests-against-installed-classes.patch diff -Nru symfony-6.4.50+dfsg/debian/php-symfony-cache.autoload.php.tpl symfony-6.4.51+dfsg/debian/php-symfony-cache.autoload.php.tpl --- symfony-6.4.50+dfsg/debian/php-symfony-cache.autoload.php.tpl 2026-11-04 15:33:54.000000000 +0000 +++ symfony-6.4.51+dfsg/debian/php-symfony-cache.autoload.php.tpl 2026-11-26 10:46:41.000000000 +0000 @@ -31,3 +31,4 @@ // @codeCoverageIgnoreEnd // Files +require_once __DIR__ . '/Traits/ValueWrapper.php'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php symfony-6.4.51+dfsg/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php 2026-11-25 09:18:34.000000000 +0000 @@ -79,9 +79,9 @@ */ public function deleteTokenBySeries(string $series) { - $sql = 'DELETE FROM rememberme_token WHERE series=:series'; - $paramValues = ['series' => $series]; - $paramTypes = ['series' => ParameterType::STRING]; + $sql = 'DELETE FROM rememberme_token WHERE series IN (:series, :tmpSeries)'; + $paramValues = ['series' => $series, 'tmpSeries' => self::getPreviousTokenSeries($series) ?? $series]; + $paramTypes = ['series' => ParameterType::STRING, 'tmpSeries' => ParameterType::STRING]; $this->conn->executeStatement($sql, $paramValues, $paramTypes); } @@ -129,6 +129,11 @@ public function verifyToken(PersistentTokenInterface $token, #[\SensitiveParameter] string $tokenValue): bool { + // Only the series generated by the remember-me handler are valid, so the copies of previous tokens are not + if (!self::isGeneratedSeries($token->getSeries())) { + return false; + } + // Check if the token value matches the current persisted token if (hash_equals($token->getTokenValue(), $tokenValue)) { return true; @@ -259,4 +264,15 @@ return \strlen($series) < 88 ? $series.'_' : null; } + + /** + * Tells whether the series has one of the two formats that the remember-me handler generates. + * + * The format is checked in PHP because the collation of the series column can make another series + * match the row of a copy, for example when it ignores trailing spaces or accents. + */ + private static function isGeneratedSeries(string $series): bool + { + return 1 === preg_match('{^(?:[A-Za-z0-9_-]{44}|[A-Za-z0-9+/]{86}==)$}D', $series); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Doctrine/Tests/DoctrineTestHelper.php symfony-6.4.51+dfsg/src/Symfony/Bridge/Doctrine/Tests/DoctrineTestHelper.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Doctrine/Tests/DoctrineTestHelper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Doctrine/Tests/DoctrineTestHelper.php 2026-11-25 09:18:34.000000000 +0000 @@ -14,6 +14,7 @@ use Doctrine\Common\EventManager; use Doctrine\DBAL\DriverManager; use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory; +use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Types\Type; use Doctrine\ORM\Configuration; use Doctrine\ORM\EntityManager; @@ -68,6 +69,9 @@ if (class_exists(DefaultSchemaManagerFactory::class)) { $config->setSchemaManagerFactory(new DefaultSchemaManagerFactory()); } + if (method_exists($config, 'setUseSchemaEditorApi') && method_exists(Schema::class, 'edit')) { + $config->setUseSchemaEditorApi(true); + } if (!class_exists(\Doctrine\Persistence\Mapping\Driver\AnnotationDriver::class)) { // doctrine/persistence >= 3.0 $config->setLazyGhostObjectEnabled(true); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Doctrine/Tests/Security/RememberMe/DoctrineTokenProviderTest.php symfony-6.4.51+dfsg/src/Symfony/Bridge/Doctrine/Tests/Security/RememberMe/DoctrineTokenProviderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Doctrine/Tests/Security/RememberMe/DoctrineTokenProviderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Doctrine/Tests/Security/RememberMe/DoctrineTokenProviderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -136,6 +136,92 @@ $this->assertTrue($provider->verifyToken($token, $oldValue)); } + /** + * @dataProvider provideSeriesAndCopySeries + */ + public function testOutdatedTokenCannotBeUsedWithTheSeriesOfItsCopy(string $series, string $copySeries) + { + $provider = $this->bootstrapProvider(); + + $token = new PersistentToken('someClass', 'someUser', $series, 'oldValue', new \DateTimeImmutable('2013-01-26T18:23:51')); + $provider->createNewToken($token); + $provider->updateExistingToken($token, 'newValue', new \DateTimeImmutable('-5 seconds')); + $provider->updateToken($series, 'newValue', new \DateTime('-5 seconds')); + + $copy = $provider->loadTokenBySeries($copySeries); + + $this->assertFalse($provider->verifyToken($copy, 'oldValue')); + } + + /** + * @dataProvider provideSeriesAndCopySeries + */ + public function testDeleteTokenAlsoDeletesTheCopyOfTheOutdatedToken(string $series, string $copySeries) + { + $provider = $this->bootstrapProvider(); + + $token = new PersistentToken('someClass', 'someUser', $series, 'oldValue', new \DateTimeImmutable('2013-01-26T18:23:51')); + $provider->createNewToken($token); + $provider->updateExistingToken($token, 'newValue', new \DateTimeImmutable('-5 seconds')); + $provider->updateToken($series, 'newValue', new \DateTime('-5 seconds')); + $provider->deleteTokenBySeries($series); + + $this->expectException(TokenNotFoundException::class); + + $provider->loadTokenBySeries($copySeries); + } + + public static function provideSeriesAndCopySeries(): iterable + { + $series = base64_encode(random_bytes(64)); + yield 'series created before Symfony 5.4.19' => [$series, preg_replace('{=+$}', '_', $series)]; + + $series = strtr(base64_encode(random_bytes(33)), '+/=', '-_~'); + yield 'series generated by the handler' => [$series, $series.'_']; + } + + /** + * @dataProvider provideSeriesGeneratedByTheHandler + */ + public function testVerifyTokenAcceptsTheSeriesGeneratedByTheHandler(string $series) + { + $provider = $this->bootstrapProvider(); + $provider->createNewToken(new PersistentToken('someClass', 'someUser', $series, 'tokenValue', new \DateTimeImmutable())); + + $this->assertTrue($provider->verifyToken($provider->loadTokenBySeries($series), 'tokenValue')); + } + + public static function provideSeriesGeneratedByTheHandler(): iterable + { + yield 'current format' => [strtr(base64_encode(random_bytes(33)), '+/=', '-_~')]; + yield 'format before Symfony 5.4.19' => [base64_encode(random_bytes(64))]; + } + + /** + * @dataProvider provideSeriesNotGeneratedByTheHandler + */ + public function testVerifyTokenRefusesTheSeriesNotGeneratedByTheHandler(string $series) + { + $provider = $this->bootstrapProvider(); + // Stands for the row of a copy that the collation of the series column could match + $provider->createNewToken(new PersistentToken('someClass', 'someUser', $series, 'tokenValue', new \DateTimeImmutable())); + + $this->assertFalse($provider->verifyToken($provider->loadTokenBySeries($series), 'tokenValue')); + } + + public static function provideSeriesNotGeneratedByTheHandler(): iterable + { + $series = strtr(base64_encode(random_bytes(33)), '+/=', '-_~'); + yield 'copy followed by a space' => [$series.'_ ']; + yield 'copy with an accented letter' => ['é'.substr($series, 1).'_']; + yield 'copy of a copy' => [$series.'__']; + yield 'series followed by a newline' => [$series."\n"]; + + $series = preg_replace('{=+$}', '_', base64_encode(random_bytes(64))); + yield 'copy of a series created before Symfony 5.4.19, followed by a space' => [$series.' ']; + yield 'copy of a series created before Symfony 5.4.19, with an accented letter' => ['é'.substr($series, 1)]; + } + protected function bootstrapProvider(): DoctrineTokenProvider { $config = ORMSetup::createConfiguration(true); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/PhpUnit/Tests/SimplePhpunitTest.php symfony-6.4.51+dfsg/src/Symfony/Bridge/PhpUnit/Tests/SimplePhpunitTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/PhpUnit/Tests/SimplePhpunitTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/PhpUnit/Tests/SimplePhpunitTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -60,4 +60,38 @@ $this->assertStringContainsString('INSTALLING IN '.$vendor.'/bin/.phpunit', $output); } + + public function testMaxParallelLimitsHowManyComponentsRunAtOnce() + { + $this->tmpDir = realpath(sys_get_temp_dir()).'/sf_simple_phpunit_'.bin2hex(random_bytes(6)); + $phpunitDir = $this->tmpDir.'/.phpunit'; + $project = $this->tmpDir.'/project'; + + mkdir($phpunitDir.'/phpunit-9.6-0', 0777, true); + mkdir($project.'/running', 0777, true); + foreach (['A', 'B', 'C', 'Fail'] as $component) { + mkdir($project.'/src/'.$component, 0777, true); + touch($project.'/src/'.$component.'/phpunit.xml.dist'); + } + + // a fake phpunit that logs how many components are running when it starts + file_put_contents($phpunitDir.'/phpunit-9.6-0/phpunit', 'tmpDir.'/composer', "#!/usr/bin/env php\n getenv('PATH'), 'COMPOSER_BINARY' => $composer, 'SYMFONY_PHPUNIT_DIR' => $phpunitDir, 'SYMFONY_PHPUNIT_VERSION' => '9.6', 'SYMFONY_PHPUNIT_MAX_PARALLEL' => '2']; + $process = proc_open($php.' '.escapeshellarg($bin).' src 2>&1', [1 => ['pipe', 'w']], $pipes, $project, $env); + $output = stream_get_contents($pipes[1]); + fclose($pipes[1]); + + $this->assertSame(1, proc_close($process), $output); + $this->assertStringContainsString("KO\033[0m src/Fail", $output); + + $counts = array_map('intval', file($project.'/counts')); + $this->assertCount(4, $counts); + $this->assertLessThanOrEqual(2, max($counts)); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php symfony-6.4.51+dfsg/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/PhpUnit/bin/simple-phpunit.php 2026-11-25 09:18:34.000000000 +0000 @@ -389,29 +389,30 @@ if ($components) { $skippedTests = $_SERVER['SYMFONY_PHPUNIT_SKIPPED_TESTS'] ?? false; + $maxParallel = max(0, (int) getenv('SYMFONY_PHPUNIT_MAX_PARALLEL')) ?: count($components); $runningProcs = []; + $lastOutput = null; + $lastOutputTime = null; - foreach ($components as $component) { - // Run phpunit tests in parallel + while ($components || $runningProcs) { + while ($components && count($runningProcs) < $maxParallel) { + // Run phpunit tests in parallel + $component = array_shift($components); - if ($skippedTests) { - putenv("SYMFONY_PHPUNIT_SKIPPED_TESTS=$component/$skippedTests"); - } + if ($skippedTests) { + putenv("SYMFONY_PHPUNIT_SKIPPED_TESTS=$component/$skippedTests"); + } - $c = escapeshellarg($component); + $c = escapeshellarg($component); - if ($proc = proc_open(sprintf($cmd, $c, " > $c/phpunit.stdout 2> $c/phpunit.stderr"), [], $pipes)) { - $runningProcs[$component] = $proc; - } else { - $exit = 1; - echo "\033[41mKO\033[0m $component\n\n"; + if ($proc = proc_open(sprintf($cmd, $c, " > $c/phpunit.stdout 2> $c/phpunit.stderr"), [], $pipes)) { + $runningProcs[$component] = $proc; + } else { + $exit = 1; + echo "\033[41mKO\033[0m $component\n\n"; + } } - } - - $lastOutput = null; - $lastOutputTime = null; - while ($runningProcs) { usleep(300000); $terminatedProcs = []; foreach ($runningProcs as $component => $proc) { @@ -423,7 +424,7 @@ } } - if (!$terminatedProcs && 1 === count($runningProcs)) { + if (!$components && !$terminatedProcs && 1 === count($runningProcs)) { $component = key($runningProcs); $output = file_get_contents("$component/phpunit.stdout"); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/PsrHttpMessage/Factory/UploadedFile.php symfony-6.4.51+dfsg/src/Symfony/Bridge/PsrHttpMessage/Factory/UploadedFile.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/PsrHttpMessage/Factory/UploadedFile.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/PsrHttpMessage/Factory/UploadedFile.php 2026-11-25 09:18:34.000000000 +0000 @@ -30,7 +30,7 @@ $error = $psrUploadedFile->getError(); $path = ''; - if (\UPLOAD_ERR_NO_FILE !== $error) { + if (\UPLOAD_ERR_OK === $error) { $path = $psrUploadedFile->getStream()->getMetadata('uri') ?? ''; if ($this->test = !\is_string($path) || !is_uploaded_file($path)) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php symfony-6.4.51+dfsg/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/PsrHttpMessage/Tests/Factory/HttpFoundationFactoryTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,6 +11,7 @@ namespace Symfony\Bridge\PsrHttpMessage\Tests\Factory; +use Nyholm\Psr7\Factory\Psr17Factory; use PHPUnit\Framework\TestCase; use Psr\Http\Message\UploadedFileInterface; use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; @@ -196,6 +197,32 @@ $symfonyUploadedFile->move($this->tmpDir, 'shouldFail.txt'); } + /** + * @dataProvider provideUploadErrors + */ + public function testCreateUploadedFileWithErrorDoesNotReadTheStream(int $error) + { + $psr17Factory = new Psr17Factory(); + $uploadedFile = $psr17Factory->createUploadedFile($psr17Factory->createStream(), 0, $error, 'a.php', 'image/jpeg'); + + $symfonyUploadedFile = $this->callCreateUploadedFile($uploadedFile); + + $this->assertSame($error, $symfonyUploadedFile->getError()); + $this->assertFalse($symfonyUploadedFile->isValid()); + $this->assertSame('a.php', $symfonyUploadedFile->getClientOriginalName()); + } + + public static function provideUploadErrors(): iterable + { + yield 'UPLOAD_ERR_INI_SIZE' => [\UPLOAD_ERR_INI_SIZE]; + yield 'UPLOAD_ERR_FORM_SIZE' => [\UPLOAD_ERR_FORM_SIZE]; + yield 'UPLOAD_ERR_PARTIAL' => [\UPLOAD_ERR_PARTIAL]; + yield 'UPLOAD_ERR_NO_FILE' => [\UPLOAD_ERR_NO_FILE]; + yield 'UPLOAD_ERR_NO_TMP_DIR' => [\UPLOAD_ERR_NO_TMP_DIR]; + yield 'UPLOAD_ERR_CANT_WRITE' => [\UPLOAD_ERR_CANT_WRITE]; + yield 'UPLOAD_ERR_EXTENSION' => [\UPLOAD_ERR_EXTENSION]; + } + private function createUploadedFile(string $content, int $error, string $clientFileName, string $clientMediaType): UploadedFile { $filePath = tempnam($this->tmpDir, uniqid('', true)); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -87,7 +87,7 @@ {% block checkbox_radio_label -%} {# Do not display the label if widget is not defined in order to prevent double label rendering #} {%- if widget is defined -%} - {%- if required -%} + {%- if label_required ?? required -%} {%- set label_attr = label_attr|merge({class: (label_attr.class|default('') ~ ' required')|trim}) -%} {%- endif -%} {%- if parent_label_class is defined -%} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -212,6 +212,7 @@
{%- for child in form %} {{- form_widget(child, { + label_required: false, parent_label_class: label_attr.class|default(''), translation_domain: choice_translation_domain, valid: valid, @@ -259,7 +260,7 @@ {%- if not compound -%} {% set label_attr = label_attr|merge({'for': id}) %} {%- endif -%} - {%- if required -%} + {%- if label_required ?? required -%} {%- set label_attr = label_attr|merge({class: (label_attr.class|default('') ~ ' required')|trim}) -%} {%- endif -%} {%- if parent_label_class is defined -%} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_5_layout.html.twig symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_5_layout.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_5_layout.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_5_layout.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -262,6 +262,7 @@
{%- for child in form %} {{- form_widget(child, { + label_required: false, parent_label_class: label_attr.class|default(''), translation_domain: choice_translation_domain, valid: valid, @@ -302,7 +303,7 @@ {%- if not compound -%} {% set label_attr = label_attr|merge({'for': id}) %} {%- endif -%} - {%- if required -%} + {%- if label_required ?? required -%} {%- set label_attr = label_attr|merge({class: (label_attr.class|default('') ~ ' required')|trim}) -%} {%- endif -%} {%- if parent_label_class is defined -%} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_base_layout.html.twig symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_base_layout.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_base_layout.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_base_layout.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -147,6 +147,7 @@ {%- if '-inline' in label_attr.class|default('') -%} {%- for child in form %} {{- form_widget(child, { + label_required: false, parent_label_class: label_attr.class|default(''), translation_domain: choice_translation_domain, }) -}} @@ -155,6 +156,7 @@
{%- for child in form %} {{- form_widget(child, { + label_required: false, parent_label_class: label_attr.class|default(''), translation_domain: choice_translation_domain, }) -}} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/form_div_layout.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -50,7 +50,7 @@
{%- for child in form %} {{- form_widget(child) -}} - {{- form_label(child, null, {translation_domain: choice_translation_domain}) -}} + {{- form_label(child, null, {translation_domain: choice_translation_domain, required: false}) -}} {% endfor -%}
{%- endblock choice_widget_expanded -%} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/foundation_5_layout.html.twig symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/foundation_5_layout.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/foundation_5_layout.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/foundation_5_layout.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -177,6 +177,7 @@
    {% for child in form %}
  • {{ form_widget(child, { + label_required: false, parent_label_class: label_attr.class|default(''), }) }}
  • {% endfor %} @@ -185,6 +186,7 @@
    {% for child in form %} {{ form_widget(child, { + label_required: false, parent_label_class: label_attr.class|default(''), }) }} {% endfor %} @@ -247,7 +249,7 @@ {%- endblock radio_label %} {% block checkbox_radio_label -%} - {% if required %} + {% if label_required ?? required %} {% set label_attr = label_attr|merge({class: (label_attr.class|default('') ~ ' required')|trim}) %} {% endif %} {% if errors|length > 0 -%} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/tailwind_2_layout.html.twig symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/tailwind_2_layout.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/tailwind_2_layout.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Resources/views/Form/tailwind_2_layout.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -36,7 +36,7 @@ {%- for child in form %}
    {{- form_widget(child) -}} - {{- form_label(child, null, { translation_domain: choice_translation_domain }) -}} + {{- form_label(child, null, { translation_domain: choice_translation_domain, required: false }) -}}
    {% endfor -%}
    diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionChoiceLabelTest.php symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionChoiceLabelTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionChoiceLabelTest.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionChoiceLabelTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Twig\Tests\Extension; + +use Symfony\Bridge\Twig\Extension\FormExtension; +use Symfony\Bridge\Twig\Extension\TranslationExtension; +use Symfony\Bridge\Twig\Test\FormLayoutTestCase; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\ChoiceType; +use Symfony\Component\Form\Extension\Core\Type\RadioType; + +class FormExtensionChoiceLabelTest extends FormLayoutTestCase +{ + private const THEMES = [ + 'form_div_layout.html.twig', + 'form_table_layout.html.twig', + 'bootstrap_3_layout.html.twig', + 'bootstrap_3_horizontal_layout.html.twig', + 'bootstrap_4_layout.html.twig', + 'bootstrap_4_horizontal_layout.html.twig', + 'bootstrap_5_layout.html.twig', + 'bootstrap_5_horizontal_layout.html.twig', + 'foundation_5_layout.html.twig', + 'foundation_6_layout.html.twig', + 'tailwind_2_layout.html.twig', + ]; + + public function testExpandedChoiceLabels() + { + foreach (self::THEMES as $theme) { + $this->assertExpandedChoiceLabels($theme, false, true, ''); + $this->assertExpandedChoiceLabels($theme, false, true, 'radio-inline'); + $this->assertExpandedChoiceLabels($theme, false, false, ''); + $this->assertExpandedChoiceLabels($theme, true, true, ''); + $this->assertExpandedChoiceLabels($theme, true, true, 'checkbox-inline'); + + if (str_starts_with($theme, 'bootstrap_4_')) { + $this->assertExpandedChoiceLabels($theme, false, true, 'radio-custom'); + $this->assertExpandedChoiceLabels($theme, false, true, 'radio-custom radio-inline'); + } + } + } + + public function testRequiredRadioAndCheckboxLabels() + { + foreach (self::THEMES as $theme) { + foreach ([RadioType::class, CheckboxType::class] as $type) { + $view = $this->factory->createNamed('name', $type)->createView(); + $this->setTheme($view, [$theme], false); + $html = $this->renderRow($view); + + $this->assertMatchesXpath($html, '//input[@required]'); + $this->assertMatchesXpath($html, '//label[contains(concat(" ", normalize-space(@class), " "), " required ")]'); + } + } + } + + protected function getTemplatePaths(): array + { + return [__DIR__.'/../../Resources/views/Form']; + } + + protected function getTwigExtensions(): array + { + return [new FormExtension(), new TranslationExtension()]; + } + + protected function getThemes(): array + { + return ['form_div_layout.html.twig']; + } + + private function assertExpandedChoiceLabels(string $theme, bool $multiple, bool $required, string $labelClass): void + { + // The renderer caches the blocks of child views by name, so each theme renders a form with a different name + $view = $this->factory->createNamed(strstr($theme, '.', true), ChoiceType::class, null, [ + 'choices' => ['Yes' => true, 'No' => false], + 'expanded' => true, + 'multiple' => $multiple, + 'required' => $required, + 'placeholder' => false, + 'label' => 'Visibility', + 'label_attr' => ['class' => $labelClass], + ])->createView(); + $this->setTheme($view, [$theme], false); + $html = $this->renderRow($view); + + $this->assertMatchesXpath($html, '//input[@type="'.($multiple ? 'checkbox' : 'radio').'"]', 2); + $this->assertMatchesXpath($html, '//input[@required]', $required && !$multiple ? 2 : 0); + $this->assertMatchesXpath($html, '//label[normalize-space(.)="Yes" or normalize-space(.)="No"]', 2); + $this->assertMatchesXpath($html, '//label[normalize-space(.)="Yes" or normalize-space(.)="No"][contains(concat(" ", normalize-space(@class), " "), " required ")]', 0); + $this->assertMatchesXpath($html, '//*[self::label or self::legend][normalize-space(.)="Visibility"]'); + $this->assertMatchesXpath($html, '//*[self::label or self::legend][normalize-space(.)="Visibility"][contains(concat(" ", normalize-space(@class), " "), " required ")]', $required ? 1 : 0); + + if (str_contains($labelClass, 'radio-custom')) { + $this->assertMatchesXpath($html, '//div[contains(concat(" ", normalize-space(@class), " "), " custom-radio ")]/label[contains(concat(" ", normalize-space(@class), " "), " custom-control-label ")]', 2); + } + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php 2026-11-25 09:18:34.000000000 +0000 @@ -125,8 +125,11 @@ $path = $scheme.':'.$path; } + $urlParts = parse_url($path); + // redirect if the path is a full URL - if (parse_url($path, \PHP_URL_SCHEME)) { + // a host is required for http(s) URLs, since browsers resolve "https:\\example.com" to another host + if (isset($urlParts['scheme']) && (isset($urlParts['host']) || !\in_array(strtolower($urlParts['scheme']), ['http', 'https'], true))) { return new RedirectResponse($path, $statusCode); } @@ -165,6 +168,11 @@ } } + // a path that doesn't start with "/" would change the host + if (!str_starts_with($path, '/')) { + $path = '/'.$path; + } + $url = $scheme.'://'.$request->getHost().$port.$request->getBaseUrl().$path.$qs; return new RedirectResponse($url, $statusCode); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php 2026-11-25 09:18:34.000000000 +0000 @@ -1960,7 +1960,7 @@ ->end() ->children() ->scalarNode('scope') - ->info('The regular expression that the request URL must match before adding the other options. When none is provided, the base URI is used instead.') + ->info('The regular expression that the request URL must match before adding the other options. When none is provided, the base URI is used instead. The regular expression should end with a "/", for example "https://api\.github\.com/", so that it doesn\'t match other hosts.') ->cannotBeEmpty() ->end() ->scalarNode('base_uri') diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Resources/config/test.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Resources/config/test.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Resources/config/test.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Resources/config/test.php 2026-11-25 09:18:34.000000000 +0000 @@ -39,6 +39,9 @@ ->args([ service_locator([ 'session_factory' => service('session.factory')->ignoreOnInvalid(), + 'logger' => service('logger')->ignoreOnInvalid(), + 'session_collector' => service('data_collector.request.session_collector')->ignoreOnInvalid(), + 'request_stack' => service('request_stack')->ignoreOnInvalid(), ]), param('kernel.debug'), param('session.storage.options'), diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php 2026-11-25 09:18:34.000000000 +0000 @@ -23,6 +23,9 @@ { public function redirect(string $path, string $route, ?string $scheme = null): array { + // a leading "//" or "/\", even with tabs or newlines in between, would make the redirection point to another host + $path = preg_replace(['#^/[\t\n\r]*+\K/#', '#^/[\t\n\r]*+\K\\\\#'], ['%2F', '%5C'], $path); + return [ '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction', 'path' => $path, diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -83,9 +83,6 @@ public function testAbstractControllerGetsContainerWhenNotSet() { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\TestAbstractController" has no container set, did you forget to define it as a service subscriber?'); - class_exists(AbstractControllerTest::class); $controller = new TestAbstractController(false); @@ -98,14 +95,13 @@ $request = Request::create('/'); $request->attributes->set('_controller', TestAbstractController::class.'::fooAction'); - $this->assertSame([$controller, 'fooAction'], $resolver->getController($request)); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\TestAbstractController" has no container set, did you forget to define it as a service subscriber?'); + $resolver->getController($request); } public function testAbstractControllerServiceWithFqcnIdGetsContainerWhenNotSet() { - $this->expectException(\LogicException::class); - $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\DummyController" has no container set, did you forget to define it as a service subscriber?'); - class_exists(AbstractControllerTest::class); $controller = new DummyController(); @@ -118,7 +114,9 @@ $request = Request::create('/'); $request->attributes->set('_controller', DummyController::class.'::fooAction'); - $this->assertSame([$controller, 'fooAction'], $resolver->getController($request)); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\DummyController" has no container set, did you forget to define it as a service subscriber?'); + $resolver->getController($request); } public function testAbstractControllerGetsNoContainerWhenSet() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/RedirectControllerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -197,6 +197,46 @@ $this->assertSame(302, $returnResponse->getStatusCode()); } + /** + * @dataProvider providePathWithoutLeadingSlash + */ + public function testPathWithoutLeadingSlash(string $baseUrl, string $path, string $expectedUrl) + { + $request = $this->createRequestObject('http', 'www.example.com', 80, $baseUrl); + $controller = $this->createRedirectController(); + + $this->assertRedirectUrl($controller->urlRedirectAction($request, $path), $expectedUrl); + + $request->attributes = new ParameterBag(['_route_params' => ['path' => $path]]); + $this->assertRedirectUrl($controller($request), $expectedUrl); + } + + public static function providePathWithoutLeadingSlash(): iterable + { + yield ['', '@foo.bar', 'http://www.example.com/@foo.bar']; + yield ['', '.foo.bar', 'http://www.example.com/.foo.bar']; + yield ['/base', 'redirect-path', 'http://www.example.com/base/redirect-path']; + } + + /** + * @dataProvider provideUrlWithoutHost + */ + public function testUrlWithoutHost(string $path, string $expectedUrl) + { + $request = $this->createRequestObject('http', 'www.example.com', 80, ''); + $controller = $this->createRedirectController(); + + $this->assertRedirectUrl($controller->urlRedirectAction($request, $path), $expectedUrl); + } + + public static function provideUrlWithoutHost(): iterable + { + yield ['https:\\\\foo.bar', 'http://www.example.com/https:\\\\foo.bar']; + yield ['https:/foo.bar', 'http://www.example.com/https:/foo.bar']; + yield ['HTTP:foo.bar', 'http://www.example.com/HTTP:foo.bar']; + yield ['mailto:foo@bar.com', 'mailto:foo@bar.com']; + } + public function testUrlRedirectDefaultPorts() { $host = 'www.example.com'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTestCase.php 2026-11-25 09:18:34.000000000 +0000 @@ -2138,6 +2138,17 @@ $this->assertEquals($expected, array_keys($container->getDefinition('session_listener')->getArgument(0)->getValues())); } + public function testSessionListenerInTestMode() + { + $container = $this->createContainer(); + (new FrameworkExtension())->load([['annotations' => false, 'http_method_override' => false, 'handle_all_throwables' => true, 'php_errors' => ['log' => true], 'test' => true, 'session' => ['storage_factory_id' => 'session.storage.factory.mock_file', 'handler_id' => null, 'cookie_secure' => 'auto', 'cookie_samesite' => 'lax']]], $container); + + $this->assertSame('test.session.listener', (string) $container->getAlias('session_listener')); + + $expected = ['session_factory', 'logger', 'session_collector', 'request_stack']; + $this->assertEquals($expected, array_keys($container->findDefinition('session_listener')->getArgument(0)->getValues())); + } + public function testRobotsTagListenerIsRegisteredInDebugMode() { $container = $this->createContainer(['kernel.debug' => true]); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableCompiledUrlMatcherTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableCompiledUrlMatcherTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableCompiledUrlMatcherTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableCompiledUrlMatcherTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -60,6 +60,46 @@ ); } + /** + * @dataProvider provideLeadingDoubleSlash + */ + public function testTrailingSlashRedirectEncodesLeadingDoubleSlash(string $pathinfo, string $redirectPath, string $slug) + { + $routes = new RouteCollection(); + $routes->add('foo', new Route('/{slug}/edit', [], ['slug' => '.+'])); + + $matcher = $this->getMatcher($routes, new RequestContext()); + + $this->assertSame($redirectPath, $matcher->match($pathinfo.'/')['path']); + $this->assertSame(['_route' => 'foo', 'slug' => $slug], $matcher->match($redirectPath)); + } + + /** + * @dataProvider provideLeadingDoubleSlash + */ + public function testSchemeRedirectEncodesLeadingDoubleSlash(string $pathinfo, string $redirectPath, string $slug) + { + $routes = new RouteCollection(); + $routes->add('foo', new Route('/{slug}/edit', [], ['slug' => '.+'], [], '', ['https'])); + + $matcher = $this->getMatcher($routes, new RequestContext()); + + $parameters = $matcher->match($pathinfo); + $this->assertSame($redirectPath, $parameters['path']); + $this->assertSame('https', $parameters['scheme']); + + $matcher = $this->getMatcher($routes, new RequestContext('', 'GET', 'localhost', 'https')); + $this->assertSame(['_route' => 'foo', 'slug' => $slug], $matcher->match($redirectPath)); + } + + public static function provideLeadingDoubleSlash(): iterable + { + yield ['//evil.example/edit', '/%2Fevil.example/edit', '/evil.example']; + yield ['///evil.example/edit', '/%2F/evil.example/edit', '//evil.example']; + yield ['/\\evil.example/edit', '/%5Cevil.example/edit', '\\evil.example']; + yield ["/\t/evil.example/edit", "/\t%2Fevil.example/edit", "\t/evil.example"]; + } + private function getMatcher(RouteCollection $routes, RequestContext $context) { $dumper = new CompiledUrlMatcherDumper($routes); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php 2026-11-25 09:18:34.000000000 +0000 @@ -57,6 +57,15 @@ public function collect(Request $request, Response $response, ?\Throwable $exception = null): void { + $firewallConfig = $this->firewallMap instanceof FirewallMap ? $this->firewallMap->getFirewallConfig($request) : null; + + // triggering a lazy firewall can use the session, which a stateless request forbids + $lazyFirewallPending = $request->attributes->getBoolean('_stateless') + && !$request->attributes->has('_security_firewall_run') + && null !== $firewallConfig + && $firewallConfig->isSecurityEnabled() + && !$firewallConfig->isStateless(); + if (null === $this->tokenStorage) { $this->data = [ 'enabled' => false, @@ -72,7 +81,7 @@ 'inherited_roles' => [], 'supports_role_hierarchy' => null !== $this->roleHierarchy, ]; - } elseif (null === $token = $this->tokenStorage->getToken()) { + } elseif ($lazyFirewallPending || null === $token = $this->tokenStorage->getToken()) { $this->data = [ 'enabled' => true, 'authenticated' => false, @@ -168,31 +177,34 @@ // collect firewall context information $this->data['firewall'] = null; - if ($this->firewallMap instanceof FirewallMap) { - $firewallConfig = $this->firewallMap->getFirewallConfig($request); - if (null !== $firewallConfig) { - $this->data['firewall'] = [ - 'name' => $firewallConfig->getName(), - 'request_matcher' => $firewallConfig->getRequestMatcher(), - 'security_enabled' => $firewallConfig->isSecurityEnabled(), - 'stateless' => $firewallConfig->isStateless(), - 'provider' => $firewallConfig->getProvider(), - 'context' => $firewallConfig->getContext(), - 'entry_point' => $firewallConfig->getEntryPoint(), - 'access_denied_handler' => $firewallConfig->getAccessDeniedHandler(), - 'access_denied_url' => $firewallConfig->getAccessDeniedUrl(), - 'user_checker' => $firewallConfig->getUserChecker(), - 'authenticators' => $firewallConfig->getAuthenticators(), - ]; - - // generate exit impersonation path from current request - if ($this->data['impersonated'] && null !== $switchUserConfig = $firewallConfig->getSwitchUser()) { - $exitPath = $request->getRequestUri(); - $exitPath .= null === $request->getQueryString() ? '?' : '&'; - $exitPath .= \sprintf('%s=%s', urlencode($switchUserConfig['parameter']), SwitchUserListener::EXIT_VALUE); + if (null !== $firewallConfig) { + $this->data['firewall'] = [ + 'name' => $firewallConfig->getName(), + 'request_matcher' => $firewallConfig->getRequestMatcher(), + 'security_enabled' => $firewallConfig->isSecurityEnabled(), + 'stateless' => $firewallConfig->isStateless(), + 'provider' => $firewallConfig->getProvider(), + 'context' => $firewallConfig->getContext(), + 'entry_point' => $firewallConfig->getEntryPoint(), + 'access_denied_handler' => $firewallConfig->getAccessDeniedHandler(), + 'access_denied_url' => $firewallConfig->getAccessDeniedUrl(), + 'user_checker' => $firewallConfig->getUserChecker(), + 'authenticators' => $firewallConfig->getAuthenticators(), + ]; - $this->data['impersonation_exit_path'] = $exitPath; + // generate exit impersonation path from current request + if ($this->data['impersonated'] && null !== $switchUserConfig = $firewallConfig->getSwitchUser()) { + $exitPath = $request->getRequestUri(); + + // a leading "//" would make the path point to another host + if (str_starts_with($exitPath, '//')) { + $exitPath = '/%2F'.substr($exitPath, 2); } + + $exitPath .= null === $request->getQueryString() ? '?' : '&'; + $exitPath .= \sprintf('%s=%s', urlencode($switchUserConfig['parameter']), SwitchUserListener::EXIT_VALUE); + + $this->data['impersonation_exit_path'] = $exitPath; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Debug/TraceableFirewallListener.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Debug/TraceableFirewallListener.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Debug/TraceableFirewallListener.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Debug/TraceableFirewallListener.php 2026-11-25 09:18:34.000000000 +0000 @@ -56,9 +56,11 @@ foreach ($listeners as $listener) { if ($listener instanceof LazyFirewallContext) { - \Closure::bind(function () use (&$wrappedLazyListeners, &$wrappedListeners, &$authenticatorManagerListener) { + $contextListeners = []; + \Closure::bind(function () use (&$wrappedLazyListeners, &$wrappedListeners, &$authenticatorManagerListener, &$contextListeners) { $listeners = []; foreach ($this->listeners as $listener) { + $contextListeners[] = $listener; if (!$authenticatorManagerListener && $listener instanceof TraceableAuthenticatorManagerListener) { $authenticatorManagerListener = $listener; } @@ -77,7 +79,15 @@ $this->listeners = $listeners; }, $listener, FirewallContext::class)(); - $listener($event); + try { + $listener($event); + } finally { + // The context outlives the request: put its listeners back so that the next request does not wrap the wrapped ones. + // Listeners that run lazily keep their wrapper, the context captured them when it was called. + \Closure::bind(function () use ($contextListeners) { + $this->listeners = $contextListeners; + }, $listener, FirewallContext::class)(); + } } else { $wrappedListener = $listener instanceof FirewallListenerInterface ? new WrappedLazyListener($listener) : new WrappedListener($listener); $wrappedListener($event); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php 2026-11-25 09:18:34.000000000 +0000 @@ -515,6 +515,10 @@ $firewallAuthenticationProviders = []; [$authListeners, $defaultEntryPoint] = $this->createAuthenticationListeners($container, $id, $firewall, $firewallAuthenticationProviders, $defaultProvider, $providerIds, $configuredEntryPoint); + if ($container->hasDefinition('security.listener.login_throttling.'.$id)) { + $container->getDefinition('security.listener.login_throttling.'.$id)->replaceArgument(2, $firewall['stateless']); + } + // $configuredEntryPoint is resolved into a service ID and stored in $defaultEntryPoint $configuredEntryPoint = $defaultEntryPoint; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator.php 2026-11-25 09:18:34.000000000 +0000 @@ -106,6 +106,7 @@ ->args([ service('request_stack'), abstract_arg('request rate limiter'), + true, ]) // Authenticators diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator_remember_me.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator_remember_me.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator_remember_me.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_authenticator_remember_me.php 2026-11-25 09:18:34.000000000 +0000 @@ -88,7 +88,7 @@ ->args([ abstract_arg('remember me handler'), param('kernel.secret'), - service('security.token_storage'), + service('security.untracked_token_storage'), abstract_arg('options'), service('logger')->nullOnInvalid(), ]) diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_debug.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_debug.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_debug.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Resources/config/security_debug.php 2026-11-25 09:18:34.000000000 +0000 @@ -22,6 +22,7 @@ ->args([ service('debug.security.access.decision_manager.inner'), ]) + ->tag('kernel.reset', ['method' => 'reset', 'on_invalid' => 'ignore']) ->set('debug.security.voter.vote_listener', VoteListener::class) ->args([ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -76,6 +76,41 @@ $this->assertNull($collector->getFirewall()); } + public function testCollectDoesNotTriggerLazyFirewallOnStatelessRequest() + { + $cases = [ + 'stateless request, lazy firewall not triggered' => [true, false, true, false, false], + 'stateless request, firewall already run' => [true, false, true, true, true], + 'stateless request, stateless firewall' => [true, true, true, false, true], + 'stateless request, security disabled' => [true, false, false, false, true], + 'stateful request, lazy firewall not triggered' => [false, false, true, false, true], + ]; + + foreach ($cases as $case => [$stateless, $statelessFirewall, $securityEnabled, $firewallRun, $expectedInitialized]) { + $initialized = false; + $tokenStorage = new TokenStorage(); + $tokenStorage->setInitializer(static function () use (&$initialized) { + $initialized = true; + }); + + $request = new Request(); + $request->attributes->set('_stateless', $stateless); + if ($firewallRun) { + $request->attributes->set('_security_firewall_run', '_security_main'); + } + + $firewallMap = $this->createStub(FirewallMap::class); + $firewallMap->method('getFirewallConfig')->willReturn(new FirewallConfig('main', 'security.user_checker.main', null, $securityEnabled, $statelessFirewall)); + + $collector = new SecurityDataCollector($tokenStorage, null, null, null, $firewallMap, null); + $collector->collect($request, new Response()); + + $this->assertTrue($collector->isEnabled(), $case); + $this->assertFalse($collector->isAuthenticated(), $case); + $this->assertSame($expectedInitialized, $initialized, $case); + } + } + /** @dataProvider provideRoles */ public function testCollectAuthenticationTokenAndRoles(array $roles, array $normalizedRoles, array $inheritedRoles) { @@ -120,6 +155,32 @@ $this->assertSame('hhamon', $collector->getUser()); } + /** + * @dataProvider provideImpersonationExitPath + */ + public function testCollectImpersonationExitPath(string $requestUri, string $exitPath) + { + $adminToken = new UsernamePasswordToken(new InMemoryUser('yceruto', 'P4$$w0rD', ['ROLE_ADMIN']), 'provider', ['ROLE_ADMIN']); + + $tokenStorage = new TokenStorage(); + $tokenStorage->setToken(new SwitchUserToken(new InMemoryUser('hhamon', 'P4$$w0rD', ['ROLE_USER', 'ROLE_PREVIOUS_ADMIN']), 'provider', ['ROLE_USER', 'ROLE_PREVIOUS_ADMIN'], $adminToken)); + + $firewallMap = $this->createStub(FirewallMap::class); + $firewallMap->method('getFirewallConfig')->willReturn(new FirewallConfig('dummy', 'security.user_checker.dummy', null, true, false, null, null, null, null, null, [], ['parameter' => '_switch_user'])); + + $collector = new SecurityDataCollector($tokenStorage, $this->getRoleHierarchy(), null, null, $firewallMap, null, true); + $collector->collect(new Request([], [], [], [], [], ['REQUEST_URI' => $requestUri]), new Response()); + $collector->lateCollect(); + + $this->assertSame($exitPath, $collector->getImpersonationExitPath()); + } + + public static function provideImpersonationExitPath(): iterable + { + yield ['/profile', '/profile?_switch_user=_exit']; + yield ['//example.com/profile', '/%2Fexample.com/profile?_switch_user=_exit']; + } + public function testGetFirewall() { $firewallConfig = new FirewallConfig('dummy', 'security.request_matcher.dummy', 'security.user_checker.dummy'); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Debug/TraceableFirewallListenerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,7 +13,9 @@ use PHPUnit\Framework\TestCase; use Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener; +use Symfony\Bundle\SecurityBundle\Security\FirewallContext; use Symfony\Bundle\SecurityBundle\Security\FirewallMap; +use Symfony\Bundle\SecurityBundle\Security\LazyFirewallContext; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; @@ -21,12 +23,14 @@ use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Http\Authentication\AuthenticatorManager; use Symfony\Component\Security\Http\Authenticator\Debug\TraceableAuthenticatorManagerListener; use Symfony\Component\Security\Http\Authenticator\InteractiveAuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport; +use Symfony\Component\Security\Http\Firewall\AbstractListener; use Symfony\Component\Security\Http\Firewall\AuthenticatorManagerListener; use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator; @@ -130,6 +134,86 @@ $this->assertTrue($authenticatorsInfo[1]['supports']); $this->assertStringContainsString('DummyAuthenticator', $authenticatorsInfo[1]['stub']); } + + public function testOnKernelRequestDoesNotWrapTheListenersOfALazyContextTwice() + { + $this->assertListenersOfALazyContextAreWrappedOnce(true); + } + + public function testOnKernelRequestDoesNotWrapTheDeferredListenersOfALazyContextTwice() + { + $this->assertListenersOfALazyContextAreWrappedOnce(null); + } + + public function testOnKernelRequestPutsTheListenersOfALazyContextBackWhenOneThrows() + { + $request = new Request(); + $event = new RequestEvent($this->createStub(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST); + $listener = new class extends AbstractListener { + public function supports(Request $request): ?bool + { + return true; + } + + public function authenticate(RequestEvent $event): void + { + throw new AccessDeniedException(); + } + }; + $context = new LazyFirewallContext([$listener], null, null, null, new TokenStorage()); + $firewallMap = $this->createStub(FirewallMap::class); + $firewallMap->method('getListeners')->willReturn([[$context], null, null]); + + $firewall = new TraceableFirewallListener($firewallMap, new EventDispatcher(), new LogoutUrlGenerator()); + + try { + $firewall->onKernelRequest($event); + $this->fail('An AccessDeniedException should have been thrown.'); + } catch (AccessDeniedException) { + } + + $this->assertSame([$listener], \Closure::bind(fn () => $this->listeners, $context, FirewallContext::class)()); + } + + private function assertListenersOfALazyContextAreWrappedOnce(?bool $supports): void + { + $request = new Request(); + $event = new RequestEvent($this->createStub(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST); + $listener = new class($supports) extends AbstractListener { + public int $calls = 0; + + public function __construct(private ?bool $supports) + { + } + + public function supports(Request $request): ?bool + { + return $this->supports; + } + + public function authenticate(RequestEvent $event): void + { + ++$this->calls; + } + }; + $tokenStorage = new TokenStorage(); + $context = new LazyFirewallContext([$listener], null, null, null, $tokenStorage); + $firewallMap = $this->createStub(FirewallMap::class); + $firewallMap->method('getListeners')->willReturn([[$context], null, null]); + + $firewall = new TraceableFirewallListener($firewallMap, new EventDispatcher(), new LogoutUrlGenerator()); + + for ($i = 1; $i <= 2; ++$i) { + $firewall->reset(); + $firewall->onKernelRequest($event); + $tokenStorage->getToken(); + + $this->assertSame([$listener], \Closure::bind(fn () => $this->listeners, $context, FirewallContext::class)()); + $this->assertCount(1, $listeners = $firewall->getWrappedListeners()); + $this->assertSame($listener, $listeners[0]['stub']); + $this->assertSame($i, $listener->calls); + } + } } abstract class DummyAuthenticator implements InteractiveAuthenticatorInterface diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -26,6 +26,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\ExpressionLanguage\Expression; +use Symfony\Component\HttpFoundation\RateLimiter\RequestRateLimiterInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestMatcher\PathRequestMatcher; use Symfony\Component\HttpFoundation\RequestMatcherInterface; @@ -1099,6 +1100,33 @@ $this->assertTrue($container->has('security.listener.session.'.$firewallId)); } + public function testLoginThrottlingListenerKnowsWhetherItsFirewallIsStateless() + { + $container = $this->getRawContainer(); + $container->register('app.rate_limiter', RequestRateLimiterInterface::class); + + $container->loadFromExtension('security', [ + 'firewalls' => [ + 'api' => [ + 'pattern' => '^/api', + 'stateless' => true, + 'http_basic' => true, + 'login_throttling' => ['limiter' => 'app.rate_limiter'], + ], + 'main' => [ + 'pattern' => '/.*', + 'http_basic' => true, + 'login_throttling' => ['limiter' => 'app.rate_limiter'], + ], + ], + ]); + + $container->compile(); + + $this->assertTrue($container->getDefinition('security.listener.login_throttling.api')->getArgument(2)); + $this->assertFalse($container->getDefinition('security.listener.login_throttling.main')->getArgument(2)); + } + public function testFirewallsSharingAContextDispatchOnTheirOwnEventDispatcher() { $container = $this->getRawContainer(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/RememberMeBundle/Controller/StatelessController.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/RememberMeBundle/Controller/StatelessController.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/RememberMeBundle/Controller/StatelessController.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/RememberMeBundle/Controller/StatelessController.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\RememberMeBundle\Controller; + +use Symfony\Component\HttpFoundation\Response; + +class StatelessController +{ + public function __invoke() + { + return new Response('stateless'); + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/RememberMeTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/RememberMeTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/RememberMeTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/RememberMeTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -126,6 +126,48 @@ $this->assertNull($cookieJar->get('REMEMBERME')); } + public function testStatelessRouteDoesNotUseSession() + { + $client = $this->createClient(['test_case' => 'RememberMe', 'root_config' => ['config.yml', 'config_session.yml'], 'debug' => true]); + $client->catchExceptions(false); + + $client->request('GET', '/stateless'); + $this->assertSame('stateless', $client->getResponse()->getContent()); + + $client->request('POST', '/login', [ + '_username' => 'johannes', + '_password' => 'test', + ]); + $this->assertSame(302, $client->getResponse()->getStatusCode()); + + $client->request('GET', '/stateless'); + $this->assertSame('stateless', $client->getResponse()->getContent()); + } + + public function testProfilerDoesNotTriggerLazyFirewallOnStatelessRoute() + { + $client = $this->createClient(['test_case' => 'RememberMe', 'root_config' => 'lazy_config.yml', 'debug' => true]); + $client->catchExceptions(false); + + $client->request('POST', '/login', [ + '_username' => 'johannes', + '_password' => 'test', + ]); + $this->assertSame(302, $client->getResponse()->getStatusCode()); + + $client->request('GET', '/stateless'); + $this->assertSame('stateless', $client->getResponse()->getContent()); + + $client->getCookieJar()->expire('MOCKSESSID'); + + $client->request('GET', '/stateless'); + $this->assertSame('stateless', $client->getResponse()->getContent()); + $this->assertFalse($client->getProfile()->getCollector('security')->isAuthenticated()); + + $client->request('GET', '/profile'); + $this->assertSame('johannes', $client->getResponse()->getContent()); + } + public static function provideConfigs(): iterable { yield [['root_config' => 'config_session.yml']]; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/SecurityTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/SecurityTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/SecurityTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/SecurityTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -205,6 +205,18 @@ $this->assertFalse($accessDecisionManager->decide($user, [new Expression('is_granted("ROLE_ADMIN")')])); $this->assertSame(['ROLE_ADMIN'], $checks); } + + public function testProfileListsOnlyTheAccessDecisionsOfItsRequest() + { + $client = $this->createClient(['test_case' => 'StandardFormLogin', 'root_config' => 'base_config.yml', 'debug' => true]); + $client->disableReboot(); + + $client->request('GET', '/profile'); + $this->assertCount(1, $client->getProfile()->getCollector('security')->getAccessDecisionLog()); + + $client->request('GET', '/profile'); + $this->assertCount(1, $client->getProfile()->getCollector('security')->getAccessDecisionLog()); + } } final class UserWithoutEquatable implements UserInterface, PasswordAuthenticatedUserInterface diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/lazy_config.yml symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/lazy_config.yml --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/lazy_config.yml 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/lazy_config.yml 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,8 @@ +imports: + - { resource: ./config.yml } + - { resource: ./config_session.yml } + +security: + firewalls: + default: + lazy: true diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/routing.yml symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/routing.yml --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/routing.yml 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/RememberMe/routing.yml 2026-11-25 09:18:34.000000000 +0000 @@ -7,3 +7,8 @@ profile: path: /profile controller: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\RememberMeBundle\Controller\ProfileController + +stateless: + path: /stateless + controller: Symfony\Bundle\SecurityBundle\Tests\Functional\Bundle\RememberMeBundle\Controller\StatelessController + stateless: true diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Impersonate/ImpersonateUrlGeneratorTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Impersonate/ImpersonateUrlGeneratorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Impersonate/ImpersonateUrlGeneratorTest.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/Tests/Impersonate/ImpersonateUrlGeneratorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,59 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\SecurityBundle\Tests\Impersonate; + +use PHPUnit\Framework\TestCase; +use Symfony\Bundle\SecurityBundle\Security\FirewallConfig; +use Symfony\Bundle\SecurityBundle\Security\FirewallMap; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; +use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; +use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\User\InMemoryUser; +use Symfony\Component\Security\Http\Impersonate\ImpersonateUrlGenerator; + +class ImpersonateUrlGeneratorTest extends TestCase +{ + public function testExitUrlsAreBuiltFromTheCurrentUri() + { + $generator = $this->createGenerator('/profile?page=2'); + + $this->assertSame('/profile?page=2&_switch_user=_exit', $generator->generateExitPath()); + $this->assertSame('http://localhost/profile?page=2&_switch_user=_exit', $generator->generateExitUrl()); + $this->assertSame('/dashboard?_switch_user=_exit', $generator->generateExitPath('/dashboard')); + } + + public function testExitUrlsEncodeTheLeadingDoubleSlashOfTheCurrentUri() + { + $generator = $this->createGenerator('//example.com/profile'); + + $this->assertSame('/%2Fexample.com/profile?_switch_user=_exit', $generator->generateExitPath()); + $this->assertSame('http://localhost/%2Fexample.com/profile?_switch_user=_exit', $generator->generateExitUrl()); + $this->assertSame('//example.com/profile?_switch_user=_exit', $generator->generateExitPath('//example.com/profile')); + } + + private function createGenerator(string $requestUri): ImpersonateUrlGenerator + { + $requestStack = new RequestStack(); + $requestStack->push(new Request([], [], [], [], [], ['HTTP_HOST' => 'localhost', 'REQUEST_URI' => $requestUri])); + + $firewallMap = $this->createStub(FirewallMap::class); + $firewallMap->method('getFirewallConfig')->willReturn(new FirewallConfig('main', 'security.user_checker', null, true, false, null, null, null, null, null, [], ['parameter' => '_switch_user'])); + + $originalToken = new UsernamePasswordToken(new InMemoryUser('admin', ''), 'main'); + $tokenStorage = new TokenStorage(); + $tokenStorage->setToken(new SwitchUserToken(new InMemoryUser('kuba', ''), 'main', [], $originalToken)); + + return new ImpersonateUrlGenerator($requestStack, $firewallMap, $tokenStorage); + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/composer.json symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/composer.json --- symfony-6.4.50+dfsg/src/Symfony/Bundle/SecurityBundle/composer.json 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/SecurityBundle/composer.json 2026-11-25 09:18:34.000000000 +0000 @@ -27,9 +27,9 @@ "symfony/http-kernel": "^6.2", "symfony/http-foundation": "^6.4.50|^7.4.23", "symfony/password-hasher": "^5.4|^6.0|^7.0", - "symfony/security-core": "^6.4.49|^7.4.22", + "symfony/security-core": "^6.4.51|^7.4.22", "symfony/security-csrf": "^5.4|^6.0|^7.0", - "symfony/security-http": "^6.3.6|^7.0", + "symfony/security-http": "^6.4.51|^7.4.24", "symfony/service-contracts": "^2.5|^3" }, "require-dev": { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/http_client.html.twig symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/http_client.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/http_client.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Collector/http_client.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -108,7 +108,7 @@ {% if header matches '/^x-debug-token: .*$/i' %} {% set profiler_token = (header.getValue | slice('x-debug-token: ' | length)) %} {% endif %} - {% if header matches '/^x-debug-token-link: .*$/i' %} + {% if header matches '{^x-debug-token-link: https?://}i' %} {% set profiler_link = (header.getValue | slice('x-debug-token-link: ' | length)) %} {% endif %} {% endfor %} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/_request_summary.html.twig symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/_request_summary.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/_request_summary.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/_request_summary.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -55,7 +55,7 @@ {% endif %} {% set referer = request_collector ? request_collector.requestheaders.get('referer') : null %} - {% if referer %} + {% if referer and referer matches '{^https?://}i' %}
    {{ source('@WebProfiler/Icon/referrer.svg') }} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_js.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -109,6 +109,19 @@ var requestStack = []; + var parseUrl = function(url) { + var a = document.createElement('a'); + a.href = url; + + return a; + }; + + var isSameOrigin = function(url) { + url = parseUrl(url); + + return url.protocol === location.protocol && url.host === location.host; + }; + var extractHeaders = function(xhr, stackElement) { /* Here we avoid to call xhr.getResponseHeader in order to */ /* prevent polluting the console with CORS security errors */ @@ -121,6 +134,9 @@ if (ret = allHeaders.match(/^x-debug-token-link:\s+(.*)$/im)) { stackElement.profilerUrl = ret[1]; } + if (!isSameOrigin(xhr.responseURL || stackElement.url)) { + return; + } if (ret = allHeaders.match(/^Symfony-Debug-Toolbar-Replace:\s+(.*)$/im)) { stackElement.toolbarReplaceFinished = false; stackElement.toolbarReplace = '1' === ret[1]; @@ -291,7 +307,7 @@ durationCell.textContent = request.duration + ' ms'; } - if (request.profilerUrl) { + if (request.profilerUrl && /^https?:$/.test(parseUrl(request.profilerUrl).protocol)) { profilerCell.textContent = ''; var profilerLink = document.createElement('a'); profilerLink.setAttribute('href', request.profilerUrl); @@ -343,8 +359,10 @@ stackElement.statusCode = r.status; stackElement.profile = r.headers.get('x-debug-token'); stackElement.profilerUrl = r.headers.get('x-debug-token-link'); - stackElement.toolbarReplaceFinished = false; - stackElement.toolbarReplace = '1' === r.headers.get('Symfony-Debug-Toolbar-Replace'); + if (isSameOrigin(r.url || url)) { + stackElement.toolbarReplaceFinished = false; + stackElement.toolbarReplace = '1' === r.headers.get('Symfony-Debug-Toolbar-Replace'); + } finishAjaxRequest(idx); }, function (e){ stackElement.error = true; @@ -548,9 +566,27 @@ newToken = (newToken || token); + var showError = function() { + var sfwdt = that.getSfwdt(token); + sfwdt.innerHTML = '\ +
    \ +
    \ + An error occurred while loading the web debug toolbar. Open the web profiler.\ +
    \ + '; + sfwdt.querySelector('.sf-toolbarreset > a').setAttribute('href', '{{ url("_profiler_home")|escape('js') }}' + encodeURIComponent(newToken)); + sfwdt.parentElement.setAttribute('class', 'sf-toolbar sf-error-toolbar'); + }; + + if (!/^[\w-]+$/.test(newToken)) { + showError(); + + return this; + } + this.load( 'sfwdt' + token, - '{{ url("_wdt", { "token": "xxxxxx" })|escape('js') }}'.replace(/xxxxxx/, newToken), + '{{ url("_wdt", { "token": "xxxxxx" })|escape('js') }}'.replace(/xxxxxx/, encodeURIComponent(newToken)), function(xhr, el) { var toolbarContent = document.getElementById('sfToolbarMainContent-' + newToken); @@ -634,14 +670,7 @@ }, function(xhr) { if (xhr.status !== 0 && !options.stop) { - var sfwdt = that.getSfwdt(token); - sfwdt.innerHTML = '\ -
    \ -
    \ - An error occurred while loading the web debug toolbar. Open the web profiler.\ -
    \ - '; - sfwdt.parentElement.setAttribute('class', 'sf-toolbar sf-error-toolbar'); + showError(); } }, options diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_redirect.html.twig symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_redirect.html.twig --- symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_redirect.html.twig 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Resources/views/Profiler/toolbar_redirect.html.twig 2026-11-25 09:18:34.000000000 +0000 @@ -42,7 +42,9 @@ {% set absolute_url = absolute_url(location) %}

    This request redirects to {{ absolute_url }}

    -

    Follow redirect

    + {% if absolute_url matches '{^https?://}i' %} +

    Follow redirect

    + {% endif %}

    The redirect was intercepted by the Symfony Web Debug toolbar to help debugging. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Controller/ProfilerControllerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -121,6 +121,57 @@ $this->assertSame('_', $crawler->filter('.metrics .metric .value')->eq(0)->text()); } + /** + * @dataProvider provideRefererLinks + */ + public function testPanelActionLinksToHttpRefererOnly(string $referer, bool $isLinked) + { + $kernel = new WebProfilerBundleKernel(); + $client = new KernelBrowser($kernel); + + $client->request('POST', '/', [], [], ['HTTP_REFERER' => $referer]); + $crawler = $client->request('GET', '/_profiler/latest'); + + $this->assertCount($isLinked ? 1 : 0, $crawler->filter('a.referer')); + } + + public static function provideRefererLinks(): iterable + { + yield ['http://localhost/form', true]; + yield ['HTTPS://localhost/form', true]; + yield ['javascript:alert(1)', false]; + yield [' javascript:alert(1)', false]; + } + + /** + * @dataProvider provideRedirectLocations + */ + public function testToolbarRedirectLinksToHttpLocationOnly(string $location, bool $isLinked) + { + $kernel = new WebProfilerBundleKernel(true); + $client = new KernelBrowser($kernel); + + $crawler = $client->request('GET', '/redirect', ['location' => $location]); + + $this->assertSame(200, $client->getResponse()->getStatusCode()); + + $links = $crawler->filter('.block-exception a'); + if ($isLinked) { + $this->assertCount(1, $links); + } + foreach ($links as $link) { + $this->assertSame(1, preg_match('{^(https?://|/)}i', $link->getAttribute('href'))); + } + } + + public static function provideRedirectLocations(): iterable + { + yield ['http://localhost/target', true]; + yield ['/target', true]; + yield ['javascript:alert(1)', false]; + yield ['javascript://%0aalert(1)', false]; + } + public function testToolbarActionWithProfilerDisabled() { $urlGenerator = $this->createStub(UrlGeneratorInterface::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Functional/WebProfilerBundleKernel.php symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Functional/WebProfilerBundleKernel.php --- symfony-6.4.50+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Functional/WebProfilerBundleKernel.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Bundle/WebProfilerBundle/Tests/Functional/WebProfilerBundleKernel.php 2026-11-25 09:18:34.000000000 +0000 @@ -18,6 +18,8 @@ use Symfony\Bundle\WebProfilerBundle\WebProfilerBundle; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\HttpFoundation\RedirectResponse; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\DumpDataCollector; use Symfony\Component\HttpKernel\Kernel; @@ -27,8 +29,9 @@ { use MicroKernelTrait; - public function __construct() - { + public function __construct( + private bool $interceptRedirects = false, + ) { parent::__construct('test', false); } @@ -46,6 +49,7 @@ $routes->import(__DIR__.'/../../Resources/config/routing/profiler.xml')->prefix('/_profiler'); $routes->import(__DIR__.'/../../Resources/config/routing/wdt.xml')->prefix('/_wdt'); $routes->add('_', '/')->controller('kernel::homepageController'); + $routes->add('redirect', '/redirect')->controller('kernel::redirectController'); $routes->add('csp', '/csp')->controller('kernel::cspController'); } @@ -69,13 +73,13 @@ $container->loadFromExtension('web_profiler', [ 'toolbar' => true, - 'intercept_redirects' => false, + 'intercept_redirects' => $this->interceptRedirects, ]); } public function getCacheDir(): string { - return sys_get_temp_dir().'/cache-'.spl_object_id($this); + return sys_get_temp_dir().'/cache-'.spl_object_id($this).($this->interceptRedirects ? '-intercept' : ''); } public function getLogDir(): string @@ -94,6 +98,11 @@ return new Response('Homepage Controller.'); } + public function redirectController(Request $request): Response + { + return new RedirectResponse($request->query->get('location')); + } + public function cspController(): Response { return new Response('CSP Controller.', 200, ['Content-Security-Policy' => "default-src 'self'"]); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapAuditor.php symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapAuditor.php --- symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapAuditor.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapAuditor.php 2026-11-25 09:18:34.000000000 +0000 @@ -108,7 +108,16 @@ $range = ['=', $range[0]]; } - if (!version_compare($version, $range[1], $range[0])) { + $result = ImportMapVersionChecker::compareVersions($version, $range[1]); + $matches = match ($range[0]) { + '<' => $result < 0, + '<=' => $result <= 0, + '>' => $result > 0, + '>=' => $result >= 0, + '=' => 0 === $result, + }; + + if (!$matches) { return false; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapUpdateChecker.php symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapUpdateChecker.php --- symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapUpdateChecker.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapUpdateChecker.php 2026-11-25 09:18:34.000000000 +0000 @@ -71,24 +71,34 @@ private function getVersionPart(string $version, int $part): ?string { - return explode('.', $version)[$part] ?? $version; + return explode('.', $this->getVersionCore($version))[$part] ?? $version; + } + + private function getVersionCore(string $version): string + { + return explode('-', $version, 2)[0]; } private function getUpdateType(string $currentVersion, string $latestVersion): string { - if (version_compare($currentVersion, $latestVersion, '>')) { + if (0 < ImportMapVersionChecker::compareVersions($currentVersion, $latestVersion)) { return PackageUpdateInfo::UPDATE_TYPE_DOWNGRADE; } - if (version_compare($currentVersion, $latestVersion, '==')) { + if (0 === ImportMapVersionChecker::compareVersions($currentVersion, $latestVersion)) { return PackageUpdateInfo::UPDATE_TYPE_UP_TO_DATE; } if ($this->getVersionPart($currentVersion, 0) < $this->getVersionPart($latestVersion, 0)) { return PackageUpdateInfo::UPDATE_TYPE_MAJOR; } + // like npm and Composer, ^0.186.0 excludes 0.187.0 and ^0.0.3 excludes 0.0.4 if ($this->getVersionPart($currentVersion, 1) < $this->getVersionPart($latestVersion, 1)) { - return PackageUpdateInfo::UPDATE_TYPE_MINOR; + return str_starts_with($currentVersion, '0.') ? PackageUpdateInfo::UPDATE_TYPE_MAJOR : PackageUpdateInfo::UPDATE_TYPE_MINOR; } if ($this->getVersionPart($currentVersion, 2) < $this->getVersionPart($latestVersion, 2)) { + return str_starts_with($currentVersion, '0.0.') ? PackageUpdateInfo::UPDATE_TYPE_MAJOR : PackageUpdateInfo::UPDATE_TYPE_PATCH; + } + if ($this->getVersionCore($currentVersion) === $this->getVersionCore($latestVersion)) { + // only the pre-release differs: npm and Composer both accept 2.0.0-beta.4 and 2.0.0 for ^2.0.0-beta.3 return PackageUpdateInfo::UPDATE_TYPE_PATCH; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapVersionChecker.php symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapVersionChecker.php --- symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapVersionChecker.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/ImportMap/ImportMapVersionChecker.php 2026-11-25 09:18:34.000000000 +0000 @@ -158,6 +158,47 @@ return implode(' ', $processedSegments); } + /** + * Compares two npm versions using the semver precedence rules, where pre-releases come before their release. + * + * @internal + */ + public static function compareVersions(string $version1, string $version2): int + { + [$version1, $preRelease1] = explode('-', $version1, 2) + [1 => null]; + [$version2, $preRelease2] = explode('-', $version2, 2) + [1 => null]; + + if ($result = version_compare($version1, $version2)) { + return $result; + } + if (null === $preRelease1 || null === $preRelease2) { + return (null === $preRelease1) <=> (null === $preRelease2); + } + + $identifiers1 = explode('.', $preRelease1); + $identifiers2 = explode('.', $preRelease2); + + foreach ($identifiers1 as $i => $identifier1) { + if (!isset($identifiers2[$i])) { + return 1; + } + + $identifier2 = $identifiers2[$i]; + $result = match (true) { + ctype_digit($identifier1) && ctype_digit($identifier2) => $identifier1 <=> $identifier2, + ctype_digit($identifier1) => -1, + ctype_digit($identifier2) => 1, + default => strcmp($identifier1, $identifier2), + }; + + if ($result) { + return $result; + } + } + + return \count($identifiers1) <=> \count($identifiers2); + } + private static function cleanVersionSegment(string $segment): string { return str_replace(['v', '.x'], ['', '.*'], $segment); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/Factory/CachedMappedAssetFactoryTest.php symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/Factory/CachedMappedAssetFactoryTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/Factory/CachedMappedAssetFactoryTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/Factory/CachedMappedAssetFactoryTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -100,6 +100,7 @@ $newSourceTimestamp = $cacheTimestamp + 1; touch($sourcePath, $sourceTimestamp); touch($cachePath, $cacheTimestamp); + touch($cachePath.'.meta', $cacheTimestamp); clearstatcache(); $configCache = new ConfigCache($cachePath, true); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapAuditorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapAuditorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapAuditorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapAuditorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -130,6 +130,13 @@ yield [false, '1.0.0', '> 1.0.0, < 1.2.0']; yield [true, '1.1.0', '> 1.0.0, < 1.2.0']; yield [false, '1.2.0', '> 1.0.0, < 1.2.0']; + yield [true, '11.0.0-preview.7.26381.103', '< 11.0.0']; + yield [true, '11.0.0-preview.7.26381.103', '< 11.0.0-rc.1']; + yield [true, '1.2.3-pre.1', '>= 1.0.0, < 1.2.3']; + yield [true, '1.2.3-1', '< 1.2.3']; + yield [true, '1.0.0-alpha.1', '< 1.0.0-alpha.beta']; + yield [true, '4.0.0-canary.9', '>= 4.0.0-canary.0, < 4.0.0-canary.34']; + yield [false, '4.0.0-canary.34', '>= 4.0.0-canary.0, < 4.0.0-canary.34']; } public function testAuditError() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapUpdateCheckerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapUpdateCheckerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapUpdateCheckerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapUpdateCheckerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -160,6 +160,51 @@ ), ], null, ]; + yield 'pre-release to pre-release' => [ + [self::createRemoteEntry('next-beta', '2.0.0-beta.3')], + ['next-beta' => new PackageUpdateInfo('next-beta', '2.0.0-beta.3', '2.0.0-beta.4', 'patch')], + null, + ]; + yield 'pre-release without a dot to pre-release' => [ + [self::createRemoteEntry('next-beta-nodot', '5.0.0-beta1')], + ['next-beta-nodot' => new PackageUpdateInfo('next-beta-nodot', '5.0.0-beta1', '5.0.0-beta2', 'patch')], + null, + ]; + yield 'pre-release to release' => [ + [self::createRemoteEntry('next-release', '2.0.0-beta.3')], + ['next-release' => new PackageUpdateInfo('next-release', '2.0.0-beta.3', '2.0.0', 'patch')], + null, + ]; + yield 'pre-release to a later patch' => [ + [self::createRemoteEntry('next-patch', '1.2.3-beta.1')], + ['next-patch' => new PackageUpdateInfo('next-patch', '1.2.3-beta.1', '1.2.10', 'patch')], + null, + ]; + yield 'pre-release named "preview" to release' => [ + [self::createRemoteEntry('next-preview', '11.0.0-preview.7.26381.103')], + ['next-preview' => new PackageUpdateInfo('next-preview', '11.0.0-preview.7.26381.103', '11.0.0', 'patch')], + null, + ]; + yield 'numeric pre-release to release' => [ + [self::createRemoteEntry('next-numeric', '1.2.3-1')], + ['next-numeric' => new PackageUpdateInfo('next-numeric', '1.2.3-1', '1.2.3', 'patch')], + null, + ]; + yield '0.x minor update' => [ + [self::createRemoteEntry('zero-minor', '0.186.0')], + ['zero-minor' => new PackageUpdateInfo('zero-minor', '0.186.0', '0.187.0', 'major')], + null, + ]; + yield '0.x patch update' => [ + [self::createRemoteEntry('zero-patch', '0.186.0')], + ['zero-patch' => new PackageUpdateInfo('zero-patch', '0.186.0', '0.186.1', 'patch')], + null, + ]; + yield '0.0.x patch update' => [ + [self::createRemoteEntry('zero-zero-patch', '0.0.3')], + ['zero-zero-patch' => new PackageUpdateInfo('zero-zero-patch', '0.0.3', '0.0.4', 'major')], + null, + ]; yield [ [ self::createRemoteEntry( @@ -200,6 +245,33 @@ 'https://registry.npmjs.org/lodash' => new JsonMockResponse([ 'dist-tags' => ['latest' => '4.17.21'], // no update ]), + 'https://registry.npmjs.org/next-beta' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '2.0.0-beta.4'], + ]), + 'https://registry.npmjs.org/next-beta-nodot' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '5.0.0-beta2'], + ]), + 'https://registry.npmjs.org/next-release' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '2.0.0'], + ]), + 'https://registry.npmjs.org/next-patch' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '1.2.10'], + ]), + 'https://registry.npmjs.org/next-preview' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '11.0.0'], + ]), + 'https://registry.npmjs.org/next-numeric' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '1.2.3'], + ]), + 'https://registry.npmjs.org/zero-minor' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '0.187.0'], + ]), + 'https://registry.npmjs.org/zero-patch' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '0.186.1'], + ]), + 'https://registry.npmjs.org/zero-zero-patch' => new JsonMockResponse([ + 'dist-tags' => ['latest' => '0.0.4'], + ]), ]; return $map[$url] ?? new MockResponse('Not found', ['http_code' => 404]); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapVersionCheckerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapVersionCheckerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapVersionCheckerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/AssetMapper/Tests/ImportMap/ImportMapVersionCheckerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -444,6 +444,14 @@ ]; } + public function testCompareVersions() + { + $versions = ['1.0.0', '1.0.0-rc.10', '1.0.0-rc.1', '1.0.0-preview.7', '1.0.0-pre.1', '1.0.0-beta.11', '1.0.0-beta.2', '1.0.0-beta', '1.0.0-alpha.beta', '1.0.0-alpha.1', '1.0.0-alpha', '1.0.0-1', '0.9.0']; + usort($versions, ImportMapVersionChecker::compareVersions(...)); + + $this->assertSame(['0.9.0', '1.0.0-1', '1.0.0-alpha', '1.0.0-alpha.1', '1.0.0-alpha.beta', '1.0.0-beta', '1.0.0-beta.2', '1.0.0-beta.11', '1.0.0-pre.1', '1.0.0-preview.7', '1.0.0-rc.1', '1.0.0-rc.10', '1.0.0'], $versions); + } + private static function createRemoteEntry(string $importName, string $version, ?string $packageModuleSpecifier = null): ImportMapEntry { $packageModuleSpecifier ??= $importName; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/BrowserKit/AbstractBrowser.php symfony-6.4.51+dfsg/src/Symfony/Component/BrowserKit/AbstractBrowser.php --- symfony-6.4.50+dfsg/src/Symfony/Component/BrowserKit/AbstractBrowser.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/BrowserKit/AbstractBrowser.php 2026-11-25 09:18:34.000000000 +0000 @@ -580,6 +580,16 @@ $server = $request->getServer(); $server = $this->updateServerFromUri($server, $this->redirect); + // Authorization and Cookie headers MUST NOT follow redirects to another scheme or authority + $uri = $this->getAbsoluteUri($this->redirect); + if (parse_url($uri, \PHP_URL_SCHEME) !== parse_url($request->getUri(), \PHP_URL_SCHEME) || $this->extractHost($uri) !== $this->extractHost($request->getUri())) { + foreach ($server as $key => $value) { + if (\in_array(strtolower(str_replace('_', '-', $key)), ['http-authorization', 'http-cookie'], true)) { + unset($server[$key]); + } + } + } + $this->isMainRequest = false; $response = $this->request($method, $this->redirect, $parameters, $files, $server, $content); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php symfony-6.4.51+dfsg/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/BrowserKit/Tests/AbstractBrowserTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -621,6 +621,31 @@ $this->assertEquals($headers, $client->getRequest()->getServer()); } + /** + * @dataProvider provideRedirectsAndCredentials + */ + public function testFollowRedirectDropsCredentialsWhenTheOriginChanges(string $location, bool $keepsCredentials) + { + $credentials = ['HTTP_Authorization' => 'Bearer foo', 'HTTP_COOKIE' => 'foo=bar']; + + $client = $this->getBrowser(); + $client->setNextResponse(new Response('', 302, ['Location' => $location])); + $client->request('GET', 'http://www.example.com/foo/', [], [], $credentials); + + $this->assertSame($keepsCredentials ? $credentials : [], array_intersect_key($client->getRequest()->getServer(), $credentials)); + } + + public static function provideRedirectsAndCredentials(): iterable + { + yield 'same origin' => ['http://www.example.com/redirected', true]; + yield 'relative path' => ['redirected', true]; + yield 'absolute path' => ['/redirected', true]; + yield 'other host' => ['http://www.example.org/redirected', false]; + yield 'other scheme' => ['https://www.example.com/redirected', false]; + yield 'other port' => ['http://www.example.com:8080/redirected', false]; + yield 'protocol-relative' => ['//www.example.org/redirected', false]; + } + public function testIsFollowingRedirects() { $client = $this->getBrowser(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/AbstractTagAwareAdapter.php 2026-11-25 09:18:34.000000000 +0000 @@ -95,7 +95,7 @@ if ($metadata) { // For compactness, expiry and creation duration are packed, using magic numbers as separators - $value['meta'] = pack('VN', (int) (0.1 + $metadata[CacheItem::METADATA_EXPIRY] - CacheItem::METADATA_EXPIRY_OFFSET), $metadata[CacheItem::METADATA_CTIME]); + $value['meta'] = pack('VN', (int) (0.1 + $metadata[CacheItem::METADATA_EXPIRY] - CacheItem::METADATA_EXPIRY_OFFSET), $metadata[CacheItem::METADATA_CTIME] ?? 0); } // Extract tag changes, these should be removed from values in doSave() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/ChainAdapter.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/ChainAdapter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/ChainAdapter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/ChainAdapter.php 2026-11-25 09:18:34.000000000 +0000 @@ -38,6 +38,7 @@ private int $defaultLifetime; private static \Closure $syncItem; + private static \Closure $setExpiryMetadata; /** * @param CacheItemPoolInterface[] $adapters The ordered list of adapters used to fetch cached items @@ -87,6 +88,22 @@ null, CacheItem::class ); + self::$setExpiryMetadata ??= \Closure::bind( + static function (CacheItemInterface $item) { + if (!$item instanceof CacheItem) { + return; + } + + if ($item->expiry) { + // keep the expiry so that it can be restored when the item is propagated to previous adapters + $item->newMetadata[CacheItem::METADATA_EXPIRY] = $item->expiry; + } else { + unset($item->newMetadata[CacheItem::METADATA_EXPIRY]); + } + }, + null, + CacheItem::class + ); } public function get(string $key, callable $callback, ?float $beta = null, ?array &$metadata = null): mixed @@ -234,6 +251,7 @@ public function save(CacheItemInterface $item): bool { + (self::$setExpiryMetadata)($item); $saved = true; $i = $this->adapterCount; @@ -246,6 +264,7 @@ public function saveDeferred(CacheItemInterface $item): bool { + (self::$setExpiryMetadata)($item); $saved = true; $i = $this->adapterCount; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/MemcachedAdapter.php 2026-11-25 09:18:34.000000000 +0000 @@ -180,12 +180,43 @@ if (!\array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !\array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) { $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true); } + $booleanOptions = [ + 'AUTO_EJECT_HOSTS', + 'BINARY_PROTOCOL', + 'BUFFER_WRITES', + 'CACHE_LOOKUPS', + 'COMPRESSION', + 'HASH_WITH_PREFIX_KEY', + 'LIBKETAMA_COMPATIBLE', + 'NO_BLOCK', + 'NOREPLY', + 'RANDOMIZE_REPLICA_READ', + 'REMOVE_FAILED_SERVERS', + 'SORT_HOSTS', + 'TCP_KEEPALIVE', + 'TCP_NODELAY', + 'USE_UDP', + 'VERIFY_KEY', + ]; + $constantPrefixes = [ + 'COMPRESSION_TYPE' => 'COMPRESSION_', + 'LIBKETAMA_HASH' => 'HASH_', + ]; foreach ($options as $name => $value) { if (\is_int($name)) { continue; } if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) { $value = \constant('Memcached::'.$name.'_'.strtoupper($value)); + } elseif (\is_string($value) && isset($constantPrefixes[$name]) && \defined('Memcached::'.$constantPrefixes[$name].strtoupper($value))) { + $value = \constant('Memcached::'.$constantPrefixes[$name].strtoupper($value)); + } elseif (\is_string($value) && 'PREFIX_KEY' !== $name && \defined('Memcached::OPT_'.$name)) { + // ext-memcached reads the other options as integers, which turns strings like "true" into 0 + if (\in_array($name, $booleanOptions, true)) { + $value = filter_var($value, \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Invalid Memcached DSN: parameter "%s" must be a boolean.', strtolower($name))); + } else { + $value = filter_var($value, \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Invalid Memcached DSN: parameter "%s" must be an integer.', strtolower($name))); + } } unset($options[$name]); @@ -240,7 +271,8 @@ } if ($lifetime && $lifetime > 30 * 86400) { - $lifetime += time(); + // memcached reads an expiration longer than 30 days as a Unix timestamp, which its text protocol parses as a 32-bit signed integer + $lifetime = min($lifetime + time(), 2147483647); } $encodedValues = []; @@ -255,12 +287,13 @@ { try { $encodedIds = array_map([__CLASS__, 'encodeKey'], $ids); + $ids = array_combine($encodedIds, $ids); $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds)); $result = []; foreach ($encodedResult as $key => $value) { - $result[self::decodeKey($key)] = $this->marshaller->unmarshall($value); + $result[$ids[$key]] = $this->marshaller->unmarshall($value); } return $result; @@ -324,9 +357,4 @@ { return strtr($key, self::RESERVED_MEMCACHED, self::RESERVED_PSR6); } - - private static function decodeKey(string $key): string - { - return strtr($key, self::RESERVED_PSR6, self::RESERVED_MEMCACHED); - } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Adapter/RedisTagAwareAdapter.php 2026-11-25 09:18:34.000000000 +0000 @@ -226,23 +226,25 @@ until '0' == cursor; end - redis.call('SUNIONSTORE', '{'..id..'}'..id, id) + redis.call('SUNIONSTORE', KEYS[2], id) redis.call('DEL', id) - return redis.call('SSCAN', '{'..id..'}'..id, '0', 'COUNT', 5000) + return redis.call('SSCAN', KEYS[2], '0', 'COUNT', 5000) EOLUA; - $results = $this->pipeline(function () use ($tagIds, $lua) { - $isRelay = $this->redis instanceof Relay; + $isRelay = $this->redis instanceof Relay; - if ($this->redis instanceof \Predis\ClientInterface) { - $prefix = $this->redis->getOptions()->prefix ? $this->redis->getOptions()->prefix->getPrefix() : ''; - } elseif (\is_array($prefix = $this->redis->getOption($isRelay ? Relay::OPT_PREFIX : \Redis::OPT_PREFIX) ?? '')) { - $prefix = current($prefix); - } + if ($this->redis instanceof \Predis\ClientInterface) { + $prefix = $this->redis->getOptions()->prefix ? $this->redis->getOptions()->prefix->getPrefix() : ''; + } elseif (\is_array($prefix = $this->redis->getOption($isRelay ? Relay::OPT_PREFIX : \Redis::OPT_PREFIX) ?? '')) { + $prefix = current($prefix); + } + $results = $this->pipeline(function () use ($tagIds, $lua, $prefix, $isRelay) { foreach ($tagIds as $id) { - yield 'eval' => $this->redis instanceof \Predis\ClientInterface ? [$lua, 1, $id, $prefix, '1'] : [$lua, [$id, $prefix, $isRelay ? '0' : '1'], 1]; + // declared so that servers enforcing KEYS (e.g. Dragonfly) accept the script; same hash slot as $id + $tmpId = '{'.$prefix.$id.'}'.$id; + yield 'eval' => $this->redis instanceof \Predis\ClientInterface ? [$lua, 2, $id, $tmpId, $prefix, '1'] : [$lua, [$id, $tmpId, $prefix, $isRelay ? '0' : '1'], 2]; } }); @@ -251,9 +253,9 @@ local id = KEYS[1] local cursor = table.remove(ARGV) - redis.call('SREM', '{'..id..'}'..id, unpack(ARGV)) + redis.call('SREM', KEYS[2], unpack(ARGV)) - return redis.call('SSCAN', '{'..id..'}'..id, cursor, 'COUNT', 5000) + return redis.call('SSCAN', KEYS[2], cursor, 'COUNT', 5000) EOLUA; $success = true; @@ -270,13 +272,13 @@ while ($ids || '0' !== $cursor) { $this->doDelete($ids); - $evalArgs = [$id, $cursor]; - array_splice($evalArgs, 1, 0, $ids); + $evalArgs = [$id, '{'.$prefix.$id.'}'.$id, $cursor]; + array_splice($evalArgs, 2, 0, $ids); if ($this->redis instanceof \Predis\ClientInterface) { - array_unshift($evalArgs, $lua, 1); + array_unshift($evalArgs, $lua, 2); } else { - $evalArgs = [$lua, $evalArgs, 1]; + $evalArgs = [$lua, $evalArgs, 2]; } $results = $this->pipeline(static function () use ($evalArgs) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/AdapterTestCase.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,6 +15,7 @@ use PHPUnit\Framework\Assert; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; +use Psr\Cache\InvalidArgumentException; use Symfony\Component\Cache\CacheItem; use Symfony\Component\Cache\PruneableInterface; use Symfony\Contracts\Cache\CallbackInterface; @@ -40,6 +41,25 @@ } } + public function testInvalidKeyWithoutAssertions() + { + if (isset($this->skippedTests[__FUNCTION__])) { + $this->markTestSkipped($this->skippedTests[__FUNCTION__]); + } + + $cache = $this->createCachePool(); + $assertions = '-1' === \ini_get('zend.assertions') ? false : ini_set('zend.assertions', '0'); + + try { + $this->expectException(InvalidArgumentException::class); + $cache->getItem('user@name'); + } finally { + if (false !== $assertions) { + ini_set('zend.assertions', $assertions); + } + } + } + public function testGet() { if (isset($this->skippedTests[__FUNCTION__])) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ArrayAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -26,6 +26,7 @@ 'testDeferredSaveWithoutCommit' => 'Assumes a shared cache which ArrayAdapter is not.', 'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.', 'testClearWithInvalidPrefix' => 'ArrayAdapter does not validate the prefix.', + 'testInvalidKeyWithoutAssertions' => 'ArrayAdapter checks keys only when assert() is enabled.', ]; public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ChainAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,6 +16,8 @@ use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\ChainAdapter; use Symfony\Component\Cache\Adapter\FilesystemAdapter; +use Symfony\Component\Cache\Adapter\FilesystemTagAwareAdapter; +use Symfony\Component\Cache\Adapter\TagAwareAdapter; use Symfony\Component\Cache\CacheItem; use Symfony\Component\Cache\Exception\InvalidArgumentException; use Symfony\Component\Cache\Tests\Fixtures\ExternalAdapter; @@ -263,6 +265,95 @@ $this->assertFalse($adapter1->getItem('key')->isHit(), 'Item should have expired in adapter1 with original TTL, not defaultLifetime'); } + public function testItemExpiryIsPreservedWhenPropagatedFromFilesystemAdapter() + { + $adapter1 = new ArrayAdapter(100); + $adapter2 = new FilesystemAdapter('', 100); + + $cache = new ChainAdapter([$adapter1, $adapter2], 100); + + $cache->save($cache->getItem('key')->expiresAfter(2)->set('value')); + + $adapter1->clear(); + $cache->getItem('key'); + $this->assertTrue($adapter1->hasItem('key')); + + sleep(3); + + $this->assertFalse($adapter2->getItem('key')->isHit(), 'Item should have expired in adapter2'); + $this->assertFalse($adapter1->getItem('key')->isHit(), 'Item should have expired in adapter1 with original TTL, not defaultLifetime'); + } + + public function testItemSavedAgainWithoutExpiryIsPropagatedWithDefaultLifetime() + { + $adapter1 = new ArrayAdapter(100); + $adapter2 = new FilesystemAdapter('', 100); + + $cache = new ChainAdapter([$adapter1, $adapter2], 100); + + $item = $cache->getItem('key')->expiresAfter(2)->set('value'); + $cache->save($item); + $cache->save($item->expiresAfter(null)); + + $adapter1->clear(); + $cache->getItem('key'); + + sleep(3); + + $this->assertTrue($adapter2->getItem('key')->isHit()); + $this->assertTrue($adapter1->getItem('key')->isHit(), 'Item should have been propagated to adapter1 with defaultLifetime, not the expiry it was first saved with'); + } + + public function testPropagationToTagAwareAdapterWithDefaultLifetime() + { + $adapter1 = new FilesystemTagAwareAdapter('tag-aware'); + $adapter2 = new FilesystemAdapter('plain'); + + $adapter2->save($adapter2->getItem('key')->set('value')); + + $cache = new ChainAdapter([$adapter1, $adapter2], 100); + + $warnings = []; + set_error_handler(static function (int $type, string $message) use (&$warnings): bool { + $warnings[] = $message; + + return true; + }); + + try { + $this->assertSame('value', $cache->getItem('key')->get()); + $adapter1->commit(); + } finally { + restore_error_handler(); + } + + $this->assertSame([], $warnings); + $this->assertTrue($adapter1->getItem('key')->isHit()); + } + + public function testDefaultLifetimeAppliesToTaggedItemsPropagatedToPreviousAdapters() + { + $adapter1 = new ArrayAdapter(2); + $adapter2 = new FilesystemAdapter('', 2); + + $cache = new TagAwareAdapter(new ChainAdapter([$adapter1, $adapter2], 2)); + + $cache->get('key', static function (ItemInterface $item) { + $item->tag('tag'); + + return 'value'; + }); + + $adapter1->clear(); + $this->assertTrue($cache->getItem('key')->isHit()); + $this->assertTrue($adapter1->hasItem('key')); + + sleep(3); + + $this->assertFalse($adapter2->getItem('key')->isHit(), 'Item should have expired in adapter2'); + $this->assertFalse($cache->getItem('key')->isHit(), 'Item should have expired in adapter1 after the default lifetime'); + } + public function testExpirationOnAllAdapters() { if (isset($this->skippedTests[__FUNCTION__])) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/MemcachedAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,6 +15,7 @@ use Symfony\Component\Cache\Adapter\AbstractAdapter; use Symfony\Component\Cache\Adapter\MemcachedAdapter; use Symfony\Component\Cache\Exception\CacheException; +use Symfony\Component\Cache\Exception\InvalidArgumentException; /** * @group integration @@ -196,6 +197,55 @@ $this->assertSame(8, $client->getOption(\Memcached::OPT_RETRY_TIMEOUT)); } + public function testBooleanOptionsFromDsn() + { + $client = MemcachedAdapter::createConnection('memcached://localhost:11222?compression=true&libketama_compatible=true&tcp_nodelay=on&binary_protocol=yes&connect_timeout=500'); + + $this->assertTrue($client->getOption(\Memcached::OPT_COMPRESSION)); + $this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); + $this->assertSame(1, $client->getOption(\Memcached::OPT_TCP_NODELAY)); + $this->assertSame(1, $client->getOption(\Memcached::OPT_BINARY_PROTOCOL)); + $this->assertSame(500, $client->getOption(\Memcached::OPT_CONNECT_TIMEOUT)); + + $client = MemcachedAdapter::createConnection('memcached://localhost:11222?compression=false&libketama_compatible=0&tcp_nodelay='); + + $this->assertFalse($client->getOption(\Memcached::OPT_COMPRESSION)); + $this->assertSame(0, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); + $this->assertSame(0, $client->getOption(\Memcached::OPT_TCP_NODELAY)); + } + + public function testConstantNameOptionsFromDsn() + { + $client = MemcachedAdapter::createConnection('memcached://localhost:11222?libketama_hash=md5&compression_type=zlib'); + + $this->assertSame(\Memcached::HASH_MD5, $client->getOption(\Memcached::OPT_LIBKETAMA_HASH)); + $this->assertSame(\Memcached::COMPRESSION_ZLIB, $client->getOption(\Memcached::OPT_COMPRESSION_TYPE)); + + $client = MemcachedAdapter::createConnection('memcached://localhost:11222?compression_type='.\Memcached::COMPRESSION_ZLIB); + + $this->assertSame(\Memcached::COMPRESSION_ZLIB, $client->getOption(\Memcached::OPT_COMPRESSION_TYPE)); + } + + public function testInvalidOptionsFromDsn() + { + $cases = [ + 'compression=ture' => 'Invalid Memcached DSN: parameter "compression" must be a boolean.', + 'libketama_compatible=2' => 'Invalid Memcached DSN: parameter "libketama_compatible" must be a boolean.', + 'connect_timeout=1s' => 'Invalid Memcached DSN: parameter "connect_timeout" must be an integer.', + 'retry_timeout=' => 'Invalid Memcached DSN: parameter "retry_timeout" must be an integer.', + 'compression_type=foo' => 'Invalid Memcached DSN: parameter "compression_type" must be an integer.', + ]; + + foreach ($cases as $query => $message) { + try { + MemcachedAdapter::createConnection('memcached://localhost:11222?'.$query); + $this->fail(\sprintf('"%s" should have been rejected.', $query)); + } catch (InvalidArgumentException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + } + public function testClear() { $this->assertTrue($this->createCachePool()->clear()); @@ -274,4 +324,34 @@ self::assertTrue($pool->deleteItem($key)); self::assertFalse($pool->hasItem($key)); } + + public function testLongKeyWithSlashInHashedId() + { + $pool = $this->createCachePool(); + $key = str_repeat('a', 300); + + self::assertTrue($pool->save($pool->getItem($key)->set('foobar'))); + + $item = $pool->getItems([$key])->current(); + self::assertTrue($item->isHit()); + self::assertSame('foobar', $item->get()); + } + + public function testLifetimeEndingAfter2038() + { + $client = $this->createStub(\Memcached::class); + $client->method('getOption')->willReturnMap([[\Memcached::OPT_SERIALIZER, \Memcached::SERIALIZER_PHP]]); + $client->method('getResultCode')->willReturn(\Memcached::RES_SUCCESS); + $client->method('getMulti')->willReturn([]); + $client->method('setMulti')->willReturnCallback(static function (array $items, int $expiration) use (&$expirations) { + $expirations[] = $expiration; + + return true; + }); + + $cache = new MemcachedAdapter($client); + $cache->save($cache->getItem('foo')->set('bar')->expiresAfter(100 * 365 * 86400)); + + $this->assertSame(2147483647, end($expirations)); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PhpArrayAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -60,6 +60,7 @@ 'testDefaultLifeTime' => 'PhpArrayAdapter does not allow configuring a default lifetime.', 'testPrune' => 'PhpArrayAdapter just proxies', 'testClearWithInvalidPrefix' => 'PhpArrayAdapter does not validate the prefix.', + 'testInvalidKeyWithoutAssertions' => 'PhpArrayAdapter does not throw exceptions on invalid key.', ]; protected static string $file; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/PredisAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -43,7 +43,7 @@ 'scheme' => 'tcp', 'host' => $redisHost[0], 'port' => (int) ($redisHost[1] ?? 6379), - 'persistent' => 0, + 'persistent' => false, 'timeout' => 3, 'read_write_timeout' => 0, 'tcp_nodelay' => true, @@ -104,7 +104,7 @@ 'host' => $redisHost[0], 'port' => (int) ($redisHost[1] ?? 6379), 'ssl' => ['verify_peer' => false], - 'persistent' => 0, + 'persistent' => false, 'timeout' => 3, 'read_write_timeout' => 0, 'tcp_nodelay' => true, diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/ProxyAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -28,6 +28,7 @@ 'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.', 'testPrune' => 'ProxyAdapter just proxies', 'testClearWithInvalidPrefix' => 'Inner ArrayAdapter does not validate the prefix.', + 'testInvalidKeyWithoutAssertions' => 'Inner ArrayAdapter checks keys only when assert() is enabled.', ]; public function createCachePool(int $defaultLifetime = 0, ?string $testMethod = null): CacheItemPoolInterface diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,7 +12,9 @@ namespace Symfony\Component\Cache\Tests\Adapter; use Psr\Cache\CacheItemPoolInterface; +use Symfony\Component\Cache\Adapter\RedisAdapter; use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter; +use Symfony\Component\Cache\Tests\Fixtures\StrictKeysRedis; use Symfony\Component\Cache\Traits\RedisProxy; /** @@ -39,4 +41,18 @@ return $adapter; } + + public function testInvalidateTagsOnlyAccessesDeclaredKeys() + { + $redis = RedisAdapter::createConnection('redis://'.getenv('REDIS_HOST'), ['class' => StrictKeysRedis::class]); + $redis->setOption(\Redis::OPT_PREFIX, 'strict_'); + $pool = new RedisTagAwareAdapter($redis, str_replace('\\', '.', __CLASS__)); + $pool->clear(); + + $item = $pool->getItem('foo'); + $pool->save($item->set('bar')->tag('tag')); + + $this->assertTrue($pool->invalidateTags(['tag'])); + $this->assertFalse($pool->getItem('foo')->isHit()); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareClusterAdapterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareClusterAdapterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareClusterAdapterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/RedisTagAwareClusterAdapterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\Cache\Tests\Adapter; use Psr\Cache\CacheItemPoolInterface; +use Symfony\Component\Cache\Adapter\RedisAdapter; use Symfony\Component\Cache\Adapter\RedisTagAwareAdapter; use Symfony\Component\Cache\Traits\RedisClusterProxy; @@ -39,4 +40,16 @@ return $adapter; } + + public function testInvalidateTagsWithHashTagInPrefix() + { + $redis = RedisAdapter::createConnection('redis:?host['.str_replace(' ', ']&host[', getenv('REDIS_CLUSTER_HOSTS')).']', ['redis_cluster' => true]); + $redis->setOption(\Redis::OPT_PREFIX, '{app}:'); + $pool = new RedisTagAwareAdapter($redis, str_replace('\\', '.', __CLASS__)); + + $pool->save($pool->getItem('foo')->set('bar')->tag('tag')); + + $this->assertTrue($pool->invalidateTags(['tag'])); + $this->assertFalse($pool->getItem('foo')->isHit()); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Adapter/TagAwareTestTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -166,6 +166,7 @@ $i = $pool->getItem('k'); $this->assertSame(['foo' => 'foo'], $i->getMetadata()[CacheItem::METADATA_TAGS]); + $this->assertArrayNotHasKey(CacheItem::METADATA_EXPIRY, $i->getMetadata()); } public function testRefreshAfterExpires() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Fixtures/StrictKeysRedis.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Fixtures/StrictKeysRedis.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Fixtures/StrictKeysRedis.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Fixtures/StrictKeysRedis.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Tests\Fixtures; + +/** + * Makes scripts fail when they access a key not passed in KEYS, like servers enforcing it (e.g. Dragonfly). + */ +class StrictKeysRedis extends \Redis +{ + private const PRELUDE = <<<'EOLUA' + local __redis = redis + local redis = setmetatable({ + call = function(command, key, ...) + for _, k in ipairs(KEYS) do + if k == key then + return __redis.call(command, key, ...) + end + end + error('script tried accessing undeclared key: '..tostring(key)) + end, + }, {__index = __redis}) + + EOLUA; + + public function eval($script, $args = [], $num_keys = 0): mixed + { + return parent::eval(self::PRELUDE.$script, $args, $num_keys); + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisProxiesTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisProxiesTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisProxiesTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisProxiesTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -121,4 +121,14 @@ $this->assertEquals($expectedProxy, $proxy); } + + /** + * @requires extension relay + */ + public function testCreateLazyRelayProxy() + { + $proxy = RelayProxy::createLazyProxy(static fn () => throw new \LogicException('The proxy should not be initialized.')); + + $this->assertFalse($proxy->isLazyObjectInitialized()); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Tests/Traits/RedisTraitTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -315,6 +315,68 @@ ]; } + public function testBooleanSslOptions() + { + $predisClass = $this->createPredisCaptureClass(); + + $mock = new class { + use RedisTrait; + }; + + $mock::createConnection('redis://localhost?ssl[verify_peer]=false&ssl[verify_peer_name]=&ssl[SNI_enabled]=1', ['class' => $predisClass]); + + $this->assertSame(['verify_peer' => false, 'verify_peer_name' => false, 'SNI_enabled' => true], $predisClass::$captured['parameters']['ssl']); + } + + public function testBooleanSslOptionsPerHost() + { + $predisClass = $this->createPredisCaptureClass(); + + $mock = new class { + use RedisTrait; + }; + + $mock::createConnection('rediss:?host[localhost][ssl][verify_peer]=false&host[localhost][ssl][verify_peer_name]=&host[localhost][ssl][SNI_enabled]=1', ['class' => $predisClass]); + + $this->assertSame(['verify_peer' => false, 'verify_peer_name' => false, 'SNI_enabled' => true], $predisClass::$captured['parameters']['ssl']); + } + + public function testBooleanPersistentParameter() + { + $predisClass = $this->createPredisCaptureClass(); + + $mock = new class { + use RedisTrait; + }; + + $mock::createConnection('redis://localhost?persistent=false', ['class' => $predisClass]); + $this->assertFalse($predisClass::$captured['options']['parameters']['persistent']); + + $mock::createConnection('redis://localhost?persistent=', ['class' => $predisClass]); + $this->assertFalse($predisClass::$captured['options']['parameters']['persistent']); + + $mock::createConnection('redis://localhost?persistent=1', ['class' => $predisClass]); + $this->assertTrue($predisClass::$captured['options']['parameters']['persistent']); + } + + public function testInvalidBooleanParameters() + { + $predisClass = $this->createPredisCaptureClass(); + + $mock = new class { + use RedisTrait; + }; + + foreach (['ssl[verify_peer]', 'ssl[verify_peer_name]', 'host[localhost][ssl][verify_peer]', 'lazy', 'persistent', 'redis_cluster'] as $parameter) { + try { + $mock::createConnection('redis://localhost?'.$parameter.'=ture', ['class' => $predisClass]); + $this->fail(\sprintf('"%s=ture" should have been rejected.', $parameter)); + } catch (InvalidArgumentException $e) { + $this->assertSame(\sprintf('Invalid Redis DSN: parameter "%s" must be a boolean.', $parameter), $e->getMessage()); + } + } + } + private function assertAuthMatchesExpected(string|array|null $expectedAuth, array $parameters): void { if (null === $expectedAuth) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/AbstractAdapterTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -347,7 +347,7 @@ if (\is_string($key) && isset($this->ids[$key])) { return $this->namespace.$this->namespaceVersion.$this->ids[$key]; } - \assert('' !== CacheItem::validateKey($key)); + CacheItem::validateKey($key); $this->ids[$key] = $key; if (\count($this->ids) > 1000) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/RedisClusterNodeProxy.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/RedisClusterNodeProxy.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/RedisClusterNodeProxy.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/RedisClusterNodeProxy.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,7 +16,7 @@ * individual \Redis objects. * * Calls are made to individual nodes via: RedisCluster->{method}($host, ...args)' - * according to https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#directed-node-commands + * according to https://github.com/phpredis/phpredis/blob/develop/cluster.md#directed-node-commands * * @author Jack Thomas * diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/RedisTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/RedisTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/RedisTrait.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/RedisTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -126,6 +126,16 @@ $tls = 'rediss' === $scheme; $tcpScheme = $tls ? 'tls' : 'tcp'; + $booleanStreamOptions = [ + 'allow_self_signed', + 'capture_peer_cert', + 'capture_peer_cert_chain', + 'disable_compression', + 'SNI_enabled', + 'verify_peer', + 'verify_peer_name', + ]; + if (isset($params['query'])) { parse_str($params['query'], $query); @@ -137,6 +147,11 @@ if (\is_string($parameters)) { parse_str($parameters, $parameters); } + foreach ($parameters['ssl'] ?? [] as $streamOption => $value) { + if (\in_array($streamOption, $booleanStreamOptions, true) && \is_string($value)) { + $parameters['ssl'][$streamOption] = filter_var($value, \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Invalid Redis DSN: parameter "host[%s][ssl][%s]" must be a boolean.', $host, $streamOption)); + } + } if (false === $i = strrpos($host, ':')) { $hosts[$host] = ['scheme' => $tcpScheme, 'host' => $host, 'port' => 6379] + $parameters; } elseif ($port = (int) substr($host, 1 + $i)) { @@ -176,19 +191,9 @@ $params += $query + $options + self::$defaultConnectionOptions; - $booleanStreamOptions = [ - 'allow_self_signed', - 'capture_peer_cert', - 'capture_peer_cert_chain', - 'disable_compression', - 'SNI_enabled', - 'verify_peer', - 'verify_peer_name', - ]; - foreach ($params['ssl'] ?? [] as $streamOption => $value) { if (\in_array($streamOption, $booleanStreamOptions, true) && \is_string($value)) { - $params['ssl'][$streamOption] = filter_var($value, \FILTER_VALIDATE_BOOL); + $params['ssl'][$streamOption] = filter_var($value, \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Invalid Redis DSN: parameter "ssl[%s]" must be a boolean.', $streamOption)); } } @@ -209,9 +214,10 @@ } if (isset($params['lazy'])) { - $params['lazy'] = filter_var($params['lazy'], \FILTER_VALIDATE_BOOLEAN); + $params['lazy'] = filter_var($params['lazy'], \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Invalid Redis DSN: parameter "lazy" must be a boolean.'); } - $params['redis_cluster'] = filter_var($params['redis_cluster'], \FILTER_VALIDATE_BOOLEAN); + $params['persistent'] = filter_var($params['persistent'], \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Invalid Redis DSN: parameter "persistent" must be a boolean.'); + $params['redis_cluster'] = filter_var($params['redis_cluster'], \FILTER_VALIDATE_BOOLEAN, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Invalid Redis DSN: parameter "redis_cluster" must be a boolean.'); if ($params['redis_cluster'] && isset($params['redis_sentinel'])) { throw new InvalidArgumentException('Cannot use both "redis_cluster" and "redis_sentinel" at the same time.'); @@ -640,8 +646,8 @@ if ($redis instanceof \RedisCluster || ($redis instanceof \Predis\ClientInterface && ($redis->getConnection() instanceof RedisCluster || $redis->getConnection() instanceof Predis2RedisCluster))) { // phpredis & predis don't support pipelining with RedisCluster - // see https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#pipelining - // see https://github.com/nrk/predis/issues/267#issuecomment-123781423 + // see https://github.com/phpredis/phpredis/blob/develop/cluster.md#pipelining + // see https://github.com/predis/predis/issues/267#issuecomment-123781423 $results = []; foreach ($generator() as $command => $args) { $results[] = $redis->{$command}(...$args); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/Relay/Relay62Trait.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/Relay/Relay62Trait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/Relay/Relay62Trait.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/Relay/Relay62Trait.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,102 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Cache\Traits\Relay; + +if (version_compare(phpversion('relay'), '0.62.0', '>=')) { + /** + * @internal + */ + trait Relay62Trait + { + public function bitrangeintarray($key, $start, $end, $options = null): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->bitrangeintarray(...\func_get_args()); + } + + public function bless($command, $key = null, $directive = null, $options = null): mixed + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->bless(...\func_get_args()); + } + + public function bzmove($source, $destination, $timeout, $options = null): \Relay\Relay|array|false|null + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->bzmove(...\func_get_args()); + } + + public function saddex($key, $members, $options = null): \Relay\Relay|false|int + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->saddex(...\func_get_args()); + } + + public function sexpire($key, $expiry, $members, $exptype = null): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->sexpire(...\func_get_args()); + } + + public function sexpireat($key, $expiry, $members, $exptype = null): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->sexpireat(...\func_get_args()); + } + + public function sexpiretime($key, $members): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->sexpiretime(...\func_get_args()); + } + + public function spersist($key, $members): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->spersist(...\func_get_args()); + } + + public function spexpire($key, $expiry, $members, $exptype = null): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->spexpire(...\func_get_args()); + } + + public function spexpireat($key, $expiry, $members, $exptype = null): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->spexpireat(...\func_get_args()); + } + + public function spexpiretime($key, $members): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->spexpiretime(...\func_get_args()); + } + + public function spttl($key, $members): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->spttl(...\func_get_args()); + } + + public function sttl($key, $members): \Relay\Relay|array|false + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->sttl(...\func_get_args()); + } + + public function zmove($source, $destination, $options = null): \Relay\Relay|array|false|null + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->zmove(...\func_get_args()); + } + + public function zmovemember($source, $destination, $members, $options = null): \Relay\Relay|array|false|null + { + return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->zmovemember(...\func_get_args()); + } + } +} else { + /** + * @internal + */ + trait Relay62Trait + { + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/RelayProxy.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/RelayProxy.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/RelayProxy.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/RelayProxy.php 2026-11-25 09:18:34.000000000 +0000 @@ -33,7 +33,9 @@ use Symfony\Component\Cache\Traits\Relay\Relay50Trait; use Symfony\Component\Cache\Traits\Relay\Relay502Trait; use Symfony\Component\Cache\Traits\Relay\Relay61Trait; +use Symfony\Component\Cache\Traits\Relay\Relay62Trait; use Symfony\Component\Cache\Traits\Relay\SwapdbTrait; +use Symfony\Component\VarExporter\Internal\LazyObjectState; use Symfony\Component\VarExporter\LazyObjectInterface; use Symfony\Component\VarExporter\LazyProxyTrait; use Symfony\Contracts\Service\ResetInterface; @@ -74,10 +76,19 @@ use Relay50Trait; use Relay502Trait; use Relay61Trait; + use Relay62Trait; use SwapdbTrait; private const LAZY_OBJECT_PROPERTY_SCOPES = []; + public static function createLazyProxy(\Closure $initializer, ?self $instance = null): static + { + $instance ??= (new \ReflectionClass(static::class))->newInstanceWithoutConstructor(); + $instance->lazyObjectState = new LazyObjectState($initializer); + + return $instance; + } + public function close(): bool { return ($this->lazyObjectState->realInstance ??= ($this->lazyObjectState->initializer)())->close(...\func_get_args()); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/ValueWrapper.php symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/ValueWrapper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Cache/Traits/ValueWrapper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Cache/Traits/ValueWrapper.php 2026-11-25 09:18:34.000000000 +0000 @@ -66,7 +66,13 @@ } $metadata = unpack('Vexpiry/nctime', $pack); - $metadata['expiry'] += self::EXPIRY_OFFSET; + + if (self::INT32_MAX === $metadata['expiry']) { + // the item has no expiry, see __serialize() + unset($metadata['expiry']); + } else { + $metadata['expiry'] += self::EXPIRY_OFFSET; + } if (!$metadata['ctime'] = ((0x4000 | $metadata['ctime']) << 16 >> (0x1F & $metadata['ctime'])) - 1) { unset($metadata['ctime']); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Definition/BaseNode.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Definition/BaseNode.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Definition/BaseNode.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Definition/BaseNode.php 2026-11-25 09:18:34.000000000 +0000 @@ -316,7 +316,7 @@ throw new ForbiddenOverwriteException(\sprintf('Configuration path "%s" cannot be overwritten. You have to define all options for this path, and any of its sub-paths in one configuration section.', $this->getPath())); } - if ($leftSide !== $leftPlaceholders = self::resolvePlaceholderValue($leftSide)) { + if (\is_string($leftSide) && $leftSide !== $leftPlaceholders = self::resolvePlaceholderValue($leftSide)) { foreach ($leftPlaceholders as $leftPlaceholder) { $this->handlingPlaceholder = $leftSide; try { @@ -329,7 +329,7 @@ return $rightSide; } - if ($rightSide !== $rightPlaceholders = self::resolvePlaceholderValue($rightSide)) { + if (\is_string($rightSide) && $rightSide !== $rightPlaceholders = self::resolvePlaceholderValue($rightSide)) { foreach ($rightPlaceholders as $rightPlaceholder) { $this->handlingPlaceholder = $rightSide; try { @@ -358,7 +358,7 @@ } // resolve placeholder value - if ($value !== $placeholders = self::resolvePlaceholderValue($value)) { + if (\is_string($value) && $value !== $placeholders = self::resolvePlaceholderValue($value)) { foreach ($placeholders as $placeholder) { $this->handlingPlaceholder = $value; try { @@ -403,7 +403,7 @@ final public function finalize(mixed $value): mixed { - if ($value !== $placeholders = self::resolvePlaceholderValue($value)) { + if (\is_string($value) && $value !== $placeholders = self::resolvePlaceholderValue($value)) { foreach ($placeholders as $placeholder) { $this->handlingPlaceholder = $value; try { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Definition/EnumNode.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Definition/EnumNode.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Definition/EnumNode.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Definition/EnumNode.php 2026-11-25 09:18:34.000000000 +0000 @@ -61,7 +61,7 @@ { return implode($separator, array_unique(array_map(static function (mixed $value): string { if (!$value instanceof \UnitEnum) { - return json_encode($value); + return self::formatValue($value); } return ltrim(var_export($value, true), '\\'); @@ -85,7 +85,7 @@ $value = parent::finalizeValue($value); if (!\in_array($value, $this->values, true)) { - $ex = new InvalidConfigurationException(\sprintf('The value %s is not allowed for path "%s". Permissible values: %s', json_encode($value), $this->getPath(), $this->getPermissibleValues(', '))); + $ex = new InvalidConfigurationException(\sprintf('The value %s is not allowed for path "%s". Permissible values: %s', self::formatValue($value), $this->getPath(), $this->getPermissibleValues(', '))); $ex->setPath($this->getPath()); throw $ex; @@ -93,4 +93,10 @@ return $value; } + + private static function formatValue(mixed $value): string + { + // json_encode() fails on INF, NAN and enums without a backing value + return json_encode($value) ?: ltrim(var_export($value, true), '\\'); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Definition/NumericNode.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Definition/NumericNode.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Definition/NumericNode.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Definition/NumericNode.php 2026-11-25 09:18:34.000000000 +0000 @@ -39,6 +39,9 @@ } $errorMsg = null; + if ((isset($this->min) || isset($this->max)) && \is_float($value) && is_nan($value)) { + $errorMsg = \sprintf('The value NAN is not allowed for path "%s". Should be a number', $this->getPath()); + } if (isset($this->min) && $value < $this->min) { $errorMsg = \sprintf('The value %s is too small for path "%s". Should be greater than or equal to %s', $value, $this->getPath(), $this->min); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Resource/DirectoryResource.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Resource/DirectoryResource.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Resource/DirectoryResource.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Resource/DirectoryResource.php 2026-11-25 09:18:34.000000000 +0000 @@ -66,18 +66,13 @@ return false; } - foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->resource), \RecursiveIteratorIterator::SELF_FIRST) as $file) { + // SELF_FIRST yields directories too, so deleted files are detected through their parent's mtime. + foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->resource, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $file) { // if regex filtering is enabled only check matching files if ($this->pattern && $file->isFile() && !preg_match($this->pattern, $file->getBasename())) { continue; } - // always monitor directories for changes, except the .. entries - // (otherwise deleted files wouldn't get detected) - if ($file->isDir() && str_ends_with($file, '/..')) { - continue; - } - // for broken links try { $fileMTime = $file->getMTime(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Resource/GlobResource.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Resource/GlobResource.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Resource/GlobResource.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Resource/GlobResource.php 2026-11-25 09:18:34.000000000 +0000 @@ -66,7 +66,7 @@ public function __toString(): string { - return 'glob.'.$this->prefix.(int) $this->recursive.$this->pattern.(int) $this->forExclusion.implode("\0", $this->excludedPrefixes); + return 'glob.'.$this->prefix.(int) $this->recursive.$this->pattern.(int) $this->forExclusion.implode("\0", array_keys($this->excludedPrefixes)); } public function isFresh(int $timestamp): bool diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Definition/EnumNodeTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -77,6 +77,26 @@ $node->finalize('custom'); } + public function testFinalizeWithNonFiniteFloats() + { + $node = new EnumNode('foo', null, [1.5, \INF, -\INF]); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('The value NAN is not allowed for path "foo". Permissible values: 1.5, INF, -INF'); + + $node->finalize(\NAN); + } + + public function testFinalizeWithEnumCaseOfAnotherEnum() + { + $node = new EnumNode('foo', null, ['foo', TestEnum::Foo]); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('The value Symfony\Component\Config\Tests\Fixtures\TestEnum2::Foo is not allowed for path "foo". Permissible values: "foo", Symfony\Component\Config\Tests\Fixtures\TestEnum::Foo'); + + $node->finalize(TestEnum2::Foo); + } + public function testSameStringCoercedValuesAreDifferent() { $node = new EnumNode('ccc', null, ['', false, null]); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Definition/FloatNodeTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\Config\Tests\Definition; use PHPUnit\Framework\TestCase; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; use Symfony\Component\Config\Definition\Exception\InvalidTypeException; use Symfony\Component\Config\Definition\FloatNode; use Symfony\Component\Config\Definition\NumericNode; @@ -78,6 +79,43 @@ ]; } + public function testNanIsNotTreatedAsPlaceholder() + { + $node = new FloatNode('test'); + $node->setFinalValidationClosures([static function (float $value): float { + throw new InvalidConfigurationException(is_nan($value) ? 'NAN reached the validation closure.' : 'Unexpected value.'); + }]); + + $this->assertNan($node->normalize(\NAN)); + $this->assertSame(1.5, $node->merge(\NAN, 1.5)); + $this->assertNan($node->merge(1.5, \NAN)); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('NAN reached the validation closure.'); + + $node->finalize(\NAN); + } + + public function testFinalizeRejectsNanWithMin() + { + $node = new FloatNode('ratio', null, 0); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('The value NAN is not allowed for path "ratio". Should be a number'); + + $node->finalize(\NAN); + } + + public function testFinalizeRejectsNanWithMax() + { + $node = new FloatNode('ratio', null, null, 1); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('The value NAN is not allowed for path "ratio". Should be a number'); + + $node->finalize(\NAN); + } + public function testFinalizeAcceptsEnvPlaceholderBelowMin() { $node = new FloatNode('multiplier', null, 1); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -122,6 +122,17 @@ $this->assertFalse($resource->isFresh(time()), '->isFresh() returns false if the whole resource is removed'); } + public function testIsFreshIgnoresTheParentDirectory() + { + $subdirectory = $this->directory.'/subdirectory'; + mkdir($subdirectory); + touch($subdirectory.'/file.xml'); + touch($this->directory, time() + 20); + + $resource = new DirectoryResource($subdirectory); + $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if only the parent directory is modified'); + } + public function testIsFreshCreateFileInSubdirectory() { $subdirectory = $this->directory.'/subdirectory'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Config/Tests/Resource/GlobResourceTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -97,6 +97,15 @@ $this->assertArrayNotHasKey($file, $paths); } + public function testToStringDependsOnExcludedPrefixes() + { + $dir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; + $resource = new GlobResource($dir, '/*Exclude*', true, false, [$dir.'/Exclude' => true]); + $otherResource = new GlobResource($dir, '/*Exclude*', true, false, [$dir.'/Resource' => true]); + + $this->assertNotSame((string) $resource, (string) $otherResource); + } + public function testIsFreshNonRecursiveDetectsNewFile() { $dir = \dirname(__DIR__).'/Fixtures'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Application.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Application.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Application.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Application.php 2026-11-25 09:18:34.000000000 +0000 @@ -791,9 +791,9 @@ return false; } - $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription(); + $abbrev = $cmd.str_repeat(' ', $maxLen - Helper::width($cmd)).' '.$commandList[$cmd]->getDescription(); - return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev; + return Helper::width($abbrev) > $usableWidth ? Helper::substrToWidth($abbrev, $usableWidth - 3).'...' : $abbrev; }, array_values($commands)); if (\count($commands) > 1) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Formatter/OutputFormatter.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Formatter/OutputFormatter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Formatter/OutputFormatter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Formatter/OutputFormatter.php 2026-11-25 09:18:34.000000000 +0000 @@ -139,19 +139,15 @@ $offset = 0; $output = ''; - $openTagRegex = '[a-z](?:[^\\\\<>]*+ | \\\\.)*'; + $openTagRegex = '[a-z](?:[^\\\\<>]++ | \\\\.)*+'; $closeTagRegex = '[a-z][^<>]*+'; $currentLineLength = 0; $lineBreak = false; - preg_match_all("#<(($openTagRegex) | /($closeTagRegex)?)>#ix", $message, $matches, \PREG_OFFSET_CAPTURE); + preg_match_all("#(?#ix", $message, $matches, \PREG_OFFSET_CAPTURE); foreach ($matches[0] as $i => $match) { $pos = $match[1]; $text = $match[0]; - if (0 != $pos && '\\' == $message[$pos - 1]) { - continue; - } - // tags are delimited by "<" and ">", which are ASCII, so a tag offset can never // fall inside a multibyte sequence: slicing by bytes is safe here $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset), $width, $currentLineLength, $lineBreak); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/FormatterHelper.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/FormatterHelper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/FormatterHelper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/FormatterHelper.php 2026-11-25 09:18:34.000000000 +0000 @@ -71,7 +71,7 @@ return $message; } - return self::substr($message, 0, $length).$suffix; + return self::substrToWidth($message, $length).$suffix; } public function getName(): string diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/Helper.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/Helper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/Helper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/Helper.php 2026-11-25 09:18:34.000000000 +0000 @@ -98,6 +98,34 @@ } /** + * Returns the beginning of a string that fits in the given number of columns. + * + * @internal + */ + public static function substrToWidth(?string $string, int $width): string + { + $substring = self::substr($string, 0, $width); + + if ($width <= 0 || self::width($substring) <= $width) { + return $substring; + } + + // the width grows with the length: search the longest beginning that fits + $min = 0; + $max = $width - 1; + while ($min < $max) { + $length = ($min + $max + 1) >> 1; + if (self::width(self::substr($string, 0, $length)) <= $width) { + $min = $length; + } else { + $max = $length - 1; + } + } + + return self::substr($string, 0, $min); + } + + /** * @return string */ public static function formatTime(int|float $secs, int $precision = 1) diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/OutputWrapper.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/OutputWrapper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/OutputWrapper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/OutputWrapper.php 2026-11-25 09:18:34.000000000 +0000 @@ -44,9 +44,10 @@ */ final class OutputWrapper { - private const TAG_OPEN_REGEX_SEGMENT = '[a-z](?:[^\\\\<>]*+ | \\\\.)*'; + private const TAG_OPEN_REGEX_SEGMENT = '[a-z](?:[^\\\\<>]++ | \\\\.)*+'; private const TAG_CLOSE_REGEX_SEGMENT = '[a-z][^<>]*+'; private const URL_PATTERN = 'https?://\S+'; + private const WIDE_CHAR_FILLER = "\u{FDD0}"; public function __construct( private bool $allowCutUrls = false, @@ -59,23 +60,56 @@ return $text; } - $tagPattern = \sprintf('<(?:(?:%s)|/(?:%s)?)>', self::TAG_OPEN_REGEX_SEGMENT, self::TAG_CLOSE_REGEX_SEGMENT); - $limitPattern = "{1,$width}"; - $patternBlocks = [$tagPattern]; - if (!$this->allowCutUrls) { - $patternBlocks[] = self::URL_PATTERN; - } - $patternBlocks[] = '.'; - $blocks = implode('|', $patternBlocks); - $rowPattern = "(?:$blocks)$limitPattern"; // the u modifier counts characters instead of bytes, but preg_replace() returns null // on malformed UTF-8, which would empty the text $modifiers = preg_match('//u', $text) ? 'imux' : 'imx'; - // a line cut inside a word never ends between a backslash and the "<" or ">" it escapes, - // or the escaped character would start the next line as a tag delimiter - $pattern = \sprintf('#(?:((?>(%1$s)((?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|(%1$s)(?!(?<=\\\\)[<>]))(?:\r?\n)?|(?:\r?\n|$))#%2$s', $rowPattern, $modifiers); + // a wide character uses two columns: a filler that follows it makes the pattern count both of them, and a line can't end between the two + $wideChars = []; + if ('imux' === $modifiers && !str_contains($text, self::WIDE_CHAR_FILLER) && preg_match_all('/[^\x00-\x{10FF}]/u', $text, $chars)) { + foreach (array_unique($chars[0]) as $char) { + if (2 === Helper::width($char)) { + $wideChars[$char] = $char.self::WIDE_CHAR_FILLER; + } + } + } + if ($wideChars) { + $text = strtr($text, $wideChars); + } + + // an escaped "<" never starts a tag, as in OutputFormatter + $tagPattern = \sprintf('(?', self::TAG_OPEN_REGEX_SEGMENT, self::TAG_CLOSE_REGEX_SEGMENT); + $hasTags = str_contains($text, '<') && preg_match("#<$tagPattern#$modifiers", $text); + $hasEscapes = str_contains($text, '\\<') || str_contains($text, '\\>'); + $hasUrls = !$this->allowCutUrls && preg_match('#'.self::URL_PATTERN.'#i', $text); + // PCRE compiles a bounded repetition of a group by copying the group, so tags, escapes and URLs are subroutine calls that keep each copy small + // with them, the pattern still gets too large at about 1000 columns, and 65535 is the highest value a quantifier accepts + $width = min($width, $hasTags || $hasEscapes || $hasUrls ? 900 : 65535); + // an escaped "<" or ">" prints one character, so the backslash and the escaped character take one column together + // a line never ends between the two, or the next line would start with a tag delimiter + $char = $hasEscapes ? '(?&char)' : '.'; + $charPattern = $hasUrls ? "(?!(?&url))$char" : $char; + if ($hasTags) { + // tags print nothing, so they take no column and stay with the characters next to them + $tag = '(?:<(?&tag))'; + $rowPattern = "(?:(?:$tag*+$char){1,$width}$tag*+|$tag++)"; + $cutPattern = "(?:(?:$tag*+$charPattern){1,$width}|$tag++)"; + $wordStartPattern = "$tag*+[^\\s<]{0,$width}?$tag*+"; + } else { + $rowPattern = "$char{1,$width}"; + $cutPattern = $hasUrls ? "(?:$charPattern){1,$width}" : $rowPattern; + $wordStartPattern = "[^\\s<]{0,$width}?"; + } + // URLs are never cut. A URL longer than the width gets a line of its own, together with the start of its word when that fits + $urlPattern = $hasUrls ? "|$wordStartPattern(?&url)[^\\S\\r\\n]?" : ''; + if ($wideChars) { + $rowPattern .= '(?!'.self::WIDE_CHAR_FILLER.')'; + $cutPattern .= '(?!'.self::WIDE_CHAR_FILLER.')'; + } + $pattern = \sprintf('#(?:((?>(%1$s)((?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))%3$s|(%2$s))(?:\r?\n)?|(?:\r?\n|$))(?(DEFINE)(?%5$s)(?%6$s)(?(?>\\\\[<>]|.)))#%4$s', $rowPattern, $cutPattern, $urlPattern, $modifiers, $tagPattern, self::URL_PATTERN); $output = rtrim(preg_replace($pattern, '\\1'.$break, $text), $break); - return str_replace(' '.$break, $break, $output); + $output = str_replace(' '.$break, $break, $output); + + return $wideChars ? str_replace(self::WIDE_CHAR_FILLER, '', $output) : $output; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/Table.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/Table.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Helper/Table.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Helper/Table.php 2026-11-25 09:18:34.000000000 +0000 @@ -580,9 +580,9 @@ $titleLength = Helper::width(Helper::removeDecoration($formatter = $this->output->getFormatter(), $formattedTitle = \sprintf($titleFormat, $title))); $markupLength = Helper::width($markup); if ($titleLength > $limit = $markupLength - 4) { - $titleLength = $limit; $formatLength = Helper::width(Helper::removeDecoration($formatter, \sprintf($titleFormat, ''))); - $formattedTitle = \sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...'); + $formattedTitle = \sprintf($titleFormat, Helper::substrToWidth($title, $limit - $formatLength - 3).'...'); + $titleLength = Helper::width(Helper::removeDecoration($formatter, $formattedTitle)); } $titleStart = intdiv($markupLength - $titleLength, 2); @@ -891,13 +891,9 @@ $openTags = [[]]; foreach ($lines as $i => $line) { $tags = $openTags[$i]; - preg_match_all('#<(?:[a-z](?:[^\\\\<>]*+|\\\\.)*|/(?:[a-z][^<>]*+)?)>#i', $line, $matches, \PREG_OFFSET_CAPTURE); - - foreach ($matches[0] as [$tag, $offset]) { - if ($offset && '\\' === $line[$offset - 1]) { - continue; - } + preg_match_all('#(?]++|\\\\.)*+|/(?:[a-z][^<>]*+)?)>#i', $line, $matches); + foreach ($matches[0] as $tag) { if ('' !== $tag) { // the formatter pushes the style of a style tag, and prints any other tag as is $name = ltrim(substr($tag, 1), '/'); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/ApplicationTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/ApplicationTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/ApplicationTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/ApplicationTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -480,6 +480,20 @@ ]; } + public function testFindWithAmbiguousAbbreviationsAlignsAndTruncatesByColumns() + { + putenv('COLUMNS=40'); + $this->expectException(CommandNotFoundException::class); + $this->expectExceptionMessage("Command \"foo:\" is ambiguous.\nDid you mean one of these?\n foo:bar 日本語日本語日本語...\n foo:é c\n foo:日本 b"); + + $application = new Application(); + $application->add((new Command('foo:bar'))->setDescription(str_repeat('日本語', 10))); + $application->add((new Command('foo:é'))->setDescription('c')); + $application->add((new Command('foo:日本'))->setDescription('b')); + + $application->find('foo:'); + } + public function testFindWithAmbiguousAbbreviationsFindsCommandIfAlternativesAreHidden() { $application = new Application(); @@ -1635,7 +1649,6 @@ $this->expectExceptionMessage('error'); $tester->run(['command' => 'dym']); - $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP error did not dispatch events'); } public function testRunDispatchesAllEventsWithError() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -244,6 +244,15 @@ $this->assertEquals("\033[37;41msome error\033[39;49m".$long, $formatter->format('some error'.$long)); } + public function testFormatLongRunsOfEscapedTagDelimiters() + { + $formatter = new OutputFormatter(true); + + $text = str_repeat('array ', 10000); + $this->assertSame($text."\033[32mfoo\033[39m", $formatter->format(OutputFormatter::escape($text).'foo')); + $this->assertSame('', 10000)."\033[32mfoo\033[39m", $formatter->format('', 10000).'foo')); + } + public function testFormatToStringObject() { $formatter = new OutputFormatter(false); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -100,6 +100,8 @@ $this->assertSame('testing truncat...', $formatter->truncate($message, 15)); $this->assertSame('testing truncate...', $formatter->truncate($message, 16)); $this->assertSame('zażółć gęślą...', $formatter->truncate('zażółć gęślą jaźń', 12)); + $this->assertSame('日本...', $formatter->truncate('日本語テキスト', 4)); + $this->assertSame('日本...', $formatter->truncate('日本語テキスト', 5)); } public function testTruncatingMessageWithCustomSuffix() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Helper/OutputWrapperTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Helper/OutputWrapperTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Helper/OutputWrapperTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Helper/OutputWrapperTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\Console\Tests\Helper; use PHPUnit\Framework\TestCase; +use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Helper\OutputWrapper; class OutputWrapperTest extends TestCase @@ -32,7 +33,7 @@ $this->assertSame("Lorem\n\xB3\nipsum", $wrapper->wrap("Lorem \xB3 ipsum", 5)); $this->assertSame("Lorem\n\xF0\x9F", $wrapper->wrap("Lorem \xF0\x9F", 5)); - $this->assertSame("Lore\nm \xB3\nhttps://example.com/\nipsum ", $wrapper->wrap("Lorem \xB3 https://example.com/\nipsum \n", 5)); + $this->assertSame("Lorem\n\xB3\nhttps://example.com/\nipsum ", $wrapper->wrap("Lorem \xB3 https://example.com/\nipsum \n", 5)); } public function testWrapBreaksMalformedUtf8LikeValidText() @@ -42,14 +43,89 @@ $this->assertSame($wrapper->wrap('Lorem X ipsum', 5), str_replace("\xB3", 'X', $wrapper->wrap("Lorem \xB3 ipsum", 5))); } + public function testWrapCountsWideCharactersAsTwoColumns() + { + $wrapper = new OutputWrapper(); + + $this->assertSame("日本語\nテキス\nト", $wrapper->wrap('日本語テキスト', 6)); + $this->assertSame("日本\n語テ\nキス\nト", $wrapper->wrap('日本語テキスト', 5)); + $this->assertSame("日\n本", $wrapper->wrap('日本', 1)); + $this->assertSame("abc\n日本語\ndef", $wrapper->wrap('abc 日本語 def', 6)); + $this->assertSame("a日本\nb", $wrapper->wrap('a日本b', 5)); + $this->assertSame("日本\n語", $wrapper->wrap('日本語', 5)); + $this->assertSame("日本\nhttps://日本語.example.com/", $wrapper->wrap('日本 https://日本語.example.com/', 5)); + } + + public function testWrapKeepsNoncharactersOfTheText() + { + $wrapper = new OutputWrapper(); + + $this->assertSame("aaaa\n\u{FDD0}bbb\nb", $wrapper->wrap("aaaa\u{FDD0}bbbb", 4)); + $this->assertSame("\u{FDD0}日本", $wrapper->wrap("\u{FDD0}日本", 5)); + } + public function testWrapKeepsEscapedTagDelimitersWithTheirBackslash() { $wrapper = new OutputWrapper(); - $this->assertSame("aaaa\n\\wrap('aaaa\assertSame("aaaa\n\\>b", $wrapper->wrap('aaaa\>b', 5)); - $this->assertSame("aaa\\<\nb", $wrapper->wrap('aaa\assertSame("aaaa\n\\c", $wrapper->wrap('aaaa\c', 5)); + $this->assertSame("aaaa\\<\nb", $wrapper->wrap('aaaa\assertSame("aaaa\\>\nb", $wrapper->wrap('aaaa\>b', 5)); + $this->assertSame('aaa\wrap('aaa\assertSame("aaaa\\<\n/b\\>c", $wrapper->wrap('aaaa\c', 5)); + } + + public function testWrapCountsEscapedTagsAsText() + { + $wrapper = new OutputWrapper(); + + $this->assertSame("Expected\narray\\\nhere", $wrapper->wrap('Expected array\ here', 12)); + $this->assertSame("Unexpected\n\\ tag", $wrapper->wrap('Unexpected \ tag', 12)); + $this->assertSame("aaaa\n\\c d", $wrapper->wrap('aaaa \c d', 8)); + + $text = OutputFormatter::escape(str_repeat('array ', 10000)); + $this->assertSame($text, str_replace("\n", ' ', $wrapper->wrap($text, 120))); + + $text = 'foo ', 10000); + $this->assertSame($text, str_replace("\n", ' ', $wrapper->wrap($text, 120))); + } + + public function testWrapCountsEscapedTagDelimitersAsOneColumn() + { + $wrapper = new OutputWrapper(); + + $this->assertSame("Expected array\\\nhere", $wrapper->wrap('Expected array\ here', 19)); + $this->assertSame("\\\\\n\\", $wrapper->wrap('\\\', 6)); + $this->assertSame("a\\\\wrap('a\\\assertSame("a\\\nc", $wrapper->wrap('a\ c', 3)); + $this->assertSame("日本\\<\nb", $wrapper->wrap('日本\assertSame("\xB3\\<\nb", $wrapper->wrap("\xB3\\assertSame('Expected array\ here', $wrapper->wrap('Expected array\ here', 5000)); + } + + public function testWrapDoesNotCountTagsInTheWidth() + { + $wrapper = new OutputWrapper(); + + $this->assertSame('aaaa bbbb cccc', $wrapper->wrap('aaaa bbbb cccc', 14)); + $this->assertSame("aaaa bbbb\ncccc", $wrapper->wrap('aaaa bbbb cccc', 9)); + $this->assertSame("aaaa\nbbbb", $wrapper->wrap('aaaa bbbb', 4)); + $this->assertSame("aaaa\n\n", $wrapper->wrap("aaaa\n\n", 4)); + $this->assertSame("\\<\nb\n>\nc", $wrapper->wrap('\c', 1)); + $this->assertSame("abcdefghij\nklmnopqrst\nuvwxyz end", $wrapper->wrap('abcdefghijklmnopqrstuvwxyz end', 10)); + } + + public function testWrapCountsUrlsWithTheirWidthWithoutCuttingThem() + { + $wrapper = new OutputWrapper(); + + $this->assertSame("aaaa\nhttp://a.b", $wrapper->wrap('aaaa http://a.b', 12)); + $this->assertSame("See\nhttps://symfony.com/doc/current/console.html\nfor more", $wrapper->wrap('See https://symfony.com/doc/current/console.html for more', 10)); + $this->assertSame("See\nhttps://symfony.com/doc\nfor more", $wrapper->wrap('See https://symfony.com/doc for more', 10)); + $this->assertSame("See\n(https://symfony.com/doc/current/console.html)\nfor more", $wrapper->wrap('See (https://symfony.com/doc/current/console.html) for more', 10)); + $this->assertSame("aaaaaaaaaa\naaahttps://symfony.com/doc", $wrapper->wrap('aaaaaaaaaaaaahttps://symfony.com/doc', 10)); + $this->assertSame('aaahttps://symfony.com/doc', $wrapper->wrap('aaahttps://symfony.com/doc', 5)); + $this->assertSame("ab\nhttps://symfony.com/doc", $wrapper->wrap('abhttps://symfony.com/doc', 5)); + $this->assertSame("See\nhttps://symfony.com/doc\n\nfor more", $wrapper->wrap("See https://symfony.com/doc\n\nfor more", 10)); } public function testWrapDoesNotDropBytesOfMalformedUtf8() @@ -72,8 +148,10 @@ false, <<<'EOS' Árvíztűrőtükörfúrógé - p https://github.com/symfony/symfony Lorem ipsum - dolor sit amet, + p + https://github.com/symfony/symfony + Lorem ipsum dolor + sit amet, consectetur adipiscing elit. Praesent vestibulum @@ -105,5 +183,32 @@ ornare efficitur. EOS, ]; + + yield 'Width above the PCRE compiled-size limit' => [ + $baseTextWithUtf8AndUrl, + 150, + false, + <<<'EOS' + Árvíztűrőtükörfúrógép https://github.com/symfony/symfony Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vestibulum nulla quis urna + maximus porttitor. Donec ullamcorper risus at libero ornare efficitur. + EOS, + ]; + + yield 'Width above the quantifier limit' => [ + $baseTextWithUtf8AndUrl, + 100000, + false, + $baseTextWithUtf8AndUrl, + ]; + + yield 'Width above the PCRE compiled-size limit with URL cut' => [ + $baseTextWithUtf8AndUrl, + 150, + true, + <<<'EOS' + Árvíztűrőtükörfúrógép https://github.com/symfony/symfony Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vestibulum nulla quis urna + maximus porttitor. Donec ullamcorper risus at libero ornare efficitur. + EOS, + ]; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Helper/TableTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Helper/TableTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Helper/TableTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Helper/TableTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -1937,6 +1937,22 @@ TABLE, ], + 'long titles with wide characters' => [ + str_repeat('日本語', 20), + 'a'.str_repeat('日本語', 20), + 'default', + <<<'TABLE' + +- 日本語日本語日本語日本語日本語日本語日本語日本語日本語... -+ + | ISBN | Title | Author | + +---------------+--------------------------+------------------+ + | 99921-58-10-7 | Divine Comedy | Dante Alighieri | + | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | + | 960-425-059-0 | The Lord of the Rings | J. R. R. Tolkien | + | 80-902734-1-6 | And Then There Were None | Agatha Christie | + +- a日本語日本語日本語日本語日本語日本語日本語日本語日本... --+ + + TABLE, + ], ]; } @@ -3213,6 +3229,15 @@ $table->render(); } + public function testStyleOpenedAfterLongRunsOfEscapedTagDelimitersIsClosed() + { + $table = new Table($output = $this->getOutputStream(true)); + $table->setRows([[OutputFormatter::escape(str_repeat('array ', 10000)).'foo', 'bar']]); + $table->render(); + + $this->assertStringContainsString("\033[32mfoo\033[39m | bar |\n", $this->getOutputContent($output)); + } + public function testWithHyperlinkAndMaxWidth() { $table = new Table($output = $this->getOutputStream(true)); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Console/Tests/Style/SymfonyStyleTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,6 +15,7 @@ use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Exception\RuntimeException; use Symfony\Component\Console\Formatter\OutputFormatter; +use Symfony\Component\Console\Helper\Helper; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\Input; use Symfony\Component\Console\Input\InputInterface; @@ -130,6 +131,22 @@ $this->assertCount(1, array_unique(array_map('strlen', $lines)), 'Every line of the block is padded to the same width.'); } + public function testBlockWithWideCharactersFitsInTheLineLength() + { + $this->command->setCode(static function (InputInterface $input, OutputInterface $output) { + (new SymfonyStyle($input, $output))->error(str_repeat('日本語のエラーメッセージ', 30)); + + return Command::SUCCESS; + }); + + $this->tester->execute([], ['interactive' => false, 'decorated' => false]); + + $lines = array_filter(explode("\n", $this->tester->getDisplay(true)), static fn (string $line): bool => '' !== trim($line)); + + $this->assertGreaterThan(1, \count($lines), 'The message is wrapped over several lines.'); + $this->assertSame([120], array_values(array_unique(array_map(Helper::width(...), $lines))), 'Every line of the block uses the line length.'); + } + public function testErrorKeepsAnEscapedTagThatIsWrappedAsText() { // the escaped "<" falls right where the block wraps the message diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php --- symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Loader/FileLoader.php 2026-11-25 09:18:34.000000000 +0000 @@ -66,6 +66,16 @@ throw new \TypeError(\sprintf('Invalid argument $ignoreErrors provided to "%s::import()": boolean or "not_found" expected, "%s" given.', static::class, get_debug_type($ignoreErrors))); } + if (\is_string($resource) && \strlen($resource) !== strcspn($resource, '*?{[') && !str_contains($resource, "\n")) { + foreach ($this->glob($resource, false, $globResource, true) as $_) { + break; + } + + foreach (\is_array($globResource) ? $globResource : [$globResource] as $r) { + $this->container->addResource($r); + } + } + try { return parent::import(...$args); } catch (LoaderLoadException $e) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Compiler/ValidateEnvPlaceholdersPassTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -105,17 +105,15 @@ public function testEnvsAreValidatedInConfigWithInvalidPlaceholder() { - $this->expectException(InvalidTypeException::class); - $this->expectExceptionMessage('Invalid type for path "env_extension.bool_node". Expected "bool", but got one of "bool", "int", "float", "string", "array".'); $container = new ContainerBuilder(); - $container->registerExtension($ext = new EnvExtension()); - $container->prependExtensionConfig('env_extension', $expected = [ + $container->registerExtension(new EnvExtension()); + $container->prependExtensionConfig('env_extension', [ 'bool_node' => '%env(const:BAZ)%', ]); + $this->expectException(InvalidTypeException::class); + $this->expectExceptionMessage('Invalid type for path "env_extension.bool_node". Expected "bool", but got one of "bool", "int", "float", "string", "array".'); $this->doProcess($container); - - $this->assertSame($expected, $container->resolveEnvPlaceholders($ext->getConfig())); } public function testInvalidEnvInConfig() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -173,8 +173,6 @@ public function testSetWithNullOnInitializedPredefinedService() { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "bar" service is already initialized, you cannot replace it.'); $sc = new Container(); $sc->set('foo', new \stdClass()); $sc->set('foo', null); @@ -182,8 +180,9 @@ $sc = new ProjectServiceContainer(); $sc->get('bar'); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "bar" service is already initialized, you cannot replace it.'); $sc->set('bar', null); - $this->assertTrue($sc->has('bar'), '->set() with null service resets the pre-defined service'); } public function testSetWithNullOnUninitializedPredefinedService() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -545,15 +545,13 @@ public function testOverrideServiceWhenUsingADumpedContainer() { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('The "decorator_service" service is already initialized, you cannot replace it.'); require_once self::$fixturesPath.'/php/services9_compiled.php'; $container = new \ProjectServiceContainer(); $container->get('decorator_service'); - $container->set('decorator_service', $decorator = new \stdClass()); - - $this->assertSame($decorator, $container->get('decorator_service'), '->set() overrides an already defined service'); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('The "decorator_service" service is already initialized, you cannot replace it.'); + $container->set('decorator_service', new \stdClass()); } public function testDumpAutowireData() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/FileLoaderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -14,6 +14,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Loader\LoaderResolver; +use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; @@ -92,6 +93,17 @@ ]; $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files'); + $this->assertContainsEquals(new GlobResource(self::$fixturesPath, '/{F}ixtures/{xml,yaml}/services2.{yml,xml}', false), $container->getResources()); + } + + public function testImportGlobMatchingNoFilesTracksTheGlob() + { + $container = new ContainerBuilder(); + $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath)); + + $loader->import(self::$fixturesPath.'/Fixtures/yaml/*.missing'); + + $this->assertEquals([new GlobResource(self::$fixturesPath.'/Fixtures/yaml', '/*.missing', false)], $container->getResources()); } public function testRegisterClasses() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -910,14 +910,12 @@ public function testAliasDefinitionContainsUnsupportedElements() { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid attribute "class" defined for alias "bar" in'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid attribute "class" defined for alias "bar" in'); $loader->load('invalid_alias_definition.xml'); - - $this->assertTrue($container->has('bar')); } public function testArgumentWithKeyOutsideCollection() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Node/ConditionalNode.php symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Node/ConditionalNode.php --- symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Node/ConditionalNode.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Node/ConditionalNode.php 2026-11-25 09:18:34.000000000 +0000 @@ -29,6 +29,18 @@ public function compile(Compiler $compiler): void { + if ($this->nodes['expr1'] === $this->nodes['expr2']) { + $compiler + ->raw('((') + ->compile($this->nodes['expr1']) + ->raw(') ?: (') + ->compile($this->nodes['expr3']) + ->raw('))') + ; + + return; + } + $compiler ->raw('((') ->compile($this->nodes['expr1']) @@ -42,8 +54,8 @@ public function evaluate(array $functions, array $values): mixed { - if ($this->nodes['expr1']->evaluate($functions, $values)) { - return $this->nodes['expr2']->evaluate($functions, $values); + if ($value = $this->nodes['expr1']->evaluate($functions, $values)) { + return $this->nodes['expr1'] === $this->nodes['expr2'] ? $value : $this->nodes['expr2']->evaluate($functions, $values); } return $this->nodes['expr3']->evaluate($functions, $values); @@ -51,6 +63,10 @@ public function toArray(): array { + if ($this->nodes['expr1'] === $this->nodes['expr2']) { + return ['(', $this->nodes['expr1'], ' ?: ', $this->nodes['expr3'], ')']; + } + return ['(', $this->nodes['expr1'], ' ? ', $this->nodes['expr2'], ' : ', $this->nodes['expr3'], ')']; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Parser.php symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Parser.php --- symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Parser.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Parser.php 2026-11-25 09:18:34.000000000 +0000 @@ -485,6 +485,7 @@ private function checkDepth(Node\Node $node): void { $nodes = [[$node, 1]]; + $depths = []; while ($nodes) { [$node, $depth] = array_pop($nodes); @@ -493,6 +494,12 @@ throw new SyntaxError(\sprintf('Expression is nested too deeply, the maximum nesting level is %d', self::MAX_NESTING_LEVEL), $this->stream->current->cursor, $this->stream->getExpression()); } + // "a ?: b" uses the node of "a" twice, so skip the nodes already checked at the same depth or deeper + if (($depths[$id = spl_object_id($node)] ?? 0) >= $depth) { + continue; + } + $depths[$id] = $depth; + foreach ($node->nodes as $child) { $nodes[] = [$child, $depth + 1]; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ExpressionLanguageTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -174,6 +174,27 @@ $this->assertSame($expected, $result); } + public function testShortTernaryUsesItsConditionOnce() + { + $counter = new class { + public $calls = 0; + + public function next() + { + return ++$this->calls; + } + }; + $expression = '((counter.next() ?: 0) ?: 0) ?: 0'; + $expressionLanguage = new ExpressionLanguage(); + + $this->assertSame(1, $expressionLanguage->evaluate($expression, ['counter' => $counter])); + + $result = null; + $counter->calls = 0; + eval(\sprintf('$result = %s;', $expressionLanguage->compile($expression, ['counter']))); + $this->assertSame(1, $result); + } + public function testParseThrowsInsteadOfNotice() { $this->expectException(SyntaxError::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/Node/ConditionalNodeTest.php symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/Node/ConditionalNodeTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/Node/ConditionalNodeTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/Node/ConditionalNodeTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -21,6 +21,7 @@ return [ [1, new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))], [2, new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))], + [3, new ConditionalNode($node = new ConstantNode(3), $node, new ConstantNode(2))], ]; } @@ -29,6 +30,7 @@ return [ ['((true) ? (1) : (2))', new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))], ['((false) ? (1) : (2))', new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))], + ['((3) ?: (2))', new ConditionalNode($node = new ConstantNode(3), $node, new ConstantNode(2))], ]; } @@ -37,6 +39,7 @@ return [ ['(true ? 1 : 2)', new ConditionalNode(new ConstantNode(true), new ConstantNode(1), new ConstantNode(2))], ['(false ? 1 : 2)', new ConditionalNode(new ConstantNode(false), new ConstantNode(1), new ConstantNode(2))], + ['(3 ?: 2)', new ConditionalNode($node = new ConstantNode(3), $node, new ConstantNode(2))], ]; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/ExpressionLanguage/Tests/ParserTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -412,6 +412,7 @@ yield 'properties' => ['a'.str_repeat('.b', 300)]; yield 'array accesses' => ['a'.str_repeat('[0]', 300)]; yield 'ternaries' => [str_repeat('1?', 300).'1'.str_repeat(':1', 300)]; + yield 'short ternaries' => [str_repeat('(', 300).'1'.str_repeat(' ?: 1)', 300)]; yield 'binary operators in nested parentheses' => [str_repeat('(', 20).'1'.str_repeat(str_repeat(' + 1', 20).')', 20)]; yield 'properties in nested parentheses' => [str_repeat('(', 20).'a'.str_repeat(str_repeat('.b', 20).')', 20)]; } @@ -422,6 +423,13 @@ $this->expectNotToPerformAssertions(); } + + public function testNestedShortTernariesAreAccepted() + { + (new Parser([]))->lint((new Lexer())->tokenize(str_repeat('(', 100).'a'.str_repeat(' ?: a)', 100)), ['a']); + + $this->expectNotToPerformAssertions(); + } public function testChainedTernariesWithBinaryConditionsAreAccepted() { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Finder/Glob.php symfony-6.4.51+dfsg/src/Symfony/Component/Finder/Glob.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Finder/Glob.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Finder/Glob.php 2026-11-25 09:18:34.000000000 +0000 @@ -45,6 +45,7 @@ $curlies = []; $bracketScanEnd = 0; $regex = ''; + $notSlash = '/' === $delimiter ? '[^\/]' : '[^/]'; if ($unanchored = str_starts_with($glob, '**/')) { $glob = '/'.$glob; } @@ -82,10 +83,10 @@ } elseif ('*' === $car) { if ($escaping || $strictWildcardSlash || !str_ends_with($regex, '.*')) { // ".*.*" matches the same as ".*" but backtracks quadratically - $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*'); + $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? $notSlash.'*' : '.*'); } } elseif ('?' === $car) { - $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.'); + $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? $notSlash : '.'); } elseif ('{' === $car) { if (!$escaping) { $curlies[] = [\strlen($regex)]; @@ -137,13 +138,13 @@ /** * Returns "\[" when no "]" closes the "[" at position $i, or when a "/" comes before the closing "]". * - * $scanEnd is where the last scan stopped without finding a "]": every "[" before that position gets the same result. + * $scanEnd is where the last scan stopped without finding a "]": every "[" before that position gets the same result, except one that starts a POSIX class such as "[:alpha:]", which opens a bracket expression of its own. */ private static function bracketExpressionToRegex(string $glob, int &$i, string $delimiter, int &$scanEnd): string { $sizeGlob = \strlen($glob); - if ($i < $scanEnd) { + if ($i < $scanEnd && !preg_match('/\[:[a-z]++:\]/A', $glob, $m, 0, $i)) { return '\\['; } @@ -154,8 +155,10 @@ if (']' === $car && $j > $i + 1) { $i = $j; + $class .= ']'; - return $class.']'; + // PCRE rejects some bracket expressions that POSIX leaves undefined, such as a range whose endpoints are reversed: those match nothing + return false === @preg_match($delimiter.$class.$delimiter, '') ? '(?!)' : $class; } if ('/' === $car || ('\\' === $car && '/' === ($glob[$j + 1] ?? ''))) { @@ -170,7 +173,8 @@ break; } $class .= preg_quote($glob[$j], $delimiter); - } elseif ($delimiter === $car || str_contains('.()|+^$', $car)) { + } elseif ($delimiter === $car || str_contains('.()|+^$:', $car)) { + // ":" is escaped so that a class such as "[:alpha:]" is not read as a POSIX one $class .= '\\'.$car; } else { $class .= $car; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Finder/Tests/GlobTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Finder/Tests/GlobTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Finder/Tests/GlobTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Finder/Tests/GlobTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -22,7 +22,16 @@ $this->assertEquals('#^(?=[^\.])\#$#', Glob::toRegex('#')); $this->assertEquals('#^\.[^/]*$#', Glob::toRegex('.*')); $this->assertEquals('^\.[^/]*$', Glob::toRegex('.*', true, true, '')); - $this->assertEquals('/^\.[^/]*$/', Glob::toRegex('.*', true, true, '/')); + $this->assertEquals('/^\.[^\/]*$/', Glob::toRegex('.*', true, true, '/')); + + foreach (['/', '#', '~'] as $delimiter) { + $this->assertSame(1, preg_match(Glob::toRegex('*.php', true, true, $delimiter), 'a.php')); + $this->assertSame(0, preg_match(Glob::toRegex('*.php', true, true, $delimiter), 'a/b.php')); + $this->assertSame(1, preg_match(Glob::toRegex('?.php', true, true, $delimiter), 'a.php')); + $this->assertSame(0, preg_match(Glob::toRegex('?.php', true, true, $delimiter), '/.php')); + $this->assertSame(1, preg_match(Glob::toRegex('**/*.php', true, true, $delimiter), 'a/b.php')); + $this->assertSame(1, preg_match(Glob::toRegex('a'.$delimiter.'[bc]', true, true, $delimiter), 'a'.$delimiter.'c')); + } } public function testGlobToRegexBracketExpressions() @@ -193,8 +202,35 @@ public function testGlobToRegexBracketsAfterAnUnclosedOne() { - $this->assertSame('#^(?=[^\.])\[\[:alpha:]$#', Glob::toRegex('[[:alpha:]')); - $this->assertSame(1, preg_match(Glob::toRegex('[[:alpha:]'), '[[:alpha:]')); + $this->assertSame('#^(?=[^\.])\[[\:alpha\:]$#', Glob::toRegex('[[:alpha:]')); + $this->assertSame(1, preg_match(Glob::toRegex('[[:alpha:]'), '[:')); + $this->assertSame(1, preg_match(Glob::toRegex('[[:alpha:]'), '[a')); + $this->assertSame(0, preg_match(Glob::toRegex('[[:alpha:]'), '[z')); + $this->assertSame(0, preg_match(Glob::toRegex('[[:alpha:]'), '[[:alpha:]')); + + $this->assertSame('#^(?=[^\.])\[[\:alpha\:]/(?=[^\.])]$#', Glob::toRegex('[[:alpha:]/]')); + $this->assertSame(1, preg_match(Glob::toRegex('[[:alpha:]/]'), '[a/]')); + $this->assertSame(0, preg_match(Glob::toRegex('[[:alpha:]/]'), '[z/]')); + } + + public function testGlobToRegexColonsAreNotAPosixClass() + { + $this->assertSame('#^(?=[^\.])[\:alpha\:]$#', Glob::toRegex('[:alpha:]')); + $this->assertSame(1, preg_match(Glob::toRegex('[:alpha:]'), ':')); + $this->assertSame(1, preg_match(Glob::toRegex('[:alpha:]'), 'a')); + $this->assertSame(0, preg_match(Glob::toRegex('[:alpha:]'), 'z')); + + $this->assertSame('#^(?=[^\.])[[:alpha:]]$#', Glob::toRegex('[[:alpha:]]')); + $this->assertSame(1, preg_match(Glob::toRegex('[[:alpha:]]'), 'z')); + $this->assertSame(0, preg_match(Glob::toRegex('[[:alpha:]]'), ':')); + } + + public function testGlobToRegexBracketExpressionPcreRejects() + { + $this->assertSame('#^(?=[^\.])(?!)$#', Glob::toRegex('[[-?]')); + $this->assertSame(0, preg_match(Glob::toRegex('[[-?]'), '[')); + $this->assertSame(0, preg_match(Glob::toRegex('[[-?]'), '?')); + $this->assertSame(0, preg_match(Glob::toRegex('[[-?]'), '[[-?]')); } public function testGlobToRegexUnclosedCurlies() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php symfony-6.4.51+dfsg/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Extension/Validator/Constraints/FormValidator.php 2026-11-25 09:18:34.000000000 +0000 @@ -25,7 +25,7 @@ class FormValidator extends ConstraintValidator { /** - * @var \SplObjectStorage> + * @var \SplObjectStorage|false> */ private \SplObjectStorage $resolvedGroups; @@ -51,7 +51,10 @@ // Validate the form data only if transformation succeeded $groups = $this->getValidationGroups($form); - if (!$groups) { + // A "validation_groups" callable returning false only skips the constraints: + // unlike the false option value, transformation failures of the children and + // extra fields are still reported + if (!$groups && false !== $groups) { return; } @@ -64,7 +67,7 @@ // Validate the data against the constraints defined in the form /** @var Constraint[] $constraints */ - $constraints = $config->getOption('constraints', []); + $constraints = false === $groups ? [] : $config->getOption('constraints', []); $hasChildren = $form->count() > 0; @@ -206,9 +209,9 @@ /** * Returns the validation groups of the given form. * - * @return string|GroupSequence|array + * @return string|GroupSequence|array|false */ - private function getValidationGroups(FormInterface $form): string|GroupSequence|array + private function getValidationGroups(FormInterface $form): string|GroupSequence|array|false { // Determine the clicked button of the complete form tree $clickedButton = null; @@ -247,14 +250,19 @@ * * @param string|GroupSequence|array|callable $groups The validation groups * - * @return GroupSequence|array + * @return GroupSequence|array|false */ - private static function resolveValidationGroups(string|GroupSequence|array|callable $groups, FormInterface $form): GroupSequence|array + private static function resolveValidationGroups(string|GroupSequence|array|callable $groups, FormInterface $form): GroupSequence|array|false { if (!\is_string($groups) && \is_callable($groups)) { $groups = $groups($form); } + // A callable may return false to skip the constraints + if (false === $groups) { + return false; + } + if ($groups instanceof GroupSequence) { return $groups; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ar.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ar.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ar.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ar.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -4,15 +4,15 @@ This form should not contain extra fields. - هذا النموذج يجب الا يحتوى على اى حقول اضافية. + يجب ألا يحتوي هذا النموذج على أي حقول إضافية. The uploaded file was too large. Please try to upload a smaller file. - مساحة الملف المرسل كبيرة. من فضلك حاول ارسال ملف اصغر. + حجم الملف المرفوع كبير جدًا. يرجى محاولة رفع ملف أصغر. The CSRF token is invalid. Please try to resubmit the form. - قيمة رمز الموقع غير صحيحة. من فضلك اعد ارسال النموذج. + رمز الحماية من تزوير الطلبات (CSRF) غير صالح. يرجى محاولة إعادة إرسال النموذج. This value is not a valid HTML5 color. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.bg.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.bg.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.bg.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.bg.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ This value is not a valid birthdate. - Стойността не е валидна дата на раждане. + Стойността не е валидна дата на раждане. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - Стойността не е валиден цвят. + Стойността не е валиден цвят. This value is not a valid country. @@ -44,7 +44,7 @@ This value is not a valid date interval. - Стойността не е валиден интервал от дати. + Стойността не е валиден интервал от дати. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - Стойността не е валиден файл. + Стойността не е валиден файл. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - Стойността не е валидно цяло число. + Стойността не е валидно цяло число. This value is not a valid language. @@ -76,11 +76,11 @@ This value is not a valid money amount. - Стойността не е валидна парична сума. + Стойността не е валидна парична сума. This value is not a valid number. - Стойността не е валидно число. + Стойността не е валидно число. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Стойността не е валидна процентна стойност. + Стойността не е валидна процентна стойност. The values do not match. @@ -108,11 +108,11 @@ This value is not a valid search term. - Стойността не е валидно търсене. + Стойността не е валиден термин за търсене. This value is not a valid phone number. - Стойността не е валиден телефонен номер. + Стойността не е валиден телефонен номер. The checkbox has an invalid value. @@ -124,11 +124,11 @@ This value is not a valid option. - Стойността не е валидна опция. + Стойността не е валидна опция. This value is not a valid range. - Стойността не е валиден обхват. + Стойността не е валиден обхват. This value is not a valid week. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ca.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ca.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ca.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.ca.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ This value is not a valid birthdate. - Aquest valor no és una data de naixement vàlida. + Aquest valor no és una data de naixement vàlida. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - Aquest valor no és un color vàlid. + Aquest valor no és un color vàlid. This value is not a valid country. @@ -44,7 +44,7 @@ This value is not a valid date interval. - Aquest valor no és un interval de dates vàlid. + Aquest valor no és un interval de dates vàlid. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - Aquest valor no és un fitxer vàlid. + Aquest valor no és un fitxer vàlid. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - Aquest valor no és un enter vàlid. + Aquest valor no és un enter vàlid. This value is not a valid language. @@ -72,15 +72,15 @@ This value is not a valid locale. - Aquest valor no és una configuració regional vàlida. + Aquest valor no és una configuració regional vàlida. This value is not a valid money amount. - Aquest valor no és una quantitat de diners vàlida. + Aquest valor no és una quantitat de diners vàlida. This value is not a valid number. - Aquest valor no és un número vàlid. + Aquest valor no és un número vàlid. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Aquest valor no és un valor percentual vàlid. + Aquest valor no és un valor percentual vàlid. The values do not match. @@ -108,15 +108,15 @@ This value is not a valid search term. - Aquest valor no és un terme de cerca vàlid. + Aquest valor no és un terme de cerca vàlid. This value is not a valid phone number. - Aquest valor no és un número de telèfon vàlid. + Aquest valor no és un número de telèfon vàlid. The checkbox has an invalid value. - La casella de selecció te un valor no vàlid. + La casella de selecció té un valor no vàlid. This value is not a valid email address. @@ -124,11 +124,11 @@ This value is not a valid option. - Aquest valor no és una opció vàlida. + Aquest valor no és una opció vàlida. This value is not a valid range. - Aquest valor no és un rang vàlid. + Aquest valor no és un rang vàlid. This value is not a valid week. @@ -140,7 +140,7 @@ The lower bound must not be greater than the upper bound. - El límit inferior no ha de ser superior al límit superior. + El límit inferior no ha de ser superior al límit superior. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.cs.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.cs.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.cs.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.cs.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ This value is not a valid birthdate. - Tato hodnota není platné datum narození. + Tato hodnota není platné datum narození. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - Tato hodnota není platná barva. + Tato hodnota není platná barva. This value is not a valid country. @@ -44,7 +44,7 @@ This value is not a valid date interval. - Tato hodnota není platné rozpětí dat. + Tato hodnota není platný časový interval. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - Tato hodnota není platný soubor. + Tato hodnota není platný soubor. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - Tato hodnota není platné celé číslo. + Tato hodnota není platné celé číslo. This value is not a valid language. @@ -76,11 +76,11 @@ This value is not a valid money amount. - Tato hodnota není platná částka. + Tato hodnota není platná částka. This value is not a valid number. - Tato hodnota není platné číslo. + Tato hodnota není platné číslo. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Tato hodnota není platná procentuální hodnota. + Tato hodnota není platná procentuální hodnota. The values do not match. @@ -108,11 +108,11 @@ This value is not a valid search term. - Tato hodnota není platný výraz k vyhledání. + Tato hodnota není platný hledaný výraz. This value is not a valid phone number. - Tato hodnota není platné telefonní číslo. + Tato hodnota není platné telefonní číslo. The checkbox has an invalid value. @@ -124,11 +124,11 @@ This value is not a valid option. - Tato hodnota není platná možnost. + Tato hodnota není platná možnost. This value is not a valid range. - Tato hodnota není platný rozsah. + Tato hodnota není platný rozsah. This value is not a valid week. @@ -140,7 +140,7 @@ The lower bound must not be greater than the upper bound. - Dolní mez nesmí být větší než horní mez. + Dolní mez nesmí být větší než horní mez. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.eu.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.eu.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.eu.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.eu.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -12,19 +12,19 @@ The CSRF token is invalid. Please try to resubmit the form. - CSRF tokena baliogabea da. Mesedez, saiatu berriro formularioa bidaltzen. + CSRF tokena baliogabea da. Mesedez, saiatu berriro formularioa bidaltzen. This value is not a valid HTML5 color. - Balio hori ez da HTML5 kolore onargarria. + Balio hau ez da HTML5 kolore onargarria. This value is not a valid birthdate. - Balio hori ez da urtebetetze-egun baliozkoa. + Balio hau ez da jaiotze-data onargarri bat. The selected choice is invalid. - Hautatutako aukera ez da egokia. + Hautatutako aukera ez da onargarria. The collection is invalid. @@ -32,11 +32,11 @@ This value is not a valid color. - Balio hori ez da kolore baliozkoa. + Balio hau ez da kolore onargarri bat. This value is not a valid country. - Balio hau ez da herrialde egoki bat. + Balio hau ez da herrialde onargarri bat. This value is not a valid currency. @@ -44,19 +44,19 @@ This value is not a valid date interval. - Balio hori ez da data-tarte baliozkoa. + Balio hau ez da data-tarte onargarri bat. This value is not a valid date and time. - Balio hau ez da data-ordu egoki bat. + Balio hau ez da data-ordu onargarri bat. This value is not a valid date. - Balio hau ez da data egoki bat. + Balio hau ez da data onargarri bat. This value is not a valid file. - Balio hori ez da fitxategi baliozkoa. + Balio hau ez da fitxategi onargarri bat. The hidden field is invalid. @@ -64,23 +64,23 @@ This value is not a valid integer. - Balio hori ez da zenbaki oso baliozkoa. + Balio hau ez da baliozko zenbaki osoa. This value is not a valid language. - Balio hau ez da hizkuntza egoki bat. + Balio hau ez da hizkuntza onargarri bat. This value is not a valid locale. - Balio hori ez da eskualde-konfigurazio baliozkoa. + Balio hau ez da lokalizazio onargarri bat. This value is not a valid money amount. - Balio hori ez da diru-kopuru baliozkoa. + Balio hau ez da diru-kopuru onargarri bat. This value is not a valid number. - Balio hori ez da zenbaki baliozkoa. + Balio hau ez da zenbaki onargarri bat. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Balio hori ez da portzentaje baliozkoa. + Balio hau ez da ehuneko onargarri bat. The values do not match. @@ -96,23 +96,23 @@ This value is not a valid time. - Balio hau ez da ordu egoki bat. + Balio hau ez da ordu onargarri bat. This value is not a valid timezone. - Balio hori ez da baliozko ordu-eremua. + Balio hau ez da baliozko ordu-eremua. This value is not a valid URL. - Balio hau ez da baliabideen kokatzaile uniforme (URL) egoki bat. + Balio hau ez da URL onargarri bat. This value is not a valid search term. - Balio hori ez da bilaketa-termino baliozkoa. + Balio hau ez da bilaketa-termino onargarri bat. This value is not a valid phone number. - Balio hori ez da telefono-zenbaki baliozkoa. + Balio hau ez da telefono-zenbaki onargarri bat. The checkbox has an invalid value. @@ -120,27 +120,27 @@ This value is not a valid email address. - Balio hau ez da posta elektroniko egoki bat. + Balio hau ez da posta elektroniko onargarri bat. This value is not a valid option. - Balio hori ez da aukera baliozkoa. + Balio hau ez da aukera onargarri bat. This value is not a valid range. - Balio hori ez da tarte baliozkoa. + Balio hau ez da tarte onargarri bat. This value is not a valid week. - Balio hori ez da aste baliozkoa. + Balio hau ez da aste onargarri bat. This value is not a valid UUID. - Balio hori ez da UUID baliozkoa. + Balio hau ez da UUID onargarri bat. The lower bound must not be greater than the upper bound. - Beheko muga ezin da goiko muga baino handiagoa izan. + Beheko muga ezin da goiko muga baino handiagoa izan. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.he.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.he.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.he.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.he.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ This value is not a valid birthdate. - ערך זה אינו תאריך לידה חוקי. + ערך זה אינו תאריך לידה חוקי. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - ערך זה אינו צבע חוקי. + ערך זה אינו צבע חוקי. This value is not a valid country. @@ -44,7 +44,7 @@ This value is not a valid date interval. - ערך זה אינו מרווח תאריכים חוקי. + ערך זה אינו מרווח זמן חוקי. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - ערך זה אינו קובץ חוקי. + ערך זה אינו קובץ חוקי. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - ערך זה אינו מספר שלם חוקי. + ערך זה אינו מספר שלם חוקי. This value is not a valid language. @@ -72,15 +72,15 @@ This value is not a valid locale. - ערך זה אינו שפה מקומית חוקית. + ערך זה אינו אזור חוקי. This value is not a valid money amount. - ערך זה אינו סכום כסף חוקי. + ערך זה אינו סכום כסף חוקי. This value is not a valid number. - ערך זה אינו מספר חוקי. + ערך זה אינו מספר חוקי. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - ערך זה אינו ערך באחוזים חוקי. + ערך זה אינו אחוז חוקי. The values do not match. @@ -108,11 +108,11 @@ This value is not a valid search term. - ערך זה אינו מונח חיפוש חוקי. + ערך זה אינו מונח חיפוש חוקי. This value is not a valid phone number. - ערך זה אינו מספר טלפון חוקי. + ערך זה אינו מספר טלפון חוקי. The checkbox has an invalid value. @@ -124,11 +124,11 @@ This value is not a valid option. - ערך זה אינו אפשרות חוקית. + ערך זה אינו אפשרות חוקית. This value is not a valid range. - ערך זה אינו טווח חוקי. + ערך זה אינו טווח חוקי. This value is not a valid week. @@ -140,7 +140,7 @@ The lower bound must not be greater than the upper bound. - הגבול התחתון לא יכול להיות גדול מהגבול העליון. + הגבול התחתון לא יכול להיות גדול מהגבול העליון. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.hu.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.hu.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.hu.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.hu.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ This value is not a valid birthdate. - Ez az érték nem érvényes születési dátum. + Ez az érték nem érvényes születési dátum. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - Ez az érték nem érvényes szín. + Ez az érték nem érvényes szín. This value is not a valid country. @@ -44,7 +44,7 @@ This value is not a valid date interval. - Ez az érték nem érvényes dátumintervallum. + Ez az érték nem érvényes dátumintervallum. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - Ez az érték nem érvényes fájl. + Ez az érték nem érvényes fájl. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - Ez az érték nem érvényes egész szám. + Ez az érték nem érvényes egész szám. This value is not a valid language. @@ -76,11 +76,11 @@ This value is not a valid money amount. - Ez az érték nem érvényes pénzösszeg. + Ez az érték nem érvényes pénzösszeg. This value is not a valid number. - Ez az érték nem érvényes szám. + Ez az érték nem érvényes szám. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Ez az érték nem érvényes százalékos érték. + Ez az érték nem érvényes százalék. The values do not match. @@ -108,11 +108,11 @@ This value is not a valid search term. - Ez az érték nem érvényes keresési kifejezés. + Ez az érték nem érvényes keresési kifejezés. This value is not a valid phone number. - Ez az érték nem érvényes telefonszám. + Ez az érték nem érvényes telefonszám. The checkbox has an invalid value. @@ -124,11 +124,11 @@ This value is not a valid option. - Ez az érték nem érvényes opció. + Ez az érték nem érvényes opció. This value is not a valid range. - Ez az érték nem érvényes tartomány. + Ez az érték nem érvényes tartomány. This value is not a valid week. @@ -140,7 +140,7 @@ The lower bound must not be greater than the upper bound. - Az alsó határérték nem lehet nagyobb a felső határértéknél. + Az alsó határérték nem lehet nagyobb a felső határértéknél. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.mk.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.mk.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.mk.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.mk.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ This value is not a valid birthdate. - Оваа вредност не е валидна дата на раѓање. + Оваа вредност не е валиден датум на раѓање. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - Оваа вредност не е валидна боја. + Оваа вредност не е валидна боја. This value is not a valid country. @@ -44,7 +44,7 @@ This value is not a valid date interval. - Оваа вредност не е валиден интервал помеѓу два датума. + Оваа вредност не е валиден интервал помеѓу два датума. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - Оваа вредност не е валидна датотека. + Оваа вредност не е валидна датотека. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - Оваа вредност не е цел број. + Оваа вредност не е валиден цел број. This value is not a valid language. @@ -76,11 +76,11 @@ This value is not a valid money amount. - Оваа вредност не е валидна сума на пари. + Оваа вредност не е валиден паричен износ. This value is not a valid number. - Оваа вредност не е валиден број. + Оваа вредност не е валиден број. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Оваа вредност не е валидна процентуална вредност. + Оваа вредност не е валидна процентуална вредност. The values do not match. @@ -108,11 +108,11 @@ This value is not a valid search term. - Оваа вредност не е валиден термин за пребарување. + Оваа вредност не е валиден термин за пребарување. This value is not a valid phone number. - Оваа вредност не е валиден телефонски број. + Оваа вредност не е валиден телефонски број. The checkbox has an invalid value. @@ -124,11 +124,11 @@ This value is not a valid option. - Оваа вредност не е валидна опција. + Оваа вредност не е валидна опција. This value is not a valid range. - Оваа вредност не е валиден опсег. + Оваа вредност не е валиден опсег. This value is not a valid week. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.pt.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.pt.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.pt.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.pt.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ This value is not a valid birthdate. - Este valor não é uma data de nascimento válida. + Este valor não é uma data de nascimento válida. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - Este valor não é uma cor válida. + Este valor não é uma cor válida. This value is not a valid country. @@ -40,11 +40,11 @@ This value is not a valid currency. - Este valor não é uma moeda válida. + Este valor não é uma moeda válida. This value is not a valid date interval. - Este valor não é um intervalo de datas válido. + Este valor não é um intervalo de datas válido. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - Este valor não é um ficheiro válido. + Este valor não é um ficheiro válido. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - Este valor não é um número inteiro válido. + Este valor não é um número inteiro válido. This value is not a valid language. @@ -72,15 +72,15 @@ This value is not a valid locale. - Este valor não é uma configuração regional válida. + Este valor não é uma configuração regional válida. This value is not a valid money amount. - Este valor não é um valor monetário válido. + Este valor não é um montante válido. This value is not a valid number. - Este valor não é um número válido. + Este valor não é um número válido. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Este valor não é um valor percentual válido. + Este valor não é uma percentagem válida. The values do not match. @@ -104,15 +104,15 @@ This value is not a valid URL. - Este valor não é uma URL válida. + Este valor não é um URL válido. This value is not a valid search term. - Este valor não é um termo de pesquisa válido. + Este valor não é um termo de pesquisa válido. This value is not a valid phone number. - Este valor não é um número de telefone válido. + Este valor não é um número de telefone válido. The checkbox has an invalid value. @@ -124,11 +124,11 @@ This value is not a valid option. - Este valor não é uma opção válida. + Este valor não é uma opção válida. This value is not a valid range. - Este valor não é um intervalo válido. + Este valor não é um intervalo válido. This value is not a valid week. @@ -140,7 +140,7 @@ The lower bound must not be greater than the upper bound. - O limite inferior não pode ser superior ao limite superior. + O limite inferior não pode ser superior ao limite superior. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.sq.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.sq.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.sq.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.sq.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -29,7 +29,7 @@ This value is not a valid birthdate. - Kjo vlerë nuk është një datëlindje e vlefshme. + Kjo vlerë nuk është një datëlindje e vlefshme. The selected choice is invalid. @@ -41,7 +41,7 @@ This value is not a valid color. - Kjo vlerë nuk është një ngjyrë e vlefshme. + Kjo vlerë nuk është një ngjyrë e vlefshme. This value is not a valid country. @@ -53,7 +53,7 @@ This value is not a valid date interval. - Kjo vlerë nuk është një interval i vlefshëm. + Kjo vlerë nuk është një interval i vlefshëm. This value is not a valid date and time. @@ -65,7 +65,7 @@ This value is not a valid file. - Kjo vlerë nuk është një skedar i vlefshëm. + Kjo vlerë nuk është një skedar i vlefshëm. The hidden field is invalid. @@ -73,7 +73,7 @@ This value is not a valid integer. - Kjo vlerë nuk është një numër i plotë i vlefshëm. + Kjo vlerë nuk është një numër i plotë i vlefshëm. This value is not a valid language. @@ -81,15 +81,15 @@ This value is not a valid locale. - Kjo vlerë nuk është një “locale” e vlefshme. + Kjo vlerë nuk është një “locale” e vlefshme. This value is not a valid money amount. - Kjo vlerë nuk është një shumë parash e vlefshme. + Kjo vlerë nuk është një shumë parash e vlefshme. This value is not a valid number. - Kjo vlerë nuk është një numër i vlefshëm. + Kjo vlerë nuk është një numër i vlefshëm. The password is invalid. @@ -97,7 +97,7 @@ This value is not a valid percentage. - Kjo vlerë nuk është një vlerë përqindjeje e vlefshme. + Kjo vlerë nuk është një vlerë përqindjeje e vlefshme. The values do not match. @@ -117,11 +117,11 @@ This value is not a valid search term. - Kjo vlerë nuk është një term kërkimi i vlefshëm. + Kjo vlerë nuk është një term kërkimi i vlefshëm. This value is not a valid phone number. - Kjo vlerë nuk është një numër telefoni i vlefshëm. + Kjo vlerë nuk është një numër telefoni i vlefshëm. The checkbox has an invalid value. @@ -133,11 +133,11 @@ This value is not a valid option. - Kjo vlerë nuk është një alternativë e vlefshme. + Kjo vlerë nuk është një alternativë e vlefshme. This value is not a valid range. - Kjo vlerë nuk është një seri e vlefshme. + Kjo vlerë nuk është një seri e vlefshme. This value is not a valid week. @@ -145,7 +145,7 @@ This value is not a valid UUID. - Kjo vlerë nuk është një UUID i vlefshëm. + Kjo vlerë nuk është një UUID e vlefshme. The lower bound must not be greater than the upper bound. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tg.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tg.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tg.xlf 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tg.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,147 @@ + + + + + + This form should not contain extra fields. + Ин шакл набояд майдонҳои иловагӣ дошта бошад. + + + The uploaded file was too large. Please try to upload a smaller file. + Файли боргузоришуда хеле калон аст. Лутфан файли хурдтарро боргузорӣ кунед. + + + The CSRF token is invalid. Please try to resubmit the form. + Токени CSRF нодуруст аст. Лутфан шаклро дубора фиристед. + + + This value is not a valid HTML5 color. + Ин қимат ранги дурусти HTML5 нест. + + + This value is not a valid birthdate. + Лутфан санаи таваллуди дурустро ворид кунед. + + + The selected choice is invalid. + Варианти интихобшуда нодуруст аст. + + + The collection is invalid. + Маҷмӯа нодуруст аст. + + + This value is not a valid color. + Лутфан ранги дурустро интихоб кунед. + + + This value is not a valid country. + Лутфан кишвари дурустро интихоб кунед. + + + This value is not a valid currency. + Лутфан асъори дурустро интихоб кунед. + + + This value is not a valid date interval. + Лутфан фосилаи санаҳои дурустро интихоб кунед. + + + This value is not a valid date and time. + Лутфан сана ва вақти дурустро ворид кунед. + + + This value is not a valid date. + Лутфан санаи дурустро ворид кунед. + + + This value is not a valid file. + Лутфан файли дурустро интихоб кунед. + + + The hidden field is invalid. + Майдони пинҳон нодуруст аст. + + + This value is not a valid integer. + Лутфан адади бутун ворид кунед. + + + This value is not a valid language. + Лутфан забони дурустро интихоб кунед. + + + This value is not a valid locale. + Лутфан локали дурустро интихоб кунед. + + + This value is not a valid money amount. + Лутфан маблағи дурусти пулиро ворид кунед. + + + This value is not a valid number. + Лутфан адад ворид кунед. + + + The password is invalid. + Парол нодуруст аст. + + + This value is not a valid percentage. + Лутфан қимати фоизиро ворид кунед. + + + The values do not match. + Қиматҳо мувофиқат намекунанд. + + + This value is not a valid time. + Лутфан вақти дурустро ворид кунед. + + + This value is not a valid timezone. + Лутфан минтақаи вақти дурустро интихоб кунед. + + + This value is not a valid URL. + Лутфан URL-и дурустро ворид кунед. + + + This value is not a valid search term. + Лутфан калимаи ҷустуҷӯи дурустро ворид кунед. + + + This value is not a valid phone number. + Лутфан рақами телефони дурустро ворид кунед. + + + The checkbox has an invalid value. + Қуттии қайд қимати нодуруст дорад. + + + This value is not a valid email address. + Лутфан суроғаи электронии дурустро ворид кунед. + + + This value is not a valid option. + Лутфан варианти дурустро интихоб кунед. + + + This value is not a valid range. + Лутфан диапазони дурустро интихоб кунед. + + + This value is not a valid week. + Лутфан ҳафтаи дурустро ворид кунед. + + + This value is not a valid UUID. + Лутфан UUID-и дурустро ворид кунед. + + + The lower bound must not be greater than the upper bound. + Ҳудуди поёнӣ набояд аз ҳудуди болоӣ зиёд бошад. + + + + diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tl.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tl.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tl.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.tl.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -16,11 +16,11 @@ This value is not a valid HTML5 color. - Ang halagang ito ay hindi wastong HTML5 color. + Ang impormasyong ito ay hindi wastong HTML5 color. This value is not a valid birthdate. - Ang halagang ito ay hindi wastong petsa ng kapanganakan. + Mangyaring maglagay ng wastong petsa ng kapanganakan. The selected choice is invalid. @@ -32,31 +32,31 @@ This value is not a valid color. - Ang halagang ito ay hindi wastong kulay. + Mangyaring pumili ng wastong kulay. This value is not a valid country. - Ang halagang ito ay hindi wastong bansa. + Ang impormasyong ito ay hindi wastong bansa. This value is not a valid currency. - Ang halagang ito ay hindi balidong pera. + Ang impormasyong ito ay hindi balidong pera. This value is not a valid date interval. - Ang halagang ito ay hindi wastong agwat ng petsa. + Mangyaring pumili ng wastong agwat ng petsa. This value is not a valid date and time. - Ang halagang ito ay hindi wastong petsa/oras. + Ang impormasyong ito ay hindi wastong petsa/oras. This value is not a valid date. - Ang halagang ito ay hindi balidong petsa. + Ang impormasyong ito ay hindi balidong petsa. This value is not a valid file. - Ang halagang ito ay hindi wastong file. + Mangyaring pumili ng wastong file. The hidden field is invalid. @@ -64,23 +64,23 @@ This value is not a valid integer. - Ang halagang ito ay hindi wastong integer. + Mangyaring maglagay ng buong numero. This value is not a valid language. - Ang halagang ito ay hindi balidong wika. + Ang impormasyong ito ay hindi balidong wika. This value is not a valid locale. - Ang halagang ito ay hindi wastong locale. + Ang impormasyong ito ay hindi wastong locale. This value is not a valid money amount. - Ang halagang ito ay hindi wastong halaga ng pera. + Mangyaring maglagay ng wastong halaga ng pera. This value is not a valid number. - Ang halagang ito ay hindi wastong numero. + Mangyaring maglagay ng numero. The password is invalid. @@ -88,19 +88,19 @@ This value is not a valid percentage. - Ang halagang ito ay hindi wastong porsyento. + Mangyaring maglagay ng porsyento. The values do not match. - Hindi tugma ang mga halaga. + Hindi tugma ang mga impormasyon. This value is not a valid time. - Ang halagang ito ay hindi wastong oras. + Ang impormasyong ito ay hindi wastong oras. This value is not a valid timezone. - Ang halagang ito ay hindi wastong timezone. + Ang impormasyong ito ay hindi wastong timezone. This value is not a valid URL. @@ -108,35 +108,35 @@ This value is not a valid search term. - Ang halagang ito ay hindi wastong katagang sinasaliksik. + Mangyaring maglagay ng wastong katagang hahanapin. This value is not a valid phone number. - Ang halagang ito ay hindi wastong numero ng telepono. + Mangyaring magbigay ng wastong numero ng telepono. The checkbox has an invalid value. - Ang checkbox ay mayroon hindi balidong halaga. + Ang checkbox ay mayroong hindi balidong impormasyon. This value is not a valid email address. - Ang halagang ito ay hindi balidong address ng email. + Ang impormasyong ito ay hindi balidong address ng email. This value is not a valid option. - Ang halagang ito ay hindi wastong pagpipilian. + Mangyaring pumili ng wastong opsyon. This value is not a valid range. - Ang halagang ito ay hindi wastong layo. + Mangyaring pumili ng wastong tinakdang hangganan. This value is not a valid week. - Ang halagang ito ay hindi isang wastong linggo. + Ang impormasyong ito ay hindi isang wastong linggo. This value is not a valid UUID. - Ang halagang ito ay hindi isang wastong UUID. + Ang impormasyong ito ay hindi isang wastong UUID. The lower bound must not be greater than the upper bound. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.uz.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.uz.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Resources/translations/validators.uz.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Resources/translations/validators.uz.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -8,7 +8,7 @@ The uploaded file was too large. Please try to upload a smaller file. - Yuklab olingan fayl juda katta. Iltimos, kichikroq faylni yuklashga harakat qiling. + Yuklangan fayl juda katta. Iltimos, kichikroq faylni yuklashga harakat qiling. The CSRF token is invalid. Please try to resubmit the form. @@ -20,7 +20,7 @@ This value is not a valid birthdate. - Qiymat noto'g'ri, tug'ilgan kun emas. + Iltimos, yaroqli tug'ilgan sanani kiriting. The selected choice is invalid. @@ -32,7 +32,7 @@ This value is not a valid color. - Qiymat noto'g'ri, rang emas. + Iltimos, yaroqli rangni tanlang. This value is not a valid country. @@ -44,7 +44,7 @@ This value is not a valid date interval. - Qiymat noto'g'ri, sana oralig'i emas. + Iltimos, yaroqli sana oralig'ini tanlang. This value is not a valid date and time. @@ -56,7 +56,7 @@ This value is not a valid file. - Qiymat noto'g'ri, fayl emas. + Iltimos, yaroqli faylni tanlang. The hidden field is invalid. @@ -64,7 +64,7 @@ This value is not a valid integer. - Qiymat noto'g'ri, butun son emas. + Iltimos, butun son kiriting. This value is not a valid language. @@ -72,15 +72,15 @@ This value is not a valid locale. - Qiymat noto'g'ri, lokal emas. + Iltimos, yaroqli lokalni tanlang. This value is not a valid money amount. - Qiymat noto'g'ri, pul miqdori emas. + Iltimos, yaroqli pul miqdorini kiriting. This value is not a valid number. - Qiymat noto'g'ri, raqam emas. + Iltimos, son kiriting. The password is invalid. @@ -88,7 +88,7 @@ This value is not a valid percentage. - Qiymat noto'g'ri, foiz emas. + Iltimos, foiz qiymatini kiriting. The values do not match. @@ -108,11 +108,11 @@ This value is not a valid search term. - Qiymat noto'g'ri, qidiruv so'zi emas. + Iltimos, yaroqli qidiruv so'zini kiriting. This value is not a valid phone number. - Qiymat noto'g'ri, telefon raqami emas. + Iltimos, yaroqli telefon raqamini kiriting. The checkbox has an invalid value. @@ -124,11 +124,11 @@ This value is not a valid option. - Qiymat noto'g'ri, variant emas. + Iltimos, yaroqli variantni tanlang. This value is not a valid range. - Qiymat noto'g'ri, oraliq emas. + Iltimos, yaroqli oraliqni tanlang. This value is not a valid week. @@ -140,7 +140,7 @@ The lower bound must not be greater than the upper bound. - Quyi chegara yuqori chegaradan katta bo'lmasligi kerak. + Quyi chegara yuqori chegaradan katta bo'lmasligi kerak. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -332,10 +332,10 @@ public function testReverseTransformWithNonExistingDate() { - $this->expectException(TransformationFailedException::class); $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', \IntlDateFormatter::SHORT); - $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('31.04.10 04:05')); + $this->expectException(TransformationFailedException::class); + $transformer->reverseTransform('31.04.10 04:05'); } public function testReverseTransformOutOfTimestampRange() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -454,6 +454,48 @@ $this->assertNoViolation(); } + public function testDontValidateConstraintsIfValidationGroupsCallbackReturnsFalse() + { + $object = new \stdClass(); + $options = [ + 'validation_groups' => static fn (FormInterface $form) => false, + 'constraints' => [new NotBlank()], + ]; + $form = $this->getCompoundForm($object, $options); + $form->submit([]); + + $this->expectNoValidate(); + + $this->validator->validate($form, new Form()); + + $this->assertNoViolation(); + } + + public function testValidateChildrenAndExtraFieldsIfValidationGroupsCallbackReturnsFalse() + { + $form = $this->getBuilder('parent', null, [ + 'validation_groups' => static fn (FormInterface $form) => false, + 'extra_fields_message' => 'Extra!|Extras!', + ]) + ->setCompound(true) + ->setDataMapper(new DataMapper()) + ->add($this->getBuilder('child')) + ->getForm(); + + $form->submit(['foo' => 'bar']); + + $this->expectValidateValueAt(0, 'children[child]', $form->get('child'), new Form()); + + $this->validator->validate($form, new Form()); + + $this->buildViolation('Extra!|Extras!') + ->setParameter('{{ extra_fields }}', '"foo"') + ->setInvalidValue(['foo' => 'bar']) + ->setPlural(1) + ->setCode(Form::NO_SUCH_FIELD_ERROR) + ->assertRaised(); + } + public function testUseValidationGroupOfClickedButton() { $object = new \stdClass(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Form/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,7 +11,9 @@ namespace Symfony\Component\Form\Tests\Extension\Validator\Type; +use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\Extension\Validator\Constraints\Form as FormConstraint; use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Form\Form; use Symfony\Component\Form\Forms; @@ -94,6 +96,25 @@ $this->assertInstanceOf(Length::class, $errors[0]->getCause()->getConstraint()); } + public function testValidationGroupsCallbackReturningFalseKeepsTransformationFailures() + { + $form = Forms::createFormFactoryBuilder() + ->addExtension(new ValidatorExtension(Validation::createValidator(), false)) + ->getFormFactory() + ->create(FormTypeTest::TESTED_TYPE, null, ['validation_groups' => static fn () => false]) + ->add('number', IntegerType::class) + ->add('name', TextType::class, ['constraints' => [new NotBlank()]]) + ; + + $form->submit(['number' => 'abc', 'name' => '']); + + $errors = $form->getErrors(true); + + $this->assertCount(1, $errors); + $this->assertSame('number', $errors[0]->getOrigin()->getName()); + $this->assertSame(FormConstraint::NOT_SYNCHRONIZED_ERROR, $errors[0]->getCause()->getCode()); + } + public function testManyFieldsGroupSequenceWithConstraintsOption() { $formMetadata = new ClassMetadata(Form::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/HtmlSanitizerConfig.php symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/HtmlSanitizerConfig.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/HtmlSanitizerConfig.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/HtmlSanitizerConfig.php 2026-11-25 09:18:34.000000000 +0000 @@ -97,6 +97,7 @@ $this->attributeSanitizers = [ new Visitor\AttributeSanitizer\UrlAttributeSanitizer(), new Visitor\AttributeSanitizer\MetaRefreshAttributeSanitizer(), + new Visitor\AttributeSanitizer\LinkTargetAttributeSanitizer(), ]; } @@ -149,7 +150,8 @@ } } - return $clone; + // Browsers merge the attributes of html and body into the elements of the page, so only their content is kept + return $clone->blockElement('html')->blockElement('body'); } /** diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Reference/W3CReference.php symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Reference/W3CReference.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Reference/W3CReference.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Reference/W3CReference.php 2026-11-25 09:18:34.000000000 +0000 @@ -45,8 +45,8 @@ */ public const HEAD_ELEMENTS = [ 'head' => true, - 'link' => true, - 'meta' => true, + 'link' => false, + 'meta' => false, 'style' => false, 'title' => true, ]; @@ -71,9 +71,9 @@ 'bgsound' => false, 'big' => true, 'blockquote' => true, - 'body' => true, + 'body' => false, 'br' => true, - 'button' => true, + 'button' => false, 'canvas' => true, 'caption' => true, 'center' => true, @@ -83,12 +83,12 @@ 'colgroup' => true, 'command' => true, 'data' => true, - 'datalist' => true, + 'datalist' => false, 'dd' => true, 'del' => true, 'details' => true, 'dfn' => true, - 'dialog' => true, + 'dialog' => false, 'dir' => true, 'div' => true, 'dl' => true, @@ -109,7 +109,7 @@ 'header' => true, 'hgroup' => true, 'hr' => true, - 'html' => true, + 'html' => false, 'i' => true, 'image' => true, 'img' => true, @@ -136,7 +136,7 @@ 'output' => true, 'p' => true, 'picture' => true, - 'plaintext' => true, + 'plaintext' => false, 'popup' => true, 'portal' => true, 'pre' => true, @@ -188,7 +188,7 @@ 'abbr' => true, 'accept' => true, 'accept-charset' => true, - 'accesskey' => true, + 'accesskey' => false, 'action' => true, 'align' => true, 'alink' => true, @@ -252,7 +252,7 @@ 'disablepictureinpicture' => true, 'disableremoteplayback' => true, 'disallowdocumentaccess' => true, - 'download' => true, + 'download' => false, 'draggable' => true, 'elementtiming' => true, 'enctype' => true, @@ -261,7 +261,7 @@ 'event' => true, 'exportparts' => true, 'face' => true, - 'for' => true, + 'for' => false, 'form' => false, 'formaction' => false, 'formenctype' => false, @@ -290,7 +290,7 @@ 'inputmode' => true, 'integrity' => true, 'invisible' => true, - 'is' => true, + 'is' => false, 'ismap' => true, 'keytype' => true, 'kind' => true, @@ -318,7 +318,7 @@ 'minlength' => true, 'multiple' => true, 'muted' => true, - 'name' => true, + 'name' => false, 'nohref' => true, 'nomodule' => true, 'nonce' => true, @@ -339,7 +339,7 @@ 'preload' => true, 'pseudo' => true, 'readonly' => true, - 'referrerpolicy' => true, + 'referrerpolicy' => false, 'rel' => true, 'reportingorigin' => true, 'required' => true, @@ -364,7 +364,7 @@ 'shape' => true, 'size' => true, 'sizes' => true, - 'slot' => true, + 'slot' => false, 'span' => true, 'spellcheck' => true, 'src' => true, @@ -376,7 +376,7 @@ 'step' => true, 'style' => false, 'summary' => true, - 'tabindex' => true, + 'tabindex' => false, 'target' => true, 'text' => true, 'title' => true, diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Tests/HtmlSanitizerCustomTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Tests/HtmlSanitizerCustomTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Tests/HtmlSanitizerCustomTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Tests/HtmlSanitizerCustomTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -30,6 +30,156 @@ ); } + /** + * @dataProvider provideSanitizeForHeadWithSafeElements + */ + public function testSanitizeForHeadWithSafeElements(string $input, string $expected) + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + $this->assertSame($expected, (new HtmlSanitizer($config))->sanitizeFor('head', $input)); + } + + public static function provideSanitizeForHeadWithSafeElements(): iterable + { + yield 'stylesheet' => ['', '']; + yield 'data stylesheet' => ['', '']; + yield 'import' => ['', '']; + yield 'referrer policy' => ['', '']; + yield 'title' => ['Hello', 'Hello']; + } + + public function testSanitizeWithSafeElementsDropsReferrerPolicy() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + $this->assertSame( + 'Hello', + $this->sanitize($config, 'Hello') + ); + } + + public function testSanitizeWithSafeElementsDropsPlaintext() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + $this->assertSame('Hello', $this->sanitize($config, 'Hello

    the rest of the page')); + } + + public function testSanitizeWithSafeElementsBlocksHtmlAndBody() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + $this->assertSame('<p>Hello</p>', $this->sanitize($config, '<body inert><p>Hello</p></body>')); + $this->assertSame('<p>Hello</p>', $this->sanitize($config, '<html dir="rtl"><p>Hello</p></html>')); + $this->assertSame('<div>Hello</div>', $this->sanitize($config, '<div><body inert>Hello</body></div>')); + + $document = '<html dir="rtl"><head><title>Hello</title></head><body inert><p>world</p></body></html>'; + $this->assertSame('<p>world</p>', $this->sanitize($config, $document)); + $this->assertSame('<p>world</p>', (new HtmlSanitizer($config))->sanitizeFor('html', $document)); + } + + public function testSanitizeWithSafeElementsDropsTheOpenerLinkType() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + $this->assertSame( + '<a href="https://example.com/" target="_blank">Hello</a>', + $this->sanitize($config, '<a href="https://example.com/" target="_blank" rel="opener">Hello</a>') + ); + + $this->assertSame( + '<a href="https://example.com/" target="_blank" rel="nofollow noreferrer">Hello</a>', + $this->sanitize($config, '<a href="https://example.com/" target="_blank" rel="nofollow OPENER noreferrer">Hello</a>') + ); + + $this->assertSame( + '<area href="https://example.com/" target="_blank" />', + $this->sanitize($config, '<area href="https://example.com/" target="_blank" rel="opener">') + ); + } + + public function testSanitizeWithSafeElementsTurnsNamedTargetsIntoBlank() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + foreach (['foo', '_new', ' _blank'] as $target) { + $this->assertSame( + '<a href="https://example.com/" target="_blank">Hello</a>', + $this->sanitize($config, \sprintf('<a href="https://example.com/" target="%s">Hello</a>', $target)) + ); + } + + foreach (['_blank', '_BLANK', '_self', '_parent', '_top'] as $target) { + $this->assertSame( + \sprintf('<a href="https://example.com/" target="%s" rel="noopener">Hello</a>', $target), + $this->sanitize($config, \sprintf('<a href="https://example.com/" target="%s" rel="noopener">Hello</a>', $target)) + ); + } + } + + public function testSanitizeWithSafeElementsDropsAttributesThatActOnThePage() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + $this->assertSame( + '<img src="https://example.com/x.png" />', + $this->sanitize($config, '<img name="cookie" src="https://example.com/x.png">') + ); + + $this->assertSame( + '<details open><summary>Hello</summary>world</details>', + $this->sanitize($config, '<details name="faq" open><summary>Hello</summary>world</details>') + ); + + $this->assertSame('<label>Hello</label>', $this->sanitize($config, '<label for="delete-account">Hello</label>')); + $this->assertSame('<p>Hello</p>', $this->sanitize($config, '<p is="page-widget">Hello</p>')); + $this->assertSame('<span>Hello</span>', $this->sanitize($config, '<span slot="header">Hello</span>')); + + $this->assertSame( + '<a href="https://example.com/">Hello</a>', + $this->sanitize($config, '<a href="https://example.com/" accesskey="s" tabindex="1" download="invoice.pdf">Hello</a>') + ); + } + + public function testSanitizeWithSafeElementsDropsElementsThatActOnThePage() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ; + + $this->assertSame('Hello', $this->sanitize($config, 'Hello<button type="reset">world</button>')); + $this->assertSame('Hello', $this->sanitize($config, 'Hello<dialog open>world</dialog>')); + $this->assertSame('Hello', $this->sanitize($config, 'Hello<datalist id="emails"><option>world</option></datalist>')); + } + + public function testSanitizeWithSafeElementsKeepsIds() + { + $config = (new HtmlSanitizerConfig()) + ->allowSafeElements() + ->allowRelativeLinks() + ; + + $this->assertSame( + '<a href="#intro">Hello</a><h2 id="intro">world</h2>', + $this->sanitize($config, '<a href="#intro">Hello</a><h2 id="intro">world</h2>') + ); + } + public function testSanitizeForTextarea() { $config = (new HtmlSanitizerConfig()) @@ -868,6 +1018,12 @@ yield 'unparsable directive' => ['0:https://evil.example/', '<meta http-equiv="refresh" />']; yield 'vertical tab in the url keyword' => ["0;url\x0B=https://trusted.example/x", '<meta http-equiv="refresh" />']; yield 'vertical tab as separator' => ["0\x0Bhttps://trusted.example/x", '<meta http-equiv="refresh" />']; + yield 'vertical tab before the time' => ["\x0B0;url=https://evil.example/", '<meta http-equiv="refresh" />']; + yield 'unicode whitespace before the time' => ["\u{3000}0;url=https://evil.example/", '<meta http-equiv="refresh" />']; + yield 'mixed whitespace before the time' => [" \u{2028}\x0B\u{205F}.5,https://evil.example/", '<meta http-equiv="refresh" />']; + yield 'control character before the time' => ["\x1F0;url=https://evil.example/", '<meta http-equiv="refresh" />']; + yield 'invisible character before the time' => ["\u{FEFF}0;url=https://evil.example/", '<meta http-equiv="refresh" />']; + yield 'long whitespace before the time' => [str_repeat(' ', 10000)."\u{3000}0;url=https://evil.example/", '<meta http-equiv="refresh" />']; yield 'allowed host' => [ '0;url=https://trusted.example/x', @@ -877,6 +1033,10 @@ '9 , https://trusted.example/x', '<meta http-equiv="refresh" content="9 , https://trusted.example/x" />', ]; + yield 'allowed host after unicode whitespace' => [ + "\u{3000}0;url=https://trusted.example/x", + "<meta http-equiv=\"refresh\" content=\"\u{3000}0;url&#61;https://trusted.example/x\" />", + ]; yield 'long trailing whitespace' => [ '0;url=https://trusted.example/x'.str_repeat(' ', 2000).'y', '<meta http-equiv="refresh" content="0;url&#61;https://trusted.example/x'.str_repeat('%20', 2000).'y" />', @@ -887,7 +1047,16 @@ '0;url&#61;&#039;&#039;', '<meta http-equiv="refresh" content="0;url&#61;&#039;&#039;" />', ]; + yield 'empty quoted url followed by another quote' => [ + '0;url=&#039;&#039;/../admin/&#039;', + '<meta http-equiv="refresh" content="0;url&#61;&#039;&#039;" />', + ]; + yield 'empty double quoted url followed by another quote' => [ + '0;&#34;&#34;/../admin/&#34;', + '<meta http-equiv="refresh" content="0;&#34;&#34;" />', + ]; yield 'not a refresh directive' => ['some text', '<meta http-equiv="refresh" content="some text" />']; + yield 'letters before a number' => ['第2回', '<meta http-equiv="refresh" content="第2回" />']; } /** diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/LinkTargetAttributeSanitizer.php symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/LinkTargetAttributeSanitizer.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/LinkTargetAttributeSanitizer.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/LinkTargetAttributeSanitizer.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,53 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HtmlSanitizer\Visitor\AttributeSanitizer; + +use Symfony\Component\HtmlSanitizer\HtmlSanitizerConfig; +use Symfony\Component\HtmlSanitizer\TextSanitizer\StringSanitizer; + +/** + * Prevents links from giving the pages they open access to the current page. + * + * Browsers expose the current page as window.opener when a link uses the "opener" + * link type or a named target. Named targets are turned into "_blank", which also + * prevents links from navigating the frames of the page. + * + * @internal + */ +final class LinkTargetAttributeSanitizer implements AttributeSanitizerInterface +{ + public function getSupportedElements(): ?array + { + return ['a', 'area']; + } + + public function getSupportedAttributes(): ?array + { + return ['rel', 'target']; + } + + public function sanitizeAttribute(string $element, string $attribute, string $value, HtmlSanitizerConfig $config): ?string + { + if ('target' === $attribute) { + return \in_array(StringSanitizer::htmlLower($value), ['', '_blank', '_self', '_parent', '_top'], true) ? $value : '_blank'; + } + + $linkTypes = preg_split('/[ \t\n\f\r]+/', $value, -1, \PREG_SPLIT_NO_EMPTY); + $kept = array_filter($linkTypes, static fn (string $linkType) => 'opener' !== StringSanitizer::htmlLower($linkType)); + + if (\count($kept) === \count($linkTypes)) { + return $value; + } + + return $kept ? implode(' ', $kept) : null; + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/MetaRefreshAttributeSanitizer.php symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/MetaRefreshAttributeSanitizer.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/MetaRefreshAttributeSanitizer.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HtmlSanitizer/Visitor/AttributeSanitizer/MetaRefreshAttributeSanitizer.php 2026-11-25 09:18:34.000000000 +0000 @@ -28,6 +28,19 @@ */ final class MetaRefreshAttributeSanitizer implements AttributeSanitizerInterface { + /** + * Controls, and Unicode whitespace and invisible characters, matched as UTF-8 byte + * sequences so that malformed UTF-8 cannot make the match fail. + */ + private const SKIPPABLE_CHARS_PATTERN = '/[\x00-\x20\x7F]' + .'|\xC2[\x80-\xA0]' // U+0080-U+00A0 + .'|\xE1\x9A\x80' // U+1680 + .'|\xE1\xA0\x8E' // U+180E + .'|\xE2\x80[\x80-\x8F\xA8-\xAF]' // U+2000-U+200F, U+2028-U+202F + .'|\xE2\x81[\x9F-\xAF]' // U+205F-U+206F + .'|\xE3\x80\x80' // U+3000 + .'|\xEF\xBB\xBF/'; // U+FEFF + public function getSupportedElements(): ?array { return ['meta']; @@ -41,13 +54,19 @@ public function sanitizeAttribute(string $element, string $attribute, string $value, HtmlSanitizerConfig $config): ?string { // A leading time is the only marker of a refresh directive: without one, the value - // cannot trigger a navigation and belongs to another meta type. Whitespace means - // the ASCII whitespace of the specification, which \s does not match exactly. - if (!preg_match('/^([ \t\n\f\r]*(?:\d[\d.]*|\.[\d.]*))(.*)$/s', $value, $m)) { + // cannot trigger a navigation and belongs to another meta type. + if (!preg_match('/^(([\x00-\x20\x7F-\xFF]*+)(?:\d[\d.]*|\.[\d.]*))(.*)$/s', $value, $m)) { return $value; } - [, $time, $rest] = $m; + [, $time, $leading, $rest] = $m; + + // Browsers can skip more than ASCII whitespace before the time. The characters are + // removed one at a time: a repeated group in the expression above would make it fail + // on long values. + if ('' !== preg_replace(self::SKIPPABLE_CHARS_PATTERN, '', $leading)) { + return $value; + } // Nothing follows the time: the directive reloads the current document. if ('' === $rest) { @@ -80,7 +99,8 @@ $quote = $first; $url = substr($url, 1); - // Everything after the closing quote is ignored by browsers. + // Everything after the closing quote is dropped: browsers disagree on whether the + // first or the last quote closes the URL. if (false !== $end = strpos($url, $quote)) { $url = substr($url, 0, $end); } @@ -93,7 +113,7 @@ // An empty URL resolves to the document's own URL: the directive reloads the // current document, exactly like a directive made of a time only. if ('' === $url) { - return $value; + return $time.$separator.$keyword.$quote.$quote; } $sanitized = UrlSanitizer::sanitize( diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/AmpHttpClient.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/AmpHttpClient.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/AmpHttpClient.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/AmpHttpClient.php 2026-11-25 09:18:34.000000000 +0000 @@ -140,12 +140,6 @@ $request->setInactivityTimeout(0); } - if ('' !== $request->getUri()->getUserInfo() && !$request->hasHeader('authorization')) { - $auth = explode(':', $request->getUri()->getUserInfo(), 2); - $auth = array_map('rawurldecode', $auth) + [1 => '']; - $request->setHeader('Authorization', 'Basic '.base64_encode(implode(':', $auth))); - } - return new AmpResponse($this->multi, $request, $options, $this->logger); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/CachingHttpClient.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/CachingHttpClient.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/CachingHttpClient.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/CachingHttpClient.php 2026-11-25 09:18:34.000000000 +0000 @@ -136,7 +136,7 @@ return new ResponseStream((function () use ($mockResponses, $clientResponses, $timeout) { yield from MockResponse::stream($mockResponses, $timeout); - yield $this->client->stream($clientResponses, $timeout); + yield from $this->client->stream($clientResponses, $timeout); })()); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Chunk/ServerSentEvent.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Chunk/ServerSentEvent.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Chunk/ServerSentEvent.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Chunk/ServerSentEvent.php 2026-11-25 09:18:34.000000000 +0000 @@ -35,6 +35,8 @@ $content = substr($content, 3); } + $data = null; + foreach (preg_split("/(?:\r\n|[\r\n])/", $content) as $line) { if (0 === $i = strpos($line, ':')) { continue; @@ -49,10 +51,10 @@ $this->id = substr($line, $i); break; case 'event': - $this->type = substr($line, $i); + $this->type = '' !== ($type = substr($line, $i)) ? $type : 'message'; break; case 'data': - $this->data .= ('' === $this->data ? '' : "\n").substr($line, $i); + $data = (null === $data ? '' : $data."\n").substr($line, $i); break; case 'retry': $retry = substr($line, $i); @@ -64,6 +66,8 @@ break; } } + + $this->data = $data ?? ''; } public function getId(): string diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/CurlHttpClient.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/CurlHttpClient.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/CurlHttpClient.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/CurlHttpClient.php 2026-11-25 09:18:34.000000000 +0000 @@ -239,7 +239,8 @@ if (!\is_string($body)) { if (\is_resource($body)) { - $curlopts[\CURLOPT_READDATA] = $body; + // Not CURLOPT_READDATA: curl would then read streams such as php://temp through a FILE* that PHP creates once and that ignores later rewinds + $curlopts[\CURLOPT_READFUNCTION] = static fn ($ch, $fd, $length) => false !== ($data = fread($body, $length)) ? $data : ''; } else { $curlopts[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) { static $eof = false; @@ -443,10 +444,11 @@ if ($redirectHeaders && isset($location['authority'])) { // Authorization and Cookie headers MUST NOT follow except for the initial scheme and authority - $requestHeaders = $url['scheme'] === $redirectHeaders['scheme'] && $location['authority'] === $redirectHeaders['authority'] ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth']; - curl_setopt($ch, \CURLOPT_HTTPHEADER, $requestHeaders); + $redirectHeaders['current'] = $url['scheme'] === $redirectHeaders['scheme'] && $location['authority'] === $redirectHeaders['authority'] ? 'with_auth' : 'no_auth'; + curl_setopt($ch, \CURLOPT_HTTPHEADER, $redirectHeaders[$redirectHeaders['current']]); } elseif ($noContent && $redirectHeaders) { - curl_setopt($ch, \CURLOPT_HTTPHEADER, $redirectHeaders['with_auth']); + // A relative redirect stays on the origin of the previous request + curl_setopt($ch, \CURLOPT_HTTPHEADER, $redirectHeaders[$redirectHeaders['current'] ?? 'with_auth']); } $proxy = self::getProxyUrl($options['proxy'], $url); @@ -527,6 +529,7 @@ \CURLOPT_CERTINFO => 'capture_peer_cert_chain', \CURLOPT_USERAGENT => 'normalized_headers', \CURLOPT_REFERER => 'headers', + \CURLOPT_COOKIE => 'headers', // options used in CurlResponse \CURLOPT_NOPROGRESS => 'on_progress', \CURLOPT_PROGRESSFUNCTION => 'on_progress', @@ -558,6 +561,7 @@ \CURLOPT_PROTOCOLS, \CURLOPT_REDIR_PROTOCOLS, \CURLOPT_COOKIEFILE, + \CURLOPT_UNRESTRICTED_AUTH, \CURLINFO_REDIRECT_COUNT, ]; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/HttpClientTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/HttpClientTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/HttpClientTrait.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/HttpClientTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,8 +13,8 @@ use Symfony\Component\HttpClient\Exception\InvalidArgumentException; use Symfony\Component\HttpClient\Exception\TransportException; +use Symfony\Component\HttpClient\Internal\ArrayBodyCaster; use Symfony\Component\HttpClient\Internal\Dechunker; -use Symfony\Component\HttpClient\Response\StreamableInterface; use Symfony\Component\HttpClient\Response\StreamWrapper; use Symfony\Component\Mime\MimeTypes; use Symfony\Contracts\HttpClient\HttpClientInterface; @@ -179,6 +179,16 @@ // Validate and resolve URL $url = self::parseUrl($url, $options['query']); $url = self::resolveUrl($url, $baseUri, $defaultOptions['query'] ?? []); + + // Send the user info of the URL as an Authorization header, so that it never ends up in reported URLs + if (false !== $i = strrpos($url['authority'], '@')) { + if (!isset($options['normalized_headers']['authorization']) && !isset($options['auth_ntlm'])) { + $userinfo = explode(':', substr($url['authority'], 2, $i - 2), 2); + $options['normalized_headers']['authorization'] = ['Authorization: Basic '.base64_encode(rawurldecode($userinfo[0]).':'.rawurldecode($userinfo[1] ?? ''))]; + } + + $url['authority'] = '//'.substr($url['authority'], 1 + $i); + } } // Finalize normalization of options @@ -200,6 +210,12 @@ { $options['normalized_headers'] = self::normalizeHeaders($options['headers'] ?? []); + if ($options['extra']['skip_default_credentials'] ?? false) { + // Set by NoPrivateNetworkHttpClient on redirects to other origins, for the decorated client and the ones it decorates + $options['normalized_headers'] += ['authorization' => [], 'cookie' => []]; + $options += ['auth_basic' => null, 'auth_bearer' => null, 'auth_ntlm' => null]; + } + if ($defaultOptions['headers'] ?? false) { $options['normalized_headers'] += self::normalizeHeaders($defaultOptions['headers']); } @@ -259,6 +275,11 @@ } if ('auth_ntlm' === $name) { + if (null === $v) { + // Decorators can unset NTLM credentials without knowing if the decorated client supports NTLM + continue; + } + if (!\extension_loaded('curl')) { $msg = 'try installing the "curl" extension to use "%s" instead.'; } else { @@ -342,24 +363,13 @@ static $cookie; $streams = []; - array_walk_recursive($body, $caster = static function (&$v) use (&$caster, &$streams, &$cookie) { - if (\is_resource($v) || $v instanceof StreamableInterface) { - $cookie = hash('xxh128', $cookie ??= random_bytes(8), true); - $k = substr(strtr(base64_encode($cookie), '+/', '-_'), 0, -2); - $streams[$k] = $v instanceof StreamableInterface ? $v->toStream(false) : $v; - $v = $k; - } elseif (\is_object($v)) { - if ($vars = get_object_vars($v)) { - array_walk_recursive($vars, $caster); - $v = $vars; - } elseif ($v instanceof \Stringable) { - $v = (string) $v; - } else { - $v = []; - } - } + $body = ArrayBodyCaster::cast($body, static function ($stream) use (&$streams, &$cookie) { + $cookie = hash('xxh128', $cookie ??= random_bytes(8), true); + $k = substr(strtr(base64_encode($cookie), '+/', '-_'), 0, -2); + $streams[$k] = $stream; + + return $k; }); - $caster = null; if ('' === $body = http_build_query($body, '', '&')) { return ''; @@ -836,8 +846,10 @@ return $proxy; } - // Ignore HTTP_PROXY except on the CLI to work around httpoxy set of vulnerabilities - $proxy = $_SERVER['http_proxy'] ?? (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? $_SERVER['HTTP_PROXY'] ?? null : null) ?? $_SERVER['all_proxy'] ?? $_SERVER['ALL_PROXY'] ?? null; + // Ignore HTTP_PROXY except on the CLI to work around httpoxy set of vulnerabilities, and read it from + // the environment there, since HTTP workers that run on the CLI put request headers in $_SERVER + $httpProxy = \in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) ? $_ENV['HTTP_PROXY'] ?? getenv('HTTP_PROXY', true) : false; + $proxy = $_SERVER['http_proxy'] ?? (false !== $httpProxy ? $httpProxy : null) ?? $_SERVER['all_proxy'] ?? $_SERVER['ALL_PROXY'] ?? null; if ('https:' === $url['scheme']) { $proxy = $_SERVER['https_proxy'] ?? $_SERVER['HTTPS_PROXY'] ?? $proxy; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Internal/AmpBody.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Internal/AmpBody.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Internal/AmpBody.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Internal/AmpBody.php 2026-11-25 09:18:34.000000000 +0000 @@ -42,7 +42,7 @@ if (\is_resource($body)) { $this->offset = ftell($body); - $this->length = fstat($body)['size']; + $this->length = stream_get_meta_data($body)['seekable'] ? fstat($body)['size'] ?? -1 : -1; $this->body = new ResourceInputStream($body); } elseif (\is_string($body)) { $this->length = \strlen($body); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Internal/ArrayBodyCaster.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Internal/ArrayBodyCaster.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Internal/ArrayBodyCaster.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Internal/ArrayBodyCaster.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,46 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpClient\Internal; + +use Symfony\Component\HttpClient\Response\StreamableInterface; + +/** + * Casts the values of an array body the same way for all clients and decorators. + * + * @internal + */ +final class ArrayBodyCaster +{ + /** + * Turns objects into arrays of their properties or into strings, and streams into what $onStream returns. + * + * @param \Closure(resource): mixed $onStream Called with each stream, including the ones created from StreamableInterface values + */ + public static function cast(array $body, \Closure $onStream): array + { + array_walk_recursive($body, static function (&$v) use ($onStream) { + if (\is_resource($v) || $v instanceof StreamableInterface) { + $v = $onStream($v instanceof StreamableInterface ? $v->toStream(false) : $v); + } elseif (\is_object($v)) { + if ($vars = get_object_vars($v)) { + $v = self::cast($vars, $onStream); + } elseif ($v instanceof \Stringable) { + $v = (string) $v; + } else { + $v = []; + } + } + }); + + return $body; + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/NativeHttpClient.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/NativeHttpClient.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/NativeHttpClient.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/NativeHttpClient.php 2026-11-25 09:18:34.000000000 +0000 @@ -267,6 +267,9 @@ $url['authority'] = substr_replace($url['authority'], $ip, -\strlen($host) - \strlen($port), \strlen($host)); } + // the fragment is for the client only, but the full URL is sent to proxies + unset($url['fragment']); + return [self::createRedirectResolver($options, $url['scheme'], $authority, $proxy, $info, $onProgress), implode('', $url)]; }; @@ -440,6 +443,8 @@ $url['authority'] = substr_replace($url['authority'], $ip, -\strlen($host) - \strlen($port), \strlen($host)); } + unset($url['fragment']); + return implode('', $url); }; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/NoPrivateNetworkHttpClient.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/NoPrivateNetworkHttpClient.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/NoPrivateNetworkHttpClient.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/NoPrivateNetworkHttpClient.php 2026-11-25 09:18:34.000000000 +0000 @@ -25,6 +25,9 @@ /** * Decorator that blocks requests to private networks by default. * + * Behind an HTTP proxy, the proxy resolves the hosts of the requests itself, + * so it must block private destinations on its own. + * * @author Hallison Boaventura <hallisonboaventura@gmail.com> * @author Nicolas Grekas <p@tchwork.com> */ @@ -34,10 +37,12 @@ use HttpClientTrait; private array $defaultOptions = self::OPTIONS_DEFAULTS; + private array $configuredOptions = []; private HttpClientInterface $client; private ?array $subnets; private int $ipFlags; private \ArrayObject $dnsCache; + private array $noAuthOptions = ['auth_basic' => null, 'auth_bearer' => null]; /** * @param string|array|null $subnets String or array of subnets using CIDR notation that should be considered private. @@ -64,14 +69,36 @@ $this->client = $client; $this->subnets = null !== $subnets ? (array) $subnets : null; + + if (\FILTER_FLAG_IPV6 === $ipFlags) { + // Block IPv4-mapped addresses too, since they reach IPv4 hosts + $this->subnets[] = '::ffff:0:0/96'; + } + $this->ipFlags = $ipFlags; $this->dnsCache = new \ArrayObject(); + + try { + $client->withOptions(['auth_ntlm' => null]); + $this->noAuthOptions['auth_ntlm'] = null; + } catch (\InvalidArgumentException $e) { + // The decorated client doesn't support NTLM + } } public function request(string $method, string $url, array $options = []): ResponseInterface { + $givenOptions = $options; [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions, true); + // Pass only the options given to this decorator and the ones it needs, so that the decorated client applies its default options to the others + $options = array_intersect_key($options, $givenOptions + $this->configuredOptions + ['headers' => true, 'normalized_headers' => true, 'body' => true, 'resolve' => true, 'max_redirects' => true]); + + if (!isset(self::normalizeHeaders($givenOptions['headers'] ?? [])['accept'])) { + unset($options['normalized_headers']['accept']); + $options['headers'] = array_merge([], ...array_values($options['normalized_headers'])); + } + $redirectHeaders = parse_url($url['authority']); $redirectHeaders['scheme'] = $url['scheme']; $host = $redirectHeaders['host']; @@ -104,12 +131,15 @@ unset($options['query']); $options['max_redirects'] = 0; $redirectHeaders['with_auth'] = $redirectHeaders['no_auth'] = $options['headers']; + $bodyOffset = \is_resource($options['body']) && stream_get_meta_data($options['body'])['seekable'] ? ftell($options['body']) : false; if (isset($options['normalized_headers']['host']) || isset($options['normalized_headers']['authorization']) || isset($options['normalized_headers']['cookie'])) { $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], static fn ($h) => 0 !== stripos($h, 'Host:') && 0 !== stripos($h, 'Authorization:') && 0 !== stripos($h, 'Cookie:')); } - return new AsyncResponse($this->client, $method, $url, $options, static function (ChunkInterface $chunk, AsyncContext $context) use (&$method, &$options, $maxRedirects, &$redirectHeaders, $subnets, $ipFlags, $dnsCache): \Generator { + $noAuthOptions = $this->noAuthOptions; + + return new AsyncResponse($this->client, $method, $url, $options, static function (ChunkInterface $chunk, AsyncContext $context) use (&$method, &$options, $maxRedirects, &$redirectHeaders, $noAuthOptions, $subnets, $ipFlags, $dnsCache, $bodyOffset): \Generator { if (null !== $chunk->getError() || $chunk->isTimeout() || !$chunk->isFirst()) { yield $chunk; @@ -141,16 +171,23 @@ $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], $filterContentHeaders); $redirectHeaders['with_auth'] = array_filter($redirectHeaders['with_auth'], $filterContentHeaders); } + } elseif (false !== $bodyOffset && isset($options['body'])) { + fseek($options['body'], $bodyOffset); } // Authorization and Cookie headers MUST NOT follow except for the initial scheme, host and port $port = parse_url($url, \PHP_URL_PORT); - $options['headers'] = parse_url($url, \PHP_URL_SCHEME).':' === $redirectHeaders['scheme'] && $redirectHeaders['host'] === $host && ($redirectHeaders['port'] ?? null) === $port ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth']; + $sameOrigin = parse_url($url, \PHP_URL_SCHEME).':' === $redirectHeaders['scheme'] && $redirectHeaders['host'] === $host && ($redirectHeaders['port'] ?? null) === $port; + $options['headers'] = $sameOrigin ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth']; static $redirectCount = 0; $context->setInfo('redirect_count', ++$redirectCount); - $context->replaceRequest($method, $url, $options); + // The decorated client must not add its default credentials either + $context->replaceRequest($method, $url, $sameOrigin ? $options : [ + 'headers' => $options['headers'] + ['Authorization' => [], 'Cookie' => []], + 'extra' => ['skip_default_credentials' => true] + ($options['extra'] ?? []), + ] + $noAuthOptions + $options); if ($redirectCount >= $maxRedirects) { $context->passthru(); @@ -170,6 +207,7 @@ $clone = clone $this; $clone->client = $this->client->withOptions($options); $clone->defaultOptions = self::mergeDefaultOptions($options, $this->defaultOptions); + $clone->configuredOptions = $options + $this->configuredOptions; return $clone; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Response/CurlResponse.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Response/CurlResponse.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Response/CurlResponse.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Response/CurlResponse.php 2026-11-25 09:18:34.000000000 +0000 @@ -421,7 +421,7 @@ self::addResponseHeaders([substr($data, 0, -2)], $info, $headers); if (!str_starts_with($data, 'HTTP/')) { - if (0 === stripos($data, 'Location:')) { + if (null === $location && 0 === stripos($data, 'Location:')) { $location = trim(substr($data, 9, -2)); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Response/MockResponse.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Response/MockResponse.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Response/MockResponse.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Response/MockResponse.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,6 +15,7 @@ use Symfony\Component\HttpClient\Chunk\FirstChunk; use Symfony\Component\HttpClient\Exception\InvalidArgumentException; use Symfony\Component\HttpClient\Exception\TransportException; +use Symfony\Component\HttpClient\HttpClientTrait; use Symfony\Component\HttpClient\Internal\ClientState; use Symfony\Contracts\HttpClient\ResponseInterface; @@ -277,6 +278,21 @@ throw new TransportException($response->info['error']); } + if (!\array_key_exists('redirect_url', $info) && 300 <= $response->info['http_code'] && $response->info['http_code'] < 400 && null !== $location = $response->headers['location'][0] ?? null) { + $urlResolver = new class { + use HttpClientTrait { + parseUrl as public; + resolveUrl as public; + } + }; + + try { + $response->info['redirect_url'] = implode('', $urlResolver::resolveUrl($urlResolver::parseUrl($location), $urlResolver::parseUrl($response->info['url']))); + } catch (InvalidArgumentException) { + // Like the transports, ignore locations that are not valid URLs + } + } + if (!isset($response->info['total_time'])) { $response->info['total_time'] = microtime(true) - $response->info['start_time']; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Response/TraceableResponse.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Response/TraceableResponse.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Response/TraceableResponse.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Response/TraceableResponse.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,6 +15,7 @@ use Symfony\Component\HttpClient\Exception\ClientException; use Symfony\Component\HttpClient\Exception\RedirectionException; use Symfony\Component\HttpClient\Exception\ServerException; +use Symfony\Component\HttpClient\Internal\Canary; use Symfony\Component\HttpClient\TraceableHttpClient; use Symfony\Component\Stopwatch\StopwatchEvent; use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface; @@ -35,6 +36,8 @@ private ResponseInterface $response; private mixed $content; private ?StopwatchEvent $event; + // Declared after $response so that the event includes the time spent destructing it + private Canary $canary; public function __construct(HttpClientInterface $client, ResponseInterface $response, &$content, ?StopwatchEvent $event = null) { @@ -42,6 +45,11 @@ $this->response = $response; $this->content = &$content; $this->event = $event; + $this->canary = new Canary(static function () use ($event) { + if ($event?->isStarted()) { + $event->stop(); + } + }); } public function __serialize(): array @@ -54,17 +62,6 @@ throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); } - public function __destruct() - { - try { - unset($this->response); - } finally { - if ($this->event?->isStarted()) { - $this->event->stop(); - } - } - } - public function getStatusCode(): int { try { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/RetryableHttpClient.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/RetryableHttpClient.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/RetryableHttpClient.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/RetryableHttpClient.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpClient; use Psr\Log\LoggerInterface; +use Symfony\Component\HttpClient\Internal\ArrayBodyCaster; use Symfony\Component\HttpClient\Response\AsyncContext; use Symfony\Component\HttpClient\Response\AsyncResponse; use Symfony\Component\HttpClient\Retry\GenericRetryStrategy; @@ -81,7 +82,9 @@ return new AsyncResponse($this->client, $method, $url, $options); } - return new AsyncResponse($this->client, $method, $url, $options, function (ChunkInterface $chunk, AsyncContext $context) use ($method, $url, $options, $maxRetries, &$baseUris) { + $rewindBody = self::createBodyRewinder($options); + + return new AsyncResponse($this->client, $method, $url, $options, function (ChunkInterface $chunk, AsyncContext $context) use ($method, $url, $options, $maxRetries, &$baseUris, $rewindBody) { static $retryCount = 0; static $content = ''; static $firstChunk; @@ -142,6 +145,12 @@ } } + if (!$rewindBody()) { + yield from $this->passthru($context, $firstChunk, $content, $chunk); + + return; + } + $context->getResponse()->cancel(); $delay = $this->getDelayFromHeader($context->getHeaders()) ?? $this->strategy->getDelay($context, !$exception && $chunk->isLast() ? $content : null, $exception); @@ -179,6 +188,60 @@ return null; } + /** + * Returns a closure that rewinds the streams of the body, or that returns false when the body was already read and cannot be sent again. + */ + private static function createBodyRewinder(array &$options): \Closure + { + $body = $options['body'] ?? ''; + $read = false; + + if ($body instanceof \Generator) { + $options['body'] = static function () use ($body, &$read) { + $read = true; + + yield from $body; + }; + } elseif ($body instanceof \Closure && !(new \ReflectionFunction($body))->isGenerator()) { + $options['body'] = static function (int $size) use ($body, &$read) { + $read = true; + + return $body($size); + }; + } + + $streams = []; + $collect = static function ($stream) use (&$streams): void { + $streams[] = [$stream, ftell($stream), stream_get_meta_data($stream)['seekable']]; + }; + + if (\is_array($body)) { + ArrayBodyCaster::cast($body, $collect); + } elseif (\is_resource($body)) { + $collect($body); + } + + return static function () use (&$read, $streams): bool { + if ($read) { + return false; + } + + foreach ($streams as [$stream, $offset, $seekable]) { + if (false === $offset || !$seekable && ftell($stream) !== $offset) { + return false; + } + } + + foreach ($streams as [$stream, $offset, $seekable]) { + if ($seekable && 0 !== fseek($stream, $offset)) { + return false; + } + } + + return true; + }; + } + private function passthru(AsyncContext $context, ?ChunkInterface $firstChunk, string &$content, ChunkInterface $lastChunk): \Generator { $context->passthru(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/ScopingHttpClient.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/ScopingHttpClient.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/ScopingHttpClient.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/ScopingHttpClient.php 2026-11-25 09:18:34.000000000 +0000 @@ -32,6 +32,11 @@ private array $defaultOptionsByRegexp; private ?string $defaultRegexp; + /** + * @param array $defaultOptionsByRegexp The default options, indexed by the regexp that the URL of a request must match. + * A regexp should end with a "/", for example "https://api\.github\.com/", + * so that it doesn't match other hosts. + */ public function __construct(HttpClientInterface $client, array $defaultOptionsByRegexp, ?string $defaultRegexp = null) { $this->client = $client; @@ -45,7 +50,7 @@ public static function forBaseUri(HttpClientInterface $client, string $baseUri, array $defaultOptions = [], ?string $regexp = null): self { - $regexp ??= preg_quote(implode('', self::resolveUrl(self::parseUrl('.'), self::parseUrl($baseUri)))); + $regexp ??= preg_quote(self::removeUserinfo(implode('', self::resolveUrl(self::parseUrl('.'), self::parseUrl($baseUri))))); $defaultOptions['base_uri'] = $baseUri; @@ -92,7 +97,7 @@ } foreach ($this->defaultOptionsByRegexp as $regexp => $defaultOptions) { - if (preg_match("{{$regexp}}A", $url)) { + if (preg_match("{{$regexp}}A", self::removeUserinfo($url))) { if (null === $e || $regexp !== $this->defaultRegexp) { $options = self::mergeDefaultOptions($options, $defaultOptions, true); } @@ -132,4 +137,9 @@ return $clone; } + + private static function removeUserinfo(string $url): string + { + return preg_replace('{^([^:/?#]++://)[^/?#]*@}', '$1', $url); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/AmpHttpClientTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/AmpHttpClientTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/AmpHttpClientTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/AmpHttpClientTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -36,6 +36,19 @@ parent::testResolve(); } + /** + * @requires extension zlib + */ + public function testZlibStreamBody() + { + $client = $this->getHttpClient(__FUNCTION__); + $body = fopen('compress.zlib://data:application/gzip;base64,'.base64_encode(gzencode('foo=0123456789')), 'r'); + + $response = $client->request('POST', 'http://localhost:8057/post', ['body' => $body]); + + $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray()); + } + protected function getHttpClient(string $testCase): HttpClientInterface { return new AmpHttpClient(['verify_peer' => false, 'verify_host' => false, 'timeout' => 5]); @@ -55,4 +68,9 @@ { $this->markTestSkipped('A real proxy server would be needed.'); } + + public function testProxyDoesNotReceiveTheFragment() + { + $this->markTestSkipped('A real proxy server would be needed.'); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/CachingHttpClientTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,12 +15,30 @@ use Symfony\Component\HttpClient\CachingHttpClient; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; +use Symfony\Component\HttpClient\TraceableHttpClient; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpCache\Store; use Symfony\Contracts\HttpClient\ResponseInterface; class CachingHttpClientTest extends TestCase { + public function testStreamMixesResponsesFromTheCacheAndFromTheClient() + { + // MockHttpClient returns MockResponse instances, which stream() would take for responses from the cache + $mockClient = new TraceableHttpClient(new MockHttpClient([new MockResponse('through the cache'), new MockResponse('not cacheable')])); + $client = new CachingHttpClient($mockClient, new Store(sys_get_temp_dir().'/sf_http_cache')); + + $get = $client->request('GET', 'http://example.com/foo'); + $post = $client->request('POST', 'http://example.com/bar', ['body' => 'payload']); + + $contents = []; + foreach ($client->stream([$get, $post]) as $response => $chunk) { + $contents[$response->getInfo('url')] = ($contents[$response->getInfo('url')] ?? '').$chunk->getContent(); + } + + $this->assertSame(['http://example.com/foo' => 'through the cache', 'http://example.com/bar' => 'not cacheable'], $contents); + } + public function testRequestHeaders() { $options = [ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/Chunk/ServerSentEventTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/Chunk/ServerSentEventTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/Chunk/ServerSentEventTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/Chunk/ServerSentEventTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -78,6 +78,31 @@ $this->assertSame("<tag>\n\n <foo />\n\n\n</tag>", $sse->getData()); } + public function testParseEmptyEventType() + { + $rawData = <<<STR + event: + data: test + + STR; + + $sse = new ServerSentEvent($rawData); + $this->assertSame('message', $sse->getType()); + $this->assertSame('test', $sse->getData()); + } + + public function testParseEmptyFirstDataLine() + { + $rawData = <<<STR + data: + data: test + + STR; + + $sse = new ServerSentEvent($rawData); + $this->assertSame("\ntest", $sse->getData()); + } + public function testGetArrayData() { $this->assertSame(['foo' => 'bar'], (new ServerSentEvent(<<<STR diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/CurlHttpClientTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -17,6 +17,7 @@ use Symfony\Component\HttpClient\Exception\TransportException; use Symfony\Component\HttpClient\Internal\CurlClientState; use Symfony\Component\Process\Process; +use Symfony\Contracts\HttpClient\Test\TestHttpServer; /** * @requires extension curl @@ -40,6 +41,21 @@ return new CurlHttpClient(['verify_peer' => false, 'verify_host' => false], 6, 50); } + public function testPostRewoundResourceAgain() + { + $client = $this->getHttpClient(__FUNCTION__); + + $h = fopen('php://temp', 'w+'); + fwrite($h, 'foo=0123456789'); + + foreach ([1, 2] as $attempt) { + rewind($h); + $response = $client->request('POST', 'http://localhost:8057/post', ['body' => $h]); + + $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray(), "Request #{$attempt}"); + } + } + public function testTimeoutIsNotAFatalError() { if ('\\' === \DIRECTORY_SEPARATOR) { @@ -123,6 +139,36 @@ ]); } + public function testOverridingCookieUsingCurlOptions() + { + $httpClient = $this->getHttpClient(__FUNCTION__); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cannot set "CURLOPT_COOKIE" with "extra.curl", use option "headers" instead.'); + + $httpClient->request('GET', 'http://localhost:8057/', [ + 'extra' => [ + 'curl' => [ + \CURLOPT_COOKIE => 'foo=bar', + ], + ], + ]); + } + + public function testSendingCredentialsToOtherHostsUsingCurlOptions() + { + $httpClient = $this->getHttpClient(__FUNCTION__); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Cannot set "CURLOPT_UNRESTRICTED_AUTH" with "extra.curl".'); + + $httpClient->request('GET', 'http://localhost:8057/', [ + 'extra' => [ + 'curl' => [ + \CURLOPT_UNRESTRICTED_AUTH => true, + ], + ], + ]); + } + public function testOverridingHttpMethodUsingCurlOptions() { $httpClient = $this->getHttpClient(__FUNCTION__); @@ -179,6 +225,10 @@ public function testProxyFromProcessEnvIsNotUsed() { + if ('\\' === \DIRECTORY_SEPARATOR) { + $this->markTestSkipped('http_proxy and HTTP_PROXY are the same environment variable on Windows.'); + } + $client = $this->getHttpClient(__FUNCTION__); // Only curl reads the process environment, and it must not do so behind our back @@ -273,6 +323,15 @@ self::assertStringNotContainsString('Re-using existing connection', $response->getInfo('debug')); } + public function testAuthNtlmWinsOverUserinfo() + { + $client = $this->getHttpClient(__FUNCTION__); + $response = $client->request('GET', 'http://foo:bar@127.0.0.1:8057/', ['auth_ntlm' => 'user:pass']); + + $this->assertMatchesRegularExpression('/^NTLM [^ ,]++$/', $response->toArray()['HTTP_AUTHORIZATION']); + $this->assertSame('http://127.0.0.1:8057/', $response->getInfo('url')); + } + public function testNtlmStateNotMutatedByNonNtlmRequest() { // A plain (non-NTLM) request must not touch the NTLM origin map. This guards against @@ -417,6 +476,41 @@ } /** + * @dataProvider provideRelativeRedirectsToGet + */ + public function testRelativeRedirectToGetDropsCredentialsOnOtherOrigins(string $url, string $expectedUrl, bool $expectCredentials) + { + if (!str_contains(file_get_contents(\dirname((new \ReflectionClass(TestHttpServer::class))->getFileName()).'/Fixtures/web/index.php'), "case '/custom':")) { + $this->markTestSkipped('The installed symfony/http-client-contracts has no "/custom" route.'); + } + + $p = TestHttpServer::start(8067); + + try { + $client = $this->getHttpClient(__FUNCTION__); + $response = $client->request('GET', $url, [ + 'auth_bearer' => 'foo', + 'headers' => ['Cookie' => 'foo=bar'], + ]); + $body = $response->toArray(); + } finally { + $p->stop(); + } + + $this->assertSame($expectedUrl, $response->getInfo('url')); + $this->assertSame($expectCredentials ? ['Bearer foo', 'foo=bar'] : [null, null], [$body['HTTP_AUTHORIZATION'] ?? null, $body['HTTP_COOKIE'] ?? null]); + } + + public static function provideRelativeRedirectsToGet(): iterable + { + $seeOther = 'custom?'.http_build_query(['status' => 303, 'headers' => ['Location: /']]); + + yield 'same origin' => ['http://localhost:8057/'.$seeOther, 'http://localhost:8057/', true]; + yield 'same origin with user info' => ['http://foo:bar@localhost:8057/'.$seeOther, 'http://localhost:8057/', true]; + yield 'other origin' => ['http://localhost:8057/custom?'.http_build_query(['status' => 302, 'headers' => ['Location: http://localhost:8067/'.$seeOther]]), 'http://localhost:8067/', false]; + } + + /** * @group integration */ public function testMaxConnections() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/Fixtures/proxy-url/index.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/Fixtures/proxy-url/index.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/Fixtures/proxy-url/index.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/Fixtures/proxy-url/index.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,42 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +if ('cli-server' !== \PHP_SAPI) { + // safe guard against unwanted execution + throw new \Exception("You cannot run this script directly, it's a fixture for HttpClientTraitTest."); +} + +$parent = __DIR__; +while (!@file_exists($parent.'/vendor/autoload.php')) { + if (!@file_exists($parent)) { + // open_basedir restriction in effect + break; + } + if ($parent === dirname($parent)) { + echo "vendor/autoload.php not found\n"; + exit(1); + } + + $parent = dirname($parent); +} + +require $parent.'/vendor/autoload.php'; + +$client = new class() { + use Symfony\Component\HttpClient\HttpClientTrait; + + public function getProxyUrlFor(string $scheme): ?string + { + return self::getProxyUrl(null, ['scheme' => $scheme]); + } +}; + +echo json_encode(['sapi' => \PHP_SAPI, 'http' => $client->getProxyUrlFor('http:'), 'https' => $client->getProxyUrlFor('https:')]); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,7 +11,9 @@ namespace Symfony\Component\HttpClient\Tests; +use Psr\Log\LoggerAwareInterface; use Symfony\Bridge\PhpUnit\DnsMock; +use Symfony\Component\HttpClient\CurlHttpClient; use Symfony\Component\HttpClient\Exception\ClientException; use Symfony\Component\HttpClient\Exception\InvalidArgumentException; use Symfony\Component\HttpClient\Exception\TimeoutException; @@ -31,7 +33,7 @@ /* Tests for HTTP2 Push need a recent version of both PHP and curl. This docker command should run them: docker run -it --rm -v $(pwd):/app -v /path/to/vulcain:/usr/local/bin/vulcain -w /app php:7.3-alpine ./phpunit src/Symfony/Component/HttpClient --filter Push -The vulcain binary can be found at https://github.com/symfony/binary-utils/releases/download/v0.1/vulcain_0.1.3_Linux_x86_64.tar.gz - see https://github.com/dunglas/vulcain for source +The vulcain binary can be found at https://github.com/symfony-tools/binary-utils/releases/download/v0.1/vulcain_0.1.3_Linux_x86_64.tar.gz - see https://github.com/dunglas/vulcain for source */ abstract class HttpClientTestCase extends BaseHttpClientTestCase @@ -356,25 +358,28 @@ $response = $client->request('GET', 'http://localhost:8057/', ['max_duration' => 1]); $time = hrtime(true); - $response->getInfo('pause_handler')(3); + // The pause outlasts max_duration by far, so that a slow machine still sees max_duration first + $response->getInfo('pause_handler')(30); try { $response->getStatusCode(); $this->fail(TransportException::class.' expected'); } catch (TransportException $e) { + $duration = (hrtime(true) - $time) / 1E9; $this->assertSame('Max duration was reached for "http://localhost:8057/".', $e->getMessage()); } - $this->assertGreaterThanOrEqual(0.9, (hrtime(true) - $time) / 1E9); - $this->assertLessThan(2.5, (hrtime(true) - $time) / 1E9); + $this->assertGreaterThanOrEqual(0.9, $duration); + $this->assertLessThan(30, $duration); } public function testTransferAfterPauseCountsTowardMaxDuration() { $client = $this->getHttpClient(__FUNCTION__); - $response = $client->request('GET', 'http://localhost:8057/timeout-header', ['max_duration' => 1]); + $response = $client->request('GET', 'http://localhost:8057/timeout-long', ['max_duration' => 1.5]); - $response->getInfo('pause_handler')(0.8); + // The headers come after 1s, which is less than max_duration but far more than the 0.1s left after the pause + $response->getInfo('pause_handler')(1.4); try { $response->getStatusCode(); @@ -382,6 +387,9 @@ } catch (TransportException $e) { $this->assertNotInstanceOf(TimeoutException::class, $e); } + + // The test server handles requests one by one, so wait until the 1s sleep is over before the next test + $this->assertSame(200, $client->request('GET', 'http://localhost:8057/')->getStatusCode()); } /** @@ -646,6 +654,17 @@ $this->expectNotToPerformAssertions(); } + public function testPipeBody() + { + $process = proc_open([\PHP_BINARY, '-r', 'echo "foo=0123456789";'], [1 => ['pipe', 'w']], $pipes); + $client = $this->getHttpClient(__FUNCTION__); + + $response = $client->request('POST', 'http://localhost:8057/post', ['body' => $pipes[1]]); + + $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray()); + proc_close($process); + } + public function testMisspelledScheme() { $httpClient = $this->getHttpClient(__FUNCTION__); @@ -742,6 +761,65 @@ $this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url')); } + public function testNoPrivateNetworkWithUserinfoAndRedirect() + { + $client = $this->getHttpClient(__FUNCTION__); + $client = new NoPrivateNetworkHttpClient($client, '104.26.14.6/32'); + $response = $client->request('GET', 'http://foo:bar@localhost:8057/302/relative'); + + $this->assertSame('foo', $response->toArray()['PHP_AUTH_USER']); + $this->assertSame('http://localhost:8057/', $response->getInfo('url')); + } + + public function testUserinfoFollowsRedirectsToTheSameOriginOnly() + { + $client = $this->getHttpClient(__FUNCTION__); + + foreach ([$client, new NoPrivateNetworkHttpClient($client, '104.26.14.6/32')] as $client) { + // "/301" redirects to another origin when it gets the credentials, and "/302" redirects back when it doesn't + $response = $client->request('GET', 'http://foo:bar@localhost:8057/301'); + + $this->assertSame('foo', $response->toArray()['PHP_AUTH_USER'] ?? null); + $this->assertSame('http://localhost:8057/', $response->getInfo('url')); + $this->assertSame(2, $response->getInfo('redirect_count')); + } + } + + public function testUserinfoIsNotReported() + { + $client = $this->getHttpClient(__FUNCTION__); + $logger = new TestLogger(); + + if ($client instanceof LoggerAwareInterface) { + $client->setLogger($logger); + } + + $progressInfo = []; + $response = $client->request('GET', 'http://foo:bar@localhost:8057/302/relative', [ + 'on_progress' => static function (int $dlNow, int $dlSize, array $info) use (&$progressInfo) { + $progressInfo[] = [$info['url'] ?? null, $info['original_url'] ?? null, $info['redirect_url'] ?? null]; + }, + ]); + + $this->assertSame('foo', $response->toArray()['PHP_AUTH_USER']); + $this->assertSame('http://localhost:8057/', $response->getInfo('url')); + $this->assertSame('http://localhost:8057/302/relative', $response->getInfo('original_url')); + + $response = $client->request('GET', 'http://foo:bar@localhost:8057/302/relative', ['max_redirects' => 0]); + + $this->assertSame(302, $response->getStatusCode()); + $this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url')); + + try { + $client->request('GET', 'http://foo:bar@localhost:8057/404')->getContent(); + $this->fail(ClientException::class.' expected'); + } catch (ClientException $e) { + $this->assertSame('HTTP/1.1 404 Not Found returned for "http://localhost:8057/404".', $e->getMessage()); + } + + $this->assertStringNotContainsString('foo:bar', json_encode([$progressInfo, $logger->logs])); + } + public function testNoPrivateNetworkStream() { $client = $this->getHttpClient(__FUNCTION__); @@ -777,6 +855,44 @@ $this->assertTrue($chunk->isLast()); } + public function testProxyDoesNotReceiveTheFragment() + { + $client = $this->getHttpClient(__FUNCTION__); + + $response = $client->request('GET', 'http://localhost:8057/#fragment', [ + 'proxy' => 'http://localhost:8057', + ]); + $this->assertSame('http://localhost:8057/', $response->toArray()['REQUEST_URI']); + + // libcurl < 7.62 removes the fragment from CURLINFO_EFFECTIVE_URL + $fragment = $client instanceof CurlHttpClient && 0x073E00 > curl_version()['version_number'] ? '' : '#fragment'; + $this->assertSame('http://localhost:8057/'.$fragment, $response->getInfo('url')); + + $response = $client->request('GET', 'http://localhost:8057/302?location=http://localhost:8057/%23fragment', [ + 'proxy' => 'http://localhost:8057', + ]); + $this->assertSame('http://localhost:8057/', $response->toArray()['REQUEST_URI']); + } + + public function testRedirectToTheFirstLocation() + { + $client = $this->getHttpClient(__FUNCTION__); + + $response = $client->request('GET', 'http://localhost:8057/302/two-locations', ['max_redirects' => 0]); + + if (!isset($response->getHeaders(false)['location'])) { + $this->markTestSkipped('The test server of symfony/http-client-contracts has no "/302/two-locations" route.'); + } + + $this->assertSame(302, $response->getStatusCode()); + $this->assertSame('http://localhost:8057/', $response->getInfo('redirect_url')); + + $response = $client->request('GET', 'http://localhost:8057/302/two-locations'); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertSame('http://localhost:8057/', $response->getInfo('url')); + } + public function testNoRedirectWithInvalidLocation() { $client = $this->getHttpClient(__FUNCTION__); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/HttpClientTraitTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,6 +15,8 @@ use Symfony\Component\HttpClient\Exception\InvalidArgumentException; use Symfony\Component\HttpClient\HttpClient; use Symfony\Component\HttpClient\HttpClientTrait; +use Symfony\Component\Process\PhpExecutableFinder; +use Symfony\Component\Process\Process; use Symfony\Contracts\HttpClient\HttpClientInterface; class HttpClientTraitTest extends TestCase @@ -340,6 +342,16 @@ self::prepareRequest('POST', 'http://example.com', ['auth_bearer' => 'foo', 'auth_basic' => 'foo:bar'], HttpClientInterface::OPTIONS_DEFAULTS); } + public function testNullAuthNtlmOptionWithoutNtlmSupport() + { + [, $options] = self::prepareRequest('GET', 'http://example.com', ['auth_ntlm' => null], HttpClientInterface::OPTIONS_DEFAULTS); + $this->assertNull($options['auth_ntlm']); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Option "auth_ntlm" is not supported by'); + self::prepareRequest('GET', 'http://example.com', ['auth_ntlm' => 'foo:bar'], HttpClientInterface::OPTIONS_DEFAULTS); + } + public function testSetJSONAndBodyOptions() { $this->expectException(InvalidArgumentException::class); @@ -364,6 +376,40 @@ $this->assertSame('Authorization: Basic '.$result, $options['normalized_headers']['authorization'][0]); } + public function testPrepareRequestMovesUserinfoToAuthBasic() + { + [$url, $options] = self::prepareRequest('GET', 'http://foo:bar%3Dbar@example.com/', ['proxy' => 'http://user:pass@proxy.example:3128'], HttpClientInterface::OPTIONS_DEFAULTS); + $this->assertSame('http://example.com/', implode('', $url)); + $this->assertSame(['Authorization: Basic '.base64_encode('foo:bar=bar')], $options['normalized_headers']['authorization']); + $this->assertContains('Authorization: Basic '.base64_encode('foo:bar=bar'), $options['headers']); + $this->assertSame('http://user:pass@proxy.example:3128', $options['proxy']); + + [$url, $options] = self::prepareRequest('GET', 'http://foo@example.com/', [], HttpClientInterface::OPTIONS_DEFAULTS); + $this->assertSame('http://example.com/', implode('', $url)); + $this->assertSame(['Authorization: Basic '.base64_encode('foo:')], $options['normalized_headers']['authorization']); + + [, $defaults] = self::prepareRequest(null, null, ['base_uri' => 'http://foo:bar@example.com/api/'], HttpClientInterface::OPTIONS_DEFAULTS); + [$url, $options] = self::prepareRequest('GET', 'users', [], $defaults); + $this->assertSame('http://example.com/api/users', implode('', $url)); + $this->assertSame(['Authorization: Basic '.base64_encode('foo:bar')], $options['normalized_headers']['authorization']); + + [$url, $options] = self::prepareRequest('GET', 'http://foo:bar@example.com/', ['auth_basic' => 'baz:qux'], HttpClientInterface::OPTIONS_DEFAULTS); + $this->assertSame('http://example.com/', implode('', $url)); + $this->assertSame(['Authorization: Basic '.base64_encode('baz:qux')], $options['normalized_headers']['authorization']); + + [$url, $options] = self::prepareRequest('GET', 'http://foo:bar@example.com/', ['auth_bearer' => 'baz'], HttpClientInterface::OPTIONS_DEFAULTS); + $this->assertSame('http://example.com/', implode('', $url)); + $this->assertSame(['Authorization: Bearer baz'], $options['normalized_headers']['authorization']); + + [$url, $options] = self::prepareRequest('GET', 'http://foo:bar@example.com/', ['headers' => ['Authorization' => 'Custom baz']], HttpClientInterface::OPTIONS_DEFAULTS); + $this->assertSame('http://example.com/', implode('', $url)); + $this->assertSame(['Authorization: Custom baz'], $options['normalized_headers']['authorization']); + + [$url, $options] = self::prepareRequest('GET', 'http://foo:bar@example.com/', ['auth_ntlm' => 'baz:qux'], HttpClientInterface::OPTIONS_DEFAULTS, true); + $this->assertSame('http://example.com/', implode('', $url)); + $this->assertArrayNotHasKey('authorization', $options['normalized_headers']); + } + public static function provideFingerprints() { foreach (['md5', 'sha1', 'sha256'] as $algo) { @@ -397,4 +443,83 @@ $this->normalizePeerFingerprint($fingerprint); } + + /** + * @dataProvider provideProxyUrlFromEnvironment + */ + public function testProxyUrlFromEnvironment(?string $expected, string $scheme, array $server, array $env, array $getenv = []) + { + $backup = []; + + foreach (['http_proxy', 'HTTP_PROXY', 'https_proxy', 'HTTPS_PROXY', 'all_proxy', 'ALL_PROXY'] as $name) { + $backup[$name] = [$_SERVER[$name] ?? null, $_ENV[$name] ?? null, getenv($name, true)]; + unset($_SERVER[$name], $_ENV[$name]); + putenv($name); + } + + try { + foreach ($server as $name => $value) { + $_SERVER[$name] = $value; + } + foreach ($env as $name => $value) { + $_ENV[$name] = $value; + } + foreach ($getenv as $name => $value) { + putenv($name.'='.$value); + } + + $this->assertSame($expected, self::getProxyUrl(null, ['scheme' => $scheme])); + } finally { + foreach ($backup as $name => [$serverValue, $envValue, $getenvValue]) { + unset($_SERVER[$name], $_ENV[$name]); + + if (null !== $serverValue) { + $_SERVER[$name] = $serverValue; + } + if (null !== $envValue) { + $_ENV[$name] = $envValue; + } + + false === $getenvValue ? putenv($name) : putenv($name.'='.$getenvValue); + } + } + } + + public static function provideProxyUrlFromEnvironment(): iterable + { + yield 'HTTP_PROXY only in $_SERVER' => [null, 'http:', ['HTTP_PROXY' => 'http://header.example:3128'], []]; + yield 'HTTP_PROXY only in $_SERVER, https' => [null, 'https:', ['HTTP_PROXY' => 'http://header.example:3128'], []]; + yield 'HTTP_PROXY from getenv()' => ['http://env.example:3128', 'http:', [], [], ['HTTP_PROXY' => 'http://env.example:3128']]; + yield 'HTTP_PROXY from getenv(), https' => ['http://env.example:3128', 'https:', [], [], ['HTTP_PROXY' => 'http://env.example:3128']]; + yield 'HTTP_PROXY from $_ENV' => ['http://env.example:3128', 'http:', [], ['HTTP_PROXY' => 'http://env.example:3128']]; + yield 'HTTP_PROXY from getenv() over $_SERVER' => ['http://env.example:3128', 'http:', ['HTTP_PROXY' => 'http://header.example:3128'], [], ['HTTP_PROXY' => 'http://env.example:3128']]; + yield 'http_proxy' => ['http://lower.example:3128', 'http:', ['http_proxy' => 'http://lower.example:3128'], []]; + yield 'http_proxy over HTTP_PROXY' => ['http://lower.example:3128', 'http:', ['http_proxy' => 'http://lower.example:3128'], [], ['HTTP_PROXY' => 'http://env.example:3128']]; + yield 'https_proxy' => ['http://secure.example:3128', 'https:', ['https_proxy' => 'http://secure.example:3128'], []]; + yield 'HTTPS_PROXY' => ['http://secure.example:3128', 'https:', ['HTTPS_PROXY' => 'http://secure.example:3128'], []]; + yield 'https_proxy is not used for http' => [null, 'http:', ['https_proxy' => 'http://secure.example:3128'], []]; + yield 'all_proxy' => ['http://all.example:3128', 'http:', ['all_proxy' => 'http://all.example:3128'], []]; + yield 'ALL_PROXY' => ['http://all.example:3128', 'https:', ['ALL_PROXY' => 'http://all.example:3128'], []]; + yield 'all_proxy when HTTP_PROXY is only in $_SERVER' => ['http://all.example:3128', 'http:', ['all_proxy' => 'http://all.example:3128', 'HTTP_PROXY' => 'http://header.example:3128'], []]; + } + + public function testHttpProxyIsIgnoredOnOtherSapis() + { + $finder = new PhpExecutableFinder(); + $env = ['HTTP_PROXY' => 'http://env.example:3128', 'http_proxy' => false, 'https_proxy' => false, 'HTTPS_PROXY' => false, 'all_proxy' => false, 'ALL_PROXY' => false]; + $process = new Process(array_merge([$finder->find(false)], $finder->findArguments(), ['-dopcache.enable=0', '-dvariables_order=EGPCS', '-S', '127.0.0.1:8098']), __DIR__.'/Fixtures/proxy-url', $env); + $process->start(); + + try { + do { + usleep(50000); + } while ($process->isRunning() && !@fopen('http://127.0.0.1:8098', 'r')); + + $context = stream_context_create(['http' => ['header' => 'Proxy: http://header.example:3128']]); + + $this->assertSame('{"sapi":"cli-server","http":null,"https":null}', file_get_contents('http://127.0.0.1:8098/', false, $context)); + } finally { + $process->stop(); + } + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/NoPrivateNetworkHttpClientTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,12 +13,17 @@ use PHPUnit\Framework\TestCase; use Symfony\Bridge\PhpUnit\DnsMock; +use Symfony\Component\HttpClient\CachingHttpClient; +use Symfony\Component\HttpClient\CurlHttpClient; use Symfony\Component\HttpClient\Exception\InvalidArgumentException; use Symfony\Component\HttpClient\Exception\TransportException; use Symfony\Component\HttpClient\MockHttpClient; use Symfony\Component\HttpClient\NativeHttpClient; use Symfony\Component\HttpClient\NoPrivateNetworkHttpClient; use Symfony\Component\HttpClient\Response\MockResponse; +use Symfony\Component\HttpClient\ScopingHttpClient; +use Symfony\Component\HttpClient\TraceableHttpClient; +use Symfony\Component\HttpKernel\HttpCache\StoreInterface; use Symfony\Contracts\HttpClient\Test\TestHttpServer; class NoPrivateNetworkHttpClientTest extends TestCase @@ -43,9 +48,12 @@ ['10.0.0.1', '10.0.0.1', true], ['fc00::1', 'fc00::1/120', true], ['fc00::1', 'fc00::1', true], + ['::ffff:127.0.0.1', ['127.0.0.0/8', '::1/128'], true], + ['::ffff:7f00:1', ['127.0.0.0/8', '::1/128'], true], ['172.16.0.1', ['10.0.0.0/8', '192.168.0.0/16'], false], ['fc00::1', ['fe80::/10', '::ffff:0:0/96'], false], + ['::ffff:172.16.0.1', ['127.0.0.0/8', '::1/128'], false], // public ['104.26.14.6', null, false], @@ -66,6 +74,8 @@ // weird scenarios (e.g.: when trying to match ipv4 address on ipv6 subnet) yield ['10.0.0.1', 'fc00::/7', true]; yield ['fc00::1', '10.0.0.0/8', true]; + yield ['::ffff:10.0.0.1', 'fc00::/7', true]; + yield ['::ffff:104.26.14.6', ['fc00::/7', '::1/128'], true]; } /** @@ -167,6 +177,29 @@ $this->assertSame([['example.com' => '104.26.14.6'], ['example.com' => '104.26.14.6']], $resolved); } + /** + * @dataProvider getIpv4MappedRequestData + */ + public function testIpv4MappedAddressIsCheckedAgainstCustomIpv4Subnets(string $url, array $options, string $message) + { + $client = new NoPrivateNetworkHttpClient(new MockHttpClient([ + new MockResponse('', ['http_code' => 302, 'redirect_url' => 'http://[::ffff:127.0.0.1]/']), + new MockResponse('internal'), + ]), ['10.0.0.0/8', '127.0.0.0/8', 'fc00::/7', '::1/128']); + + $this->expectException(TransportException::class); + $this->expectExceptionMessage($message); + + $client->request('GET', $url, $options)->getContent(); + } + + public static function getIpv4MappedRequestData(): iterable + { + yield 'url' => ['http://[::ffff:127.0.0.1]/', [], 'Host "[::ffff:127.0.0.1]" is blocked for "http://[::ffff:127.0.0.1]/".']; + yield 'resolve option' => ['http://example.com/', ['resolve' => ['example.com' => '::ffff:127.0.0.1']], 'Host "example.com" is blocked for "http://example.com/".']; + yield 'redirect' => ['http://104.26.14.6/', [], 'Host "[::ffff:127.0.0.1]" is blocked for "http://[::ffff:127.0.0.1]/".']; + } + public function testCustomOnProgressCallback() { $ipAddr = '104.26.14.6'; @@ -222,6 +255,107 @@ $this->assertArrayNotHasKey('cookie', $headers); } + /** + * @requires extension openssl + */ + public function testRedirectToADifferentSchemeDropsTheDefaultCredentialsOfTheDecoratedClient() + { + TestRedirectServer::start(); + $client = new NoPrivateNetworkHttpClient(new NativeHttpClient([ + 'auth_bearer' => 'foo', + 'headers' => ['Cookie' => 'a=b', 'X-Custom' => 'kept'], + ]), '10.0.0.0/8'); + + $response = $client->request('GET', 'https://127.0.0.1:8059/', [ + 'verify_peer' => false, + 'verify_host' => false, + ]); + $headers = $response->toArray(); + + $this->assertSame('http://127.0.0.1:8059/', $response->getInfo('url')); + $this->assertSame('kept', $headers['x-custom']); + $this->assertArrayNotHasKey('authorization', $headers); + $this->assertArrayNotHasKey('cookie', $headers); + } + + public function testRedirectToAnotherOriginDropsDefaultCredentials() + { + $requests = []; + $mockClient = new MockHttpClient(function (string $method, string $url, array $options) use (&$requests) { + $requests[] = [$url, $options['normalized_headers']['authorization'][0] ?? null, $options['normalized_headers']['cookie'][0] ?? null, $options['auth_ntlm'] ?? null]; + + switch (\count($requests) % 4) { + case 1: return new MockResponse('', ['http_code' => 302, 'redirect_url' => 'https://104.26.14.6/same-origin']); + case 2: return new MockResponse('', ['http_code' => 302, 'redirect_url' => 'https://104.26.14.7/other-origin']); + case 3: return new MockResponse('', ['http_code' => 302, 'redirect_url' => 'https://104.26.14.6/back']); + default: return new MockResponse('OK'); + } + }); + + $client = new NoPrivateNetworkHttpClient($mockClient->withOptions([ + 'auth_basic' => 'foo:bar', + 'headers' => ['Cookie' => 'a=b'], + 'auth_ntlm' => 'foo:bar', + ])); + $client->request('GET', 'https://104.26.14.6/')->getContent(); + + $client = (new NoPrivateNetworkHttpClient($mockClient))->withOptions([ + 'auth_bearer' => 'foo', + 'headers' => ['Cookie' => 'a=b'], + ]); + $client->request('GET', 'https://104.26.14.6/')->getContent(); + + $client = new NoPrivateNetworkHttpClient(new TraceableHttpClient($mockClient->withOptions(['headers' => ['Authorization' => 'Bearer foo']]))); + $client->request('GET', 'https://104.26.14.6/', ['auth_ntlm' => 'foo:bar'])->getContent(); + + $this->assertSame([ + ['https://104.26.14.6/', 'Authorization: Basic Zm9vOmJhcg==', 'Cookie: a=b', 'foo:bar'], + ['https://104.26.14.6/same-origin', 'Authorization: Basic Zm9vOmJhcg==', 'Cookie: a=b', 'foo:bar'], + ['https://104.26.14.7/other-origin', null, null, null], + ['https://104.26.14.6/back', 'Authorization: Basic Zm9vOmJhcg==', 'Cookie: a=b', 'foo:bar'], + ['https://104.26.14.6/', 'Authorization: Bearer foo', 'Cookie: a=b', null], + ['https://104.26.14.6/same-origin', 'Authorization: Bearer foo', 'Cookie: a=b', null], + ['https://104.26.14.7/other-origin', null, null, null], + ['https://104.26.14.6/back', 'Authorization: Bearer foo', 'Cookie: a=b', null], + ['https://104.26.14.6/', 'Authorization: Bearer foo', null, 'foo:bar'], + ['https://104.26.14.6/same-origin', 'Authorization: Bearer foo', null, 'foo:bar'], + ['https://104.26.14.7/other-origin', null, null, null], + ['https://104.26.14.6/back', 'Authorization: Bearer foo', null, 'foo:bar'], + ], $requests); + } + + public function testRedirectToAnotherOriginDropsDefaultCredentialsBehindOtherDecorators() + { + $requests = []; + $mockClient = new MockHttpClient(function (string $method, string $url, array $options) use (&$requests) { + $requests[] = [$url, $options['normalized_headers']['authorization'][0] ?? null, $options['normalized_headers']['cookie'][0] ?? null, $options['auth_ntlm'] ?? null]; + + return 1 === \count($requests) % 2 ? new MockResponse('', ['http_code' => 302, 'redirect_url' => 'https://104.26.14.7/other-origin']) : new MockResponse('OK'); + }); + $mockClient = $mockClient->withOptions([ + 'auth_bearer' => 'foo', + 'headers' => ['Cookie' => 'a=b'], + 'auth_ntlm' => 'foo:bar', + ]); + + $decorators = [ + new ScopingHttpClient($mockClient, ['https://104\.26\.14\.7/' => ['headers' => ['X-Scope' => 'b']]]), + new CachingHttpClient($mockClient, $this->createMock(StoreInterface::class)), + new NoPrivateNetworkHttpClient($mockClient), + new NoPrivateNetworkHttpClient(new ScopingHttpClient($mockClient, ['https://104\.26\.14\.7/' => []])), + ]; + + foreach ($decorators as $decorator) { + $client = new NoPrivateNetworkHttpClient($decorator); + $client->request('GET', 'https://104.26.14.6/', ['extra' => ['no_cache' => true]])->getContent(); + } + + $this->assertSame(array_merge(...array_fill(0, 4, [ + ['https://104.26.14.6/', 'Authorization: Bearer foo', 'Cookie: a=b', 'foo:bar'], + ['https://104.26.14.7/other-origin', null, null, null], + ])), $requests); + } + public function testRedirectDoesNotRepeatTheQueryOption() { TestHttpServer::start(); @@ -234,6 +368,81 @@ $this->assertSame('/', $response->toArray()['REQUEST_URI']); } + public function testRedirectSendsTheStreamBodyAgain() + { + TestHttpServer::start(); + + $clients = ['native' => new NativeHttpClient()]; + if (\extension_loaded('curl')) { + $clients['curl'] = new CurlHttpClient(); + } + + foreach ($clients as $type => $client) { + $body = fopen('php://temp', 'r+'); + fwrite($body, 'skipped foo=0123456789'); + fseek($body, 8); + + $client = new NoPrivateNetworkHttpClient($client, '10.0.0.0/8'); + $response = $client->request('POST', 'http://localhost:8057/307', ['body' => $body]); + + $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray(), $type); + } + } + + /** + * @requires extension openssl + */ + public function testDecoratedClientAppliesItsDefaultPeerFingerprint() + { + TestRedirectServer::start(); + $client = new NoPrivateNetworkHttpClient(new NativeHttpClient(['peer_fingerprint' => ['sha256' => str_repeat('0', 64)]]), '10.0.0.0/8'); + + $this->expectException(TransportException::class); + $this->expectExceptionMessage('peer_fingerprint match failure'); + + $client->request('GET', 'https://127.0.0.1:8059/', ['verify_peer' => false, 'verify_host' => false])->getHeaders(); + } + + public function testDecoratedClientAppliesItsDefaultOptions() + { + $requests = []; + $mockClient = new MockHttpClient(function (string $method, string $url, array $options) use (&$requests) { + $requests[] = [$url, $options['cafile'] ?? null, $options['proxy'] ?? null, $options['timeout'], $options['max_redirects'], $options['normalized_headers']['accept']]; + + return 1 === \count($requests) % 2 ? new MockResponse('', ['http_code' => 302, 'redirect_url' => 'https://104.26.14.7/']) : new MockResponse('OK'); + }); + + $client = new NoPrivateNetworkHttpClient($mockClient->withOptions([ + 'cafile' => '/path/to/ca.pem', + 'proxy' => 'http://proxy.example:3128', + 'timeout' => 7, + 'headers' => ['Accept' => 'application/json'], + ])); + $client->request('GET', 'https://104.26.14.6/')->getContent(); + + $client = new NoPrivateNetworkHttpClient(ScopingHttpClient::forBaseUri($mockClient, 'https://104.26.14.6/', ['cafile' => '/path/to/ca.pem'])); + $client->request('GET', 'https://104.26.14.6/')->getContent(); + + $progress = false; + $client = (new NoPrivateNetworkHttpClient($mockClient))->withOptions([ + 'max_redirects' => 0, + 'user_data' => 'foo', + 'on_progress' => static function () use (&$progress) { $progress = true; }, + ]); + $response = $client->request('GET', 'https://104.26.14.6/'); + $this->assertSame(302, $response->getStatusCode()); + $this->assertSame('foo', $response->getInfo('user_data')); + $this->assertTrue($progress); + + $this->assertSame([ + ['https://104.26.14.6/', '/path/to/ca.pem', 'http://proxy.example:3128', 7.0, 0, ['Accept: application/json']], + ['https://104.26.14.7/', '/path/to/ca.pem', 'http://proxy.example:3128', 7.0, 0, ['Accept: application/json']], + ['https://104.26.14.6/', '/path/to/ca.pem', null, (float) \ini_get('default_socket_timeout'), 0, ['Accept: */*']], + ['https://104.26.14.7/', null, null, (float) \ini_get('default_socket_timeout'), 0, ['Accept: */*']], + ['https://104.26.14.6/', null, null, (float) \ini_get('default_socket_timeout'), 0, ['Accept: */*']], + ], $requests); + } + public function testHeadersArePassedOnRedirect() { $ipAddr = '104.26.14.6'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/Response/MockResponseTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/Response/MockResponseTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/Response/MockResponseTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/Response/MockResponseTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -108,6 +108,48 @@ ]; } + public function testRedirectUrlIsResolvedFromTheLocationHeader() + { + $response = MockResponse::fromRequest('GET', 'https://example.com/foo/bar?a=b', [], new MockResponse('', [ + 'http_code' => 302, + 'response_headers' => ['Location' => '../baz?c=d'], + ])); + + $this->assertSame(302, $response->getStatusCode()); + $this->assertSame('https://example.com/baz?c=d', $response->getInfo('redirect_url')); + + $response = MockResponse::fromRequest('GET', 'https://example.com/', [], new MockResponse('', [ + 'http_code' => 307, + 'response_headers' => ['Location' => 'https://example.org/'], + 'redirect_url' => 'https://example.net/', + ])); + + $this->assertSame(307, $response->getStatusCode()); + $this->assertSame('https://example.net/', $response->getInfo('redirect_url')); + + $response = MockResponse::fromRequest('GET', 'https://example.com/', [], new MockResponse('', [ + 'http_code' => 301, + 'response_headers' => ['Location' => 'https://example.org/'], + 'redirect_url' => null, + ])); + + $this->assertSame(301, $response->getStatusCode()); + $this->assertNull($response->getInfo('redirect_url')); + + $response = MockResponse::fromRequest('GET', 'https://example.com/', [], new MockResponse('', [ + 'http_code' => 201, + 'response_headers' => ['Location' => 'https://example.org/'], + ])); + + $this->assertSame(201, $response->getStatusCode()); + $this->assertNull($response->getInfo('redirect_url')); + + $response = MockResponse::fromRequest('GET', 'https://example.com/', [], new MockResponse('', ['http_code' => 302])); + + $this->assertSame(302, $response->getStatusCode()); + $this->assertNull($response->getInfo('redirect_url')); + } + public function testErrorIsTakenIntoAccountInInitialization() { $this->expectException(TransportException::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/RetryableHttpClientTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\HttpClient\Tests; use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpClient\CurlHttpClient; use Symfony\Component\HttpClient\Exception\ServerException; use Symfony\Component\HttpClient\Exception\TransportException; use Symfony\Component\HttpClient\HttpClient; @@ -152,6 +153,200 @@ } } + public function testRetrySendsTheStreamBodyAgain() + { + $body = fopen('php://temp', 'r+'); + fwrite($body, 'skipped payload'); + fseek($body, 8); + + $sentBodies = []; + $client = new RetryableHttpClient(new MockHttpClient(static function (string $method, string $url, array $options) use (&$sentBodies) { + $sentBodies[] = self::readBody($options['body']); + + return new MockResponse('', ['http_code' => 1 === \count($sentBodies) ? 503 : 200]); + }), new GenericRetryStrategy([503], 0), 1); + + $this->assertSame(200, $client->request('PUT', 'http://example.com/', ['body' => $body])->getStatusCode()); + $this->assertSame(['payload', 'payload'], $sentBodies); + } + + public function testRetrySendsTheStreamsOfAMultipartBodyAgain() + { + $file = fopen('php://temp', 'r+'); + fwrite($file, 'payload'); + rewind($file); + + $sentBodies = []; + $client = new RetryableHttpClient(new MockHttpClient(static function (string $method, string $url, array $options) use (&$sentBodies) { + $sentBodies[] = self::readBody($options['body']); + + return new MockResponse('', ['http_code' => 1 === \count($sentBodies) ? 503 : 200]); + }), new GenericRetryStrategy([503], 0), 1); + + $this->assertSame(200, $client->request('POST', 'http://example.com/', ['body' => ['form' => ['file' => $file]]])->getStatusCode()); + $this->assertCount(2, $sentBodies); + $this->assertStringContainsString("\r\n\r\npayload\r\n", $sentBodies[1]); + } + + public function testRetrySendsTheStreamsNestedInObjectsAgain() + { + $form = new \stdClass(); + $form->file = fopen('php://temp', 'r+'); + fwrite($form->file, 'payload'); + rewind($form->file); + + $sentBodies = []; + $client = new RetryableHttpClient(new MockHttpClient(static function (string $method, string $url, array $options) use (&$sentBodies) { + $sentBodies[] = self::readBody($options['body']); + + return new MockResponse('', ['http_code' => 1 === \count($sentBodies) ? 503 : 200]); + }), new GenericRetryStrategy([503], 0), 1); + + $this->assertSame(200, $client->request('POST', 'http://example.com/', ['body' => ['form' => $form]])->getStatusCode()); + $this->assertCount(2, $sentBodies); + $this->assertStringContainsString("\r\n\r\npayload\r\n", $sentBodies[1]); + } + + public function testRetrySendsAResponseUsedAsBodyPartAgainOnlyWhenItIsBuffered() + { + foreach ([true, false] as $buffer) { + $part = (new MockHttpClient(new MockResponse('payload')))->request('GET', 'http://example.com/file.txt', ['buffer' => $buffer]); + + $sentBodies = []; + $client = new RetryableHttpClient(new MockHttpClient(static function (string $method, string $url, array $options) use (&$sentBodies) { + $sentBodies[] = self::readBody($options['body']); + + return new MockResponse('', ['http_code' => 1 === \count($sentBodies) ? 503 : 200]); + }), new GenericRetryStrategy([503], 0), 1); + + $this->assertSame($buffer ? 200 : 503, $client->request('POST', 'http://example.com/', ['body' => ['file' => $part]])->getStatusCode()); + $this->assertCount($buffer ? 2 : 1, $sentBodies); + + foreach ($sentBodies as $body) { + $this->assertStringContainsString("\r\n\r\npayload\r\n", $body); + } + } + } + + public function testRetrySendsTheBodiesThatAreBuiltForEachRequestAgain() + { + $bodies = [ + 'generator closure' => static function () { + yield 'pay'; + yield 'load'; + }, + 'iterator' => new \ArrayIterator(['pay', 'load']), + ]; + + foreach ($bodies as $type => $body) { + $sentBodies = []; + $client = new RetryableHttpClient(new MockHttpClient(static function (string $method, string $url, array $options) use (&$sentBodies) { + $sentBodies[] = self::readBody($options['body']); + + return new MockResponse('', ['http_code' => 1 === \count($sentBodies) ? 503 : 200]); + }), new GenericRetryStrategy([503], 0), 1); + + $this->assertSame(200, $client->request('PUT', 'http://example.com/', ['body' => $body])->getStatusCode(), $type); + $this->assertSame(['payload', 'payload'], $sentBodies, $type); + } + } + + public function testNoRetryWhenTheBodyCannotBeSentAgain() + { + $chunks = ['pay', 'load']; + $bodies = [ + 'generator' => (static function () { + yield 'pay'; + yield 'load'; + })(), + 'closure' => static function () use (&$chunks) { + return array_shift($chunks) ?? ''; + }, + ]; + + foreach ($bodies as $type => $body) { + $sentBodies = []; + $client = new RetryableHttpClient(new MockHttpClient(static function (string $method, string $url, array $options) use (&$sentBodies) { + $sentBodies[] = self::readBody($options['body']); + + return new MockResponse('', ['http_code' => 1 === \count($sentBodies) ? 503 : 200]); + }), new GenericRetryStrategy([503], 0), 1); + + $this->assertSame(503, $client->request('PUT', 'http://example.com/', ['body' => $body])->getStatusCode(), $type); + $this->assertSame(['payload'], $sentBodies, $type); + } + } + + public function testRetrySendsTheStreamBodyAgainWithCurl() + { + if (!\extension_loaded('curl')) { + $this->markTestSkipped('This test requires the curl extension.'); + } + + TestHttpServer::start(); + + foreach (['file' => tmpfile(), 'php://temp' => fopen('php://temp', 'r+')] as $type => $body) { + fwrite($body, 'foo=0123456789'); + rewind($body); + + // Retrying on 200 makes the test server receive the body twice + $client = new RetryableHttpClient(new CurlHttpClient(), new GenericRetryStrategy([200], 0), 1); + $response = $client->request('POST', 'http://localhost:8057/post', ['body' => $body]); + + $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray(), $type); + $this->assertSame(1, $response->getInfo('retry_count'), $type); + } + } + + public function testRetrySendsTheBodyWhenTheFirstAttemptFailedBeforeReadingIt() + { + if (!\extension_loaded('curl')) { + $this->markTestSkipped('This test requires the curl extension.'); + } + + TestHttpServer::start(); + + [$writer, $stream] = stream_socket_pair('\\' === \DIRECTORY_SEPARATOR ? \STREAM_PF_INET : \STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + fwrite($writer, 'foo=0123456789'); + fclose($writer); + + $chunks = ['foo=', '0123456789']; + $bodies = [ + 'generator' => (static function () { + yield 'foo='; + yield '0123456789'; + })(), + 'closure' => static function () use (&$chunks) { + return array_shift($chunks) ?? ''; + }, + 'stream that is not seekable' => $stream, + ]; + + foreach ($bodies as $type => $body) { + $client = new RetryableHttpClient(new CurlHttpClient(), new GenericRetryStrategy([], 0), 1); + $response = $client->request('POST', 'post', ['base_uri' => ['http://does.not.exists/', 'http://localhost:8057/'], 'body' => $body]); + + $this->assertSame(['foo' => '0123456789', 'REQUEST_METHOD' => 'POST'], $response->toArray(), $type); + } + } + + public function testNoRetryWhenTheStreamBodyIsNotSeekable() + { + [$writer, $body] = stream_socket_pair('\\' === \DIRECTORY_SEPARATOR ? \STREAM_PF_INET : \STREAM_PF_UNIX, \STREAM_SOCK_STREAM, \STREAM_IPPROTO_IP); + fwrite($writer, 'payload'); + fclose($writer); + + $sentBodies = []; + $client = new RetryableHttpClient(new MockHttpClient(static function (string $method, string $url, array $options) use (&$sentBodies) { + $sentBodies[] = self::readBody($options['body']); + + return new MockResponse('', ['http_code' => 1 === \count($sentBodies) ? 503 : 200]); + }), new GenericRetryStrategy([503], 0), 1); + + $this->assertSame(503, $client->request('PUT', 'http://example.com/', ['body' => $body])->getStatusCode()); + $this->assertSame(['payload'], $sentBodies); + } + public function testRetryWithDnsIssue() { $client = new RetryableHttpClient( @@ -683,4 +878,22 @@ $this->assertSame(2, $retryCount, 'The request should have been retried once'); } + + private static function readBody($body): string + { + if (\is_resource($body)) { + return stream_get_contents($body); + } + + if (!$body instanceof \Closure) { + return $body; + } + + $data = ''; + while ('' !== $chunk = $body(16372)) { + $data .= $chunk; + } + + return $data; + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/ScopingHttpClientTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/ScopingHttpClientTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/ScopingHttpClientTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/ScopingHttpClientTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -153,6 +153,7 @@ yield 'network-path reference' => ['//safe.example/api/users/1', 'https://safe.example/api/users/1']; yield 'network-path reference with the default port' => ['//safe.example:443/api/users/1', 'https://safe.example/api/users/1']; yield 'network-path reference with an uppercase host' => ['//SAFE.Example/api/users/1', 'https://safe.example/api/users/1']; + yield 'network-path reference with userinfo' => ['//user@safe.example/api/users/1', 'https://safe.example/api/users/1']; yield 'absolute URL' => ['https://safe.example/api/users/1', 'https://safe.example/api/users/1']; } @@ -180,10 +181,56 @@ { yield 'absolute URL' => ['https://evil.example/steal', 'https://evil.example/steal']; yield 'network-path reference' => ['//evil.example/steal', 'https://evil.example/steal']; - yield 'network-path reference with userinfo naming the base host' => ['//safe.example@evil.example/steal', 'https://safe.example@evil.example/steal']; + yield 'network-path reference with userinfo naming the base host' => ['//safe.example@evil.example/steal', 'https://evil.example/steal']; yield 'network-path reference with another port' => ['//safe.example:8443/api/users/1', 'https://safe.example:8443/api/users/1']; yield 'network-path reference with the default port of another scheme' => ['//safe.example:80/api/users/1', 'https://safe.example:80/api/users/1']; - yield 'network-path reference with userinfo' => ['//user@safe.example/api/users/1', 'https://user@safe.example/api/users/1']; + } + + /** + * @dataProvider provideUrlsOnABaseUriWithUserinfo + */ + public function testForBaseUriWithUserinfoAppliesOptionsOnItsHost(string $url, string $expectedUrl, bool $withUserinfo) + { + $client = ScopingHttpClient::forBaseUri(new MockHttpClient(null, null), 'https://user:pass@safe.example/api/', [ + 'headers' => ['X-Api-Key' => 'scope-secret'], + ]); + + $response = $client->request('GET', $url); + + $this->assertSame($expectedUrl, $response->getInfo('url')); + $this->assertSame($withUserinfo, \in_array('Authorization: Basic '.base64_encode('user:pass'), $response->getRequestOptions()['headers'], true)); + $this->assertContains('X-Api-Key: scope-secret', $response->getRequestOptions()['headers']); + } + + public static function provideUrlsOnABaseUriWithUserinfo(): iterable + { + yield 'relative path' => ['users/1', 'https://safe.example/api/users/1', true]; + yield 'absolute URL' => ['https://safe.example/api/users/1', 'https://safe.example/api/users/1', false]; + yield 'absolute URL with the userinfo of the base URI' => ['https://user:pass@safe.example/api/users/1', 'https://safe.example/api/users/1', true]; + } + + /** + * @dataProvider provideUrlsWithUserinfo + */ + public function testScopesAreMatchedAgainstTheUrlWithoutItsUserinfo(string $url, bool $inScope) + { + $client = new ScopingHttpClient(new MockHttpClient(), [ + 'https://api\.github\.com' => ['auth_bearer' => 'scope-secret'], + ]); + + $response = $client->request('GET', $url); + + $this->assertSame($inScope ? 'https://api.github.com/' : 'https://evil.example/', $response->getInfo('url')); + $this->assertSame($inScope, \in_array('Authorization: Bearer scope-secret', $response->getRequestOptions()['headers'], true)); + } + + public static function provideUrlsWithUserinfo(): iterable + { + yield 'userinfo naming the host of the scope' => ['https://api.github.com@evil.example/', false]; + yield 'userinfo naming the host of the scope and a port' => ['https://api.github.com:443@evil.example/', false]; + yield 'userinfo naming the host of the scope after an @' => ['https://user@api.github.com@evil.example/', false]; + yield 'userinfo on the host of the scope' => ['https://user:pass@api.github.com/', true]; + yield 'userinfo with an @ on the host of the scope' => ['https://user@evil.example@api.github.com/', true]; } public function testNetworkPathReferenceGetsTheOptionsOfTheScopeItResolvesTo() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/Tests/TraceableHttpClientTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -144,6 +144,19 @@ $this->assertSame(0, $response->destructCount); } + public function testResponseIsUsableAfterShutdownDestructors() + { + $sut = new TraceableHttpClient(new MockHttpClient(new MockResponse('OK'))); + $response = $sut->request('GET', 'https://example.com/'); + + // At shutdown, PHP calls the destructors of the remaining objects in no particular order, so another destructor can still use the response afterwards + if (method_exists($response, '__destruct')) { + $response->__destruct(); + } + + $this->assertSame(200, $response->getStatusCode()); + } + public function testToArrayChecksStatusCodeBeforeDecoding() { $this->expectException(ClientExceptionInterface::class); @@ -242,6 +255,29 @@ $this->assertGreaterThan(0.0, $events['GET http://localhost:8057']->getDuration()); } + public function testStopwatchIncludesTheDestructorOfTheWrappedResponse() + { + $event = (new Stopwatch(true))->start('GET https://example.com/'); + $eventWasStarted = null; + $response = new class extends MockResponse { + public \Closure $onDestruct; + + public function __destruct() + { + ($this->onDestruct)(); + } + }; + $response->onDestruct = static function () use ($event, &$eventWasStarted) { + $eventWasStarted = $event->isStarted(); + }; + $content = false; + $traceableResponse = new TraceableResponse(new MockHttpClient(), $response, $content, $event); + unset($response, $traceableResponse); + + $this->assertTrue($eventWasStarted); + $this->assertFalse($event->isStarted()); + } + public function testWithOptions() { $sut = new TraceableHttpClient(new NativeHttpClient()); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/composer.json symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/composer.json --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpClient/composer.json 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpClient/composer.json 2026-11-25 09:18:34.000000000 +0000 @@ -39,6 +39,7 @@ "php-http/httplug": "^1.0|^2.0", "psr/http-client": "^1.0", "symfony/dependency-injection": "^5.4|^6.0|^7.0", + "symfony/http-foundation": "^6.4.50|^7.4.23", "symfony/http-kernel": "^5.4|^6.0|^7.0", "symfony/messenger": "^5.4|^6.0|^7.0", "symfony/process": "^5.4|^6.0|^7.0", diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/IpUtils.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/IpUtils.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/IpUtils.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/IpUtils.php 2026-11-25 09:18:34.000000000 +0000 @@ -41,6 +41,7 @@ '::1/128', // Loopback 'fc00::/7', // Unique Local Address 'fe80::/10', // Link Local Address + 'fec0::/10', // Site-Local Addresses, deprecated by RFC 3879 '::ffff:0:0/96', // IPv4-mapped IPv6 addresses (RFC 4291 section 2.5.5.2) '::/128', // Unspecified address '::/96', // IPv4-compatible IPv6 addresses (RFC 4291 section 2.5.5.1) @@ -268,6 +269,9 @@ /** * Checks if an IPv4 or IPv6 address is contained in the list of private IP subnets. * + * An IPv4-mapped, 6to4, Teredo or NAT64 address is checked as the IPv4 address it embeds: + * connecting to it reaches that IPv4 address, and a client can present it only when that IPv4 address is its own. + * * @throws \ValueError When $requestIp is not a valid IP address */ public static function isPrivateIp(string $requestIp): bool @@ -276,7 +280,26 @@ throw new \ValueError(\sprintf('"%s" is not a valid IP address.', $requestIp)); } - return self::checkIp($requestIp, self::PRIVATE_SUBNETS); + return self::checkIp(self::getEmbeddedIp4($requestIp) ?? $requestIp, self::PRIVATE_SUBNETS); + } + + private static function getEmbeddedIp4(string $ip): ?string + { + if (!str_contains($ip, ':') || false === $packed = @inet_pton($ip)) { + return null; + } + + return match (true) { + // IPv4-mapped (::ffff:0:0/96): the last 32 bits + "\0\0\0\0\0\0\0\0\0\0\xFF\xFF" === substr($packed, 0, 12) => inet_ntop(substr($packed, 12)), + // NAT64 with the well-known prefix (64:ff9b::/96): the last 32 bits + "\0\x64\xFF\x9B\0\0\0\0\0\0\0\0" === substr($packed, 0, 12) => inet_ntop(substr($packed, 12)), + // 6to4 (2002::/16): the 32 bits after the prefix + "\x20\x02" === substr($packed, 0, 2) => inet_ntop(substr($packed, 2, 4)), + // Teredo (2001::/32): the public address of the client, inverted in the last 32 bits + "\x20\x01\0\0" === substr($packed, 0, 4) => inet_ntop(~substr($packed, 12)), + default => null, + } ?: null; } private static function getCacheResult(string $cacheKey): ?bool diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/JsonResponse.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/JsonResponse.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/JsonResponse.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/JsonResponse.php 2026-11-25 09:18:34.000000000 +0000 @@ -18,7 +18,7 @@ * object. It is however recommended that you do return an object as it * protects yourself against XSSI and JSON-JavaScript Hijacking. * - * @see https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/AJAX_Security_Cheat_Sheet.md#always-return-json-with-an-object-on-the-outside + * @see https://cheatsheetseries.owasp.org/cheatsheets/Web_Frontend_Security_Cheat_Sheet.html#always-return-json-with-an-object-on-the-outside * * @author Igor Wiedler <igor@wiedler.ch> */ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Request.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Request.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Request.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Request.php 2026-11-25 09:18:34.000000000 +0000 @@ -52,6 +52,8 @@ public const HEADER_X_FORWARDED_AWS_ELB = 0b0011010; // AWS ELB doesn't send X-Forwarded-Host public const HEADER_X_FORWARDED_TRAEFIK = 0b0111110; // All "X-Forwarded-*" headers sent by Traefik reverse proxy + public const SUB_REQUEST_TRUSTED_HEADER_SET = 'SYMFONY_SUB_REQUEST_TRUSTED_HEADER_SET'; + public const METHOD_HEAD = 'HEAD'; public const METHOD_GET = 'GET'; public const METHOD_POST = 'POST'; @@ -1126,7 +1128,9 @@ // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used // as the first segment of a relative-path reference, as it would be mistaken for a scheme name // (see https://tools.ietf.org/html/rfc3986#section-4.2). - return !isset($path[0]) || '/' === $path[0] + // A leading backslash, space or control character needs the prefix too, + // since browsers read a backslash as a slash and ignore leading spaces and control characters. + return !isset($path[0]) || '/' === $path[0] || '\\' === $path[0] || \ord($path[0]) <= 0x20 || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) ? "./$path" : $path; } @@ -2052,7 +2056,19 @@ */ public function isFromTrustedProxy(): bool { - return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR', ''), self::$trustedProxies); + return null !== $this->getSubRequestTrustedHeaderSet() || (self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR', ''), self::$trustedProxies)); + } + + /** + * Returns the trusted header set of a request built by HttpKernel's SubRequestHandler, which comes from 127.0.0.1. + */ + private function getSubRequestTrustedHeaderSet(): ?int + { + if ('127.0.0.1' !== $this->server->get('REMOTE_ADDR') || !$this->server->has(self::SUB_REQUEST_TRUSTED_HEADER_SET)) { + return null; + } + + return (int) $this->server->get(self::SUB_REQUEST_TRUSTED_HEADER_SET); } /** @@ -2071,14 +2087,15 @@ $clientValues = []; $forwardedValues = []; + $trustedHeaderSet = $this->getSubRequestTrustedHeaderSet() ?? self::$trustedHeaderSet; - if ((self::$trustedHeaderSet & $type) && $this->headers->has(self::TRUSTED_HEADERS[$type])) { + if (($trustedHeaderSet & $type) && $this->headers->has(self::TRUSTED_HEADERS[$type])) { foreach (explode(',', $this->headers->get(self::TRUSTED_HEADERS[$type])) as $v) { $clientValues[] = (self::HEADER_X_FORWARDED_PORT === $type ? '0.0.0.0:' : '').trim($v); } } - if ((self::$trustedHeaderSet & self::HEADER_FORWARDED) && (isset(self::FORWARDED_PARAMS[$type])) && $this->headers->has(self::TRUSTED_HEADERS[self::HEADER_FORWARDED])) { + if (($trustedHeaderSet & self::HEADER_FORWARDED) && (isset(self::FORWARDED_PARAMS[$type])) && $this->headers->has(self::TRUSTED_HEADERS[self::HEADER_FORWARDED])) { $forwarded = $this->headers->get(self::TRUSTED_HEADERS[self::HEADER_FORWARDED]); $parts = HeaderUtils::split($forwarded, ',;='); $param = self::FORWARDED_PARAMS[$type]; @@ -2143,7 +2160,7 @@ continue; } - if (IpUtils::checkIp($clientIp, self::$trustedProxies)) { + if (IpUtils::checkIp($clientIp, self::$trustedProxies) || ('127.0.0.1' === $clientIp && null !== $this->getSubRequestTrustedHeaderSet())) { unset($clientIps[$key]); // Fallback to this when the client IP falls into the range of trusted proxies diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/MemcachedSessionHandler.php 2026-11-25 09:18:34.000000000 +0000 @@ -93,8 +93,9 @@ // If the relative TTL that is used exceeds 30 days, memcached will treat the value as Unix time. // We have to convert it to an absolute Unix time at this point, to make sure the TTL is correct. + // Memcached's text protocol parses that Unix time as a 32-bit signed integer. if ($ttl > 60 * 60 * 24 * 30) { - $ttl += time(); + $ttl = min($ttl + time(), 2147483647); } return $ttl; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -205,6 +205,7 @@ ['fe80::1', true], ['::ffff:0:1', true], ['fd00::1', true], + ['fec0::1', true], ['::7f00:1', true], ['2002:7f00:1::', true], ['2001::1', true], @@ -212,10 +213,24 @@ ['2001:0002::1', true], ['64:ff9b::7f00:1', true], ['64:ff9b:1::7f00:1', true], + // addresses embedding a private IPv4 address + ['::ffff:10.0.0.1', true], + ['2002:a00:1::', true], + ['2001:0:4136:e378:8000:63bf:f5ff:fffe', true], + ['64:ff9b::a00:1', true], + // where the IPv4 address sits is unknown, or no host presents such an address + ['64:ff9b:1::681a:e06', true], + ['::104.26.14.6', true], // public ['104.26.14.6', false], ['2606:4700:20::681a:e06', false], + // addresses embedding the public IPv4 address 104.26.14.6 + ['::ffff:104.26.14.6', false], + ['::ffff:681a:e06', false], + ['2002:681a:e06::1', false], + ['2001:0:4136:e378:8000:63bf:97e5:f1f9', false], + ['64:ff9b::681a:e06', false], // just past the boundary of the ranges above, which pins their prefix lengths ['100.128.0.1', false], ['198.20.0.1', false], @@ -295,7 +310,7 @@ public function testPrivateRangesDoNotCoverAddressesARemoteClientCanPresent(string $ip) { $this->assertFalse(IpUtils::checkIp($ip, IpUtils::PRIVATE_RANGES)); - $this->assertTrue(IpUtils::isPrivateIp($ip)); + $this->assertTrue(IpUtils::checkIp($ip, IpUtils::PRIVATE_SUBNETS)); } public static function getAddressesARemoteClientCanPresent(): array diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/RequestTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -790,6 +790,10 @@ ['../baz/me.png', '/foo/bar/b', '/foo/baz/me.png'], ['../../fooz/baz/me.png', '/foo/bar/b', '/fooz/baz/me.png'], ['baz/me.png', '/foo/bar/b', 'baz/me.png'], + ['./\\\\example.com', '/foo/bar', '/foo/\\\\example.com'], + ['./\\/example.com', '/foo/bar', '/foo/\\/example.com'], + ['./ //example.com', '/foo/bar', '/foo/ //example.com'], + ["./\t//example.com", '/foo/bar', "/foo/\t//example.com"], ]; } @@ -1100,6 +1104,10 @@ [['88.88.88.88'], '127.0.0.1', '88.88.88.88', ['127.0.0.1', '88.88.88.88']], // forwarded for with remote IPv4 range trusted [['88.88.88.88'], '123.45.67.89', '88.88.88.88', ['123.45.67.0/24']], + // forwarded for with remote IPv4-mapped addr in a trusted IPv4 range + [['88.88.88.88'], '::ffff:123.45.67.89', '88.88.88.88', ['123.45.67.0/24']], + // forwarded for with remote IPv4-mapped addr out of the trusted IPv4 range + [['::ffff:123.45.68.89'], '::ffff:123.45.68.89', '88.88.88.88', ['123.45.67.0/24']], // forwarded for with remote IPv6 addr not trusted [['1620:0:1cfe:face:b00c::3'], '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3', null], diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -128,6 +128,21 @@ $this->assertTrue($sessionHandler->write('id', 'data')); } + public function testWriteSessionWithTtlEndingAfter2038() + { + $memcached = $this->getMemcachedMock(); + $memcached + ->expects($this->once()) + ->method('set') + ->with(self::PREFIX.'id', 'data', 2147483647) + ->willReturn(true) + ; + + $sessionHandler = new MemcachedSessionHandler($memcached, ['prefix' => self::PREFIX, 'expiretime' => 100 * 365 * 86400]); + + $this->assertTrue($sessionHandler->write('id', 'data')); + } + public function testDestroySession() { $memcached = $this->getMemcachedMock(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/Test/Constraint/ResponseFormatSameTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -23,6 +23,11 @@ */ class ResponseFormatSameTest extends TestCase { + protected function tearDown(): void + { + (new \ReflectionProperty(Request::class, 'formats'))->setValue(null, null); + } + public function testConstraint() { $request = new Request(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/UrlHelperTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/UrlHelperTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpFoundation/Tests/UrlHelperTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpFoundation/Tests/UrlHelperTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -234,6 +234,7 @@ ['../foo.png', '/foo.png', '/foo/bar.html'], ['../baz/foo.png', '/baz/foo.png', '/foo/bar.html'], ['baz/foo.png', 'baz/foo.png', '/foo/bar.html'], + ['./\\\\example.com', '/foo/\\\\example.com', '/foo/bar.html'], ['http://example.com/baz', 'http://example.com/baz', '/'], ['https://example.com/baz', 'https://example.com/baz', '/'], diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/EventListener/ValidateRequestListener.php 2026-11-25 09:18:34.000000000 +0000 @@ -34,7 +34,7 @@ } $request = $event->getRequest(); - if ($request::getTrustedProxies()) { + if ($request->isFromTrustedProxy()) { $request->getClientIps(); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/HttpCache/HttpCache.php 2026-11-25 09:18:34.000000000 +0000 @@ -373,7 +373,12 @@ if (!$this->isFreshEnough($request, $entry)) { $this->record($request, 'stale'); - return $this->validate($request, $entry, $catch); + try { + return $this->validate($request, $entry, $catch); + } finally { + // release the lock taken by isFreshEnough(), even when nothing was stored + $this->store->unlock($request); + } } if ($entry->headers->hasCacheControlDirective('no-cache')) { @@ -606,6 +611,12 @@ if ($this->waitForLock($request)) { throw new CacheWasLockedException(); // unwind back to handle(), try again } + + // a no-cache entry must be validated anyway, call the backend + if ($entry->headers->hasCacheControlDirective('no-cache')) { + return false; + } + // backend is slow as hell, send a 503 response (to avoid the dog pile effect) $entry->setStatusCode(503); if (!$entry->headers->has('X-Body-File') && !$entry->headers->has('X-Body-Eval')) { @@ -771,6 +782,10 @@ */ private function mayServeStaleWhileRevalidate(Response $entry): bool { + if ($entry->mustRevalidate()) { + return false; + } + $timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate'); $timeout ??= $this->options['stale_while_revalidate']; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/HttpCache/Store.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/HttpCache/Store.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/HttpCache/Store.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/HttpCache/Store.php 2026-11-25 09:18:34.000000000 +0000 @@ -85,7 +85,7 @@ $key = $this->getCacheKey($request); if (!isset($this->locks[$key])) { - $path = $this->getPath($key); + $path = $this->getPath($key).'.lck'; if (!is_dir(\dirname($path)) && !@mkdir(\dirname($path), 0o777, true) && !is_dir(\dirname($path))) { return $path; } @@ -134,7 +134,7 @@ return true; // shortcut if lock held by this process } - if (!is_file($path = $this->getPath($key))) { + if (!is_file($path = $this->getPath($key).'.lck')) { return false; } @@ -383,49 +383,35 @@ */ private function save(string $key, string $data, bool $overwrite = true): bool { - $this->resetLocksAfterFork(); - $path = $this->getPath($key); if (!$overwrite && file_exists($path)) { return true; } - if (isset($this->locks[$key])) { - $fp = $this->locks[$key]; - @ftruncate($fp, 0); - @fseek($fp, 0); - $len = @fwrite($fp, $data); - if (\strlen($data) !== $len) { - @ftruncate($fp, 0); - - return false; - } - } else { - if (!is_dir(\dirname($path)) && !@mkdir(\dirname($path), 0o777, true) && !is_dir(\dirname($path))) { - return false; - } + if (!is_dir(\dirname($path)) && !@mkdir(\dirname($path), 0o777, true) && !is_dir(\dirname($path))) { + return false; + } - $tmpFile = tempnam(\dirname($path), basename($path)); - if (false === $fp = @fopen($tmpFile, 'w')) { - @unlink($tmpFile); + $tmpFile = tempnam(\dirname($path), basename($path)); + if (false === $fp = @fopen($tmpFile, 'w')) { + @unlink($tmpFile); - return false; - } - @fwrite($fp, $data); - @fclose($fp); + return false; + } + @fwrite($fp, $data); + @fclose($fp); - if ($data != file_get_contents($tmpFile)) { - @unlink($tmpFile); + if ($data != file_get_contents($tmpFile)) { + @unlink($tmpFile); - return false; - } + return false; + } - if (!@rename($tmpFile, $path)) { - @unlink($tmpFile); + if (!@rename($tmpFile, $path)) { + @unlink($tmpFile); - return false; - } + return false; } @chmod($path, 0o666 & ~umask()); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/HttpCache/SubRequestHandler.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/HttpCache/SubRequestHandler.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/HttpCache/SubRequestHandler.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/HttpCache/SubRequestHandler.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,7 +11,6 @@ namespace Symfony\Component\HttpKernel\HttpCache; -use Symfony\Component\HttpFoundation\IpUtils; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; @@ -25,13 +24,11 @@ { public static function handle(HttpKernelInterface $kernel, Request $request, int $type, bool $catch): Response { - // save global state related to trusted headers and proxies - $trustedProxies = Request::getTrustedProxies(); $trustedHeaderSet = Request::getTrustedHeaderSet(); // remove untrusted values $remoteAddr = $request->server->get('REMOTE_ADDR'); - if (!$remoteAddr || !IpUtils::checkIp($remoteAddr, $trustedProxies)) { + if (!$remoteAddr || !$request->isFromTrustedProxy()) { $trustedHeaders = [ 'FORWARDED' => $trustedHeaderSet & Request::HEADER_FORWARDED, 'X_FORWARDED_FOR' => $trustedHeaderSet & Request::HEADER_X_FORWARDED_FOR, @@ -68,7 +65,7 @@ $request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps)); $request->server->set('HTTP_X_FORWARDED_FOR', $v); } elseif (!(Request::HEADER_FORWARDED & $trustedHeaderSet)) { - Request::setTrustedProxies($trustedProxies, $trustedHeaderSet | Request::HEADER_X_FORWARDED_FOR); + $trustedHeaderSet |= Request::HEADER_X_FORWARDED_FOR; $request->headers->set('X-Forwarded-For', $v = implode(', ', $trustedIps)); $request->server->set('HTTP_X_FORWARDED_FOR', $v); } @@ -77,16 +74,10 @@ // which is the core responsibility of this method $request->server->set('REMOTE_ADDR', '127.0.0.1'); - // ensure 127.0.0.1 is set as trusted proxy - if (!IpUtils::checkIp('127.0.0.1', $trustedProxies)) { - Request::setTrustedProxies(array_merge($trustedProxies, ['127.0.0.1']), Request::getTrustedHeaderSet()); - } + // trust 127.0.0.1 for this request and for the ones copied from it, but not globally: + // other requests coming from 127.0.0.1, like the main one, carry headers set by the client + $request->server->set(Request::SUB_REQUEST_TRUSTED_HEADER_SET, $trustedHeaderSet); - try { - return $kernel->handle($request, $type, $catch); - } finally { - // restore global state - Request::setTrustedProxies($trustedProxies, $trustedHeaderSet); - } + return $kernel->handle($request, $type, $catch); } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Kernel.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Kernel.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Kernel.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Kernel.php 2026-11-25 09:18:34.000000000 +0000 @@ -77,11 +77,11 @@ */ private static array $freshCache = []; - public const VERSION = '6.4.50'; - public const VERSION_ID = 60450; + public const VERSION = '6.4.51'; + public const VERSION_ID = 60451; public const MAJOR_VERSION = 6; public const MINOR_VERSION = 4; - public const RELEASE_VERSION = 50; + public const RELEASE_VERSION = 51; public const EXTRA_VERSION = ''; public const END_OF_MAINTENANCE = '11/2026'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -174,6 +174,48 @@ $aggregate->warmUp(__DIR__, null, $io); } + public function testWarmupReadsTheDeprecationLogWithoutInstantiatingObjects() + { + $logFile = tempnam(sys_get_temp_dir(), 'sf_deprecations_'); + // the log file holds scalars and plain arrays; an attacker who can write to the cache directory must not be able to have an object built out of it + file_put_contents($logFile, 'a:1:{i:1;O:18:"DeprecationPayload":0:{}}'); + + // collecting deprecations is disabled when PHPUNIT_COMPOSER_INSTALL is defined, hence the child process + $srcDir = \dirname((new \ReflectionClass(CacheWarmerAggregate::class))->getFileName()); + $bootCode = <<<'EOPHP' + <?php + [, $srcDir, $logFile] = $argv; + require $srcDir.'/WarmableInterface.php'; + require $srcDir.'/CacheWarmerInterface.php'; + require $srcDir.'/CacheWarmerAggregate.php'; + + class DeprecationPayload + { + public function __wakeup(): void + { + echo 'WOKE'; + } + } + + (new \Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate([], true, $logFile))->warmUp(sys_get_temp_dir()); + + echo 'OK'; + EOPHP; + + $process = new Process([\PHP_BINARY, '--', $srcDir, $logFile]); + $process->setInput($bootCode); + $process->run(); + + try { + $this->assertSame('OK', $process->getOutput(), $process->getErrorOutput()); + $this->assertSame(0, $process->getExitCode()); + // the log is written back as a list, so the renumbered entry proves it was read + $this->assertSame('a:1:{i:0;O:18:"DeprecationPayload":0:{}}', file_get_contents($logFile)); + } finally { + @unlink($logFile); + } + } + public function testWarmupRecoversFromCorruptedDeprecationLog() { $logFile = tempnam(sys_get_temp_dir(), 'sf_deprecations_'); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -18,6 +18,7 @@ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector; use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; +use Symfony\Component\HttpKernel\Tests\Fixtures\WakingPayload; use Symfony\Component\VarDumper\Cloner\Data; class LoggerDataCollectorTest extends TestCase @@ -54,10 +55,10 @@ file_put_contents($path, serialize([[ 'type' => 16384, 'message' => 'The "Symfony\Bundle\FrameworkBundle\Controller\Controller" class is deprecated since Symfony 4.2, use Symfony\Bundle\FrameworkBundle\Controller\AbstractController instead.', - 'file' => '/home/hamza/projet/contrib/sf/vendor/symfony/framework-bundle/Controller/Controller.php', + 'file' => '/home/hamza/project/contrib/sf/vendor/symfony/framework-bundle/Controller/Controller.php', 'line' => 17, 'trace' => [[ - 'file' => '/home/hamza/projet/contrib/sf/src/Controller/DefaultController.php', + 'file' => '/home/hamza/project/contrib/sf/src/Controller/DefaultController.php', 'line' => 9, 'function' => 'spl_autoload_call', ]], @@ -92,6 +93,42 @@ @unlink($path); } + public function testDeprecationsLogIsReadWithoutInstantiatingObjects() + { + WakingPayload::reset(); + + $containerPathPrefix = __DIR__.'/'; + $path = $containerPathPrefix.'Deprecations.log'; + file_put_contents($path, serialize([[ + 'type' => 16384, + 'message' => 'The "Foo" class is deprecated.', + 'file' => '/app/src/Controller/DefaultController.php', + 'line' => 9, + 'trace' => [['file' => '/app/src/Kernel.php', 'line' => 9, 'args' => [new WakingPayload()]]], + 'count' => 1, + ]])); + + $logger = $this + ->getMockBuilder(DebugLoggerInterface::class) + ->onlyMethods(['countErrors', 'getLogs', 'clear']) + ->getMock(); + + $logger->expects($this->once())->method('countErrors')->willReturn(0); + $logger->expects($this->exactly(2))->method('getLogs')->willReturn([]); + + $c = new LoggerDataCollector($logger, $containerPathPrefix); + + try { + $c->lateCollect(); + + // the log file holds scalars and plain arrays; an attacker who can write to the cache directory must not be able to have an object built out of it + $this->assertCount(1, $c->getProcessedLogs()); + $this->assertFalse(WakingPayload::$awoken); + } finally { + @unlink($path); + } + } + public function testWithMainRequest() { $mainRequest = new Request(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/EventListener/SessionListenerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -619,12 +619,11 @@ $response = new Response(); $response->setPrivate(); - $expiresHeader = gmdate('D, d M Y H:i:s', time() + 600).' GMT'; $response->setMaxAge(600); $listener->onKernelResponse(new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, $response)); $this->assertTrue($response->headers->has('expires')); - $this->assertSame($expiresHeader, $response->headers->get('expires')); + $this->assertEqualsWithDelta(time() + 600, $response->getExpires()->getTimestamp(), 1); $this->assertFalse($response->headers->has('max-age')); $this->assertSame('600', $response->headers->getCacheControlDirective('max-age')); $this->assertFalse($response->headers->hasCacheControlDirective('public')); @@ -648,11 +647,10 @@ $listener->onKernelRequest(new RequestEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST)); $response = new Response(); - $expiresHeader = gmdate('D, d M Y H:i:s', time()).' GMT'; $listener->onKernelResponse(new ResponseEvent($kernel, $request, HttpKernelInterface::MAIN_REQUEST, $response)); $this->assertTrue($response->headers->has('expires')); - $this->assertSame($expiresHeader, $response->headers->get('expires')); + $this->assertEqualsWithDelta(time(), $response->getExpires()->getTimestamp(), 1); $this->assertFalse($response->headers->has('max-age')); $this->assertSame('0', $response->headers->getCacheControlDirective('max-age')); $this->assertFalse($response->headers->hasCacheControlDirective('public')); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/Fixtures/WakingPayload.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/Fixtures/WakingPayload.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/Fixtures/WakingPayload.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/Fixtures/WakingPayload.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,30 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\HttpKernel\Tests\Fixtures; + +/** + * Records whether unserialize() was allowed to build it. + */ +class WakingPayload +{ + public static bool $awoken = false; + + public static function reset(): void + { + self::$awoken = false; + } + + public function __wakeup(): void + { + self::$awoken = true; + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -75,7 +75,7 @@ $expectedSubRequest->headers->set('x-forwarded-for', ['127.0.0.1']); $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1'); - $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest)); + $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest, Request::HEADER_X_FORWARDED_FOR)); $this->assertSame('foo', $strategy->render('/', Request::create('/'))->getContent()); Request::setTrustedProxies([], -1); @@ -83,13 +83,13 @@ public function testRenderExceptionNoIgnoreErrors() { - $this->expectException(\RuntimeException::class); $dispatcher = $this->createMock(EventDispatcherInterface::class); $dispatcher->expects($this->never())->method('dispatch'); $strategy = new InlineFragmentRenderer($this->getKernel(new \RuntimeException('foo')), $dispatcher); - $this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent()); + $this->expectException(\RuntimeException::class); + $strategy->render('/', Request::create('/')); } public function testRenderExceptionIgnoreErrors() @@ -186,7 +186,7 @@ $expectedSubRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']); $expectedSubRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http'); - $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest)); + $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest, Request::getTrustedHeaderSet())); $request = Request::create('/'); $request->attributes->set('_format', 'foo'); @@ -207,7 +207,7 @@ $expectedSubRequest->headers->set('forwarded', ['for="127.0.0.1";host="localhost";proto=http']); $expectedSubRequest->server->set('HTTP_FORWARDED', 'for="127.0.0.1";host="localhost";proto=http'); - $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest)); + $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest, Request::getTrustedHeaderSet())); $request = Request::create('/'); $request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"'); @@ -283,7 +283,7 @@ $context = new RequestContext(); $matcher = $this->createStub(UrlMatcherInterface::class); $matcher->method('getContext')->willReturn($context); - $matcher->method('match')->willReturn(['_controller' => function () { return new Response('fragment'); }]); + $matcher->method('match')->willReturn(['_controller' => static fn () => new Response('fragment')]); $requestStack = new RequestStack(); $dispatcher = new EventDispatcher(); @@ -292,7 +292,7 @@ $renderer = new InlineFragmentRenderer($kernel); $request = Request::create('http://example.com/', 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_HOST' => 'evil.example', 'HTTP_X_FORWARDED_PROTO' => 'https']); - $request->attributes->set('_controller', function () use ($renderer, $request, $context) { + $request->attributes->set('_controller', static function () use ($renderer, $request, $context) { $renderer->render('/fragment', $request); return new Response($context->getScheme().'://'.$context->getHost()); @@ -310,7 +310,7 @@ $requestStack = new RequestStack(); $dispatcher = new EventDispatcher(); $dispatcher->addSubscriber(new RouterListener($matcher, $requestStack, $context)); - $dispatcher->addListener(KernelEvents::REQUEST, function (RequestEvent $event) { + $dispatcher->addListener(KernelEvents::REQUEST, static function (RequestEvent $event) { if (!$event->isMainRequest()) { $event->setResponse(new Response('fragment')); } @@ -319,7 +319,7 @@ $renderer = new InlineFragmentRenderer($kernel); $request = Request::create('http://example.com/', 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1', 'HTTP_X_FORWARDED_HOST' => 'evil.example', 'HTTP_X_FORWARDED_PROTO' => 'https']); - $request->attributes->set('_controller', function () use ($renderer, $request, $context) { + $request->attributes->set('_controller', static function () use ($renderer, $request, $context) { $renderer->render('/fragment', $request); return new Response($context->getScheme().'://'.$context->getHost()); @@ -405,8 +405,10 @@ /** * Creates a Kernel expecting a request equals to $request. */ - private function getKernelExpectingRequest(Request $expectedRequest) + private function getKernelExpectingRequest(Request $expectedRequest, int $trustedHeaderSet = -1) { + $expectedRequest->server->set(Request::SUB_REQUEST_TRUSTED_HEADER_SET, $trustedHeaderSet); + $kernel = $this->createMock(HttpKernelInterface::class); $kernel ->expects($this->once()) @@ -414,6 +416,8 @@ ->with($this->callback(static function (Request $request) use ($expectedRequest) { $expectedRequest->server->remove('REQUEST_TIME_FLOAT'); $request->server->remove('REQUEST_TIME_FLOAT'); + $expectedRequest->server->remove('REQUEST_TIME'); + $request->server->remove('REQUEST_TIME'); return $expectedRequest == $request; })) diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -161,12 +161,12 @@ public function testProcessWhenNoSrcInAnEsi() { - $this->expectException(\RuntimeException::class); $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo <esi:include />'); - $this->assertSame($response, $esi->process($request, $response)); + $this->expectException(\RuntimeException::class); + $esi->process($request, $response); } public function testProcessRemoveSurrogateControlHeader() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -902,6 +902,52 @@ $this->assertEquals('Hello World', $this->response->getContent()); } + public function testReleasesTheLockWhenTheRevalidatedResponseIsNotStored() + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $this->markTestSkipped('Skips on windows to avoid permissions issues.'); + } + + // Last-Modified makes the response validateable, so it is stored although it is already stale + $this->setNextResponse(200, ['Cache-Control' => 'public, max-age=0, must-revalidate', 'Last-Modified' => 'some while ago'], 'Old response'); + $this->request('GET', '/'); + $this->assertTraceContains('store'); + + $this->setNextResponse(200, ['Cache-Control' => 'private'], 'New response'); + $this->request('GET', '/'); + $this->assertTraceContains('invalid'); + $this->assertTraceNotContains('store'); + + $this->assertFalse($this->store->isLocked(Request::create('/', 'GET'))); + $this->assertFalse($this->createStore()->isLocked(Request::create('/', 'GET'))); + } + + public function testReleasesTheLockWhenTheRevalidationThrows() + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $this->markTestSkipped('Skips on windows to avoid permissions issues.'); + } + + $this->setNextResponse(200, ['Cache-Control' => 'public, max-age=0, must-revalidate', 'Last-Modified' => 'some while ago'], 'Old response'); + $this->request('GET', '/'); + $this->assertTraceContains('store'); + + $this->setNextResponse(200, [], 'New response', static function () { + throw new \RuntimeException('Backend failure.'); + }); + + try { + $this->request('GET', '/'); + $this->fail('The backend error should be thrown.'); + } catch (\RuntimeException $e) { + $this->assertSame('Backend failure.', $e->getMessage()); + } + + $this->assertTraceContains('stale'); + $this->assertFalse($this->store->isLocked(Request::create('/', 'GET'))); + $this->assertFalse($this->createStore()->isLocked(Request::create('/', 'GET'))); + } + public function testDegradationWhenCacheLocked() { if ('\\' === \DIRECTORY_SEPARATOR) { @@ -943,6 +989,35 @@ $this->assertEquals('Old response', $this->response->getContent()); } + public function testDoesNotServeStaleWhileRevalidatingResponsesThatMustBeRevalidated() + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $this->markTestSkipped('Skips on windows to avoid permissions issues.'); + } + + $this->cacheConfig['stale_while_revalidate'] = 60; + + $this->setNextResponse(200, ['Cache-Control' => 'public, max-age=5, must-revalidate']); + $this->request('GET', '/must-revalidate'); + $this->setNextResponse(200, ['Cache-Control' => 'public, max-age=5, proxy-revalidate']); + $this->request('GET', '/proxy-revalidate'); + + $this->store->lock(Request::create('/must-revalidate')); + $this->store->lock(Request::create('/proxy-revalidate')); + + sleep(10); + + $this->store = $this->createStore(); // create another store instance that does not hold the current locks + + $this->request('GET', '/must-revalidate'); + $this->assertHttpKernelIsNotCalled(); + $this->assertSame(503, $this->response->getStatusCode()); + + $this->request('GET', '/proxy-revalidate'); + $this->assertHttpKernelIsNotCalled(); + $this->assertSame(503, $this->response->getStatusCode()); + } + public function testDegradationWhenCacheLockedWithEsi() { if ('\\' === \DIRECTORY_SEPARATOR) { @@ -986,6 +1061,32 @@ $this->assertSame('Old response with fragment', $this->response->getContent()); } + public function testRevalidatesResponsesWithNoCacheDirectiveWhenCacheLocked() + { + if ('\\' === \DIRECTORY_SEPARATOR) { + $this->markTestSkipped('Skips on windows to avoid permissions issues.'); + } + + $this->cacheConfig['stale_while_revalidate'] = 0; + + $this->setNextResponse(200, ['Cache-Control' => 'public, max-age=5, no-cache', 'ETag' => '"v1"'], 'Old response'); + $this->request('GET', '/'); + + $this->store->lock(Request::create('/', 'GET')); + + sleep(10); + + $this->setNextResponse(304, ['Cache-Control' => 'public, max-age=5, no-cache', 'ETag' => '"v1"']); + $this->store = $this->createStore(); // create another store instance that does not hold the current lock + $this->request('GET', '/'); + + $this->assertHttpKernelIsCalled(); + $this->assertTraceContains('valid'); + $this->assertSame(200, $this->response->getStatusCode()); + $this->assertFalse($this->response->headers->has('Retry-After')); + $this->assertSame('Old response', $this->response->getContent()); + } + public function testHitBackendOnlyOnceWhenCacheWasLocked() { // Disable stale-while-revalidate, it circumvents waiting for the lock @@ -2066,10 +2167,10 @@ $this->request('GET', '/', ['REMOTE_ADDR' => '10.0.0.1']); $this->assertSame($existing, Request::getTrustedProxies()); - $existing = array_unique(array_merge($existing, ['127.0.0.1'])); $this->kernel->assert(function ($backendRequest) use ($existing) { $this->assertSame($existing, Request::getTrustedProxies()); - $this->assertsame('10.0.0.1', $backendRequest->getClientIp()); + $this->assertTrue($backendRequest->isFromTrustedProxy()); + $this->assertSame('10.0.0.1', $backendRequest->getClientIp()); }); Request::setTrustedProxies([], -1); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -19,6 +19,7 @@ use Symfony\Component\HttpFoundation\StreamedResponse; use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Store; +use Symfony\Component\HttpKernel\Tests\Fixtures\WakingPayload; class StoreTest extends TestCase { @@ -320,6 +321,18 @@ $this->assertFalse($this->store->isLocked($req)); } + public function testWriteKeepsTheLockHeldByAnotherStore() + { + $holder = new Store(sys_get_temp_dir().'/http_cache'); + $this->assertTrue($holder->lock($this->request)); + + $this->store->write($this->request, new Response('v1')); + $this->assertTrue((new Store(sys_get_temp_dir().'/http_cache'))->isLocked($this->request)); + + $holder->write($this->request, new Response('v2')); + $this->assertSame($this->getStorePath('en'.hash('xxh128', 'v2')), $this->store->lookup($this->request)->headers->get('X-Body-File')); + } + public function testPurgeHttps() { $request = Request::create('https://example.com/foo'); @@ -521,6 +534,21 @@ $this->assertSame($content, $responseLook->getContent()); } + public function testMetadataIsReadWithoutInstantiatingObjects() + { + WakingPayload::reset(); + + $key = $this->store->write($this->request, $this->response); + + // the metadata file holds scalars and plain arrays; an attacker who can write to the cache directory must not be able to have an object built out of it + file_put_contents($this->getStorePath($key), serialize([[['payload' => new WakingPayload()], []]])); + + $metadata = $this->getStoreMetadata($key); + + $this->assertInstanceOf(\__PHP_Incomplete_Class::class, $metadata[0][0]['payload']); + $this->assertFalse(WakingPayload::$awoken); + } + protected function storeSimpleEntry($path = null, $headers = []) { $path ??= '/test'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/SubRequestHandlerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/SubRequestHandlerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/SubRequestHandlerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/Tests/HttpCache/SubRequestHandlerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -131,6 +131,66 @@ $this->assertSame($globalState, $this->getGlobalState()); } + public function testOtherRequestsFromLocalhostAreNotTrusted() + { + $mainRequest = Request::create('https://example.com/'); + $mainRequest->server->set('REMOTE_ADDR', '127.0.0.1'); + $mainRequest->headers->set('X-Forwarded-For', '10.0.0.2'); + $mainRequest->headers->set('X-Forwarded-Host', 'evil.example'); + $mainRequest->headers->set('X-Forwarded-Proto', 'http'); + $mainRequest->headers->set('X-Forwarded-Prefix', '//evil.example'); + + $kernel = new TestSubRequestHandlerKernel(function ($request) use ($mainRequest) { + $this->assertSame('example.com', $request->getHost()); + $this->assertSame('127.0.0.1', $mainRequest->getClientIp()); + $this->assertSame('example.com', $mainRequest->getHost()); + $this->assertTrue($mainRequest->isSecure()); + $this->assertSame('', $mainRequest->getBaseUrl()); + }); + + $subRequest = Request::create('/_fragment', 'GET', [], [], [], $mainRequest->server->all()); + SubRequestHandler::handle($kernel, $subRequest, HttpKernelInterface::SUB_REQUEST, false); + + $this->assertSame(self::$globalState, $this->getGlobalState()); + } + + public function testRequestsCopiedFromTheSubRequestAreTrusted() + { + Request::setTrustedProxies(['10.0.0.1'], -1); + + $request = Request::create('/'); + $request->server->set('REMOTE_ADDR', '10.0.0.1'); + $request->headers->set('X-Forwarded-For', '10.0.0.2'); + $request->headers->set('X-Forwarded-Host', 'foo.bar'); + + $kernel = new TestSubRequestHandlerKernel(function ($request) { + $copy = Request::create('/login', 'GET', [], [], [], $request->server->all()); + $this->assertSame('10.0.0.2', $copy->getClientIp()); + $this->assertSame('foo.bar', $copy->getHost()); + $this->assertSame('10.0.0.2', $request->duplicate()->getClientIp()); + }); + + SubRequestHandler::handle($kernel, $request, HttpKernelInterface::MAIN_REQUEST, true); + } + + public function testNestedSubRequestsKeepTheClientIp() + { + $request = Request::create('/'); + $request->server->set('REMOTE_ADDR', '10.0.0.1'); + + $kernel = new TestSubRequestHandlerKernel(function ($request) { + $fragmentKernel = new TestSubRequestHandlerKernel(function ($fragment) { + $this->assertSame('127.0.0.1', $fragment->server->get('REMOTE_ADDR')); + $this->assertSame('10.0.0.1', $fragment->getClientIp()); + }); + + $fragment = Request::create('/_fragment', 'GET', [], [], [], $request->server->all()); + SubRequestHandler::handle($fragmentKernel, $fragment, HttpKernelInterface::SUB_REQUEST, false); + }); + + SubRequestHandler::handle($kernel, $request, HttpKernelInterface::MAIN_REQUEST, true); + } + private function getGlobalState(): array { return [ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/composer.json symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/composer.json --- symfony-6.4.50+dfsg/src/Symfony/Component/HttpKernel/composer.json 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/HttpKernel/composer.json 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ "symfony/deprecation-contracts": "^2.5|^3", "symfony/error-handler": "^6.4|^7.0", "symfony/event-dispatcher": "^5.4|^6.0|^7.0", - "symfony/http-foundation": "^6.4|^7.0", + "symfony/http-foundation": "^6.4.51|^7.4.24", "symfony/polyfill-ctype": "^1.8", "psr/log": "^1|^2|^3" }, diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Ldap/Tests/Security/LdapUserProviderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -108,8 +108,6 @@ public function testLoadUserByIdentifierFailsIfMoreThanOneLdapPasswordsInEntry() { - $this->expectException(InvalidArgumentException::class); - $result = $this->createMock(CollectionInterface::class); $query = $this->createMock(QueryInterface::class); $query @@ -144,7 +142,8 @@ ; $provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, [], 'sAMAccountName', '({uid_key}={user_identifier})', 'userpassword'); - $this->assertInstanceOf(LdapUser::class, $provider->loadUserByIdentifier('foo')); + $this->expectException(InvalidArgumentException::class); + $provider->loadUserByIdentifier('foo'); } public function testLoadUserByIdentifierShouldNotFailIfEntryHasNoUidKeyAttribute() @@ -185,8 +184,6 @@ public function testLoadUserByIdentifierFailsIfEntryHasNoPasswordAttribute() { - $this->expectException(InvalidArgumentException::class); - $result = $this->createMock(CollectionInterface::class); $query = $this->createMock(QueryInterface::class); $query @@ -218,7 +215,8 @@ ; $provider = new LdapUserProvider($ldap, 'ou=MyBusiness,dc=symfony,dc=com', null, null, [], 'sAMAccountName', '({uid_key}={user_identifier})', 'userpassword'); - $this->assertInstanceOf(LdapUser::class, $provider->loadUserByIdentifier('foo')); + $this->expectException(InvalidArgumentException::class); + $provider->loadUserByIdentifier('foo'); } public function testLoadUserByIdentifierIsSuccessfulWithoutPasswordAttribute() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalPostgreSqlStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalPostgreSqlStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalPostgreSqlStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalPostgreSqlStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -33,7 +33,6 @@ class DoctrineDbalPostgreSqlStore implements BlockingSharedLockStoreInterface, BlockingStoreInterface { private Connection $conn; - private static array $storeRegistry = []; /** * You can either pass an existing database connection a Doctrine DBAL Connection @@ -206,6 +205,9 @@ return $this->getInternalStore()->exists($key); } + // forget a lock the session lost, for example after a reconnection, so that other keys can acquire it again + $this->getInternalStore()->delete($key); + return false; } @@ -317,8 +319,8 @@ private function getInternalStore(): SharedLockStoreInterface { - $namespace = spl_object_id($this->conn); + static $storeRegistry = new \WeakMap(); - return self::$storeRegistry[$namespace] ??= new InMemoryStore(); + return $storeRegistry[$this->conn] ??= new InMemoryStore(); } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -332,12 +332,13 @@ $platform = $this->conn->getDatabasePlatform(); return match (true) { + // NOW() is in the session time zone, so UNIX_TIMESTAMP(NOW(6)) jumps by an hour when DST ends $platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform, - $platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform => 'UNIX_TIMESTAMP(NOW(6))', + $platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform => 'UNIX_TIMESTAMP() + MICROSECOND(NOW(6)) / 1e6', $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform => "(julianday('now') - 2440587.5) * 86400.0", $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform, $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform => 'CAST(EXTRACT(epoch FROM NOW()) AS DOUBLE PRECISION)', - $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform => "(CAST(systimestamp AT TIME ZONE 'UTC' AS DATE) - DATE '1970-01-01') * 86400 + TO_NUMBER(TO_CHAR(systimestamp AT TIME ZONE 'UTC', 'SSSSS.FF'))", + $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform => "(TRUNC(systimestamp AT TIME ZONE 'UTC', 'MI') - DATE '1970-01-01') * 86400 + EXTRACT(SECOND FROM systimestamp)", $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform, $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform => "CAST(DATEDIFF_BIG(ms, '1970-01-01', SYSUTCDATETIME()) AS FLOAT) / 1000.0", default => (new \DateTimeImmutable())->format('U.u'), diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/MemcachedStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/MemcachedStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/MemcachedStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/MemcachedStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -62,7 +62,7 @@ { $token = $this->getUniqueToken($key); $key->reduceLifetime($this->initialTtl); - if (!$this->memcached->add((string) $key, $token, (int) ceil($this->initialTtl))) { + if (!$this->memcached->add($this->getKeyName($key), $token, $this->getExpiration($this->initialTtl))) { // the lock is already acquired. It could be us. Let's try to put off. $this->putOffExpiration($key, $this->initialTtl); } @@ -81,6 +81,7 @@ // Interface defines a float value but Store required an integer. $ttl = (int) ceil($ttl); + $expiration = $this->getExpiration($ttl); $token = $this->getUniqueToken($key); @@ -89,7 +90,7 @@ $key->reduceLifetime($ttl); // Could happens when we ask a putOff after a timeout but in luck nobody steal the lock if (\Memcached::RES_NOTFOUND === $this->memcached->getResultCode()) { - if ($this->memcached->add((string) $key, $token, $ttl)) { + if ($this->memcached->add($this->getKeyName($key), $token, $expiration)) { return; } @@ -102,7 +103,7 @@ throw new LockConflictedException(); } - if (!$this->memcached->cas($cas, (string) $key, $token, $ttl)) { + if (!$this->memcached->cas($cas, $this->getKeyName($key), $token, $expiration)) { throw new LockConflictedException(); } @@ -124,18 +125,18 @@ } // To avoid concurrency in deletion, the trick is to extends the TTL then deleting the key - if (!$this->memcached->cas($cas, (string) $key, $token, 2)) { + if (!$this->memcached->cas($cas, $this->getKeyName($key), $token, 2)) { // Someone steal our lock. It does not belongs to us anymore. Nothing to do. return; } // Now, we are the owner of the lock for 2 more seconds, we can delete it. - $this->memcached->delete((string) $key); + $this->memcached->delete($this->getKeyName($key)); } public function exists(Key $key): bool { - return $this->memcached->get((string) $key) === $this->getUniqueToken($key); + return $this->memcached->get($this->getKeyName($key)) === $this->getUniqueToken($key); } private function getUniqueToken(Key $key): string @@ -148,10 +149,16 @@ return $key->getState(__CLASS__); } + private function getExpiration(int $ttl): int + { + // memcached reads an expiration longer than 30 days as a Unix timestamp, which its text protocol parses as a 32-bit signed integer + return $ttl > 30 * 86400 ? min(time() + $ttl, 2147483647) : $ttl; + } + private function getValueAndCas(Key $key): array { if ($this->useExtendedReturn ??= version_compare(phpversion('memcached'), '2.9.9', '>')) { - $extendedReturn = $this->memcached->get((string) $key, null, \Memcached::GET_EXTENDED); + $extendedReturn = $this->memcached->get($this->getKeyName($key), null, \Memcached::GET_EXTENDED); if (\Memcached::GET_ERROR_RETURN_VALUE === $extendedReturn) { return [$extendedReturn, 0.0]; } @@ -160,8 +167,34 @@ } $cas = 0.0; - $value = $this->memcached->get((string) $key, null, $cas); + $value = $this->memcached->get($this->getKeyName($key), null, $cas); return [$value, $cas]; } + + /** + * Returns the name of the key in memcached, hashing the names that memcached rejects. + * + * Keys can't be longer than 250 bytes, prefix included. With the text protocol, they can't contain + * spaces or control characters, nor non-ASCII characters with php-memcached < 3.3 or its verify_key + * option. With the binary protocol, php-memcached only rejects "\n". + */ + private function getKeyName(Key $key): string + { + $name = (string) $key; + + if ($this->memcached->getOption(\Memcached::OPT_BINARY_PROTOCOL)) { + $invalidChars = '/\n/'; + } elseif ($this->memcached->getOption(\Memcached::OPT_VERIFY_KEY) || version_compare(phpversion('memcached'), '3.3', '<')) { + $invalidChars = '/[^\x21-\x7E]/'; + } else { + $invalidChars = '/[\x00-\x20\x7F]/'; + } + + if ('' === $name || \strlen($this->memcached->getOption(\Memcached::OPT_PREFIX_KEY).$name) > 250 || preg_match($invalidChars, $name)) { + return hash('sha256', $name); + } + + return $name; + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/MongoDbStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/MongoDbStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/MongoDbStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/MongoDbStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -298,7 +298,7 @@ public function exists(Key $key): bool { - $cursor = $this->manager->executeQuery($this->namespace, new Query( + $cursor = $this->getManager()->executeQuery($this->namespace, new Query( [ '_id' => (string) $key, 'token' => $this->getUniqueToken($key), diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/PdoStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/PdoStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/PdoStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/PdoStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -288,10 +288,11 @@ private function getCurrentTimestampStatement(): string { return match ($this->getDriver()) { - 'mysql' => 'UNIX_TIMESTAMP(NOW(6))', + // NOW() is in the session time zone, so UNIX_TIMESTAMP(NOW(6)) jumps by an hour when DST ends + 'mysql' => 'UNIX_TIMESTAMP() + MICROSECOND(NOW(6)) / 1e6', 'sqlite' => "(julianday('now') - 2440587.5) * 86400.0", 'pgsql' => 'CAST(EXTRACT(epoch FROM NOW()) AS DOUBLE PRECISION)', - 'oci' => "(CAST(systimestamp AT TIME ZONE 'UTC' AS DATE) - DATE '1970-01-01') * 86400 + TO_NUMBER(TO_CHAR(systimestamp AT TIME ZONE 'UTC', 'SSSSS.FF'))", + 'oci' => "(TRUNC(systimestamp AT TIME ZONE 'UTC', 'MI') - DATE '1970-01-01') * 86400 + EXTRACT(SECOND FROM systimestamp)", 'sqlsrv' => "CAST(DATEDIFF_BIG(ms, '1970-01-01', SYSUTCDATETIME()) AS FLOAT) / 1000.0", default => (new \DateTimeImmutable())->format('U.u'), }; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/PostgreSqlStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/PostgreSqlStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/PostgreSqlStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/PostgreSqlStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -31,7 +31,6 @@ private ?string $username = null; private ?string $password = null; private array $connectionOptions = []; - private static array $storeRegistry = []; /** * You can either pass an existing database connection as PDO instance or @@ -198,6 +197,9 @@ return $this->getInternalStore()->exists($key); } + // forget a lock the session lost, for example after pg_advisory_unlock_all(), so that other keys can acquire it again + $this->getInternalStore()->delete($key); + return false; } @@ -316,8 +318,8 @@ private function getInternalStore(): SharedLockStoreInterface { - $namespace = spl_object_id($this->getConnection()); + static $storeRegistry = new \WeakMap(); - return self::$storeRegistry[$namespace] ??= new InMemoryStore(); + return $storeRegistry[$this->getConnection()] ??= new InMemoryStore(); } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/RedisStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/RedisStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Store/RedisStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Store/RedisStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,6 +11,7 @@ namespace Symfony\Component\Lock\Store; +use Predis\Response\ErrorInterface; use Predis\Response\ServerException; use Relay\Relay; use Symfony\Component\Lock\Exception\InvalidTtlException; @@ -263,10 +264,17 @@ \assert($this->redis instanceof \Predis\ClientInterface); try { - return $this->redis->eval(...array_merge([$script, 1, $resource], $args)); + $result = $this->redis->eval(...array_merge([$script, 1, $resource], $args)); } catch (ServerException $e) { throw new LockStorageException($e->getMessage(), $e->getCode(), $e); } + + // a client created with the "exceptions" option disabled, as AbstractAdapter::createConnection() does, returns errors + if ($result instanceof ErrorInterface) { + throw new LockStorageException($result->getMessage()); + } + + return $result; } private function getUniqueToken(Key $key): string diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/KeyTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/KeyTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/KeyTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/KeyTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -20,6 +20,9 @@ */ class KeyTest extends TestCase { + /** + * @group time-sensitive + */ public function testSerialize() { $key = new Key(__METHOD__); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/AbstractRedisStoreTestCase.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/AbstractRedisStoreTestCase.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/AbstractRedisStoreTestCase.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/AbstractRedisStoreTestCase.php 2026-11-25 09:18:34.000000000 +0000 @@ -14,6 +14,7 @@ use Relay\Relay; use Symfony\Component\Lock\Exception\InvalidArgumentException; use Symfony\Component\Lock\Exception\LockConflictedException; +use Symfony\Component\Lock\Exception\LockStorageException; use Symfony\Component\Lock\Key; use Symfony\Component\Lock\PersistingStoreInterface; use Symfony\Component\Lock\Store\RedisStore; @@ -53,6 +54,36 @@ $newStore->save($key2); } + public function testSaveReportsErrorReplies() + { + $resource = uniqid(__METHOD__, true); + $redis = $this->getRedisConnection(); + $redis->hset($resource, 'field', 'value'); + + try { + $this->expectException(LockStorageException::class); + $this->expectExceptionMessage('WRONGTYPE'); + $this->getStore()->save(new Key($resource)); + } finally { + $redis->del($resource); + } + } + + public function testExistsReportsErrorReplies() + { + $resource = uniqid(__METHOD__, true); + $redis = $this->getRedisConnection(); + $redis->hset($resource, 'field', 'value'); + + try { + $this->expectException(LockStorageException::class); + $this->expectExceptionMessage('WRONGTYPE'); + $this->getStore()->exists(new Key($resource)); + } finally { + $redis->del($resource); + } + } + public function testWriteMemberIsNotOwnedByTheKeyThatNamesIt() { $store = $this->getStore(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalPostgreSqlStoreTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalPostgreSqlStoreTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalPostgreSqlStoreTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalPostgreSqlStoreTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -97,6 +97,18 @@ $this->assertTrue($store2->exists($key)); } + public function testInternalStoreIsFreedWithTheConnection() + { + $conn = $this->createPostgreSqlConnection(); + $store = new DoctrineDbalPostgreSqlStore($conn); + $store->save(new Key(__METHOD__)); + + $internalStore = \WeakReference::create((fn () => $this->getInternalStore())->call($store)); + unset($store, $conn); + + $this->assertNull($internalStore->get()); + } + public function testWaitAndSaveAfterConflictReleasesLockFromInternalStore() { $store1 = $this->getStore(); @@ -253,6 +265,68 @@ pg_close($waiter); } + public function testSaveAfterTheSessionIsLost() + { + $conn = $this->createPostgreSqlConnection(); + $store = new DoctrineDbalPostgreSqlStore($conn); + + $key1 = new Key(__METHOD__); + $store->save($key1); + + $conn->close(); + $store->delete($key1); + + $key2 = new Key(__METHOD__); + $store->save($key2); + + $this->assertTrue($store->exists($key2)); + $this->assertFalse($store->exists($key1)); + + $store->delete($key2); + $this->assertFalse($store->exists($key2)); + } + + public function testSaveAfterTheSessionIsLostWithAReadLock() + { + $conn = $this->createPostgreSqlConnection(); + $store = new DoctrineDbalPostgreSqlStore($conn); + + $key1 = new Key(__METHOD__); + $store->saveRead($key1); + + $conn->close(); + $store->delete($key1); + + $key2 = new Key(__METHOD__); + $store->save($key2); + + $this->assertTrue($store->exists($key2)); + $this->assertFalse($store->exists($key1)); + + $store->delete($key2); + $this->assertFalse($store->exists($key2)); + } + + public function testSaveAfterTheSessionIsLostWithoutDelete() + { + $conn = $this->createPostgreSqlConnection(); + $store = new DoctrineDbalPostgreSqlStore($conn); + + $key1 = new Key(__METHOD__); + $store->save($key1); + + $conn->close(); + $this->assertFalse($store->exists($key1)); + + $key2 = new Key(__METHOD__); + $store->save($key2); + + $this->assertTrue($store->exists($key2)); + + $store->delete($key2); + $this->assertFalse($store->exists($key2)); + } + private static function getDbalConnection(string $dsn): Connection { $params = class_exists(DsnParser::class) ? (new DsnParser(['sqlite' => 'pdo_sqlite']))->parse($dsn) : ['url' => $dsn]; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/DoctrineDbalStoreTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -35,6 +35,7 @@ class DoctrineDbalStoreTest extends AbstractStoreTestCase { use ExpiringStoreTestTrait; + use MysqlDaylightSavingTimeTestTrait; protected static string $dbFile; @@ -71,6 +72,17 @@ return new DoctrineDbalStore(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile], $config)); } + protected function createMysqlStore(array $params): array + { + $config = new Configuration(); + if (class_exists(DefaultSchemaManagerFactory::class)) { + $config->setSchemaManagerFactory(new DefaultSchemaManagerFactory()); + } + $conn = DriverManager::getConnection(['driver' => 'pdo_mysql'] + $params, $config); + + return [new DoctrineDbalStore($conn, [], 0.0), $conn->executeStatement(...)]; + } + public function testAbortAfterExpiration() { $this->markTestSkipped('Pdo expects a TTL greater than 1 sec. Simulating a slow network is too hard'); @@ -413,4 +425,18 @@ $table = $schema->getTable('lock_keys'); $this->assertSame([], $table->getColumns(), 'The table was not overwritten'); } + + public function testOracleClockCountsTheTimeOfDayOnce() + { + $conn = $this->createMock(Connection::class); + $conn->method('getDatabasePlatform') + ->willReturn($this->createStub(\Doctrine\DBAL\Platforms\OraclePlatform::class)); + $conn->expects($this->once()) + ->method('executeStatement') + ->with($this->stringContains("VALUES (?, ?, (TRUNC(systimestamp AT TIME ZONE 'UTC', 'MI') - DATE '1970-01-01') * 86400 + EXTRACT(SECOND FROM systimestamp) + 300)")) + ->willReturn(1); + + $store = new DoctrineDbalStore($conn, [], 0); + $store->save(new Key(__METHOD__)); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/MemcachedStoreTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -61,10 +61,99 @@ $this->markTestSkipped('Memcached expects a TTL greater than 1 sec. Simulating a slow network is too hard'); } + public function testTtlLongerThanThirtyDays() + { + $memcached = new \Memcached(); + $memcached->addServer(getenv('MEMCACHED_HOST'), 11211); + + $store = new MemcachedStore($memcached, 31 * 86400); + $key = new Key(uniqid(__METHOD__, true)); + + $store->save($key); + $this->assertTrue($store->exists($key)); + + $store->putOffExpiration($key, 45 * 86400); + $this->assertTrue($store->exists($key)); + + $memcached->delete((string) $key); + $store->putOffExpiration($key, 45 * 86400); + $this->assertTrue($store->exists($key)); + + $store->delete($key); + $this->assertFalse($store->exists($key)); + } + + public function testTtlEndingAfter2038() + { + $memcached = $this->createMock(\Memcached::class); + $memcached->expects($this->once()) + ->method('add') + ->with($this->anything(), $this->anything(), 2147483647) + ->willReturnCallback(static function (string $key, string $value) use (&$token) { + $token = $value; + + return true; + }); + $memcached->method('get')->willReturnCallback(static function () use (&$token) { + return ['value' => $token, 'cas' => 1]; + }); + $memcached->method('getResultCode')->willReturn(\Memcached::RES_SUCCESS); + $memcached->expects($this->once()) + ->method('cas') + ->with(1, $this->anything(), $this->anything(), 2147483647) + ->willReturn(true); + + $store = new MemcachedStore($memcached, 100 * 365 * 86400); + $key = new Key(__METHOD__); + + $store->save($key); + $store->putOffExpiration($key, 100 * 365 * 86400); + } + public function testInvalidTtl() { $this->expectException(InvalidTtlException::class); $store = $this->getStore(); $store->putOffExpiration(new Key('toto'), 0.1); } + + public function testKeysRejectedByMemcachedAreHashed() + { + $memcached = new \Memcached(); + $memcached->addServer(getenv('MEMCACHED_HOST'), 11211); + $memcached->setOption(\Memcached::OPT_PREFIX_KEY, 'lock_'); + $store = new MemcachedStore($memcached); + + foreach (['', 'a b', "a\nb", str_repeat('a', 246)] as $resource) { + $key = new Key($resource); + + $store->save($key); + $this->assertTrue($store->exists($key)); + $this->assertSame($key->getState(MemcachedStore::class), $memcached->get(hash('sha256', $resource))); + + $store->putOffExpiration($key, 300); + $this->assertTrue($store->exists($key)); + + $store->delete($key); + $this->assertFalse($store->exists($key)); + } + } + + public function testKeysAcceptedByMemcachedAreNotHashed() + { + $memcached = new \Memcached(); + $memcached->addServer(getenv('MEMCACHED_HOST'), 11211); + $memcached->setOption(\Memcached::OPT_BINARY_PROTOCOL, true); + $memcached->setOption(\Memcached::OPT_PREFIX_KEY, 'lock_'); + $store = new MemcachedStore($memcached); + + foreach (['a b', str_repeat('a', 245)] as $resource) { + $key = new Key($resource); + + $store->save($key); + $this->assertSame($key->getState(MemcachedStore::class), $memcached->get($resource)); + + $store->delete($key); + } + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/MongoDbStoreTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/MongoDbStoreTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/MongoDbStoreTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/MongoDbStoreTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -88,6 +88,8 @@ $store = new MongoDbStore($mongo, $options); + $this->assertFalse($store->exists($key)); + $store->save($key); $this->assertTrue($store->exists($key)); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/MysqlDaylightSavingTimeTestTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/MysqlDaylightSavingTimeTestTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/MysqlDaylightSavingTimeTestTrait.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/MysqlDaylightSavingTimeTestTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,81 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Lock\Tests\Store; + +use Symfony\Component\Lock\Exception\LockConflictedException; +use Symfony\Component\Lock\Key; +use Symfony\Component\Lock\PersistingStoreInterface; + +trait MysqlDaylightSavingTimeTestTrait +{ + /** + * @param array{host: string, user: string, password: string, dbname: string} $params + * + * @return array{PersistingStoreInterface, \Closure(string): mixed} The store and a closure that runs SQL on its connection + */ + abstract protected function createMysqlStore(array $params): array; + + /** + * @requires extension pdo_mysql + * + * @group integration + */ + public function testMysqlLockSurvivesDaylightSavingTimeChange() + { + // On 2025-11-02, America/Chicago went from 02:00 CDT back to 01:00 CST at 07:00 UTC, so 01:00-02:00 local happened twice. + $this->doTestMysqlLockSurvivesDaylightSavingTimeChange('lock taken before 02:00 CST', gmmktime(7, 58, 0, 11, 2, 2025), gmmktime(8, 0, 30, 11, 2, 2025), true); + $this->doTestMysqlLockSurvivesDaylightSavingTimeChange('lock expired after the second 01:00', gmmktime(6, 58, 0, 11, 2, 2025), gmmktime(7, 4, 0, 11, 2, 2025), false); + } + + private function doTestMysqlLockSurvivesDaylightSavingTimeChange(string $case, int $holderTime, int $contenderTime, bool $holderKeepsLock) + { + if (!$host = getenv('MYSQL_HOST')) { + $this->markTestSkipped('Missing MYSQL_HOST env variable'); + } + + $params = [ + 'host' => $host, + 'user' => getenv('MYSQL_USERNAME') ?: 'root', + 'password' => getenv('MYSQL_PASSWORD') ?: '', + 'dbname' => 'symfony_lock_test', + ]; + $pdo = new \PDO('mysql:host='.$host, $params['user'], $params['password']); + + if (null === $pdo->query("SELECT CONVERT_TZ('2025-11-02 07:00:00', '+00:00', 'America/Chicago')")->fetchColumn()) { + $this->markTestSkipped('MySQL time zone tables are not loaded'); + } + + $pdo->exec('CREATE DATABASE IF NOT EXISTS symfony_lock_test'); + + try { + [$store, $exec] = $this->createMysqlStore($params); + $exec("SET time_zone = 'America/Chicago'"); + $holder = new Key(__METHOD__); + $contender = new Key(__METHOD__); + + $exec('SET TIMESTAMP = '.$holderTime); + $store->save($holder); + + $exec('SET TIMESTAMP = '.$contenderTime); + try { + $store->save($contender); + } catch (LockConflictedException) { + // expected when the holder keeps the lock + } + + $this->assertSame($holderKeepsLock, $store->exists($holder), $case); + $this->assertSame(!$holderKeepsLock, $store->exists($contender), $case); + } finally { + $pdo->exec('DROP DATABASE IF EXISTS symfony_lock_test'); + } + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/PdoStoreTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -25,6 +25,7 @@ class PdoStoreTest extends AbstractStoreTestCase { use ExpiringStoreTestTrait; + use MysqlDaylightSavingTimeTestTrait; protected static string $dbFile; @@ -51,6 +52,13 @@ return new PdoStore('sqlite:'.self::$dbFile); } + protected function createMysqlStore(array $params): array + { + $pdo = new \PDO('mysql:host='.$params['host'].';dbname='.$params['dbname'], $params['user'], $params['password']); + + return [new PdoStore($pdo, [], 0.0), $pdo->exec(...)]; + } + public function testAbortAfterExpiration() { $this->markTestSkipped('Pdo expects a TTL greater than 1 sec. Simulating a slow network is too hard'); @@ -199,4 +207,21 @@ $pdo->exec('DROP TABLE IF EXISTS lock_keys'); } } + + public function testOracleClockCountsTheTimeOfDayOnce() + { + $pdo = $this->createMock(\PDO::class); + $pdo->method('getAttribute') + ->willReturnMap([ + [\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION], + [\PDO::ATTR_DRIVER_NAME, 'oci'], + ]); + $pdo->expects($this->once()) + ->method('prepare') + ->with($this->stringContains("VALUES (:id, :token, (TRUNC(systimestamp AT TIME ZONE 'UTC', 'MI') - DATE '1970-01-01') * 86400 + EXTRACT(SECOND FROM systimestamp) + 300)")) + ->willReturn($this->createStub(\PDOStatement::class)); + + $store = new PdoStore($pdo, [], 0); + $store->save(new Key(__METHOD__)); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/PostgreSqlStoreTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/PostgreSqlStoreTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/PostgreSqlStoreTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/PostgreSqlStoreTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -84,6 +84,27 @@ $this->assertTrue($store2->exists($key)); } + public function testWaitAndSaveOnANewConnectionAfterTheOldOneIsFreed() + { + $pdo = new \PDO('pgsql:host='.$this->getPostgresHost(), 'postgres', 'password'); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + (new PostgreSqlStore($pdo))->save(new Key(__METHOD__)); + $pdo = null; + + // PHP reuses the object id of the freed connection for the new one + $pdo = new \PDO('pgsql:host='.$this->getPostgresHost(), 'postgres', 'password'); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $pdo->exec('SET lock_timeout = 5000'); + $store = new PostgreSqlStore($pdo); + + $key = new Key(__METHOD__); + // the server can still be ending the old session + $store->waitAndSave($key); + $this->assertTrue($store->exists($key)); + + $store->delete($key); + } + public function testWaitAndSaveAfterConflictReleasesLockFromInternalStore() { $store1 = $this->getStore(); @@ -245,4 +266,25 @@ $this->assertSame(\PGSQL_TUPLES_OK, pg_result_status(pg_get_result($waiter))); pg_close($waiter); } + + public function testSaveAfterTheSessionLostTheLock() + { + $pdo = new \PDO('pgsql:host='.$this->getPostgresHost(), 'postgres', 'password'); + $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + $store = new PostgreSqlStore($pdo); + + $key1 = new Key(__METHOD__); + $store->save($key1); + + $pdo->exec('SELECT pg_advisory_unlock_all()'); + $this->assertFalse($store->exists($key1)); + + $key2 = new Key(__METHOD__); + $store->save($key2); + + $this->assertTrue($store->exists($key2)); + + $store->delete($key2); + $this->assertFalse($store->exists($key2)); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/PredisStoreWithoutExceptionsTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/PredisStoreWithoutExceptionsTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Lock/Tests/Store/PredisStoreWithoutExceptionsTest.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Lock/Tests/Store/PredisStoreWithoutExceptionsTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,60 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Lock\Tests\Store; + +use Predis\Command\CommandInterface; +use Predis\Connection\Parameters; +use Predis\Connection\StreamConnection; +use Predis\Response\ServerException; +use Symfony\Component\Lock\Exception\LockStorageException; +use Symfony\Component\Lock\Key; +use Symfony\Component\Lock\Store\RedisStore; + +/** + * @group integration + */ +class PredisStoreWithoutExceptionsTest extends AbstractRedisStoreTestCase +{ + public static function setUpBeforeClass(): void + { + $redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]), ['exceptions' => false]); + try { + $redis->connect(); + } catch (\Exception $e) { + self::markTestSkipped($e->getMessage()); + } + } + + protected function getRedisConnection(): \Predis\Client + { + $redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]), ['exceptions' => false]); + $redis->connect(); + + return $redis; + } + + public function testSaveReportsErrorRepliesReturnedAsServerExceptions() + { + // Predis' RelayConnection returns error replies as ServerException objects instead of Error ones + $connection = new class(Parameters::create([])) extends StreamConnection { + public function executeCommand(CommandInterface $command): mixed + { + return new ServerException('READONLY You can\'t write against a read only replica.'); + } + }; + $store = new RedisStore(new \Predis\Client($connection, ['exceptions' => false])); + + $this->expectException(LockStorageException::class); + $this->expectExceptionMessage('READONLY'); + $store->save(new Key(__METHOD__)); + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Mailer/Tests/Transport/Smtp/SmtpTransportTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Mailer/Tests/Transport/Smtp/SmtpTransportTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Mailer/Tests/Transport/Smtp/SmtpTransportTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Mailer/Tests/Transport/Smtp/SmtpTransportTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -352,6 +352,23 @@ $this->assertSame(2, $calls); } + public function testParseMessageId() + { + $transport = new SmtpTransport(new DummyStream()); + $parseMessageId = new \ReflectionMethod($transport, 'parseMessageId'); + + $this->assertSame('000501c4054c', $parseMessageId->invoke($transport, "250 OK queued as 000501c4054c\r\n")); + $this->assertSame('4ZrPq51nVbz9sWg', $parseMessageId->invoke($transport, "250 2.0.0 Ok: queued as 4ZrPq51nVbz9sWg\r\n")); + $this->assertSame('X8P9ZIaiT3653-UXj4ljGX', $parseMessageId->invoke($transport, "250 Ok: queued as X8P9ZIaiT3653-UXj4ljGX\r\n")); + $this->assertSame('0100018b1f5e6d2a-3c4d5e6f-7a8b-4c9d-0e1f-2a3b4c5d6e7f-000000', $parseMessageId->invoke($transport, "250 Ok 0100018b1f5e6d2a-3c4d5e6f-7a8b-4c9d-0e1f-2a3b4c5d6e7f-000000\r\n")); + $this->assertSame('1rXyzA-000abc-12', $parseMessageId->invoke($transport, "250 OK id=1rXyzA-000abc-12\r\n")); + $this->assertSame('d7ef132b5d7711eea8c8000c29c33806', $parseMessageId->invoke($transport, "250 OK ids=d7ef132b5d7711eea8c8000c29c33806\r\n")); + $this->assertSame('edd8d788b4a111f098b2cc28aa0a5c5a', $parseMessageId->invoke($transport, "250-super fantastic!\r\n250 OK ids=edd8d788b4a111f098b2cc28aa0a5c5a\r\n")); + $this->assertSame('', $parseMessageId->invoke($transport, "250 2.0.0 OK: queued\r\n")); + $this->assertSame('', $parseMessageId->invoke($transport, "250 ok dirdel\r\n")); + $this->assertSame('', $parseMessageId->invoke($transport, "250 OK\r\n")); + } + public function testAssertResponseCodeNoCodes() { $this->expectException(LogicException::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php symfony-6.4.51+dfsg/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Mailer/Transport/Smtp/SmtpTransport.php 2026-11-25 09:18:34.000000000 +0000 @@ -170,7 +170,8 @@ protected function parseMessageId(string $mtaResult): string { - return preg_match('/^250 (?:\S+ )?Ok:?+ (?:queued as |id=)?+(?P<id>[A-Z0-9._-]++)/im', $mtaResult, $matches) ? $matches['id'] : ''; + // an id without a prefix must contain a digit, so that a word like "queued" is not taken as the id + return preg_match('/^250 (?:\S+ )?Ok:?+ (?:queued as |ids?=|(?=[A-Z._-]*+\d))(?P<id>[A-Z0-9._-]++)/im', $mtaResult, $matches) ? $matches['id'] : ''; } public function __toString(): string diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Tests/Transport/ConnectionTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -255,6 +255,34 @@ Connection::fromDsn('sqs://default?foo=foo', ['bar' => 'bar']); } + public function testFromDsnWithInvalidQueryOptionValues() + { + $cases = [ + 'visibility_timeout=abc' => 'Option "visibility_timeout" of the Amazon SQS Messenger transport must be an integer.', + 'visibility_timeout=' => 'Option "visibility_timeout" of the Amazon SQS Messenger transport must be an integer.', + 'wait_time=abc' => 'Option "wait_time" of the Amazon SQS Messenger transport must be an integer.', + 'buffer_size=abc' => 'Option "buffer_size" of the Amazon SQS Messenger transport must be an integer.', + 'auto_setup=nope' => 'Option "auto_setup" of the Amazon SQS Messenger transport must be a boolean.', + ]; + + foreach ($cases as $query => $message) { + try { + Connection::fromDsn('sqs://default/queue?'.$query); + $this->fail(\sprintf('"%s" should have been rejected.', $query)); + } catch (\InvalidArgumentException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + } + + public function testFromDsnWithInvalidOptionValues() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Option "visibility_timeout" of the Amazon SQS Messenger transport must be an integer.'); + + Connection::fromDsn('sqs://default/queue', ['visibility_timeout' => 1.5]); + } + public function testKeepGettingPendingMessages() { $client = $this->createMock(SqsClient::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/AmazonSqs/Transport/Connection.php 2026-11-25 09:18:34.000000000 +0000 @@ -129,11 +129,11 @@ $options = $query + $options + self::DEFAULT_OPTIONS; $configuration = [ - 'buffer_size' => (int) $options['buffer_size'], - 'wait_time' => (int) $options['wait_time'], + 'buffer_size' => filter_var($options['buffer_size'], \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "buffer_size" of the Amazon SQS Messenger transport must be an integer.'), + 'wait_time' => filter_var($options['wait_time'], \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "wait_time" of the Amazon SQS Messenger transport must be an integer.'), 'poll_timeout' => $options['poll_timeout'], - 'visibility_timeout' => null !== $options['visibility_timeout'] ? (int) $options['visibility_timeout'] : null, - 'auto_setup' => filter_var($options['auto_setup'], \FILTER_VALIDATE_BOOL), + 'visibility_timeout' => null !== $options['visibility_timeout'] ? filter_var($options['visibility_timeout'], \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "visibility_timeout" of the Amazon SQS Messenger transport must be an integer.') : null, + 'auto_setup' => filter_var($options['auto_setup'], \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "auto_setup" of the Amazon SQS Messenger transport must be a boolean.'), 'queue_name' => (string) $options['queue_name'], ]; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Tests/Transport/ConnectionTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -243,6 +243,36 @@ Connection::fromDsn($dsn, $options); } + public function testFromDsnWithInvalidQueryOptions() + { + $cases = [ + 'heartbeat=abc' => 'Option "heartbeat" of the AMQP Messenger transport must be an integer.', + 'sasl_method=EXTERNAL' => 'Option "sasl_method" of the AMQP Messenger transport must be an integer.', + 'read_timeout=abc' => 'Option "read_timeout" of the AMQP Messenger transport must be a number.', + 'confirm_timeout=1s' => 'Option "confirm_timeout" of the AMQP Messenger transport must be a number.', + 'auto_setup=nope' => 'Option "auto_setup" of the AMQP Messenger transport must be a boolean.', + 'persistent=nope' => 'Option "persistent" of the AMQP Messenger transport must be a boolean.', + 'delay[daily_delay_queues]=nope' => 'Option "delay.daily_delay_queues" of the AMQP Messenger transport must be a boolean.', + ]; + + foreach ($cases as $query => $message) { + try { + Connection::fromDsn('amqp://localhost?'.$query); + $this->fail(\sprintf('"%s" should have been rejected.', $query)); + } catch (InvalidArgumentException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + } + + public function testFromDsnWithInvalidOptions() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Option "heartbeat" of the AMQP Messenger transport must be an integer.'); + + Connection::fromDsn('amqp://localhost', ['heartbeat' => 1.5]); + } + public function testCredentialsAreNotExposedInTrace() { if (!class_exists(\SensitiveParameterValue::class)) { @@ -299,6 +329,50 @@ $connection->publish('body'); } + public function testItReadsThePersistentOptionAsABoolean() + { + $amqpConnection = $this->createStub(\AMQPConnection::class); + foreach (['connect', 'pconnect', 'disconnect', 'pdisconnect'] as $method) { + $amqpConnection->method($method)->willReturnCallback(static function () use (&$calls, $method) { + $calls[] = $method; + }); + } + $amqpChannel = $this->createStub(\AMQPChannel::class); + $amqpChannel->method('getConnection')->willReturn($amqpConnection); + $factory = new TestAmqpFactory($amqpConnection, $amqpChannel, $this->createStub(\AMQPQueue::class), $this->createStub(\AMQPExchange::class)); + + $getCalls = static function (Connection $connection) use (&$calls): array { + $calls = []; + $connection->channel(); + (new \ReflectionProperty($connection, 'lastActivityTime'))->setValue($connection, time() - 3); + $connection->channel(); + + return $calls; + }; + + $cases = [ + 'persistent=true' => true, + 'persistent=yes' => true, + 'persistent=on' => true, + 'persistent=1' => true, + 'persistent=false' => false, + 'persistent=no' => false, + 'persistent=off' => false, + 'persistent=0' => false, + 'persistent=' => false, + ]; + + foreach ($cases as $query => $persistent) { + $expected = $persistent ? ['pconnect', 'pdisconnect'] : ['connect', 'disconnect']; + $this->assertSame($expected, $getCalls(Connection::fromDsn('amqp://localhost?heartbeat=1&'.$query, [], $factory)), $query); + } + + $this->assertSame(['pconnect', 'pdisconnect'], $getCalls(Connection::fromDsn('amqp://localhost?heartbeat=1', ['persistent' => true], $factory))); + $this->assertSame(['connect', 'disconnect'], $getCalls(Connection::fromDsn('amqp://localhost?heartbeat=1', ['persistent' => false], $factory))); + $this->assertSame(['connect', 'disconnect'], $getCalls(Connection::fromDsn('amqp://localhost?heartbeat=1', ['persistent' => null], $factory))); + $this->assertSame(['connect', 'disconnect'], $getCalls(new Connection(['heartbeat' => 1, 'persistent' => 'false'], [], [], $factory))); + } + public function testItSetupsTheConnectionWithDefaults() { $factory = new TestAmqpFactory( @@ -757,6 +831,20 @@ } } + public function testNoCaCertOnSslConnectionWhenCaCertIsFalse() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('No CA certificate has been provided.'); + + $oldCaCertValue = ini_set('amqp.cacert', ''); + + try { + Connection::fromDsn('amqps://', ['cacert' => false]); + } finally { + ini_set('amqp.cacert', $oldCaCertValue); + } + } + public function testAmqpStampHeadersAreUsed() { $factory = new TestAmqpFactory( @@ -890,6 +978,17 @@ $connection->publish('body'); } + public function testItPublishMessagesWithoutWaitingForConfirmationWhenConfirmTimeoutIsEmpty() + { + $factory = new TestAmqpFactory($this->createStub(\AMQPConnection::class), $amqpChannel = $this->createMock(\AMQPChannel::class), $this->createStub(\AMQPQueue::class), $this->createStub(\AMQPExchange::class)); + + $amqpChannel->expects($this->never())->method('confirmSelect'); + $amqpChannel->expects($this->never())->method('waitForConfirm'); + + $connection = Connection::fromDsn('amqp://localhost?confirm_timeout=', [], $factory); + $connection->publish('body'); + } + public function testSetChannelToConfirmMessage() { $factory = new TestAmqpFactory( @@ -978,6 +1077,82 @@ ); } + public function testItReadsTheVerifyOptionAsABoolean() + { + $factory = $this->createStub(AmqpFactory::class); + $factory->method('createConnection')->willReturnCallback(function (array $credentials) use (&$connectionOptions) { + $connectionOptions = $credentials; + + return $this->createStub(\AMQPConnection::class); + }); + $factory->method('createChannel')->willReturn($this->createStub(\AMQPChannel::class)); + + $cases = [ + 'verify=true' => true, + 'verify=yes' => true, + 'verify=on' => true, + 'verify=1' => true, + 'verify=false' => false, + 'verify=no' => false, + 'verify=off' => false, + 'verify=0' => false, + 'verify=' => false, + ]; + + foreach ($cases as $query => $verify) { + Connection::fromDsn('amqps://localhost?cacert=/etc/ssl/certs&'.$query, [], $factory)->channel(); + $this->assertSame($verify, $connectionOptions['verify'], $query); + } + + Connection::fromDsn('amqps://localhost?cacert=/etc/ssl/certs', ['verify' => 'true'], $factory)->channel(); + $this->assertTrue($connectionOptions['verify']); + + Connection::fromDsn('amqps://localhost?cacert=/etc/ssl/certs', ['verify' => null], $factory)->channel(); + $this->assertArrayNotHasKey('verify', $connectionOptions); + } + + public function testItRejectsInvalidVerifyOptions() + { + foreach (['verify=ture', 'verify=2', 'verify[]=1'] as $query) { + try { + Connection::fromDsn('amqps://localhost?cacert=/etc/ssl/certs&'.$query); + $this->fail('"'.$query.'" should have been rejected.'); + } catch (InvalidArgumentException $e) { + $this->assertSame('Option "verify" of the AMQP Messenger transport must be a boolean.', $e->getMessage()); + } + } + } + + public function testTheAmqpExtensionGetsTheVerifyOption() + { + $factory = $this->createStub(AmqpFactory::class); + $factory->method('createConnection')->willReturnCallback(function (array $credentials) use (&$verify) { + $verify = (new AmqpFactory())->createConnection($credentials)->getVerify(); + + return $this->createStub(\AMQPConnection::class); + }); + $factory->method('createChannel')->willReturn($this->createStub(\AMQPChannel::class)); + + $cases = [ + 'verify=true' => true, + 'verify=yes' => true, + 'verify=on' => true, + 'verify=1' => true, + 'verify=false' => false, + 'verify=no' => false, + 'verify=off' => false, + 'verify=0' => false, + ]; + + foreach ($cases as $query => $expected) { + Connection::fromDsn('amqps://localhost?cacert=/etc/ssl/certs&'.$query, [], $factory)->channel(); + $this->assertSame($expected, $verify, $query); + } + + Connection::fromDsn('amqps://localhost?cacert=/etc/ssl/certs', ['verify' => null], $factory)->channel(); + $this->assertSame((new AmqpFactory())->createConnection([])->getVerify(), $verify); + } + public function testItCanRetryPublishWhenAMQPConnectionExceptionIsThrown() { $factory = new TestAmqpFactory( diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Amqp/Transport/Connection.php 2026-11-25 09:18:34.000000000 +0000 @@ -216,12 +216,29 @@ $exchangeOptions = $amqpOptions['exchange']; $queuesOptions = $amqpOptions['queues']; unset($amqpOptions['queues'], $amqpOptions['exchange']); + + foreach (['heartbeat', 'sasl_method'] as $k) { + if ('' !== ($amqpOptions[$k] ?? '')) { + $amqpOptions[$k] = filter_var($amqpOptions[$k], \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "%s" of the AMQP Messenger transport must be an integer.', $k)); + } + } + + foreach (['read_timeout', 'write_timeout', 'connect_timeout', 'rpc_timeout', 'confirm_timeout'] as $k) { + if ('' !== ($amqpOptions[$k] ?? '')) { + $amqpOptions[$k] = filter_var($amqpOptions[$k], \FILTER_VALIDATE_FLOAT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "%s" of the AMQP Messenger transport must be a number.', $k)); + } + } + if (isset($amqpOptions['auto_setup'])) { - $amqpOptions['auto_setup'] = filter_var($amqpOptions['auto_setup'], \FILTER_VALIDATE_BOOL); + $amqpOptions['auto_setup'] = filter_var($amqpOptions['auto_setup'], \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "auto_setup" of the AMQP Messenger transport must be a boolean.'); + } + + if (isset($amqpOptions['persistent'])) { + $amqpOptions['persistent'] = filter_var($amqpOptions['persistent'], \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "persistent" of the AMQP Messenger transport must be a boolean.'); } if (isset($amqpOptions['delay']['daily_delay_queues'])) { - $amqpOptions['delay']['daily_delay_queues'] = filter_var($amqpOptions['delay']['daily_delay_queues'], \FILTER_VALIDATE_BOOL); + $amqpOptions['delay']['daily_delay_queues'] = filter_var($amqpOptions['delay']['daily_delay_queues'], \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "delay.daily_delay_queues" of the AMQP Messenger transport must be a boolean.'); } $queuesOptions = array_map(static function ($queueOptions) { @@ -243,6 +260,13 @@ throw new InvalidArgumentException('No CA certificate has been provided. Set "amqp.cacert" in your php.ini or pass the "cacert" parameter in the DSN to use SSL. Alternatively, you can use amqp:// to use without SSL.'); } + // ext-amqp casts "verify" to an integer, which turns null and strings like "true" into false + if (null === ($amqpOptions['verify'] ?? null)) { + unset($amqpOptions['verify']); + } else { + $amqpOptions['verify'] = filter_var($amqpOptions['verify'], \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException('Option "verify" of the AMQP Messenger transport must be a boolean.'); + } + return new self($amqpOptions, $exchangeOptions, $queuesOptions, $amqpFactory); } @@ -289,7 +313,7 @@ private static function hasCaCertConfigured(array $amqpOptions): bool { - return (isset($amqpOptions['cacert']) && '' !== $amqpOptions['cacert']) || '' !== \ini_get('amqp.cacert'); + return !\in_array($amqpOptions['cacert'] ?? null, [null, false, ''], true) || '' !== \ini_get('amqp.cacert'); } /** @@ -530,7 +554,7 @@ { if (!isset($this->amqpChannel)) { $connection = $this->amqpFactory->createConnection($this->connectionOptions); - $connectMethod = 'true' === ($this->connectionOptions['persistent'] ?? 'false') ? 'pconnect' : 'connect'; + $connectMethod = filter_var($this->connectionOptions['persistent'] ?? false, \FILTER_VALIDATE_BOOL) ? 'pconnect' : 'connect'; try { $connection->{$connectMethod}(); @@ -550,7 +574,7 @@ $this->lastActivityTime = time(); } elseif (0 < ($this->connectionOptions['heartbeat'] ?? 0) && time() > $this->lastActivityTime + 2 * $this->connectionOptions['heartbeat'] && 0 === $this->inFlightMessages) { - $disconnectMethod = 'true' === ($this->connectionOptions['persistent'] ?? 'false') ? 'pdisconnect' : 'disconnect'; + $disconnectMethod = filter_var($this->connectionOptions['persistent'] ?? false, \FILTER_VALIDATE_BOOL) ? 'pdisconnect' : 'disconnect'; $this->amqpChannel->getConnection()->{$disconnectMethod}(); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/ConnectionTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -619,6 +619,33 @@ Connection::buildConfiguration('doctrine://default?new_option=woops'); } + public function testBuildConfigurationWithInvalidQueryOptions() + { + $cases = [ + 'redeliver_timeout=1h' => 'Option "redeliver_timeout" of the Doctrine Messenger transport must be an integer.', + 'redeliver_timeout=1.5' => 'Option "redeliver_timeout" of the Doctrine Messenger transport must be an integer.', + 'redeliver_timeout=' => 'Option "redeliver_timeout" of the Doctrine Messenger transport must be an integer.', + 'auto_setup=nope' => 'Option "auto_setup" of the Doctrine Messenger transport must be a boolean.', + ]; + + foreach ($cases as $query => $message) { + try { + Connection::buildConfiguration('doctrine://default?'.$query); + $this->fail(\sprintf('"%s" should have been rejected.', $query)); + } catch (InvalidArgumentException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + } + + public function testBuildConfigurationWithInvalidOptions() + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Option "redeliver_timeout" of the Doctrine Messenger transport must be an integer.'); + + Connection::buildConfiguration('doctrine://default', ['redeliver_timeout' => 1.5]); + } + public function testFind() { $queryBuilder = $this->getQueryBuilderStub(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineIntegrationTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineIntegrationTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineIntegrationTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrineIntegrationTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -203,6 +203,39 @@ $this->assertEquals('the body', $envelope['body']); } + public function testSetupReplacesTheIndexesOfATableCreatedBeforeTheCompositeIndex() + { + $this->connection->setup(); + $compositeIndex = $this->listIndexNames(); + $this->assertCount(1, $compositeIndex); + + // bring the table back to the single-column indexes of older versions + $platform = $this->driverConnection->getDatabasePlatform(); + $this->driverConnection->executeStatement($platform->getDropIndexSQL($compositeIndex[0], 'messenger_messages')); + + foreach (['queue_name', 'available_at', 'delivered_at'] as $column) { + $this->driverConnection->executeStatement(\sprintf('CREATE INDEX idx_%s ON messenger_messages (%s)', $column, $column)); + } + + $this->assertSame(['idx_available_at', 'idx_delivered_at', 'idx_queue_name'], $this->listIndexNames()); + + $this->connection->setup(); + + $this->assertSame($compositeIndex, $this->listIndexNames()); + } + + /** + * @return list<string> + */ + private function listIndexNames(): array + { + $names = array_keys($this->createSchemaManager()->listTableIndexes('messenger_messages')); + $names = array_filter($names, static fn ($name) => 'primary' !== $name); + sort($names); + + return $names; + } + private function formatDateTime(\DateTimeImmutable $dateTime): string { return $dateTime->format($this->driverConnection->getDatabasePlatform()->getDateTimeFormatString()); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrinePostgreSqlNotifyIntegrationTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrinePostgreSqlNotifyIntegrationTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrinePostgreSqlNotifyIntegrationTest.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/DoctrinePostgreSqlNotifyIntegrationTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,187 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Messenger\Bridge\Doctrine\Tests\Transport; + +use Doctrine\DBAL\Configuration; +use Doctrine\DBAL\Connection; +use Doctrine\DBAL\Driver\PgSQL\Driver; +use Doctrine\DBAL\DriverManager; +use Doctrine\DBAL\Schema\DefaultSchemaManagerFactory; +use Doctrine\DBAL\Tools\DsnParser; +use PHPUnit\Framework\TestCase; +use Symfony\Component\Messenger\Bridge\Doctrine\Transport\PostgreSqlConnection; + +/** + * @requires extension pgsql + * + * @group integration + */ +class DoctrinePostgreSqlNotifyIntegrationTest extends TestCase +{ + private const NOTIFY_DELAY_IN_SECONDS = 0.3; + private const LONG_TIMEOUT_IN_MS = 10000; + private const MESSAGE_BODY = '{"message": "Hi"}'; + + private Connection $driverConnection; + private Connection $senderConnection; + + protected function setUp(): void + { + if (!$host = getenv('POSTGRES_HOST')) { + $this->markTestSkipped('Missing POSTGRES_HOST env variable'); + } + + if (!class_exists(Driver::class)) { + $this->markTestSkipped('The "pgsql" driver requires DBAL 3.6'); + } + + $config = new Configuration(); + $config->setSchemaManagerFactory(new DefaultSchemaManagerFactory()); + + $params = (new DsnParser())->parse("pgsql://postgres:password@$host"); + $this->driverConnection = DriverManager::getConnection($params, $config); + $this->senderConnection = DriverManager::getConnection($params, $config); + } + + protected function tearDown(): void + { + if (!isset($this->senderConnection)) { + return; + } + + $sender = $this->senderConnection->getNativeConnection(); + while (pg_get_result($sender)) { + } + + $this->senderConnection->createSchemaManager()->dropTable('queue_table'); + $this->senderConnection->close(); + $this->driverConnection->close(); + } + + public function testGetWakesUpOnNotify() + { + $connection = $this->createPostgreSqlConnection(self::LONG_TIMEOUT_IN_MS); + $this->assertNull($connection->get()); + + $startedAt = hrtime(true); + pg_send_query($this->senderConnection->getNativeConnection(), \sprintf("SELECT pg_sleep(%F); %s; SELECT pg_notify('queue_table', 'default')", self::NOTIFY_DELAY_IN_SECONDS, $this->createInsertSql())); + + $this->assertSame(self::MESSAGE_BODY, $connection->get()['body']); + $this->assertWaitedForTheDelay($startedAt); + } + + public function testGetTimesOutWithoutNotify() + { + $connection = $this->createPostgreSqlConnection((int) (self::NOTIFY_DELAY_IN_SECONDS * 1000)); + $this->assertNull($connection->get()); + + $startedAt = hrtime(true); + + $this->assertNull($connection->get()); + $this->assertWaitedForTheDelay($startedAt); + } + + public function testGetDoesNotWaitForANotifyReceivedBeforeTheWait() + { + $connection = $this->createPostgreSqlConnection(self::LONG_TIMEOUT_IN_MS); + $this->assertNull($connection->get()); + + $this->driverConnection->executeStatement('LISTEN "queue_table"'); + $this->senderConnection->executeStatement($this->createInsertSql()); + $this->senderConnection->executeStatement("SELECT pg_notify('queue_table', 'default')"); + usleep(100000); + + $startedAt = hrtime(true); + + $this->assertSame(self::MESSAGE_BODY, $connection->get()['body']); + $this->assertLessThan(self::LONG_TIMEOUT_IN_MS / 2000, $this->getElapsedSeconds($startedAt)); + } + + public function testGetReturnsNullWhenTheConnectionIsLostBeforeTheWait() + { + $driverConnection = new class($this->driverConnection->getParams(), new Driver(), $this->driverConnection->getConfiguration()) extends Connection { + public \Closure $afterListen; + + public function executeStatement($sql, array $params = [], array $types = []): int + { + $result = parent::executeStatement($sql, $params, $types); + + if (str_starts_with($sql, 'LISTEN')) { + ($this->afterListen)(); + } + + return (int) $result; + } + }; + $driverConnection->afterListen = function () use ($driverConnection) { + $nativeConnection = $driverConnection->getNativeConnection(); + $this->senderConnection->executeStatement(\sprintf('SELECT pg_terminate_backend(%d, 5000)', pg_get_pid($nativeConnection))); + usleep(100000); + // Takes the FATAL of the server out of the socket, so that the next read of libpq finds it closed + pg_consume_input($nativeConnection); + }; + + $connection = new PostgreSqlConnection(['table_name' => 'queue_table', 'get_notify_timeout' => self::LONG_TIMEOUT_IN_MS], $driverConnection); + $connection->setup(); + $this->assertNull($connection->get()); + + $startedAt = hrtime(true); + + $this->assertNull($connection->get()); + $this->assertLessThan(self::LONG_TIMEOUT_IN_MS / 2000, $this->getElapsedSeconds($startedAt)); + } + + public function testDestructDoesNotThrowWhenTheNativeConnectionIsAlreadyClosed() + { + $connection = $this->createPostgreSqlConnection(1); + $connection->get(); + $connection->get(); + $this->assertTrue($connection->isListening()); + + pg_close($this->driverConnection->getNativeConnection()); + $connection->__destruct(); + + $this->assertFalse($connection->isListening()); + + try { + // DBAL closes the native connection once more when it releases its driver connection + $this->driverConnection->close(); + } catch (\Error) { + } + } + + private function createPostgreSqlConnection(int $getNotifyTimeout): PostgreSqlConnection + { + $connection = new PostgreSqlConnection(['table_name' => 'queue_table', 'get_notify_timeout' => $getNotifyTimeout], $this->driverConnection); + $connection->setup(); + + return $connection; + } + + private function createInsertSql(): string + { + return \sprintf("INSERT INTO queue_table (body, headers, queue_name, created_at, available_at) VALUES ('%s', '[]', 'default', '2000-01-01', '2000-01-01')", self::MESSAGE_BODY); + } + + private function assertWaitedForTheDelay(int|float $startedAt): void + { + $elapsed = $this->getElapsedSeconds($startedAt); + + $this->assertGreaterThanOrEqual(self::NOTIFY_DELAY_IN_SECONDS - 0.05, $elapsed); + $this->assertLessThan(self::LONG_TIMEOUT_IN_MS / 2000, $elapsed); + } + + private function getElapsedSeconds(int|float $startedAt): float + { + return (hrtime(true) - $startedAt) / 1e9; + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/PostgreSqlConnectionTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/PostgreSqlConnectionTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/PostgreSqlConnectionTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Tests/Transport/PostgreSqlConnectionTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -51,6 +51,23 @@ $connection->__unserialize([]); } + public function testBuildConfigurationWithInvalidQueryOptions() + { + $cases = [ + 'check_delayed_interval=1m' => 'Option "check_delayed_interval" of the Doctrine Messenger transport must be an integer.', + 'get_notify_timeout=abc' => 'Option "get_notify_timeout" of the Doctrine Messenger transport must be an integer.', + ]; + + foreach ($cases as $query => $message) { + try { + PostgreSqlConnection::buildConfiguration('doctrine://default?'.$query); + $this->fail(\sprintf('"%s" should have been rejected.', $query)); + } catch (\InvalidArgumentException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + } + public function testListenOnConnection() { $driverConnection = $this->createMock(\Doctrine\DBAL\Connection::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/Connection.php 2026-11-25 09:18:34.000000000 +0000 @@ -111,7 +111,13 @@ $configuration = ['connection' => $params['host']]; $configuration += $query + $options + static::DEFAULT_OPTIONS; - $configuration['auto_setup'] = filter_var($configuration['auto_setup'], \FILTER_VALIDATE_BOOL); + foreach (static::DEFAULT_OPTIONS as $k => $v) { + $configuration[$k] = match (\gettype($v)) { + 'integer' => filter_var($configuration[$k], \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "%s" of the Doctrine Messenger transport must be an integer.', $k)), + 'boolean' => filter_var($configuration[$k], \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "%s" of the Doctrine Messenger transport must be a boolean.', $k)), + default => $configuration[$k], + }; + } // check for extra keys in options $optionsExtraKeys = array_diff(array_keys($options), array_keys(static::DEFAULT_OPTIONS)); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Doctrine/Transport/PostgreSqlConnection.php 2026-11-25 09:18:34.000000000 +0000 @@ -49,8 +49,8 @@ { try { $this->unlisten(); - } catch (DBALException) { - // a broken connection does not keep its LISTEN + } catch (DBALException|\Error) { + // a broken or closed connection does not keep its LISTEN } } @@ -87,9 +87,11 @@ } } - $notification = \PHP_VERSION_ID >= 80500 - ? $wrappedConnection->getNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout']) - : $wrappedConnection->pgsqlGetNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout']); + $notification = match (true) { + $wrappedConnection instanceof \PgSql\Connection => $this->getPgSqlNotification($wrappedConnection, $this->configuration['get_notify_timeout']), + \PHP_VERSION_ID >= 80500 => $wrappedConnection->getNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout']), + default => $wrappedConnection->pgsqlGetNotify(\PDO::FETCH_ASSOC, $this->configuration['get_notify_timeout']), + }; if ( // no notifications, or for another table or queue (false === $notification || $notification['message'] !== $this->configuration['table_name'] || $notification['payload'] !== $this->configuration['queue_name']) @@ -117,4 +119,26 @@ $this->executeStatement(\sprintf('UNLISTEN "%s"', $this->configuration['table_name'])); } } + + /** + * @return array{message: string, pid: int, payload: string}|false + */ + private function getPgSqlNotification(\PgSql\Connection $connection, int $timeoutMs): array|false + { + if (false !== $notification = pg_get_notify($connection, \PGSQL_ASSOC)) { + return $notification; + } + + // stream_select() throws a ValueError on the socket of a connection that libpq already dropped + if (\PGSQL_CONNECTION_OK !== pg_connection_status($connection) || false === $socket = pg_socket($connection)) { + return false; + } + + $read = [$socket]; + $write = $except = null; + // A signal interrupts the wait with a warning: the worker handles the signal right after + @stream_select($read, $write, $except, intdiv($timeoutMs, 1000), $timeoutMs % 1000 * 1000); + + return pg_get_notify($connection, \PGSQL_ASSOC); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/ConnectionTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/ConnectionTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/ConnectionTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Tests/Transport/ConnectionTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -42,6 +42,35 @@ } } + public function testFromDsnWithInvalidQueryOptions() + { + $cases = [ + 'redeliver_timeout=1.5' => 'Option "redeliver_timeout" of the Redis Messenger transport must be an integer.', + 'claim_interval=1m' => 'Option "claim_interval" of the Redis Messenger transport must be an integer.', + 'dbindex=' => 'Option "dbindex" of the Redis Messenger transport must be an integer.', + 'stream_max_entries=10k' => 'Option "stream_max_entries" of the Redis Messenger transport must be an integer.', + 'timeout=1s' => 'Option "timeout" of the Redis Messenger transport must be a number.', + 'delete_after_ack=ture' => 'Option "delete_after_ack" of the Redis Messenger transport must be a boolean.', + ]; + + foreach ($cases as $query => $message) { + try { + Connection::fromDsn('redis://localhost/queue?lazy=1&'.$query); + $this->fail(\sprintf('"%s" should have been rejected.', $query)); + } catch (\InvalidArgumentException $e) { + $this->assertSame($message, $e->getMessage()); + } + } + } + + public function testFromDsnWithInvalidOptions() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Option "redeliver_timeout" of the Redis Messenger transport must be an integer.'); + + Connection::fromDsn('redis://localhost/queue', ['lazy' => true, 'redeliver_timeout' => 1.5]); + } + public function testFromDsn() { $this->assertEquals( @@ -184,6 +213,28 @@ Connection::fromDsn('rediss://127.0.0.1', [], $redis); } + public function testFromDsnWithBooleanSslOptions() + { + $redis = $this->createMock(\Redis::class); + $redis->expects($this->once()) + ->method('connect') + ->with('localhost', 6379, 0.0, null, 0, 0.0, ['stream' => ['verify_peer' => false, 'verify_peer_name' => false, 'SNI_enabled' => true]]) + ->willReturn(true); + $redis + ->method('isConnected') + ->willReturnOnConsecutiveCalls(false, true); + + Connection::fromDsn('redis://localhost/queue?ssl[verify_peer]=false&ssl[verify_peer_name]=&ssl[SNI_enabled]=1', [], $redis); + } + + public function testFromDsnWithInvalidSslOption() + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Option "ssl[verify_peer]" of the Redis Messenger transport must be a boolean.'); + + Connection::fromDsn('redis://localhost/queue?lazy=1&ssl[verify_peer]=ture'); + } + public function testFromDsnWithQueryOptions() { $this->assertEquals( diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Bridge/Redis/Transport/Connection.php 2026-11-25 09:18:34.000000000 +0000 @@ -111,7 +111,7 @@ foreach ($options['ssl'] ?? [] as $streamOption => $value) { if (\in_array($streamOption, $booleanStreamOptions, true) && \is_string($value)) { - $options['ssl'][$streamOption] = filter_var($value, \FILTER_VALIDATE_BOOL); + $options['ssl'][$streamOption] = filter_var($value, \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "ssl[%s]" of the Redis Messenger transport must be a boolean.', $streamOption)); } } @@ -279,9 +279,9 @@ } foreach (self::DEFAULT_OPTIONS as $k => $v) { $options[$k] = match (\gettype($v)) { - 'integer' => filter_var($options[$k] ?? $v, \FILTER_VALIDATE_INT), - 'boolean' => filter_var($options[$k] ?? $v, \FILTER_VALIDATE_BOOL), - 'double' => filter_var($options[$k] ?? $v, \FILTER_VALIDATE_FLOAT), + 'integer' => filter_var($options[$k] ?? $v, \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "%s" of the Redis Messenger transport must be an integer.', $k)), + 'boolean' => filter_var($options[$k] ?? $v, \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "%s" of the Redis Messenger transport must be a boolean.', $k)), + 'double' => filter_var($options[$k] ?? $v, \FILTER_VALIDATE_FLOAT, \FILTER_NULL_ON_FAILURE) ?? throw new InvalidArgumentException(\sprintf('Option "%s" of the Redis Messenger transport must be a number.', $k)), default => $options[$k] ?? $v, }; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Command/ConsumeMessagesCommand.php 2026-11-25 09:18:34.000000000 +0000 @@ -51,6 +51,7 @@ private ?ContainerInterface $rateLimiterLocator; private ?array $signals; private ?Worker $worker = null; + private bool $shouldStop = false; public function __construct(RoutableMessageBus $routableBus, ContainerInterface $receiverLocator, EventDispatcherInterface $eventDispatcher, ?LoggerInterface $logger = null, array $receiverNames = [], ?ResetServicesListener $resetServicesListener = null, array $busIds = [], ?ContainerInterface $rateLimiterLocator = null, ?array $signals = null) { @@ -233,6 +234,9 @@ $bus = $input->getOption('bus') ? $this->routableBus->getMessageBus($input->getOption('bus')) : $this->routableBus; $this->worker = new Worker($receivers, $bus, $this->eventDispatcher, $this->logger, $rateLimiters); + if ($this->shouldStop) { + $this->worker->stop(); + } $options = [ 'sleep' => $input->getOption('sleep') * 1000000, 'time_limit' => null !== $timeLimit ? (int) $timeLimit : null, @@ -249,6 +253,7 @@ $this->worker->run($options); } finally { $this->worker = null; + $this->shouldStop = false; foreach ($subscribers as $subscriber) { $this->eventDispatcher->removeSubscriber($subscriber); @@ -279,6 +284,8 @@ public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false { if (!$this->worker) { + $this->shouldStop = true; + return false; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Command/FailedMessagesRetryCommand.php 2026-11-25 09:18:34.000000000 +0000 @@ -140,6 +140,8 @@ public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false { if (!$this->worker) { + $this->shouldStop = true; + return false; } @@ -226,6 +228,9 @@ $this->eventDispatcher, $this->logger ); + if ($this->shouldStop) { + $this->worker->stop(); + } try { $this->worker->run(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Command/ConsumeMessagesCommandTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -272,6 +272,52 @@ $this->assertStringContainsString('[OK] Consuming messages from transport "dummy-receiver"', $tester->getDisplay()); } + /** + * @requires extension pcntl + */ + public function testRunStopsWhenSignalWasReceivedBeforeTheWorkerWasCreated() + { + $envelope = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]); + + $getCalls = 0; + $receiver = $this->createStub(ReceiverInterface::class); + $receiver->method('get')->willReturnCallback(static function () use ($envelope, &$getCalls) { + ++$getCalls; + + return [$envelope]; + }); + + $receiverLocator = new Container(); + $receiverLocator->set('dummy-receiver', $receiver); + + $busLocator = new Container(); + $busLocator->set('dummy-bus', new MessageBus()); + + $command = new ConsumeMessagesCommand(new RoutableMessageBus($busLocator), $receiverLocator, new EventDispatcher()); + + $application = new Application(); + $application->add($command); + $tester = new CommandTester($application->get('messenger:consume')); + + $this->assertFalse($command->handleSignal(\SIGTERM)); + + $tester->execute([ + 'receivers' => ['dummy-receiver'], + '--limit' => 1, + ]); + + $tester->assertCommandIsSuccessful(); + $this->assertSame(0, $getCalls); + + $tester->execute([ + 'receivers' => ['dummy-receiver'], + '--limit' => 1, + ]); + + $tester->assertCommandIsSuccessful(); + $this->assertSame(1, $getCalls); + } + public function testRunWithMemoryLimit() { $envelope = new Envelope(new \stdClass(), [new BusNameStamp('dummy-bus')]); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRemoveCommandTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRemoveCommandTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRemoveCommandTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRemoveCommandTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -83,17 +83,14 @@ { $failureReceiverName = 'failure_receiver'; - $this->expectException(InvalidArgumentException::class); $command = new FailedMessagesRemoveCommand( $failureReceiverName, new ServiceLocator([]) ); $tester = new CommandTester($command); + $this->expectException(InvalidArgumentException::class); $tester->execute(['id' => [20], '--transport' => $failureReceiverName, '--force' => true]); - - $this->assertStringContainsString('Failed Message Details', $tester->getDisplay()); - $this->assertStringContainsString('Message with id 20 removed.', $tester->getDisplay()); } public function testRemoveMultipleMessagesWithServiceLocator() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Command/FailedMessagesRetryCommandTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -302,4 +302,27 @@ $this->assertStringContainsString('messages pending', $stdout); $this->assertStringNotContainsString('messages pending', $stderr); } + + /** + * @requires extension pcntl + */ + public function testRunStopsWhenSignalWasReceivedBeforeTheWorkerWasCreated() + { + $receiver = $this->createMock(ListableReceiverInterface::class); + $receiver->method('find')->willReturn(new Envelope(new \stdClass())); + $receiver->expects($this->never())->method('ack'); + + $bus = $this->createMock(MessageBusInterface::class); + $bus->expects($this->never())->method('dispatch'); + + $command = new FailedMessagesRetryCommand('failure_receiver', new ServiceLocator(['failure_receiver' => static fn () => $receiver]), $bus, new EventDispatcher()); + + $this->assertFalse($command->handleSignal(\SIGTERM)); + + $tester = new CommandTester($command); + $tester->execute(['id' => [10, 12], '--force' => true]); + + $tester->assertCommandIsSuccessful(); + $this->assertStringNotContainsString('[OK]', $tester->getDisplay()); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Stamp/DelayStampTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Stamp/DelayStampTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Messenger/Tests/Stamp/DelayStampTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Messenger/Tests/Stamp/DelayStampTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -32,12 +32,15 @@ $this->assertSame(-5000, $stamp->getDelay()); } + /** + * @group time-sensitive + */ public function testDelayUntil() { - $stamp = DelayStamp::delayUntil(new \DateTimeImmutable('+30 seconds')); + $stamp = DelayStamp::delayUntil(new \DateTimeImmutable('@'.(time() + 30))); $this->assertSame(30000, $stamp->getDelay()); - $stamp = DelayStamp::delayUntil(new \DateTimeImmutable('-5 seconds')); + $stamp = DelayStamp::delayUntil(new \DateTimeImmutable('@'.(time() - 5))); $this->assertSame(-5000, $stamp->getDelay()); } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Mime/Crypto/SMime.php symfony-6.4.51+dfsg/src/Symfony/Component/Mime/Crypto/SMime.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Mime/Crypto/SMime.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Mime/Crypto/SMime.php 2026-11-25 09:18:34.000000000 +0000 @@ -64,8 +64,18 @@ protected function getStreamIterator($stream): iterable { + $carry = ''; while (!feof($stream)) { - yield str_replace("\n", "\r\n", str_replace("\r\n", "\n", fread($stream, 16372))); + $chunk = $carry.fread($stream, 16372); + $carry = ''; + + // Don't split a CRLF across two chunks, or normalizing each chunk turns it into "\r\r\n" + if (str_ends_with($chunk, "\r") && !feof($stream)) { + $chunk = substr($chunk, 0, -1); + $carry = "\r"; + } + + yield str_replace("\n", "\r\n", str_replace("\r\n", "\n", $chunk)); } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Mime/Tests/AddressTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Mime/Tests/AddressTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Mime/Tests/AddressTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Mime/Tests/AddressTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -69,10 +69,10 @@ $this->assertSame('"em@il"@[em@il]', $a->getAddress()); } - public function testConstructorWithACommentAfterADomainLiteral() + public function testConstructorWithAnAtSignInACommentInTheDomain() { - $a = new Address('user@[em@il] (comment)'); - $this->assertSame('user@[em@il] (comment)', $a->getAddress()); + $a = new Address('user@example(c@mment).test'); + $this->assertSame('user@example(c@mment).test', $a->getAddress()); } /** diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Mime/Tests/Crypto/SMimeSignerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -39,6 +39,24 @@ $this->assertMessageSignatureIsValid($signedMessage, $message); } + public function testSignedMessageDoesNotSplitCrlfAcrossChunks() + { + // The signed output is read back in 16372-byte chunks. + // Shifting the body by up to one line length makes a CRLF straddle a chunk boundary for at least one shift. + for ($shift = 0; $shift < 62; ++$shift) { + $lines = [str_repeat('x', $shift)]; + for ($i = 0; $i < 1000; ++$i) { + $lines[] = str_pad("Line $i", 60, '.'); + } + + $message = new Message((new Headers())->addMailboxListHeader('From', ['fabien@symfony.com']), new TextPart(implode("\r\n", $lines))); + + $signer = new SMimeSigner($this->samplesDir.'sign.crt', $this->samplesDir.'sign.key'); + + $this->assertStringNotContainsString("\r\r\n", $signer->sign($message)->toString(), "shift $shift"); + } + } + public function testSignEncryptedMessage() { $message = (new Email()) diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/BrevoTransport.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/BrevoTransport.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/BrevoTransport.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/BrevoTransport.php 2026-11-25 09:18:34.000000000 +0000 @@ -55,7 +55,7 @@ $sender = $message->getFrom() ?: $this->sender; - $response = $this->client->request('POST', 'https://'.$this->getEndpoint().'/v3/transactionalSMS/sms', [ + $response = $this->client->request('POST', 'https://'.$this->getEndpoint().'/v3/transactionalSMS/send', [ 'json' => [ 'sender' => $sender, 'recipient' => $message->getPhone(), diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/Tests/BrevoTransportTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/Tests/BrevoTransportTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/Tests/BrevoTransportTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Brevo/Tests/BrevoTransportTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -56,4 +56,19 @@ $transport->send(new SmsMessage('phone', 'testMessage')); } + + public function testSendUsesTheTransactionalSmsSendEndpoint() + { + $client = new MockHttpClient(function (string $method, string $url, array $options): ResponseInterface { + $this->assertSame('POST', $method); + $this->assertSame('https://host.test/v3/transactionalSMS/send', $url); + $this->assertSame(['sender' => '0611223344', 'recipient' => '0699887766', 'content' => 'Hello!'], json_decode($options['body'], true)); + + return new MockResponse(json_encode(['messageId' => 1511882900176220]), ['http_code' => 201]); + }); + + $sentMessage = self::createTransport($client)->send(new SmsMessage('0699887766', 'Hello!')); + + $this->assertSame('1511882900176220', $sentMessage->getMessageId()); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/EngagespotOptions.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/EngagespotOptions.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/EngagespotOptions.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/EngagespotOptions.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,7 +16,7 @@ /** * @author Daniel GORGAN <https://github.com/danut007ro> * - * @see https://docs.engagespot.co/how-to-send-notifications-via-engagespot-api/how-to-send-notifications-using-engagespot-rest-api + * @see https://docs.engagespot.co/api/api-reference/introduction */ final class EngagespotOptions implements MessageOptionsInterface { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/README.md symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/README.md --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/README.md 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Engagespot/README.md 2026-11-25 09:18:34.000000000 +0000 @@ -1,7 +1,7 @@ Engagespot Notifier =================== -Provides [Engagespot](https://docs.engagespot.co/how-to-send-notifications-via-engagespot-api/how-to-send-notifications-using-engagespot-rest-api) integration for Symfony Notifier. +Provides [Engagespot](https://docs.engagespot.co/api/api-reference/introduction) integration for Symfony Notifier. DSN example ----------- diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsOptions.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsOptions.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsOptions.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsOptions.php 2026-11-25 09:18:34.000000000 +0000 @@ -57,12 +57,6 @@ public function toArray(): array { $options = $this->options; - - // Send a text, not a message card - if (1 === \count($options) && isset($options['text'])) { - return $options; - } - $options['@type'] = 'MessageCard'; $options['@context'] = 'https://schema.org/extensions'; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsTransport.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsTransport.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsTransport.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/MicrosoftTeamsTransport.php 2026-11-25 09:18:34.000000000 +0000 @@ -57,7 +57,7 @@ throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message); } - $options = $message->getOptions()?->toArray() ?? []; + $options = ($message->getOptions() ?? new MicrosoftTeamsOptions())->toArray(); $options['text'] ??= $message->getSubject(); $path = $message->getRecipientId() ?? $this->path; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/README.md symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/README.md --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/README.md 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/README.md 2026-11-25 09:18:34.000000000 +0000 @@ -8,11 +8,19 @@ ----------- ``` -MICROSOFT_TEAMS_DSN=microsoftteams://default/PATH +MICROSOFT_TEAMS_DSN=microsoftteams://HOST/PATH ``` where: - - `PATH` has the following format: `webhookb2/{uuid}@{uuid}/IncomingWebhook/{id}/{uuid}` + - `HOST/PATH` is the URL of a Workflows webhook without its `https://` prefix, + query string included, for example + `default123.45.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/678/triggers/manual/paths/invoke?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=SIGNATURE` + +To get this URL, create a workflow in the Teams channel from the "Send webhook +alerts to a channel" template. See [Send messages in Teams using incoming webhooks](https://support.microsoft.com/en-us/workflows/send-messages-in-teams-using-incoming-webhooks). + +Office 365 connectors (`outlook.office.com/webhookb2/...` URLs) stopped working +in May 2026, see [their retirement notice](https://devblogs.microsoft.com/microsoft365dev/retirement-of-office-365-connectors-within-microsoft-teams/). Adding text to a Message ------------------------ @@ -32,6 +40,8 @@ With a Microsoft Teams Message, you can use the `MicrosoftTeamsOptions` class to add [MessageCard options](https://docs.microsoft.com/en-us/outlook/actionable-messages/message-card-reference). +Note that Workflows webhooks display the content of MessageCards but not their +action buttons. ```php use Symfony\Component\Notifier\Bridge\MicrosoftTeams\Action\ActionCard; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/Tests/MicrosoftTeamsTransportTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/Tests/MicrosoftTeamsTransportTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/Tests/MicrosoftTeamsTransportTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/MicrosoftTeams/Tests/MicrosoftTeamsTransportTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -99,6 +99,8 @@ $message = 'testMessage'; $expectedBody = json_encode([ + '@context' => 'https://schema.org/extensions', + '@type' => 'MessageCard', 'text' => $message, ]); @@ -121,6 +123,8 @@ ]); $expectedBody = json_encode([ + '@context' => 'https://schema.org/extensions', + '@type' => 'MessageCard', 'text' => $optionsTextMessage, ]); @@ -168,6 +172,8 @@ $chatMessage = ChatMessage::fromNotification($notification); $expectedBody = json_encode([ + '@context' => 'https://schema.org/extensions', + '@type' => 'MessageCard', 'text' => $message, ]); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/NtfyTransportFactory.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/NtfyTransportFactory.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/NtfyTransportFactory.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/NtfyTransportFactory.php 2026-11-25 09:18:34.000000000 +0000 @@ -30,11 +30,7 @@ $host = 'default' === $dsn->getHost() ? null : $dsn->getHost(); $topic = substr($dsn->getPath(), 1); - if (\in_array($dsn->getOption('secureHttp', true), [0, false, 'false', 'off', 'no'])) { - $secureHttp = false; - } else { - $secureHttp = true; - } + $secureHttp = filter_var($dsn->getOption('secureHttp', true), \FILTER_VALIDATE_BOOL); $transport = (new NtfyTransport($topic, $secureHttp))->setHost($host); if (!empty($port = $dsn->getPort())) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/Tests/NtfyTransportFactoryTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/Tests/NtfyTransportFactoryTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/Tests/NtfyTransportFactoryTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Ntfy/Tests/NtfyTransportFactoryTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,6 +13,7 @@ use Symfony\Component\Notifier\Bridge\Ntfy\NtfyTransportFactory; use Symfony\Component\Notifier\Test\TransportFactoryTestCase; +use Symfony\Component\Notifier\Transport\Dsn; use Symfony\Component\Notifier\Transport\TransportFactoryInterface; /** @@ -25,6 +26,25 @@ return new NtfyTransportFactory(); } + public function testSecureHttpOption() + { + $cases = [ + '' => true, + 'secureHttp=1' => true, + 'secureHttp=on' => true, + 'secureHttp=0' => false, + 'secureHttp=' => false, + 'secureHttp=off' => false, + 'secureHttp=Off' => false, + 'secureHttp=FALSE' => false, + ]; + + foreach ($cases as $query => $secureHttp) { + $transport = $this->createFactory()->create(new Dsn('ntfy://user:password@default/test?'.$query)); + $this->assertSame($secureHttp, (new \ReflectionProperty($transport, 'secureHttp'))->getValue($transport), $query); + } + } + public static function createProvider(): iterable { yield [ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Plivo/README.md symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Plivo/README.md --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/Plivo/README.md 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/Plivo/README.md 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ --------------------------- With a Plivo Message, you can use the `PlivoOptions` class to add -[message options](https://www.plivo.com/docs/sms/api/message#send-a-message). +[message options](https://www.plivo.com/docs/messaging/api/messages#send-a-message). ```php use Symfony\Component\Notifier\Message\SmsMessage; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransportFactory.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransportFactory.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransportFactory.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/SpotHitTransportFactory.php 2026-11-25 09:18:34.000000000 +0000 @@ -30,7 +30,7 @@ $token = $this->getUser($dsn); $from = $dsn->getOption('from'); - $smsLong = $dsn->getOption('smslong'); + $smsLong = filter_var($dsn->getOption('smslong', '-'), \FILTER_VALIDATE_BOOL, \FILTER_NULL_ON_FAILURE); $smsLongNBr = $dsn->getOption('smslongnbr'); $host = 'default' === $dsn->getHost() ? null : $dsn->getHost(); $port = $dsn->getPort(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/Tests/SpotHitTransportFactoryTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/Tests/SpotHitTransportFactoryTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/Tests/SpotHitTransportFactoryTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Notifier/Bridge/SpotHit/Tests/SpotHitTransportFactoryTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -35,6 +35,10 @@ 'spothit://spot-hit.fr?from=MyCompany&smslong=1', 'spothit://api_token@default?from=MyCompany&smslong=1', ]; + yield [ + 'spothit://spot-hit.fr?from=MyCompany&smslong=0', + 'spothit://api_token@default?from=MyCompany&smslong=false', + ]; } public static function supportsProvider(): iterable diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/OptionsResolver/Tests/Debug/OptionsResolverIntrospectorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -102,23 +102,23 @@ public function testGetAllowedTypesThrowsOnNoConfiguredValue() { - $this->expectException(NoConfigurationException::class); - $this->expectExceptionMessage('No allowed types were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); $debug = new OptionsResolverIntrospector($resolver); - $this->assertSame('bar', $debug->getAllowedTypes($option)); + $this->expectException(NoConfigurationException::class); + $this->expectExceptionMessage('No allowed types were set for the "foo" option.'); + $debug->getAllowedTypes($option); } public function testGetAllowedTypesThrowsOnNotDefinedOption() { - $this->expectException(UndefinedOptionsException::class); - $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); - $this->assertSame('bar', $debug->getAllowedTypes('foo')); + $this->expectException(UndefinedOptionsException::class); + $this->expectExceptionMessage('The option "foo" does not exist.'); + $debug->getAllowedTypes('foo'); } public function testGetAllowedValues() @@ -133,23 +133,23 @@ public function testGetAllowedValuesThrowsOnNoConfiguredValue() { - $this->expectException(NoConfigurationException::class); - $this->expectExceptionMessage('No allowed values were set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); $debug = new OptionsResolverIntrospector($resolver); - $this->assertSame('bar', $debug->getAllowedValues($option)); + $this->expectException(NoConfigurationException::class); + $this->expectExceptionMessage('No allowed values were set for the "foo" option.'); + $debug->getAllowedValues($option); } public function testGetAllowedValuesThrowsOnNotDefinedOption() { - $this->expectException(UndefinedOptionsException::class); - $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); - $this->assertSame('bar', $debug->getAllowedValues('foo')); + $this->expectException(UndefinedOptionsException::class); + $this->expectExceptionMessage('The option "foo" does not exist.'); + $debug->getAllowedValues('foo'); } public function testGetNormalizer() @@ -164,23 +164,23 @@ public function testGetNormalizerThrowsOnNoConfiguredValue() { - $this->expectException(NoConfigurationException::class); - $this->expectExceptionMessage('No normalizer was set for the "foo" option.'); $resolver = new OptionsResolver(); $resolver->setDefined($option = 'foo'); $debug = new OptionsResolverIntrospector($resolver); - $this->assertSame('bar', $debug->getNormalizer($option)); + $this->expectException(NoConfigurationException::class); + $this->expectExceptionMessage('No normalizer was set for the "foo" option.'); + $debug->getNormalizer($option); } public function testGetNormalizerThrowsOnNotDefinedOption() { - $this->expectException(UndefinedOptionsException::class); - $this->expectExceptionMessage('The option "foo" does not exist.'); $resolver = new OptionsResolver(); $debug = new OptionsResolverIntrospector($resolver); - $this->assertSame('bar', $debug->getNormalizer('foo')); + $this->expectException(UndefinedOptionsException::class); + $this->expectExceptionMessage('The option "foo" does not exist.'); + $debug->getNormalizer('foo'); } public function testGetNormalizers() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyAccess/PropertyAccessor.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyAccess/PropertyAccessor.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyAccess/PropertyAccessor.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyAccess/PropertyAccessor.php 2026-11-25 09:18:34.000000000 +0000 @@ -56,7 +56,6 @@ private const IS_REF_CHAINED = 2; private const CACHE_PREFIX_READ = 'r'; private const CACHE_PREFIX_WRITE = 'w'; - private const CACHE_PREFIX_PROPERTY_PATH = 'p'; private const RESULT_PROTO = [self::VALUE => null]; private static array $dynamicPropertiesCache = []; @@ -489,6 +488,11 @@ return $this->readPropertyCache[$key]; } + if (1000 < \count($this->readPropertyCache)) { + // stop memory leak if there are many keys + $this->readPropertyCache = \array_slice($this->readPropertyCache, 500, null, true); + } + if ($this->cacheItemPool) { $item = $this->cacheItemPool->getItem(self::CACHE_PREFIX_READ.rawurlencode($key)); if ($item->isHit()) { @@ -502,7 +506,7 @@ 'enable_constructor_extraction' => false, ]); - if (isset($item)) { + if (isset($item) && self::isPersistable($class, $property, $accessor)) { $this->cacheItemPool->save($item->set($accessor)); } @@ -617,6 +621,11 @@ return $this->writePropertyCache[$key]; } + if (1000 < \count($this->writePropertyCache)) { + // stop memory leak if there are many keys + $this->writePropertyCache = \array_slice($this->writePropertyCache, 500, null, true); + } + if ($this->cacheItemPool) { $item = $this->cacheItemPool->getItem(self::CACHE_PREFIX_WRITE.rawurlencode($key)); if ($item->isHit()) { @@ -631,7 +640,7 @@ 'enable_adder_remover_extraction' => $useAdderAndRemover, ]); - if (isset($item)) { + if (isset($item) && self::isPersistable($class, $property, $mutator)) { $this->cacheItemPool->save($item->set($mutator)); } @@ -676,20 +685,13 @@ return $this->propertyPathCache[$propertyPath]; } - if ($this->cacheItemPool) { - $item = $this->cacheItemPool->getItem(self::CACHE_PREFIX_PROPERTY_PATH.rawurlencode($propertyPath)); - if ($item->isHit()) { - return $this->propertyPathCache[$propertyPath] = $item->get(); - } + if (1000 < \count($this->propertyPathCache)) { + // stop memory leak if there are many keys + $this->propertyPathCache = \array_slice($this->propertyPathCache, 500, null, true); } - $propertyPathInstance = new PropertyPath($propertyPath); - if (isset($item)) { - $item->set($propertyPathInstance); - $this->cacheItemPool->save($item); - } - - return $this->propertyPathCache[$propertyPath] = $propertyPathInstance; + // property paths are not persisted in the cache pool: they can come from the input and parsing them is as fast as fetching them + return $this->propertyPathCache[$propertyPath] = new PropertyPath($propertyPath); } /** @@ -747,4 +749,41 @@ return false; } + + /** + * Tells whether the info found for a property can be persisted in the cache pool. + * + * Magic methods accept any name, and a method can be found through many spellings of its name. Persisting all of them would let the pool grow with the input. + * + * @param PropertyReadInfo|PropertyWriteInfo|null $info + */ + private static function isPersistable(string $class, string $property, $info): bool + { + if (property_exists($class, $property)) { + return true; + } + + if ($info instanceof PropertyReadInfo && PropertyReadInfo::TYPE_METHOD === $info->getType()) { + $methods = [$info->getName()]; + } elseif ($info instanceof PropertyWriteInfo && PropertyWriteInfo::TYPE_METHOD === $info->getType()) { + $methods = [$info->getName()]; + } elseif ($info instanceof PropertyWriteInfo && PropertyWriteInfo::TYPE_ADDER_AND_REMOVER === $info->getType()) { + $methods = [$info->getAdderInfo()->getName(), $info->getRemoverInfo()->getName()]; + } else { + return false; + } + + // camelCase or snake_case only, since extractors also accept extra underscores and spaces + if (!preg_match('/^(?:[a-zA-Z0-9\x80-\xff]++|[a-z0-9\x80-\xff]++(?:_[a-z0-9\x80-\xff]++)++)$/D', $property)) { + return false; + } + + foreach ($methods as $method) { + if (!method_exists($class, $method) || $method !== (new \ReflectionMethod($class, $method))->name) { + return false; + } + } + + return true; + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyAccess/Tests/PropertyAccessorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -760,6 +760,76 @@ $this->assertSame('bar', $propertyAccessor->getValue($obj, 'foo')); } + public function testCachePoolIgnoresUndeclaredNames() + { + $object = new class { + public $name; + public $values = []; + private $fullName; + + public function getFullName() + { + return $this->fullName; + } + + public function setFullName($fullName) + { + $this->fullName = $fullName; + } + + public function __get($name) + { + return $this->values[$name] ?? null; + } + + public function __set($name, $value) + { + $this->values[$name] = $value; + } + }; + $cache = new ArrayAdapter(); + $propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_GET | PropertyAccessor::MAGIC_SET, PropertyAccessor::DO_NOT_THROW, $cache); + + foreach (['name', 'fullName', 'full_name', 'FullName'] as $property) { + $propertyAccessor->setValue($object, $property, $property); + $this->assertSame($property, $propertyAccessor->getValue($object, $property)); + } + + $cachedKeys = array_keys(array_filter($cache->getValues())); + $this->assertCount(8, $cachedKeys); + + foreach (['FULLNAME', 'fullname', 'full__name', '_full_name', 'full_name_', 'full name'] as $property) { + $propertyAccessor->setValue($object, $property, $property); + $this->assertSame($property, $propertyAccessor->getValue($object, $property)); + } + + $propertyAccessor->setValue($object, 'magic', 'value'); + $this->assertSame('value', $propertyAccessor->getValue($object, 'magic')); + $this->assertSame(['magic' => 'value'], $object->values); + $this->assertNull($propertyAccessor->getValue(new \stdClass(), 'unknown')); + $this->assertSame('value', $propertyAccessor->getValue(['key' => 'value'], '[key]')); + + $this->assertSame($cachedKeys, array_keys(array_filter($cache->getValues()))); + } + + public function testCacheSizeLimit() + { + $object = new TestClassMagicGet('foo'); + $propertyAccessor = new PropertyAccessor(PropertyAccessor::MAGIC_GET | PropertyAccessor::MAGIC_SET, PropertyAccessor::DO_NOT_THROW); + + for ($i = 0; $i < 2000; ++$i) { + $propertyAccessor->setValue($object, 'property'.$i, $i); + $propertyAccessor->getValue($object, 'property'.$i); + $propertyAccessor->getValue([], '[property'.$i.']'); + } + + $caches = \Closure::bind(fn () => [$this->propertyPathCache, $this->readPropertyCache, $this->writePropertyCache], $propertyAccessor, PropertyAccessor::class)(); + + foreach ($caches as $cache) { + $this->assertLessThanOrEqual(1001, \count($cache)); + } + } + public function testAttributeWithSpecialChars() { $obj = new \stdClass(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpDocExtractor.php 2026-11-25 09:18:34.000000000 +0000 @@ -189,7 +189,7 @@ } try { - $docBlock = $this->docBlockFactory->create($reflectionConstructor, $this->contextFactory->createFromReflector($reflectionConstructor)); + $docBlock = $this->docBlockFactory->create($reflectionConstructor, $this->createFromReflector($this->getDeclaringTrait($reflectionConstructor) ?? $reflectionConstructor->getDeclaringClass())); return [$this->filterDocBlockParams($docBlock, $property), $reflectionConstructor->class]; } catch (\InvalidArgumentException) { @@ -216,6 +216,11 @@ return $this->docBlocks[$propertyHash]; } + if (1000 < \count($this->docBlocks)) { + // stop memory leak if there are many keys + $this->docBlocks = \array_slice($this->docBlocks, 500, null, true); + } + try { $reflectionProperty = new \ReflectionProperty($class, $property); } catch (\ReflectionException) { @@ -265,7 +270,8 @@ $reflector = $reflectionProperty->getDeclaringClass(); foreach ($reflector->getTraits() as $trait) { - if ($trait->hasProperty($property)) { + // a class can declare a property of its traits again, with another doc comment + if ($trait->hasProperty($property) && $trait->getProperty($property)->getDocComment() === $reflectionProperty->getDocComment()) { return $this->getDocBlockFromProperty($trait->getName(), $property, $reflector->isTrait() ? $originalClass : $reflector->getName()); } } @@ -282,9 +288,8 @@ /** * @return array{DocBlock, string, string}|null */ - private function getDocBlockFromMethod(string $class, string $ucFirstProperty, int $type, ?string $originalClass = null): ?array + private function getDocBlockFromMethod(string $class, string $ucFirstProperty, int $type): ?array { - $originalClass ??= $class; $prefixes = self::ACCESSOR === $type ? $this->accessorPrefixes : $this->mutatorPrefixes; $prefix = null; $method = null; @@ -323,18 +328,20 @@ return null; } - $reflector = $method->getDeclaringClass(); + $declaringClass = $method->class; - foreach ($reflector->getTraits() as $trait) { - if ($trait->hasMethod($methodName)) { - return $this->getDocBlockFromMethod($trait->getName(), $ucFirstProperty, $type, $reflector->isTrait() ? $originalClass : $reflector->getName()); + // a method that implements an abstract trait method uses the docblock of the trait when its own docblock has no tag for the type, for example when PHP gives it the docblock of a "use" statement + if (!str_contains((string) $method->getDocComment(), self::ACCESSOR === $type ? '@return' : '@param')) { + foreach ($method->getDeclaringClass()->getTraits() as $trait) { + if ($trait->hasMethod($method->name) && $trait->getMethod($method->name)->isAbstract()) { + $method = $trait->getMethod($method->name); + break; + } } } try { - $declaringClass = $reflector->isTrait() ? $originalClass : $reflector->getName(); - - return [$this->docBlockFactory->create($method, $this->createFromReflector($reflector)), $prefix, $declaringClass]; + return [$this->docBlockFactory->create($method, $this->createFromReflector($this->getDeclaringTrait($method) ?? $method->getDeclaringClass())), $prefix, $declaringClass]; } catch (\InvalidArgumentException|\RuntimeException) { return null; } @@ -356,6 +363,24 @@ return $this->contexts[$cacheKey]; } + /** + * Finds the trait where a method is written, since reflection gives the class using the trait as its declaring class. + */ + private function getDeclaringTrait(\ReflectionMethod $method, ?\ReflectionClass $class = null): ?\ReflectionClass + { + foreach (($class ?? $method->getDeclaringClass())->getTraits() as $trait) { + if ($declaringTrait = $this->getDeclaringTrait($method, $trait)) { + return $declaringTrait; + } + + if ($trait->getFileName() === $method->getFileName() && $trait->getStartLine() <= $method->getStartLine() && $method->getEndLine() <= $trait->getEndLine()) { + return $trait; + } + } + + return null; + } + private function resolveClassKeywords(Type $type, string $class, ?string $declaringClass): Type { $resolvedClass = match ($type->getClassName()) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Extractor/PhpStanExtractor.php 2026-11-25 09:18:34.000000000 +0000 @@ -135,12 +135,12 @@ public function getTypesFromConstructor(string $class, string $property): ?array { - if (![$tagDocNode, $declaringClass] = $this->getDocBlockFromConstructor($class, $property)) { + if (![$tagDocNode, $declaringClass, $declaringTrait] = $this->getDocBlockFromConstructor($class, $property)) { return $this->getTypes($class, $property); } $types = []; - foreach ($this->phpStanTypeHelper->getTypes($tagDocNode, $this->nameScopeFactory->create($class, $declaringClass)) as $type) { + foreach ($this->phpStanTypeHelper->getTypes($tagDocNode, $this->nameScopeFactory->create($class, $declaringTrait ?? $declaringClass, $declaringClass)) as $type) { $types[] = $type; } @@ -152,7 +152,7 @@ } /** - * @return array{ParamTagValueNode, string}|null + * @return array{ParamTagValueNode, string, string|null}|null */ private function getDocBlockFromConstructor(string $class, string $property): ?array { @@ -174,7 +174,7 @@ return null; } - return [$tagDocNode, $reflectionConstructor->class]; + return [$tagDocNode, $reflectionConstructor->class, $this->getDeclaringTrait($reflectionConstructor)?->name]; } private function filterDocBlockParams(PhpDocNode $docNode, string $allowedParam): ?ParamTagValueNode @@ -199,14 +199,19 @@ return $this->docBlocks[$propertyHash]; } + if (1000 < \count($this->docBlocks)) { + // stop memory leak if there are many keys + $this->docBlocks = \array_slice($this->docBlocks, 500, null, true); + } + $ucFirstProperty = ucfirst($property); if ([$docBlock, $source, $declaringClass, $selfClass] = $this->getDocBlockFromProperty($class, $property)) { $data = [$docBlock, $source, null, $declaringClass, $selfClass]; - } elseif ([$docBlock, $_, $declaringClass] = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::ACCESSOR)) { - $data = [$docBlock, self::ACCESSOR, null, $declaringClass, $declaringClass]; - } elseif ([$docBlock, $prefix, $declaringClass] = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::MUTATOR)) { - $data = [$docBlock, self::MUTATOR, $prefix, $declaringClass, $declaringClass]; + } elseif ([$docBlock, $_, $declaringClass, $selfClass] = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::ACCESSOR)) { + $data = [$docBlock, self::ACCESSOR, null, $declaringClass, $selfClass]; + } elseif ([$docBlock, $prefix, $declaringClass, $selfClass] = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::MUTATOR)) { + $data = [$docBlock, self::MUTATOR, $prefix, $declaringClass, $selfClass]; } else { $data = [null, null, null, null, null]; } @@ -229,7 +234,8 @@ $reflector = $reflectionProperty->getDeclaringClass(); foreach ($reflector->getTraits() as $trait) { - if ($trait->hasProperty($property)) { + // a class can declare a property of its traits again, with another doc comment + if ($trait->hasProperty($property) && $trait->getProperty($property)->getDocComment() === $reflectionProperty->getDocComment()) { return $this->getDocBlockFromProperty($trait->getName(), $property, $reflector->isTrait() ? $selfClass : $reflector->getName()); } } @@ -245,7 +251,7 @@ // or in the constructor as `@param` for promoted properties if (!$phpDocNode && $reflectionProperty->isPromoted()) { - $constructor = new \ReflectionMethod($class, '__construct'); + $constructor = new \ReflectionMethod($reflectionProperty->class, '__construct'); $rawDocNode = $constructor->getDocComment(); $phpDocNode = $rawDocNode ? $this->getPhpDocNode($rawDocNode) : null; $source = self::MUTATOR; @@ -259,7 +265,7 @@ } /** - * @return array{PhpDocNode, string, string}|null + * @return array{PhpDocNode, string, string, string}|null */ private function getDocBlockFromMethod(string $class, string $ucFirstProperty, int $type): ?array { @@ -307,7 +313,7 @@ $phpDocNode = $this->getPhpDocNode($rawDocNode); - return [$phpDocNode, $prefix, $method->class]; + return [$phpDocNode, $prefix, $this->getDeclaringTrait($method)->name ?? $method->class, $method->class]; } private function getPhpDocNode(string $rawDocNode): PhpDocNode @@ -318,4 +324,22 @@ return $phpDocNode; } + + /** + * Finds the trait where a method is written, since reflection gives the class using the trait as its declaring class. + */ + private function getDeclaringTrait(\ReflectionMethod $method, ?\ReflectionClass $class = null): ?\ReflectionClass + { + foreach (($class ?? $method->getDeclaringClass())->getTraits() as $trait) { + if ($declaringTrait = $this->getDeclaringTrait($method, $trait)) { + return $declaringTrait; + } + + if ($trait->getFileName() === $method->getFileName() && $trait->getStartLine() <= $method->getStartLine() && $method->getEndLine() <= $trait->getEndLine()) { + return $trait; + } + } + + return null; + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/PhpStan/NameScopeFactory.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/PhpStan/NameScopeFactory.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/PhpStan/NameScopeFactory.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/PhpStan/NameScopeFactory.php 2026-11-25 09:18:34.000000000 +0000 @@ -26,7 +26,7 @@ $declaringReflection = new \ReflectionClass($declaringClassName); [$declaringNamespace, $declaringUses] = $this->extractFromFullClassName($declaringReflection); - $declaringUses = array_merge($declaringUses, $this->collectUses($declaringReflection)); + $declaringUses += $this->collectUses($declaringReflection); return new NameScope($calledClassName, $declaringNamespace, $declaringUses, $selfClassName ?? $declaringClassName); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpDocExtractorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -34,8 +34,10 @@ use Symfony\Component\PropertyInfo\Tests\Fixtures\Php80Dummy; use Symfony\Component\PropertyInfo\Tests\Fixtures\PseudoTypeDummy; use Symfony\Component\PropertyInfo\Tests\Fixtures\RejectedCandidateDocDummy; +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace\DummyInAnotherNamespace; use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\DummyUsedInTrait; use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\DummyUsingTrait; +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\DummyUsingTraitWithUseDocBlock; use Symfony\Component\PropertyInfo\Tests\Fixtures\VoidNeverReturnTypeDummy; use Symfony\Component\PropertyInfo\Type; @@ -369,6 +371,7 @@ ['propertyInExternalTraitPrimitiveType', new Type(Type::BUILTIN_TYPE_STRING)], ['propertyInExternalTraitObjectSameNamespace', new Type(Type::BUILTIN_TYPE_OBJECT, false, Dummy::class)], ['propertyInExternalTraitObjectDifferentNamespace', new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], + ['redeclaredPropertyInTraitInAnotherNamespace', new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], ]; } @@ -392,6 +395,22 @@ ]; } + public function testMethodsDefinedByTraitInAnotherNamespace() + { + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'aliasedMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'overriddenMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'abstractMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTraitWithUseDocBlock::class, 'abstractMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'overriddenAbstractMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'mutatorInTraitInAnotherNamespace')); + } + + public function testConstructorDefinedByTrait() + { + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypesFromConstructor(DummyUsingTrait::class, 'dummyInConstructor')); + } + /** * @dataProvider propertiesStaticTypeProvider */ @@ -446,6 +465,19 @@ $this->assertNull($this->extractor->getTypes(Dummy::class, 'genericInterface')); } + public function testDocBlocksCacheSizeLimit() + { + for ($i = 0; $i < 2000; ++$i) { + $this->assertNull($this->extractor->getTypes(Dummy::class, 'unknown'.$i)); + } + + $this->assertEquals([new Type(Type::BUILTIN_TYPE_STRING)], $this->extractor->getTypes(Dummy::class, 'bar')); + + $docBlocks = \Closure::bind(fn () => $this->docBlocks, $this->extractor, PhpDocExtractor::class)(); + + $this->assertLessThanOrEqual(1001, \count($docBlocks)); + } + public function testIntersectionTypesAreIgnored() { $this->assertNull($this->extractor->getTypes(DummyIntersectionType::class, 'objects')); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpStanExtractorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpStanExtractorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpStanExtractorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Extractor/PhpStanExtractorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,10 @@ use Symfony\Component\PropertyInfo\Tests\Fixtures\Dummy; use Symfony\Component\PropertyInfo\Tests\Fixtures\DummyCollection; use Symfony\Component\PropertyInfo\Tests\Fixtures\DummyGeneric; +use Symfony\Component\PropertyInfo\Tests\Fixtures\Extractor\ChildWithConstructorOverride; +use Symfony\Component\PropertyInfo\Tests\Fixtures\Extractor\ChildWithoutConstructorOverride; use Symfony\Component\PropertyInfo\Tests\Fixtures\Extractor\ChildWithSelfDocBlock; +use Symfony\Component\PropertyInfo\Tests\Fixtures\Extractor\ParentWithPromotedPropertyDocBlock; use Symfony\Component\PropertyInfo\Tests\Fixtures\Extractor\ParentWithSelfDocBlock; use Symfony\Component\PropertyInfo\Tests\Fixtures\IFace; use Symfony\Component\PropertyInfo\Tests\Fixtures\MultiParameterAdderDocDummy; @@ -30,6 +33,7 @@ use Symfony\Component\PropertyInfo\Tests\Fixtures\RejectedCandidateDocDummy; use Symfony\Component\PropertyInfo\Tests\Fixtures\RootDummy\RootDummyItem; use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace\DummyInAnotherNamespace; +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\DummyImportingDummy; use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\DummyUsedInTrait; use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\DummyUsingTrait; use Symfony\Component\PropertyInfo\Tests\Fixtures\VoidNeverReturnTypeDummy; @@ -329,9 +333,31 @@ ['propertyInTraitObjectSameNamespace', new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], ['propertyInTraitObjectDifferentNamespace', new Type(Type::BUILTIN_TYPE_OBJECT, false, Dummy::class)], ['dummyInAnotherNamespace', new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], + ['redeclaredPropertyInTraitInAnotherNamespace', new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], ]; } + public function testMethodsDefinedByTraits() + { + $this->assertEquals([new Type(Type::BUILTIN_TYPE_STRING)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInTraitPrimitiveType')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInTraitObjectSameNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, Dummy::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInTraitObjectDifferentNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_STRING)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInExternalTraitPrimitiveType')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, Dummy::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInExternalTraitObjectSameNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInExternalTraitObjectDifferentNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'methodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'aliasedMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'overriddenMethodInTraitInAnotherNamespace')); + $this->assertNull($this->extractor->getTypes(DummyUsingTrait::class, 'abstractMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'overriddenAbstractMethodInTraitInAnotherNamespace')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyUsingTrait::class, 'mutatorInTraitInAnotherNamespace')); + } + + public function testConstructorDefinedByTrait() + { + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypesFromConstructor(DummyUsingTrait::class, 'dummyInConstructor')); + } + /** * @dataProvider propertiesStaticTypeProvider */ @@ -492,6 +518,26 @@ $this->assertEquals($phpDocTypes[0]->getClassName(), $phpStanTypes[0]->getClassName()); } + public function testClassImportsWinOverTraitAndParentImports() + { + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, Dummy::class)], $this->extractor->getTypes(DummyImportingDummy::class, 'dummy')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyInAnotherNamespace::class)], $this->extractor->getTypes(DummyImportingDummy::class, 'dummyFromTrait')); + $this->assertEquals([new Type(Type::BUILTIN_TYPE_OBJECT, false, DummyUsedInTrait::class)], $this->extractor->getTypes(DummyImportingDummy::class, 'dummyFromParent')); + } + + public function testDocBlocksCacheSizeLimit() + { + for ($i = 0; $i < 2000; ++$i) { + $this->assertNull($this->extractor->getTypes(Dummy::class, 'unknown'.$i)); + } + + $this->assertEquals([new Type(Type::BUILTIN_TYPE_STRING)], $this->extractor->getTypes(Dummy::class, 'bar')); + + $docBlocks = \Closure::bind(fn () => $this->docBlocks, $this->extractor, PhpStanExtractor::class)(); + + $this->assertLessThanOrEqual(1001, \count($docBlocks)); + } + /** * @dataProvider intRangeTypeProvider */ @@ -529,6 +575,15 @@ ]; } + public function testInheritedPromotedPropertyWithConstructorOverride() + { + $expectedTypes = [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_STRING), new Type(Type::BUILTIN_TYPE_INT))]; + + $this->assertEquals($expectedTypes, $this->extractor->getTypes(ParentWithPromotedPropertyDocBlock::class, 'items')); + $this->assertEquals($expectedTypes, $this->extractor->getTypes(ChildWithoutConstructorOverride::class, 'items')); + $this->assertEquals($expectedTypes, $this->extractor->getTypes(ChildWithConstructorOverride::class, 'items')); + } + public function testGenericInterface() { $this->assertEquals( diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyParentImportingDummy.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyParentImportingDummy.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyParentImportingDummy.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyParentImportingDummy.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace; + +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\DummyUsedInTrait as Dummy; + +class DummyParentImportingDummy +{ + /** + * @var Dummy + */ + public $dummyFromParent; +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitImportingDummy.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitImportingDummy.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitImportingDummy.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitImportingDummy.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,22 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace; + +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace\DummyInAnotherNamespace as Dummy; + +trait DummyTraitImportingDummy +{ + /** + * @var Dummy + */ + public $dummyFromTrait; +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitInAnotherNamespace.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitInAnotherNamespace.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitInAnotherNamespace.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/AnotherNamespace/DummyTraitInAnotherNamespace.php 2026-11-25 09:18:34.000000000 +0000 @@ -8,4 +8,49 @@ * @var DummyInAnotherNamespace */ public $dummyInAnotherNamespace; + + /** + * @var DummyInAnotherNamespace + */ + public $redeclaredPropertyInTraitInAnotherNamespace; + + /** + * @param DummyInAnotherNamespace $dummyInConstructor + */ + public function __construct($dummyInConstructor = null) + { + } + + /** + * @return DummyInAnotherNamespace + */ + public function getMethodInTraitInAnotherNamespace() + { + return new DummyInAnotherNamespace(); + } + + /** + * @return DummyInAnotherNamespace + */ + public function getOverriddenMethodInTraitInAnotherNamespace() + { + return new DummyInAnotherNamespace(); + } + + /** + * @return DummyInAnotherNamespace + */ + abstract public function getAbstractMethodInTraitInAnotherNamespace(); + + /** + * @return DummyInAnotherNamespace + */ + abstract public function getOverriddenAbstractMethodInTraitInAnotherNamespace(); + + /** + * @param DummyInAnotherNamespace $value + */ + public function setMutatorInTraitInAnotherNamespace($value) + { + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyImportingDummy.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyImportingDummy.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyImportingDummy.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyImportingDummy.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,26 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage; + +use Symfony\Component\PropertyInfo\Tests\Fixtures\Dummy; +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace\DummyParentImportingDummy; +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace\DummyTraitImportingDummy; + +class DummyImportingDummy extends DummyParentImportingDummy +{ + use DummyTraitImportingDummy; + + /** + * @var Dummy + */ + public $dummy; +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTrait.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,5 +16,33 @@ class DummyUsingTrait { use DummyTrait; - use DummyTraitInAnotherNamespace; + use DummyTraitInAnotherNamespace { + getMethodInTraitInAnotherNamespace as getAliasedMethodInTraitInAnotherNamespace; + } + + /** + * @var DummyUsedInTrait + */ + public $redeclaredPropertyInTraitInAnotherNamespace; + + /** + * @return DummyUsedInTrait + */ + public function getOverriddenMethodInTraitInAnotherNamespace() + { + return new DummyUsedInTrait(); + } + + public function getAbstractMethodInTraitInAnotherNamespace() + { + return null; + } + + /** + * @return DummyUsedInTrait + */ + public function getOverriddenAbstractMethodInTraitInAnotherNamespace() + { + return new DummyUsedInTrait(); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTraitWithUseDocBlock.php symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTraitWithUseDocBlock.php --- symfony-6.4.50+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTraitWithUseDocBlock.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/PropertyInfo/Tests/Fixtures/TraitUsage/DummyUsingTraitWithUseDocBlock.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,35 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage; + +use Symfony\Component\PropertyInfo\Tests\Fixtures\TraitUsage\AnotherNamespace\DummyTraitInAnotherNamespace; + +class DummyUsingTraitWithUseDocBlock +{ + /** + * @use DummyTraitInAnotherNamespace<DummyUsedInTrait> + */ + use DummyTraitInAnotherNamespace; + + public function getAbstractMethodInTraitInAnotherNamespace() + { + return null; + } + + /** + * @return DummyUsedInTrait + */ + public function getOverriddenAbstractMethodInTraitInAnotherNamespace() + { + return new DummyUsedInTrait(); + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/CompoundLimiter.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/CompoundLimiter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/CompoundLimiter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/CompoundLimiter.php 2026-11-25 09:18:34.000000000 +0000 @@ -42,11 +42,7 @@ foreach ($this->limiters as $limiter) { $rateLimit = $limiter->consume($tokens); - if ( - null === $minimalRateLimit - || $rateLimit->getRemainingTokens() < $minimalRateLimit->getRemainingTokens() - || ($minimalRateLimit->isAccepted() && !$rateLimit->isAccepted()) - ) { + if (null === $minimalRateLimit || self::isMoreRestrictive($rateLimit, $minimalRateLimit)) { $minimalRateLimit = $rateLimit; } } @@ -60,4 +56,22 @@ $limiter->reset(); } } + + private static function isMoreRestrictive(RateLimit $rateLimit, RateLimit $minimalRateLimit): bool + { + if ($rateLimit->isAccepted() !== $minimalRateLimit->isAccepted()) { + return !$rateLimit->isAccepted(); + } + + // the latest retry-after is when all the refusing limiters accept the hit again + if (!$rateLimit->isAccepted() && $rateLimit->getRetryAfter() != $minimalRateLimit->getRetryAfter()) { + return $rateLimit->getRetryAfter() > $minimalRateLimit->getRetryAfter(); + } + + if ($rateLimit->getRemainingTokens() !== $minimalRateLimit->getRemainingTokens()) { + return $rateLimit->getRemainingTokens() < $minimalRateLimit->getRemainingTokens(); + } + + return $rateLimit->getRetryAfter() > $minimalRateLimit->getRetryAfter(); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindow.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindow.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindow.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindow.php 2026-11-25 09:18:34.000000000 +0000 @@ -26,6 +26,7 @@ private int $hitCountForLastWindow = 0; private int $intervalInSeconds; private float $windowEndAt; + private ?int $maxSize = null; public function __construct(string $id, int $intervalInSeconds) { @@ -40,27 +41,46 @@ public static function createFromPreviousWindow(self $window, int $intervalInSeconds): self { $new = new self($window->id, $intervalInSeconds); - $windowEndAt = $window->windowEndAt + $intervalInSeconds; - - if (microtime(true) < $windowEndAt) { - $new->hitCountForLastWindow = $window->hitCount; - $new->windowEndAt = $windowEndAt; + $new->maxSize = $window->maxSize; + // without a size, no hits are carried to the next windows + $maxSize = $window->maxSize ?? max(1, $window->hitCount); + $windows = max(1, 1 + (int) ((microtime(true) - $window->windowEndAt) / $intervalInSeconds)); + // the reserved hits beyond the size of a window act in the next ones + $hitCountForLastWindow = min($maxSize, max(0, $window->hitCount - ($windows - 1) * $maxSize)); + + if (1 === $windows || $hitCountForLastWindow) { + $new->hitCountForLastWindow = $hitCountForLastWindow; + $new->hitCount = max(0, $window->hitCount - $windows * $maxSize); + $new->windowEndAt = $window->windowEndAt + $windows * $intervalInSeconds; } return $new; } + public function configure(int $maxSize): void + { + if (null !== $this->maxSize && $maxSize !== $this->maxSize && $this->hitCount > 0) { + // full windows stay full and the last one is capped at the new size, like for fixed windows + $fullWindows = intdiv($this->hitCount - 1, $this->maxSize); + $this->hitCount = $fullWindows * $maxSize + min($this->hitCount - $fullWindows * $this->maxSize, $maxSize); + } + + $this->maxSize = $maxSize; + } + public function getId(): string { return $this->id; } /** - * Returns the remaining of this timeframe and the next one. + * Returns the remaining of this timeframe and of the next ones its hits act in. */ public function getExpirationTime(): int { - return (int) ceil($this->windowEndAt + $this->intervalInSeconds - microtime(true)); + $windows = null !== $this->maxSize ? max(1, (int) ceil($this->hitCount / $this->maxSize)) : 1; + + return (int) ceil($this->windowEndAt + $windows * $this->intervalInSeconds - microtime(true)); } public function isExpired(): bool @@ -113,14 +133,27 @@ return $toRelease * $this->intervalInSeconds / $this->hitCountForLastWindow; } - return ($this->windowEndAt - $time) + ($toRelease - $releasableInWindow) * $this->intervalInSeconds / max(1, $this->hitCount); + // the reserved hits beyond the size of a window act in the next ones: the tokens fit in the first window with room left + $inWindow = (int) ceil(($this->hitCount + $tokens) / $maxSize) - 1; + $hitCountForPreviousWindow = min($maxSize, $this->hitCount - ($inWindow - 1) * $maxSize); + $hitCountForWindow = max(0, $this->hitCount - $inWindow * $maxSize); + $toReleaseInWindow = $hitCountForPreviousWindow + $hitCountForWindow - ($maxSize - $tokens + 1); + + return ($this->windowEndAt - $time) + ($inWindow - 1) * $this->intervalInSeconds + $toReleaseInWindow * $this->intervalInSeconds / max(1, $hitCountForPreviousWindow); } public function __serialize(): array { - return [ + $data = [ pack('NNN', $this->hitCount, $this->hitCountForLastWindow, $this->intervalInSeconds).$this->id => $this->windowEndAt, ]; + + // older versions read the first entry only + if (null !== $this->maxSize) { + $data[''] = $this->maxSize; + } + + return $data; } public function __unserialize(array $data): void @@ -142,6 +175,7 @@ $pack = key($data); $this->windowEndAt = $data[$pack]; + $this->maxSize = $data[''] ?? null; ['a' => $this->hitCount, 'b' => $this->hitCountForLastWindow, 'c' => $this->intervalInSeconds] = unpack('Na/Nb/Nc', $pack); $this->id = substr($pack, 12); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindowLimiter.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindowLimiter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindowLimiter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Policy/SlidingWindowLimiter.php 2026-11-25 09:18:34.000000000 +0000 @@ -62,7 +62,12 @@ $window = $this->storage->fetch($this->id); if (!$window instanceof SlidingWindow) { $window = new SlidingWindow($this->id, $this->interval); - } elseif ($window->isExpired()) { + } + + // before the expiry check, so that the next window gets the size too + $window->configure($this->limit); + + if ($window->isExpired()) { $window = SlidingWindow::createFromPreviousWindow($window, $this->interval); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Policy/TokenBucketLimiter.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Policy/TokenBucketLimiter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Policy/TokenBucketLimiter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Policy/TokenBucketLimiter.php 2026-11-25 09:18:34.000000000 +0000 @@ -79,14 +79,15 @@ $retryAfter = $now; if ($availableTokens === $tokens) { - $retryAfter += $this->rate->calculateTimeForTokens(1); + // the bucket refills at whole intervals from its timer, not from now + $retryAfter = $bucket->getTimer() + $this->rate->calculateTimeForTokens(1); } $reservation = new Reservation($now, new RateLimit($bucket->getAvailableTokens($now), \DateTimeImmutable::createFromFormat('U', $availableTokens === $tokens ? ceil($retryAfter) : floor($retryAfter)), true, $this->maxBurst)); } else { // peeking with 0 tokens tells when the next token is available $remainingTokens = max(1, $tokens) - $availableTokens; - $waitDuration = $this->rate->calculateTimeForTokens($remainingTokens); + $waitDuration = $bucket->getTimer() + $this->rate->calculateTimeForTokens($remainingTokens) - $now; if (null !== $maxTime && $waitDuration > $maxTime) { // process needs to wait longer than set interval diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/RateLimit.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/RateLimit.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/RateLimit.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/RateLimit.php 2026-11-25 09:18:34.000000000 +0000 @@ -72,6 +72,12 @@ return; } - usleep((int) ($delta * 1e6)); + // on 32-bit platforms, usleep() cannot take more than about 35 minutes + if (1 <= $seconds = (int) $delta) { + sleep($seconds); + $delta -= $seconds; + } + + usleep((int) ceil($delta * 1e6)); } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/CompoundLimiterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/CompoundLimiterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/CompoundLimiterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/CompoundLimiterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -30,6 +30,7 @@ $this->storage = new InMemoryStorage(); ClockMock::register(InMemoryStorage::class); + ClockMock::register(FixedWindowLimiter::class); } public function testConsume() @@ -82,6 +83,87 @@ $this->assertTrue($limiter->consume()->isAccepted()); } + public function testConsumeIsRefusedWhenOneLimiterRefuses() + { + $limiter1 = $this->createLimiter(10, new \DateInterval('PT1M')); + $limiter2 = $this->createLimiter(100, new \DateInterval('PT1M')); + $limiter1->consume(7); + $limiter2->consume(94); + $limiter = new CompoundLimiter([$limiter1, $limiter2]); + + $rateLimit = $limiter->consume(5); + + $this->assertFalse($rateLimit->isAccepted()); + $this->assertSame(3, $rateLimit->getRemainingTokens()); + } + + public function testConsumeIsRefusedUntilTheLatestRetryAfter() + { + ClockMock::withClockMock(1729990780.75); + $limiter1 = $this->createLimiter(10, new \DateInterval('PT1M')); + $limiter2 = $this->createLimiter(20, new \DateInterval('PT1H')); + $limiter1->consume(10); + $limiter2->consume(20); + $limiter = new CompoundLimiter([$limiter1, $limiter2]); + + $rateLimit = $limiter->consume(); + $this->assertFalse($rateLimit->isAccepted()); + $this->assertSame(1729994381, $rateLimit->getRetryAfter()->getTimestamp()); + $this->assertSame(1729994381, (new CompoundLimiter([$limiter2, $limiter1]))->consume()->getRetryAfter()->getTimestamp()); + + $rateLimit->wait(); + $this->assertTrue($limiter->consume()->isAccepted()); + } + + public function testConsumeOfSeveralTokensIsRefusedUntilTheLatestRetryAfter() + { + ClockMock::withClockMock(1729990780.75); + $limiter1 = $this->createLimiter(10, new \DateInterval('PT1M')); + $limiter2 = $this->createLimiter(100, new \DateInterval('PT1H')); + $limiter1->consume(7); + $limiter2->consume(96); + $limiter = new CompoundLimiter([$limiter1, $limiter2]); + + $rateLimit = $limiter->consume(5); + $this->assertFalse($rateLimit->isAccepted()); + $this->assertSame(1729994381, $rateLimit->getRetryAfter()->getTimestamp()); + + $rateLimit->wait(); + $this->assertTrue($limiter->consume(5)->isAccepted()); + } + + public function testRefusalsWithTheSameRetryAfterKeepTheFewestRemainingTokens() + { + ClockMock::withClockMock(1729990780.75); + $limiter1 = $this->createLimiter(10, new \DateInterval('PT1M')); + $limiter2 = $this->createLimiter(20, new \DateInterval('PT1M')); + $limiter1->consume(7); + $limiter2->consume(19); + + $rateLimit = (new CompoundLimiter([$limiter1, $limiter2]))->consume(5); + $this->assertFalse($rateLimit->isAccepted()); + $this->assertSame(1, $rateLimit->getRemainingTokens()); + $this->assertSame(1729990841, $rateLimit->getRetryAfter()->getTimestamp()); + } + + public function testConsumeOfTheLastTokensTellsTheLatestRetryAfter() + { + ClockMock::withClockMock(1729990780.75); + $limiter1 = $this->createLimiter(10, new \DateInterval('PT1M')); + $limiter2 = $this->createLimiter(20, new \DateInterval('PT1H')); + $limiter1->consume(9); + $limiter2->consume(19); + $limiter = new CompoundLimiter([$limiter1, $limiter2]); + + $rateLimit = $limiter->consume(); + $this->assertTrue($rateLimit->isAccepted()); + $this->assertSame(0, $rateLimit->getRemainingTokens()); + $this->assertSame(1729994381, $rateLimit->getRetryAfter()->getTimestamp()); + + $rateLimit->wait(); + $this->assertTrue($limiter->consume()->isAccepted()); + } + public function testReserve() { $this->expectException(ReserveNotSupportedException::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/SlidingWindowLimiterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/SlidingWindowLimiterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/SlidingWindowLimiterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/SlidingWindowLimiterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -202,6 +202,82 @@ $this->assertSame(98, $rateLimit->getRemainingTokens()); } + public function testReservationsWaitForTheWindowWhereTheyFit() + { + $limiter = $this->createLimiter(); + $limiter->consume(10); + + // the hits of the first window fade out during the second one + $this->assertEqualsWithDelta(22.8, $limiter->reserve(10)->getWaitDuration(), 0.01); + // the second window is full, so the next tokens are only available in the third one + $this->assertEqualsWithDelta(34.8, $limiter->reserve(10)->getWaitDuration(), 0.01); + } + + public function testConsumeIsRefusedWhileReservationsFillTheWindow() + { + $limiter = $this->createLimiter(); + $limiter->consume(10); + $limiter->reserve(10); + $limiter->reserve(10); + + sleep(23); + + $this->assertFalse($limiter->consume()->isAccepted()); + } + + public function testStorageKeepsTheStateUntilTheReservationsHaveActed() + { + $limiter = $this->createLimiter(); + $limiter->consume(10); + $limiter->reserve(10); + $limiter->reserve(10); + $limiter->reserve(10); + + sleep(25); + + $this->assertFalse($limiter->consume()->isAccepted()); + } + + public function testLoweringTheLimitDoesNotTurnAcceptedHitsIntoReservations() + { + (new SlidingWindowLimiter('test', 100, new \DateInterval('PT12S'), $this->storage))->consume(50); + + $this->assertEqualsWithDelta(12, $this->createLimiter()->reserve()->getWaitDuration(), 0.01); + } + + public function testStorageKeepsTheStateOfTheNextWindowUntilItsReservationsHaveActed() + { + $limiter = $this->createLimiter(); + $limiter->consume(10); + $limiter->reserve(10); + $limiter->reserve(10); + + sleep(13); + $limiter->reserve(); + sleep(24); + + $this->assertFalse($limiter->consume()->isAccepted()); + } + + public function testLoweringTheLimitKeepsTheReservations() + { + $limiter = new SlidingWindowLimiter('test', 20, new \DateInterval('PT12S'), $this->storage); + $limiter->consume(20); + $limiter->reserve(20); + + $this->assertEqualsWithDelta(24, $this->createLimiter()->reserve()->getWaitDuration(), 0.01); + } + + public function testRaisingTheLimitKeepsTheReservations() + { + $limiter = $this->createLimiter(); + $limiter->consume(10); + $limiter->reserve(10); + + $limiter = new SlidingWindowLimiter('test', 20, new \DateInterval('PT12S'), $this->storage); + $this->assertEqualsWithDelta(18, $limiter->reserve()->getWaitDuration(), 0.01); + } + public function testRejectLimitBelowOne() { $this->expectException(\InvalidArgumentException::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/Policy/TokenBucketLimiterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -288,7 +288,7 @@ sleep(11); $this->assertEquals(0, $limiter->reserve(9)->getWaitDuration()); - $this->assertEquals(10, $limiter->reserve(1)->getWaitDuration()); + $this->assertEquals(9, $limiter->reserve(1)->getWaitDuration()); } public function testEffectivelyInfiniteBurstSizeIsCapped() @@ -339,6 +339,38 @@ $this->assertTrue($limiter->consume()->isAccepted()); } + public function testWaitEndsAtTheNextRefill() + { + ClockMock::withClockMock(1729990800.0); + $limiter = $this->createLimiter(10, Rate::perMinute(10)); + $limiter->consume(9); + + sleep(50); + + $rateLimit = $limiter->consume(); + $this->assertTrue($rateLimit->isAccepted()); + $this->assertSame(1729990860, $rateLimit->getRetryAfter()->getTimestamp()); + + $rateLimit = $limiter->consume(); + $this->assertFalse($rateLimit->isAccepted()); + $this->assertSame(1729990860, $rateLimit->getRetryAfter()->getTimestamp()); + + $this->assertEquals(10, $limiter->reserve()->getWaitDuration()); + $this->assertEquals(70, $limiter->reserve(10)->getWaitDuration()); + } + + public function testConsumeIsAcceptedAfterWaitingForTheRetryAfter() + { + ClockMock::withClockMock(1729990800.0); + $limiter = $this->createLimiter(1, Rate::perSecond(1)); + $limiter->consume(); + usleep(250); + + $limiter->consume()->wait(); + + $this->assertTrue($limiter->consume()->isAccepted()); + } + private function createLimiter($initialTokens = 10, ?Rate $rate = null) { return new TokenBucketLimiter('test', $initialTokens, $rate ?? Rate::perSecond(10), $this->storage); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/RateLimitTest.php symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/RateLimitTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/RateLimiter/Tests/RateLimitTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/RateLimiter/Tests/RateLimitTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -54,4 +54,14 @@ $rateLimit->wait(); // wait until $retryAfter (~2.5 seconds) $this->assertEqualsWithDelta($retryAfter, microtime(true), 0.49); } + + public function testWaitForMoreThanUsleepCanTakeOn32BitPlatforms() + { + ClockMock::register(RateLimit::class); + $retryAfter = time() + 3600.5; + $rateLimit = new RateLimit(10, \DateTimeImmutable::createFromFormat('U.u', $retryAfter), true, 10); + + $rateLimit->wait(); + $this->assertEqualsWithDelta($retryAfter, microtime(true), 0.49); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Generator/UrlGenerator.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Generator/UrlGenerator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Generator/UrlGenerator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Generator/UrlGenerator.php 2026-11-25 09:18:34.000000000 +0000 @@ -187,7 +187,21 @@ return ''; } - $url = $token[1].$mergedParams[$varName].$url; + // browsers resolve "." and ".." path segments even when they are percent-encoded + $value = (string) $mergedParams[$varName]; + if (false !== strpbrk($value, './') && preg_match('#(?:^|/)\.\.?(?:/|$)#D', $token[1].$value.explode('/', $url, 2)[0])) { + $message = 'Parameter "{parameter}" for route "{route}" must not add "." or ".." segments to the path ("{given}" given) to generate a corresponding URL.'; + + if ($this->strictRequirements) { + throw new InvalidParameterException(strtr($message, ['{parameter}' => $varName, '{route}' => $name, '{given}' => $mergedParams[$varName]])); + } + + $this->logger?->error($message, ['parameter' => $varName, 'route' => $name, 'given' => $mergedParams[$varName]]); + + return ''; + } + + $url = $token[1].$value.$url; $optional = false; } } else { @@ -245,6 +259,21 @@ return ''; } + // characters that are forbidden in a host, or that IDNA maps to ".", can change which host the URL points to + // only IPv6 literals like "[::1]" can contain some of them + $value = $mergedParams[$token[3]] ?? ''; + if (preg_match('/[\x00-\x20#%\/:<>?@\[\\\\\]^|\x7F]|\xE3\x80\x82|\xEF\xBC\x8E|\xEF\xBD\xA1/', $value) && !(str_starts_with($value, '[') && str_ends_with($value, ']') && filter_var(substr($value, 1, -1), \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6))) { + $message = 'Parameter "{parameter}" for route "{route}" must not contain characters that are forbidden in a host ("{given}" given) to generate a corresponding URL.'; + + if ($this->strictRequirements) { + throw new InvalidParameterException(strtr($message, ['{parameter}' => $token[3], '{route}' => $name, '{given}' => $mergedParams[$token[3]]])); + } + + $this->logger?->error($message, ['parameter' => $token[3], 'route' => $name, 'given' => $mergedParams[$token[3]]]); + + return ''; + } + $routeHost = $token[1].$mergedParams[$token[3]].$routeHost; } else { $routeHost = $token[1].$routeHost; @@ -277,6 +306,11 @@ $url = self::getRelativePath($this->context->getPathInfo(), $url); } else { $url = $schemeAuthority.$this->context->getBaseUrl().$url; + + // without scheme and host, a URL that starts with "//" would point to another host + if ('' === $schemeAuthority && str_starts_with($url, '//')) { + $url = '/%2F'.substr($url, 2); + } } // add a query string if needed @@ -364,7 +398,9 @@ // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used // as the first segment of a relative-path reference, as it would be mistaken for a scheme name // (see http://tools.ietf.org/html/rfc3986#section-4.2). - return '' === $path || '/' === $path[0] + // A leading backslash, space or control character needs the prefix too, + // since browsers read a backslash as a slash and ignore leading spaces and control characters. + return '' === $path || '/' === $path[0] || '\\' === $path[0] || \ord($path[0]) <= 0x20 || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) ? "./$path" : $path; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/Configurator/RoutingConfigurator.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/Configurator/RoutingConfigurator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/Configurator/RoutingConfigurator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/Configurator/RoutingConfigurator.php 2026-11-25 09:18:34.000000000 +0000 @@ -41,6 +41,7 @@ final public function import(string|array $resource, ?string $type = null, bool $ignoreErrors = false, string|array|null $exclude = null): ImportConfigurator { $this->loader->setCurrentDir(\dirname($this->path)); + $this->loader->trackGlobResource($resource, $this->collection); $imported = $this->loader->import($resource, $type, $ignoreErrors, $this->file, $exclude) ?: []; if (!\is_array($imported)) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/Configurator/Traits/GlobResourceTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/Configurator/Traits/GlobResourceTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/Configurator/Traits/GlobResourceTrait.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/Configurator/Traits/GlobResourceTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,38 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Routing\Loader\Configurator\Traits; + +use Symfony\Component\Routing\RouteCollection; + +/** + * @internal + */ +trait GlobResourceTrait +{ + /** + * @internal + */ + public function trackGlobResource(mixed $resource, RouteCollection $collection): void + { + if (!\is_string($resource) || \strlen($resource) === strcspn($resource, '*?{[') || str_contains($resource, "\n")) { + return; + } + + foreach ($this->glob($resource, false, $globResource, true) as $_) { + break; + } + + foreach (\is_array($globResource) ? $globResource : [$globResource] as $r) { + $collection->addResource($r); + } + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/PhpFileLoader.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/PhpFileLoader.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/PhpFileLoader.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/PhpFileLoader.php 2026-11-25 09:18:34.000000000 +0000 @@ -14,6 +14,7 @@ use Symfony\Component\Config\Loader\FileLoader; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; +use Symfony\Component\Routing\Loader\Configurator\Traits\GlobResourceTrait; use Symfony\Component\Routing\RouteCollection; /** @@ -27,6 +28,8 @@ */ class PhpFileLoader extends FileLoader { + use GlobResourceTrait; + /** * Loads a PHP file. */ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/XmlFileLoader.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/XmlFileLoader.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/XmlFileLoader.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/XmlFileLoader.php 2026-11-25 09:18:34.000000000 +0000 @@ -14,6 +14,7 @@ use Symfony\Component\Config\Loader\FileLoader; use Symfony\Component\Config\Resource\FileResource; use Symfony\Component\Config\Util\XmlUtils; +use Symfony\Component\Routing\Loader\Configurator\Traits\GlobResourceTrait; use Symfony\Component\Routing\Loader\Configurator\Traits\HostTrait; use Symfony\Component\Routing\Loader\Configurator\Traits\LocalizedRouteTrait; use Symfony\Component\Routing\Loader\Configurator\Traits\PrefixTrait; @@ -27,6 +28,7 @@ */ class XmlFileLoader extends FileLoader { + use GlobResourceTrait; use HostTrait; use LocalizedRouteTrait; use PrefixTrait; @@ -187,7 +189,7 @@ $exclude = []; foreach ($node->childNodes as $child) { - if ($child instanceof \DOMElement && $child->localName === $exclude && self::NAMESPACE_URI === $child->namespaceURI) { + if ($child instanceof \DOMElement && 'exclude' === $child->localName && self::NAMESPACE_URI === $child->namespaceURI) { $exclude[] = $child->nodeValue; } } @@ -200,6 +202,7 @@ } $this->setCurrentDir(\dirname($path)); + $this->trackGlobResource($resource, $collection); /** @var RouteCollection[] $imported */ $imported = $this->import($resource, '' !== $type ? $type : null, false, $file, $exclude) ?: []; @@ -294,6 +297,7 @@ $condition = trim($n->textContent); break; case 'resource': + case 'exclude': break; default: throw new \InvalidArgumentException(\sprintf('Unknown tag "%s" used in file "%s". Expected "default", "requirement", "option" or "condition".', $n->localName, $path)); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/YamlFileLoader.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/YamlFileLoader.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Loader/YamlFileLoader.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Loader/YamlFileLoader.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,6 +13,7 @@ use Symfony\Component\Config\Loader\FileLoader; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Routing\Loader\Configurator\Traits\GlobResourceTrait; use Symfony\Component\Routing\Loader\Configurator\Traits\HostTrait; use Symfony\Component\Routing\Loader\Configurator\Traits\LocalizedRouteTrait; use Symfony\Component\Routing\Loader\Configurator\Traits\PrefixTrait; @@ -29,6 +30,7 @@ */ class YamlFileLoader extends FileLoader { + use GlobResourceTrait; use HostTrait; use LocalizedRouteTrait; use PrefixTrait; @@ -209,6 +211,7 @@ } $this->setCurrentDir(\dirname($path)); + $this->trackGlobResource($config['resource'], $collection); /** @var RouteCollection[] $imported */ $imported = $this->import($config['resource'], $type, false, $file, $exclude) ?: []; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherDumper.php 2026-11-25 09:18:34.000000000 +0000 @@ -70,6 +70,16 @@ if ($host = $route->getHost()) { $matchHost = true; $host = '/'.strtr(strrev($host), '}.{', '(/)'); + // routes are grouped and reordered only on variables that take a whole label and can't match a dot, + // as the label of a variable that is next to other characters may also be matched by a variable alone + $host = preg_replace_callback('#(?<=(.))\(([\w\x80-\xFF]++)!?\)(?=(.?))#', static function ($m) use ($route) { + if ('/' !== $m[1] || '' !== $m[3] && '/' !== $m[3]) { + return '(.*)'; + } + $requirement = $route->getRequirement(strrev($m[2])); + + return null === $requirement || preg_match('#^(?:[\w|?*+{},:)-]|\((?!\?)|\(\?[:|]|\\\\[dw]|\[(?:\w|\\\\[dw]|(?<=\w)-(?=\w)|(?<=\[)-|-(?=\]))++\])++$#', $requirement) ? $m[0] : '(.*)'; + }, $host); } $routes->addRoute($host ?: '/(.*)', [$name, $route]); @@ -269,10 +279,6 @@ 'vars' => [], ]; $state->getVars = static function ($m) use ($state) { - if ('_route' === $m[1]) { - return '?:'; - } - $state->vars[] = $m[1]; return ''; @@ -323,10 +329,8 @@ // Group 1 captures the path so that host variables cannot match any part of it. // Group 1 is mapped to the first host variable, then the group of that variable overwrites it. // The first lookahead skips the capture when the host cannot match. - // It is left out when requirements contain named groups, because a regexp can't define the same name twice. $hostCheck = preg_replace('#\?P<[^>]++>#', '?:', $rx[1]); - $hostCheck = preg_match('#\(\?(?:<[^=!]|\')#', $hostCheck) ? '' : '(?=(?i:'.$hostCheck.')\.)'; - $hostRegex = $hostCheck.'(?=[^/]*+(.*+))'.$hostRegex.'(?=\1)'; + $hostRegex = '(?=(?i:'.$hostCheck.')\.)(?=[^/]*+(.*+))'.$hostRegex.'(?=\1)'; array_unshift($state->hostVars, $state->hostVars[0]); } } else { @@ -409,6 +413,12 @@ [$name, $regex, $vars, $route, $hasTrailingSlash, $hasTrailingVar] = $route; $compiledRoute = $route->compile(); + foreach ($vars as $i => $var) { + // as in UrlMatcher, a variable that is also in the host takes the value of the host: groups named "_route" are skipped + if (\in_array($var, $state->hostVars, true)) { + $vars[$i] = '_route'; + } + } $vars = array_merge($state->hostVars, $vars); if ($compiledRoute->getRegex() === $prevRegex) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Matcher/Dumper/CompiledUrlMatcherTrait.php 2026-11-25 09:18:34.000000000 +0000 @@ -52,7 +52,8 @@ $this->context->setScheme(key($allowSchemes)); try { if ($ret = $this->doMatch($pathinfo)) { - return $this->redirect($pathinfo, $ret['_route'], $this->context->getScheme()) + $ret; + // a leading "//" or "/\", even with tabs or newlines in between, would make the redirection point to another host + return $this->redirect(preg_replace(['#^/[\t\n\r]*+\K/#', '#^/[\t\n\r]*+\K\\\\#'], ['%2F', '%5C'], $pathinfo), $ret['_route'], $this->context->getScheme()) + $ret; } } finally { $this->context->setScheme($scheme); @@ -62,7 +63,7 @@ $fallbackPathinfo = $pathinfo; $pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo; if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes, $trailingSlashSchemes)) { - return $this->redirect($pathinfo, $ret['_route']) + $ret; + return $this->redirect(preg_replace(['#^/[\t\n\r]*+\K/#', '#^/[\t\n\r]*+\K\\\\#'], ['%2F', '%5C'], $pathinfo), $ret['_route']) + $ret; } if ($allowSchemes = $allowSchemes ?: $trailingSlashSchemes) { goto redirect_scheme; @@ -94,6 +95,10 @@ $supportsRedirections = 'GET' === $canonicalMethod && $this instanceof RedirectableUrlMatcherInterface; foreach ($this->staticRoutes[$trimmedPathinfo] ?? [] as [$ret, $requiredHost, $requiredMethods, $requiredSchemes, $hasTrailingSlash, , $condition]) { + if ($trimmedPathinfo !== $pathinfo && str_ends_with($pathinfo, '//')) { + break; + } + if ($requiredHost) { if ('{' !== $requiredHost[0] ? $requiredHost !== $host : !preg_match($requiredHost, $host, $hostMatches)) { continue; @@ -151,7 +156,7 @@ } foreach ($vars as $i => $v) { - if (isset($matches[1 + $i])) { + if (isset($matches[1 + $i]) && '_route' !== $v) { $ret[$v] = $matches[1 + $i]; } } @@ -161,7 +166,7 @@ } if ('/' !== $pathinfo && !$hasTrailingVar && $hasTrailingSlash === ($trimmedPathinfo === $pathinfo)) { - if ($supportsRedirections && (!$requiredMethods || isset($requiredMethods['GET']))) { + if ($supportsRedirections && '/' !== $trimmedPathinfo && (!$requiredMethods || isset($requiredMethods['GET']))) { $trailingSlashSchemes = $allowSchemes; return $allow = $allowSchemes = []; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Matcher/RedirectableUrlMatcher.php 2026-11-25 09:18:34.000000000 +0000 @@ -35,7 +35,8 @@ try { $ret = parent::match($pathinfo); - return $this->redirect($pathinfo, $ret['_route'] ?? null, $this->context->getScheme()) + $ret; + // a leading "//" or "/\", even with tabs or newlines in between, would make the redirection point to another host + return $this->redirect(preg_replace(['#^/[\t\n\r]*+\K/#', '#^/[\t\n\r]*+\K\\\\#'], ['%2F', '%5C'], $pathinfo), $ret['_route'] ?? null, $this->context->getScheme()) + $ret; } catch (ExceptionInterface) { throw $e; } finally { @@ -50,7 +51,7 @@ $pathinfo = $trimmedPathinfo === $pathinfo ? $pathinfo.'/' : $trimmedPathinfo; $ret = parent::match($pathinfo); - return $this->redirect($pathinfo, $ret['_route'] ?? null) + $ret; + return $this->redirect(preg_replace(['#^/[\t\n\r]*+\K/#', '#^/[\t\n\r]*+\K\\\\#'], ['%2F', '%5C'], $pathinfo), $ret['_route'] ?? null) + $ret; } catch (ExceptionInterface) { if ($this->allowSchemes) { goto redirect_scheme; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/RouteCompiler.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/RouteCompiler.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/RouteCompiler.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/RouteCompiler.php 2026-11-25 09:18:34.000000000 +0000 @@ -325,6 +325,9 @@ continue; } if ('*' === $regexp[++$i] || '?' === $regexp[$i]) { + if (preg_match('/\G\?(?:P?<(?![=!])[^>]++>|\'[^\']++\')/', $regexp, $m, 0, $i)) { + $regexp = substr_replace($regexp, '?:', $i, \strlen($m[0])); + } ++$i; continue; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/dumper/compiled_url_matcher13.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/dumper/compiled_url_matcher13.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/dumper/compiled_url_matcher13.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/dumper/compiled_url_matcher13.php 2026-11-25 09:18:34.000000000 +0000 @@ -20,8 +20,8 @@ ], [ // $dynamicRoutes 114 => [ - [['_route' => 'r1'], ['foo', 'foo', 'foo'], null, null, false, true, null], - [['_route' => 'r2'], ['foo', 'foo', 'foo'], null, null, false, true, null], + [['_route' => 'r1'], ['foo', 'foo', '_route'], null, null, false, true, null], + [['_route' => 'r2'], ['foo', 'foo', '_route'], null, null, false, true, null], [null, null, null, null, false, false, 0], ], ], diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/glob/import_exclude.xml symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/glob/import_exclude.xml --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/glob/import_exclude.xml 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Fixtures/glob/import_exclude.xml 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<routes xmlns="http://symfony.com/schema/routing" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/routing + https://symfony.com/schema/routing/routing-1.0.xsd"> + + <import resource="ba?.xml"> + <exclude>baz.xml</exclude> + </import> +</routes> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -477,6 +477,36 @@ $this->assertSame('/path-and-not-domain', $this->getGenerator($routes, ['BaseUrl' => ''])->generate('test')); } + /** + * @dataProvider provideParametersThatStartThePathWithTwoSlashes + */ + public function testParametersThatStartThePathWithTwoSlashes(?bool $strictRequirements, string $routePath, array $requirements, array $parameters, string $path) + { + $routes = $this->getRoutes('test', new Route($routePath, [], $requirements)); + $generator = $this->getGenerator($routes, ['BaseUrl' => '']); + $generator->setStrictRequirements($strictRequirements); + + $this->assertSame('/%2F'.substr($path, 2), $generator->generate('test', $parameters)); + $this->assertSame('http://localhost'.$path, $generator->generate('test', $parameters, UrlGeneratorInterface::ABSOLUTE_URL)); + + $generator->getContext()->setHost(''); + $this->assertSame('/%2F'.substr($path, 2), $generator->generate('test', $parameters, UrlGeneratorInterface::ABSOLUTE_URL)); + + $generator->getContext()->setBaseUrl('/app.php'); + $this->assertSame('/app.php'.$path, $generator->generate('test', $parameters)); + } + + public static function provideParametersThatStartThePathWithTwoSlashes() + { + yield [null, '/{_locale}/blog/rss.xml', ['_locale' => 'en|fr|vi|zh_CN'], ['_locale' => '/evil.com'], '//evil.com/blog/rss.xml']; + + foreach ([true, false, null] as $strictRequirements) { + yield [$strictRequirements, '/{slug}', ['slug' => '.+'], ['slug' => '/evil.example'], '//evil.example']; + yield [$strictRequirements, '/{slug}', ['slug' => '.+'], ['slug' => '//evil.example'], '///evil.example']; + yield [$strictRequirements, '/{dir}/{slug}', ['dir' => '.*'], ['dir' => '', 'slug' => 'evil.example'], '//evil.example']; + } + } + public function testNoTrailingSlashForMultipleOptionalParameters() { $routes = $this->getRoutes('test', new Route('/category/{slug1}/{slug2}/{slug3}', ['slug2' => null, 'slug3' => null])); @@ -552,16 +582,62 @@ $this->assertSame('/app.php/a./.a/a../..a/...', $this->getGenerator($routes)->generate('test')); } - public function testEncodingOfChainedRelativePathSegments() + /** + * @dataProvider provideParametersThatMakeDotSegments + */ + public function testParametersThatMakeDotSegments(string $routePath, array $requirements, array $parameters) { - $routes = $this->getRoutes('test', new Route('/foo/{path}/bar', [], ['path' => '.+'])); - $this->assertSame('/app.php/foo/%2E%2E/%2E%2E/%2E%2E/bar', $this->getGenerator($routes)->generate('test', ['path' => '../../..'])); - $this->assertSame('/app.php/foo/%2E/%2E/%2E/bar', $this->getGenerator($routes)->generate('test', ['path' => '././.'])); - $this->assertSame('/app.php/foo/%2E%2E/%2E/%2E/%2E%2E/bar', $this->getGenerator($routes)->generate('test', ['path' => '../././..'])); + $routes = $this->getRoutes('test', new Route($routePath, [], $requirements)); + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', $parameters); + } + + public static function provideParametersThatMakeDotSegments() + { + yield ['/foo/{path}/bar', ['path' => '.+'], ['path' => '../../..']]; + yield ['/foo/{path}/bar', ['path' => '.+'], ['path' => '././.']]; + yield ['/foo/{path}/bar', ['path' => '.+'], ['path' => '../././..']]; + yield ['/foo/{path}', ['path' => '.+'], ['path' => '../../..']]; + yield ['/foo/{path}', ['path' => '.+'], ['path' => '././.']]; + yield ['/foo/{path}', ['path' => '.+'], ['path' => '../admin']]; + yield ['/foo/{path}', ['path' => '.+'], ['path' => 'a/..']]; + yield ['/{path}', ['path' => '.+'], ['path' => '/./evil.example']]; + yield ['/user/{id}/edit', [], ['id' => '..']]; + yield ['/user/{id}/edit', [], ['id' => '.']]; + yield ['/foo/.{suffix}', [], ['suffix' => '.']]; + yield ['/foo/.{suffix}', ['suffix' => '.+'], ['suffix' => '/bar']]; + yield ['/foo/{path}./bar', ['path' => '.+'], ['path' => 'a/']]; + } + + /** + * @dataProvider provideNonStrictRequirements + */ + public function testParametersThatMakeDotSegmentsInNonStrictMode(?bool $strictRequirements) + { $routes = $this->getRoutes('test', new Route('/foo/{path}', [], ['path' => '.+'])); - $this->assertSame('/app.php/foo/%2E%2E/%2E%2E/%2E%2E', $this->getGenerator($routes)->generate('test', ['path' => '../../..'])); - $this->assertSame('/app.php/foo/%2E/%2E/%2E', $this->getGenerator($routes)->generate('test', ['path' => '././.'])); + $logger = $this->createMock(LoggerInterface::class); + $logger->expects($this->once()) + ->method('error'); + $generator = $this->getGenerator($routes, [], $logger); + $generator->setStrictRequirements($strictRequirements); + + $this->assertSame('', $generator->generate('test', ['path' => '../admin'])); + } + + public static function provideNonStrictRequirements() + { + yield [false]; + yield [null]; + } + + public function testParametersWithDotsThatDoNotMakeDotSegments() + { + $routes = $this->getRoutes('test', new Route('/foo/{path}.json', [], ['path' => '.+'])); + $generator = $this->getGenerator($routes); + + $this->assertSame('/app.php/foo/.../a../..a/.a/a..json', $generator->generate('test', ['path' => '.../a../..a/.a/a.'])); + $this->assertSame('/app.php/foo/a/..json', $generator->generate('test', ['path' => 'a/.'])); } public function testEncodingOfSlashInPath() @@ -699,6 +775,100 @@ $this->assertSame('', $generator->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH)); } + /** + * @dataProvider provideHostParametersWithForbiddenCharacters + */ + public function testHostParameterWithForbiddenCharacters(string $value) + { + $routes = $this->getRoutes('test', new Route('/dashboard', [], [], [], '{tenant}.example.com')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['tenant' => $value], UrlGeneratorInterface::ABSOLUTE_URL); + } + + public static function provideHostParametersWithForbiddenCharacters() + { + yield ['evil%2Ecom#']; + yield ['3232235777/']; + yield ['evil?']; + yield ['user@evil']; + yield ['evil\\']; + yield ['evil:8080']; + yield ['evil example']; + yield ["evil\t"]; + yield ["evil\n"]; + yield ["evil\0"]; + yield ["evil\x7F"]; + yield ['evil<']; + yield ['evil>']; + yield ['evil^']; + yield ['evil|']; + yield ["evil\u{FF0E}com"]; + yield ["evil\u{3002}com"]; + yield ["evil\u{FF61}com"]; + } + + public function testHostParameterWithForbiddenCharactersAndPermissiveRequirement() + { + $routes = $this->getRoutes('test', new Route('/dashboard', [], ['tenant' => '.+'], [], '{tenant}.example.com')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['tenant' => 'evil.example/'], UrlGeneratorInterface::ABSOLUTE_URL); + } + + public function testHostParameterWithIpv6Literal() + { + $routes = $this->getRoutes('test', new Route('/dashboard', [], ['domain' => '.+'], [], '{domain}')); + $generator = $this->getGenerator($routes); + + $this->assertSame('http://[::1]/app.php/dashboard', $generator->generate('test', ['domain' => '[::1]'], UrlGeneratorInterface::ABSOLUTE_URL)); + + $generator->setStrictRequirements(null); + $this->assertSame('http://[::1]/app.php/dashboard', $generator->generate('test', ['domain' => '[::1]'], UrlGeneratorInterface::ABSOLUTE_URL)); + } + + /** + * @dataProvider provideHostParametersThatAreNotIpv6Literals + */ + public function testHostParameterThatIsNotAnIpv6Literal(string $value) + { + $routes = $this->getRoutes('test', new Route('/dashboard', [], ['domain' => '.+'], [], '{domain}')); + + $this->expectException(InvalidParameterException::class); + $this->getGenerator($routes)->generate('test', ['domain' => $value], UrlGeneratorInterface::ABSOLUTE_URL); + } + + public static function provideHostParametersThatAreNotIpv6Literals() + { + yield ['[::1]:80']; + yield ['[evil.com]']; + yield ['[::1]x']; + } + + /** + * @dataProvider provideNonStrictRequirements + */ + public function testHostParameterWithForbiddenCharactersInNonStrictMode(?bool $strictRequirements) + { + $routes = $this->getRoutes('test', new Route('/dashboard', [], [], [], '{tenant}.example.com')); + $logger = $this->createMock(LoggerInterface::class); + $logger->expects($this->once()) + ->method('error'); + $generator = $this->getGenerator($routes, [], $logger); + $generator->setStrictRequirements($strictRequirements); + + $this->assertSame('', $generator->generate('test', ['tenant' => 'evil%2Ecom#'], UrlGeneratorInterface::ABSOLUTE_URL)); + } + + public function testHostParameterWithValidCharacters() + { + $routes = $this->getRoutes('test', new Route('/dashboard', [], ['tenant' => '.+'], [], '{tenant}.example.com')); + $generator = $this->getGenerator($routes); + + $this->assertSame('http://a-b_c.d.example.com/app.php/dashboard', $generator->generate('test', ['tenant' => 'a-b_c.d'], UrlGeneratorInterface::ABSOLUTE_URL)); + $this->assertSame('http://bücher.example.com/app.php/dashboard', $generator->generate('test', ['tenant' => 'bücher'], UrlGeneratorInterface::ABSOLUTE_URL)); + } + public function testHostIsCaseInsensitive() { $routes = $this->getRoutes('test', new Route('/', [], ['locale' => 'en|de|fr'], [], '{locale}.FooBar.com')); @@ -1040,6 +1210,26 @@ '/dir/:subdir/', './:subdir/', ], + [ + '/dir/file', + '/dir/\\\\example.com', + './\\\\example.com', + ], + [ + '/dir/file', + '/dir/\\/example.com', + './\\/example.com', + ], + [ + '/dir/file', + '/dir/ //example.com', + './ //example.com', + ], + [ + '/dir/file', + "/dir/\t//example.com", + "./\t//example.com", + ], ]; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,7 +16,9 @@ use Symfony\Component\Config\FileLocatorInterface; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\Routing\Loader\AttributeClassLoader; +use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; use Symfony\Component\Routing\Loader\PhpFileLoader; use Symfony\Component\Routing\Loader\Psr4DirectoryLoader; use Symfony\Component\Routing\Route; @@ -255,6 +257,17 @@ $route = $routeCollection->get('baz_route'); $this->assertSame('AppBundle:Baz:view', $route->getDefault('_controller')); + + $this->assertContainsEquals(new GlobResource(__DIR__.'/../Fixtures/glob', '/php_dsl_ba?.php', false), $routeCollection->getResources()); + } + + public function testRoutingConfiguratorTracksGlobMatchingNoFiles() + { + $collection = new RouteCollection(); + $routes = new RoutingConfigurator($collection, new PhpFileLoader(new FileLocator()), __FILE__, __FILE__); + $routes->import(__DIR__.'/../Fixtures/glob/*.missing'); + + $this->assertEquals([new GlobResource(__DIR__.'/../Fixtures/glob', '/*.missing', false)], $collection->getResources()); } public function testRoutingI18nConfigurator() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,6 +16,7 @@ use Symfony\Component\Config\FileLocatorInterface; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\Routing\Loader\AttributeClassLoader; use Symfony\Component\Routing\Loader\Psr4DirectoryLoader; use Symfony\Component\Routing\Loader\XmlFileLoader; @@ -516,6 +517,17 @@ $route = $routeCollection->get('baz_route'); $this->assertSame('AppBundle:Baz:view', $route->getDefault('_controller')); + + $this->assertContainsEquals(new GlobResource(__DIR__.'/../Fixtures/glob', '/ba?.xml', false), $routeCollection->getResources()); + } + + public function testImportWithExcludeTags() + { + $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/glob'])); + $routeCollection = $loader->load('import_exclude.xml'); + + $this->assertNotNull($routeCollection->get('bar_route')); + $this->assertNull($routeCollection->get('baz_route')); } public function testImportRouteWithNamePrefix() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,6 +16,7 @@ use Symfony\Component\Config\FileLocatorInterface; use Symfony\Component\Config\Loader\LoaderResolver; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Config\Resource\GlobResource; use Symfony\Component\Routing\Loader\AttributeClassLoader; use Symfony\Component\Routing\Loader\Psr4DirectoryLoader; use Symfony\Component\Routing\Loader\YamlFileLoader; @@ -209,6 +210,8 @@ $route = $routeCollection->get('baz_route'); $this->assertSame('AppBundle:Baz:view', $route->getDefault('_controller')); + + $this->assertContainsEquals(new GlobResource(__DIR__.'/../Fixtures/glob', '/ba?.yml', false), $routeCollection->getResources()); } public function testImportRouteWithNamePrefix() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -132,6 +132,41 @@ $matcher->match('/foo%3Abar'); } + /** + * @dataProvider provideLeadingDoubleSlash + */ + public function testSlashRedirectEncodesLeadingDoubleSlash(string $pathinfo, string $redirectPath) + { + $coll = new RouteCollection(); + $coll->add('foo', new Route('/{path}/edit/', [], ['path' => '.+'])); + + $matcher = $this->getUrlMatcher($coll, null, true); + $matcher->expects($this->once())->method('redirect')->with($redirectPath.'/', 'foo')->willReturn([]); + $matcher->match($pathinfo); + } + + /** + * @dataProvider provideLeadingDoubleSlash + */ + public function testSchemeRedirectEncodesLeadingDoubleSlash(string $pathinfo, string $redirectPath) + { + $coll = new RouteCollection(); + $coll->add('foo', new Route('/{path}/edit', [], ['path' => '.+'], [], '', ['https'])); + + $matcher = $this->getUrlMatcher($coll, null, true); + $matcher->expects($this->once())->method('redirect')->with($redirectPath, 'foo', 'https')->willReturn([]); + $matcher->match($pathinfo); + } + + public static function provideLeadingDoubleSlash(): iterable + { + yield ['//evil.example/edit', '/%2Fevil.example/edit']; + yield ['///evil.example/edit', '/%2F/evil.example/edit']; + yield ['/\\evil.example/edit', '/%5Cevil.example/edit']; + yield ["/\t/evil.example/edit", "/\t%2Fevil.example/edit"]; + yield ["/\r\n\\evil.example/edit", "/\r\n%5Cevil.example/edit"]; + } + public function testSchemeRequirement() { $coll = new RouteCollection(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -477,6 +477,49 @@ $matcher->match('/foo/'); } + public function testMoreThanOneTrailingSlash() + { + $this->expectException(ResourceNotFoundException::class); + $coll = new RouteCollection(); + $coll->add('foo', new Route('/foo/')); + + $matcher = $this->getUrlMatcher($coll); + $matcher->match('/foo//'); + } + + public function testMoreThanOneTrailingSlashWithCatchAllRoute() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/')); + $coll->add('b', new Route('/login')); + $coll->add('c', new Route('/admin/')); + $coll->add('d', new Route('/blog/{slug}/')); + $coll->add('e', new Route('/{path}', [], ['path' => '.*'])); + + $matcher = $this->getUrlMatcher($coll); + $this->assertEquals(['_route' => 'e', 'path' => '/'], $matcher->match('//')); + $this->assertEquals(['_route' => 'e', 'path' => 'login//'], $matcher->match('/login//')); + $this->assertEquals(['_route' => 'e', 'path' => 'admin//'], $matcher->match('/admin//')); + $this->assertEquals(['_route' => 'e', 'path' => 'admin///'], $matcher->match('/admin///')); + $this->assertEquals(['_route' => 'e', 'path' => 'blog/foo//'], $matcher->match('/blog/foo//')); + } + + public function testMoreThanOneTrailingSlashWithRootRouteAfterCatchAllRoute() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/{path}', [], ['path' => '.*'], [], '', [], ['POST'])); + $coll->add('b', new Route('/')); + + $matcher = $this->getUrlMatcher($coll); + + try { + $matcher->match('//'); + $this->fail(); + } catch (MethodNotAllowedException $e) { + $this->assertSame(['POST'], $e->getAllowedMethods()); + } + } + public function testSchemeRequirement() { $this->getExpectedException() ?: $this->expectException(ResourceNotFoundException::class); @@ -939,6 +982,39 @@ $this->assertEquals('b', $matcher->match('/bar/abc.123')['_route']); } + public function testHostVariableMatchingDotsKeepsTheOrderOfRoutes() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/{slug}', [], ['slug' => '\d+'], [], 'app.{sub}.{domain}')); + $coll->add('b', new Route('/admin/report/{id}', [], ['domain' => '.+'], [], '{domain}')); + $coll->add('c', new Route('/admin/{slug}/{id}', [], ['domain' => '.+'], [], '{tld}.{domain}')); + + $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', 'app.example.com')); + $this->assertSame('b', $matcher->match('/admin/report/1')['_route']); + } + + /** + * @dataProvider provideHostsWithVariablesSharingTheirLabel + */ + public function testHostVariableSharingItsLabelKeepsTheOrderOfRoutes(string $firstHost, string $secondHost, string $thirdHost, string $host) + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/foo', [], [], [], $firstHost)); + $coll->add('b', new Route('/report/{id}', [], [], [], $secondHost)); + $coll->add('c', new Route('/report/{id}', [], [], [], $thirdHost)); + + $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', $host)); + $this->assertSame('b', $matcher->match('/report/1')['_route']); + } + + public static function provideHostsWithVariablesSharingTheirLabel(): iterable + { + yield ['xyz-{sub}.example.com', '{sub}.example.com', 'app-{sub}.example.com', 'app-x.example.com']; + yield ['{c}-{b}.example.com', '{b}.example.com', '{a}-{b}.example.com', 'x-y.example.com']; + yield ['{c}x{b}', '{b}', '{a}x{b}', 'axb']; + yield ['bpi{n}.example.com', '{n}.example.com', 'api{n}.example.com', 'api1.example.com']; + } + public function testHostVariableDoesNotMatchThePath() { $coll = new RouteCollection(); @@ -1003,6 +1079,53 @@ $matcher->match('/x./admin/report/latest'); } + public function testHostVariableNamedRouteDoesNotMatchThePath() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/admin/report/{id}', [], [], [], 'app.{_route}')); + + $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', 'app.localhost')); + $this->assertEquals(['_route' => 'a', 'id' => '1'], $matcher->match('/admin/report/1')); + + $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', 'app')); + + $this->expectException(ResourceNotFoundException::class); + $matcher->match('/x./admin/report/1'); + } + + public function testRouteVariableDoesNotReplaceTheRouteName() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/foo/{_route}/{bar}')); + + $matcher = $this->getUrlMatcher($coll); + $this->assertEquals(['_route' => 'a', 'bar' => 'baz'], $matcher->match('/foo/abc/baz')); + } + + public function testNamedGroupsInRequirements() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/admin/{section}/{id}', [], ['section' => '(?<s>[a-z]+)(?<!x)', 'id' => "(?'i'\\d+)"])); + $coll->add('b', new Route('/report/{id}', [], ['id' => '(?P<i>\d+)', 'tenant' => '(?<t>[a-z]+)'], [], '{tenant}.example.com')); + + $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', 'acme.example.com')); + $this->assertEquals(['_route' => 'a', 'section' => 'report', 'id' => '42'], $matcher->match('/admin/report/42')); + $this->assertEquals(['_route' => 'b', 'tenant' => 'acme', 'id' => '42'], $matcher->match('/report/42')); + } + + public function testVariableInHostAndPathTakesTheValueOfTheHost() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/{tenant}/dashboard', [], [], [], '{tenant}.example.com')); + $coll->add('b', new Route('/{tenant}/report/{id}', [], [], [], '{id}.{tenant}.example.org')); + + $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', 'acme.example.com')); + $this->assertEquals(['_route' => 'a', 'tenant' => 'acme'], $matcher->match('/other/dashboard')); + + $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'GET', '1.acme.example.org')); + $this->assertEquals(['_route' => 'b', 'tenant' => 'acme', 'id' => '1'], $matcher->match('/other/report/2')); + } + public function testSlashVariant() { $coll = new RouteCollection(); @@ -1077,6 +1200,16 @@ $this->assertEquals(['_route' => 'a', 'a' => 'foo/'], $matcher->match('/foo/')); } + public function testGreedyTrailingRequirementAfterNamedGroup() + { + $coll = new RouteCollection(); + $coll->add('a', new Route('/{a}/{b}', [], ['a' => '(?P<c>[a-z]+)', 'b' => '.+'])); + + $matcher = $this->getUrlMatcher($coll); + + $this->assertEquals(['_route' => 'a', 'a' => 'foo', 'b' => 'bar/'], $matcher->match('/foo/bar/')); + } + public function testTrailingRequirementWithDefault() { $coll = new RouteCollection(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Routing/Tests/RouteCompilerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -188,15 +188,11 @@ */ public function testCompileImplicitUtf8Data($name, $arguments, $prefix, $regex, $variables, $tokens, $deprecationType) { - $this->expectException(\LogicException::class); $r = new \ReflectionClass(Route::class); $route = $r->newInstanceArgs($arguments); - $compiled = $route->compile(); - $this->assertEquals($prefix, $compiled->getStaticPrefix(), $name.' (static prefix)'); - $this->assertEquals($regex, $compiled->getRegex(), $name.' (regex)'); - $this->assertEquals($variables, $compiled->getVariables(), $name.' (variables)'); - $this->assertEquals($tokens, $compiled->getTokens(), $name.' (tokens)'); + $this->expectException(\LogicException::class); + $route->compile(); } public static function provideCompileImplicitUtf8Data() @@ -389,6 +385,9 @@ yield ['{^/(?P<foo>(?(b)b))$}sD', '(?(b)b)']; yield ['{^/(?P<foo>(*F))$}sD', '(*F)']; yield ['{^/(?P<foo>(?:(?:foo)))$}sD', '((foo))']; + yield ['{^/(?P<foo>a(?:b)(?:c)(?:d))$}sD', "a(?P<x>b)(?<y>c)(?'z'd)"]; + yield ['{^/(?P<foo>(?:(?:b)))$}sD', '(?<x>(b))']; + yield ['{^/(?P<foo>(?<=a)b(?<!c))$}sD', '(?<=a)b(?<!c)']; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Generator/Checkpoint.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Generator/Checkpoint.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Generator/Checkpoint.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Generator/Checkpoint.php 2026-11-25 09:18:34.000000000 +0000 @@ -33,6 +33,9 @@ ) { } + /** + * @phpstan-impure + */ public function acquire(\DateTimeImmutable $now): bool { if ($this->lock && !$this->lock->acquire()) { @@ -47,11 +50,17 @@ $state = !$this->reset && isset($this->time) ? [$this->time, $this->index, $this->from] : [$now, -1, $now]; $this->reset = false; - [$this->time, $this->index, $this->from] = $this->cache->get($this->name, static function (CacheItemInterface $item) use ($state) { + [$this->time, $this->index, $this->from, $time, $from] = $this->cache->get($this->name, static function (CacheItemInterface $item) use ($state) { $item->expiresAfter(self::CACHE_EXPIRY); return $state; - }) + [2 => $now]; + }) + [2 => $now, 3 => null, 4 => null]; + + if ($time && $from) { + $this->time = $time->setTimezone($this->time->getTimezone()); + $this->from = $from->setTimezone($this->from->getTimezone()); + } + $this->save($this->time, $this->index); } elseif ($this->reset) { $this->reset = false; @@ -86,18 +95,23 @@ $this->from ??= $time; $from = $this->from; + // A serialized date can come back one hour off when clocks go back, so the UTC copies keep the exact times. + // Older versions read only the first three elements. + $utc = new \DateTimeZone('UTC'); + $state = [$time, $index, $from, $time->setTimezone($utc), $from->setTimezone($utc)]; + if (!$this->cache instanceof CacheItemPoolInterface) { - $this->cache?->get($this->name, static function (CacheItemInterface $item) use ($time, $index, $from) { + $this->cache?->get($this->name, static function (CacheItemInterface $item) use ($state) { $item->expiresAfter(self::CACHE_EXPIRY); - return [$time, $index, $from]; + return $state; }, \INF); return; } $item = $this->cache->getItem($this->name); - $item->set([$time, $index, $from]); + $item->set($state); $item->expiresAfter(self::CACHE_EXPIRY); // Cache pools report backend failures only through the return value of save(). Going on would @@ -120,8 +134,8 @@ if (!$nextTime) { $this->lock->release(); - } elseif ($remaining = $this->lock->getRemainingLifetime()) { - // the lock might have expired during a long run; stores reject negative TTLs and some reject TTLs below one second + } elseif (0 < $remaining = $this->lock->getRemainingLifetime()) { + // an expired lock might be held by another worker now; some stores reject TTLs below one second if (1 <= $ttl = (float) $nextTime->format('U.u') - (float) $now->format('U.u') + $remaining) { $this->lock->refresh($ttl); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Generator/MessageGenerator.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Generator/MessageGenerator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Generator/MessageGenerator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Generator/MessageGenerator.php 2026-11-25 09:18:34.000000000 +0000 @@ -24,6 +24,8 @@ private ?Schedule $schedule = null; private TriggerHeap $triggerHeap; private bool $heapInitialized = false; + /** @var array<string, \DateTimeImmutable|null> */ + private array $addedAt = []; private ?\DateTimeImmutable $waitUntil; public function __construct( @@ -56,9 +58,11 @@ } $startTime = $checkpoint->from(); - $lastTime = $checkpoint->time(); + // the checkpoint has the timezone of the last run, and triggers without one use the timezone of the date they get + $lastTime = $checkpoint->time()->setTimezone($now->getTimezone()); $lastIndex = $checkpoint->index(); - $heap = $this->heap($lastTime, $startTime, $lastIndex); + $heap = $this->heap($lastTime, $startTime, $lastIndex, $now); + $lock = $this->getSchedule()->getLock(); while (!$heap->isEmpty() && $heap->top()[0] <= $now) { /** @var \DateTimeImmutable $time */ @@ -86,12 +90,22 @@ if ($yield) { $context = new MessageContext($this->name, $id, $trigger, $time, $nextTime); + $lockLost = false; try { foreach ($recurringMessage->getMessages($context) as $message) { yield $context => $message; } } finally { - $checkpoint->save($time, $index); + // when the lock expired during the run and another worker acquired it, that worker continues from the checkpoint + $lockLost = $lock?->isExpired() && !$checkpoint->acquire($now); + + if (!$lockLost) { + $checkpoint->save($time, $index); + } + } + + if ($lockLost) { + return; } } } @@ -106,7 +120,7 @@ return $this->schedule ??= $this->scheduleProvider->getSchedule(); } - private function heap(\DateTimeImmutable $time, \DateTimeImmutable $startTime, int $lastIndex): TriggerHeap + private function heap(\DateTimeImmutable $time, \DateTimeImmutable $startTime, int $lastIndex, \DateTimeImmutable $now): TriggerHeap { if (isset($this->triggerHeap) && $this->triggerHeap->time <= $time) { return $this->triggerHeap; @@ -122,23 +136,31 @@ // un-processed remainder through. Subsequent rebuilds happen after a normal // yield-then-advance cycle (not after a partial yield), so re-probing $time // would re-emit entries that are already advanced past. - $probeTime = !$this->heapInitialized && $lastIndex >= 0 ? $time->modify('-1 microsecond') : $time; + $probeTime = !$this->heapInitialized && $lastIndex >= 0 ? $time->setTimezone(new \DateTimeZone('UTC'))->modify('-1 microsecond')->setTimezone($time->getTimezone()) : $time; + $rebuilt = $this->heapInitialized; $this->heapInitialized = true; + $addedAt = []; foreach ($this->getSchedule()->getRecurringMessages() as $index => $recurringMessage) { $trigger = $recurringMessage->getTrigger(); + $id = $recurringMessage->getId(); if ($trigger instanceof StatefulTriggerInterface) { $trigger->continue($startTime); } - if (!$nextTime = $trigger->getNextRunDate($probeTime)) { + // a message added to a running schedule starts from the time it was added, its earlier runs were never due + $added = $addedAt[$id] = $rebuilt ? (\array_key_exists($id, $this->addedAt) ? $this->addedAt[$id] : $now) : null; + + if (!$nextTime = $trigger->getNextRunDate($added && $added > $probeTime ? $added : $probeTime)) { continue; } $heap->insert([$nextTime, $index, $recurringMessage]); } + $this->addedAt = $addedAt; + return $this->triggerHeap = $heap; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/RecurringMessage.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/RecurringMessage.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/RecurringMessage.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/RecurringMessage.php 2026-11-25 09:18:34.000000000 +0000 @@ -56,7 +56,8 @@ */ public static function cron(string $expression, object $message, \DateTimeZone|string|null $timezone = null): self { - if (!str_contains($expression, '#')) { + // a hashed part starts a field ("#", "#(0-2)", "#daily"...); "1#2" is the standard "nth weekday" syntax + if (!preg_match('/(?:^|\s)#/', $expression)) { return self::trigger(CronExpressionTrigger::fromSpec($expression, null, $timezone), $message); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/CheckpointTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/CheckpointTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/CheckpointTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/CheckpointTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -51,7 +51,7 @@ $this->assertTrue($checkpoint->acquire($now)); $this->assertEquals($now, $checkpoint->time()); $this->assertEquals(-1, $checkpoint->index()); - $this->assertEquals([$now, -1, $now], $cache->get('cache', static fn () => [])); + $this->assertEquals([$now, -1, $now, $now, $now], $cache->get('cache', static fn () => [])); } public function testWithStateLoadStateOnAcquiring() @@ -64,7 +64,7 @@ $this->assertTrue($checkpoint->acquire($startedAt = $now->modify('1 min'))); $this->assertEquals($now, $checkpoint->time()); $this->assertEquals(0, $checkpoint->index()); - $this->assertEquals([$now, 0, $startedAt], $cache->get('cache', static fn () => [])); + $this->assertEquals([$now, 0, $startedAt, $now, $startedAt], $cache->get('cache', static fn () => [])); } public function testWithLockInitStateOnFirstAcquiring() @@ -116,7 +116,7 @@ $this->assertSame($now, $checkpoint->time()); $this->assertSame(3, $checkpoint->index()); $this->assertSame($startedAt, $checkpoint->from()); - $this->assertEquals([$now, 3, $startedAt], $cache->get('cache', static fn () => [])); + $this->assertEquals([$now, 3, $startedAt, $now, $startedAt], $cache->get('cache', static fn () => [])); } public function testWithLockSave() @@ -144,7 +144,7 @@ $this->assertSame($now, $checkpoint->time()); $this->assertSame(3, $checkpoint->index()); - $this->assertEquals([$now, 3, $startTime], $cache->get('dummy', static fn () => [])); + $this->assertEquals([$now, 3, $startTime, $now, $startTime], $cache->get('dummy', static fn () => [])); } public function testWithCacheFullCycle() @@ -165,7 +165,7 @@ $this->assertSame(3, $lastIndex); $this->assertEquals($now, $checkpoint->time()); $this->assertSame(0, $checkpoint->index()); - $this->assertEquals([$now, 0, $now], $cache->get('cache', static fn () => [])); + $this->assertEquals([$now, 0, $now, $now, $now], $cache->get('cache', static fn () => [])); } public function testWithLockResetStateAfterLockedAcquiring() @@ -243,7 +243,7 @@ $this->assertEquals($savedTime, $checkpoint->time()); $this->assertSame(3, $checkpoint->index()); $this->assertEquals($startTime, $checkpoint->from()); - $this->assertEquals([$savedTime, 3, $startTime], $cache->get('cache', static fn () => [])); + $this->assertEquals([$savedTime, 3, $startTime, $savedTime, $startTime], $cache->get('cache', static fn () => [])); } public function testWithLockAndCacheResetStateWhenCacheIsClearedAfterLockedAcquiring() @@ -327,6 +327,21 @@ $checkpoint->release($now, $now->modify('60 sec')); } + public function testWithLockNoRefreshWhenLockExpiredBeforeADistantRun() + { + $lock = $this->createMock(LockInterface::class); + $lock->method('acquire')->willReturn(true); + $lock->method('getRemainingLifetime')->willReturn(-1.0); + $lock->expects($this->never())->method('refresh'); + $lock->expects($this->never())->method('release'); + + $checkpoint = new Checkpoint('dummy', $lock); + $now = new \DateTimeImmutable('2020-02-20 20:20:20Z'); + + $checkpoint->acquire($now->modify('-10 min')); + $checkpoint->release($now, $now->modify('1 hour')); + } + public function testWithLockNoRefreshWhenComputedTtlIsBelowOneSecond() { $lock = $this->createMock(LockInterface::class); @@ -376,4 +391,40 @@ $expiry = $cache->getItem('cache')->getMetadata()[ItemInterface::METADATA_EXPIRY] ?? null; $this->assertGreaterThan(time() + 365 * 86400, $expiry); } + + public function testWithCacheKeepTimesThatHappenTwiceWhenClocksGoBack() + { + // 01:30 EST in New York and 02:30 CEST in Paris: these wall-clock times happen twice on those days + foreach (['America/New_York' => '2026-11-01 06:30:00', 'Europe/Paris' => '2026-10-25 00:30:00'] as $timezone => $utcTime) { + $time = (new \DateTimeImmutable($utcTime, new \DateTimeZone('UTC')))->setTimezone(new \DateTimeZone($timezone)); + $cache = new ArrayAdapter(); + (new Checkpoint('cache', new NoLock(), $cache))->acquire($time); + + $checkpoint = new Checkpoint('cache', new NoLock(), $cache); + $this->assertTrue($checkpoint->acquire($time)); + $this->assertSame($time->format('Y-m-d H:i:s T e'), $checkpoint->time()->format('Y-m-d H:i:s T e')); + $this->assertSame($time->format('Y-m-d H:i:s T e'), $checkpoint->from()->format('Y-m-d H:i:s T e')); + } + } + + public function testWithCacheStateIsCompatibleWithOlderVersions() + { + $cache = new ArrayAdapter(); + $time = new \DateTimeImmutable('2026-06-01 09:30:00', new \DateTimeZone('America/New_York')); + $from = new \DateTimeImmutable('2026-05-01 10:00:00', new \DateTimeZone('Europe/Paris')); + $cache->get('cache', static fn () => [$time, 3, $from], \INF); + + $checkpoint = new Checkpoint('cache', new NoLock(), $cache); + $this->assertTrue($checkpoint->acquire(new \DateTimeImmutable('2026-06-01 13:31:00Z'))); + $this->assertSame('2026-06-01 09:30:00 America/New_York', $checkpoint->time()->format('Y-m-d H:i:s e')); + $this->assertSame(3, $checkpoint->index()); + $this->assertSame('2026-05-01 10:00:00 Europe/Paris', $checkpoint->from()->format('Y-m-d H:i:s e')); + + // older versions read only the first three elements + $checkpoint->save(new \DateTimeImmutable('2026-06-01 10:30:00', new \DateTimeZone('America/New_York')), 0); + [$savedTime, $savedIndex, $savedFrom] = $cache->get('cache', static fn () => []); + $this->assertSame('2026-06-01 10:30:00 America/New_York', $savedTime->format('Y-m-d H:i:s e')); + $this->assertSame(0, $savedIndex); + $this->assertSame('2026-05-01 10:00:00 Europe/Paris', $savedFrom->format('Y-m-d H:i:s e')); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Generator/MessageGeneratorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,6 +16,9 @@ use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\CacheItem; use Symfony\Component\Clock\MockClock; +use Symfony\Component\Lock\Key; +use Symfony\Component\Lock\Lock; +use Symfony\Component\Lock\Store\InMemoryStore; use Symfony\Component\Scheduler\Exception\LogicException; use Symfony\Component\Scheduler\Exception\RuntimeException; use Symfony\Component\Scheduler\Generator\Checkpoint; @@ -182,6 +185,61 @@ $this->assertEquals(self::makeDateTime('22:16:00'), $context->nextTriggerAt); } + public function testRunsDueAtTheSameTimeAreLeftToTheWorkerThatTookTheExpiredLock() + { + $clock = new MockClock(self::makeDateTime('22:12:00')); + $first = (object) ['id' => 'first']; + $second = (object) ['id' => 'second']; + $cache = new ArrayAdapter(); + $store = new InMemoryStore(); + $createGenerator = static fn (Key $key) => new MessageGenerator((new Schedule())->add(RecurringMessage::every('1 minute', $first), RecurringMessage::every('1 minute', $second))->lock(new Lock($key, $store))->stateful($cache), 'dummy', $clock); + + $generator1 = $createGenerator($key1 = new Key('scheduler')); + $generator2 = $createGenerator(new Key('scheduler')); + $this->assertSame([], iterator_to_array($generator1->getMessages(), false)); + + $clock->sleep(60); + $messages = $generator1->getMessages(); + $this->assertSame($first, $messages->current()); + + // the lock of the first worker expires while it handles the first message + $store->delete($key1); + $key1->reduceLifetime(0); + + $this->assertSame([$first, $second], iterator_to_array($generator2->getMessages(), false)); + + $messages->next(); + $this->assertNull($messages->current()); + + // the second worker restarts before the next run + $generator2 = null; + $clock->sleep(30); + $this->assertSame([], iterator_to_array($createGenerator(new Key('scheduler'))->getMessages(), false)); + } + + public function testRunIsSavedWhenNoOtherWorkerTookTheExpiredLock() + { + $clock = new MockClock(self::makeDateTime('22:12:00')); + $first = (object) ['id' => 'first']; + $second = (object) ['id' => 'second']; + $cache = new ArrayAdapter(); + $store = new InMemoryStore(); + $createGenerator = static fn (Key $key) => new MessageGenerator((new Schedule())->add(RecurringMessage::every('1 minute', $first), RecurringMessage::every('1 minute', $second))->lock(new Lock($key, $store))->stateful($cache), 'dummy', $clock); + + $generator = $createGenerator($key = new Key('scheduler')); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->sleep(60); + $messages = $generator->getMessages(); + $this->assertSame($first, $messages->current()); + + // the lock expires while the worker handles the first message, then the worker stops and restarts + $key->reduceLifetime(0); + $generator = $messages = null; + + $this->assertSame([$second], iterator_to_array($createGenerator(new Key('scheduler'))->getMessages(), false)); + } + public function testCheckpointSavedInBrokenLoop() { $clock = new MockClock(self::makeDateTime('22:12:00')); @@ -371,6 +429,93 @@ $this->assertSame([$message], iterator_to_array($generator->getMessages(), false)); } + public function testCronWithoutTimezoneKeepsTheClockTimezoneAfterARestart() + { + $clock = new MockClock('2026-11-09 00:00:00', 'UTC'); + $cache = new ArrayAdapter(); + $nightly = (object) ['id' => 'nightly']; + $newYork = (object) ['id' => 'new_york']; + $schedule = (new Schedule())->add(RecurringMessage::cron('0 2 * * *', $nightly), RecurringMessage::cron('0 9 * * *', $newYork, 'America/New_York'))->stateful($cache); + + $generator = new MessageGenerator($schedule, 'dummy', $clock); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + $clock->modify('2026-11-09 02:00:30'); + $this->assertSame([$nightly], iterator_to_array($generator->getMessages(), false)); + $clock->modify('2026-11-09 14:00:30'); + $this->assertSame([$newYork], iterator_to_array($generator->getMessages(), false)); + + $generator = new MessageGenerator($schedule, 'dummy', $clock); + $clock->modify('2026-11-10 02:00:30'); + $this->assertSame([$nightly], iterator_to_array($generator->getMessages(), false)); + } + + public function testMessageAddedAtRuntimeStartsFromNow() + { + $clock = new MockClock('2026-11-09 08:00:00', 'UTC'); + $daily = (object) ['id' => 'daily']; + $everyFiveMinutes = (object) ['id' => 'every_five_minutes']; + $schedule = (new Schedule())->add(RecurringMessage::cron('0 0 * * *', $daily)); + + $generator = new MessageGenerator($schedule, 'dummy', $clock); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:00:30'); + $schedule->add(RecurringMessage::cron('*/5 * * * *', $everyFiveMinutes)); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:05:30'); + $this->assertSame([$everyFiveMinutes], iterator_to_array($generator->getMessages(), false)); + } + + public function testMessageAddedAtRuntimeStillStartsFromWhenItWasAddedAfterTheScheduleChangesAgain() + { + $clock = new MockClock('2026-11-09 08:00:00', 'UTC'); + $daily = (object) ['id' => 'daily']; + $everyFiveMinutes = (object) ['id' => 'every_five_minutes']; + $hourly = (object) ['id' => 'hourly']; + $schedule = (new Schedule())->add(RecurringMessage::cron('0 0 * * *', $daily)); + + $generator = new MessageGenerator($schedule, 'dummy', $clock); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:00:30'); + $schedule->add(RecurringMessage::cron('*/5 * * * *', $everyFiveMinutes)); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:02:30'); + $schedule->add(RecurringMessage::cron('0 * * * *', $hourly)); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:05:30'); + $this->assertSame([$everyFiveMinutes], iterator_to_array($generator->getMessages(), false)); + } + + public function testMessageAddedAtRuntimeDoesNotRunAgainWhenTheScheduleIsRebuiltInAnotherOrder() + { + $clock = new MockClock('2026-11-09 08:00:00', 'UTC'); + $daily = RecurringMessage::cron('0 0 * * *', (object) ['id' => 'daily']); + $hourly = RecurringMessage::cron('0 * * * *', (object) ['id' => 'hourly']); + $everyFiveMinutes = RecurringMessage::cron('*/5 * * * *', $message = (object) ['id' => 'every_five_minutes']); + $schedule = (new Schedule())->add($daily); + + $generator = new MessageGenerator($schedule, 'dummy', $clock); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:00:30'); + $schedule->add($everyFiveMinutes); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:05:30'); + $this->assertSame([$message], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:06:30'); + $schedule->clear()->add($hourly, $daily, $everyFiveMinutes); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + + $clock->modify('2026-11-09 12:10:30'); + $this->assertSame([$message], iterator_to_array($generator->getMessages(), false)); + } + public function testThrowsWhenTriggerDoesNotMoveTheRunDateForward() { $clock = new MockClock(self::makeDateTime('22:12:00')); @@ -395,6 +540,23 @@ iterator_to_array($scheduler->getMessages(), false); } + public function testRestartAfterARunWhenTheClocksGoForward() + { + $clock = new MockClock('2027-03-28 01:50:00', 'Europe/Paris'); + $nightly = (object) ['id' => 'nightly']; + $later = (object) ['id' => 'later']; + $schedule = (new Schedule())->add(RecurringMessage::cron('0 3 * * *', $nightly), RecurringMessage::cron('30 3 * * *', $later))->stateful(new ArrayAdapter()); + + $generator = new MessageGenerator($schedule, 'dummy', $clock); + $this->assertSame([], iterator_to_array($generator->getMessages(), false)); + $clock->sleep(630); // 03:00:30 CEST, 02:00 does not exist on that day + $this->assertSame([$nightly], iterator_to_array($generator->getMessages(), false)); + + $generator = new MessageGenerator($schedule, 'dummy', $clock); + $clock->sleep(1800); + $this->assertSame([$later], iterator_to_array($generator->getMessages(), false)); + } + public static function messagesProvider(): \Generator { $first = (object) ['id' => 'first']; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/RecurringMessageTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/RecurringMessageTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/RecurringMessageTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/RecurringMessageTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -40,6 +40,11 @@ RecurringMessage::cron('#midnight', new \stdClass()); } + public function testNthWeekdayCronDoesNotRequireAStringableMessage() + { + $this->assertSame('0 9 * * 1#2', (string) RecurringMessage::cron('0 9 * * 1#2', new \stdClass())->getTrigger()); + } + public function testHashedCronExpressionIsBuiltFromTheMessageInsideTheEnvelope() { $message = new DummyStringableMessage(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/CronExpressionTriggerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/CronExpressionTriggerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/CronExpressionTriggerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/CronExpressionTriggerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Random\Randomizer; +use Symfony\Component\Scheduler\Exception\LogicException; use Symfony\Component\Scheduler\Trigger\CronExpressionTrigger; class CronExpressionTriggerTest extends TestCase @@ -97,6 +98,21 @@ $this->assertSame('0 0 * * *', (string) CronExpressionTrigger::fromSpec('@daily')); } + public function testNthWeekdayIsNotAHashedExpression() + { + $trigger = CronExpressionTrigger::fromSpec('0 9 * * 1#2'); + + $this->assertSame('0 9 * * 1#2', (string) $trigger); + $this->assertEquals(new \DateTimeImmutable('2024-01-08 09:00:00'), $trigger->getNextRunDate(new \DateTimeImmutable('2024-01-01 10:00:00'))); + } + + public function testHashedExpressionWithNthWeekdayRequiresAContext() + { + $this->expectException(LogicException::class); + + CronExpressionTrigger::fromSpec('#(0-2) 9 * * 1#2'); + } + public function testDefaultTimezone() { $now = new \DateTimeImmutable('Europe/Paris'); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/PeriodicalTriggerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/PeriodicalTriggerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/PeriodicalTriggerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Tests/Trigger/PeriodicalTriggerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -27,11 +27,18 @@ $this->assertSame('2922-02-23 13:34:00+01:00', $trigger->getNextRunDate($run)->format('Y-m-d H:i:sP')); - if ($optimizable) { - // test that we are using the fast algorithm for short period of time - $p = new \ReflectionProperty($trigger, 'intervalInSeconds'); - $this->assertNotSame(0, $p->getValue($trigger)); - } + // test that we are using the fast algorithm for short period of time + $p = new \ReflectionProperty($trigger, 'intervalInSeconds'); + $this->assertSame($optimizable, 0.0 !== $p->getValue($trigger)); + } + + public function testIsoIntervalWithDaysOrMonthsFollowsTheCalendar() + { + $from = new \DateTimeImmutable('2026-03-28 09:00:00', new \DateTimeZone('Europe/Paris')); + $this->assertSame('2026-03-29 09:00:00+02:00', (new PeriodicalTrigger('P1D', $from))->getNextRunDate($from)->format('Y-m-d H:i:sP')); + + $from = new \DateTimeImmutable('2026-02-01 09:00:00', new \DateTimeZone('Europe/Paris')); + $this->assertSame('2026-03-01 09:00:00+01:00', (new PeriodicalTrigger('P1M', $from))->getNextRunDate($from)->format('Y-m-d H:i:sP')); } public static function provideForConstructor(): iterable @@ -76,6 +83,8 @@ yield [-3600, 'The "$interval" argument must be greater than zero.']; yield ['0', 'The "$interval" argument must be greater than zero.']; yield [0, 'The "$interval" argument must be greater than zero.']; + yield [\NAN, 'The "$interval" argument must be greater than zero.']; + yield [\INF, 'The "$interval" argument must be greater than zero.']; yield ['PT0S', 'The "$interval" argument must be greater than zero.']; yield ['P0D', 'The "$interval" argument must be greater than zero.']; yield ['0 seconds', 'The "$interval" argument must be greater than zero.']; @@ -98,6 +107,7 @@ yield ['every 20 seconds', new PeriodicalTrigger(20, $from, $until)]; yield ['every 20 seconds', new PeriodicalTrigger('20', $from, $until)]; yield ['every 2 seconds (PT2S)', new PeriodicalTrigger('PT2S', $from, $until)]; + yield ['every P1D', new PeriodicalTrigger('P1D', $from, $until)]; yield ['every 20 seconds', new PeriodicalTrigger('20 seconds', $from, $until)]; yield ['every 4 minutes 20 seconds', new PeriodicalTrigger('4 minutes 20 seconds', $from, $until)]; yield ['every 2 hours', new PeriodicalTrigger('2 hours', $from, $until)]; @@ -258,6 +268,22 @@ ]; } + public function testFloatInterval() + { + $from = new \DateTimeImmutable('2026-11-09 10:00:00', new \DateTimeZone('UTC')); + + $trigger = new PeriodicalTrigger(1.5, $from); + $this->assertSame('every 1.5 seconds', (string) $trigger); + $this->assertSame('10:00:01.500000', $trigger->getNextRunDate($from)->format('H:i:s.u')); + + $trigger = new PeriodicalTrigger(0.1, $from); + $run = $from; + for ($i = 0; $i < 10; ++$i) { + $run = $trigger->getNextRunDate($run); + } + $this->assertSame('10:00:01.000000', $run->format('H:i:s.u')); + } + private static function createTrigger(string|int|\DateInterval $interval): PeriodicalTrigger { return new PeriodicalTrigger($interval, '2023-03-19 13:45', '2023-06-19'); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Trigger/CronExpressionTrigger.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Trigger/CronExpressionTrigger.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Trigger/CronExpressionTrigger.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Trigger/CronExpressionTrigger.php 2026-11-25 09:18:34.000000000 +0000 @@ -64,7 +64,8 @@ throw new LogicException(\sprintf('You cannot use "%s" as the "cron expression" package is not installed. Try running "composer require dragonmantank/cron-expression".', __CLASS__)); } - if (!str_contains($expression, '#')) { + // a hashed part starts a field ("#", "#(0-2)", "#daily"...); "1#2" is the standard "nth weekday" syntax + if (!preg_match('/(?:^|\s)#/', $expression)) { return new self(new CronExpression($expression), $timezone); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Trigger/PeriodicalTrigger.php symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Trigger/PeriodicalTrigger.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Scheduler/Trigger/PeriodicalTrigger.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Scheduler/Trigger/PeriodicalTrigger.php 2026-11-25 09:18:34.000000000 +0000 @@ -31,19 +31,28 @@ $this->until = \is_string($until) ? new \DateTimeImmutable($until) : $until; if (\is_int($interval) || \is_float($interval) || \is_string($interval) && ctype_digit($interval)) { - if (0 >= (int) $interval) { + if (!is_finite($seconds = (float) $interval) || 0 >= $seconds) { throw new InvalidArgumentException('The "$interval" argument must be greater than zero.'); } - $this->intervalInSeconds = (int) $interval; - $this->description = \sprintf('every %d seconds', $this->intervalInSeconds); + $this->intervalInSeconds = $seconds; + $this->description = \sprintf('every %s seconds', $seconds); return; } try { if (\is_string($interval) && 'P' === ($interval[0] ?? '')) { - $this->intervalInSeconds = $this->calcInterval(new \DateInterval($interval)); + $i = new \DateInterval($interval); + + if (!$this->canBeConvertedToSeconds($i)) { + $this->interval = $i; + $this->description = \sprintf('every %s', $interval); + + return; + } + + $this->intervalInSeconds = $this->calcInterval($i); $this->description = \sprintf('every %d seconds (%s)', $this->intervalInSeconds, $interval); return; @@ -103,6 +112,12 @@ $nextRunTimestamp = \sprintf('%.6F', ($recurrencesPassed + 1) * $this->intervalInSeconds + $from); $nextRun = \DateTimeImmutable::createFromFormat('U.u', $nextRunTimestamp)->setTimezone($fromDate->getTimezone()); + if ($nextRun <= $run) { + // floor() can be one too low because of rounding errors, for example with an interval of 0.1 seconds + $nextRunTimestamp = \sprintf('%.6F', ($recurrencesPassed + 2) * $this->intervalInSeconds + $from); + $nextRun = \DateTimeImmutable::createFromFormat('U.u', $nextRunTimestamp)->setTimezone($fromDate->getTimezone()); + } + if ($this->from > $nextRun) { return $this->from; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Authorization/AccessDecisionManager.php 2026-11-25 09:18:34.000000000 +0000 @@ -14,6 +14,7 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Strategy\AccessDecisionStrategyInterface; use Symfony\Component\Security\Core\Authorization\Strategy\AffirmativeStrategy; +use Symfony\Component\Security\Core\Authorization\Strategy\UnanimousStrategy; use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Exception\InvalidArgumentException; @@ -66,6 +67,15 @@ */ private function collectResults(TokenInterface $token, array $attributes, mixed $object): \Traversable { + // Voters are asked about each attribute separately so that the unanimous strategy denies access if any of them is denied + if (\count($attributes) > 1 && $this->strategy instanceof UnanimousStrategy) { + foreach ($attributes as $attribute) { + yield from $this->collectResults($token, [$attribute], $object); + } + + return; + } + foreach ($this->getVoters($attributes, $object) as $voter) { $result = $voter->vote($token, $object, $attributes); if (!\is_int($result) || !(self::VALID_VOTES[$result] ?? false)) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Authorization/TraceableAccessDecisionManager.php 2026-11-25 09:18:34.000000000 +0000 @@ -14,6 +14,7 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Strategy\AccessDecisionStrategyInterface; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; +use Symfony\Contracts\Service\ResetInterface; /** * Decorates the original AccessDecisionManager class to log information @@ -23,7 +24,7 @@ * * @internal */ -class TraceableAccessDecisionManager implements AccessDecisionManagerInterface +class TraceableAccessDecisionManager implements AccessDecisionManagerInterface, ResetInterface { private AccessDecisionManagerInterface $manager; private ?AccessDecisionStrategyInterface $strategy = null; @@ -106,4 +107,9 @@ { return $this->decisionLog; } + + public function reset(): void + { + $this->decisionLog = []; + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.ar.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.ar.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.ar.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.ar.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -4,19 +4,19 @@ <body> <trans-unit id="1"> <source>An authentication exception occurred.</source> - <target>حدث خطأ اثناء الدخول.</target> + <target>حدث خطأ أثناء المصادقة.</target> </trans-unit> <trans-unit id="2"> <source>Authentication credentials could not be found.</source> - <target>لم استطع العثور على معلومات الدخول.</target> + <target>تعذّر العثور على بيانات اعتماد المصادقة.</target> </trans-unit> <trans-unit id="3"> <source>Authentication request could not be processed due to a system problem.</source> - <target>لم يكتمل طلب الدخول نتيجه عطل فى النظام.</target> + <target>تعذّرت معالجة طلب المصادقة بسبب مشكلة في النظام.</target> </trans-unit> <trans-unit id="4"> <source>Invalid credentials.</source> - <target>معلومات الدخول خاطئة.</target> + <target>بيانات الاعتماد غير صالحة.</target> </trans-unit> <trans-unit id="5"> <source>Cookie has already been used by someone else.</source> @@ -24,7 +24,7 @@ </trans-unit> <trans-unit id="6"> <source>Not privileged to request the resource.</source> - <target>ليست لديك الصلاحيات الكافية لهذا الطلب.</target> + <target>ليست لديك الصلاحيات الكافية لطلب هذا المورد.</target> </trans-unit> <trans-unit id="7"> <source>Invalid CSRF token.</source> @@ -40,11 +40,11 @@ </trans-unit> <trans-unit id="11"> <source>No token could be found.</source> - <target>لم استطع العثور على الرمز.</target> + <target>تعذّر العثور على الرمز.</target> </trans-unit> <trans-unit id="12"> <source>Username could not be found.</source> - <target>لم استطع العثور على اسم الدخول.</target> + <target>تعذّر العثور على اسم المستخدم.</target> </trans-unit> <trans-unit id="13"> <source>Account has expired.</source> @@ -52,7 +52,7 @@ </trans-unit> <trans-unit id="14"> <source>Credentials have expired.</source> - <target>انتهت صلاحية معلومات الدخول.</target> + <target>انتهت صلاحية بيانات الاعتماد.</target> </trans-unit> <trans-unit id="15"> <source>Account is disabled.</source> @@ -60,7 +60,7 @@ </trans-unit> <trans-unit id="16"> <source>Account is locked.</source> - <target>الحساب مغلق.</target> + <target>الحساب مقفل.</target> </trans-unit> <trans-unit id="17"> <source>Too many failed login attempts, please try again later.</source> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.eu.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.eu.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.eu.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.eu.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -64,7 +64,7 @@ </trans-unit> <trans-unit id="17"> <source>Too many failed login attempts, please try again later.</source> - <target>Saioa hasteko saio huts gehiegi, saiatu berriro geroago.</target> + <target>Saioa hasteko saiakera huts gehiegi, saiatu berriro geroago.</target> </trans-unit> <trans-unit id="18"> <source>Invalid or expired login link.</source> @@ -72,11 +72,11 @@ </trans-unit> <trans-unit id="19"> <source>Too many failed login attempts, please try again in %minutes% minute.</source> - <target>Saioa hasteko huts gehiegi egin dira, saiatu berriro minutu %minutes% geroago.</target> + <target>Saioa hasteko huts gehiegi egin dira, saiatu berriro %minutes% minutu geroago.</target> </trans-unit> <trans-unit id="20"> <source>Too many failed login attempts, please try again in %minutes% minutes.</source> - <target state="needs-review-translation">Saioa hasteko saiakera huts gehiegi, saiatu berriro %minutes% minututan.</target> + <target>Saioa hasteko huts gehiegi egin dira, saiatu berriro %minutes% minutu geroago.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -44,7 +44,7 @@ </trans-unit> <trans-unit id="12"> <source>Username could not be found.</source> - <target>Nome de usuário não encontrado.</target> + <target>Nome de utilizador não encontrado.</target> </trans-unit> <trans-unit id="13"> <source>Account has expired.</source> @@ -64,19 +64,19 @@ </trans-unit> <trans-unit id="17"> <source>Too many failed login attempts, please try again later.</source> - <target>Muitas tentativas de login sem sucesso, por favor, tente mais tarde.</target> + <target>Demasiadas tentativas de início de sessão falhadas. Por favor, tente novamente mais tarde.</target> </trans-unit> <trans-unit id="18"> <source>Invalid or expired login link.</source> - <target>Ligação de login inválida ou expirada.</target> + <target>Ligação de início de sessão inválida ou expirada.</target> </trans-unit> <trans-unit id="19"> <source>Too many failed login attempts, please try again in %minutes% minute.</source> - <target>Muitas tentativas de login sem sucesso, por favor, tente novamente novamente em 1 minuto.</target> + <target>Demasiadas tentativas de início de sessão falhadas. Por favor, tente novamente dentro de %minutes% minuto.</target> </trans-unit> <trans-unit id="20"> <source>Too many failed login attempts, please try again in %minutes% minutes.</source> - <target>Muitas tentativas de login sem sucesso, por favor, tente novamente em %minutes% minutos.</target> + <target>Demasiadas tentativas de início de sessão falhadas. Por favor, tente novamente dentro de %minutes% minutos.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt_BR.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt_BR.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt_BR.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.pt_BR.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -4,7 +4,7 @@ <body> <trans-unit id="1"> <source>An authentication exception occurred.</source> - <target>Uma exceção ocorreu durante a autenticação.</target> + <target>Ocorreu uma exceção durante a autenticação.</target> </trans-unit> <trans-unit id="2"> <source>Authentication credentials could not be found.</source> @@ -60,7 +60,7 @@ </trans-unit> <trans-unit id="16"> <source>Account is locked.</source> - <target>A conta está travada.</target> + <target>A conta está bloqueada.</target> </trans-unit> <trans-unit id="17"> <source>Too many failed login attempts, please try again later.</source> @@ -72,11 +72,11 @@ </trans-unit> <trans-unit id="19"> <source>Too many failed login attempts, please try again in %minutes% minute.</source> - <target>Muitas tentativas de login inválidas, por favor, tente novamente em um minuto.</target> + <target>Muitas tentativas de login malsucedidas, por favor, tente novamente em um minuto.</target> </trans-unit> <trans-unit id="20"> <source>Too many failed login attempts, please try again in %minutes% minutes.</source> - <target>Muitas tentativas de login sem sucesso, por favor, tente novamente em %minutes% minutos.</target> + <target>Muitas tentativas de login malsucedidas, por favor, tente novamente em %minutes% minutos.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.tg.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.tg.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.tg.xlf 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.tg.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,83 @@ +<?xml version="1.0" encoding="utf-8"?> +<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2"> + <file source-language="en" target-language="tg" datatype="plaintext" original="file.ext"> + <body> + <trans-unit id="1"> + <source>An authentication exception occurred.</source> + <target>Ҳангоми санҷиши ҳаққоният хато рух дод.</target> + </trans-unit> + <trans-unit id="2"> + <source>Authentication credentials could not be found.</source> + <target>Маълумоти санҷиши ҳаққоният ёфт нашуд.</target> + </trans-unit> + <trans-unit id="3"> + <source>Authentication request could not be processed due to a system problem.</source> + <target>Дархости санҷиши ҳаққоният бо сабаби мушкилии система коркард нашуд.</target> + </trans-unit> + <trans-unit id="4"> + <source>Invalid credentials.</source> + <target>Маълумоти воридшавӣ нодуруст аст.</target> + </trans-unit> + <trans-unit id="5"> + <source>Cookie has already been used by someone else.</source> + <target>Cookie аллакай аз ҷониби каси дигар истифода шудааст.</target> + </trans-unit> + <trans-unit id="6"> + <source>Not privileged to request the resource.</source> + <target>Барои дархости ин манбаъ ҳуқуқ надоред.</target> + </trans-unit> + <trans-unit id="7"> + <source>Invalid CSRF token.</source> + <target>Токени CSRF нодуруст аст.</target> + </trans-unit> + <trans-unit id="9"> + <source>No authentication provider found to support the authentication token.</source> + <target>Провайдери санҷиши ҳаққоният, ки ин токенро дастгирӣ кунад, ёфт нашуд.</target> + </trans-unit> + <trans-unit id="10"> + <source>No session available, it either timed out or cookies are not enabled.</source> + <target>Ҷаласа дастрас нест: ё мӯҳлати он гузаштааст, ё cookies фаъол нестанд.</target> + </trans-unit> + <trans-unit id="11"> + <source>No token could be found.</source> + <target>Токен ёфт нашуд.</target> + </trans-unit> + <trans-unit id="12"> + <source>Username could not be found.</source> + <target>Номи истифодабаранда ёфт нашуд.</target> + </trans-unit> + <trans-unit id="13"> + <source>Account has expired.</source> + <target>Мӯҳлати амали ҳисоб ба охир расидааст.</target> + </trans-unit> + <trans-unit id="14"> + <source>Credentials have expired.</source> + <target>Мӯҳлати амали маълумоти воридшавӣ ба охир расидааст.</target> + </trans-unit> + <trans-unit id="15"> + <source>Account is disabled.</source> + <target>Ҳисоб ғайрифаъол карда шудааст.</target> + </trans-unit> + <trans-unit id="16"> + <source>Account is locked.</source> + <target>Ҳисоб баста шудааст.</target> + </trans-unit> + <trans-unit id="17"> + <source>Too many failed login attempts, please try again later.</source> + <target>Кӯшишҳои ноками воридшавӣ аз ҳад зиёданд. Лутфан баъдтар дубора кӯшиш кунед.</target> + </trans-unit> + <trans-unit id="18"> + <source>Invalid or expired login link.</source> + <target>Пайванди воридшавӣ нодуруст аст ё мӯҳлаташ гузаштааст.</target> + </trans-unit> + <trans-unit id="19"> + <source>Too many failed login attempts, please try again in %minutes% minute.</source> + <target>Кӯшишҳои ноками воридшавӣ аз ҳад зиёданд. Лутфан пас аз %minutes% дақиқа дубора кӯшиш кунед.</target> + </trans-unit> + <trans-unit id="20"> + <source>Too many failed login attempts, please try again in %minutes% minutes.</source> + <target>Кӯшишҳои ноками воридшавӣ аз ҳад зиёданд. Лутфан пас аз %minutes% дақиқа дубора кӯшиш кунед.</target> + </trans-unit> + </body> + </file> +</xliff> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.uk.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.uk.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.uk.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Resources/translations/security.uk.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -20,7 +20,7 @@ </trans-unit> <trans-unit id="5"> <source>Cookie has already been used by someone else.</source> - <target>Хтось інший вже використав цей сookie.</target> + <target>Хтось інший вже використав цей cookie.</target> </trans-unit> <trans-unit id="6"> <source>Not privileged to request the resource.</source> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -17,7 +17,12 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; use Symfony\Component\Security\Core\Authorization\Strategy\AccessDecisionStrategyInterface; +use Symfony\Component\Security\Core\Authorization\Strategy\AffirmativeStrategy; +use Symfony\Component\Security\Core\Authorization\Strategy\ConsensusStrategy; +use Symfony\Component\Security\Core\Authorization\Strategy\PriorityStrategy; +use Symfony\Component\Security\Core\Authorization\Strategy\UnanimousStrategy; use Symfony\Component\Security\Core\Authorization\Voter\CacheableVoterInterface; +use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; class AccessDecisionManagerTest extends TestCase @@ -236,6 +241,78 @@ $this->assertTrue($manager->decide($token, ['foo', 1337], 'bar', true)); } + /** + * @dataProvider provideMultipleAttributesWithRoleVoter + */ + public function testMultipleAttributesWithRoleVoter(AccessDecisionStrategyInterface $strategy, array $roles, bool $expected) + { + $token = $this->createStub(TokenInterface::class); + $token->method('getRoleNames')->willReturn($roles); + + $manager = new AccessDecisionManager([new RoleVoter()], $strategy); + + $this->assertSame($expected, $manager->decide($token, ['ROLE_ADMIN', 'ROLE_AUDITOR'], null, true)); + } + + public static function provideMultipleAttributesWithRoleVoter(): iterable + { + yield [new UnanimousStrategy(), ['ROLE_ADMIN', 'ROLE_AUDITOR'], true]; + yield [new UnanimousStrategy(), ['ROLE_ADMIN'], false]; + yield [new UnanimousStrategy(), ['ROLE_AUDITOR'], false]; + yield [new UnanimousStrategy(), ['ROLE_USER'], false]; + + foreach ([new AffirmativeStrategy(), new ConsensusStrategy(), new PriorityStrategy()] as $strategy) { + yield [$strategy, ['ROLE_ADMIN', 'ROLE_AUDITOR'], true]; + yield [$strategy, ['ROLE_ADMIN'], true]; + yield [$strategy, ['ROLE_AUDITOR'], true]; + yield [$strategy, ['ROLE_USER'], false]; + } + } + + public function testUnanimousStrategyAsksVotersAboutEachAttribute() + { + $token = $this->createStub(TokenInterface::class); + $calls = []; + + $voter = $this->createMock(VoterInterface::class); + $voter + ->expects($this->exactly(2)) + ->method('vote') + ->willReturnCallback(static function (TokenInterface $token, $subject, array $attributes) use (&$calls) { + $calls[] = $attributes; + + return ['foo'] === $attributes ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_ABSTAIN; + }); + + $manager = new AccessDecisionManager([$voter], new UnanimousStrategy()); + + $this->assertTrue($manager->decide($token, ['foo', 'bar'], 'subject', true)); + $this->assertSame([['foo'], ['bar']], $calls); + } + + public function testUnanimousStrategyWithCacheableVoters() + { + $token = $this->createStub(TokenInterface::class); + $voter = $this->createMock(CacheableVoterInterface::class); + $voter + ->expects($this->exactly(2)) + ->method('supportsAttribute') + ->willReturnMap([['foo', true], ['bar', false]]); + $voter + ->expects($this->once()) + ->method('supportsType') + ->with('string') + ->willReturn(true); + $voter + ->expects($this->once()) + ->method('vote') + ->with($token, 'bar', ['foo']) + ->willReturn(VoterInterface::ACCESS_GRANTED); + + $manager = new AccessDecisionManager([$voter], new UnanimousStrategy()); + $this->assertTrue($manager->decide($token, ['foo', 'bar'], 'bar', true)); + } + protected static function getVoters($grants, $denies, $abstains): array { $voters = []; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Core/Tests/Authorization/TraceableAccessDecisionManagerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -16,7 +16,9 @@ use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\AccessDecisionManager; use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; +use Symfony\Component\Security\Core\Authorization\Strategy\UnanimousStrategy; use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager; +use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; use Symfony\Component\Security\Core\Tests\Fixtures\DummyVoter; @@ -265,4 +267,58 @@ $this->assertEquals('-', $adm->getStrategy()); } + + public function testResetClearsTheDecisionLog() + { + $voter = $this->createStub(VoterInterface::class); + $sut = new TraceableAccessDecisionManager(new AccessDecisionManager([$voter])); + $voter->method('vote')->willReturnCallback(static function (TokenInterface $token, $subject, array $attributes) use ($sut, $voter) { + $sut->addVoterVote($voter, $attributes, VoterInterface::ACCESS_GRANTED); + + return VoterInterface::ACCESS_GRANTED; + }); + + $token = new NullToken(); + $sut->decide($token, ['attr1']); + $sut->reset(); + $sut->decide($token, ['attr2']); + + $this->assertSame([['attr2']], array_column($sut->getDecisionLog(), 'attributes')); + $this->assertSame('affirmative', $sut->getStrategy()); + $this->assertContains($voter, $sut->getVoters()); + } + + public function testUnanimousStrategyLogsVotesForEachAttribute() + { + $voter = $this->createMock(VoterInterface::class); + $sut = new TraceableAccessDecisionManager(new AccessDecisionManager([$voter], new UnanimousStrategy())); + + $roleVoter = new RoleVoter(); + $voter + ->expects($this->exactly(2)) + ->method('vote') + ->willReturnCallback(static function (TokenInterface $token, $subject, array $attributes) use ($sut, $voter, $roleVoter) { + $vote = $roleVoter->vote($token, $subject, $attributes); + $sut->addVoterVote($voter, $attributes, $vote); + + return $vote; + }); + + $token = $this->createStub(TokenInterface::class); + $token->method('getRoleNames')->willReturn(['ROLE_ADMIN']); + + $this->assertFalse($sut->decide($token, ['ROLE_ADMIN', 'ROLE_AUDITOR'], null, true)); + + $this->assertEquals([ + [ + 'attributes' => ['ROLE_ADMIN', 'ROLE_AUDITOR'], + 'object' => null, + 'voterDetails' => [ + ['voter' => $voter, 'attributes' => ['ROLE_ADMIN'], 'vote' => VoterInterface::ACCESS_GRANTED], + ['voter' => $voter, 'attributes' => ['ROLE_AUDITOR'], 'vote' => VoterInterface::ACCESS_DENIED], + ], + 'result' => false, + ], + ], $sut->getDecisionLog()); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Authenticator/RemoteUserAuthenticator.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Authenticator/RemoteUserAuthenticator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Authenticator/RemoteUserAuthenticator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Authenticator/RemoteUserAuthenticator.php 2026-11-25 09:18:34.000000000 +0000 @@ -45,6 +45,10 @@ throw new BadCredentialsException(\sprintf('User key was not found: "%s".', $this->userKey)); } - return $request->server->get($this->userKey) ?: null; + if ('' === $username = $request->server->get($this->userKey)) { + throw new BadCredentialsException(\sprintf('User key is empty: "%s".', $this->userKey)); + } + + return $username; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Authenticator/X509Authenticator.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Authenticator/X509Authenticator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Authenticator/X509Authenticator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Authenticator/X509Authenticator.php 2026-11-25 09:18:34.000000000 +0000 @@ -59,12 +59,23 @@ private function extractUsernameFromDn(string $dn): ?string { - $pattern = 'emailAddress' === $this->credentialUserIdentifier - ? '#^\s*(?:emailAddress|1\.2\.840\.113549\.1\.9\.1)=([^,/@]++@[^,/]++)$#D' - : '#^\s*'.preg_quote($this->credentialUserIdentifier, '#').'=([^,/]++)$#D'; + if ('emailAddress' === $this->credentialUserIdentifier) { + $attribute = '(?:emailAddress|1\.2\.840\.113549\.1\.9\.1)'; + $value = '[^,/@]++@[^,/]++'; + } else { + $attribute = preg_quote($this->credentialUserIdentifier, '#'); + $value = '[^,/]++'; + } + + $rdns = self::splitDn($dn); + + // In the legacy format, some servers don't escape slashes inside values, so a DN that contains the attribute twice can't be trusted + if (str_starts_with($dn, '/') && 1 < preg_match_all('#'.$attribute.'=#', implode(',', $rdns))) { + return null; + } - foreach (self::splitDn($dn) as $rdn) { - if (preg_match($pattern, $rdn, $matches)) { + foreach ($rdns as $rdn) { + if (preg_match('#^\s*'.$attribute.'=('.$value.')$#D', $rdn, $matches)) { return trim($matches[1]); } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/EventListener/LoginThrottlingListener.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/EventListener/LoginThrottlingListener.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/EventListener/LoginThrottlingListener.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/EventListener/LoginThrottlingListener.php 2026-11-25 09:18:34.000000000 +0000 @@ -15,6 +15,7 @@ use Symfony\Component\HttpFoundation\RateLimiter\PeekableRequestRateLimiterInterface; use Symfony\Component\HttpFoundation\RateLimiter\RequestRateLimiterInterface; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\RateLimiter\RateLimit; use Symfony\Component\Security\Core\Exception\TooManyLoginAttemptsAuthenticationException; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; use Symfony\Component\Security\Http\Event\CheckPassportEvent; @@ -28,14 +29,21 @@ final class LoginThrottlingListener implements EventSubscriberInterface { private const UNTOUCHED_LIMITER_ATTRIBUTE = '_security_login_throttling_untouched'; + private const CONSUMED_ATTRIBUTE = '_security_login_throttling_consumed'; private RequestStack $requestStack; private RequestRateLimiterInterface $limiter; + private bool $stateless; - public function __construct(RequestStack $requestStack, RequestRateLimiterInterface $limiter) + /** + * @param bool $stateless Whether the firewall is stateless. On stateless firewalls, a successful login + * in an untouched window doesn't write to the storage of the limiter. + */ + public function __construct(RequestStack $requestStack, RequestRateLimiterInterface $limiter, bool $stateless = true) { $this->requestStack = $requestStack; $this->limiter = $limiter; + $this->stateless = $stateless; } public function checkPassport(CheckPassportEvent $event): void @@ -48,28 +56,38 @@ $request = $this->requestStack->getMainRequest(); $request->attributes->set(SecurityRequestAttributes::LAST_USERNAME, $passport->getBadge(UserBadge::class)->getUserIdentifier()); - if ($this->limiter instanceof PeekableRequestRateLimiterInterface) { + $untouched = false; + + if ($this->stateless && $this->limiter instanceof PeekableRequestRateLimiterInterface) { $limit = $this->limiter->peek($request); // Checking isAccepted here is not enough as peek consumes 0 token, it will // be accepted even if there are 0 tokens remaining to be consumed. We check both // anyway for safety in case third party implementations behave unexpectedly. if (!$limit->isAccepted() || 0 === $limit->getRemainingTokens()) { - throw new TooManyLoginAttemptsAuthenticationException(ceil(($limit->getRetryAfter()->getTimestamp() - time()) / 60)); + throw new TooManyLoginAttemptsAuthenticationException($this->getThreshold($limit)); } - // Remember an untouched window, a successful login then has nothing to reset. - $request->attributes->set(self::UNTOUCHED_LIMITER_ATTRIBUTE, $limit->getRemainingTokens() === $limit->getLimit()); - } else { - $limit = $this->limiter->consume($request); - if (!$limit->isAccepted()) { - throw new TooManyLoginAttemptsAuthenticationException(ceil(($limit->getRetryAfter()->getTimestamp() - time()) / 60)); - } + $untouched = $limit->getRemainingTokens() === $limit->getLimit(); + } + + // Remember an untouched window, a successful login then has nothing to reset. + $request->attributes->set(self::UNTOUCHED_LIMITER_ATTRIBUTE, $untouched); + $request->attributes->set(self::CONSUMED_ATTRIBUTE, !$untouched); + + if ($untouched) { + return; + } + + // consume before checking the credentials, so that concurrent attempts are counted too + $limit = $this->limiter->consume($request); + if (!$limit->isAccepted()) { + throw new TooManyLoginAttemptsAuthenticationException($this->getThreshold($limit)); } } public function onSuccessfulLogin(LoginSuccessEvent $event): void { - if ($this->limiter instanceof PeekableRequestRateLimiterInterface && $event->getRequest()->attributes->get(self::UNTOUCHED_LIMITER_ATTRIBUTE, false)) { + if ($event->getRequest()->attributes->get(self::UNTOUCHED_LIMITER_ATTRIBUTE, false)) { return; } @@ -78,7 +96,7 @@ public function onFailedLogin(LoginFailureEvent $event): void { - if ($this->limiter instanceof PeekableRequestRateLimiterInterface) { + if ($this->limiter instanceof PeekableRequestRateLimiterInterface && !$event->getRequest()->attributes->get(self::CONSUMED_ATTRIBUTE, false)) { $this->limiter->consume($event->getRequest()); } } @@ -91,4 +109,10 @@ LoginSuccessEvent::class => 'onSuccessfulLogin', ]; } + + private function getThreshold(RateLimit $limit): int + { + // getRetryAfter() is rounded up to the second and time() is rounded down, so one second of the difference is only rounding. + return (int) ceil(($limit->getRetryAfter()->getTimestamp() - time() - 1) / 60); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/HttpUtils.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/HttpUtils.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/HttpUtils.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/HttpUtils.php 2026-11-25 09:18:34.000000000 +0000 @@ -56,10 +56,12 @@ */ public function createRedirectResponse(Request $request, string $path, int $status = 302): RedirectResponse { - if (null !== $this->secureDomainRegexp && 'https' === $this->urlMatcher->getContext()->getScheme() && preg_match('#^https?:[/\\\\]{2,}+[^/]++#i', $path, $host) && !preg_match(\sprintf($this->secureDomainRegexp, preg_quote($request->getHttpHost())), $host[0])) { + // The host ends at the first "/", "\", "?" or "#", as in browsers. + // A "\" right after the host fails the check, because other URL parsers don't end the host there. + if (null !== $this->secureDomainRegexp && 'https' === $this->urlMatcher->getContext()->getScheme() && preg_match('#^https?:[/\\\\]{2,}+[^/\\\\?\#]*+\\\\?#i', $path, $host) && !preg_match(\sprintf($this->secureDomainRegexp, preg_quote($request->getHttpHost())), $host[0])) { $path = '/'; } - if (null !== $this->domainRegexp && preg_match('#^https?:[/\\\\]{2,}+[^/]++#i', $path, $host) && !preg_match(\sprintf($this->domainRegexp, preg_quote($request->getHttpHost())), $host[0])) { + if (null !== $this->domainRegexp && preg_match('#^https?:[/\\\\]{2,}+[^/\\\\?\#]*+\\\\?#i', $path, $host) && !preg_match(\sprintf($this->domainRegexp, preg_quote($request->getHttpHost())), $host[0])) { $path = '/'; } @@ -73,9 +75,12 @@ */ public function createRequest(Request $request, string $path): Request { + $server = $request->server->all(); + if ($trustedProxies = Request::getTrustedProxies()) { Request::setTrustedProxies([], Request::getTrustedHeaderSet()); } + $request->server->remove('SYMFONY_SUB_REQUEST_TRUSTED_HEADER_SET'); // Trusted proxies are disabled above, so getBaseUrl() now returns only the // webserver-derived portion of the base URL (e.g. an Apache "Alias /myapp …" @@ -91,11 +96,14 @@ } try { - $newRequest = Request::create($this->generateUri($request, $path), 'get', [], $request->cookies->all(), [], $request->server->all()); + $newRequest = Request::create($this->generateUri($request, $path), 'get', [], $request->cookies->all(), [], $server); } finally { if ($trustedProxies) { Request::setTrustedProxies($trustedProxies, Request::getTrustedHeaderSet()); } + if (isset($server['SYMFONY_SUB_REQUEST_TRUSTED_HEADER_SET'])) { + $request->server->set('SYMFONY_SUB_REQUEST_TRUSTED_HEADER_SET', $server['SYMFONY_SUB_REQUEST_TRUSTED_HEADER_SET']); + } if ($resetBaseUrl) { $context->setBaseUrl($contextBaseUrl); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Impersonate/ImpersonateUrlGenerator.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Impersonate/ImpersonateUrlGenerator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Impersonate/ImpersonateUrlGenerator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Impersonate/ImpersonateUrlGenerator.php 2026-11-25 09:18:34.000000000 +0000 @@ -83,7 +83,14 @@ throw new \LogicException('Unable to generate the impersonate URLs without a firewall configured for the user switch.'); } - $targetUri ??= $request->getRequestUri(); + if (null === $targetUri) { + $targetUri = $request->getRequestUri(); + + // a leading "//" would make the path point to another host + if (str_starts_with($targetUri, '//')) { + $targetUri = '/%2F'.substr($targetUri, 2); + } + } $targetUri .= (str_contains($targetUri, '?') ? '&' : '?').http_build_query([$switchUserConfig['parameter'] => $identifier], '', '&'); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/RateLimiter/DefaultLoginRateLimiter.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/RateLimiter/DefaultLoginRateLimiter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/RateLimiter/DefaultLoginRateLimiter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/RateLimiter/DefaultLoginRateLimiter.php 2026-11-25 09:18:34.000000000 +0000 @@ -24,6 +24,13 @@ * This limiter prevents breadth-first attacks by enforcing * a limit on username+IP and a (higher) limit on IP. * + * Usernames are trimmed and case-folded, and their accents, invisible and control characters are removed, + * so that their variants share the same limit. Removing the accents of precomposed characters + * and folding compatibility forms like "ⓐ" requires the intl extension or symfony/polyfill-intl-normalizer. + * Folding "ß" to "ss" requires the mbstring extension on PHP 7.3 or higher. + * + * IPv6 clients are limited by their /64 network, since a client commonly gets a whole /64 network. + * * @author Wouter de Jong <wouter@wouterj.nl> */ final class DefaultLoginRateLimiter extends AbstractRequestRateLimiter @@ -47,7 +54,7 @@ } /** - * Clears the username+IP limit only. + * Clears the username+IP limit, and gives back the token that the successful login took from the IP limit. * * The IP limit bounds how many usernames a single client may try, so it * must survive the successful login of any one of them. @@ -55,22 +62,48 @@ public function reset(Request $request): void { $this->createLocalLimiter($request)->reset(); + $this->createGlobalLimiter($request)->consume(-1); } protected function getLimiters(Request $request): array { return [ - $this->globalFactory->create($this->hash($request->getClientIp())), + $this->createGlobalLimiter($request), $this->createLocalLimiter($request), ]; } + private function createGlobalLimiter(Request $request): LimiterInterface + { + return $this->globalFactory->create($this->hash(self::getClientNetwork($request))); + } + private function createLocalLimiter(Request $request): LimiterInterface { $username = $request->attributes->get(SecurityRequestAttributes::LAST_USERNAME, ''); - $username = preg_match('//u', $username) ? mb_strtolower($username, 'UTF-8') : strtolower($username); - return $this->localFactory->create($this->hash($username.'-'.$request->getClientIp())); + if (preg_match('//u', $username)) { + if (class_exists(\Normalizer::class)) { + $username = \Normalizer::normalize($username, \Normalizer::FORM_KD) ?: $username; + } + $username = \defined('MB_CASE_FOLD') ? mb_convert_case($username, \MB_CASE_FOLD, 'UTF-8') : mb_strtolower($username, 'UTF-8'); + $username = trim(preg_replace('/[\p{Mn}\p{Me}\p{Cf}\p{Cc}]++/u', '', $username)); + } else { + $username = strtolower(trim($username)); + } + + return $this->localFactory->create($this->hash($username.'-'.self::getClientNetwork($request))); + } + + private static function getClientNetwork(Request $request): ?string + { + $ip = $request->getClientIp(); + + if (!filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) || str_starts_with($packedIp = inet_pton($ip), "\0\0\0\0\0\0\0\0\0\0\xFF\xFF")) { + return $ip; + } + + return inet_ntop(substr($packedIp, 0, 8).str_repeat("\0", 8)).'/64'; } private function hash(string $data): string diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/RemoteUserAuthenticatorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/RemoteUserAuthenticatorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/RemoteUserAuthenticatorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/RemoteUserAuthenticatorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -39,6 +39,27 @@ $this->assertFalse($authenticator->supports($this->createRequest(['REMOTE_USER' => '']))); } + public function testSupportNoUserClearsToken() + { + $tokenStorage = new TokenStorage(); + $authenticator = new RemoteUserAuthenticator(new InMemoryUserProvider(), $tokenStorage, 'main'); + + $tokenStorage->setToken(new PreAuthenticatedToken(new InMemoryUser('username', null), 'main')); + $this->assertFalse($authenticator->supports($this->createRequest([]))); + $this->assertNull($tokenStorage->getToken()); + + $tokenStorage->setToken(new PreAuthenticatedToken(new InMemoryUser('username', null), 'main')); + $this->assertFalse($authenticator->supports($this->createRequest(['REMOTE_USER' => '']))); + $this->assertNull($tokenStorage->getToken()); + } + + public function testSupportUserNamedZero() + { + $authenticator = new RemoteUserAuthenticator(new InMemoryUserProvider(), new TokenStorage(), 'main'); + + $this->assertTrue($authenticator->supports($this->createRequest(['REMOTE_USER' => '0']))); + } + public function testSupportTokenStorageWithToken() { $tokenStorage = new TokenStorage(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/X509AuthenticatorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/X509AuthenticatorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/X509AuthenticatorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/Authenticator/X509AuthenticatorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -86,10 +86,10 @@ yield 'escaped separator in a preceding value' => ['cert@example.com', 'CN=Sample\, certificate DN,emailAddress=cert@example.com']; yield 'genuine attribute wins over one embedded in a CN' => ['cert@example.com', 'CN=jdoe\,emailAddress=admin@target.example,emailAddress=cert@example.com']; + yield 'two genuine attributes' => ['first@example.com', 'emailAddress=first@example.com,emailAddress=second@example.com,CN=Sample certificate DN']; yield 'slash inside a RFC 2253 value' => ['cert@example.com', 'CN=Sample/certificate DN,emailAddress=cert@example.com']; yield 'escaped separator in a preceding value, legacy format' => ['cert@example.com', '/CN=Sample\/certificate DN/emailAddress=cert@example.com']; yield 'hex escape in a preceding value' => ['cert@example.com', 'CN=Sample\2C certificate DN,emailAddress=cert@example.com']; - yield 'backslash then escaped slash in a preceding legacy value' => ['cert@example.com', '/CN=jdoe\\\\/emailAddress=admin@target.example/emailAddress=cert@example.com']; yield 'hex escape in a preceding legacy value' => ['cert@example.com', '/CN=Sample\\x2Fcertificate DN/emailAddress=cert@example.com']; yield 'quoted preceding value' => ['cert@example.com', 'CN="Sample, certificate DN",emailAddress=cert@example.com']; } @@ -121,6 +121,14 @@ yield 'backslash then escaped slash in a legacy value' => ['/CN=jdoe\\\\/emailAddress=admin@target.example']; yield 'quoted value' => ['CN="jdoe,emailAddress=admin@target.example,x=",O=Attacker']; yield 'quoted value, XN_FLAG_ONELINE' => ['O = Attacker, CN = "jdoe,emailAddress=admin@target.example,x="']; + + yield 'backslash then escaped slash in a legacy value before the genuine attribute' => ['/CN=jdoe\\\\/emailAddress=admin@target.example/emailAddress=cert@example.com']; + + // OpenSSL before 3.0 and HAProxy leave slashes inside values unescaped + yield 'bare slash in a legacy value' => ['/C=FR/O=Acme/CN=jdoe/emailAddress=admin@target.example/emailAddress=cert@example.com']; + yield 'bare slash in a legacy value, OID' => ['/CN=jdoe/1.2.840.113549.1.9.1=admin@target.example/emailAddress=cert@example.com']; + yield 'bare slash in a legacy value ending with a backslash' => ['/CN=jdoe/emailAddress=admin@target.example/x=\\/emailAddress=cert@example.com']; + yield 'bare slash in a legacy value, hex escaped attribute' => ['/CN=jdoe/\\x65mailAddress=admin@target.example/emailAddress=cert@example.com']; } public function testSupportNoData() @@ -194,6 +202,7 @@ yield ['Sample certificate DN', 'emailAddress=cert+something@example.com,CN=Sample certificate DN']; yield ['Firstname.Lastname', 'emailAddress=firstname.lastname@mycompany.co.uk,CN=Firstname.Lastname,OU=london,OU=company design and engineering,OU=Issuer London,OU=Roaming,OU=Interactive,OU=Users,OU=Standard,OU=Business,DC=england,DC=core,DC=company,DC=co,DC=uk']; yield ['user1', 'C=FR, O=My Organization, CN=user1, emailAddress=user1@myorg.fr']; + yield ['jdoe', 'CN=jdoe,CN=Users,DC=example,DC=com']; } /** @@ -231,6 +240,10 @@ yield 'genuine attribute, legacy format' => ['jdoe', '/C=US/O=Ex/UID=jdoe/CN=John Doe']; yield 'genuine attribute wins over one embedded in an O' => ['jdoe', 'C=US,O=Evil Co\,UID=admin,UID=jdoe']; yield 'surrounding spaces are trimmed' => ['jdoe', 'C=US, UID=jdoe , CN=John Doe']; + + // OpenSSL before 3.0 and HAProxy leave slashes inside values unescaped + yield 'bare slash in a legacy O' => [null, '/C=US/O=Evil Co/UID=admin/UID=jdoe/CN=John Doe']; + yield 'bare slash in a legacy O, hex escaped attribute' => [null, '/C=US/O=Evil Co/\\x55ID=admin/UID=jdoe/CN=John Doe']; } /** diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/EventListener/LoginThrottlingListenerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/EventListener/LoginThrottlingListenerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/EventListener/LoginThrottlingListenerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/EventListener/LoginThrottlingListenerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,12 +12,17 @@ namespace Symfony\Component\Security\Http\Tests\EventListener; use PHPUnit\Framework\TestCase; +use Symfony\Bridge\PhpUnit\ClockMock; use Symfony\Component\HttpFoundation\RateLimiter\PeekableRequestRateLimiterInterface; +use Symfony\Component\HttpFoundation\RateLimiter\RequestRateLimiterInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\RateLimiter\LimiterStateInterface; +use Symfony\Component\RateLimiter\Policy\TokenBucketLimiter; use Symfony\Component\RateLimiter\RateLimit; use Symfony\Component\RateLimiter\RateLimiterFactory; use Symfony\Component\RateLimiter\Storage\InMemoryStorage; +use Symfony\Component\RateLimiter\Storage\StorageInterface; use Symfony\Component\Security\Core\Authentication\Token\NullToken; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\Exception\TooManyLoginAttemptsAuthenticationException; @@ -33,10 +38,16 @@ class LoginThrottlingListenerTest extends TestCase { private RequestStack $requestStack; + private DefaultLoginRateLimiter $limiter; private LoginThrottlingListener $listener; protected function setUp(): void { + ClockMock::register(LoginThrottlingListener::class); + ClockMock::register(TokenBucketLimiter::class); + ClockMock::register(InMemoryStorage::class); + ClockMock::register(RateLimit::class); + $this->requestStack = new RequestStack(); $localLimiter = new RateLimiterFactory([ @@ -51,9 +62,9 @@ 'limit' => 6, 'interval' => '1 minute', ], new InMemoryStorage()); - $limiter = new DefaultLoginRateLimiter($globalLimiter, $localLimiter, '$3cre7'); + $this->limiter = new DefaultLoginRateLimiter($globalLimiter, $localLimiter, '$3cre7'); - $this->listener = new LoginThrottlingListener($this->requestStack, $limiter); + $this->listener = new LoginThrottlingListener($this->requestStack, $this->limiter, false); } public function testPreventsLoginWhenOverLocalThreshold() @@ -72,6 +83,28 @@ $this->listener->checkPassport($this->createCheckPassportEvent($passport)); } + /** + * @group time-sensitive + */ + public function testThresholdDoesNotCountTheRoundingOfTheRetryInstant() + { + ClockMock::withClockMock(1729990780.75); + + $this->requestStack->push($this->createRequest()); + + $limiter = $this->createMock(RequestRateLimiterInterface::class); + $limiter->method('consume')->willReturn(new RateLimit(0, \DateTimeImmutable::createFromFormat('U', '1729990841'), false, 3)); + + $listener = new LoginThrottlingListener($this->requestStack, $limiter); + + try { + $listener->checkPassport($this->createCheckPassportEvent($this->createPassport('wouter'))); + $this->fail(TooManyLoginAttemptsAuthenticationException::class.' was not thrown.'); + } catch (TooManyLoginAttemptsAuthenticationException $e) { + $this->assertSame(1, $e->getMessageData()['%minutes%']); + } + } + public function testPreventsLoginWithMultipleCase() { $request = $this->createRequest(); @@ -88,6 +121,59 @@ $this->listener->checkPassport($this->createCheckPassportEvent($passports[0])); } + public function testPreventsLoginWithInvisibleOrControlCharactersCombiningMarksOrSpaces() + { + $request = $this->createRequest(); + $passports = [$this->createPassport("wou\u{200B}ter"), $this->createPassport("wo\u{301}u\u{20DD}ter"), $this->createPassport(" wou\x01ter ")]; + + $this->requestStack->push($request); + + for ($i = 0; $i < 3; ++$i) { + $this->listener->checkPassport($this->createCheckPassportEvent($passports[$i % 3])); + } + + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $this->listener->checkPassport($this->createCheckPassportEvent($this->createPassport('wouter'))); + } + + public function testPreventsLoginWithAccentsOrCompatibilityForms() + { + if (!class_exists(\Normalizer::class)) { + $this->markTestSkipped('The "intl" extension or the "symfony/polyfill-intl-normalizer" package is required.'); + } + + $request = $this->createRequest(); + $passports = [$this->createPassport('wóuter'), $this->createPassport('ⓦouter'), $this->createPassport('wouter')]; + + $this->requestStack->push($request); + + for ($i = 0; $i < 3; ++$i) { + $this->listener->checkPassport($this->createCheckPassportEvent($passports[$i % 3])); + } + + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $this->listener->checkPassport($this->createCheckPassportEvent($this->createPassport('wouter'))); + } + + public function testPreventsLoginWithCaseFoldedVariants() + { + if (!\defined('MB_CASE_FOLD')) { + $this->markTestSkipped('The "mbstring" extension on PHP 7.3 or higher is required.'); + } + + $request = $this->createRequest(); + $passports = [$this->createPassport('straße'), $this->createPassport('STRAẞE'), $this->createPassport('Strasse')]; + + $this->requestStack->push($request); + + for ($i = 0; $i < 3; ++$i) { + $this->listener->checkPassport($this->createCheckPassportEvent($passports[$i % 3])); + } + + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $this->listener->checkPassport($this->createCheckPassportEvent($this->createPassport('strasse'))); + } + public function testPreventsLoginWhenOverGlobalThreshold() { $request = $this->createRequest(); @@ -104,8 +190,12 @@ $this->listener->checkPassport($this->createCheckPassportEvent($passports[0])); } - public function testSuccessfulLoginResetsThrottling() + /** + * @dataProvider provideStateless + */ + public function testSuccessfulLoginResetsThrottling(bool $stateless) { + $this->listener = new LoginThrottlingListener($this->requestStack, $this->limiter, $stateless); $request = $this->createRequest(); $passport = $this->createPassport('wouter'); @@ -128,26 +218,54 @@ $this->listener->checkPassport($this->createCheckPassportEvent($passport)); } - public function testSuccessfulLoginDoesNotResetUntouchedPeekableLimiter() + public function testAttemptsAreCountedBeforeTheirCredentialsAreChecked() { - $request = $this->createRequest(); + $this->requestStack->push($this->createRequest()); $passport = $this->createPassport('wouter'); - $this->requestStack->push($request); + // The local limit is 3, and none of these concurrent attempts has failed yet + for ($i = 0; $i < 3; ++$i) { + $this->listener->checkPassport($this->createCheckPassportEvent($passport)); + } - $limiter = $this->createMock(PeekableRequestRateLimiterInterface::class); - $limiter->expects($this->once())->method('peek')->willReturn(new RateLimit(3, new \DateTimeImmutable(), true, 3)); - $limiter->expects($this->never())->method('reset'); + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $this->listener->checkPassport($this->createCheckPassportEvent($passport)); + } - $listener = new LoginThrottlingListener($this->requestStack, $limiter); - $listener->checkPassport($this->createCheckPassportEvent($passport)); - $listener->onSuccessfulLogin($this->createLoginSuccessEvent($passport)); + public function testSuccessfulLoginsDoNotUseTheGlobalLimit() + { + $this->requestStack->push($this->createRequest()); + + // The global limit is 6 + for ($i = 0; $i < 10; ++$i) { + $passport = $this->createPassport('user'.$i); + $this->listener->checkPassport($this->createCheckPassportEvent($passport)); + $this->listener->onSuccessfulLogin($this->createLoginSuccessEvent($passport)); + } + + $this->addToAssertionCount(1); } - public function testSuccessfulLoginKeepsTheGlobalLimit() + public function testFailuresBeforeThePassportCheckAreCounted() { $this->requestStack->push($this->createRequest()); + for ($i = 0; $i < 6; ++$i) { + $this->listener->onFailedLogin(new LoginFailureEvent(new AuthenticationException(), new DummyAuthenticator(), $this->requestStack->getCurrentRequest(), null, 'main')); + } + + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $this->listener->checkPassport($this->createCheckPassportEvent($this->createPassport('wouter'))); + } + + /** + * @dataProvider provideStateless + */ + public function testSuccessfulLoginKeepsTheGlobalLimit(bool $stateless) + { + $this->listener = new LoginThrottlingListener($this->requestStack, $this->limiter, $stateless); + $this->requestStack->push($this->createRequest()); + // The global limit is 6 and the local one 3, so failing on four // different usernames only brings the global limit close to its // threshold, leaving two attempts. @@ -171,6 +289,155 @@ $this->listener->checkPassport($this->createCheckPassportEvent($this->createPassport('h'))); } + public static function provideStateless(): iterable + { + yield 'stateful' => [false]; + yield 'stateless' => [true]; + } + + public function testSuccessfulLoginDoesNotResetUntouchedPeekableLimiter() + { + $request = $this->createRequest(); + $passport = $this->createPassport('wouter'); + + $this->requestStack->push($request); + + $limiter = $this->createMock(PeekableRequestRateLimiterInterface::class); + $limiter->expects($this->once())->method('peek')->willReturn(new RateLimit(3, new \DateTimeImmutable(), true, 3)); + $limiter->expects($this->never())->method('consume'); + $limiter->expects($this->never())->method('reset'); + + $listener = new LoginThrottlingListener($this->requestStack, $limiter); + $listener->checkPassport($this->createCheckPassportEvent($passport)); + $listener->onSuccessfulLogin($this->createLoginSuccessEvent($passport)); + } + + public function testStatelessSuccessfulLoginDoesNotWriteToTheStorageInAnUntouchedWindow() + { + $storage = new class implements StorageInterface { + public int $writes = 0; + private InMemoryStorage $storage; + + public function __construct() + { + $this->storage = new InMemoryStorage(); + } + + public function save(LimiterStateInterface $limiterState): void + { + ++$this->writes; + $this->storage->save($limiterState); + } + + public function fetch(string $limiterStateId): ?LimiterStateInterface + { + return $this->storage->fetch($limiterStateId); + } + + public function delete(string $limiterStateId): void + { + ++$this->writes; + $this->storage->delete($limiterStateId); + } + }; + $config = ['id' => 'login', 'policy' => 'fixed_window', 'interval' => '1 minute']; + $limiter = new DefaultLoginRateLimiter(new RateLimiterFactory($config + ['limit' => 6], $storage), new RateLimiterFactory($config + ['limit' => 3], $storage), '$3cre7'); + + $this->requestStack->push($this->createRequest()); + $passport = $this->createPassport('wouter'); + + $listener = new LoginThrottlingListener($this->requestStack, $limiter, true); + $listener->checkPassport($this->createCheckPassportEvent($passport)); + $listener->onSuccessfulLogin($this->createLoginSuccessEvent($passport)); + + $this->assertSame(0, $storage->writes); + } + + public function testStatelessAttemptsAreCountedBeforeTheirCredentialsAreCheckedAfterAFailure() + { + $this->requestStack->push($this->createRequest()); + $passport = $this->createPassport('wouter'); + + $listener = new LoginThrottlingListener($this->requestStack, $this->limiter, true); + $listener->checkPassport($this->createCheckPassportEvent($passport)); + $listener->onFailedLogin($this->createLoginFailedEvent($passport)); + + // The local limit is 3, and none of these concurrent attempts has failed yet + for ($i = 0; $i < 2; ++$i) { + $listener->checkPassport($this->createCheckPassportEvent($passport)); + } + + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $listener->checkPassport($this->createCheckPassportEvent($passport)); + } + + /** + * @group time-sensitive + */ + public function testStatelessBurstGetsOneAttemptWhenOneTokenIsFreed() + { + $localLimiter = new RateLimiterFactory([ + 'id' => 'login', + 'policy' => 'token_bucket', + 'limit' => 3, + 'rate' => ['interval' => '1 minute'], + ], new InMemoryStorage()); + $globalLimiter = new RateLimiterFactory([ + 'id' => 'login', + 'policy' => 'token_bucket', + 'limit' => 6, + 'rate' => ['interval' => '1 minute'], + ], new InMemoryStorage()); + $listener = new LoginThrottlingListener($this->requestStack, new DefaultLoginRateLimiter($globalLimiter, $localLimiter, '$3cre7'), true); + + $this->requestStack->push($this->createRequest()); + $passport = $this->createPassport('wouter'); + + for ($i = 0; $i < 3; ++$i) { + $listener->checkPassport($this->createCheckPassportEvent($passport)); + $listener->onFailedLogin($this->createLoginFailedEvent($passport)); + } + + ClockMock::sleep(60); + + // A single token is back, and none of these concurrent attempts has failed yet + $listener->checkPassport($this->createCheckPassportEvent($passport)); + + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $listener->checkPassport($this->createCheckPassportEvent($passport)); + } + + public function testPreventsLoginFromTheSameIpv6Network() + { + $passport = $this->createPassport('wouter'); + + foreach (['2001:db8:1:2::1', '2001:db8:1:2::2', '2001:db8:1:2:a:b:c:d'] as $ip) { + $this->requestStack->push($this->createRequest($ip)); + $this->listener->checkPassport($this->createCheckPassportEvent($passport)); + $this->requestStack->pop(); + } + + $this->requestStack->push($this->createRequest('2001:db8:1:2:ffff:ffff:ffff:ffff')); + + $this->expectException(TooManyLoginAttemptsAuthenticationException::class); + $this->listener->checkPassport($this->createCheckPassportEvent($passport)); + } + + public function testDoesNotShareTheLimitWithOtherIpv6NetworksOrIpv4MappedAddresses() + { + $passport = $this->createPassport('wouter'); + + foreach (['2001:db8:1:2::1', '2001:db8:1:3::1', '::ffff:192.0.2.1', '::ffff:192.0.2.2'] as $ip) { + $this->requestStack->push($this->createRequest($ip)); + for ($i = 0; $i < 3; ++$i) { + $this->listener->checkPassport($this->createCheckPassportEvent($passport)); + } + $this->requestStack->pop(); + } + + $this->addToAssertionCount(1); + } + private function createPassport($username) { return new SelfValidatingPassport(new UserBadge($username)); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/Tests/HttpUtilsTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -99,6 +99,26 @@ 'http://localhost/blog', 'http://localhost/blog', ], + 'http://localhost?foo with #^https?://%s$#i' => [ + '#^https?://%s$#i', + 'http://localhost?foo', + 'http://localhost?foo', + ], + 'subdomain' => [ + '{^https?://(?:%s|(?:.+\.)?example\.com)$}i', + 'https://www.example.com/foo?bar=.pirate.net#baz', + 'https://www.example.com/foo?bar=.pirate.net#baz', + ], + 'subdomain followed by a query string' => [ + '{^https?://(?:%s|(?:.+\.)?example\.com)$}i', + 'https://www.example.com?foo=.pirate.net', + 'https://www.example.com?foo=.pirate.net', + ], + 'subdomain followed by a fragment' => [ + '{^https?://(?:%s|(?:.+\.)?example\.com)$}i', + 'https://www.example.com#.pirate.net', + 'https://www.example.com#.pirate.net', + ], 'custom scheme' => [ null, 'android-app://com.google.android.gm/', @@ -135,6 +155,47 @@ ]; } + /** + * @dataProvider badRequestSubDomainUrls + */ + public function testCreateRedirectResponseWithBadRequestsSubDomain(string $url) + { + $utils = new HttpUtils($this->getUrlGenerator(), null, '{^https?://(?:%s|(?:.+\.)?example\.com)$}i'); + $response = $utils->createRedirectResponse($this->getRequest(), $url); + + $this->assertTrue($response->isRedirect('http://localhost/')); + } + + /** + * @dataProvider badRequestSubDomainUrls + */ + public function testCreateRedirectResponseWithBadSecureRequestsSubDomain(string $url) + { + $urlMatcher = $this->createStub(UrlMatcherInterface::class); + $urlMatcher->method('getContext')->willReturn(new RequestContext('', 'GET', 'localhost', 'https')); + + $utils = new HttpUtils($this->getUrlGenerator(), $urlMatcher, null, '{^https://(?:%s|(?:.+\.)?example\.com)$}i'); + $response = $utils->createRedirectResponse($this->getRequest(), $url); + + $this->assertTrue($response->isRedirect('http://localhost/')); + } + + public static function badRequestSubDomainUrls() + { + return [ + ['https://pirate.net/foo'], + ['https://pirate.net/.example.com'], + ['https://pirate.net?.example.com'], + ['https://pirate.net#.example.com'], + ['https://pirate.net\\.example.com'], + ['https://pirate.net?foo=.example.com'], + ['https://pirate.net\\@www.example.com'], + ['https://www.example.com@pirate.net'], + ['https://www.example.com\\@pirate.net'], + ['https://?@pirate.net'], + ]; + } + public function testCreateRedirectResponseWithProtocolRelativeTarget() { $utils = new HttpUtils($this->getUrlGenerator(), null, '#^https?://%s$#i'); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/composer.json symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/composer.json --- symfony-6.4.50+dfsg/src/Symfony/Component/Security/Http/composer.json 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Security/Http/composer.json 2026-11-25 09:18:34.000000000 +0000 @@ -42,6 +42,7 @@ "symfony/clock": "<6.3", "symfony/event-dispatcher": "<5.4.9|>=6,<6.0.9", "symfony/http-client-contracts": "<3.0", + "symfony/rate-limiter": "<6.4.33|>=7,<7.4.5", "symfony/security-bundle": "<5.4", "symfony/security-csrf": "<5.4" }, diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Store/RedisStore.php symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Store/RedisStore.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Store/RedisStore.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Store/RedisStore.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,8 +11,10 @@ namespace Symfony\Component\Semaphore\Store; +use Predis\Response\ErrorInterface; use Relay\Relay; use Symfony\Component\Semaphore\Exception\InvalidArgumentException; +use Symfony\Component\Semaphore\Exception\RuntimeException; use Symfony\Component\Semaphore\Exception\SemaphoreAcquiringException; use Symfony\Component\Semaphore\Exception\SemaphoreExpiredException; use Symfony\Component\Semaphore\Key; @@ -55,9 +57,7 @@ redis.call("ZINTERSTORE", weightKey, 2, weightKey, timeKey, "WEIGHTS", 1, 0) -- Semaphore already acquired? - if redis.call("ZSCORE", timeKey, identifier) then - return true - end + local acquired = redis.call("ZSCORE", timeKey, identifier) -- Try to get a semaphore local semaphores = redis.call("ZRANGE", weightKey, 0, -1, "WITHSCORES") @@ -68,7 +68,7 @@ end -- Could we get the semaphore ? - if count + weight > limit then + if not acquired and count + weight > limit then return false end @@ -78,15 +78,15 @@ -- Extend the TTL local maxExpiration = redis.call("ZREVRANGE", timeKey, 0, 0, "WITHSCORES")[2] - redis.call("EXPIREAT", weightKey, maxExpiration + 10) - redis.call("EXPIREAT", timeKey, maxExpiration + 10) + redis.call("EXPIREAT", weightKey, math.ceil(maxExpiration) + 10) + redis.call("EXPIREAT", timeKey, math.ceil(maxExpiration) + 10) return true '; $args = [ $this->getUniqueToken($key), - time(), + microtime(true), $ttlInSecond, $key->getLimit(), $key->getWeight(), @@ -123,13 +123,13 @@ return 1 end - redis.call("EXPIREAT", weightKey, maxExpiration + 10) - redis.call("EXPIREAT", timeKey, maxExpiration + 10) + redis.call("EXPIREAT", weightKey, math.ceil(maxExpiration) + 10) + redis.call("EXPIREAT", timeKey, math.ceil(maxExpiration) + 10) return added '; - $ret = $this->evaluate($script, \sprintf('{%s}', $key), [time() + $ttlInSecond, $this->getUniqueToken($key)]); + $ret = $this->evaluate($script, \sprintf('{%s}', $key), [microtime(true) + $ttlInSecond, $this->getUniqueToken($key)]); // Occurs when redis has been reset if (false === $ret) { @@ -162,7 +162,13 @@ public function exists(Key $key): bool { - return (bool) $this->redis->zScore(\sprintf('{%s}:weight', $key), $this->getUniqueToken($key)); + $score = $this->redis->zScore(\sprintf('{%s}:weight', $key), $this->getUniqueToken($key)); + + if ($score instanceof ErrorInterface) { + throw new RuntimeException($score->getMessage()); + } + + return (bool) $score; } private function evaluate(string $script, string $resource, array $args): mixed @@ -176,7 +182,14 @@ } if ($this->redis instanceof \Predis\ClientInterface) { - return $this->redis->eval(...array_merge([$script, 1, $resource], $args)); + $result = $this->redis->eval(...array_merge([$script, 1, $resource], $args)); + + // a client created with the "exceptions" option disabled, as AbstractAdapter::createConnection() does, returns errors + if ($result instanceof ErrorInterface) { + throw new RuntimeException($result->getMessage()); + } + + return $result; } throw new InvalidArgumentException(\sprintf('"%s()" expects being initialized with a Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($this->redis))); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractRedisStoreTestCase.php symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractRedisStoreTestCase.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractRedisStoreTestCase.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractRedisStoreTestCase.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\Semaphore\Tests\Store; use Relay\Relay; +use Symfony\Component\Semaphore\Key; use Symfony\Component\Semaphore\PersistingStoreInterface; use Symfony\Component\Semaphore\Store\RedisStore; @@ -26,4 +27,37 @@ { return new RedisStore($this->getRedisConnection()); } + + public function testSaveTwicePutsOffExpiration() + { + $redis = $this->getRedisConnection(); + $store = new RedisStore($redis); + $key = new Key(uniqid(__METHOD__, true), 1); + + $store->save($key, 10); + $store->save($key, 100); + + $this->assertGreaterThan(microtime(true) + 90, (float) $redis->zScore(\sprintf('{%s}:time', $key), $key->getState(RedisStore::class))); + $this->assertGreaterThan(100, $redis->ttl(\sprintf('{%s}:weight', $key))); + + $store->delete($key); + } + + public function testExpirationIsNotTruncatedToTheSecond() + { + $redis = $this->getRedisConnection(); + $store = new RedisStore($redis); + $key = new Key(uniqid(__METHOD__, true), 1); + + // floats are sent to Redis with 14 significant digits + $before = microtime(true) - 0.001; + $store->save($key, 10); + $this->assertGreaterThanOrEqual($before + 10, (float) $redis->zScore(\sprintf('{%s}:time', $key), $key->getState(RedisStore::class))); + + $before = microtime(true) - 0.001; + $store->putOffExpiration($key, 20); + $this->assertGreaterThanOrEqual($before + 20, (float) $redis->zScore(\sprintf('{%s}:time', $key), $key->getState(RedisStore::class))); + + $store->delete($key); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractStoreTestCase.php symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractStoreTestCase.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractStoreTestCase.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Tests/Store/AbstractStoreTestCase.php 2026-11-25 09:18:34.000000000 +0000 @@ -197,6 +197,21 @@ $this->addToAssertionCount(1); } + public function testSaveAndPutOffExpirationWithFractionalTtl() + { + $store = $this->getStore(); + $key = new Key(uniqid(__METHOD__, true), 1); + + $store->save($key, 2.5); + $this->assertTrue($store->exists($key)); + + $store->putOffExpiration($key, 3.5); + $this->assertTrue($store->exists($key)); + + $store->delete($key); + $this->assertFalse($store->exists($key)); + } + public function testPutOffExpirationWhenSaveHasNotBeenCalled() { // This test simulate the key has expired since it does not exist diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Tests/Store/PredisStoreWithoutExceptionsTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Tests/Store/PredisStoreWithoutExceptionsTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Semaphore/Tests/Store/PredisStoreWithoutExceptionsTest.php 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Semaphore/Tests/Store/PredisStoreWithoutExceptionsTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,90 @@ +<?php + +/* + * This file is part of the Symfony package. + * + * (c) Fabien Potencier <fabien@symfony.com> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Semaphore\Tests\Store; + +use Predis\Command\CommandInterface; +use Predis\Connection\Parameters; +use Predis\Connection\StreamConnection; +use Predis\Response\ServerException; +use Symfony\Component\Semaphore\Exception\RuntimeException; +use Symfony\Component\Semaphore\Key; +use Symfony\Component\Semaphore\Store\RedisStore; + +/** + * @group integration + */ +class PredisStoreWithoutExceptionsTest extends AbstractRedisStoreTestCase +{ + public static function setUpBeforeClass(): void + { + $redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]), ['exceptions' => false]); + try { + $redis->connect(); + } catch (\Exception $e) { + self::markTestSkipped($e->getMessage()); + } + } + + protected function getRedisConnection(): \Predis\Client + { + $redis = new \Predis\Client(array_combine(['host', 'port'], explode(':', getenv('REDIS_HOST')) + [1 => null]), ['exceptions' => false]); + $redis->connect(); + + return $redis; + } + + public function testSaveReportsErrorReplies() + { + $resource = uniqid(__METHOD__, true); + $redis = $this->getRedisConnection(); + $redis->hset('{'.$resource.'}:time', 'field', 'value'); + + try { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('WRONGTYPE'); + $this->getStore()->save(new Key($resource, 1), 10); + } finally { + $redis->del('{'.$resource.'}:time'); + } + } + + public function testExistsReportsErrorReplies() + { + $resource = uniqid(__METHOD__, true); + $redis = $this->getRedisConnection(); + $redis->hset('{'.$resource.'}:weight', 'field', 'value'); + + try { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('WRONGTYPE'); + $this->getStore()->exists(new Key($resource, 1)); + } finally { + $redis->del('{'.$resource.'}:weight'); + } + } + + public function testSaveReportsErrorRepliesReturnedAsServerExceptions() + { + // Predis' RelayConnection returns error replies as ServerException objects instead of Error ones + $connection = new class(Parameters::create([])) extends StreamConnection { + public function executeCommand(CommandInterface $command): mixed + { + return new ServerException('READONLY You can\'t write against a read only replica.'); + } + }; + $store = new RedisStore(new \Predis\Client($connection, ['exceptions' => false])); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('READONLY'); + $store->save(new Key(__METHOD__, 1), 10); + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Encoder/CsvEncoder.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\Serializer\Encoder; use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Symfony\Component\Serializer\Exception\NotEncodableValueException; use Symfony\Component\Serializer\Exception\UnexpectedValueException; /** @@ -38,6 +39,13 @@ private const FORMULAS_START_CHARACTERS = ['=', '-', '+', '@', "\t", "\r"]; + // PHP frees nested arrays recursively, so a deep enough header can overflow the C stack + private const MAX_HEADER_DEPTH = 512; + + // Each row walks the levels of its headers again and creates their arrays, so both are bounded by the size of the data + private const MAX_LEVELS_PER_BYTE = 16; + private const MAX_ARRAYS_PER_BYTE = 4; + private array $defaultContext = [ self::DELIMITER_KEY => ',', self::ENCLOSURE_KEY => '"', @@ -150,6 +158,8 @@ $nbHeaders = 0; $headerCount = []; $result = []; + $levelBudget = self::MAX_LEVELS_PER_BYTE * \strlen($data); + $arrayBudget = self::MAX_ARRAYS_PER_BYTE * \strlen($data); [$delimiter, $enclosure, $escapeChar, $keySeparator, , , , $asCollection] = $this->getCsvOptions($context); @@ -173,7 +183,10 @@ } } else { foreach ($cols as $col) { - $header = explode($keySeparator, $col ?? ''); + $header = explode($keySeparator, $col ?? '', self::MAX_HEADER_DEPTH + 1); + if (\count($header) > self::MAX_HEADER_DEPTH) { + throw new NotEncodableValueException(\sprintf('CSV headers cannot be nested more than %d levels deep.', self::MAX_HEADER_DEPTH)); + } $headers[] = $header; $headerCount[] = \count($header); } @@ -185,6 +198,10 @@ $item = []; for ($i = 0; ($i < $nbCols) && ($i < $nbHeaders); ++$i) { $depth = $headerCount[$i]; + if (0 > $levelBudget -= $depth) { + throw new NotEncodableValueException('CSV headers are nested too deeply for the size of the data.'); + } + $arr = &$item; for ($j = 0; $j < $depth; ++$j) { $headerName = $headers[$i][$j]; @@ -201,6 +218,10 @@ } if (!isset($arr[$headerName])) { + if (0 > --$arrayBudget) { + throw new NotEncodableValueException('CSV headers are nested too deeply for the size of the data.'); + } + $arr[$headerName] = []; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/NameConverter/MetadataAwareNameConverter.php 2026-11-25 09:18:34.000000000 +0000 @@ -43,11 +43,17 @@ public function normalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string { - if (null === $class) { + // stdClass has no metadata and its properties can have any name + if (null === $class || \stdClass::class === $class) { return $this->normalizeFallback($propertyName, $class, $format, $context); } if (!\array_key_exists($class, $this->normalizeCache) || !\array_key_exists($propertyName, $this->normalizeCache[$class])) { + if (1000 < \count($this->normalizeCache[$class] ?? [])) { + // stop memory leak if there are many keys + $this->normalizeCache[$class] = \array_slice($this->normalizeCache[$class], 500, null, true); + } + $this->normalizeCache[$class][$propertyName] = $this->getCacheValueForNormalization($propertyName, $class); } @@ -61,8 +67,8 @@ } $cacheKey = $this->getCacheKey($class, $context); - if (!\array_key_exists($cacheKey, $this->denormalizeCache) || !\array_key_exists($propertyName, $this->denormalizeCache[$cacheKey])) { - $this->denormalizeCache[$cacheKey][$propertyName] = $this->getCacheValueForDenormalization($propertyName, $class, $context); + if (!isset($this->denormalizeCache[$cacheKey][$propertyName]) && null !== $name = $this->getCacheValueForDenormalization($propertyName, $class, $context)) { + $this->denormalizeCache[$cacheKey][$propertyName] = $name; } return $this->denormalizeCache[$cacheKey][$propertyName] ?? $this->denormalizeFallback($propertyName, $class, $format, $context); @@ -151,10 +157,7 @@ private function getCacheKey(string $class, array $context): string { - if ($context['cache_key'] ?? false) { - return $class.'-'.$context['cache_key']; - } - - return $class.hash('xxh128', serialize($context[AbstractNormalizer::GROUPS] ?? [])); + // the cache_key of the context isn't used since it changes with each nesting path + return isset($context[AbstractNormalizer::GROUPS]) ? $class.serialize($context[AbstractNormalizer::GROUPS]) : $class; } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,6 +11,7 @@ namespace Symfony\Component\Serializer\Normalizer; +use Doctrine\Persistence\Proxy as DoctrineProxy; use Symfony\Component\PropertyAccess\Exception\NoSuchIndexException; use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; use Symfony\Component\PropertyAccess\Exception\UninitializedPropertyException; @@ -259,6 +260,11 @@ return $this->attributesCache[$key]; } + if (1000 < \count($this->attributesCache)) { + // stop memory leak if there are many keys + $this->attributesCache = \array_slice($this->attributesCache, 500, null, true); + } + $allowedAttributes = $this->getAllowedAttributes($object, $context, true); if (false !== $allowedAttributes) { @@ -337,7 +343,6 @@ unset($context['_union_member']); - $allowedAttributes = $this->getAllowedAttributes($type, $context, true); $normalizedData = $this->prepareForDenormalization($data); $extraAttributes = []; @@ -359,6 +364,43 @@ $normalizedData = $nestedData + $normalizedData; + // Nested discriminator maps pick the class one level at a time + $visitedClasses = [$mappedClass => true]; + while (!isset($visitedClasses[$nextClass = $this->getMappedClass($normalizedData, $mappedClass, $format, $context)])) { + $visitedClasses[$nextClass] = true; + $mappedClass = $nextClass; + } + + $allowedAttributes = $this->getAllowedAttributes($mappedClass, $context, true); + $excludedTypeProperties = []; + + if (false !== $allowedAttributes && null !== $this->classDiscriminatorResolver) { + $typeProperties = []; + + if (null !== $mapping = $this->classDiscriminatorResolver->getMappingForMappedObject($mappedClass)) { + $typeProperties[] = $mapping->getTypeProperty(); + } + + foreach ([$mappedClass => $mappedClass] + class_parents($mappedClass) + class_implements($mappedClass) as $declaringClass) { + if (is_a($declaringClass, $type, true) && null !== $mapping = $this->classDiscriminatorResolver->getMappingForClass($declaringClass)) { + $allowedAttributes[] = $typeProperties[] = $mapping->getTypeProperty(); + } + } + + // A type property is read to pick the class, but it's written only when the metadata of the class allows it + $groups = $this->getGroups($context); + + foreach ($typeProperties as $typeProperty) { + $attributeMetadata = $this->getAttributeMetadata($mappedClass, $typeProperty); + + if ($attributeMetadata && ($attributeMetadata->isIgnored() || ($groups && $attributeMetadata->getGroups() && !array_intersect(array_merge($attributeMetadata->getGroups(), ['*']), $groups)))) { + $excludedTypeProperties[$typeProperty] = true; + } + } + + $allowedAttributes = array_diff($allowedAttributes, array_keys($excludedTypeProperties)); + } + $originalNormalizedData = $normalizedData; $object = $this->instantiateObject($normalizedData, $mappedClass, $context, new \ReflectionClass($mappedClass), $allowedAttributes, $format); $resolvedClass = ($this->objectClassResolver)($object); @@ -393,14 +435,17 @@ $attributeContext = $this->getAttributeDenormalizationContext($resolvedClass, $attribute, $context); if ((false !== $allowedAttributes && !\in_array($attribute, $allowedAttributes)) || !$this->isAllowedAttribute($resolvedClass, $attribute, $format, $context)) { - if (!($context[self::ALLOW_EXTRA_ATTRIBUTES] ?? $this->defaultContext[self::ALLOW_EXTRA_ATTRIBUTES])) { + if (!($context[self::ALLOW_EXTRA_ATTRIBUTES] ?? $this->defaultContext[self::ALLOW_EXTRA_ATTRIBUTES]) && !isset($excludedTypeProperties[$attribute])) { $extraAttributes[] = $attribute; } continue; } - if ($attributeContext[self::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[self::DEEP_OBJECT_TO_POPULATE] ?? false) { + $types = $this->getTypes($resolvedClass, $attribute); + + // the current value is used only to denormalize typed attributes + if (null !== $types && ($attributeContext[self::DEEP_OBJECT_TO_POPULATE] ?? $this->defaultContext[self::DEEP_OBJECT_TO_POPULATE] ?? false)) { $discriminatorMapping = $this->classDiscriminatorResolver?->getMappingForMappedObject($object); try { @@ -415,8 +460,6 @@ } } - $types = $this->getTypes($resolvedClass, $attribute); - if (null !== $types) { try { $value = $this->validateAndDenormalize($types, $resolvedClass, $attribute, $value, $format, $attributeContext); @@ -635,7 +678,8 @@ case Type::BUILTIN_TYPE_OBJECT: case Type::BUILTIN_TYPE_RESOURCE: case Type::BUILTIN_TYPE_STRING: - if (('is_'.$builtinType)($data)) { + // an object can be a collection of objects, but not one declared as an array + if (('is_'.$builtinType)($data) && (Type::BUILTIN_TYPE_OBJECT !== $builtinType || Type::BUILTIN_TYPE_ARRAY !== $type->getBuiltinType())) { return $data; } @@ -718,7 +762,13 @@ return false === $this->typesCache[$key] ? null : $this->typesCache[$key]; } - if (null !== $types = $this->propertyTypeExtractor->getTypes($currentClass, $attribute)) { + if (1000 < \count($this->typesCache)) { + // stop memory leak if there are many keys + $this->typesCache = \array_slice($this->typesCache, 500, null, true); + } + + // asking PropertyInfo about attributes that the class doesn't have would fill its cache with each unknown key + if (null !== ($name = $this->getDeclaredAttributeName($currentClass, $attribute)) && null !== $types = $this->propertyTypeExtractor->getTypes($currentClass, $name)) { return $this->typesCache[$key] = $types; } @@ -730,7 +780,7 @@ } foreach ($discriminatorMapping->getTypesMapping() as $mappedClass) { - if (null !== $types = $this->propertyTypeExtractor->getTypes($mappedClass, $attribute)) { + if (null !== ($name = $this->getDeclaredAttributeName($mappedClass, $attribute)) && null !== $types = $this->propertyTypeExtractor->getTypes($mappedClass, $name)) { return $this->typesCache[$key] = $types; } } @@ -742,6 +792,35 @@ } /** + * Returns the name of the property, getter, setter or constructor argument that the attribute refers to, as PropertyInfo lists it. + */ + private function getDeclaredAttributeName(string $class, string $attribute): ?string + { + if (property_exists($class, $attribute)) { + return $attribute; + } + + if (method_exists($class, '__construct')) { + foreach ((new \ReflectionMethod($class, '__construct'))->getParameters() as $parameter) { + if ($attribute === $parameter->name) { + return $attribute; + } + } + } + + foreach (['get', 'set'] as $prefix) { + if (method_exists($class, $prefix.$attribute)) { + // method names are case-insensitive, so the name is read from the method, the way ReflectionExtractor::getProperties() does + $name = substr((new \ReflectionMethod($class, $prefix.$attribute))->name, 3); + + return property_exists($class, lcfirst($name)) || (!property_exists($class, $name) && !preg_match('/^[A-Z]{2,}/', $name)) ? lcfirst($name) : $name; + } + } + + return null; + } + + /** * Sets an attribute and apply the name converter if necessary. */ private function updateData(array $data, string $attribute, mixed $attributeValue, string $class, ?string $format, array $context, ?array $attributesMetadata, ?ClassMetadataInterface $classMetadata): array @@ -838,35 +917,6 @@ if (null !== $discriminatorMapping = $this->classDiscriminatorResolver->getMappingForMappedObject($classOrObject)) { $allowedAttributes[] = $attributesAsString ? $discriminatorMapping->getTypeProperty() : new AttributeMetadata($discriminatorMapping->getTypeProperty()); } - - // A class name can be denormalized into any of the mapped classes, so their attributes - // are all allowed. The class of an object is known and the others cannot be read from it. - if (!\is_object($classOrObject) && null !== $discriminatorMapping = $this->classDiscriminatorResolver->getMappingForClass($classOrObject)) { - $attributes = []; - $mappedClasses = array_values($discriminatorMapping->getTypesMapping()); - $visited = [$classOrObject => true]; - - // Forcing extra attributes off makes the mapped classes return their attributes instead of false - $mappedContext = [self::ALLOW_EXTRA_ATTRIBUTES => false] + $context; - - while (null !== $mappedClass = array_shift($mappedClasses)) { - if (isset($visited[$mappedClass])) { - continue; - } - $visited[$mappedClass] = true; - - $attributes[] = parent::getAllowedAttributes($mappedClass, $mappedContext, $attributesAsString); - - // Mapped classes can declare a discriminator map of their own - if (null !== $nestedMapping = $this->classDiscriminatorResolver->getMappingForClass($mappedClass)) { - $typeProperty = $nestedMapping->getTypeProperty(); - $attributes[] = [$attributesAsString ? $typeProperty : new AttributeMetadata($typeProperty)]; - $mappedClasses = array_merge($mappedClasses, array_values($nestedMapping->getTypesMapping())); - } - } - - $allowedAttributes = array_merge($allowedAttributes, ...$attributes); - } } return $allowedAttributes; @@ -920,6 +970,7 @@ unset($context['cache_key']); // avoid artificially different keys unset($context['not_normalizable_value_exceptions']); // grows with every collected error unset($context['debug_trace_id']); // unique per call when the serializer is traced + unset($context['deserialization_path']); // differs for each item of a collection try { return hash('xxh128', $format.serialize([ @@ -975,7 +1026,15 @@ private function getMappedClass(array $data, string $class, ?string $format, array $context): string { if (null !== $object = $this->extractObjectToPopulate($class, $context, self::OBJECT_TO_POPULATE)) { - return $object::class; + $resolvedClass = ($this->objectClassResolver)($object); + + if (!$object instanceof $resolvedClass) { + // instantiateObject() populates the object only when it's an instance of the returned class + return $object::class; + } + + // Doctrine proxies declare public properties that the proxied class doesn't have + return $object::class === $resolvedClass && $object instanceof DoctrineProxy ? get_parent_class($object) : $resolvedClass; } if (!$mapping = $this->classDiscriminatorResolver?->getMappingForClass($class)) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.php 2026-11-25 09:18:34.000000000 +0000 @@ -190,7 +190,7 @@ protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []) { $setter = 'set'.$attribute; - $key = $object::class.':'.$setter; + $key = $object::class.':'.strtolower($setter); if (!isset(self::$setterAccessibleCache[$key])) { self::$setterAccessibleCache[$key] = method_exists($object, $setter) && \is_callable([$object, $setter]) && !(new \ReflectionMethod($object, $setter))->isStatic(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Normalizer/ObjectNormalizer.php 2026-11-25 09:18:34.000000000 +0000 @@ -134,6 +134,14 @@ */ protected function setAttributeValue(object $object, string $attribute, mixed $value, ?string $format = null, array $context = []) { + if ($writeInfo = $this->getWriteInfoInsteadOfGetterSetter($object, $attribute, $value, $context)) { + if (PropertyWriteInfo::TYPE_PROPERTY === $writeInfo->getType()) { + $object->{$writeInfo->getName()} = $value; + } + + return; + } + try { $this->propertyAccessor->setValue($object, $attribute, $value); } catch (NoSuchPropertyException) { @@ -183,7 +191,13 @@ return self::$isWritableCache[$cacheKey]; } - if ($this->propertyInfoExtractor->isWritable($class, $attribute, $context)) { + if (1000 < \count(self::$isWritableCache)) { + // stop memory leak if there are many keys + self::$isWritableCache = \array_slice(self::$isWritableCache, 500, null, true); + } + + // asking PropertyInfo about attributes that the class doesn't have would fill its cache with each unknown key + if (null !== ($name = $this->getWritableAttributeName($class, $attribute)) && $this->propertyInfoExtractor->isWritable($class, $name, $context)) { return self::$isWritableCache[$cacheKey] = true; } @@ -193,6 +207,25 @@ && (PropertyWriteInfo::TYPE_PROPERTY !== $writeType || !property_exists($class, $attribute)); } + /** + * Returns the name of the property or of the setter that the attribute refers to, as PropertyInfo lists it. + */ + private function getWritableAttributeName(string $class, string $attribute): ?string + { + if (property_exists($class, $attribute)) { + return $attribute; + } + + if (!method_exists($class, 'set'.$attribute)) { + return null; + } + + // method names are case-insensitive, so the name is read from the method, the way ReflectionExtractor::getProperties() does + $name = substr((new \ReflectionMethod($class, 'set'.$attribute))->name, 3); + + return property_exists($class, lcfirst($name)) || (!property_exists($class, $name) && !preg_match('/^[A-Z]{2,}/', $name)) ? lcfirst($name) : $name; + } + private function hasAttributeAccessorMethod(string $class, string $attribute): bool { $reflection = self::$reflectionCache[$class] ??= new \ReflectionClass($class); @@ -224,4 +257,31 @@ { return str_contains($attribute, '.') || str_contains($attribute, '['); } + + /** + * Returns how to write the attribute when PropertyAccessor would call a method named after it, like name($value), that isAllowedAttribute() doesn't account for. + */ + private function getWriteInfoInsteadOfGetterSetter(object $object, string $attribute, mixed $value, array $context): ?PropertyWriteInfo + { + $method = str_replace(['_', ' '], '', $attribute); + + if (!method_exists($object, $method) || !(new \ReflectionMethod($object, $method))->getNumberOfParameters()) { + return null; + } + + $context = ['enable_constructor_extraction' => false, 'enable_adder_remover_extraction' => is_iterable($value)] + array_intersect_key($context, ['enable_getter_setter_extraction' => true, 'enable_magic_methods_extraction' => true]); + $writeInfo = $this->writeInfoExtractor->getWriteInfo($object::class, $attribute, ['enable_getter_setter_extraction' => true] + $context); + + if (PropertyWriteInfo::TYPE_METHOD !== $writeInfo->getType()) { + return null; + } + + $writeInfoWithoutGetterSetter = $this->writeInfoExtractor->getWriteInfo($object::class, $attribute, $context); + + if (PropertyWriteInfo::TYPE_METHOD === $writeInfoWithoutGetterSetter->getType() && $writeInfo->getName() === $writeInfoWithoutGetterSetter->getName()) { + return null; + } + + return $writeInfoWithoutGetterSetter; + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Serializer\Encoder\CsvEncoder; +use Symfony\Component\Serializer\Exception\NotEncodableValueException; use Symfony\Component\Serializer\Exception\UnexpectedValueException; /** @@ -662,6 +663,53 @@ )); } + public function testDecodeHeadersNestedUpToTheMaximumDepth() + { + $item = 'a'; + for ($i = 0; $i < 512; ++$i) { + $item = ['k' => $item]; + } + + $this->assertSame([$item], $this->encoder->decode(str_repeat('k.', 511)."k\na\n", 'csv')); + } + + public function testDecodeRejectsHeadersNestedDeeperThanTheMaximumDepth() + { + $this->expectException(NotEncodableValueException::class); + $this->expectExceptionMessage('CSV headers cannot be nested more than 512 levels deep.'); + + $this->encoder->decode('foo,'.str_repeat('k.', 512)."k\na,b\n", 'csv'); + } + + public function testDecodeNestedHeadersOnManyRows() + { + $rows = $this->encoder->decode("a.b.c,a.b.d,e.f.g,h\n".str_repeat(",,,\n", 10000), 'csv'); + + $this->assertCount(10000, $rows); + $this->assertSame(['a' => ['b' => ['c' => '', 'd' => '']], 'e' => ['f' => ['g' => '']], 'h' => ''], $rows[9999]); + } + + public function testDecodeRejectsRowsCreatingTooManyArraysForTheSizeOfTheData() + { + $this->expectException(NotEncodableValueException::class); + $this->expectExceptionMessage('CSV headers are nested too deeply for the size of the data.'); + + $this->encoder->decode(str_repeat('k.', 511)."k\n".str_repeat(str_repeat('a', 39)."\n", 100), 'csv'); + } + + public function testDecodeRejectsRowsWalkingTooManyLevelsForTheSizeOfTheData() + { + $this->expectException(NotEncodableValueException::class); + $this->expectExceptionMessage('CSV headers are nested too deeply for the size of the data.'); + + $headers = []; + for ($i = 0; $i < 64; ++$i) { + $headers[] = str_repeat('k.', 63).$i; + } + + $this->encoder->decode(implode(',', $headers)."\n".str_repeat(str_repeat(',', 63)."\n", 100), 'csv'); + } + public function testDecodeCustomSettings() { $this->encoder = new CsvEncoder([ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/NameConverter/MetadataAwareNameConverterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -200,6 +200,20 @@ $nameConverter->normalize('foo', NestedPathAndName::class); } + public function testNormalizeCacheSizeLimit() + { + $nameConverter = new MetadataAwareNameConverter(new ClassMetadataFactory(new AttributeLoader())); + + for ($i = 0; $i < 2000; ++$i) { + $this->assertSame('unknown'.$i, $nameConverter->normalize('unknown'.$i, OtherSerializedNameDummy::class)); + } + $this->assertSame('quux', $nameConverter->normalize('qux', OtherSerializedNameDummy::class)); + + $normalizeCache = (new \ReflectionProperty(MetadataAwareNameConverter::class, 'normalizeCache'))->getValue($nameConverter); + + $this->assertLessThanOrEqual(1001, \count($normalizeCache[OtherSerializedNameDummy::class])); + } + public function testNormalizeAndDenormalizeAfterAConverterWithoutMapping() { $attributes = new MetadataAwareNameConverter(new ClassMetadataFactory(new AttributeLoader())); @@ -223,6 +237,34 @@ $this->assertSame('foo', $attributes->normalize('foo', ScalarDummy::class)); $this->assertSame('yaml_foo', $attributes->denormalize('yaml_foo', ScalarDummy::class)); } + + public function testDenormalizeDoesNotCacheUnknownNames() + { + $nameConverter = new MetadataAwareNameConverter(new ClassMetadataFactory(new YamlFileLoader(__DIR__.'/../Fixtures/serialized-name-mapping.yml'))); + + for ($i = 0; $i < 2000; ++$i) { + $this->assertSame('unknown'.$i, $nameConverter->denormalize('unknown'.$i, Dummy::class)); + } + $this->assertSame('foo', $nameConverter->denormalize('yaml_foo', Dummy::class)); + $this->assertSame('foo', $nameConverter->denormalize('yaml_foo', Dummy::class)); + + $denormalizeCache = \Closure::bind(fn () => $this->denormalizeCache, $nameConverter, MetadataAwareNameConverter::class)(); + + $this->assertSame(1, array_sum(array_map('count', $denormalizeCache))); + } + + public function testNormalizeDoesNotCacheStdClassProperties() + { + $nameConverter = new MetadataAwareNameConverter(new ClassMetadataFactory(new YamlFileLoader(__DIR__.'/../Fixtures/serialized-name-mapping.yml'))); + + for ($i = 0; $i < 2000; ++$i) { + $this->assertSame('property'.$i, $nameConverter->normalize('property'.$i, \stdClass::class)); + } + + $normalizeCache = \Closure::bind(fn () => $this->normalizeCache, $nameConverter, MetadataAwareNameConverter::class)(); + + $this->assertSame([], $normalizeCache); + } } class NestedPathAndName diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -11,6 +11,7 @@ namespace Symfony\Component\Serializer\Tests\Normalizer; +use Doctrine\Persistence\Proxy; use PHPUnit\Framework\TestCase; use Symfony\Component\PropertyAccess\PropertyPath; use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; @@ -19,6 +20,8 @@ use Symfony\Component\PropertyInfo\Type; use Symfony\Component\Serializer\Attribute\Context; use Symfony\Component\Serializer\Attribute\DiscriminatorMap; +use Symfony\Component\Serializer\Attribute\Groups; +use Symfony\Component\Serializer\Attribute\Ignore; use Symfony\Component\Serializer\Attribute\SerializedName; use Symfony\Component\Serializer\Attribute\SerializedPath; use Symfony\Component\Serializer\Debug\TraceableSerializer; @@ -37,6 +40,7 @@ use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader; use Symfony\Component\Serializer\NameConverter\CamelCaseToSnakeCaseNameConverter; use Symfony\Component\Serializer\NameConverter\MetadataAwareNameConverter; +use Symfony\Component\Serializer\NameConverter\NameConverterInterface; use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer; use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer; @@ -44,6 +48,7 @@ use Symfony\Component\Serializer\Normalizer\CustomNormalizer; use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; +use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; use Symfony\Component\Serializer\Normalizer\PropertyNormalizer; use Symfony\Component\Serializer\Serializer; @@ -52,6 +57,7 @@ use Symfony\Component\Serializer\Tests\Fixtures\Attributes\AbstractDummy; use Symfony\Component\Serializer\Tests\Fixtures\Attributes\AbstractDummyFirstChild; use Symfony\Component\Serializer\Tests\Fixtures\Attributes\AbstractDummySecondChild; +use Symfony\Component\Serializer\Tests\Fixtures\Attributes\SerializedNameDummy; use Symfony\Component\Serializer\Tests\Fixtures\DummyFirstChildQuux; use Symfony\Component\Serializer\Tests\Fixtures\DummyMessageInterface; use Symfony\Component\Serializer\Tests\Fixtures\DummyMessageNumberFour; @@ -654,6 +660,279 @@ $this->assertInstanceOf(AbstractDummySecondChild::class, $denormalizedData); } + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeDiscriminatorMapRespectsIgnoreOnTheMappedClass(AbstractObjectNormalizer $normalizer) + { + $data = ['type' => 'restricted', 'name' => 'foo', 'verified' => true, 'secret' => 'leaked']; + + $object = $normalizer->denormalize($data, RestrictedDiscriminatorBase::class); + + $this->assertInstanceOf(RestrictedDiscriminatorChild::class, $object); + $this->assertSame('foo', $object->getName()); + $this->assertFalse($object->getVerified()); + $this->assertSame('default', $object->getSecret()); + + try { + $normalizer->denormalize($data, RestrictedDiscriminatorBase::class, null, [AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false]); + $this->fail(ExtraAttributesException::class.' expected'); + } catch (ExtraAttributesException $e) { + $this->assertEqualsCanonicalizing(['verified', 'secret'], $e->getExtraAttributes()); + } + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeDiscriminatorMapRespectsGroupsOfTheMappedClass(AbstractObjectNormalizer $normalizer) + { + $context = [AbstractNormalizer::GROUPS => ['write']]; + + $restricted = $normalizer->denormalize(['type' => 'restricted', 'name' => 'foo', 'role' => 'admin'], RestrictedDiscriminatorBase::class, null, $context); + + $this->assertInstanceOf(RestrictedDiscriminatorChild::class, $restricted); + $this->assertSame('foo', $restricted->getName()); + $this->assertSame('user', $restricted->getRole()); + + $open = $normalizer->denormalize(['type' => 'open', 'name' => 'foo', 'role' => 'admin'], RestrictedDiscriminatorBase::class, null, $context); + + $this->assertInstanceOf(OpenDiscriminatorChild::class, $open); + $this->assertSame('admin', $open->getRole()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeObjectToPopulateRespectsIgnoreOnItsClass(AbstractObjectNormalizer $normalizer) + { + $object = $normalizer->denormalize(['name' => 'foo', 'verified' => true], RestrictedDiscriminatorBase::class, null, [ + AbstractNormalizer::OBJECT_TO_POPULATE => $child = new RestrictedDiscriminatorChild(), + ]); + + $this->assertSame($child, $object); + $this->assertSame('foo', $object->getName()); + $this->assertFalse($object->getVerified()); + + $object = $normalizer->denormalize(['verified' => true], UnmappedParent::class, null, [ + AbstractNormalizer::OBJECT_TO_POPULATE => $child = new UnmappedChildWithIgnoredAttribute(), + ]); + + $this->assertSame($child, $object); + $this->assertFalse($object->getVerified()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeNestedDiscriminatorMapRespectsIgnoreOnTheMappedClass(AbstractObjectNormalizer $normalizer) + { + $data = ['type' => 'middle', 'nested_type' => 'leaf', 'name' => 'foo', 'verified' => true]; + + $object = $normalizer->denormalize($data, NestedRestrictedDiscriminatorBase::class); + + $this->assertInstanceOf(NestedRestrictedDiscriminatorLeaf::class, $object); + $this->assertSame('foo', $object->getName()); + $this->assertFalse($object->getVerified()); + + $object = $normalizer->denormalize(['type' => 'middle', 'nested_type' => 'leaf', 'name' => 'foo'], NestedRestrictedDiscriminatorBase::class, null, [AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false]); + + $this->assertInstanceOf(NestedRestrictedDiscriminatorLeaf::class, $object); + $this->assertSame('foo', $object->getName()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeConcreteDiscriminatorMapRootIgnoresAttributesOfOtherMappedClasses(AbstractObjectNormalizer $normalizer) + { + $root = $normalizer->denormalize(['type' => 'root', 'role' => 'admin'], ConcreteRestrictedDiscriminatorRoot::class); + + $this->assertInstanceOf(ConcreteRestrictedDiscriminatorRoot::class, $root); + $this->assertSame('user', $root->getRole()); + + $other = $normalizer->denormalize(['type' => 'other', 'role' => 'admin'], ConcreteRestrictedDiscriminatorRoot::class); + + $this->assertInstanceOf(ConcreteRestrictedDiscriminatorOther::class, $other); + $this->assertSame('admin', $other->getRole()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeDeepObjectToPopulateRespectsIgnoreOnItsClass(AbstractObjectNormalizer $normalizer) + { + $normalizer->setSerializer(new Serializer([$normalizer])); + $holder = new RestrictedDiscriminatorHolder(); + $holder->setNotification($child = new RestrictedDiscriminatorChild()); + + $normalizer->denormalize(['notification' => ['name' => 'foo', 'verified' => true]], RestrictedDiscriminatorHolder::class, null, [ + AbstractNormalizer::OBJECT_TO_POPULATE => $holder, + AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE => true, + ]); + + $this->assertSame($child, $holder->getNotification()); + $this->assertSame('foo', $child->getName()); + $this->assertFalse($child->getVerified()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeObjectToPopulateIgnoresThePropertiesOfDoctrineProxies(AbstractObjectNormalizer $normalizer) + { + if (!interface_exists(Proxy::class)) { + $this->markTestSkipped('The "doctrine/persistence" package is not installed.'); + } + + $proxy = new class extends RestrictedDiscriminatorChild implements Proxy { + public $__initializer__; + public $__cloner__; + public $__isInitialized__ = false; + + public function __load(): void + { + } + + public function __isInitialized(): bool + { + return $this->__isInitialized__; + } + }; + + $object = $normalizer->denormalize(['name' => 'foo', '__initializer__' => 'bar', '__cloner__' => 'bar', '__isInitialized__' => true], RestrictedDiscriminatorBase::class, null, [ + AbstractNormalizer::OBJECT_TO_POPULATE => $proxy, + ]); + + $this->assertSame($proxy, $object); + $this->assertSame('foo', $proxy->getName()); + $this->assertNull($proxy->__initializer__); + $this->assertNull($proxy->__cloner__); + $this->assertFalse($proxy->__isInitialized__); + } + + /** + * @dataProvider provideNormalizersWithObjectClassResolver + */ + public function testDenormalizeObjectToPopulateComputesTheAllowedAttributesForTheResolvedClass(AbstractObjectNormalizer $normalizer) + { + $object = $normalizer->denormalize(['name' => 'foo', 'role' => 'admin'], RestrictedDiscriminatorBase::class, null, [ + AbstractNormalizer::GROUPS => ['write'], + AbstractNormalizer::OBJECT_TO_POPULATE => $child = new RestrictedDiscriminatorChildWithWritableRole(), + ]); + + $this->assertSame($child, $object); + $this->assertSame('foo', $child->getName()); + $this->assertSame('user', $child->getRole()); + } + + /** + * @dataProvider provideNormalizersWithObjectClassResolver + */ + public function testDenormalizeObjectToPopulateIgnoresAResolvedClassItIsNotAnInstanceOf(AbstractObjectNormalizer $normalizer) + { + $object = $normalizer->denormalize(['name' => 'foo'], RestrictedDiscriminatorBase::class, null, [ + AbstractNormalizer::OBJECT_TO_POPULATE => $child = new OpenDiscriminatorChild(), + ]); + + $this->assertSame($child, $object); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeNestedDiscriminatorMapPassesTheTypePropertiesToTheConstructor(AbstractObjectNormalizer $normalizer) + { + $data = ['type' => 'middle', 'nested_type' => 'leaf', 'name' => 'foo']; + + $object = $normalizer->denormalize($data, NestedConstructorDiscriminatorBase::class, null, [AbstractNormalizer::GROUPS => ['write']]); + + $this->assertInstanceOf(NestedConstructorDiscriminatorLeaf::class, $object); + $this->assertSame('middle', $object->getType()); + $this->assertSame('foo', $object->getName()); + + $object = $normalizer->denormalize($data, NestedConstructorDiscriminatorBase::class, null, [AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false]); + + $this->assertSame('middle', $object->getType()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeIntoAMappedClassIgnoresTheTypePropertiesOfOuterMaps(AbstractObjectNormalizer $normalizer) + { + $object = $normalizer->denormalize(['type' => 'client', 'name' => 'foo'], NestedRestrictedDiscriminatorLeafWithIgnoredType::class); + + $this->assertSame('server', $object->getType()); + $this->assertSame('foo', $object->getName()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeDiscriminatorMapDoesNotWriteAnIgnoredTypeProperty(AbstractObjectNormalizer $normalizer) + { + $object = $normalizer->denormalize(['type' => 'middle', 'nested_type' => 'leaf_with_ignored_type', 'name' => 'foo'], NestedRestrictedDiscriminatorBase::class); + + $this->assertInstanceOf(NestedRestrictedDiscriminatorLeafWithIgnoredType::class, $object); + $this->assertSame('server', $object->getType()); + $this->assertSame('foo', $object->getName()); + + $object = $normalizer->denormalize(['type' => 'client', 'name' => 'foo'], NestedRestrictedDiscriminatorBase::class, null, [ + AbstractNormalizer::OBJECT_TO_POPULATE => $leaf = new NestedRestrictedDiscriminatorLeafWithIgnoredType(), + ]); + + $this->assertSame($leaf, $object); + $this->assertSame('server', $object->getType()); + $this->assertSame('foo', $object->getName()); + } + + /** + * @dataProvider provideDiscriminatorAwareNormalizers + */ + public function testDenormalizeDiscriminatorMapDoesNotWriteATypePropertyOfOtherGroups(AbstractObjectNormalizer $normalizer) + { + $data = ['type' => 'admin_type', 'name' => 'foo']; + $context = [AbstractNormalizer::GROUPS => ['write'], AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false]; + + $object = $normalizer->denormalize($data, RestrictedDiscriminatorBase::class, null, $context); + + $this->assertInstanceOf(AdminTypeDiscriminatorChild::class, $object); + $this->assertSame('server', $object->getType()); + $this->assertSame('foo', $object->getName()); + + $object = $normalizer->denormalize($data, RestrictedDiscriminatorBase::class, null, [AbstractNormalizer::GROUPS => ['write', 'admin']] + $context); + + $this->assertSame('admin_type', $object->getType()); + } + + public static function provideDiscriminatorAwareNormalizers(): iterable + { + $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); + $discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory); + $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); + + yield 'ObjectNormalizer' => [new ObjectNormalizer($classMetadataFactory, null, null, $extractor, $discriminator)]; + yield 'PropertyNormalizer' => [new PropertyNormalizer($classMetadataFactory, null, $extractor, $discriminator)]; + yield 'GetSetMethodNormalizer' => [new GetSetMethodNormalizer($classMetadataFactory, null, $extractor, $discriminator)]; + } + + public static function provideNormalizersWithObjectClassResolver(): iterable + { + $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); + $discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory); + $extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]); + $objectClassResolver = static fn (object $object): string => match (true) { + $object instanceof RestrictedDiscriminatorChildWithWritableRole => RestrictedDiscriminatorChild::class, + $object instanceof OpenDiscriminatorChild => \stdClass::class, + default => $object::class, + }; + + yield 'ObjectNormalizer' => [new ObjectNormalizer($classMetadataFactory, null, null, $extractor, $discriminator, $objectClassResolver)]; + yield 'PropertyNormalizer' => [new PropertyNormalizer($classMetadataFactory, null, $extractor, $discriminator, $objectClassResolver)]; + yield 'GetSetMethodNormalizer' => [new GetSetMethodNormalizer($classMetadataFactory, null, $extractor, $discriminator, $objectClassResolver)]; + } + public function testDenormalizeBasicTypePropertiesFromXml() { $denormalizer = $this->getDenormalizerForObjectWithBasicProperties(); @@ -1037,6 +1316,39 @@ $this->assertSame('plain', $actual->children); } + public function testDenormalizeObjectIntoListOfObjects() + { + $serializer = new Serializer([new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]))]); + + try { + $serializer->denormalize(['children' => new \DateTimeImmutable()], DummyWithListOfChildren::class); + $this->fail('A NotNormalizableValueException should have been thrown.'); + } catch (NotNormalizableValueException $e) { + $this->assertSame(\sprintf('The type of the "children" attribute for class "%s" must be one of "%s[]" ("DateTimeImmutable" given).', DummyWithListOfChildren::class, DummyChildWithConstructor::class), $e->getMessage()); + } + + $this->expectException(NotNormalizableValueException::class); + $this->expectExceptionMessage(\sprintf('The type of the "children" attribute for class "%s" must be one of "%s[]" ("stdClass" given).', DummyWithListOfChildren::class, DummyChildWithConstructor::class)); + + $serializer->denormalize(['children' => (object) ['bar' => 'first']], DummyWithListOfChildren::class); + } + + public function testDenormalizeObjectIntoObjectCollectionOfObjects() + { + $serializer = new Serializer([new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]))]); + $children = new \ArrayObject([new DummyChildWithConstructor('first')]); + + $this->assertSame($children, $serializer->denormalize(['children' => $children], DummyWithArrayObjectOfChildren::class)->children); + } + + public function testDenormalizeArrayIntoListOfObjects() + { + $serializer = new Serializer([new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]))]); + $actual = $serializer->denormalize(['children' => [['bar' => 'first']]], DummyWithListOfChildren::class); + + $this->assertEquals([new DummyChildWithConstructor('first')], $actual->children); + } + /** * @dataProvider provideScalarsForUnionWithObjectAndScalarTypes */ @@ -1252,6 +1564,97 @@ $this->assertFalse($normalizer->childContextCacheKey); } + public function testCollectionItemsShareTheSameCacheKey() + { + $nameConverter = new class implements NameConverterInterface { + public $cacheKeys = []; + + public function normalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string + { + return $propertyName; + } + + public function denormalize(string $propertyName, ?string $class = null, ?string $format = null, array $context = []): string + { + $this->cacheKeys[$context['cache_key']] = true; + + return $propertyName; + } + }; + + $serializer = new Serializer([new ArrayDenormalizer(), new ObjectNormalizer(null, $nameConverter)]); + $serializer->denormalize(['first' => ['foo' => 'a'], 'second' => ['foo' => 'b'], 'third' => ['foo' => 'c']], Dummy::class.'[]'); + + $this->assertCount(1, $nameConverter->cacheKeys); + } + + public function testNestedObjectsShareTheCachesOfTheNameConverter() + { + $classMetadataFactory = new ClassMetadataFactory(new AttributeLoader()); + $nameConverter = new MetadataAwareNameConverter($classMetadataFactory); + $serializer = new Serializer([new ObjectNormalizer($classMetadataFactory, $nameConverter, null, new PhpDocExtractor())]); + + $data = ['baz' => 'foo0']; + for ($i = 1; $i < 100; ++$i) { + $data = ['baz' => 'foo'.$i, 'child' => $data]; + } + + $object = $serializer->denormalize($data, SerializedNameDummy::class); + + for ($i = 99; $i >= 0; --$i) { + $this->assertSame('foo'.$i, $object->foo); + $object = $object->child; + } + + $caches = \Closure::bind(fn () => [$this->denormalizeCache, $this->attributesMetadataCache], $nameConverter, MetadataAwareNameConverter::class)(); + + foreach ($caches as $cache) { + $this->assertCount(1, $cache); + } + } + + public function testAttributesCacheSizeLimit() + { + $createTree = function (int $depth) use (&$createTree) { + $node = new Dummy(); + + if ($depth) { + $node->foo = $createTree($depth - 1); + $node->bar = $createTree($depth - 1); + } + + return $node; + }; + $normalizer = new ObjectNormalizer(); + $serializer = new Serializer([$normalizer]); + + $data = $serializer->normalize($createTree(10)); + + $this->assertNull($data['bar']['foo']['bar']['foo']['bar']['foo']['bar']['foo']['bar']['foo']['bar']); + + $attributesCache = \Closure::bind(fn () => $this->attributesCache, $normalizer, AbstractObjectNormalizer::class)(); + + $this->assertLessThanOrEqual(1001, \count($attributesCache)); + } + + public function testTypesCacheSizeLimit() + { + $object = new class { + public function __set(string $name, $value): void + { + } + }; + $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); + + for ($i = 0; $i < 2000; ++$i) { + $normalizer->denormalize(['attribute'.$i => 'value'], $object::class, null, ['object_to_populate' => $object]); + } + + $typesCache = \Closure::bind(fn () => $this->typesCache, $normalizer, AbstractObjectNormalizer::class)(); + + $this->assertLessThanOrEqual(1001, \count($typesCache)); + } + public function testDenormalizeXmlScalar() { $normalizer = new class extends AbstractObjectNormalizer { @@ -1641,6 +2044,26 @@ public array|string $children = []; } +class DummyWithListOfChildren +{ + /** + * @param list<DummyChildWithConstructor> $children + */ + public function __construct(public array $children) + { + } +} + +class DummyWithArrayObjectOfChildren +{ + /** + * @param \ArrayObject<int, DummyChildWithConstructor> $children + */ + public function __construct(public \ArrayObject $children) + { + } +} + class XmlScalarDummy { #[SerializedName('#')] @@ -1848,3 +2271,266 @@ } } } + +#[DiscriminatorMap(typeProperty: 'type', mapping: [ + 'restricted' => RestrictedDiscriminatorChild::class, + 'open' => OpenDiscriminatorChild::class, + 'admin_type' => AdminTypeDiscriminatorChild::class, +])] +abstract class RestrictedDiscriminatorBase +{ + #[Groups(['write'])] + private string $name = ''; + + public function getName(): string + { + return $this->name; + } + + public function setName(string $name): void + { + $this->name = $name; + } +} + +class RestrictedDiscriminatorChild extends RestrictedDiscriminatorBase +{ + #[Ignore] + private bool $verified = false; + + private string $role = 'user'; + + public function __construct( + #[Ignore] + private string $secret = 'default', + ) { + } + + public function getVerified(): bool + { + return $this->verified; + } + + public function setVerified(bool $verified): void + { + $this->verified = $verified; + } + + public function getRole(): string + { + return $this->role; + } + + public function setRole(string $role): void + { + $this->role = $role; + } + + public function getSecret(): string + { + return $this->secret; + } +} + +class RestrictedDiscriminatorChildWithWritableRole extends RestrictedDiscriminatorChild +{ + #[Groups(['write'])] + public function setRole(string $role): void + { + parent::setRole($role); + } +} + +class OpenDiscriminatorChild extends RestrictedDiscriminatorBase +{ + #[Groups(['write'])] + private string $role = 'user'; + + public function getRole(): string + { + return $this->role; + } + + public function setRole(string $role): void + { + $this->role = $role; + } +} + +class AdminTypeDiscriminatorChild extends RestrictedDiscriminatorBase +{ + #[Groups(['admin'])] + private string $type = 'server'; + + public function getType(): string + { + return $this->type; + } + + public function setType(string $type): void + { + $this->type = $type; + } +} + +class UnmappedParent +{ +} + +class UnmappedChildWithIgnoredAttribute extends UnmappedParent +{ + #[Ignore] + private bool $verified = false; + + public function getVerified(): bool + { + return $this->verified; + } + + public function setVerified(bool $verified): void + { + $this->verified = $verified; + } +} + +#[DiscriminatorMap(typeProperty: 'type', mapping: [ + 'middle' => NestedRestrictedDiscriminatorMiddle::class, +])] +abstract class NestedRestrictedDiscriminatorBase +{ + private string $name = ''; + + public function getName(): string + { + return $this->name; + } + + public function setName(string $name): void + { + $this->name = $name; + } +} + +#[DiscriminatorMap(typeProperty: 'nested_type', mapping: [ + 'leaf' => NestedRestrictedDiscriminatorLeaf::class, + 'leaf_with_ignored_type' => NestedRestrictedDiscriminatorLeafWithIgnoredType::class, +])] +abstract class NestedRestrictedDiscriminatorMiddle extends NestedRestrictedDiscriminatorBase +{ +} + +class NestedRestrictedDiscriminatorLeaf extends NestedRestrictedDiscriminatorMiddle +{ + #[Ignore] + private bool $verified = false; + + public function getVerified(): bool + { + return $this->verified; + } + + public function setVerified(bool $verified): void + { + $this->verified = $verified; + } +} + +class RestrictedDiscriminatorHolder +{ + private ?RestrictedDiscriminatorBase $notification = null; + + public function getNotification(): ?RestrictedDiscriminatorBase + { + return $this->notification; + } + + public function setNotification(?RestrictedDiscriminatorBase $notification): void + { + $this->notification = $notification; + } +} + +class NestedRestrictedDiscriminatorLeafWithIgnoredType extends NestedRestrictedDiscriminatorMiddle +{ + #[Ignore] + private string $type = 'server'; + + public function getType(): string + { + return $this->type; + } + + public function setType(string $type): void + { + $this->type = $type; + } +} + +#[DiscriminatorMap(typeProperty: 'type', mapping: [ + 'middle' => NestedConstructorDiscriminatorMiddle::class, +])] +abstract class NestedConstructorDiscriminatorBase +{ +} + +#[DiscriminatorMap(typeProperty: 'nested_type', mapping: [ + 'leaf' => NestedConstructorDiscriminatorLeaf::class, +])] +abstract class NestedConstructorDiscriminatorMiddle extends NestedConstructorDiscriminatorBase +{ +} + +class NestedConstructorDiscriminatorLeaf extends NestedConstructorDiscriminatorMiddle +{ + public function __construct( + private string $type, + #[Groups(['write'])] + private string $name = '', + ) { + } + + public function getType(): string + { + return $this->type; + } + + public function getName(): string + { + return $this->name; + } +} + +#[DiscriminatorMap(typeProperty: 'type', mapping: [ + 'root' => ConcreteRestrictedDiscriminatorRoot::class, + 'other' => ConcreteRestrictedDiscriminatorOther::class, +])] +class ConcreteRestrictedDiscriminatorRoot +{ + #[Ignore] + private string $role = 'user'; + + public function getRole(): string + { + return $this->role; + } + + public function setRole(string $role): void + { + $this->role = $role; + } +} + +class ConcreteRestrictedDiscriminatorOther +{ + private string $role = 'user'; + + public function getRole(): string + { + return $this->role; + } + + public function setRole(string $role): void + { + $this->role = $role; + } +} diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -469,6 +469,18 @@ $this->assertEquals('bar', $obj->getFoo()); } + public function testSetterCacheIgnoresCase() + { + foreach (['foo', 'Foo', 'FOO', 'fOo'] as $attribute) { + $this->assertSame('bar', $this->normalizer->denormalize([$attribute => 'bar'], GetSetDummy::class)->getFoo()); + } + + $setterAccessibleCache = \Closure::bind(static fn () => self::$setterAccessibleCache, null, GetSetMethodNormalizer::class)(); + $keys = array_filter(array_keys($setterAccessibleCache), static fn ($key) => 0 === strcasecmp($key, GetSetDummy::class.':setFoo')); + + $this->assertCount(1, $keys); + } + public function testHasGetterDenormalize() { $obj = $this->normalizer->denormalize(['foo' => true], ObjectWithHasGetterDummy::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/JsonSerializableNormalizerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -58,7 +58,6 @@ public function testCircularNormalize() { - $this->expectException(CircularReferenceException::class); $normalizer = new JsonSerializableNormalizer(null, null, [JsonSerializableNormalizer::CIRCULAR_REFERENCE_LIMIT => 1]); $serializer = $this->createMock(JsonSerializerNormalizer::class); @@ -73,7 +72,8 @@ ; $normalizer->setSerializer($serializer); - $this->assertEquals('string_object', $normalizer->normalize(new JsonSerializableDummy())); + $this->expectException(CircularReferenceException::class); + $normalizer->normalize(new JsonSerializableDummy()); } protected function getNormalizerForCircularReference(array $defaultContext): JsonSerializableNormalizer diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,12 +13,14 @@ use PHPStan\PhpDocParser\Parser\PhpDocParser; use PHPUnit\Framework\TestCase; +use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\PropertyAccess\Exception\UnexpectedTypeException; use Symfony\Component\PropertyAccess\PropertyAccessorBuilder; use Symfony\Component\PropertyAccess\PropertyAccessorInterface; use Symfony\Component\PropertyInfo\Extractor\PhpDocExtractor; use Symfony\Component\PropertyInfo\Extractor\PhpStanExtractor; use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor; +use Symfony\Component\PropertyInfo\PropertyInfoCacheExtractor; use Symfony\Component\PropertyInfo\PropertyInfoExtractor; use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface; use Symfony\Component\Serializer\Attribute\DiscriminatorMap; @@ -700,6 +702,70 @@ return $normalizer; } + public function testDeepObjectToPopulateDoesNotCallMethodNamedAfterUntypedAttribute() + { + $object = new class { + public $data = []; + public $loggedOut = false; + + public function __set($name, $value) + { + $this->data[$name] = $value; + } + + public function logout() + { + $this->loggedOut = true; + } + }; + + $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); + new Serializer([$normalizer]); + $normalizer->denormalize(['logout' => ['foo' => 'bar']], $object::class, null, [ + 'object_to_populate' => $object, + 'deep_object_to_populate' => true, + ]); + + $this->assertFalse($object->loggedOut); + $this->assertSame(['logout' => ['foo' => 'bar']], $object->data); + } + + public function testDeepObjectToPopulateReadsThroughMethodNamedAfterTypedAttribute() + { + $inner = new ObjectInner(); + $inner->bar = 'bar'; + + $object = new class($inner) { + private $inner; + + public function __construct(ObjectInner $inner) + { + $this->inner = $inner; + } + + public function inner(): ObjectInner + { + return $this->inner; + } + + public function setInner(ObjectInner $inner): void + { + $this->inner = $inner; + } + }; + + $normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor()); + new Serializer([$normalizer]); + $normalizer->denormalize(['inner' => ['foo' => 'foo']], $object::class, null, [ + 'object_to_populate' => $object, + 'deep_object_to_populate' => true, + ]); + + $this->assertSame($inner, $object->inner()); + $this->assertSame('foo', $inner->foo); + $this->assertSame('bar', $inner->bar); + } + // skip null protected function getNormalizerForSkipNullValues(): ObjectNormalizer @@ -789,6 +855,64 @@ $this->assertSame(42, $obj->params['param2']); } + public function testDenormalizeDoesNotLookUpUnknownAttributes() + { + $cache = new ArrayAdapter(); + $propertyInfo = new PropertyInfoCacheExtractor(new PropertyInfoExtractor([], [new ReflectionExtractor()], [], [new ReflectionExtractor()]), $cache); + $normalizer = new ObjectNormalizer(null, null, null, $propertyInfo, null, null, [], $propertyInfo); + + $normalizer->denormalize(['foo' => 'foo'], ObjectDummy::class); + $cachedValues = $cache->getValues(); + + $obj = $normalizer->denormalize(['foo' => 'foo', 'foo_' => 'bar', 'unknown1' => 1, 'unknown2' => 2], ObjectDummy::class); + + $this->assertSame('bar', $obj->getFoo()); + $this->assertSame($cachedValues, $cache->getValues()); + } + + public function testDenormalizeDoesNotLookUpMagicAttributes() + { + $object = new class { + public $foo; + public $values = []; + + public function __set(string $name, $value): void + { + $this->values[$name] = $value; + } + }; + $cache = new ArrayAdapter(); + $propertyInfo = new PropertyInfoCacheExtractor(new PropertyInfoExtractor([], [new ReflectionExtractor()], [], [new ReflectionExtractor()]), $cache); + $normalizer = new ObjectNormalizer(null, null, null, $propertyInfo, null, null, [], $propertyInfo); + + $normalizer->denormalize(['foo' => 'foo'], $object::class, null, ['object_to_populate' => $object]); + $cachedValues = $cache->getValues(); + + $normalizer->denormalize(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'], $object::class, null, ['object_to_populate' => $object]); + + $this->assertSame(['bar' => 'bar', 'baz' => 'baz'], $object->values); + $this->assertSame($cachedValues, $cache->getValues()); + } + + public function testDenormalizeLooksUpCaseVariantsByTheirDeclaredName() + { + $cache = new ArrayAdapter(); + $propertyInfo = new PropertyInfoCacheExtractor(new PropertyInfoExtractor([], [new ReflectionExtractor()], [], [new ReflectionExtractor()]), $cache); + $serializer = new Serializer([new ObjectNormalizer(null, null, null, $propertyInfo, null, null, [], $propertyInfo)]); + + $serializer->denormalize(['inner' => ['foo' => 'foo']], ObjectOuter::class); + $cachedValues = $cache->getValues(); + + foreach (['INNER', 'Inner', 'iNnEr'] as $attribute) { + $obj = $serializer->denormalize([$attribute => ['foo' => 'foo']], ObjectOuter::class); + + $this->assertInstanceOf(ObjectInner::class, $obj->getInner()); + $this->assertSame('foo', $obj->getInner()->foo); + } + + $this->assertSame($cachedValues, $cache->getValues()); + } + public function testNoTraversableSupport() { $this->assertFalse($this->normalizer->supportsNormalization(new \ArrayObject())); @@ -828,6 +952,15 @@ }])); } + public function testIsWritableCacheSizeLimit() + { + for ($i = 0; $i < 2000; ++$i) { + $this->normalizer->denormalize(['unknown'.$i => 'value'], ObjectDummy::class); + } + + $this->assertLessThanOrEqual(1001, \count((new \ReflectionProperty(ObjectNormalizer::class, 'isWritableCache'))->getValue())); + } + public function testThrowUnexpectedValueException() { $this->expectException(UnexpectedValueException::class); @@ -1832,6 +1965,140 @@ $this->assertSame('FOO', $denormalized->foo); $this->assertSame('hidden', $denormalized->hidden); } + + public function testDenormalizeIgnoresUndeclaredPropertyPathIndexWithMagicSetter() + { + $object = new class { + public $values = []; + + public function __set($name, $value) + { + } + }; + + (new ObjectNormalizer())->denormalize(['values[first]' => 'foo'], $object::class, 'json', [ + 'object_to_populate' => $object, + 'ignored_attributes' => ['values'], + ]); + + $this->assertSame([], $object->values); + } + + public function testDenormalizeWritesPublicPropertyRatherThanMethodOfSameName() + { + $object = new class { + public $refund = false; + public $refunded = false; + + public function refund($notify) + { + $this->refunded = true; + } + }; + + (new ObjectNormalizer())->denormalize(['refund' => true], $object::class, 'json', [ + 'object_to_populate' => $object, + ]); + + $this->assertTrue($object->refund); + $this->assertFalse($object->refunded); + } + + public function testDenormalizeWritesMagicPropertyRatherThanMethodOfSameName() + { + $object = new class { + public $data = []; + public $deleted = false; + + public function __set($name, $value) + { + $this->data[$name] = $value; + } + + public function delete($confirm) + { + $this->deleted = true; + } + }; + + (new ObjectNormalizer())->denormalize(['delete' => true], $object::class, 'json', [ + 'object_to_populate' => $object, + ]); + + $this->assertSame(['delete' => true], $object->data); + $this->assertFalse($object->deleted); + } + + public function testDenormalizeDoesNotCallMethodNamedAfterConstructorArgument() + { + $object = new class(1) { + public $calls = 0; + private $amount; + + public function __construct($amount) + { + $this->amount = $amount; + } + + public function amount($multiplier) + { + ++$this->calls; + } + }; + + (new ObjectNormalizer())->denormalize(['amount' => 2], $object::class, 'json', [ + 'object_to_populate' => $object, + ]); + + $this->assertSame(0, $object->calls); + } + + public function testDenormalizeDoesNotCallMethodNamedAfterAdder() + { + $object = new class { + public $calls = []; + + public function addRefund($refund) + { + $this->calls[] = 'addRefund'; + } + + public function removeRefund($refund) + { + $this->calls[] = 'removeRefund'; + } + + public function refund($amount) + { + $this->calls[] = 'refund'; + } + }; + + (new ObjectNormalizer())->denormalize(['refund' => 5], $object::class, 'json', [ + 'object_to_populate' => $object, + ]); + + $this->assertSame([], $object->calls); + } + + public function testDenormalizeCallsMethodOfSameNameWhenGetterSetterExtractionIsEnabled() + { + $object = new class { + public $calls = []; + + public function refund($amount) + { + $this->calls[] = $amount; + } + }; + + (new ObjectNormalizer())->denormalize(['refund' => 5], $object::class, 'json', [ + 'object_to_populate' => $object, + 'enable_getter_setter_extraction' => true, + ]); + + $this->assertSame([5], $object->calls); + } } class ProxyObjectDummy extends ObjectDummy diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/SerializerTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/SerializerTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Serializer/Tests/SerializerTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Serializer/Tests/SerializerTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -122,9 +122,9 @@ public function testNormalizeOnDenormalizer() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new TestDenormalizer()], []); - $this->assertTrue($serializer->normalize(new \stdClass(), 'json')); + $this->expectException(UnexpectedValueException::class); + $serializer->normalize(new \stdClass(), 'json'); } public function testDenormalizeNoMatch() @@ -144,10 +144,10 @@ public function testDenormalizeOnNormalizer() { - $this->expectException(UnexpectedValueException::class); $serializer = new Serializer([new TestNormalizer()], []); $data = ['title' => 'foo', 'numbers' => [5, 3]]; - $this->assertTrue($serializer->denormalize(json_encode($data), 'stdClass', 'json')); + $this->expectException(UnexpectedValueException::class); + $serializer->denormalize(json_encode($data), 'stdClass', 'json'); } public function testCustomNormalizerCanNormalizeCollectionsAndScalar() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Templating/PhpEngine.php symfony-6.4.51+dfsg/src/Symfony/Component/Templating/PhpEngine.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Templating/PhpEngine.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Templating/PhpEngine.php 2026-11-25 09:18:34.000000000 +0000 @@ -275,10 +275,15 @@ return $value; } - // If we deal with a scalar value, we can cache the result to increase + // If we deal with a short scalar value, we can cache the result to increase // the performance when the same value is escaped multiple times (e.g. loops) - if (\is_scalar($value)) { + if (\is_scalar($value) && \strlen($value) <= 100) { if (!isset(self::$escaperCache[$context][$value])) { + if (1000 < \count(self::$escaperCache[$context] ?? [])) { + // stop memory leak if there are many values + self::$escaperCache[$context] = \array_slice(self::$escaperCache[$context], 500, null, true); + } + self::$escaperCache[$context][$value] = $this->getEscaper($context)($value); } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Templating/Tests/PhpEngineTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Templating/Tests/PhpEngineTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Templating/Tests/PhpEngineTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Templating/Tests/PhpEngineTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -13,6 +13,7 @@ use PHPUnit\Framework\TestCase; use Symfony\Component\Templating\Helper\SlotsHelper; +use Symfony\Component\Templating\PhpEngine; use Symfony\Component\Templating\TemplateNameParser; use Symfony\Component\Templating\Tests\Fixtures\ProjectTemplateEngine; use Symfony\Component\Templating\Tests\Fixtures\ProjectTemplateEngineLoader; @@ -145,6 +146,31 @@ $this->assertEquals($foo, $engine->escape($foo), '->escape() does nothing on non strings'); } + public function testEscapeCacheSizeLimit() + { + $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader); + + for ($i = 0; $i < 2000; ++$i) { + $this->assertSame('&lt;'.$i.'&gt;', $engine->escape('<'.$i.'>')); + } + + $escaperCache = \Closure::bind(static fn () => self::$escaperCache, null, PhpEngine::class)(); + + $this->assertLessThanOrEqual(1001, \count($escaperCache['html'])); + } + + public function testEscapeDoesNotCacheLongValues() + { + $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader); + $value = str_repeat('<', 1000); + + $this->assertSame(str_repeat('&lt;', 1000), $engine->escape($value)); + + $escaperCache = \Closure::bind(static fn () => self::$escaperCache, null, PhpEngine::class)(); + + $this->assertArrayNotHasKey($value, $escaperCache['html'] ?? []); + } + public function testGetSetCharset() { $helper = new SlotsHelper(); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Translation/Resources/bin/translation-status.php symfony-6.4.51+dfsg/src/Symfony/Component/Translation/Resources/bin/translation-status.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Translation/Resources/bin/translation-status.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Translation/Resources/bin/translation-status.php 2026-11-25 09:18:34.000000000 +0000 @@ -82,6 +82,7 @@ $totalMissingTranslations = 0; $totalTranslationMismatches = 0; +$totalMixedAlphabetWords = 0; foreach ($config['original_files'] as $originalFilePath) { $translationFilePaths = findTranslationFiles($originalFilePath, $config['locale_to_analyze']); @@ -89,11 +90,12 @@ $totalMissingTranslations += array_sum(array_map(static fn ($translation) => count($translation['missingKeys']), array_values($translationStatus))); $totalTranslationMismatches += array_sum(array_map(static fn ($translation) => count($translation['mismatches']), array_values($translationStatus))); + $totalMixedAlphabetWords += array_sum(array_map(static fn ($translation) => count($translation['mixedAlphabetWords']), array_values($translationStatus))); printTranslationStatus($originalFilePath, $translationStatus, $config['verbose_output'], $config['include_completed_languages']); } -exit($totalTranslationMismatches > 0 ? 1 : 0); +exit($totalTranslationMismatches > 0 || $totalMixedAlphabetWords > 0 ? 1 : 0); function findTranslationFiles($originalFilePath, $localeToAnalyze): array { @@ -133,6 +135,7 @@ 'translated' => count($translatedKeys), 'missingKeys' => $missingKeys, 'mismatches' => $mismatches, + 'mixedAlphabetWords' => findMixedAlphabetWords($translationPath), ]; $translationStatus[$locale]['is_completed'] = isTranslationCompleted($translationStatus[$locale]); } @@ -142,7 +145,7 @@ function isTranslationCompleted(array $translationStatus): bool { - return $translationStatus['total'] === $translationStatus['translated'] && 0 === count($translationStatus['mismatches']); + return $translationStatus['total'] === $translationStatus['translated'] && 0 === count($translationStatus['mismatches']) && 0 === count($translationStatus['mixedAlphabetWords']); } function printTranslationStatus($originalFilePath, $translationStatus, $verboseOutput, $includeCompletedLanguages) @@ -196,6 +199,28 @@ return $mismatches; } +/** + * Find the words of the targets that mix letters from the Latin, Cyrillic and Greek alphabets. + */ +function findMixedAlphabetWords($filePath): array +{ + $words = []; + $contents = new SimpleXMLElement(file_get_contents($filePath)); + + foreach ($contents->file->body->{'trans-unit'} as $translationKey) { + foreach (preg_split('/[^\p{L}]++/u', (string) $translationKey->target, -1, \PREG_SPLIT_NO_EMPTY) as $word) { + // a letter shared by several scripts (like U+02BC) belongs to none of them + $alphabets = preg_match('/(?![\p{Cyrillic}\p{Greek}])\p{Latin}/u', $word) + preg_match('/(?![\p{Latin}\p{Greek}])\p{Cyrillic}/u', $word) + preg_match('/(?![\p{Latin}\p{Cyrillic}])\p{Greek}/u', $word); + + if (1 < $alphabets) { + $words[] = [(string) $translationKey['id'], $word]; + } + } + } + + return $words; +} + function printTitle($title) { echo $title.\PHP_EOL; @@ -218,18 +243,19 @@ if ($translation['translated'] > $translation['total']) { textColorRed(); - } elseif ($translation['mismatches']) { + } elseif ($translation['mismatches'] || $translation['mixedAlphabetWords']) { textColorRed(); } elseif ($translation['is_completed']) { textColorGreen(); } echo sprintf( - '| Locale: %-'.$longestLocaleNameLength.'s | Translated: %2d/%2d | Mismatches: %d |', + '| Locale: %-'.$longestLocaleNameLength.'s | Translated: %2d/%2d | Mismatches: %d | Mixed alphabets: %d |', $locale, $translation['translated'], $translation['total'], - count($translation['mismatches']) + count($translation['mismatches']), + count($translation['mixedAlphabetWords']) ).\PHP_EOL; textColorNormal(); @@ -252,6 +278,14 @@ } $shouldBeClosed = true; } + if ($verboseOutput && $translation['mixedAlphabetWords']) { + echo '| Words mixing letters from the Latin, Cyrillic and Greek alphabets:'.\PHP_EOL; + + foreach ($translation['mixedAlphabetWords'] as [$id, $word]) { + echo sprintf('| (id=%s) %s', $id, $word).\PHP_EOL; + } + $shouldBeClosed = true; + } if ($shouldBeClosed) { echo str_repeat('-', 80).\PHP_EOL; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Translation/Resources/schemas/LICENSE.txt symfony-6.4.51+dfsg/src/Symfony/Component/Translation/Resources/schemas/LICENSE.txt --- symfony-6.4.50+dfsg/src/Symfony/Component/Translation/Resources/schemas/LICENSE.txt 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Translation/Resources/schemas/LICENSE.txt 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,184 @@ +The XML schemas in this directory are not covered by the license of the +Translation component. They come with their own terms, reproduced below. + +xliff-core-1.2-transitional.xsd +=============================== + +Copy of the transitional schema of XLIFF Version 1.2, an OASIS Standard: +https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html + +Copyright © OASIS® 1993 - 2007. All Rights Reserved. + +All capitalized terms in the following text have the meanings assigned to them +in the OASIS Intellectual Property Rights Policy (the "OASIS IPR Policy"). The +full Policy may be found at the OASIS website. + +This document and translations of it may be copied and furnished to others, and +derivative works that comment on or otherwise explain it or assist in its +implementation may be prepared, copied, published, and distributed, in whole or +in part, without restriction of any kind, provided that the above copyright +notice and this section are included on all such copies and derivative works. +However, this document itself may not be modified in any way, including by +removing the copyright notice or references to OASIS, except as needed for the +purpose of developing any document or deliverable produced by an OASIS +Technical Committee (in which case the rules applicable to copyrights, as set +forth in the OASIS IPR Policy, must be followed) or as required to translate it +into languages other than English. + +The limited permissions granted above are perpetual and will not be revoked by +OASIS or its successors or assigns. + +This document and the information contained herein is provided on an "AS IS" +basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT +INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR +FITNESS FOR A PARTICULAR PURPOSE. + +OASIS requests that any OASIS Party or any other party that believes it has +patent claims that would necessarily be infringed by implementations of this +OASIS Committee Specification or OASIS Standard, to notify OASIS TC +Administrator and provide an indication of its willingness to grant patent +licenses to such patent claims in a manner consistent with the IPR Mode of the +OASIS Technical Committee that produced this specification. + +OASIS invites any party to contact the OASIS TC Administrator if it is aware of +a claim of ownership of any patent claims that would necessarily be infringed +by implementations of this specification by a patent holder that is not willing +to provide a license to such patent claims in a manner consistent with the IPR +Mode of the OASIS Technical Committee that produced this specification. OASIS +may include such claims on its website, but disclaims any obligation to do so. + +OASIS takes no position regarding the validity or scope of any intellectual +property or other rights that might be claimed to pertain to the implementation +or use of the technology described in this document or the extent to which any +license under such rights might or might not be available; neither does it +represent that it has made any effort to identify any such rights. Information +on OASIS' procedures with respect to rights in any document or deliverable +produced by an OASIS Technical Committee can be found on the OASIS website. +Copies of claims of rights made available for publication and any assurances of +licenses to be made available, or the result of an attempt made to obtain a +general license or permission for the use of such proprietary rights by +implementers or users of this OASIS Committee Specification or OASIS Standard, +can be obtained from the OASIS TC Administrator. OASIS makes no representation +that any information or list of intellectual property rights will at any time +be complete, or that any claims in such list are, in fact, Essential Claims. + +The names "OASIS" and "XLIFF" are trademarks of OASIS, the owner and developer +of this specification, and should be used only to refer to the organization and +its official outputs. OASIS welcomes reference to, and implementation and use +of, specifications, while reserving the right to enforce its marks against +misleading uses. Please see http://www.oasis-open.org/who/trademark.php for +above guidance. + +xliff-core-2.0.xsd +================== + +Copy of the core schema of XLIFF Version 2.0, an OASIS Standard: +https://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html + +Copyright © OASIS Open 2014. All Rights Reserved. + +All capitalized terms in the following text have the meanings assigned to them +in the OASIS Intellectual Property Rights Policy (the "OASIS IPR Policy"). The +full Policy may be found at the OASIS website. + +This document and translations of it may be copied and furnished to others, and +derivative works that comment on or otherwise explain it or assist in its +implementation may be prepared, copied, published, and distributed, in whole or +in part, without restriction of any kind, provided that the above copyright +notice and this section are included on all such copies and derivative works. +However, this document itself may not be modified in any way, including by +removing the copyright notice or references to OASIS, except as needed for the +purpose of developing any document or deliverable produced by an OASIS +Technical Committee (in which case the rules applicable to copyrights, as set +forth in the OASIS IPR Policy, must be followed) or as required to translate it +into languages other than English. + +The limited permissions granted above are perpetual and will not be revoked by +OASIS or its successors or assigns. + +This document and the information contained herein is provided on an "AS IS" +basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT +INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR +FITNESS FOR A PARTICULAR PURPOSE. + +OASIS requests that any OASIS Party or any other party that believes it has +patent claims that would necessarily be infringed by implementations of this +OASIS Committee Specification or OASIS Standard, to notify OASIS TC +Administrator and provide an indication of its willingness to grant patent +licenses to such patent claims in a manner consistent with the IPR Mode of the +OASIS Technical Committee that produced this specification. + +OASIS invites any party to contact the OASIS TC Administrator if it is aware of +a claim of ownership of any patent claims that would necessarily be infringed +by implementations of this specification by a patent holder that is not willing +to provide a license to such patent claims in a manner consistent with the IPR +Mode of the OASIS Technical Committee that produced this specification. OASIS +may include such claims on its website, but disclaims any obligation to do so. + +OASIS takes no position regarding the validity or scope of any intellectual +property or other rights that might be claimed to pertain to the implementation +or use of the technology described in this document or the extent to which any +license under such rights might or might not be available; neither does it +represent that it has made any effort to identify any such rights. Information +on OASIS' procedures with respect to rights in any document or deliverable +produced by an OASIS Technical Committee can be found on the OASIS website. +Copies of claims of rights made available for publication and any assurances of +licenses to be made available, or the result of an attempt made to obtain a +general license or permission for the use of such proprietary rights by +implementers or users of this OASIS Committee Specification or OASIS Standard, +can be obtained from the OASIS TC Administrator. OASIS makes no representation +that any information or list of intellectual property rights will at any time +be complete, or that any claims in such list are, in fact, Essential Claims. + +The name "OASIS" is a trademark of OASIS, the owner and developer of this +specification, and should be used only to refer to the organization and its +official outputs. OASIS welcomes reference to, and implementation and use of, +specifications, while reserving the right to enforce its marks against +misleading uses. Please see +http://www.oasis-open.org/policies-guidelines/trademark for above guidance. + +xml.xsd +======= + +Copy of https://www.w3.org/2001/xml.xsd, published by the World Wide Web +Consortium (W3C) under the W3C Software and Document License: +https://www.w3.org/copyright/software-license-2023/ + +By obtaining and/or copying this work, you (the licensee) agree that you have +read, understood, and will comply with the following terms and conditions. + +Permission to copy, modify, and distribute this work, with or without +modification, for any purpose and without fee or royalty is hereby granted, +provided that you include the following on ALL copies of the work or portions +thereof, including modifications: + +- The full text of this NOTICE in a location viewable to users of the +redistributed or derivative work. + +- Any pre-existing intellectual property disclaimers, notices, or terms and +conditions. If none exist, the W3C software and document short notice should be +included. + +- Notice of any changes or modifications, through a copyright statement on the +new code or document such as "This software or document includes material +copied from or derived from [title and URI of the W3C document]. Copyright © +[$year-of-document] World Wide Web Consortium. +https://www.w3.org/copyright/software-license-2023/" + +Disclaimers + +THIS WORK IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR +WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF +MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE +SOFTWARE OR DOCUMENT WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, +TRADEMARKS OR OTHER RIGHTS. + +COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENT. + +The name and trademarks of copyright holders may NOT be used in advertising or +publicity pertaining to the work without specific, written prior permission. +Title to copyright in this work will at all times remain with copyright +holders. diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Constraints/IbanValidator.php symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Constraints/IbanValidator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Constraints/IbanValidator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Constraints/IbanValidator.php 2026-11-25 09:18:34.000000000 +0000 @@ -51,12 +51,12 @@ 'BH' => 'BH\d{2}[A-Z]{4}[\dA-Z]{14}', // Bahrain 'BI' => 'BI\d{2}\d{5}\d{5}\d{11}\d{2}', // Burundi 'BJ' => 'BJ\d{2}[\dA-Z]{2}\d{22}', // Benin - 'BR' => 'BR\d{2}\d{8}\d{5}\d{10}[A-Z]{1}[\dA-Z]{1}', // Brazil - 'BY' => 'BY\d{2}[\dA-Z]{4}\d{4}[\dA-Z]{16}', // Republic of Belarus + 'BR' => 'BR\d{2}[\dA-Z]{8}\d{5}\d{10}[\dA-Z]{1}[\dA-Z]{1}', // Brazil + 'BY' => 'BY\d{2}[\dA-Z]{4}\d{4}[\dA-Z]{16}', // Belarus 'CF' => 'CF\d{2}\d{23}', // Central African Republic 'CG' => 'CG\d{2}\d{23}', // Congo, Republic of the 'CH' => 'CH\d{2}\d{5}[\dA-Z]{12}', // Switzerland - 'CI' => 'CI\d{2}[A-Z]{1}\d{23}', // Côte d'Ivoire + 'CI' => 'CI\d{2}[A-Z]{2}\d{22}', // Côte d'Ivoire 'CM' => 'CM\d{2}\d{23}', // Cameroon 'CR' => 'CR\d{2}\d{4}\d{14}', // Costa Rica 'CV' => 'CV\d{2}\d{21}', // Cabo Verde @@ -71,7 +71,7 @@ 'EG' => 'EG\d{2}\d{4}\d{4}\d{17}', // Egypt 'ES' => 'ES\d{2}\d{4}\d{4}\d{1}\d{1}\d{10}', // Spain 'FI' => 'FI\d{2}\d{3}\d{11}', // Finland - 'FK' => 'FK\d{2}[A-Z]{2}\d{12}', // Falkland Islands + 'FK' => 'FK\d{2}[A-Z]{2}\d{12}', // Falkland Islands (Malvinas) 'FO' => 'FO\d{2}\d{4}\d{9}\d{1}', // Faroe Islands 'FR' => 'FR\d{2}\d{5}\d{5}[\dA-Z]{11}\d{2}', // France 'GA' => 'GA\d{2}\d{23}', // Gabon @@ -105,10 +105,10 @@ 'LY' => 'LY\d{2}\d{3}\d{3}\d{15}', // Libya 'MA' => 'MA\d{2}\d{24}', // Morocco 'MC' => 'MC\d{2}\d{5}\d{5}[\dA-Z]{11}\d{2}', // Monaco - 'MD' => 'MD\d{2}[\dA-Z]{2}[\dA-Z]{18}', // Moldova + 'MD' => 'MD\d{2}[\dA-Z]{2}[\dA-Z]{18}', // Moldova, Republic of 'ME' => 'ME\d{2}\d{3}\d{13}\d{2}', // Montenegro 'MG' => 'MG\d{2}\d{23}', // Madagascar - 'MK' => 'MK\d{2}\d{3}[\dA-Z]{10}\d{2}', // Macedonia + 'MK' => 'MK\d{2}\d{3}[\dA-Z]{10}\d{2}', // North Macedonia 'ML' => 'ML\d{2}[\dA-Z]{2}\d{22}', // Mali 'MN' => 'MN\d{2}\d{4}\d{12}', // Mongolia 'MR' => 'MR\d{2}\d{5}\d{5}\d{11}\d{2}', // Mauritania @@ -127,7 +127,7 @@ 'QA' => 'QA\d{2}[A-Z]{4}[\dA-Z]{21}', // Qatar 'RO' => 'RO\d{2}[A-Z]{4}[\dA-Z]{16}', // Romania 'RS' => 'RS\d{2}\d{3}\d{13}\d{2}', // Serbia - 'RU' => 'RU\d{2}\d{9}\d{5}[\dA-Z]{15}', // Russia + 'RU' => 'RU\d{2}\d{9}\d{5}[\dA-Z]{15}', // Russian Federation 'SA' => 'SA\d{2}\d{2}[\dA-Z]{18}', // Saudi Arabia 'SC' => 'SC\d{2}[A-Z]{4}\d{2}\d{2}\d{16}[A-Z]{3}', // Seychelles 'SD' => 'SD\d{2}\d{2}\d{12}', // Sudan @@ -137,16 +137,16 @@ 'SM' => 'SM\d{2}[A-Z]{1}\d{5}\d{5}[\dA-Z]{12}', // San Marino 'SN' => 'SN\d{2}[A-Z]{2}\d{22}', // Senegal 'SO' => 'SO\d{2}\d{4}\d{3}\d{12}', // Somalia - 'ST' => 'ST\d{2}\d{8}\d{11}\d{2}', // Sao Tome and Principe + 'ST' => 'ST\d{2}\d{4}\d{4}\d{11}\d{2}', // Sao Tome and Principe 'SV' => 'SV\d{2}[A-Z]{4}\d{20}', // El Salvador 'TD' => 'TD\d{2}\d{23}', // Chad 'TG' => 'TG\d{2}[A-Z]{2}\d{22}', // Togo 'TL' => 'TL\d{2}\d{3}\d{14}\d{2}', // Timor-Leste 'TN' => 'TN\d{2}\d{2}\d{3}\d{13}\d{2}', // Tunisia - 'TR' => 'TR\d{2}\d{5}\d{1}[\dA-Z]{16}', // Turkey + 'TR' => 'TR\d{2}\d{5}\d{1}[\dA-Z]{16}', // Turkiye 'UA' => 'UA\d{2}\d{6}[\dA-Z]{19}', // Ukraine - 'VA' => 'VA\d{2}\d{3}\d{15}', // Vatican City State - 'VG' => 'VG\d{2}[A-Z]{4}\d{16}', // Virgin Islands + 'VA' => 'VA\d{2}\d{3}\d{15}', // Holy See + 'VG' => 'VG\d{2}[A-Z]{4}\d{16}', // Virgin Islands (British) 'XK' => 'XK\d{2}\d{4}\d{10}\d{2}', // Kosovo 'YE' => 'YE\d{2}[A-Z]{4}\d{4}[\dA-Z]{18}', // Yemen ]; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Constraints/IpValidator.php symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Constraints/IpValidator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Constraints/IpValidator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Constraints/IpValidator.php 2026-11-25 09:18:34.000000000 +0000 @@ -58,6 +58,7 @@ '::1/128', // loopback 'fc00::/7', // unique local address 'fe80::/10', // link local address + 'fec0::/10', // site local address, deprecated by RFC 3879 '::ffff:0:0/96', // IPv4-mapped '::/96', // IPv4-compatible, including the unspecified address '2002::/16', // 6to4 diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Constraints/NotCompromisedPasswordValidator.php symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Constraints/NotCompromisedPasswordValidator.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Constraints/NotCompromisedPasswordValidator.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Constraints/NotCompromisedPasswordValidator.php 2026-11-25 09:18:34.000000000 +0000 @@ -24,7 +24,7 @@ * Checks if a password has been leaked in a data breach using haveibeenpwned.com's API. * Use a k-anonymity model to protect the password being searched for. * - * @see https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange + * @see https://haveibeenpwned.com/API/v3#SearchingPwnedPasswordsByRange * * @author Kévin Dunglas <dunglas@gmail.com> */ diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/bin/sync-iban-formats.php symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/bin/sync-iban-formats.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/bin/sync-iban-formats.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/bin/sync-iban-formats.php 2026-11-25 09:18:34.000000000 +0000 @@ -107,7 +107,8 @@ foreach ($lines as $line) { $columns = str_getcsv($line, "\t", '"', '\\'); - $propertyLabel = array_shift($columns); + // str_getcsv() returns [null] for an empty line + $propertyLabel = (string) array_shift($columns); if (!isset($properties[$propertyLabel])) { continue; @@ -144,27 +145,57 @@ { $formats = []; - foreach ($this->readIbanFormatsTable() as $item) { - if (!preg_match('/^([A-Z]{2})/', $item['IBAN Fields'], $matches)) { + foreach ($this->readIbanFormatsTables() as [$ibanFields, $bbanFormat, $country]) { + if (!preg_match('/^([A-Z]{2})/', $ibanFields, $matches)) { continue; } $countryCode = $matches[1]; - $formats[$countryCode] = [$this->buildIbanRegexp($countryCode, $item['BBAN Format']), $item['Country']]; + $formats[$countryCode] = [$this->buildIbanRegexp($countryCode, $bbanFormat), $country]; } return $formats; } /** - * @return list<array<string, string|int>> + * Reads the tables of IBAN countries ("IBAN Fields" column) and of partial IBAN countries ("Example" column). + * + * @return list<array{string, string, string}> */ - private function readIbanFormatsTable(): array + private function readIbanFormatsTables(): array { - $tablesResponse = file_get_contents('https://www.wikitable2json.com/api/International_Bank_Account_Number?table=3&keyRows=1&clearRef=true'); + $tablesResponse = file_get_contents('https://www.wikitable2json.com/api/International_Bank_Account_Number?keyRows=1&clearRef=true'); - return json_decode($tablesResponse, true, 512, \JSON_THROW_ON_ERROR)[0]; + $items = []; + $missingColumns = ['iban fields' => true, 'example' => true]; + + foreach (json_decode($tablesResponse, true, 512, \JSON_THROW_ON_ERROR) as $table) { + $columns = array_keys(array_change_key_case($table[0] ?? [])); + $ibanColumn = in_array('iban fields', $columns, true) ? 'iban fields' : 'example'; + + if (array_diff([$ibanColumn, 'bban format', 'country'], $columns)) { + continue; + } + + unset($missingColumns[$ibanColumn]); + + foreach ($table as $row) { + $row = array_change_key_case($row); + + if (!isset($row[$ibanColumn], $row['bban format'], $row['country'])) { + throw new RuntimeException(sprintf('Unexpected row in the Wikipedia table with the "%s" column: "%s".', $ibanColumn, json_encode($row))); + } + + $items[] = [$row[$ibanColumn], $row['bban format'], preg_replace('/\[[^\]]*\]/', '', $row['country'])]; + } + } + + if ($missingColumns) { + throw new RuntimeException(sprintf('Cannot find the Wikipedia table with the "%s" column.', array_key_first($missingColumns))); + } + + return $items; } private function buildIbanRegexp(string $countryCode, string $bbanFormat): string diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.ca.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.ca.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.ca.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.ca.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -580,71 +580,71 @@ </trans-unit> <trans-unit id="149"> <source>This file is not a valid audio file.</source> - <target state="needs-review-translation">Aquest fitxer no és un fitxer d'àudio vàlid.</target> + <target>Aquest fitxer no és un fitxer d'àudio vàlid.</target> </trans-unit> <trans-unit id="150"> <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> - <target state="needs-review-translation">L'àudio és massa curt ({{ duration }} segons). La durada mínima esperada és {{ min_duration }} segons.</target> + <target>L'àudio és massa curt ({{ duration }} segons). La durada mínima esperada és {{ min_duration }} segons.</target> </trans-unit> <trans-unit id="151"> <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> - <target state="needs-review-translation">L'àudio és massa llarg ({{ duration }} segons). La durada màxima permesa és {{ max_duration }} segons.</target> + <target>L'àudio és massa llarg ({{ duration }} segons). La durada màxima permesa és {{ max_duration }} segons.</target> </trans-unit> <trans-unit id="152"> <source>The duration of the audio could not be detected.</source> - <target state="needs-review-translation">No s'ha pogut detectar la durada de l'àudio.</target> + <target>No s'ha pogut detectar la durada de l'àudio.</target> </trans-unit> <trans-unit id="153"> <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> - <target state="needs-review-translation">La taxa de bits de l'àudio és massa baixa ({{ bitrate }} bps). La taxa de bits mínima esperada és {{ min_bitrate }} bps.</target> + <target>La taxa de bits de l'àudio és massa baixa ({{ bitrate }} bps). La taxa de bits mínima esperada és {{ min_bitrate }} bps.</target> </trans-unit> <trans-unit id="154"> <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> - <target state="needs-review-translation">La taxa de bits de l'àudio és massa alta ({{ bitrate }} bps). La taxa de bits màxima permesa és {{ max_bitrate }} bps.</target> + <target>La taxa de bits de l'àudio és massa alta ({{ bitrate }} bps). La taxa de bits màxima permesa és {{ max_bitrate }} bps.</target> </trans-unit> <trans-unit id="155"> <source>The bitrate of the audio could not be detected.</source> - <target state="needs-review-translation">No s'ha pogut detectar la taxa de bits de l'àudio.</target> + <target>No s'ha pogut detectar la taxa de bits de l'àudio.</target> </trans-unit> <trans-unit id="156"> <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> - <target state="needs-review-translation">Freqüència de mostreig d'àudio incompatible ({{ sample_rate }} Hz).</target> + <target>Freqüència de mostreig d'àudio incompatible ({{ sample_rate }} Hz).</target> </trans-unit> <trans-unit id="157"> <source>The sample rate of the audio could not be detected.</source> - <target state="needs-review-translation">No s'ha pogut detectar la freqüència de mostreig de l'àudio.</target> + <target>No s'ha pogut detectar la freqüència de mostreig de l'àudio.</target> </trans-unit> <trans-unit id="158"> <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> - <target state="needs-review-translation">L'àudio no té suficients canals ({{ channels }}). La quantitat mínima esperada és {{ min_channels }}.</target> + <target>L'àudio no té suficients canals ({{ channels }}). La quantitat mínima esperada és {{ min_channels }}.</target> </trans-unit> <trans-unit id="159"> <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> - <target state="needs-review-translation">L'àudio té massa canals ({{ channels }}). La quantitat màxima prevista és {{ max_channels }}.</target> + <target>L'àudio té massa canals ({{ channels }}). La quantitat màxima prevista és {{ max_channels }}.</target> </trans-unit> <trans-unit id="160"> <source>The number of audio channels could not be detected.</source> - <target state="needs-review-translation">No s'ha pogut detectar el nombre de canals d'àudio.</target> + <target>No s'ha pogut detectar el nombre de canals d'àudio.</target> </trans-unit> <trans-unit id="161"> <source>The audio file is corrupted.</source> - <target state="needs-review-translation">El fitxer d'àudio està espatllat.</target> + <target>El fitxer d'àudio està malmès.</target> </trans-unit> <trans-unit id="162"> <source>The audio contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">L'àudio conté diversos fluxos. Només es permet un sol flux.</target> + <target>L'àudio conté diversos fluxos. Només se'n permet un.</target> </trans-unit> <trans-unit id="163"> <source>Unsupported audio codec "{{ codec }}".</source> - <target state="needs-review-translation">Còdec d'àudio incompatible «{{ codec }}».</target> + <target>Còdec d'àudio no compatible «{{ codec }}».</target> </trans-unit> <trans-unit id="164"> <source>Unsupported audio container "{{ container }}".</source> - <target state="needs-review-translation">Contenidor d'àudio incompatible "{{ container }}".</target> + <target>Contenidor d'àudio no compatible "{{ container }}".</target> </trans-unit> <trans-unit id="165"> <source>The file does not contain any audio stream.</source> - <target state="needs-review-translation">El fitxer no conté cap flux d'àudio.</target> + <target>El fitxer no conté cap flux d'àudio.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.cs.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.cs.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.cs.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.cs.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -556,95 +556,95 @@ </trans-unit> <trans-unit id="143"> <source>This value is not valid XML.</source> - <target state="needs-review-translation">Tato hodnota není platné XML.</target> + <target>Tato hodnota není platné XML.</target> </trans-unit> <trans-unit id="144"> <source>This value does not conform to the expected XSD schema.</source> - <target state="needs-review-translation">Tato hodnota neodpovídá očekávanému schématu XSD.</target> + <target>Tato hodnota neodpovídá očekávanému schématu XSD.</target> </trans-unit> <trans-unit id="145"> <source>This XML payload is too large ({{ size }} bytes): it exceeds the limit of {{ limit }} bytes.</source> - <target state="needs-review-translation">Tato datová část XML je příliš velká ({{ size }} bajtů): překračuje limit {{ limit }} bajtů.</target> + <target>Dokument XML překračuje povolenou velikost ({{ size }} B, limit {{ limit }} B).</target> </trans-unit> <trans-unit id="146"> <source>This value is not a valid cron expression.</source> - <target state="needs-review-translation">Tato hodnota není platný výraz cron.</target> + <target>Tato hodnota není platný výraz cron.</target> </trans-unit> <trans-unit id="147"> <source>The referenced entity does not exist.</source> - <target state="needs-review-translation">Odkazovaná entita neexistuje.</target> + <target>Odkazovaná entita neexistuje.</target> </trans-unit> <trans-unit id="148" resname="This is not a valid ULID."> <source>This value is not a valid ULID.</source> - <target state="needs-review-translation">Tato hodnota není platným ULID.</target> + <target>Tato hodnota není platným ULID.</target> </trans-unit> <trans-unit id="149"> <source>This file is not a valid audio file.</source> - <target state="needs-review-translation">Tento soubor není zvukový soubor.</target> + <target>Tento soubor není platným zvukovým souborem.</target> </trans-unit> <trans-unit id="150"> <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> - <target state="needs-review-translation">Zvuk je příliš krátký ({{ duration }} sekund). Minimální očekávaná délka je {{ min_duration }} sekund.</target> + <target>Zvuk je příliš krátký ({{ duration }} s). Minimální požadovaná délka je {{ min_duration }} s.</target> </trans-unit> <trans-unit id="151"> <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> - <target state="needs-review-translation">Zvuk je příliš dlouhý ({{ duration }} sekund). Maximální povolená délka je {{ max_duration }} sekund.</target> + <target>Zvuk je příliš dlouhý ({{ duration }} s). Maximální povolená délka je {{ max_duration }} s.</target> </trans-unit> <trans-unit id="152"> <source>The duration of the audio could not be detected.</source> - <target state="needs-review-translation">Nepodařilo se zjistit délku zvuku.</target> + <target>Nepodařilo se zjistit délku zvuku.</target> </trans-unit> <trans-unit id="153"> <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> - <target state="needs-review-translation">Datový tok zvuku je příliš nízký ({{ bitrate }} bps). Minimální očekávaný datový tok je {{ min_bitrate }} bps.</target> + <target>Datový tok zvuku je příliš nízký ({{ bitrate }} bit/s). Minimální požadovaný datový tok je {{ min_bitrate }} bit/s.</target> </trans-unit> <trans-unit id="154"> <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> - <target state="needs-review-translation">Datový tok zvuku je příliš vysoký ({{ bitrate }} bps). Maximální povolený datový tok je {{ max_bitrate }} bps.</target> + <target>Datový tok zvuku je příliš vysoký ({{ bitrate }} bit/s). Maximální povolený datový tok je {{ max_bitrate }} bit/s.</target> </trans-unit> <trans-unit id="155"> <source>The bitrate of the audio could not be detected.</source> - <target state="needs-review-translation">Nepodařilo se zjistit datový tok zvuku.</target> + <target>Nepodařilo se zjistit datový tok zvuku.</target> </trans-unit> <trans-unit id="156"> <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> - <target state="needs-review-translation">Nepodporovaná vzorkovací frekvence zvuku ({{ sample_rate }} Hz).</target> + <target>Nepodporovaná vzorkovací frekvence zvuku ({{ sample_rate }} Hz).</target> </trans-unit> <trans-unit id="157"> <source>The sample rate of the audio could not be detected.</source> - <target state="needs-review-translation">Nepodařilo se zjistit vzorkovací frekvenci zvuku.</target> + <target>Nepodařilo se zjistit vzorkovací frekvenci zvuku.</target> </trans-unit> <trans-unit id="158"> <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> - <target state="needs-review-translation">Zvuk má příliš málo kanálů ({{ channels }}). Minimální očekávané množství je {{ min_channels }}.</target> + <target>Zvuk má příliš málo kanálů ({{ channels }}). Minimální požadovaný počet kanálů je {{ min_channels }}.</target> </trans-unit> <trans-unit id="159"> <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> - <target state="needs-review-translation">Zvuk má příliš mnoho kanálů ({{ channels }}). Maximální očekávané množství je {{ max_channels }}.</target> + <target>Zvuk má příliš mnoho kanálů ({{ channels }}). Maximální povolený počet kanálů je {{ max_channels }}.</target> </trans-unit> <trans-unit id="160"> <source>The number of audio channels could not be detected.</source> - <target state="needs-review-translation">Nepodařilo se zjistit počet zvukových kanálů.</target> + <target>Nepodařilo se zjistit počet zvukových kanálů.</target> </trans-unit> <trans-unit id="161"> <source>The audio file is corrupted.</source> - <target state="needs-review-translation">Zvukový soubor je poškozený.</target> + <target>Zvukový soubor je poškozený.</target> </trans-unit> <trans-unit id="162"> <source>The audio contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">Zvuk obsahuje více proudů. Povolen je pouze jeden proud.</target> + <target>Soubor obsahuje více zvukových stop. Povolená je pouze jedna.</target> </trans-unit> <trans-unit id="163"> <source>Unsupported audio codec "{{ codec }}".</source> - <target state="needs-review-translation">Nepodporovaný kodek zvuku "{{ codec }}".</target> + <target>Nepodporovaný zvukový kodek "{{ codec }}".</target> </trans-unit> <trans-unit id="164"> <source>Unsupported audio container "{{ container }}".</source> - <target state="needs-review-translation">Nepodporovaný kontejner zvuku "{{ container }}".</target> + <target>Nepodporovaný formát zvukového kontejneru "{{ container }}".</target> </trans-unit> <trans-unit id="165"> <source>The file does not contain any audio stream.</source> - <target state="needs-review-translation">Soubor neobsahuje žádný zvukový proud.</target> + <target>Soubor neobsahuje žádnou zvukovou stopu.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.el.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -208,11 +208,11 @@ </trans-unit> <trans-unit id="55"> <source>This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.</source> - <target>Αυτή η συλλογή πρέπει να περιέχει {{ limit }} στοιχείo ή λιγότερα.|Αυτή η συλλογή πρέπει να περιέχει {{ limit }} στοιχεία ή λιγότερα.</target> + <target>Αυτή η συλλογή πρέπει να περιέχει {{ limit }} στοιχείο ή λιγότερα.|Αυτή η συλλογή πρέπει να περιέχει {{ limit }} στοιχεία ή λιγότερα.</target> </trans-unit> <trans-unit id="56"> <source>This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.</source> - <target>Αυτή η συλλογή πρέπει να περιέχει ακριβώς {{ limit }} στοιχείo.|Αυτή η συλλογή πρέπει να περιέχει ακριβώς {{ limit }} στοιχεία.</target> + <target>Αυτή η συλλογή πρέπει να περιέχει ακριβώς {{ limit }} στοιχείο.|Αυτή η συλλογή πρέπει να περιέχει ακριβώς {{ limit }} στοιχεία.</target> </trans-unit> <trans-unit id="57"> <source>Invalid card number.</source> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.eu.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.eu.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.eu.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.eu.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -108,7 +108,7 @@ </trans-unit> <trans-unit id="27"> <source>This value is not a valid URL.</source> - <target>Balio hau ez da baliabideen kokatzaile uniforme (URL) egoki bat.</target> + <target>Balio hau ez da URL onargarri bat.</target> </trans-unit> <trans-unit id="31"> <source>The two values should be equal.</source> @@ -136,7 +136,7 @@ </trans-unit> <trans-unit id="37" resname="This is not a valid IP address."> <source>This value is not a valid IP address.</source> - <target state="needs-review-translation">Balio hau ez da IP helbide baliozko bat.</target> + <target>Balio hau ez da IP helbide egoki bat.</target> </trans-unit> <trans-unit id="38"> <source>This value is not a valid language.</source> @@ -144,7 +144,7 @@ </trans-unit> <trans-unit id="39"> <source>This value is not a valid locale.</source> - <target>Balio hau ez da kokapen egoki bat.</target> + <target>Balio hau ez da lokalizazio onargarri bat.</target> </trans-unit> <trans-unit id="40"> <source>This value is not a valid country.</source> @@ -192,7 +192,7 @@ </trans-unit> <trans-unit id="51" resname="No temporary folder was configured in php.ini."> <source>No temporary folder was configured in php.ini, or the configured folder does not exist.</source> - <target state="needs-review-translation">Ez da aldi baterako karpetarik konfiguratu php.ini-n, edo konfiguratutako karpeta ez da existitzen.</target> + <target>Ez da aldi baterako karpetarik konfiguratu php.ini-n, edo konfiguratutako karpeta ez da existitzen.</target> </trans-unit> <trans-unit id="52"> <source>Cannot write temporary file to disk.</source> @@ -224,7 +224,7 @@ </trans-unit> <trans-unit id="59" resname="This is not a valid International Bank Account Number (IBAN)."> <source>This value is not a valid International Bank Account Number (IBAN).</source> - <target state="needs-review-translation">Balio hau ez da Nazioarteko Banku Kontu Zenbaki (IBAN) baliozko bat.</target> + <target>Balio hau ez da banku-kontuaren nazioarteko zenbaki (IBAN) egoki bat.</target> </trans-unit> <trans-unit id="60"> <source>This value is not a valid ISBN-10.</source> @@ -280,7 +280,7 @@ </trans-unit> <trans-unit id="73"> <source>The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.</source> - <target>Irudiaren proportzioa oso handia da ({{ ratio }}). Onartutako proportzio handienda {{ max_ratio }} da.</target> + <target>Irudiaren proportzioa oso handia da ({{ ratio }}). Onartutako proportzio handiena {{ max_ratio }} da.</target> </trans-unit> <trans-unit id="74"> <source>The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.</source> @@ -312,7 +312,7 @@ </trans-unit> <trans-unit id="81" resname="This is not a valid Business Identifier Code (BIC)."> <source>This value is not a valid Business Identifier Code (BIC).</source> - <target state="needs-review-translation">Balio hau ez da Negozioaren Identifikazio Kode (BIC) baliozko bat.</target> + <target>Balio hau ez da banku-identifikazioko kode (BIC) egoki bat.</target> </trans-unit> <trans-unit id="82"> <source>Error</source> @@ -320,7 +320,7 @@ </trans-unit> <trans-unit id="83" resname="This is not a valid UUID."> <source>This value is not a valid UUID.</source> - <target state="needs-review-translation">Balio hau ez da UUID baliozko bat.</target> + <target>Balio hau ez da UUID egoki bat.</target> </trans-unit> <trans-unit id="84"> <source>This value should be a multiple of {{ compared_value }}.</source> @@ -356,11 +356,11 @@ </trans-unit> <trans-unit id="92"> <source>This value is not a valid timezone.</source> - <target>Balio hori ez da baliozko ordu-eremua.</target> + <target>Balio hau ez da baliozko ordu-eremua.</target> </trans-unit> <trans-unit id="93"> <source>This password has been leaked in a data breach, it must not be used. Please use another password.</source> - <target>Pasahitz hori ezin da erabili, beste gune eta aplikazio batzuetako segurtasun-akatsei esker lortutako pasahitz publikoen zerrendan sartuta dagoelako. Mesedez, erabili beste pasahitz bat.</target> + <target>Pasahitz hau datu-urratze batean agerian geratu da, ez da erabili behar. Mesedez, erabili beste pasahitz bat.</target> </trans-unit> <trans-unit id="94"> <source>This value should be between {{ min }} and {{ max }}.</source> @@ -368,7 +368,7 @@ </trans-unit> <trans-unit id="95"> <source>This value is not a valid hostname.</source> - <target>Balio hori ez da ostalari-izen onargarria.</target> + <target>Balio hau ez da ostalari-izen onargarria.</target> </trans-unit> <trans-unit id="96"> <source>The number of elements in this collection should be a multiple of {{ compared_value }}.</source> @@ -384,19 +384,19 @@ </trans-unit> <trans-unit id="99"> <source>This value is not a valid International Securities Identification Number (ISIN).</source> - <target>Balio hori ez da baliozko baloreen nazioarteko identifikazio-zenbaki bat (ISIN).</target> + <target>Balio hau ez da baliozko baloreen nazioarteko identifikazio-zenbaki bat (ISIN).</target> </trans-unit> <trans-unit id="100"> <source>This value should be a valid expression.</source> - <target>Balio hori baliozko adierazpena izan beharko litzateke.</target> + <target>Balio hau baliozko adierazpena izan beharko litzateke.</target> </trans-unit> <trans-unit id="101"> <source>This value is not a valid CSS color.</source> - <target>Balio hori ez da baliozko CSS kolorea.</target> + <target>Balio hau ez da baliozko CSS kolorea.</target> </trans-unit> <trans-unit id="102"> <source>This value is not a valid CIDR notation.</source> - <target>Balio hori ez da baliozko CIDR notazioa.</target> + <target>Balio hau ez da baliozko CIDR notazioa.</target> </trans-unit> <trans-unit id="103"> <source>The value of the netmask should be between {{ min }} and {{ max }}.</source> @@ -420,7 +420,7 @@ </trans-unit> <trans-unit id="108"> <source>Mixing numbers from different scripts is not allowed.</source> - <target>Ez da onartzen script ezberdinetako zenbakiak nahastea</target> + <target>Ez da onartzen script ezberdinetako zenbakiak nahastea.</target> </trans-unit> <trans-unit id="109"> <source>Using hidden overlay characters is not allowed.</source> @@ -428,223 +428,223 @@ </trans-unit> <trans-unit id="110"> <source>The extension of the file is invalid ({{ extension }}). Allowed extensions are {{ extensions }}.</source> - <target state="needs-review-translation">Fitxategiaren luzapena ez da zuzena ({{ extension }}). Baimendutako luzapenak hauek dira: {{ extensions }}.</target> + <target>Fitxategiaren luzapena ez da egokia ({{ extension }}). Hauek dira baimendutako luzapenak: {{ extensions }}.</target> </trans-unit> <trans-unit id="111"> <source>The detected character encoding is invalid ({{ detected }}). Allowed encodings are {{ encodings }}.</source> - <target state="needs-review-translation">Detektatutako karaktere-kodetzea ez da zuzena ({{ detected }}). Baimendutako kodetzeak hauek dira: {{ encodings }}.</target> + <target>Detektatutako karaktere-kodeketa ez da egokia ({{ detected }}). Hauek dira baimendutako kodeketak: {{ encodings }}.</target> </trans-unit> <trans-unit id="112"> <source>This value is not a valid MAC address.</source> - <target state="needs-review-translation">Balio hau ez da MAC helbide baliozko bat.</target> + <target>Balio hau ez da MAC helbide egoki bat.</target> </trans-unit> <trans-unit id="113"> <source>This URL is missing a top-level domain.</source> - <target state="needs-review-translation">URL honek ez du goi-mailako domeinurik.</target> + <target>URL honek ez du goi-mailako domeinurik.</target> </trans-unit> <trans-unit id="114"> <source>This value is too short. It should contain at least one word.|This value is too short. It should contain at least {{ min }} words.</source> - <target state="needs-review-translation">Balio hau oso laburra da. Gutxienez hitz bat izan behar du.|Balio hau oso laburra da. Gutxienez {{ min }} hitz izan behar ditu.</target> + <target>Balio hau motzegia da. Gutxienez hitz bat eduki beharko luke.|Balio hau motzegia da. Gutxienez {{ min }} hitz eduki beharko lituzke.</target> </trans-unit> <trans-unit id="115"> <source>This value is too long. It should contain one word.|This value is too long. It should contain {{ max }} words or less.</source> - <target state="needs-review-translation">Balio hau oso luzea da. Hitz bat bakarrik izan behar du.|Balio hau oso luzea da. {{ max }} hitz edo gutxiago izan behar ditu.</target> + <target>Balio hau luzeegia da. Hitz bakarra eduki beharko luke.|Balio hau luzeegia da. Gehienez {{ max }} hitz eduki beharko lituzke.</target> </trans-unit> <trans-unit id="116"> <source>This value does not represent a valid week in the ISO 8601 format.</source> - <target state="needs-review-translation">Balio honek ez du ISO 8601 formatuan aste baliozko bat adierazten.</target> + <target>Balio honek ez du ISO 8601 formatuko aste egoki bat adierazten.</target> </trans-unit> <trans-unit id="117"> <source>This value is not a valid week.</source> - <target state="needs-review-translation">Balio hau ez da aste balioduna.</target> + <target>Balio hau ez da aste egoki bat.</target> </trans-unit> <trans-unit id="118"> <source>This value should not be before week "{{ min }}".</source> - <target state="needs-review-translation">Balio hau ez luke aste "{{ min }}" baino lehenagokoa izan behar.</target> + <target>Balio hau ez litzateke "{{ min }}" astea baino lehenagokoa izan behar.</target> </trans-unit> <trans-unit id="119"> <source>This value should not be after week "{{ max }}".</source> - <target state="needs-review-translation">Balio hau ez luke astearen "{{ max }}" ondoren egon behar.</target> + <target>Balio hau ez litzateke "{{ max }}" astea baino geroagokoa izan behar.</target> </trans-unit> <trans-unit id="121"> <source>This value is not a valid Twig template.</source> - <target state="needs-review-translation">Balio hau ez da Twig txantiloi baliozko bat.</target> + <target>Balio hau ez da Twig txantiloi egoki bat.</target> </trans-unit> <trans-unit id="122"> <source>This file is not a valid video.</source> - <target state="needs-review-translation">Fitxategi hau ez da baliozko bideo bat.</target> + <target>Fitxategi hau ez da bideo egoki bat.</target> </trans-unit> <trans-unit id="123"> <source>The size of the video could not be detected.</source> - <target state="needs-review-translation">Ezin izan da bideoaren tamaina detektatu.</target> + <target>Ezin izan da bideoaren tamaina detektatu.</target> </trans-unit> <trans-unit id="124"> <source>The video width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.</source> - <target state="needs-review-translation">Bideoaren zabalera handiegia da ({{ width }}px). Baimendutako gehieneko zabalera {{ max_width }}px da.</target> + <target>Bideoaren zabalera handiegia da ({{ width }}px). Onartutako gehienezko zabalera {{ max_width }}px da.</target> </trans-unit> <trans-unit id="125"> <source>The video width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.</source> - <target state="needs-review-translation">Bideoaren zabalera txikiegia da ({{ width }}px). Gutxieneko espero den zabalera {{ min_width }}px da.</target> + <target>Bideoaren zabalera txikiegia da ({{ width }}px). Espero den gutxieneko zabalera {{ min_width }}px da.</target> </trans-unit> <trans-unit id="126"> <source>The video height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.</source> - <target state="needs-review-translation">Bideoaren altuera handiegia da ({{ height }}px). Onartutako gehienezko altuera {{ max_height }}px da.</target> + <target>Bideoaren altuera handiegia da ({{ height }}px). Onartutako gehienezko altuera {{ max_height }}px da.</target> </trans-unit> <trans-unit id="127"> <source>The video height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.</source> - <target state="needs-review-translation">Bideoaren altuera txikiegia da ({{ height }}px). Espero den gutxieneko altuera {{ min_height }}px da.</target> + <target>Bideoaren altuera txikiegia da ({{ height }}px). Espero den gutxieneko altuera {{ min_height }}px da.</target> </trans-unit> <trans-unit id="128"> <source>The video has too few pixels ({{ pixels }} pixels). Minimum amount expected is {{ min_pixels }} pixels.</source> - <target state="needs-review-translation">Bideoak pixel gutiegi ditu ({{ pixels }}). Gutxieneko espero den kopurua {{ min_pixels }} da.</target> + <target>Bideoak pixel gutxiegi ditu ({{ pixels }} pixel). Espero den gutxieneko kopurua {{ min_pixels }} pixel da.</target> </trans-unit> <trans-unit id="129"> <source>The video has too many pixels ({{ pixels }} pixels). Maximum amount expected is {{ max_pixels }} pixels.</source> - <target state="needs-review-translation">Bideoak pixel gehiegi ditu ({{ pixels }}). Espero den gehieneko kopurua {{ max_pixels }} da.</target> + <target>Bideoak pixel gehiegi ditu ({{ pixels }} pixel). Espero den gehienezko kopurua {{ max_pixels }} pixel da.</target> </trans-unit> <trans-unit id="130"> <source>The video ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.</source> - <target state="needs-review-translation">Bideoaren erlazioa handiegia da ({{ ratio }}). Onartutako gehieneko erlazioa {{ max_ratio }} da.</target> + <target>Bideoaren proportzioa handiegia da ({{ ratio }}). Onartutako gehienezko proportzioa {{ max_ratio }} da.</target> </trans-unit> <trans-unit id="131"> <source>The video ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.</source> - <target state="needs-review-translation">Bideoaren erlazioa txikiegia da ({{ ratio }}). Espero den gutxieneko erlazioa {{ min_ratio }} da.</target> + <target>Bideoaren proportzioa txikiegia da ({{ ratio }}). Espero den gutxieneko proportzioa {{ min_ratio }} da.</target> </trans-unit> <trans-unit id="132"> <source>The video is square ({{ width }}x{{ height }}px). Square videos are not allowed.</source> - <target state="needs-review-translation">Bideoa karratua da ({{ width }}x{{ height }}px). Bideo karratuak ez dira onartzen.</target> + <target>Bideoa karratua da ({{ width }}x{{ height }}px). Bideo karratuak ez dira onartzen.</target> </trans-unit> <trans-unit id="133"> <source>The video is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented videos are not allowed.</source> - <target state="needs-review-translation">Bideoa paisaia orientazioan dago ({{ width }}x{{ height }} px). Paisaia-orientazioko bideoak ez daude baimenduta.</target> + <target>Bideoa horizontalki orientatuta dago ({{ width }}x{{ height }}px). Horizontalki orientatutako bideoak ez dira onartzen.</target> </trans-unit> <trans-unit id="134"> <source>The video is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented videos are not allowed.</source> - <target state="needs-review-translation">Bideoa bertikal orientatuta dago ({{ width }}x{{ height }} px). Orientazio bertikaleko bideoak ez dira onartzen.</target> + <target>Bideoa bertikalki orientatuta dago ({{ width }}x{{ height }}px). Bertikalki orientatutako bideoak ez dira onartzen.</target> </trans-unit> <trans-unit id="135"> <source>The video file is corrupted.</source> - <target state="needs-review-translation">Bideo fitxategia hondatuta dago.</target> + <target>Bideo-fitxategia hondatuta dago.</target> </trans-unit> <trans-unit id="136"> <source>The video contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">Bideoak korronte anitz ditu. Korronte bakarra onartzen da.</target> + <target>Bideoak korronte bat baino gehiago ditu. Korronte bakarra onartzen da.</target> </trans-unit> <trans-unit id="137"> <source>Unsupported video codec "{{ codec }}".</source> - <target state="needs-review-translation">Bideo kodek onartugabea "{{ codec }}".</target> + <target>Ez da onartzen "{{ codec }}" bideo-kodeka.</target> </trans-unit> <trans-unit id="138"> <source>Unsupported video container "{{ container }}".</source> - <target state="needs-review-translation">Onartzen ez den bideo edukiontzia "{{ container }}".</target> + <target>Ez da onartzen "{{ container }}" bideo-edukiontzia.</target> </trans-unit> <trans-unit id="139"> <source>The image file is corrupted.</source> - <target state="needs-review-translation">Irudi fitxategia hondatuta dago.</target> + <target>Irudi-fitxategia hondatuta dago.</target> </trans-unit> <trans-unit id="140"> <source>The image has too few pixels ({{ pixels }} pixels). Minimum amount expected is {{ min_pixels }} pixels.</source> - <target state="needs-review-translation">Irudiak pixelen kopuru gutiegi du ({{ pixels }}). Espero den gutxienekoa {{ min_pixels }} da.</target> + <target>Irudiak pixel gutxiegi ditu ({{ pixels }} pixel). Espero den gutxieneko kopurua {{ min_pixels }} pixel da.</target> </trans-unit> <trans-unit id="141"> <source>The image has too many pixels ({{ pixels }} pixels). Maximum amount expected is {{ max_pixels }} pixels.</source> - <target state="needs-review-translation">Irudiak pixel gehiegi ditu ({{ pixels }}). Espero den gehienezko kopurua {{ max_pixels }} da.</target> + <target>Irudiak pixel gehiegi ditu ({{ pixels }} pixel). Espero den gehienezko kopurua {{ max_pixels }} pixel da.</target> </trans-unit> <trans-unit id="142"> <source>This filename does not match the expected charset.</source> - <target state="needs-review-translation">Fitxategi-izen honek ez du espero zen karaktere multzoarekin bat egiten.</target> + <target>Fitxategi-izen hau ez dator bat espero den karaktere-multzoarekin.</target> </trans-unit> <trans-unit id="143"> <source>This value is not valid XML.</source> - <target state="needs-review-translation">Balio hau ez da baliozko XML bat.</target> + <target>Balio hau ez da XML egoki bat.</target> </trans-unit> <trans-unit id="144"> <source>This value does not conform to the expected XSD schema.</source> - <target state="needs-review-translation">Balio hau ez dator bat espero den XSD eskemarekin.</target> + <target>Balio hau ez dator bat espero den XSD eskemarekin.</target> </trans-unit> <trans-unit id="145"> <source>This XML payload is too large ({{ size }} bytes): it exceeds the limit of {{ limit }} bytes.</source> - <target state="needs-review-translation">XML karga hau handiegia da ({{ size }} byte): {{ limit }} byteko muga gainditzen du.</target> + <target>XML karga hau handiegia da ({{ size }} byte): {{ limit }} byteko muga gainditzen du.</target> </trans-unit> <trans-unit id="146"> <source>This value is not a valid cron expression.</source> - <target state="needs-review-translation">Balio hau ez da baliozko cron adierazpena.</target> + <target>Balio hau ez da cron adierazpen egoki bat.</target> </trans-unit> <trans-unit id="147"> <source>The referenced entity does not exist.</source> - <target state="needs-review-translation">Erreferentziatutako entitatea ez da existitzen.</target> + <target>Erreferentziatutako entitatea ez da existitzen.</target> </trans-unit> <trans-unit id="148" resname="This is not a valid ULID."> <source>This value is not a valid ULID.</source> - <target state="needs-review-translation">Balio hau ez da ULID baliozko bat.</target> + <target>Balio hau ez da ULID egoki bat.</target> </trans-unit> <trans-unit id="149"> <source>This file is not a valid audio file.</source> - <target state="needs-review-translation">Fitxategi hau ez da baliozko audio fitxategi bat.</target> + <target>Fitxategi hau ez da audio-fitxategi egoki bat.</target> </trans-unit> <trans-unit id="150"> <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> - <target state="needs-review-translation">Audioa laburregia da ({{ duration }} segundo). Gutxieneko espero den iraupena {{ min_duration }} segundo da.</target> + <target>Audioa laburregia da ({{ duration }} segundo). Espero den gutxieneko iraupena {{ min_duration }} segundo da.</target> </trans-unit> <trans-unit id="151"> <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> - <target state="needs-review-translation">Audioa luzeegia da ({{ duration }} segundo). Baimendutako gehieneko iraupena {{ max_duration }} segundo da.</target> + <target>Audioa luzeegia da ({{ duration }} segundo). Onartutako gehienezko iraupena {{ max_duration }} segundo da.</target> </trans-unit> <trans-unit id="152"> <source>The duration of the audio could not be detected.</source> - <target state="needs-review-translation">Ezin izan da audioaren iraupena detektatu.</target> + <target>Ezin izan da audioaren iraupena detektatu.</target> </trans-unit> <trans-unit id="153"> <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> - <target state="needs-review-translation">Audioaren bit-emaria baxuegia da ({{ bitrate }} bps). Gutxieneko espero den bit-emaria {{ min_bitrate }} bps da.</target> + <target>Audioaren bit-emaria baxuegia da ({{ bitrate }} bps). Espero den gutxieneko bit-emaria {{ min_bitrate }} bps da.</target> </trans-unit> <trans-unit id="154"> <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> - <target state="needs-review-translation">Audioaren bit-emaria altuegia da ({{ bitrate }} bps). Baimendutako gehieneko bit-emaria {{ max_bitrate }} bps da.</target> + <target>Audioaren bit-emaria altuegia da ({{ bitrate }} bps). Onartutako gehienezko bit-emaria {{ max_bitrate }} bps da.</target> </trans-unit> <trans-unit id="155"> <source>The bitrate of the audio could not be detected.</source> - <target state="needs-review-translation">Ezin izan da audioaren bit-emaria detektatu.</target> + <target>Ezin izan da audioaren bit-emaria detektatu.</target> </trans-unit> <trans-unit id="156"> <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> - <target state="needs-review-translation">Onartzen ez den audioaren lagin-maiztasuna ({{ sample_rate }} Hz).</target> + <target>Audioaren lagin-maiztasuna ez da onartzen ({{ sample_rate }} Hz).</target> </trans-unit> <trans-unit id="157"> <source>The sample rate of the audio could not be detected.</source> - <target state="needs-review-translation">Ezin izan da audioaren lagin-maiztasuna detektatu.</target> + <target>Ezin izan da audioaren lagin-maiztasuna detektatu.</target> </trans-unit> <trans-unit id="158"> <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> - <target state="needs-review-translation">Audioak kanal gutxiegi ditu ({{ channels }}). Gutxieneko espero den kopurua {{ min_channels }} da.</target> + <target>Audioak kanal gutxiegi ditu ({{ channels }}). Espero den gutxieneko kopurua {{ min_channels }} da.</target> </trans-unit> <trans-unit id="159"> <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> - <target state="needs-review-translation">Audioak kanal gehiegi ditu ({{ channels }}). Espero den gehieneko kopurua {{ max_channels }} da.</target> + <target>Audioak kanal gehiegi ditu ({{ channels }}). Espero den gehienezko kopurua {{ max_channels }} da.</target> </trans-unit> <trans-unit id="160"> <source>The number of audio channels could not be detected.</source> - <target state="needs-review-translation">Ezin izan da audio kanalen kopurua detektatu.</target> + <target>Ezin izan da audio-kanalen kopurua detektatu.</target> </trans-unit> <trans-unit id="161"> <source>The audio file is corrupted.</source> - <target state="needs-review-translation">Audio fitxategia hondatuta dago.</target> + <target>Audio-fitxategia hondatuta dago.</target> </trans-unit> <trans-unit id="162"> <source>The audio contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">Audioak korronte anitz ditu. Korronte bakarra onartzen da.</target> + <target>Audioak korronte bat baino gehiago ditu. Korronte bakarra onartzen da.</target> </trans-unit> <trans-unit id="163"> <source>Unsupported audio codec "{{ codec }}".</source> - <target state="needs-review-translation">Audio kodek onartugabea "{{ codec }}".</target> + <target>Ez da onartzen "{{ codec }}" audio-kodeka.</target> </trans-unit> <trans-unit id="164"> <source>Unsupported audio container "{{ container }}".</source> - <target state="needs-review-translation">Onartzen ez den audio edukiontzia "{{ container }}".</target> + <target>Ez da onartzen "{{ container }}" audio-edukiontzia.</target> </trans-unit> <trans-unit id="165"> <source>The file does not contain any audio stream.</source> - <target state="needs-review-translation">Fitxategiak ez du audio korronterik.</target> + <target>Fitxategiak ez du audio korronterik.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.he.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.he.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.he.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.he.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -36,7 +36,7 @@ </trans-unit> <trans-unit id="9"> <source>This field was not expected.</source> - <target>שדה זה לא היה צפוי</target> + <target>שדה זה לא היה צפוי.</target> </trans-unit> <trans-unit id="10"> <source>This field is missing.</source> @@ -76,7 +76,7 @@ </trans-unit> <trans-unit id="19"> <source>This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.</source> - <target>הערך ארוך מידי. הוא צריך להכיל {{ limit }} תווים לכל היותר.|הערך ארוך מידי. הוא צריך להכיל {{ limit }} תווים לכל היותר.</target> + <target>הערך ארוך מדי. הוא צריך להכיל {{ limit }} תווים לכל היותר.|הערך ארוך מדי. הוא צריך להכיל {{ limit }} תווים לכל היותר.</target> </trans-unit> <trans-unit id="20"> <source>This value should be {{ limit }} or more.</source> @@ -84,7 +84,7 @@ </trans-unit> <trans-unit id="21"> <source>This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.</source> - <target>הערך קצר מידי. הוא צריך להכיל {{ limit }} תווים לפחות.|הערך קצר מידי. הערך צריך להכיל {{ limit }} תווים לפחות.</target> + <target>הערך קצר מדי. הוא צריך להכיל {{ limit }} תווים לפחות.|הערך קצר מדי. הערך צריך להכיל {{ limit }} תווים לפחות.</target> </trans-unit> <trans-unit id="22"> <source>This value should not be blank.</source> @@ -124,7 +124,7 @@ </trans-unit> <trans-unit id="34"> <source>The file could not be uploaded.</source> - <target>לא ניתן לעלות את הקובץ.</target> + <target>לא ניתן להעלות את הקובץ.</target> </trans-unit> <trans-unit id="35"> <source>This value should be a valid number.</source> @@ -372,7 +372,7 @@ </trans-unit> <trans-unit id="96"> <source>The number of elements in this collection should be a multiple of {{ compared_value }}.</source> - <target>מספר האלמנטים באוסף זה צריך להיות מכפיל של {{ compared_value }}.</target> + <target>מספר האלמנטים באוסף זה צריך להיות כפולה של {{ compared_value }}.</target> </trans-unit> <trans-unit id="97"> <source>This value should satisfy at least one of the following constraints:</source> @@ -556,95 +556,95 @@ </trans-unit> <trans-unit id="143"> <source>This value is not valid XML.</source> - <target state="needs-review-translation">ערך זה אינו XML תקין.</target> + <target>ערך זה אינו XML תקין.</target> </trans-unit> <trans-unit id="144"> <source>This value does not conform to the expected XSD schema.</source> - <target state="needs-review-translation">ערך זה אינו תואם לסכמת ה-XSD הצפויה.</target> + <target>ערך זה אינו תואם לסכמת ה-XSD הצפויה.</target> </trans-unit> <trans-unit id="145"> <source>This XML payload is too large ({{ size }} bytes): it exceeds the limit of {{ limit }} bytes.</source> - <target state="needs-review-translation">מטען ה-XML הזה גדול מדי ({{ size }} בתים): הוא חורג מהמגבלה של {{ limit }} בתים.</target> + <target>תוכן ה-XML הזה גדול מדי ({{ size }} בתים): הוא חורג מהמגבלה של {{ limit }} בתים.</target> </trans-unit> <trans-unit id="146"> <source>This value is not a valid cron expression.</source> - <target state="needs-review-translation">ערך זה אינו ביטוי cron תקין.</target> + <target>ערך זה אינו ביטוי cron תקין.</target> </trans-unit> <trans-unit id="147"> <source>The referenced entity does not exist.</source> - <target state="needs-review-translation">הישות שאליה מפנים אינה קיימת.</target> + <target>הישות שאליה מפנים אינה קיימת.</target> </trans-unit> <trans-unit id="148" resname="This is not a valid ULID."> <source>This value is not a valid ULID.</source> - <target state="needs-review-translation">ערך זה אינו ULID תקף.</target> + <target>ערך זה אינו ULID תקף.</target> </trans-unit> <trans-unit id="149"> <source>This file is not a valid audio file.</source> - <target state="needs-review-translation">קובץ זה אינו קובץ אודיו תקין.</target> + <target>קובץ זה אינו קובץ אודיו תקין.</target> </trans-unit> <trans-unit id="150"> <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> - <target state="needs-review-translation">האודיו קצר מדי ({{ duration }} שניות). משך מינימלי צפוי הוא {{ min_duration }} שניות.</target> + <target>האודיו קצר מדי ({{ duration }} שניות). משך מינימלי צפוי הוא {{ min_duration }} שניות.</target> </trans-unit> <trans-unit id="151"> <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> - <target state="needs-review-translation">האודיו ארוך מדי ({{ duration }} שניות). משך מרבי מותר הוא {{ max_duration }} שניות.</target> + <target>האודיו ארוך מדי ({{ duration }} שניות). משך מרבי מותר הוא {{ max_duration }} שניות.</target> </trans-unit> <trans-unit id="152"> <source>The duration of the audio could not be detected.</source> - <target state="needs-review-translation">לא ניתן היה לזהות את משך האודיו.</target> + <target>לא ניתן היה לזהות את משך האודיו.</target> </trans-unit> <trans-unit id="153"> <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> - <target state="needs-review-translation">קצב הסיביות של האודיו נמוך מדי ({{ bitrate }} bps). קצב סיביות מינימלי צפוי הוא {{ min_bitrate }} bps.</target> + <target>קצב הסיביות של האודיו נמוך מדי ({{ bitrate }} bps). קצב סיביות מינימלי צפוי הוא {{ min_bitrate }} bps.</target> </trans-unit> <trans-unit id="154"> <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> - <target state="needs-review-translation">קצב הסיביות של האודיו גבוה מדי ({{ bitrate }} bps). קצב סיביות מרבי מותר הוא {{ max_bitrate }} bps.</target> + <target>קצב הסיביות של האודיו גבוה מדי ({{ bitrate }} bps). קצב סיביות מרבי מותר הוא {{ max_bitrate }} bps.</target> </trans-unit> <trans-unit id="155"> <source>The bitrate of the audio could not be detected.</source> - <target state="needs-review-translation">לא ניתן היה לזהות את קצב הסיביות של האודיו.</target> + <target>לא ניתן היה לזהות את קצב הסיביות של האודיו.</target> </trans-unit> <trans-unit id="156"> <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> - <target state="needs-review-translation">קצב דגימת אודיו שאינו נתמך ({{ sample_rate }} Hz).</target> + <target>קצב דגימת אודיו שאינו נתמך ({{ sample_rate }} Hz).</target> </trans-unit> <trans-unit id="157"> <source>The sample rate of the audio could not be detected.</source> - <target state="needs-review-translation">לא ניתן היה לזהות את קצב הדגימה של האודיו.</target> + <target>לא ניתן היה לזהות את קצב הדגימה של האודיו.</target> </trans-unit> <trans-unit id="158"> <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> - <target state="needs-review-translation">לאודיו יש מעט מדי ערוצים ({{ channels }}). הכמות המינימלית הצפויה היא {{ min_channels }}.</target> + <target>לאודיו יש מעט מדי ערוצים ({{ channels }}). הכמות המינימלית הצפויה היא {{ min_channels }}.</target> </trans-unit> <trans-unit id="159"> <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> - <target state="needs-review-translation">לאודיו יש יותר מדי ערוצים ({{ channels }}). הכמות המרבית הצפויה היא {{ max_channels }}.</target> + <target>לאודיו יש יותר מדי ערוצים ({{ channels }}). הכמות המרבית הצפויה היא {{ max_channels }}.</target> </trans-unit> <trans-unit id="160"> <source>The number of audio channels could not be detected.</source> - <target state="needs-review-translation">לא ניתן היה לזהות את מספר ערוצי האודיו.</target> + <target>לא ניתן היה לזהות את מספר ערוצי האודיו.</target> </trans-unit> <trans-unit id="161"> <source>The audio file is corrupted.</source> - <target state="needs-review-translation">קובץ האודיו פגום.</target> + <target>קובץ האודיו פגום.</target> </trans-unit> <trans-unit id="162"> <source>The audio contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">האודיו מכיל מספר זרמים. מותר זרם אחד בלבד.</target> + <target>האודיו מכיל מספר זרמים. מותר זרם אחד בלבד.</target> </trans-unit> <trans-unit id="163"> <source>Unsupported audio codec "{{ codec }}".</source> - <target state="needs-review-translation">מקודד אודיו שאינו נתמך "{{ codec }}".</target> + <target>מקודד אודיו שאינו נתמך "{{ codec }}".</target> </trans-unit> <trans-unit id="164"> <source>Unsupported audio container "{{ container }}".</source> - <target state="needs-review-translation">מיכל אודיו שאינו נתמך "{{ container }}".</target> + <target>מיכל אודיו שאינו נתמך "{{ container }}".</target> </trans-unit> <trans-unit id="165"> <source>The file does not contain any audio stream.</source> - <target state="needs-review-translation">הקובץ אינו מכיל זרם אודיו.</target> + <target>הקובץ אינו מכיל זרם אודיו.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.hu.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.hu.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.hu.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.hu.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -452,7 +452,7 @@ </trans-unit> <trans-unit id="116"> <source>This value does not represent a valid week in the ISO 8601 format.</source> - <target>Ez a érték érvénytelen hetet jelent az ISO 8601 formátumban.</target> + <target>Ez az érték érvénytelen hetet jelent az ISO 8601 formátumban.</target> </trans-unit> <trans-unit id="117"> <source>This value is not a valid week.</source> @@ -460,11 +460,11 @@ </trans-unit> <trans-unit id="118"> <source>This value should not be before week "{{ min }}".</source> - <target>Ez az érték nem lehet a "{{ min }}". hétnél korábbi.</target> + <target>Ez az érték nem lehet korábbi a következő hétnél: {{ min }}.</target> </trans-unit> <trans-unit id="119"> <source>This value should not be after week "{{ max }}".</source> - <target>Ez az érték nem lehet a "{{ max }}". hétnél későbbi.</target> + <target>Ez az érték nem lehet későbbi a következő hétnél: {{ max }}.</target> </trans-unit> <trans-unit id="121"> <source>This value is not a valid Twig template.</source> @@ -532,11 +532,11 @@ </trans-unit> <trans-unit id="137"> <source>Unsupported video codec "{{ codec }}".</source> - <target>Nem támogatott videókodek „{{ codec }}".</target> + <target>Nem támogatott videókodek „{{ codec }}”.</target> </trans-unit> <trans-unit id="138"> <source>Unsupported video container "{{ container }}".</source> - <target>Nem támogatott videókonténer „{{ container }}".</target> + <target>Nem támogatott videókonténer „{{ container }}”.</target> </trans-unit> <trans-unit id="139"> <source>The image file is corrupted.</source> @@ -580,71 +580,71 @@ </trans-unit> <trans-unit id="149"> <source>This file is not a valid audio file.</source> - <target state="needs-review-translation">Ez a fájl nem érvényes hangfájl.</target> + <target>Ez a fájl nem érvényes hangfájl.</target> </trans-unit> <trans-unit id="150"> <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> - <target state="needs-review-translation">A hang túl rövid ({{ duration }} másodperc). Az elvárt legrövidebb hossz {{ min_duration }} másodperc.</target> + <target>A hanganyag túl rövid ({{ duration }} másodperc). Az elvárt legrövidebb időtartam {{ min_duration }} másodperc.</target> </trans-unit> <trans-unit id="151"> <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> - <target state="needs-review-translation">A hang túl hosszú ({{ duration }} másodperc). A megengedett leghosszabb hossz {{ max_duration }} másodperc.</target> + <target>A hanganyag túl hosszú ({{ duration }} másodperc). A megengedett leghosszabb időtartam {{ max_duration }} másodperc.</target> </trans-unit> <trans-unit id="152"> <source>The duration of the audio could not be detected.</source> - <target state="needs-review-translation">A hang hosszát nem sikerült megállapítani.</target> + <target>A hanganyag időtartamát nem sikerült megállapítani.</target> </trans-unit> <trans-unit id="153"> <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> - <target state="needs-review-translation">A hang bitrátája túl alacsony ({{ bitrate }} bps). Az elvárt legkisebb bitráta {{ min_bitrate }} bps.</target> + <target>A hanganyag bitrátája túl alacsony ({{ bitrate }} bps). Az elvárt legkisebb bitráta {{ min_bitrate }} bps.</target> </trans-unit> <trans-unit id="154"> <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> - <target state="needs-review-translation">A hang bitrátája túl magas ({{ bitrate }} bps). A megengedett legnagyobb bitráta {{ max_bitrate }} bps.</target> + <target>A hanganyag bitrátája túl magas ({{ bitrate }} bps). A megengedett legnagyobb bitráta {{ max_bitrate }} bps.</target> </trans-unit> <trans-unit id="155"> <source>The bitrate of the audio could not be detected.</source> - <target state="needs-review-translation">A hang bitrátáját nem sikerült megállapítani.</target> + <target>A hanganyag bitrátáját nem sikerült megállapítani.</target> </trans-unit> <trans-unit id="156"> <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> - <target state="needs-review-translation">Nem támogatott hangmintavételi frekvencia ({{ sample_rate }} Hz).</target> + <target>Nem támogatott hangmintavételi frekvencia ({{ sample_rate }} Hz).</target> </trans-unit> <trans-unit id="157"> <source>The sample rate of the audio could not be detected.</source> - <target state="needs-review-translation">A hang mintavételi frekvenciáját nem sikerült megállapítani.</target> + <target>A hanganyag mintavételi frekvenciáját nem sikerült megállapítani.</target> </trans-unit> <trans-unit id="158"> <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> - <target state="needs-review-translation">A hangban túl kevés a csatorna ({{ channels }}). Az elvárt legkisebb mennyiség {{ min_channels }}.</target> + <target>A hanganyagban túl kevés a csatorna ({{ channels }}). Az elvárt legkisebb mennyiség {{ min_channels }}.</target> </trans-unit> <trans-unit id="159"> <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> - <target state="needs-review-translation">A hangban túl sok a csatorna ({{ channels }}). A megengedett legnagyobb mennyiség {{ max_channels }}.</target> + <target>A hanganyagban túl sok a csatorna ({{ channels }}). A megengedett legnagyobb mennyiség {{ max_channels }}.</target> </trans-unit> <trans-unit id="160"> <source>The number of audio channels could not be detected.</source> - <target state="needs-review-translation">A hangcsatornák számát nem sikerült megállapítani.</target> + <target>A hangcsatornák számát nem sikerült megállapítani.</target> </trans-unit> <trans-unit id="161"> <source>The audio file is corrupted.</source> - <target state="needs-review-translation">A hangfájl sérült.</target> + <target>A hangfájl sérült.</target> </trans-unit> <trans-unit id="162"> <source>The audio contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">A hang több adatfolyamot tartalmaz. Csak egy adatfolyam engedélyezett.</target> + <target>A hanganyag több adatfolyamot tartalmaz. Csak egy adatfolyam engedélyezett.</target> </trans-unit> <trans-unit id="163"> <source>Unsupported audio codec "{{ codec }}".</source> - <target state="needs-review-translation">Nem támogatott hangkodek „{{ codec }}".</target> + <target>Nem támogatott hangkodek „{{ codec }}”.</target> </trans-unit> <trans-unit id="164"> <source>Unsupported audio container "{{ container }}".</source> - <target state="needs-review-translation">Nem támogatott hangkonténer „{{ container }}".</target> + <target>Nem támogatott hangkonténer „{{ container }}”.</target> </trans-unit> <trans-unit id="165"> <source>The file does not contain any audio stream.</source> - <target state="needs-review-translation">A fájl nem tartalmaz hang adatfolyamot.</target> + <target>A fájl nem tartalmaz hangadatfolyamot.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.mn.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.mn.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.mn.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.mn.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -248,7 +248,7 @@ </trans-unit> <trans-unit id="65"> <source>This value should be equal to {{ compared_value }}.</source> - <target>Энэ утга {{ compared_value }} -тaй тэнцүү байх ёстой.</target> + <target>Энэ утга {{ compared_value }} -тай тэнцүү байх ёстой.</target> </trans-unit> <trans-unit id="66"> <source>This value should be greater than {{ compared_value }}.</source> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -24,11 +24,11 @@ </trans-unit> <trans-unit id="6"> <source>You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.</source> - <target>Você deveria selecionar {{ limit }} opção no mínimo.|Você deveria selecionar {{ limit }} opções no mínimo.</target> + <target>Deve selecionar pelo menos {{ limit }} opção.|Deve selecionar pelo menos {{ limit }} opções.</target> </trans-unit> <trans-unit id="7"> <source>You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.</source> - <target>Você deve selecionar, no máximo {{ limit }} opção.|Você deve selecionar, no máximo {{ limit }} opções.</target> + <target>Deve selecionar no máximo {{ limit }} opção.|Deve selecionar no máximo {{ limit }} opções.</target> </trans-unit> <trans-unit id="8"> <source>One or more of the given values is invalid.</source> @@ -40,7 +40,7 @@ </trans-unit> <trans-unit id="10"> <source>This field is missing.</source> - <target>Este campo está faltando.</target> + <target>Este campo está em falta.</target> </trans-unit> <trans-unit id="11"> <source>This value is not a valid date.</source> @@ -108,7 +108,7 @@ </trans-unit> <trans-unit id="27"> <source>This value is not a valid URL.</source> - <target>Este valor não é uma URL válida.</target> + <target>Este valor não é um URL válido.</target> </trans-unit> <trans-unit id="31"> <source>The two values should be equal.</source> @@ -156,7 +156,7 @@ </trans-unit> <trans-unit id="42"> <source>The size of the image could not be detected.</source> - <target>O tamanho da imagem não foi detectado.</target> + <target>O tamanho da imagem não foi detetado.</target> </trans-unit> <trans-unit id="43"> <source>The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.</source> @@ -176,11 +176,11 @@ </trans-unit> <trans-unit id="47"> <source>This value should be the user's current password.</source> - <target>Este valor deveria ser a palvra-passe atual do usuário.</target> + <target>Este valor deveria ser a palavra-passe atual do utilizador.</target> </trans-unit> <trans-unit id="48"> <source>This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.</source> - <target>Este valor deve possuir exatamente {{ limit }} caractere.|Este valor deve possuir exatamente {{ limit }} caracteres.</target> + <target>Este valor deve ter exatamente {{ limit }} carácter.|Este valor deve ter exatamente {{ limit }} carateres.</target> </trans-unit> <trans-unit id="49"> <source>The file was only partially uploaded.</source> @@ -244,7 +244,7 @@ </trans-unit> <trans-unit id="64"> <source>This value is not a valid currency.</source> - <target>Este não é um valor monetário válido.</target> + <target>Este valor não é uma moeda válida.</target> </trans-unit> <trans-unit id="65"> <source>This value should be equal to {{ compared_value }}.</source> @@ -404,11 +404,11 @@ </trans-unit> <trans-unit id="104"> <source>The filename is too long. It should have {{ filename_max_length }} character or less.|The filename is too long. It should have {{ filename_max_length }} characters or less.</source> - <target>O nome do ficheiro é muito grande. Deveria ter {{ filename_max_length }} caractere ou menos.|O nome do ficheiro é muito grande. Deveria ter {{ filename_max_length }} caracteres ou menos.</target> + <target>O nome do ficheiro é demasiado longo. Deve ter {{ filename_max_length }} carácter ou menos.|O nome do ficheiro é demasiado longo. Deve ter {{ filename_max_length }} carateres ou menos.</target> </trans-unit> <trans-unit id="105"> <source>The password strength is too low. Please use a stronger password.</source> - <target>A força da palvra-passe é muito baixa. Por favor utilize uma palvra-passe mais forte.</target> + <target>A força da palavra-passe é demasiado baixa. Por favor, utilize uma palavra-passe mais forte.</target> </trans-unit> <trans-unit id="106"> <source>This value contains characters that are not allowed by the current restriction-level.</source> @@ -432,7 +432,7 @@ </trans-unit> <trans-unit id="111"> <source>The detected character encoding is invalid ({{ detected }}). Allowed encodings are {{ encodings }}.</source> - <target>A codificação de carateres detectada é inválida ({{ detected }}). As codificações permitidas são {{ encodings }}.</target> + <target>A codificação de carateres detetada é inválida ({{ detected }}). As codificações permitidas são {{ encodings }}.</target> </trans-unit> <trans-unit id="112"> <source>This value is not a valid MAC address.</source> @@ -440,7 +440,7 @@ </trans-unit> <trans-unit id="113"> <source>This URL is missing a top-level domain.</source> - <target>Esta URL está faltando o domínio de nível superior.</target> + <target>Falta o domínio de nível superior neste URL.</target> </trans-unit> <trans-unit id="114"> <source>This value is too short. It should contain at least one word.|This value is too short. It should contain at least {{ min }} words.</source> @@ -556,95 +556,95 @@ </trans-unit> <trans-unit id="143"> <source>This value is not valid XML.</source> - <target state="needs-review-translation">Este valor não é um XML válido.</target> + <target>Este valor não é um XML válido.</target> </trans-unit> <trans-unit id="144"> <source>This value does not conform to the expected XSD schema.</source> - <target state="needs-review-translation">Este valor não está em conformidade com o esquema XSD esperado.</target> + <target>Este valor não está em conformidade com o esquema XSD esperado.</target> </trans-unit> <trans-unit id="145"> <source>This XML payload is too large ({{ size }} bytes): it exceeds the limit of {{ limit }} bytes.</source> - <target state="needs-review-translation">Esta carga útil XML é demasiado grande ({{ size }} bytes): excede o limite de {{ limit }} bytes.</target> + <target>O conteúdo XML é demasiado grande ({{ size }} bytes): excede o limite de {{ limit }} bytes.</target> </trans-unit> <trans-unit id="146"> <source>This value is not a valid cron expression.</source> - <target state="needs-review-translation">Este valor não é uma expressão cron válida.</target> + <target>Este valor não é uma expressão cron válida.</target> </trans-unit> <trans-unit id="147"> <source>The referenced entity does not exist.</source> - <target state="needs-review-translation">A entidade referenciada não existe.</target> + <target>A entidade referenciada não existe.</target> </trans-unit> <trans-unit id="148" resname="This is not a valid ULID."> <source>This value is not a valid ULID.</source> - <target state="needs-review-translation">Este valor não é um ULID válido.</target> + <target>Este valor não é um ULID válido.</target> </trans-unit> <trans-unit id="149"> <source>This file is not a valid audio file.</source> - <target state="needs-review-translation">Este ficheiro não é um ficheiro de áudio válido.</target> + <target>Este ficheiro não é um ficheiro de áudio válido.</target> </trans-unit> <trans-unit id="150"> <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> - <target state="needs-review-translation">O áudio é demasiado curto ({{ duration }} segundos). A duração mínima esperada é {{ min_duration }} segundos.</target> + <target>O áudio é demasiado curto ({{ duration }} segundos). A duração mínima esperada é {{ min_duration }} segundos.</target> </trans-unit> <trans-unit id="151"> <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> - <target state="needs-review-translation">O áudio é demasiado longo ({{ duration }} segundos). A duração máxima permitida é {{ max_duration }} segundos.</target> + <target>O áudio é demasiado longo ({{ duration }} segundos). A duração máxima permitida é {{ max_duration }} segundos.</target> </trans-unit> <trans-unit id="152"> <source>The duration of the audio could not be detected.</source> - <target state="needs-review-translation">Não foi possível detetar a duração do áudio.</target> + <target>Não foi possível detetar a duração do áudio.</target> </trans-unit> <trans-unit id="153"> <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> - <target state="needs-review-translation">A taxa de bits do áudio é demasiado baixa ({{ bitrate }} bps). A taxa de bits mínima esperada é {{ min_bitrate }} bps.</target> + <target>A taxa de bits do áudio é demasiado baixa ({{ bitrate }} bps). A taxa de bits mínima esperada é {{ min_bitrate }} bps.</target> </trans-unit> <trans-unit id="154"> <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> - <target state="needs-review-translation">A taxa de bits do áudio é demasiado alta ({{ bitrate }} bps). A taxa de bits máxima permitida é {{ max_bitrate }} bps.</target> + <target>A taxa de bits do áudio é demasiado alta ({{ bitrate }} bps). A taxa de bits máxima permitida é {{ max_bitrate }} bps.</target> </trans-unit> <trans-unit id="155"> <source>The bitrate of the audio could not be detected.</source> - <target state="needs-review-translation">Não foi possível detetar a taxa de bits do áudio.</target> + <target>Não foi possível detetar a taxa de bits do áudio.</target> </trans-unit> <trans-unit id="156"> <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> - <target state="needs-review-translation">Taxa de amostragem de áudio ({{ sample_rate }} Hz) não suportada.</target> + <target>Taxa de amostragem de áudio ({{ sample_rate }} Hz) não suportada.</target> </trans-unit> <trans-unit id="157"> <source>The sample rate of the audio could not be detected.</source> - <target state="needs-review-translation">Não foi possível detetar a taxa de amostragem do áudio.</target> + <target>Não foi possível detetar a taxa de amostragem do áudio.</target> </trans-unit> <trans-unit id="158"> <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> - <target state="needs-review-translation">O áudio tem poucos canais ({{ channels }}). A quantidade mínima esperada é {{ min_channels }}.</target> + <target>O áudio tem poucos canais ({{ channels }}). A quantidade mínima esperada é {{ min_channels }}.</target> </trans-unit> <trans-unit id="159"> <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> - <target state="needs-review-translation">O áudio tem demasiados canais ({{ channels }}). A quantidade máxima esperada é {{ max_channels }}.</target> + <target>O áudio tem demasiados canais ({{ channels }}). A quantidade máxima esperada é {{ max_channels }}.</target> </trans-unit> <trans-unit id="160"> <source>The number of audio channels could not be detected.</source> - <target state="needs-review-translation">Não foi possível detetar o número de canais de áudio.</target> + <target>Não foi possível detetar o número de canais de áudio.</target> </trans-unit> <trans-unit id="161"> <source>The audio file is corrupted.</source> - <target state="needs-review-translation">O ficheiro de áudio está corrompido.</target> + <target>O ficheiro de áudio está corrompido.</target> </trans-unit> <trans-unit id="162"> <source>The audio contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">O áudio contém múltiplos fluxos. Apenas é permitido um fluxo.</target> + <target>O áudio contém múltiplos fluxos. Apenas é permitido um fluxo.</target> </trans-unit> <trans-unit id="163"> <source>Unsupported audio codec "{{ codec }}".</source> - <target state="needs-review-translation">Codec de áudio "{{ codec }}" não suportado.</target> + <target>Codec de áudio "{{ codec }}" não suportado.</target> </trans-unit> <trans-unit id="164"> <source>Unsupported audio container "{{ container }}".</source> - <target state="needs-review-translation">Contentor de áudio "{{ container }}" não suportado.</target> + <target>Contentor de áudio "{{ container }}" não suportado.</target> </trans-unit> <trans-unit id="165"> <source>The file does not contain any audio stream.</source> - <target state="needs-review-translation">O ficheiro não contém nenhum fluxo de áudio.</target> + <target>O ficheiro não contém nenhum fluxo de áudio.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.pt_BR.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -124,7 +124,7 @@ </trans-unit> <trans-unit id="34"> <source>The file could not be uploaded.</source> - <target>O arquivo não pode ser enviado.</target> + <target>O arquivo não pôde ser enviado.</target> </trans-unit> <trans-unit id="35"> <source>This value should be a valid number.</source> @@ -156,7 +156,7 @@ </trans-unit> <trans-unit id="42"> <source>The size of the image could not be detected.</source> - <target>O tamanho da imagem não pode ser detectado.</target> + <target>Não foi possível detectar o tamanho da imagem.</target> </trans-unit> <trans-unit id="43"> <source>The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.</source> @@ -244,7 +244,7 @@ </trans-unit> <trans-unit id="64"> <source>This value is not a valid currency.</source> - <target>Este não é um valor monetário válido.</target> + <target>Este valor não é uma moeda válida.</target> </trans-unit> <trans-unit id="65"> <source>This value should be equal to {{ compared_value }}.</source> @@ -288,15 +288,15 @@ </trans-unit> <trans-unit id="75"> <source>The image is square ({{ width }}x{{ height }}px). Square images are not allowed.</source> - <target>A imagem está num formato quadrado ({{ width }}x{{ height }}px). Imagens com formato quadrado não são permitidas.</target> + <target>A imagem é quadrada ({{ width }}x{{ height }}px). Imagens quadradas não são permitidas.</target> </trans-unit> <trans-unit id="76"> <source>The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.</source> - <target>A imagem está orientada à paisagem ({{ width }}x{{ height }}px). Imagens orientadas à paisagem não são permitidas.</target> + <target>A imagem está no modo paisagem ({{ width }}x{{ height }}px). Imagens no modo paisagem não são permitidas.</target> </trans-unit> <trans-unit id="77"> <source>The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.</source> - <target>A imagem está orientada ao retrato ({{ width }}x{{ height }}px). Imagens orientadas ao retrato não são permitidas.</target> + <target>A imagem está no modo retrato ({{ width }}x{{ height }}px). Imagens no modo retrato não são permitidas.</target> </trans-unit> <trans-unit id="78"> <source>An empty file is not allowed.</source> @@ -312,7 +312,7 @@ </trans-unit> <trans-unit id="81" resname="This is not a valid Business Identifier Code (BIC)."> <source>This value is not a valid Business Identifier Code (BIC).</source> - <target>Este valor não é um Código de Identificação de Negócios (BIC) válido.</target> + <target>Este valor não é um Código Identificador Bancário (BIC) válido.</target> </trans-unit> <trans-unit id="82"> <source>Error</source> @@ -360,7 +360,7 @@ </trans-unit> <trans-unit id="93"> <source>This password has been leaked in a data breach, it must not be used. Please use another password.</source> - <target>Esta senha foi divulgada num vazamento de dados e não deve ser utilizada. Por favor, utilize outra senha.</target> + <target>Esta senha foi divulgada em um vazamento de dados e não deve ser utilizada. Por favor, utilize outra senha.</target> </trans-unit> <trans-unit id="94"> <source>This value should be between {{ min }} and {{ max }}.</source> @@ -420,7 +420,7 @@ </trans-unit> <trans-unit id="108"> <source>Mixing numbers from different scripts is not allowed.</source> - <target>Misturar números de scripts diferentes não é permitido.</target> + <target>Não é permitido misturar números de sistemas de escrita diferentes.</target> </trans-unit> <trans-unit id="109"> <source>Using hidden overlay characters is not allowed.</source> @@ -440,7 +440,7 @@ </trans-unit> <trans-unit id="113"> <source>This URL is missing a top-level domain.</source> - <target>Esta URL está faltando o domínio de nível superior.</target> + <target>Esta URL não possui um domínio de nível superior.</target> </trans-unit> <trans-unit id="114"> <source>This value is too short. It should contain at least one word.|This value is too short. It should contain at least {{ min }} words.</source> @@ -464,7 +464,7 @@ </trans-unit> <trans-unit id="119"> <source>This value should not be after week "{{ max }}".</source> - <target>Este valor não deve estar após a semana "{{ max }}".</target> + <target>Este valor não deve ser posterior à semana "{{ max }}".</target> </trans-unit> <trans-unit id="121"> <source>This value is not a valid Twig template.</source> @@ -516,11 +516,11 @@ </trans-unit> <trans-unit id="133"> <source>The video is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented videos are not allowed.</source> - <target>O vídeo está no modo paisagem ({{ width }}x{{ height }}px). Vídeos em paisagem não são permitidos.</target> + <target>O vídeo está no modo paisagem ({{ width }}x{{ height }}px). Vídeos no modo paisagem não são permitidos.</target> </trans-unit> <trans-unit id="134"> <source>The video is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented videos are not allowed.</source> - <target>O vídeo está em orientação vertical ({{ width }}x{{ height }}px). Vídeos em orientação vertical não são permitidos.</target> + <target>O vídeo está no modo retrato ({{ width }}x{{ height }}px). Vídeos no modo retrato não são permitidos.</target> </trans-unit> <trans-unit id="135"> <source>The video file is corrupted.</source> @@ -544,7 +544,7 @@ </trans-unit> <trans-unit id="140"> <source>The image has too few pixels ({{ pixels }} pixels). Minimum amount expected is {{ min_pixels }} pixels.</source> - <target>A imagem tem pixels de menos ({{ pixels }}). A quantidade mínima esperada é {{ min_pixels }}.</target> + <target>A imagem tem poucos pixels ({{ pixels }}). A quantidade mínima esperada é {{ min_pixels }}.</target> </trans-unit> <trans-unit id="141"> <source>The image has too many pixels ({{ pixels }} pixels). Maximum amount expected is {{ max_pixels }} pixels.</source> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.tg.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.tg.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.tg.xlf 1970-01-01 00:00:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.tg.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -0,0 +1,651 @@ +<?xml version="1.0" encoding="utf-8"?> +<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2"> + <file source-language="en" target-language="tg" datatype="plaintext" original="file.ext"> + <body> + <trans-unit id="1"> + <source>This value should be false.</source> + <target>Ин қимат бояд false бошад.</target> + </trans-unit> + <trans-unit id="2"> + <source>This value should be true.</source> + <target>Ин қимат бояд true бошад.</target> + </trans-unit> + <trans-unit id="3"> + <source>This value should be of type {{ type }}.</source> + <target>Ин қимат бояд аз навъи {{ type }} бошад.</target> + </trans-unit> + <trans-unit id="4"> + <source>This value should be blank.</source> + <target>Ин қимат бояд холӣ бошад.</target> + </trans-unit> + <trans-unit id="5"> + <source>The value you selected is not a valid choice.</source> + <target>Қимати интихобкардаи шумо нодуруст аст.</target> + </trans-unit> + <trans-unit id="6"> + <source>You must select at least {{ limit }} choice.|You must select at least {{ limit }} choices.</source> + <target>Шумо бояд ҳадди ақал {{ limit }} вариант интихоб кунед.|Шумо бояд ҳадди ақал {{ limit }} вариант интихоб кунед.</target> + </trans-unit> + <trans-unit id="7"> + <source>You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.</source> + <target>Шумо бояд на зиёда аз {{ limit }} вариант интихоб кунед.|Шумо бояд на зиёда аз {{ limit }} вариант интихоб кунед.</target> + </trans-unit> + <trans-unit id="8"> + <source>One or more of the given values is invalid.</source> + <target>Як ё якчанд қимати додашуда нодуруст аст.</target> + </trans-unit> + <trans-unit id="9"> + <source>This field was not expected.</source> + <target>Ин майдон пешбинӣ нашудааст.</target> + </trans-unit> + <trans-unit id="10"> + <source>This field is missing.</source> + <target>Ин майдон мавҷуд нест.</target> + </trans-unit> + <trans-unit id="11"> + <source>This value is not a valid date.</source> + <target>Ин қимат санаи дуруст нест.</target> + </trans-unit> + <trans-unit id="12"> + <source>This value is not a valid datetime.</source> + <target>Ин қимат сана ва вақти дуруст нест.</target> + </trans-unit> + <trans-unit id="13"> + <source>This value is not a valid email address.</source> + <target>Ин қимат суроғаи электронии дуруст нест.</target> + </trans-unit> + <trans-unit id="14"> + <source>The file could not be found.</source> + <target>Файл ёфт нашуд.</target> + </trans-unit> + <trans-unit id="15"> + <source>The file is not readable.</source> + <target>Файлро хондан ғайриимкон аст.</target> + </trans-unit> + <trans-unit id="16"> + <source>The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.</source> + <target>Файл хеле калон аст ({{ size }} {{ suffix }}). Ҳаҷми ҳадди аксари иҷозатдодашуда {{ limit }} {{ suffix }} аст.</target> + </trans-unit> + <trans-unit id="17"> + <source>The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.</source> + <target>Навъи MIME-и файл нодуруст аст ({{ type }}). Навъҳои MIME-и иҷозатдодашуда: {{ types }}.</target> + </trans-unit> + <trans-unit id="18"> + <source>This value should be {{ limit }} or less.</source> + <target>Ин қимат бояд {{ limit }} ё камтар бошад.</target> + </trans-unit> + <trans-unit id="19"> + <source>This value is too long. It should have {{ limit }} character or less.|This value is too long. It should have {{ limit }} characters or less.</source> + <target>Ин қимат хеле дароз аст. Он бояд {{ limit }} аломат ё камтар дошта бошад.|Ин қимат хеле дароз аст. Он бояд {{ limit }} аломат ё камтар дошта бошад.</target> + </trans-unit> + <trans-unit id="20"> + <source>This value should be {{ limit }} or more.</source> + <target>Ин қимат бояд {{ limit }} ё зиёдтар бошад.</target> + </trans-unit> + <trans-unit id="21"> + <source>This value is too short. It should have {{ limit }} character or more.|This value is too short. It should have {{ limit }} characters or more.</source> + <target>Ин қимат хеле кӯтоҳ аст. Он бояд {{ limit }} аломат ё зиёдтар дошта бошад.|Ин қимат хеле кӯтоҳ аст. Он бояд {{ limit }} аломат ё зиёдтар дошта бошад.</target> + </trans-unit> + <trans-unit id="22"> + <source>This value should not be blank.</source> + <target>Ин қимат набояд холӣ бошад.</target> + </trans-unit> + <trans-unit id="23"> + <source>This value should not be null.</source> + <target>Ин қимат набояд null бошад.</target> + </trans-unit> + <trans-unit id="24"> + <source>This value should be null.</source> + <target>Ин қимат бояд null бошад.</target> + </trans-unit> + <trans-unit id="25"> + <source>This value is not valid.</source> + <target>Ин қимат нодуруст аст.</target> + </trans-unit> + <trans-unit id="26"> + <source>This value is not a valid time.</source> + <target>Ин қимат вақти дуруст нест.</target> + </trans-unit> + <trans-unit id="27"> + <source>This value is not a valid URL.</source> + <target>Ин қимат URL-и дуруст нест.</target> + </trans-unit> + <trans-unit id="31"> + <source>The two values should be equal.</source> + <target>Ҳарду қимат бояд баробар бошанд.</target> + </trans-unit> + <trans-unit id="32"> + <source>The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.</source> + <target>Файл хеле калон аст. Ҳаҷми ҳадди аксари иҷозатдодашуда {{ limit }} {{ suffix }} аст.</target> + </trans-unit> + <trans-unit id="33"> + <source>The file is too large.</source> + <target>Файл хеле калон аст.</target> + </trans-unit> + <trans-unit id="34"> + <source>The file could not be uploaded.</source> + <target>Файлро боргузорӣ кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="35"> + <source>This value should be a valid number.</source> + <target>Ин қимат бояд адади дуруст бошад.</target> + </trans-unit> + <trans-unit id="36"> + <source>This file is not a valid image.</source> + <target>Ин файл расми дуруст нест.</target> + </trans-unit> + <trans-unit id="37" resname="This is not a valid IP address."> + <source>This value is not a valid IP address.</source> + <target>Ин суроғаи дурусти IP нест.</target> + </trans-unit> + <trans-unit id="38"> + <source>This value is not a valid language.</source> + <target>Ин қимат забони дуруст нест.</target> + </trans-unit> + <trans-unit id="39"> + <source>This value is not a valid locale.</source> + <target>Ин қимат локали дуруст нест.</target> + </trans-unit> + <trans-unit id="40"> + <source>This value is not a valid country.</source> + <target>Ин қимат кишвари дуруст нест.</target> + </trans-unit> + <trans-unit id="41"> + <source>This value is already used.</source> + <target>Ин қимат аллакай истифода шудааст.</target> + </trans-unit> + <trans-unit id="42"> + <source>The size of the image could not be detected.</source> + <target>Андозаи расмро муайян кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="43"> + <source>The image width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.</source> + <target>Бари расм хеле калон аст ({{ width }}px). Ҳадди аксари бари иҷозатдодашуда {{ max_width }}px аст.</target> + </trans-unit> + <trans-unit id="44"> + <source>The image width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.</source> + <target>Бари расм хеле хурд аст ({{ width }}px). Ҳадди ақали бари интизоршаванда {{ min_width }}px аст.</target> + </trans-unit> + <trans-unit id="45"> + <source>The image height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.</source> + <target>Баландии расм хеле калон аст ({{ height }}px). Ҳадди аксари баландии иҷозатдодашуда {{ max_height }}px аст.</target> + </trans-unit> + <trans-unit id="46"> + <source>The image height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.</source> + <target>Баландии расм хеле хурд аст ({{ height }}px). Ҳадди ақали баландии интизоршаванда {{ min_height }}px аст.</target> + </trans-unit> + <trans-unit id="47"> + <source>This value should be the user's current password.</source> + <target>Ин қимат бояд пароли ҷории истифодабаранда бошад.</target> + </trans-unit> + <trans-unit id="48"> + <source>This value should have exactly {{ limit }} character.|This value should have exactly {{ limit }} characters.</source> + <target>Ин қимат бояд дақиқан {{ limit }} аломат дошта бошад.|Ин қимат бояд дақиқан {{ limit }} аломат дошта бошад.</target> + </trans-unit> + <trans-unit id="49"> + <source>The file was only partially uploaded.</source> + <target>Файл танҳо қисман боргузорӣ шуд.</target> + </trans-unit> + <trans-unit id="50"> + <source>No file was uploaded.</source> + <target>Ягон файл боргузорӣ нашуд.</target> + </trans-unit> + <trans-unit id="51" resname="No temporary folder was configured in php.ini."> + <source>No temporary folder was configured in php.ini, or the configured folder does not exist.</source> + <target>Дар php.ini ҷузвдони муваққатӣ танзим нашудааст.</target> + </trans-unit> + <trans-unit id="52"> + <source>Cannot write temporary file to disk.</source> + <target>Файли муваққатиро ба диск навиштан ғайриимкон аст.</target> + </trans-unit> + <trans-unit id="53"> + <source>A PHP extension caused the upload to fail.</source> + <target>Васеъшавии PHP боиси нокомии боргузорӣ гардид.</target> + </trans-unit> + <trans-unit id="54"> + <source>This collection should contain {{ limit }} element or more.|This collection should contain {{ limit }} elements or more.</source> + <target>Ин маҷмӯа бояд {{ limit }} элемент ё зиёдтар дошта бошад.|Ин маҷмӯа бояд {{ limit }} элемент ё зиёдтар дошта бошад.</target> + </trans-unit> + <trans-unit id="55"> + <source>This collection should contain {{ limit }} element or less.|This collection should contain {{ limit }} elements or less.</source> + <target>Ин маҷмӯа бояд {{ limit }} элемент ё камтар дошта бошад.|Ин маҷмӯа бояд {{ limit }} элемент ё камтар дошта бошад.</target> + </trans-unit> + <trans-unit id="56"> + <source>This collection should contain exactly {{ limit }} element.|This collection should contain exactly {{ limit }} elements.</source> + <target>Ин маҷмӯа бояд дақиқан {{ limit }} элемент дошта бошад.|Ин маҷмӯа бояд дақиқан {{ limit }} элемент дошта бошад.</target> + </trans-unit> + <trans-unit id="57"> + <source>Invalid card number.</source> + <target>Рақами корт нодуруст аст.</target> + </trans-unit> + <trans-unit id="58"> + <source>Unsupported card type or invalid card number.</source> + <target>Навъи корт дастгирӣ намешавад ё рақами корт нодуруст аст.</target> + </trans-unit> + <trans-unit id="59" resname="This is not a valid International Bank Account Number (IBAN)."> + <source>This value is not a valid International Bank Account Number (IBAN).</source> + <target>Ин рақами дурусти байналмилалии суратҳисоби бонкӣ (IBAN) нест.</target> + </trans-unit> + <trans-unit id="60"> + <source>This value is not a valid ISBN-10.</source> + <target>Ин қимат ISBN-10-и дуруст нест.</target> + </trans-unit> + <trans-unit id="61"> + <source>This value is not a valid ISBN-13.</source> + <target>Ин қимат ISBN-13-и дуруст нест.</target> + </trans-unit> + <trans-unit id="62"> + <source>This value is neither a valid ISBN-10 nor a valid ISBN-13.</source> + <target>Ин қимат на ISBN-10-и дуруст аст, на ISBN-13-и дуруст.</target> + </trans-unit> + <trans-unit id="63"> + <source>This value is not a valid ISSN.</source> + <target>Ин қимат ISSN-и дуруст нест.</target> + </trans-unit> + <trans-unit id="64"> + <source>This value is not a valid currency.</source> + <target>Ин қимат асъори дуруст нест.</target> + </trans-unit> + <trans-unit id="65"> + <source>This value should be equal to {{ compared_value }}.</source> + <target>Ин қимат бояд ба {{ compared_value }} баробар бошад.</target> + </trans-unit> + <trans-unit id="66"> + <source>This value should be greater than {{ compared_value }}.</source> + <target>Ин қимат бояд аз {{ compared_value }} зиёд бошад.</target> + </trans-unit> + <trans-unit id="67"> + <source>This value should be greater than or equal to {{ compared_value }}.</source> + <target>Ин қимат бояд аз {{ compared_value }} зиёд ё баробар бошад.</target> + </trans-unit> + <trans-unit id="68"> + <source>This value should be identical to {{ compared_value_type }} {{ compared_value }}.</source> + <target>Ин қимат бояд бо {{ compared_value_type }} {{ compared_value }} айнан якхела бошад.</target> + </trans-unit> + <trans-unit id="69"> + <source>This value should be less than {{ compared_value }}.</source> + <target>Ин қимат бояд аз {{ compared_value }} камтар бошад.</target> + </trans-unit> + <trans-unit id="70"> + <source>This value should be less than or equal to {{ compared_value }}.</source> + <target>Ин қимат бояд аз {{ compared_value }} камтар ё баробар бошад.</target> + </trans-unit> + <trans-unit id="71"> + <source>This value should not be equal to {{ compared_value }}.</source> + <target>Ин қимат набояд ба {{ compared_value }} баробар бошад.</target> + </trans-unit> + <trans-unit id="72"> + <source>This value should not be identical to {{ compared_value_type }} {{ compared_value }}.</source> + <target>Ин қимат набояд бо {{ compared_value_type }} {{ compared_value }} айнан якхела бошад.</target> + </trans-unit> + <trans-unit id="73"> + <source>The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.</source> + <target>Таносуби тарафҳои расм хеле калон аст ({{ ratio }}). Ҳадди аксари таносуби иҷозатдодашуда {{ max_ratio }} аст.</target> + </trans-unit> + <trans-unit id="74"> + <source>The image ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.</source> + <target>Таносуби тарафҳои расм хеле хурд аст ({{ ratio }}). Ҳадди ақали таносуби интизоршаванда {{ min_ratio }} аст.</target> + </trans-unit> + <trans-unit id="75"> + <source>The image is square ({{ width }}x{{ height }}px). Square images are not allowed.</source> + <target>Расм мураббаъ аст ({{ width }}x{{ height }}px). Расмҳои мураббаъ иҷозат дода намешаванд.</target> + </trans-unit> + <trans-unit id="76"> + <source>The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.</source> + <target>Расм уфуқӣ аст ({{ width }}x{{ height }}px). Расмҳои уфуқӣ иҷозат дода намешаванд.</target> + </trans-unit> + <trans-unit id="77"> + <source>The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.</source> + <target>Расм амудӣ аст ({{ width }}x{{ height }}px). Расмҳои амудӣ иҷозат дода намешаванд.</target> + </trans-unit> + <trans-unit id="78"> + <source>An empty file is not allowed.</source> + <target>Файли холӣ иҷозат дода намешавад.</target> + </trans-unit> + <trans-unit id="79"> + <source>The host could not be resolved.</source> + <target>Хостро муайян кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="80"> + <source>This value does not match the expected {{ charset }} charset.</source> + <target>Ин қимат ба рамзгузории интизоршавандаи {{ charset }} мувофиқат намекунад.</target> + </trans-unit> + <trans-unit id="81" resname="This is not a valid Business Identifier Code (BIC)."> + <source>This value is not a valid Business Identifier Code (BIC).</source> + <target>Ин рамзи дурусти мушаххаскунандаи бизнес (BIC) нест.</target> + </trans-unit> + <trans-unit id="82"> + <source>Error</source> + <target>Хато</target> + </trans-unit> + <trans-unit id="83" resname="This is not a valid UUID."> + <source>This value is not a valid UUID.</source> + <target>Ин UUID-и дуруст нест.</target> + </trans-unit> + <trans-unit id="84"> + <source>This value should be a multiple of {{ compared_value }}.</source> + <target>Ин қимат бояд ба {{ compared_value }} бе боқимонда тақсим шавад.</target> + </trans-unit> + <trans-unit id="85"> + <source>This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}.</source> + <target>Ин рамзи мушаххаскунандаи бизнес (BIC) бо IBAN {{ iban }} алоқаманд нест.</target> + </trans-unit> + <trans-unit id="86"> + <source>This value should be valid JSON.</source> + <target>Ин қимат бояд JSON-и дуруст бошад.</target> + </trans-unit> + <trans-unit id="87"> + <source>This collection should contain only unique elements.</source> + <target>Ин маҷмӯа бояд танҳо элементҳои такрорнашаванда дошта бошад.</target> + </trans-unit> + <trans-unit id="88"> + <source>This value should be positive.</source> + <target>Ин қимат бояд мусбат бошад.</target> + </trans-unit> + <trans-unit id="89"> + <source>This value should be either positive or zero.</source> + <target>Ин қимат бояд мусбат ё ба сифр баробар бошад.</target> + </trans-unit> + <trans-unit id="90"> + <source>This value should be negative.</source> + <target>Ин қимат бояд манфӣ бошад.</target> + </trans-unit> + <trans-unit id="91"> + <source>This value should be either negative or zero.</source> + <target>Ин қимат бояд манфӣ ё ба сифр баробар бошад.</target> + </trans-unit> + <trans-unit id="92"> + <source>This value is not a valid timezone.</source> + <target>Ин қимат минтақаи вақти дуруст нест.</target> + </trans-unit> + <trans-unit id="93"> + <source>This password has been leaked in a data breach, it must not be used. Please use another password.</source> + <target>Ин парол дар маълумоти ифшошуда дида шудааст ва набояд истифода шавад. Лутфан пароли дигарро истифода баред.</target> + </trans-unit> + <trans-unit id="94"> + <source>This value should be between {{ min }} and {{ max }}.</source> + <target>Ин қимат бояд байни {{ min }} ва {{ max }} бошад.</target> + </trans-unit> + <trans-unit id="95"> + <source>This value is not a valid hostname.</source> + <target>Ин қимат номи хости дуруст нест.</target> + </trans-unit> + <trans-unit id="96"> + <source>The number of elements in this collection should be a multiple of {{ compared_value }}.</source> + <target>Миқдори элементҳои ин маҷмӯа бояд ба {{ compared_value }} бе боқимонда тақсим шавад.</target> + </trans-unit> + <trans-unit id="97"> + <source>This value should satisfy at least one of the following constraints:</source> + <target>Ин қимат бояд ҳадди ақал ба яке аз маҳдудиятҳои зерин мувофиқат кунад:</target> + </trans-unit> + <trans-unit id="98"> + <source>Each element of this collection should satisfy its own set of constraints.</source> + <target>Ҳар як элементи ин маҷмӯа бояд ба маҷмӯи маҳдудиятҳои худ мувофиқат кунад.</target> + </trans-unit> + <trans-unit id="99"> + <source>This value is not a valid International Securities Identification Number (ISIN).</source> + <target>Ин қимат рақами дурусти байналмилалии мушаххаскунандаи коғазҳои қиматнок (ISIN) нест.</target> + </trans-unit> + <trans-unit id="100"> + <source>This value should be a valid expression.</source> + <target>Ин қимат бояд ифодаи дуруст бошад.</target> + </trans-unit> + <trans-unit id="101"> + <source>This value is not a valid CSS color.</source> + <target>Ин қимат ранги дурусти CSS нест.</target> + </trans-unit> + <trans-unit id="102"> + <source>This value is not a valid CIDR notation.</source> + <target>Ин қимат ба навишти CIDR мувофиқат намекунад.</target> + </trans-unit> + <trans-unit id="103"> + <source>The value of the netmask should be between {{ min }} and {{ max }}.</source> + <target>Қимати маскаи шабака бояд байни {{ min }} ва {{ max }} бошад.</target> + </trans-unit> + <trans-unit id="104"> + <source>The filename is too long. It should have {{ filename_max_length }} character or less.|The filename is too long. It should have {{ filename_max_length }} characters or less.</source> + <target>Номи файл хеле дароз аст. Он бояд {{ filename_max_length }} аломат ё камтар дошта бошад.|Номи файл хеле дароз аст. Он бояд {{ filename_max_length }} аломат ё камтар дошта бошад.</target> + </trans-unit> + <trans-unit id="105"> + <source>The password strength is too low. Please use a stronger password.</source> + <target>Мустаҳкамии парол хеле паст аст. Лутфан пароли мустаҳкамтарро истифода баред.</target> + </trans-unit> + <trans-unit id="106"> + <source>This value contains characters that are not allowed by the current restriction-level.</source> + <target>Ин қимат аломатҳоеро дар бар мегирад, ки дар сатҳи ҷории маҳдудият иҷозат дода намешаванд.</target> + </trans-unit> + <trans-unit id="107"> + <source>Using invisible characters is not allowed.</source> + <target>Истифодаи аломатҳои ноаён иҷозат дода намешавад.</target> + </trans-unit> + <trans-unit id="108"> + <source>Mixing numbers from different scripts is not allowed.</source> + <target>Омехта кардани рақамҳо аз хатҳои гуногун иҷозат дода намешавад.</target> + </trans-unit> + <trans-unit id="109"> + <source>Using hidden overlay characters is not allowed.</source> + <target>Истифодаи аломатҳои пинҳонии болопӯш иҷозат дода намешавад.</target> + </trans-unit> + <trans-unit id="110"> + <source>The extension of the file is invalid ({{ extension }}). Allowed extensions are {{ extensions }}.</source> + <target>Пасванди файл нодуруст аст ({{ extension }}). Пасвандҳои иҷозатдодашуда: {{ extensions }}.</target> + </trans-unit> + <trans-unit id="111"> + <source>The detected character encoding is invalid ({{ detected }}). Allowed encodings are {{ encodings }}.</source> + <target>Рамзгузории муайяншудаи аломатҳо нодуруст аст ({{ detected }}). Рамзгузориҳои иҷозатдодашуда: {{ encodings }}.</target> + </trans-unit> + <trans-unit id="112"> + <source>This value is not a valid MAC address.</source> + <target>Ин қимат суроғаи дурусти MAC нест.</target> + </trans-unit> + <trans-unit id="113"> + <source>This URL is missing a top-level domain.</source> + <target>Дар ин URL домени сатҳи боло мавҷуд нест.</target> + </trans-unit> + <trans-unit id="114"> + <source>This value is too short. It should contain at least one word.|This value is too short. It should contain at least {{ min }} words.</source> + <target>Ин қимат хеле кӯтоҳ аст. Он бояд ҳадди ақал {{ min }} калима дошта бошад.|Ин қимат хеле кӯтоҳ аст. Он бояд ҳадди ақал {{ min }} калима дошта бошад.</target> + </trans-unit> + <trans-unit id="115"> + <source>This value is too long. It should contain one word.|This value is too long. It should contain {{ max }} words or less.</source> + <target>Ин қимат хеле дароз аст. Он бояд {{ max }} калима ё камтар дошта бошад.|Ин қимат хеле дароз аст. Он бояд {{ max }} калима ё камтар дошта бошад.</target> + </trans-unit> + <trans-unit id="116"> + <source>This value does not represent a valid week in the ISO 8601 format.</source> + <target>Ин қимат ҳафтаи дурустро дар формати ISO 8601 ифода намекунад.</target> + </trans-unit> + <trans-unit id="117"> + <source>This value is not a valid week.</source> + <target>Ин қимат ҳафтаи дуруст нест.</target> + </trans-unit> + <trans-unit id="118"> + <source>This value should not be before week "{{ min }}".</source> + <target>Ин қимат набояд пеш аз ҳафтаи «{{ min }}» бошад.</target> + </trans-unit> + <trans-unit id="119"> + <source>This value should not be after week "{{ max }}".</source> + <target>Ин қимат набояд баъд аз ҳафтаи «{{ max }}» бошад.</target> + </trans-unit> + <trans-unit id="121"> + <source>This value is not a valid Twig template.</source> + <target>Ин қимат қолаби дурусти Twig нест.</target> + </trans-unit> + <trans-unit id="122"> + <source>This file is not a valid video.</source> + <target>Ин файл видеои дуруст нест.</target> + </trans-unit> + <trans-unit id="123"> + <source>The size of the video could not be detected.</source> + <target>Андозаи видеоро муайян кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="124"> + <source>The video width is too big ({{ width }}px). Allowed maximum width is {{ max_width }}px.</source> + <target>Бари видео хеле калон аст ({{ width }}px). Ҳадди аксари бари иҷозатдодашуда {{ max_width }}px аст.</target> + </trans-unit> + <trans-unit id="125"> + <source>The video width is too small ({{ width }}px). Minimum width expected is {{ min_width }}px.</source> + <target>Бари видео хеле хурд аст ({{ width }}px). Ҳадди ақали бари интизоршаванда {{ min_width }}px аст.</target> + </trans-unit> + <trans-unit id="126"> + <source>The video height is too big ({{ height }}px). Allowed maximum height is {{ max_height }}px.</source> + <target>Баландии видео хеле калон аст ({{ height }}px). Ҳадди аксари баландии иҷозатдодашуда {{ max_height }}px аст.</target> + </trans-unit> + <trans-unit id="127"> + <source>The video height is too small ({{ height }}px). Minimum height expected is {{ min_height }}px.</source> + <target>Баландии видео хеле хурд аст ({{ height }}px). Ҳадди ақали баландии интизоршаванда {{ min_height }}px аст.</target> + </trans-unit> + <trans-unit id="128"> + <source>The video has too few pixels ({{ pixels }} pixels). Minimum amount expected is {{ min_pixels }} pixels.</source> + <target>Видео пикселҳои хеле кам дорад ({{ pixels }} пиксел). Ҳадди ақали миқдори интизоршаванда {{ min_pixels }} пиксел аст.</target> + </trans-unit> + <trans-unit id="129"> + <source>The video has too many pixels ({{ pixels }} pixels). Maximum amount expected is {{ max_pixels }} pixels.</source> + <target>Видео пикселҳои хеле зиёд дорад ({{ pixels }} пиксел). Ҳадди аксари миқдори интизоршаванда {{ max_pixels }} пиксел аст.</target> + </trans-unit> + <trans-unit id="130"> + <source>The video ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.</source> + <target>Таносуби тарафҳои видео хеле калон аст ({{ ratio }}). Ҳадди аксари таносуби иҷозатдодашуда {{ max_ratio }} аст.</target> + </trans-unit> + <trans-unit id="131"> + <source>The video ratio is too small ({{ ratio }}). Minimum ratio expected is {{ min_ratio }}.</source> + <target>Таносуби тарафҳои видео хеле хурд аст ({{ ratio }}). Ҳадди ақали таносуби интизоршаванда {{ min_ratio }} аст.</target> + </trans-unit> + <trans-unit id="132"> + <source>The video is square ({{ width }}x{{ height }}px). Square videos are not allowed.</source> + <target>Видео мураббаъ аст ({{ width }}x{{ height }}px). Видеоҳои мураббаъ иҷозат дода намешаванд.</target> + </trans-unit> + <trans-unit id="133"> + <source>The video is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented videos are not allowed.</source> + <target>Видео уфуқӣ аст ({{ width }}x{{ height }}px). Видеоҳои уфуқӣ иҷозат дода намешаванд.</target> + </trans-unit> + <trans-unit id="134"> + <source>The video is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented videos are not allowed.</source> + <target>Видео амудӣ аст ({{ width }}x{{ height }}px). Видеоҳои амудӣ иҷозат дода намешаванд.</target> + </trans-unit> + <trans-unit id="135"> + <source>The video file is corrupted.</source> + <target>Файли видео вайрон шудааст.</target> + </trans-unit> + <trans-unit id="136"> + <source>The video contains multiple streams. Only one stream is allowed.</source> + <target>Видео якчанд ҷараён дорад. Танҳо як ҷараён иҷозат дода мешавад.</target> + </trans-unit> + <trans-unit id="137"> + <source>Unsupported video codec "{{ codec }}".</source> + <target>Кодеки видеоии «{{ codec }}» дастгирӣ намешавад.</target> + </trans-unit> + <trans-unit id="138"> + <source>Unsupported video container "{{ container }}".</source> + <target>Контейнери видеоии «{{ container }}» дастгирӣ намешавад.</target> + </trans-unit> + <trans-unit id="139"> + <source>The image file is corrupted.</source> + <target>Файли расм вайрон шудааст.</target> + </trans-unit> + <trans-unit id="140"> + <source>The image has too few pixels ({{ pixels }} pixels). Minimum amount expected is {{ min_pixels }} pixels.</source> + <target>Расм пикселҳои хеле кам дорад ({{ pixels }} пиксел). Ҳадди ақали миқдори интизоршаванда {{ min_pixels }} пиксел аст.</target> + </trans-unit> + <trans-unit id="141"> + <source>The image has too many pixels ({{ pixels }} pixels). Maximum amount expected is {{ max_pixels }} pixels.</source> + <target>Расм пикселҳои хеле зиёд дорад ({{ pixels }} пиксел). Ҳадди аксари миқдори интизоршаванда {{ max_pixels }} пиксел аст.</target> + </trans-unit> + <trans-unit id="142"> + <source>This filename does not match the expected charset.</source> + <target>Ин номи файл ба рамзгузории интизоршаванда мувофиқат намекунад.</target> + </trans-unit> + <trans-unit id="143"> + <source>This value is not valid XML.</source> + <target>Ин қимат XML-и дуруст нест.</target> + </trans-unit> + <trans-unit id="144"> + <source>This value does not conform to the expected XSD schema.</source> + <target>Ин қимат ба схемаи интизоршавандаи XSD мувофиқат намекунад.</target> + </trans-unit> + <trans-unit id="145"> + <source>This XML payload is too large ({{ size }} bytes): it exceeds the limit of {{ limit }} bytes.</source> + <target>Ҳаҷми маълумоти XML хеле калон аст ({{ size }} байт): он аз ҳадди {{ limit }} байт зиёд аст.</target> + </trans-unit> + <trans-unit id="146"> + <source>This value is not a valid cron expression.</source> + <target>Ин қимат ифодаи дурусти cron нест.</target> + </trans-unit> + <trans-unit id="147"> + <source>The referenced entity does not exist.</source> + <target>Объекти истинодшуда мавҷуд нест.</target> + </trans-unit> + <trans-unit id="148" resname="This is not a valid ULID."> + <source>This value is not a valid ULID.</source> + <target>Ин ULID-и дуруст нест.</target> + </trans-unit> + <trans-unit id="149"> + <source>This file is not a valid audio file.</source> + <target>Ин файл файли аудиоии дуруст нест.</target> + </trans-unit> + <trans-unit id="150"> + <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> + <target>Аудио хеле кӯтоҳ аст ({{ duration }} сония). Ҳадди ақали давомнокии интизоршаванда {{ min_duration }} сония аст.</target> + </trans-unit> + <trans-unit id="151"> + <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> + <target>Аудио хеле дароз аст ({{ duration }} сония). Ҳадди аксари давомнокии иҷозатдодашуда {{ max_duration }} сония аст.</target> + </trans-unit> + <trans-unit id="152"> + <source>The duration of the audio could not be detected.</source> + <target>Давомнокии аудиоро муайян кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="153"> + <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> + <target>Битрейти аудио хеле паст аст ({{ bitrate }} бит/с). Ҳадди ақали битрейти интизоршаванда {{ min_bitrate }} бит/с аст.</target> + </trans-unit> + <trans-unit id="154"> + <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> + <target>Битрейти аудио хеле баланд аст ({{ bitrate }} бит/с). Ҳадди аксари битрейти иҷозатдодашуда {{ max_bitrate }} бит/с аст.</target> + </trans-unit> + <trans-unit id="155"> + <source>The bitrate of the audio could not be detected.</source> + <target>Битрейти аудиоро муайян кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="156"> + <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> + <target>Басомади намунагирии аудио ({{ sample_rate }} Гс) дастгирӣ намешавад.</target> + </trans-unit> + <trans-unit id="157"> + <source>The sample rate of the audio could not be detected.</source> + <target>Басомади намунагирии аудиоро муайян кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="158"> + <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> + <target>Аудио каналҳои хеле кам дорад ({{ channels }}). Ҳадди ақали миқдори интизоршаванда {{ min_channels }} аст.</target> + </trans-unit> + <trans-unit id="159"> + <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> + <target>Аудио каналҳои хеле зиёд дорад ({{ channels }}). Ҳадди аксари миқдори интизоршаванда {{ max_channels }} аст.</target> + </trans-unit> + <trans-unit id="160"> + <source>The number of audio channels could not be detected.</source> + <target>Миқдори каналҳои аудиоро муайян кардан муяссар нашуд.</target> + </trans-unit> + <trans-unit id="161"> + <source>The audio file is corrupted.</source> + <target>Файли аудио вайрон шудааст.</target> + </trans-unit> + <trans-unit id="162"> + <source>The audio contains multiple streams. Only one stream is allowed.</source> + <target>Аудио якчанд ҷараён дорад. Танҳо як ҷараён иҷозат дода мешавад.</target> + </trans-unit> + <trans-unit id="163"> + <source>Unsupported audio codec "{{ codec }}".</source> + <target>Кодеки аудиоии «{{ codec }}» дастгирӣ намешавад.</target> + </trans-unit> + <trans-unit id="164"> + <source>Unsupported audio container "{{ container }}".</source> + <target>Контейнери аудиоии «{{ container }}» дастгирӣ намешавад.</target> + </trans-unit> + <trans-unit id="165"> + <source>The file does not contain any audio stream.</source> + <target>Файл ягон ҷараёни аудиоӣ надорад.</target> + </trans-unit> + </body> + </file> +</xliff> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.uz.xlf symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.uz.xlf --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.uz.xlf 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Resources/translations/validators.uz.xlf 2026-11-25 09:18:34.000000000 +0000 @@ -28,7 +28,7 @@ </trans-unit> <trans-unit id="7"> <source>You must select at most {{ limit }} choice.|You must select at most {{ limit }} choices.</source> - <target>Siz {{ limit }} ta qiymatni tanlashingiz kerak.|Siz {{ limit }} dan ortiq qiymat tanlashingiz kerak.</target> + <target>Siz ko'pi bilan {{ limit }} ta qiymat tanlashingiz kerak.|Siz ko'pi bilan {{ limit }} ta qiymat tanlashingiz kerak.</target> </trans-unit> <trans-unit id="8"> <source>One or more of the given values is invalid.</source> @@ -40,7 +40,7 @@ </trans-unit> <trans-unit id="10"> <source>This field is missing.</source> - <target>Bu maydon majvud emas.</target> + <target>Bu maydon mavjud emas.</target> </trans-unit> <trans-unit id="11"> <source>This value is not a valid date.</source> @@ -64,7 +64,7 @@ </trans-unit> <trans-unit id="16"> <source>The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.</source> - <target>Fayl hajmi katta ({{ size }} {{ suffix }}). Maksimal ruxsat etilgan hajim {{ limit }} {{ suffix }}.</target> + <target>Fayl hajmi katta ({{ size }} {{ suffix }}). Maksimal ruxsat etilgan hajm {{ limit }} {{ suffix }}.</target> </trans-unit> <trans-unit id="17"> <source>The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.</source> @@ -88,7 +88,7 @@ </trans-unit> <trans-unit id="22"> <source>This value should not be blank.</source> - <target>Qiymatni bo'sh kirtish mumkin emas.</target> + <target>Qiymatni bo'sh kiritish mumkin emas.</target> </trans-unit> <trans-unit id="23"> <source>This value should not be null.</source> @@ -116,7 +116,7 @@ </trans-unit> <trans-unit id="32"> <source>The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.</source> - <target>Fayl hajmi katta. Maksimal ruxsat berilgan hajim {{ limit }} {{ suffix }}.</target> + <target>Fayl hajmi katta. Maksimal ruxsat berilgan hajm {{ limit }} {{ suffix }}.</target> </trans-unit> <trans-unit id="33"> <source>The file is too large.</source> @@ -216,7 +216,7 @@ </trans-unit> <trans-unit id="57"> <source>Invalid card number.</source> - <target>Kata raqami noto'g'ri.</target> + <target>Karta raqami noto'g'ri.</target> </trans-unit> <trans-unit id="58"> <source>Unsupported card type or invalid card number.</source> @@ -260,11 +260,11 @@ </trans-unit> <trans-unit id="68"> <source>This value should be identical to {{ compared_value_type }} {{ compared_value }}.</source> - <target>Значение должно быть идентичным {{ compared_value_type }} {{ compared_value }}.</target> + <target>Qiymat {{ compared_value_type }} {{ compared_value }} bilan bir xil bo'lishi shart.</target> </trans-unit> <trans-unit id="69"> <source>This value should be less than {{ compared_value }}.</source> - <target>Qiymat bir xil bo'lishi kerak {{ compared_value }}.</target> + <target>Qiymat {{ compared_value }} dan kichik bo'lishi shart.</target> </trans-unit> <trans-unit id="70"> <source>This value should be less than or equal to {{ compared_value }}.</source> @@ -276,7 +276,7 @@ </trans-unit> <trans-unit id="72"> <source>This value should not be identical to {{ compared_value_type }} {{ compared_value }}.</source> - <target>Qiymat bir xil bo'lishi kerak emas {{ compared_value_type }} {{ compared_value }}.</target> + <target>Qiymat {{ compared_value_type }} {{ compared_value }} bilan bir xil bo'lmasligi kerak.</target> </trans-unit> <trans-unit id="73"> <source>The image ratio is too big ({{ ratio }}). Allowed maximum ratio is {{ max_ratio }}.</source> @@ -304,7 +304,7 @@ </trans-unit> <trans-unit id="79"> <source>The host could not be resolved.</source> - <target>Xost nomini nomiga ruxsat berilmagan.</target> + <target>Xost nomini aniqlab bo'lmadi.</target> </trans-unit> <trans-unit id="80"> <source>This value does not match the expected {{ charset }} charset.</source> @@ -328,7 +328,7 @@ </trans-unit> <trans-unit id="85"> <source>This Business Identifier Code (BIC) is not associated with IBAN {{ iban }}.</source> - <target>Ushbu BIC IBAN {{ iban }} bilan bog'liq emas..</target> + <target>Ushbu BIC IBAN {{ iban }} bilan bog'liq emas.</target> </trans-unit> <trans-unit id="86"> <source>This value should be valid JSON.</source> @@ -372,7 +372,7 @@ </trans-unit> <trans-unit id="96"> <source>The number of elements in this collection should be a multiple of {{ compared_value }}.</source> - <target>Ushbu to'plamdagi narsalar soni {{ compared_value }} dan ko'p bo'lishi kerak.</target> + <target>Ushbu to'plamdagi narsalar soni {{ compared_value }} ning ko'paytmasi bo'lishi kerak.</target> </trans-unit> <trans-unit id="97"> <source>This value should satisfy at least one of the following constraints:</source> @@ -572,79 +572,79 @@ </trans-unit> <trans-unit id="147"> <source>The referenced entity does not exist.</source> - <target state="needs-review-translation">Havola qilingan obyekt mavjud emas.</target> + <target>Havola qilingan obyekt mavjud emas.</target> </trans-unit> <trans-unit id="148" resname="This is not a valid ULID."> <source>This value is not a valid ULID.</source> - <target state="needs-review-translation">Bu qiymat haqiqiy ULID emas.</target> + <target>Bu qiymat haqiqiy ULID emas.</target> </trans-unit> <trans-unit id="149"> <source>This file is not a valid audio file.</source> - <target state="needs-review-translation">Ushbu fayl yaroqli audio fayl emas.</target> + <target>Ushbu fayl yaroqli audio fayl emas.</target> </trans-unit> <trans-unit id="150"> <source>The audio is too short ({{ duration }} seconds). Minimum duration expected is {{ min_duration }} seconds.</source> - <target state="needs-review-translation">Audio juda qisqa ({{ duration }} sekund). Kutilgan minimal davomiylik {{ min_duration }} sekund.</target> + <target>Audio juda qisqa ({{ duration }} soniya). Kutilayotgan minimal davomiylik {{ min_duration }} soniya.</target> </trans-unit> <trans-unit id="151"> <source>The audio is too long ({{ duration }} seconds). Allowed maximum duration is {{ max_duration }} seconds.</source> - <target state="needs-review-translation">Audio juda uzun ({{ duration }} sekund). Ruxsat etilgan maksimal davomiylik {{ max_duration }} sekund.</target> + <target>Audio juda uzun ({{ duration }} soniya). Ruxsat etilgan maksimal davomiylik {{ max_duration }} soniya.</target> </trans-unit> <trans-unit id="152"> <source>The duration of the audio could not be detected.</source> - <target state="needs-review-translation">Audioning davomiyligini aniqlab bo‘lmadi.</target> + <target>Audioning davomiyligini aniqlab bo'lmadi.</target> </trans-unit> <trans-unit id="153"> <source>The audio bitrate is too low ({{ bitrate }} bps). Minimum bitrate expected is {{ min_bitrate }} bps.</source> - <target state="needs-review-translation">Audio bitreyti juda past ({{ bitrate }} bps). Kutilayotgan minimal bitreyt {{ min_bitrate }} bps.</target> + <target>Audio bitreyti juda past ({{ bitrate }} bps). Kutilayotgan minimal bitreyt {{ min_bitrate }} bps.</target> </trans-unit> <trans-unit id="154"> <source>The audio bitrate is too high ({{ bitrate }} bps). Allowed maximum bitrate is {{ max_bitrate }} bps.</source> - <target state="needs-review-translation">Audio bitreyti juda yuqori ({{ bitrate }} bps). Ruxsat etilgan maksimal bitreyt {{ max_bitrate }} bps.</target> + <target>Audio bitreyti juda yuqori ({{ bitrate }} bps). Ruxsat etilgan maksimal bitreyt {{ max_bitrate }} bps.</target> </trans-unit> <trans-unit id="155"> <source>The bitrate of the audio could not be detected.</source> - <target state="needs-review-translation">Audioning bitreytini aniqlab bo‘lmadi.</target> + <target>Audioning bitreytini aniqlab bo'lmadi.</target> </trans-unit> <trans-unit id="156"> <source>Unsupported audio sample rate ({{ sample_rate }} Hz).</source> - <target state="needs-review-translation">Qo‘llab-quvvatlanmaydigan audio namuna olish chastotasi ({{ sample_rate }} Hz).</target> + <target>Qo'llab-quvvatlanmaydigan audio namuna olish chastotasi ({{ sample_rate }} Hz).</target> </trans-unit> <trans-unit id="157"> <source>The sample rate of the audio could not be detected.</source> - <target state="needs-review-translation">Audioning namuna olish chastotasini aniqlab bo‘lmadi.</target> + <target>Audioning namuna olish chastotasini aniqlab bo'lmadi.</target> </trans-unit> <trans-unit id="158"> <source>The audio has too few channels ({{ channels }}). Minimum amount expected is {{ min_channels }}.</source> - <target state="needs-review-translation">Audioda kanallar soni juda kam ({{ channels }}). Kutilgan minimal miqdor {{ min_channels }}.</target> + <target>Audioda kanallar soni juda kam ({{ channels }}). Kutilayotgan minimal miqdor {{ min_channels }}.</target> </trans-unit> <trans-unit id="159"> <source>The audio has too many channels ({{ channels }}). Maximum amount expected is {{ max_channels }}.</source> - <target state="needs-review-translation">Audioda juda ko‘p kanal bor ({{ channels }}). Kutilayotgan maksimal miqdor {{ max_channels }}.</target> + <target>Audioda kanallar soni juda ko'p ({{ channels }}). Ruxsat etilgan maksimal miqdor {{ max_channels }}.</target> </trans-unit> <trans-unit id="160"> <source>The number of audio channels could not be detected.</source> - <target state="needs-review-translation">Audio kanallari sonini aniqlab bo‘lmadi.</target> + <target>Audio kanallari sonini aniqlab bo'lmadi.</target> </trans-unit> <trans-unit id="161"> <source>The audio file is corrupted.</source> - <target state="needs-review-translation">Audio fayli buzilgan.</target> + <target>Audio fayli buzilgan.</target> </trans-unit> <trans-unit id="162"> <source>The audio contains multiple streams. Only one stream is allowed.</source> - <target state="needs-review-translation">Audioda bir nechta oqim mavjud. Faqat bitta oqimga ruxsat beriladi.</target> + <target>Audioda bir nechta oqim mavjud. Faqat bitta oqimga ruxsat beriladi.</target> </trans-unit> <trans-unit id="163"> <source>Unsupported audio codec "{{ codec }}".</source> - <target state="needs-review-translation">Qo‘llab-quvvatlanmaydigan audio kodek "{{ codec }}".</target> + <target>Qo'llab-quvvatlanmaydigan audio kodek "{{ codec }}".</target> </trans-unit> <trans-unit id="164"> <source>Unsupported audio container "{{ container }}".</source> - <target state="needs-review-translation">Qo'llab-quvvatlanmaydigan audio konteyner "{{ container }}".</target> + <target>Qo'llab-quvvatlanmaydigan audio konteyner "{{ container }}".</target> </trans-unit> <trans-unit id="165"> <source>The file does not contain any audio stream.</source> - <target state="needs-review-translation">Faylda audio oqim mavjud emas.</target> + <target>Faylda audio oqim mavjud emas.</target> </trans-unit> </body> </file> diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -153,6 +153,8 @@ ['BJ11B00610100400271101192591'], // Benin ['BR9700360305000010009795493P1'], // Brazil ['BR1800000000141455123924100C2'], // Brazil + ['BR6699999A03000010009795493C1'], // Brazil (alphanumeric bank code) + ['BR8799999A0300001000979549301'], // Brazil (numeric account type) ['VG96VPVG0000012345678901'], // British Virgin Islands ['BF42BF0840101300463574000390'], // Burkina Faso ['BI4210000100010000332045181'], // Burundi @@ -165,7 +167,7 @@ ['GT82TRAJ01020000001210029690'], // Guatemala ['IR580540105180021273113007'], // Iran ['IL620108000000099999999'], // Israel - ['CI05A00060174100178530011852'], // Ivory Coast + ['CI93CI0590101012167967100188'], // Ivory Coast ['JO94CBJO0010000000000131000302'], // Jordan ['KZ176010251000042993'], // Kazakhstan ['KW74NBOK0000000000001000372151'], // Kuwait @@ -284,7 +286,8 @@ ['GT82TRAJ010200000012100296901'], // Guatemala ['IR5805401051800212731130071'], // Iran ['IL6201080000000999999991'], // Israel - ['CI05A000601741001785300118521'], // Ivory Coast + ['CI93CI05901010121679671001881'], // Ivory Coast + ['CI05A00060174100178530011852'], // Ivory Coast (pre-2010 format) ['JO94CBJO00100000000001310003021'], // Jordan ['KZ1760102510000429931'], // Kazakhstan ['KW74NBOK00000000000010003721511'], // Kuwait @@ -384,6 +387,7 @@ ['BJ11B00610100400271101192592'], // Benin ['BR9700360305000010009795493P2'], // Brazil ['BR1800000000141455123924100C3'], // Brazil + ['BR6599999A03000010009795493C1'], // Brazil (alphanumeric bank code) ['VG96VPVG0000012345678902'], // British Virgin Islands ['BF41BF0840101300463574000390'], // Burkina Faso ['BI3210000100010000332045181'], // Burundi @@ -396,7 +400,7 @@ ['GT82TRAJ01020000001210029691'], // Guatemala ['IR580540105180021273113008'], // Iran ['IL620108000000099999998'], // Israel - ['CI05A00060174100178530011853'], // Ivory Coast + ['CI92CI0590101012167967100188'], // Ivory Coast ['JO94CBJO0010000000000131000303'], // Jordan ['KZ176010251000042994'], // Kazakhstan ['KW74NBOK0000000000001000372152'], // Kuwait diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -278,7 +278,6 @@ ['fbff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'], ['fe00::1'], ['fe7f:ffff:ffff:ffff:ffff:ffff:ffff:ffff'], - ['fec0::1'], ['::1:0:0:0'], ['2001:1::1'], ['2001:1:ffff:ffff:ffff:ffff:ffff:ffff'], @@ -523,6 +522,10 @@ ['febf::1'], ['febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff'], ['fe80:0000:0000:0000:0202:b3ff:fe1e:8329'], + // fec0::/10 deprecated site local address, both edges included + ['fec0::'], + ['fec0::1'], + ['feff:ffff:ffff:ffff:ffff:ffff:ffff:ffff'], // ::ffff:0:0/96 IPv4-mapped ['::ffff:127.0.0.1'], ['::ffff:7f00:1'], diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Caster/Caster.php symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Caster/Caster.php --- symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Caster/Caster.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Caster/Caster.php 2026-11-25 09:18:34.000000000 +0000 @@ -60,10 +60,6 @@ $a = $obj instanceof \Closure ? [] : (array) $obj; - if ($obj instanceof \__PHP_Incomplete_Class) { - return $a; - } - $classProperties = self::$classProperties[$class] ??= self::getClassProperties(new \ReflectionClass($class)); $a = array_replace($classProperties, $a); @@ -73,8 +69,11 @@ $i = 0; $prefixedKeys = []; foreach ($a as $k => $v) { - if ("\0" !== ($k[0] ?? '')) { - if (!isset($classProperties[$k])) { + if (str_starts_with($k, "\0~")) { + // "\0~" is reserved for the virtual properties added by casters + $prefixedKeys[$i] = self::PREFIX_DYNAMIC.$k; + } elseif ("\0" !== ($k[0] ?? '')) { + if (!isset($classProperties[$k]) && !$obj instanceof \__PHP_Incomplete_Class) { $prefixedKeys[$i] = self::PREFIX_DYNAMIC.$k; } } elseif ($debugClass !== $class && 1 === strpos($k, $class)) { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Caster/LinkStub.php symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Caster/LinkStub.php --- symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Caster/LinkStub.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Caster/LinkStub.php 2026-11-25 09:18:34.000000000 +0000 @@ -36,7 +36,9 @@ } $href = substr($href, 7); } elseif (str_contains($href, '://')) { - $this->attr['href'] = $href; + if (preg_match('{^https?://}i', $href)) { + $this->attr['href'] = $href; + } return; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Dumper/CliDumper.php symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Dumper/CliDumper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Dumper/CliDumper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Dumper/CliDumper.php 2026-11-25 09:18:34.000000000 +0000 @@ -430,7 +430,8 @@ } } - $this->line .= $bin.$this->style($style, $key[1], $attr).($attr['separator'] ?? ': '); + $separator = $attr['separator'] ?? ': '; + $this->line .= $bin.$this->style($style, $key[1], $attr).($this instanceof HtmlDumper ? htmlspecialchars($separator, \ENT_QUOTES, 'UTF-8') : $separator); } else { // This case should not happen $this->line .= '-'.$bin.'"'.$this->style('private', $key, ['class' => '']).'": '; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Dumper/HtmlDumper.php 2026-11-25 09:18:34.000000000 +0000 @@ -792,7 +792,7 @@ $this->line .= $cursor->depth >= $this->displayOptions['maxDepth'] ? ' <samp class=sf-dump-compact>' : ' <samp class=sf-dump-expanded>'; $this->endValue($cursor); $this->line .= $this->indentPad; - $this->line .= \sprintf('<img src="data:%s;base64,%s" /></samp>', $cursor->attr['content-type'], base64_encode($cursor->attr['img-data'])); + $this->line .= \sprintf('<img src="data:%s;base64,%s" /></samp>', esc($cursor->attr['content-type']), base64_encode($cursor->attr['img-data'])); $this->endValue($cursor); } else { parent::dumpString($cursor, $str, $bin, $cut); @@ -886,7 +886,7 @@ $dumpClasses[] = 'sf-dump-ellipsization'; $ellipsisClass = 'sf-dump-ellipsis'; if (isset($attr['ellipsis-type'])) { - $ellipsisClass .= ' sf-dump-ellipsis-'.$attr['ellipsis-type']; + $ellipsisClass .= ' sf-dump-ellipsis-'.esc($attr['ellipsis-type']); } $label = esc(substr($value, -$attr['ellipsis'])); $dumpTitle = $v."\n".$dumpTitle; diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Tests/Caster/StubCasterTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -224,4 +224,24 @@ $this->assertStringMatchesFormat($expectedDump, $dump); } + + public function testLinkStubWithNonHttpUrl() + { + $var = [new LinkStub('javascript:alert(1)//://')]; + + $cloner = new VarCloner(); + $dumper = new HtmlDumper(); + $dumper->setDumpHeader('<foo></foo>'); + $dumper->setDumpBoundaries('<bar>', '</bar>'); + $dump = $dumper->dump($cloner->cloneVar($var), true); + + $expectedDump = <<<'EODUMP' +<foo></foo><bar><span class=sf-dump-note>array:1</span> [<samp data-depth=1 class=sf-dump-expanded> + <span class=sf-dump-index>0</span> => "<span class=sf-dump-str title="24 characters">javascript:alert(1)//://</span>" +</samp>] +</bar> +EODUMP; + + $this->assertStringMatchesFormat($expectedDump, $dump); + } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Tests/Dumper/HtmlDumperTest.php symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Tests/Dumper/HtmlDumperTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/VarDumper/Tests/Dumper/HtmlDumperTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/VarDumper/Tests/Dumper/HtmlDumperTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -12,6 +12,7 @@ namespace Symfony\Component\VarDumper\Tests\Dumper; use PHPUnit\Framework\TestCase; +use Symfony\Component\VarDumper\Caster\EnumStub; use Symfony\Component\VarDumper\Caster\ImgStub; use Symfony\Component\VarDumper\Cloner\VarCloner; use Symfony\Component\VarDumper\Dumper\HtmlDumper; @@ -175,6 +176,41 @@ ); } + public function testObjectKeysAreNotParsedAsAttributes() + { + $key = "\0~separator=<img src=x>&ellipsis=1&ellipsis-type=\"><img src=y>\0foo"; + + $unserializeCallbackHandler = ini_set('unserialize_callback_func', null); + $incompleteObject = unserialize(sprintf('O:8:"Foo\Buzz":1:{s:%d:"%s";s:3:"bar";}', \strlen($key), $key)); + ini_set('unserialize_callback_func', $unserializeCallbackHandler); + + $dumper = new HtmlDumper(); + $dumper->setDumpHeader(''); + $dumper->setDumpBoundaries('', ''); + $cloner = new VarCloner(); + + foreach ([(object) [$key => 'bar'], $incompleteObject] as $var) { + $out = $dumper->dump($cloner->cloneVar($var), true); + + $this->assertStringNotContainsString('<img', $out); + $this->assertStringContainsString('<span class=sf-dump-public title="Runtime added dynamic property">', $out); + } + } + + public function testVirtualKeyAttributesAreEscaped() + { + $var = [new EnumStub(["\0~separator=<b>&ellipsis=1&ellipsis-type=\"><i>\0foo" => 'bar'])]; + + $dumper = new HtmlDumper(); + $dumper->setDumpHeader(''); + $dumper->setDumpBoundaries('', ''); + $out = $dumper->dump((new VarCloner())->cloneVar($var), true); + + $this->assertStringNotContainsString('<b>', $out); + $this->assertStringNotContainsString('"><i>', $out); + $this->assertStringContainsString('&lt;b&gt;', $out); + } + /** * @dataProvider varToDumpProvider */ @@ -194,6 +230,7 @@ { return [ [['dummy' => new ImgStub('dummy', 'img/png', '100em')], '<img src="data:img/png;base64,ZHVtbXk=" />'], + [['dummy' => new ImgStub('dummy', 'image/png"><script>alert(1)</script>', '')], '<img src="data:image/png&quot;&gt;&lt;script&gt;alert(1)&lt;/script&gt;;base64,ZHVtbXk=" />'], ['foo', '<span class=sf-dump-str title="3 characters">foo</span>'], ]; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php symfony-6.4.51+dfsg/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php 2026-11-25 09:18:34.000000000 +0000 @@ -290,7 +290,8 @@ return $value ? '1' : '0'; } - return htmlspecialchars($value, \ENT_XML1 | \ENT_QUOTES, 'UTF-8'); + // Graphviz interprets escape sequences like \N in HTML labels too + return str_replace('\\', '\\\\', htmlspecialchars($value, \ENT_XML1 | \ENT_QUOTES, 'UTF-8')); } /** diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Workflow/Tests/Dumper/GraphvizDumperTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Workflow/Tests/Dumper/GraphvizDumperTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Workflow/Tests/Dumper/GraphvizDumperTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Workflow/Tests/Dumper/GraphvizDumperTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -327,6 +327,24 @@ $this->assertStringNotContainsString('<tag>', $dump); } + public function testDumpEscapesBackslashesInHtmlLabels() + { + $transition = new Transition('t1', 'a', 'b'); + + $transitionsMetadata = new \SplObjectStorage(); + $transitionsMetadata[$transition] = ['step' => 'App\Workflow\NotifyCustomer']; + + $store = new InMemoryMetadataStore(['class' => 'App\Workflow\Order'], ['a' => ['label' => 'App\Place']], $transitionsMetadata); + $definition = new Definition(['a', 'b'], [$transition], null, $store); + + $dump = (new GraphvizDumper())->dump($definition, null, ['with-metadata' => true, 'label' => 'App\Title']); + + $this->assertStringContainsString('<<B>App\\\\Place</B>', $dump); + $this->assertStringContainsString('step: App\\\\Workflow\\\\NotifyCustomer', $dump); + $this->assertStringContainsString('<<B>App\\\\Title</B>', $dump); + $this->assertStringContainsString('class: App\\\\Workflow\\\\Order', $dump); + } + public static function provideSimpleWorkflowDumpWithoutMarkingWithMetadata(): string { return 'digraph workflow { diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Workflow/Tests/RegistryTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Workflow/Tests/RegistryTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Workflow/Tests/RegistryTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Workflow/Tests/RegistryTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -62,18 +62,14 @@ { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Too many workflows (workflow2, workflow3) match this subject (Symfony\Component\Workflow\Tests\Subject2); set a different name on each and use the second (name) argument of this method.'); - $w1 = $this->registry->get(new Subject2()); - $this->assertInstanceOf(Workflow::class, $w1); - $this->assertSame('workflow1', $w1->getName()); + $this->registry->get(new Subject2()); } public function testGetWithNoMatch() { $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unable to find a workflow for class "stdClass".'); - $w1 = $this->registry->get(new \stdClass()); - $this->assertInstanceOf(Workflow::class, $w1); - $this->assertSame('workflow1', $w1->getName()); + $this->registry->get(new \stdClass()); } public function testAllWithOneMatchWithSuccess() diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Inline.php symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Inline.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Inline.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Inline.php 2026-11-25 09:18:34.000000000 +0000 @@ -385,6 +385,8 @@ $lastToken = null; while ($i < $len) { if (']' === $sequence[$i]) { + $state->nodeCount += \count($output); + return $output; } if (',' === $sequence[$i] || ' ' === $sequence[$i]) { @@ -408,6 +410,7 @@ if (null !== $anchorRef && (!isset($sequence[$i]) || ',' === $sequence[$i] || ']' === $sequence[$i])) { $value = null; $references[$anchorRef] = $value; + $state->anchorNodeCounts[$anchorRef] = 0; if (null !== $tag && '' !== $tag) { $value = new TaggedValue($tag, $value); } @@ -420,6 +423,8 @@ break; } + $nodeCount = $state->nodeCount; + switch ($sequence[$i]) { case '[': // nested sequence @@ -455,6 +460,7 @@ if (null !== $anchorRef) { $references[$anchorRef] = $value; + $state->anchorNodeCounts[$anchorRef] = $state->nodeCount - $nodeCount; } if (null !== $tag && '' !== $tag) { @@ -577,6 +583,8 @@ ++$i; continue 2; case '}': + $state->nodeCount += \count($output); + if (self::$objectForMap) { return (object) $output; } @@ -585,19 +593,37 @@ } // key + $keyAnchor = self::parseAnchor($mapping, $i); + + if (!isset($mapping[$i])) { + break; + } + + if (Parser::preg_match('/\?[ \t]|[\[{]/A', $mapping, $match, 0, $i)) { + throw new ParseException('Complex mappings are not supported.', self::$parsedLineNumber + 1, $mapping); + } + $offsetBeforeKeyParsing = $i; $isKeyQuoted = \in_array($mapping[$i], ['"', "'"], true); - $key = self::parseScalar($mapping, $flags, [':', ' '], $i, false); + $keyDelimiters = $isKeyQuoted || Parser::preg_match('#!php/(const|enum) #A', $mapping, $match, 0, $i) ? [':', ' '] : [':']; + $key = self::parseScalar($mapping, $flags, $keyDelimiters, $i, false); if ($offsetBeforeKeyParsing === $i) { throw new ParseException('Missing mapping key.', self::$parsedLineNumber + 1, $mapping); } - $isKeyEvaluated = '!php/const' === $key || '!php/enum' === $key; + if (!$isKeyQuoted && str_contains($key, ',')) { + throw new ParseException(\sprintf('Malformed inline YAML string: "%s".', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename); + } + + $isKeyEvaluated = '!php/const' === $key || '!php/enum' === $key || (!$isKeyQuoted && str_starts_with($key, '*')); if ($isKeyEvaluated) { - $key .= ' '.self::parseScalar($mapping, $flags, ['(?<!:):(?!:)'], $i, false); - $key = self::evaluateScalar($state, $key, $flags); + if ('*' !== $key[0]) { + $key .= ' '.self::parseScalar($mapping, $flags, ['(?<!:):(?!:)'], $i, false); + } + + $key = self::evaluateScalar($state, $key, $flags, $references); if (!\is_string($key) && !\is_int($key)) { throw new ParseException((is_numeric($key) ? 'Numeric' : 'Non-string').' keys are not supported. Quote your evaluable mapping keys instead.', self::$parsedLineNumber + 1, $mapping); @@ -624,6 +650,11 @@ throw new ParseException('Colons must be followed by a space or an indication character (i.e. " ", ",", "[", "]", "{", "}").', self::$parsedLineNumber + 1, $mapping); } + if (null !== $keyAnchor) { + $references[$keyAnchor] = $key; + $state->anchorNodeCounts[$keyAnchor] = 0; + } + $isMergeKey = !$isKeyQuoted && !$isKeyEvaluated && '<<' === $key; if ($isMergeKey) { @@ -646,6 +677,7 @@ if (null !== $anchorRef && (!isset($mapping[$i]) || \in_array($mapping[$i], [',', '}', "\n"], true))) { $value = null; $references[$anchorRef] = $value; + $state->anchorNodeCounts[$anchorRef] = 0; if (!$isMergeKey) { if ($allowOverwrite || !isset($output[$key])) { $output[$key] = null !== $tag ? new TaggedValue($tag, $value) : $value; @@ -660,12 +692,15 @@ break; } + $nodeCount = $state->nodeCount; + switch ($mapping[$i]) { case '[': // nested sequence $value = self::parseSequence($state, $mapping, $flags, $i, $references); if (null !== $anchorRef) { $references[$anchorRef] = $value; + $state->anchorNodeCounts[$anchorRef] = $state->nodeCount - $nodeCount; } // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines @@ -698,6 +733,7 @@ $value = self::parseMapping($state, $mapping, $flags, $i, $references); if (null !== $anchorRef) { $references[$anchorRef] = $value; + $state->anchorNodeCounts[$anchorRef] = $state->nodeCount - $nodeCount; } // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines @@ -719,6 +755,7 @@ $value = self::parseScalar($mapping, $flags, [',', '}', "\n"], $i, null === $tag, $references, $isValueQuoted, $state); if (null !== $anchorRef) { $references[$anchorRef] = $value; + $state->anchorNodeCounts[$anchorRef] = $state->nodeCount - $nodeCount; } // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines @@ -784,7 +821,7 @@ throw new ParseException(\sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename); } - $state->countAlias($references[$value], self::$parsedLineNumber + 1, null, self::$parsedFilename); + $state->countAlias($value, $references[$value], self::$parsedLineNumber + 1, null, self::$parsedFilename); return $references[$value]; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Parser.php symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Parser.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Parser.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Parser.php 2026-11-25 09:18:34.000000000 +0000 @@ -29,7 +29,8 @@ public const DEFAULT_MAX_NESTING_LEVEL = 128; public const DEFAULT_MAX_ALIASES_FOR_COLLECTIONS = 128; - // nested blocks that have a longer run of empty or comment lines are read in place instead of being copied at each nesting level + // nested blocks that have more bytes, or a longer run of empty or comment lines, are read in place instead of being copied at each nesting level + private const MAX_COPIED_BYTES = 8192; private const MAX_COPIED_EMPTY_LINES = 8; private ?string $filename = null; @@ -110,6 +111,7 @@ $state = $this->getState(); $state->reset(); $state->aliasesEnabled = 0 === (Yaml::PARSE_EXCEPTION_ON_ALIAS & $flags); + $state->maxAliasedNodeCount = min(\PHP_INT_MAX, $state->maxAliasesForCollections * \strlen($value)); try { $data = $this->doParse($value, $flags); @@ -156,7 +158,7 @@ } $this->locallySkippedLineNumbers = []; - $this->totalNumberOfLines ??= $this->numberOfParsedLines; + $this->totalNumberOfLines ??= $this->offset + $this->numberOfParsedLines; if (!$this->moveToNextLine()) { return null; @@ -194,6 +196,7 @@ Inline::initialize($flags, $this->getRealCurrentLineNb(), $this->filename); $isRef = $mergeNode = false; + $nodeCount = $this->getState()->nodeCount; if ('-' === $this->currentLine[0] && self::preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+))?$#u', rtrim($this->currentLine), $values)) { if ($context && 'mapping' == $context) { throw new ParseException('You cannot define a sequence item when in a mapping.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); @@ -264,6 +267,7 @@ } if (false !== $isRef) { $this->refs[$isRef] = end($data); + $this->getState()->anchorNodeCounts[$isRef] = $this->getState()->nodeCount - $nodeCount; array_pop($this->refsBeingParsed); } } elseif ( @@ -289,7 +293,7 @@ } try { - $key = Inline::parseScalar($values['key']); + $key = str_starts_with($values['key'], '*') ? $this->parseValue($values['key'], $flags, $context) : Inline::parseScalar($values['key']); } catch (ParseException $e) { $e->setParsedLine($this->getRealCurrentLineNb() + 1); $e->setSnippet($this->currentLine); @@ -334,7 +338,7 @@ $refValue = $this->refs[$refName]; - $this->getState()->countAlias($refValue, $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); + $this->getState()->countAlias($refName, $refValue, $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $refValue instanceof \stdClass) { $refValue = (array) $refValue; @@ -419,6 +423,7 @@ $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags); if ($isMergeKey) { $this->refs[$refMatches['ref']] = $value; + $this->getState()->anchorNodeCounts[$refMatches['ref']] = $this->getState()->nodeCount - $nodeCount; if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $value instanceof \stdClass) { $value = (array) $value; @@ -449,6 +454,7 @@ } if (false !== $isRef) { $this->refs[$isRef] = $data[$key]; + $this->getState()->anchorNodeCounts[$isRef] = $this->getState()->nodeCount - $nodeCount; array_pop($this->refsBeingParsed); } } elseif ('"' === $this->currentLine[0] || "'" === $this->currentLine[0]) { @@ -584,6 +590,8 @@ } } while ($this->moveToNextLine()); + $this->getState()->nodeCount += \count($data); + if (null !== $tag) { $data = new TaggedValue($tag, $data); } @@ -667,8 +675,8 @@ /** * Returns the next embed block of YAML. * - * A block that contains many empty or comment lines is returned as an array - * that describes the lines to read in place. + * A long block, or a block that contains many empty or comment lines, is + * returned as an array that describes the lines to read in place. * * @param int|null $indentation The indent level at which the block is to be read, or null for default * @param bool $inSequence True if the enclosing data structure is a sequence @@ -794,11 +802,13 @@ } } - if ($inPlace) { + $block = implode("\n", $data); + + if ($inPlace || self::MAX_COPIED_BYTES < \strlen($block)) { return $this->createBlock($firstLineNumber, $this->currentLineNb, $newIndent ?? 0, $data[0]); } - return implode("\n", $data); + return $block; } /** @@ -1098,7 +1108,7 @@ throw new ParseException(\sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename); } - $this->getState()->countAlias($this->refs[$value], $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); + $this->getState()->countAlias($value, $this->refs[$value], $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); return $this->refs[$value]; } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/ParserState.php symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/ParserState.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/ParserState.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/ParserState.php 2026-11-25 09:18:34.000000000 +0000 @@ -24,12 +24,20 @@ public int $maxAliasesForCollections = Parser::DEFAULT_MAX_ALIASES_FOR_COLLECTIONS; public int $collectionAliasCount = 0; public bool $aliasesEnabled = true; + public int $maxAliasedNodeCount = \PHP_INT_MAX; + public int $aliasedNodeCount = 0; + public int $nodeCount = 0; + public array $anchorNodeCounts = []; public function reset(): void { $this->currentNestingLevel = 0; $this->collectionAliasCount = 0; $this->aliasesEnabled = true; + $this->maxAliasedNodeCount = \PHP_INT_MAX; + $this->aliasedNodeCount = 0; + $this->nodeCount = 0; + $this->anchorNodeCounts = []; } public function enterNestingLevel(int $line, ?string $snippet, ?string $filename): void @@ -48,7 +56,7 @@ } } - public function countAlias(mixed $refValue, int $line, ?string $snippet, ?string $filename): void + public function countAlias(string $name, mixed $refValue, int $line, ?string $snippet, ?string $filename): void { if (!$this->aliasesEnabled) { throw new ParseException('Aliases are disabled.', $line, $snippet, $filename); @@ -65,5 +73,13 @@ if (++$this->collectionAliasCount > $this->maxAliasesForCollections) { throw new ParseException(\sprintf('Maximum number of collection aliases (%d) exceeded. This limit can be increased via the Parser constructor.', $this->maxAliasesForCollections), $line, $snippet, $filename); } + + // an alias shares the nodes of its anchor, but the code that walks the parsed value visits them once per alias + $nodeCount = $this->anchorNodeCounts[$name] ?? 0; + $this->nodeCount += $nodeCount; + + if (($this->aliasedNodeCount += $nodeCount) > $this->maxAliasedNodeCount) { + throw new ParseException(\sprintf('Maximum number of nodes expanded by collection aliases (%d) exceeded. This limit can be increased via the Parser constructor.', $this->maxAliasedNodeCount), $line, $snippet, $filename); + } } } diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Tests/InlineTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Tests/InlineTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Tests/InlineTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Tests/InlineTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -445,6 +445,7 @@ ['{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', ['foo: ' => 'bar', 'bar: ' => 'foo: bar']], ['{"foo:bar": "baz"}', ['foo:bar' => 'baz']], ['{"foo":"bar"}', ['foo' => 'bar']], + ['{foo bar: baz, foo qux: quux}', ['foo bar' => 'baz', 'foo qux' => 'quux']], // nested sequences and mappings ['[foo, [bar, foo]]', ['foo', ['bar', 'foo']]], @@ -530,6 +531,7 @@ ['{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', (object) ['foo: ' => 'bar', 'bar: ' => 'foo: bar']], ['{"foo:bar": "baz"}', (object) ['foo:bar' => 'baz']], ['{"foo":"bar"}', (object) ['foo' => 'bar']], + ['{foo bar: baz, foo qux: quux}', (object) ['foo bar' => 'baz', 'foo qux' => 'quux']], // nested sequences and mappings ['[foo, [bar, foo]]', ['foo', ['bar', 'foo']]], @@ -913,6 +915,41 @@ Inline::parse('{this, is not, supported}'); } + public function testNotSupportedMissingValueBeforeAKey() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Malformed inline YAML string: "{foo, bar: baz}" at line 1.'); + Inline::parse('{foo, bar: baz}'); + } + + public function testNotSupportedMissingValueBeforeAMapping() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Malformed inline YAML string: "[{foo}, {bar: baz}]" at line 1.'); + Inline::parse('[{foo}, {bar: baz}]'); + } + + public function testComplexMappingKeyThrowsParseException() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "{? foo: bar}").'); + Inline::parse('{? foo: bar}'); + } + + public function testSequenceAsMappingKeyThrowsParseException() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "{[foo]: bar}").'); + Inline::parse('{[foo]: bar}'); + } + + public function testMappingAsMappingKeyThrowsParseException() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Complex mappings are not supported at line 1 (near "{&a {foo: bar}: baz}").'); + Inline::parse('{&a {foo: bar}: baz}'); + } + public function testUnterminatedSequenceEndingWithTag() { $this->expectException(ParseException::class); @@ -945,6 +982,14 @@ Inline::parse('{foo: &bar'); } + public function testUnterminatedMappingEndingWithKeyAnchor() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Malformed inline YAML string: "{&foo"'); + + Inline::parse('{&foo'); + } + public function testVeryLongQuotedStrings() { $longStringWithQuotes = str_repeat("x\r\n\\\"x\"x", 1000); @@ -1366,6 +1411,22 @@ '{ foo: &a bar, baz: *a }', ['foo' => 'bar', 'baz' => 'bar'], ]; + yield 'plain key in mapping' => [ + '{ &a foo: bar, baz: *a }', + ['foo' => 'bar', 'baz' => 'foo'], + ]; + yield 'quoted key in mapping' => [ + '{ &a "foo bar": baz, qux: *a }', + ['foo bar' => 'baz', 'qux' => 'foo bar'], + ]; + yield 'key in mapping in sequence' => [ + '[{ &a foo: bar }, *a]', + [['foo' => 'bar'], 'foo'], + ]; + yield 'alias as key in mapping' => [ + '{ foo: &a bar, *a : baz }', + ['foo' => 'bar', 'bar' => 'baz'], + ]; } public function testParseAnchoredMergeKey() @@ -1399,6 +1460,14 @@ Inline::parse('{ <<: [foo] }'); } + public function testParseAliasOfACollectionAsMappingKeyThrowsParseException() + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Non-string keys are not supported'); + + Inline::parse('{ foo: &a [bar], *a : baz }'); + } + public function testParseKeyStartingWithNulByteWithMapObjectsThrowsParseException() { $this->expectException(ParseException::class); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Tests/ParserTest.php symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Tests/ParserTest.php --- symfony-6.4.50+dfsg/src/Symfony/Component/Yaml/Tests/ParserTest.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Component/Yaml/Tests/ParserTest.php 2026-11-25 09:18:34.000000000 +0000 @@ -1058,8 +1058,6 @@ */ public function testMappingDuplicateKeyBlock() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Duplicate key "child" detected'); $input = <<<'EOD' parent: child: first @@ -1068,28 +1066,20 @@ child: duplicate child: duplicate EOD; - $expected = [ - 'parent' => [ - 'child' => 'first', - ], - ]; - $this->assertSame($expected, Yaml::parse($input)); + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Duplicate key "child" detected'); + Yaml::parse($input); } public function testMappingDuplicateKeyFlow() { - $this->expectException(ParseException::class); - $this->expectExceptionMessage('Duplicate key "child" detected'); $input = <<<'EOD' parent: { child: first, child: duplicate } parent: { child: duplicate, child: duplicate } EOD; - $expected = [ - 'parent' => [ - 'child' => 'first', - ], - ]; - $this->assertSame($expected, Yaml::parse($input)); + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Duplicate key "child" detected'); + Yaml::parse($input); } /** @@ -3346,7 +3336,7 @@ $this->expectException(ParseException::class); $this->expectExceptionMessage('Reference "foo" does not exist'); $yaml = <<<EOE - foo: { &foo { a: Steve, <<: *foo} } + foo: { bar: &foo { a: Steve, <<: *foo } } EOE; $this->parser->parse($yaml); } @@ -3443,6 +3433,20 @@ $this->assertSame([['foo' => ['bar' => "text\n"]], 'second'], $this->parser->parse($yaml)); } + public function testBlockScalarKeepsTrailingNewlineAfterLeadingComments() + { + $yaml = <<<'YAML' + # comment 1 + # comment 2 + foo: + bar: | + text + z: 2 + YAML; + + $this->assertSame(['foo' => ['bar' => "text\n"], 'z' => 2], $this->parser->parse($yaml)); + } + public function testBlockScalarsInCompactNestedCollections() { $this->assertSame([['a' => "\n"], 'b'], $this->parser->parse("- a: |+\n\n- b")); @@ -3825,6 +3829,61 @@ $this->parser->parse($yaml, Yaml::PARSE_EXCEPTION_ON_ALIAS); } + /** + * @dataProvider provideChainedCollectionAliases + */ + public function testParseRejectsCollectionAliasesThatExpandToTooManyNodes(string $yaml, int $flags = 0) + { + $this->expectException(ParseException::class); + $this->expectExceptionMessage('Maximum number of nodes expanded by collection aliases'); + + $this->parser->parse($yaml, $flags); + } + + public static function provideChainedCollectionAliases(): iterable + { + $flowSequences = "a0: &a0 [x]\n"; + $blockSequences = "a0: &a0\n - x\n"; + $flowMappings = "a0: &a0 {x: 1}\n"; + $mergeKeys = "a0: &a0 {x: 1}\n"; + $taggedSequences = "a0: &a0 !t [x]\n"; + $inlineMapping = 'root: {a0: &a0 [x]'; + $inlineSequence = 'root: [&a0 [x]'; + + for ($i = 1; $i <= 40; ++$i) { + $flowSequences .= "a$i: &a$i [*a".($i - 1).', *a'.($i - 1)."]\n"; + $blockSequences .= "a$i: &a$i\n - *a".($i - 1)."\n - *a".($i - 1)."\n"; + $flowMappings .= "a$i: &a$i {x: *a".($i - 1).', y: *a'.($i - 1)."}\n"; + $mergeKeys .= "a$i: &a$i\n <<: *a".($i - 1)."\n k$i: *a".($i - 1)."\n"; + $taggedSequences .= "a$i: &a$i !t [*a".($i - 1).', *a'.($i - 1)."]\n"; + $inlineMapping .= ", a$i: &a$i [*a".($i - 1).', *a'.($i - 1).']'; + $inlineSequence .= ", &a$i [*a".($i - 1).', *a'.($i - 1).']'; + } + + yield 'flow sequences' => [$flowSequences.'items: *a40']; + yield 'block sequences' => [$blockSequences.'items: *a40']; + yield 'flow mappings' => [$flowMappings.'items: *a40']; + yield 'flow mappings as objects' => [$flowMappings.'items: *a40', Yaml::PARSE_OBJECT_FOR_MAP]; + yield 'merge keys' => [$mergeKeys.'items: *a40']; + yield 'tagged sequences' => [$taggedSequences.'items: *a40', Yaml::PARSE_CUSTOM_TAGS]; + yield 'anchors inside a flow mapping' => [$inlineMapping.', items: *a40}']; + yield 'anchors inside a flow sequence' => [$inlineSequence.', *a40]']; + } + + public function testParseAcceptsLargeCollectionAliasedManyTimes() + { + $items = implode(', ', array_map(static fn ($i) => "item$i", range(1, 500))); + $yaml = "defaults: &defaults [$items]\n"; + + for ($i = 0; $i < Parser::DEFAULT_MAX_ALIASES_FOR_COLLECTIONS; ++$i) { + $yaml .= "a$i: *defaults\n"; + } + + $result = $this->parser->parse($yaml); + + $this->assertCount(500, $result['a'.(Parser::DEFAULT_MAX_ALIASES_FOR_COLLECTIONS - 1)]); + } + public function testParseHandlesLargeYamlHeaders() { $yaml = '%YAML:'.str_repeat('1', 100000)."\nfoo: bar\n"; @@ -3981,6 +4040,62 @@ $this->assertLessThan(20 * 1024 * 1024, MemoryUsageRecorder::$memoryUsage - $memoryUsage); } + /** + * @dataProvider provideNestedBlocksWithManyBytes + */ + public function testParseNestedBlocksWithManyBytes(int $lines, int $length) + { + $yaml = ''; + for ($i = 0; $i < 100; ++$i) { + $yaml .= str_repeat(' ', $i)."k:\n"; + } + for ($i = 0; $i < $lines; ++$i) { + $yaml .= str_repeat(' ', 100)."a$i: ".str_repeat('x', $length)."\n"; + } + $yaml .= str_repeat(' ', 100).'b: !php/object '.serialize(new MemoryUsageRecorder()); + + $memoryUsage = memory_get_usage(); + $data = $this->parser->parse($yaml, Yaml::PARSE_OBJECT); + + for ($i = 0; $i < 100; ++$i) { + $data = $data['k']; + } + + $this->assertSame(str_repeat('x', $length), $data['a'.($lines - 1)]); + $this->assertInstanceOf(MemoryUsageRecorder::class, $data['b']); + + // the lines used to be copied by each nesting level + $this->assertLessThan(10 * 1024 * 1024, MemoryUsageRecorder::$memoryUsage - $memoryUsage); + } + + public static function provideNestedBlocksWithManyBytes(): iterable + { + yield 'many lines' => [10000, 1]; + yield 'long lines' => [2, 500000]; + } + + public function testParseNestedSequencesOnOneLineWithManyLines() + { + $yaml = str_repeat('- ', 100)."a0: 0\n"; + for ($i = 1; $i < 10000; ++$i) { + $yaml .= str_repeat(' ', 200)."a$i: $i\n"; + } + $yaml .= str_repeat(' ', 200).'b: !php/object '.serialize(new MemoryUsageRecorder()); + + $memoryUsage = memory_get_usage(); + $data = $this->parser->parse($yaml, Yaml::PARSE_OBJECT); + + for ($i = 0; $i < 100; ++$i) { + $data = $data[0]; + } + + $this->assertSame(9999, $data['a9999']); + $this->assertInstanceOf(MemoryUsageRecorder::class, $data['b']); + + // the lines used to be copied by each nesting level + $this->assertLessThan(10 * 1024 * 1024, MemoryUsageRecorder::$memoryUsage - $memoryUsage); + } + public function testParseHandlesTrailingNewlinesAfterDocumentEndMarker() { $yaml = "---\nfoo: bar\n...\n\n"; @@ -4074,6 +4189,22 @@ ); } + public function testParseInlineMappingWithAnchoredKey() + { + $this->assertSame(['map' => ['foo' => 'bar'], 'alias' => 'foo'], $this->parser->parse("map: { &a foo: bar }\nalias: *a\n")); + } + + public function testParseAliasAsMappingKey() + { + $yaml = <<<YAML + foo: &a bar + *a : baz + map: { *a : qux } + YAML; + + $this->assertSame(['foo' => 'bar', 'bar' => 'baz', 'map' => ['bar' => 'qux']], $this->parser->parse($yaml)); + } + private function assertSameData($expected, $actual) { $this->assertEquals($expected, $actual); diff -Nru symfony-6.4.50+dfsg/src/Symfony/Contracts/HttpClient/Test/Fixtures/web/index.php symfony-6.4.51+dfsg/src/Symfony/Contracts/HttpClient/Test/Fixtures/web/index.php --- symfony-6.4.50+dfsg/src/Symfony/Contracts/HttpClient/Test/Fixtures/web/index.php 2026-11-04 11:23:00.000000000 +0000 +++ symfony-6.4.51+dfsg/src/Symfony/Contracts/HttpClient/Test/Fixtures/web/index.php 2026-11-25 09:18:34.000000000 +0000 @@ -110,6 +110,11 @@ header('Location: ..', true, 302); break; + case '/302/two-locations': + header('Location: http://localhost:8057/', true, 302); + header('Location: http://localhost:8057/404', false); + break; + case '/304': header('Content-Length: 10', true, 304); echo '12345';