From 8f1f9be81bb14f9fc09dcba8e9cffea28da3ca5d Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Sat, 28 Nov 2026 17:38:58 +0100 Subject: [PATCH 1/2] Prepare 14.0.0: clean dependency audit, WebAuthn on webauthn-lib 5.3, dependency and tooling updates, bug fixes, tests and docs --- .cbmignore | 1 - .gitattributes | 4 +- .github/workflows/ci.yml | 137 ++-- .gitignore | 1 - .semver | 5 - .travis.yml | 59 -- CHANGELOG.md | 45 ++ CONTRIBUTING.md | 2 +- LICENSE.txt | 2 +- README.md | 36 +- composer.json | 80 ++- .../20180313201241_initial_jwt_auth.php | 6 +- .../Migrations/20231003201241_auth_store.php | 6 +- config/api.php | 28 +- config/api_permissions.php.default | 25 +- config/bootstrap.php | 6 +- .../rector/AddInheritedPropertyTypeRector.php | 197 ++++++ config/rector/RenameInheritedCallRector.php | 139 +++++ config/rector/cakephp-api-13-changes.php | 265 ++++++++ config/rector/cakephp-api-13.php | 64 ++ config/routes.php | 6 +- docs/Documentation/Auth/jwt.md | 316 ++-------- docs/Documentation/Renderers/jsend.md | 6 +- docs/Documentation/Renderers/json.md | 0 docs/Documentation/Renderers/raw.md | 0 docs/Documentation/Renderers/xml.md | 0 docs/Documentation/actions.md | 10 +- docs/Documentation/auth.md | 105 ++-- docs/Documentation/configuration.md | 29 +- docs/Documentation/crud.md | 13 +- docs/Documentation/di.md | 5 + docs/Documentation/extensions.md | 47 +- docs/Documentation/installation.md | 41 +- docs/Documentation/middleware.md | 14 +- docs/Documentation/overview.md | 42 +- docs/Documentation/plans.md | 10 +- docs/Documentation/renderers.md | 12 +- docs/Documentation/roadmap.md | 29 + docs/Documentation/services.md | 35 +- docs/Documentation/transformers.md | 36 +- docs/Documentation/upgrading.md | 347 +++++++++++ docs/Documentation/versioning.md | 13 +- docs/attributes.md | 45 +- docs/home.md | 28 - docs/index.md | 278 ++++++--- patches/endroid-qr-code-nullable.patch | 22 - patches/flysystem-nullable.patch | 72 --- patches/flysystem-vfs-null-str-replace.patch | 11 - phpcs.xml | 34 +- phpcs.xml.dist | 6 - phpunit.xml.dist | 9 - psalm.xml | 126 ---- rector.php | 22 +- src/ApiInitializer.php | 8 +- src/ApiPlugin.php | 18 +- src/Command/ServiceRoutesCommand.php | 27 +- src/Controller/AppController.php | 6 +- src/Exception/MethodNotAllowedException.php | 13 +- src/Exception/ServiceException.php | 13 +- src/Exception/UnauthenticatedException.php | 13 +- src/Exception/UnauthorizedException.php | 13 +- src/Exception/ValidationException.php | 12 +- .../ContainerInjectorMiddleware.php | 12 +- src/Middleware/ParseApiRequestMiddleware.php | 43 +- .../ProcessApiRequestMiddleware.php | 6 +- src/Middleware/RequestHandlerMiddleware.php | 26 - .../ApiExceptionHandler.php | 8 +- src/Model/Entity/AuthStore.php | 10 + .../Entity/EntityDescriptionInterface.php | 6 +- src/Model/Entity/EntityLabelsInterface.php | 6 +- src/Model/Entity/JwtRefreshToken.php | 6 +- src/Model/Table/AuthStoreTable.php | 15 +- src/Model/Table/JwtRefreshTokensTable.php | 9 +- src/Plugin.php | 12 - src/Rbac/ApiRbac.php | 88 ++- src/Rbac/CachedApiRbac.php | 83 ++- src/Rbac/Permissions/AbstractProvider.php | 6 +- src/Rbac/Permissions/ApiConfigProvider.php | 9 +- src/Rbac/Rules/TwoFactorPassedScope.php | 9 +- src/Rbac/Rules/TwoFactorScope.php | 9 +- src/Routing/ApiRouteBuilder.php | 153 +++++ src/Routing/ApiRouter.php | 29 +- src/Service/Action/Action.php | 40 +- src/Service/Action/Auth/JwtLoginAction.php | 9 +- src/Service/Action/Auth/JwtRefreshAction.php | 37 +- .../Action/Auth/JwtSocialLoginAction.php | 11 +- src/Service/Action/Auth/JwtTokenTrait.php | 129 +++- src/Service/Action/Auth/LoginAction.php | 16 +- src/Service/Action/Auth/OtpVerifyAction.php | 54 +- .../Action/Auth/OtpVerifyCheckAction.php | 9 +- .../Action/Auth/OtpVerifyGetAction.php | 22 +- src/Service/Action/Auth/RegisterAction.php | 16 +- .../Action/Auth/ResetPasswordAction.php | 16 +- .../Auth/ResetPasswordRequestAction.php | 14 +- src/Service/Action/Auth/SecondFactorTrait.php | 24 +- src/Service/Action/Auth/SocialLoginAction.php | 22 +- .../Action/Auth/TwoFactorAuthAction.php | 20 +- .../Action/Auth/ValidateAccountAction.php | 14 +- .../Auth/ValidateAccountRequestAction.php | 14 +- src/Service/Action/Auth/Webauthn2faAction.php | 6 +- .../Action/Auth/Webauthn2faAuthAction.php | 31 +- .../Auth/Webauthn2faAuthOptionsAction.php | 12 +- .../Action/Auth/Webauthn2faRegisterAction.php | 21 +- .../Auth/Webauthn2faRegisterOptionsAction.php | 14 +- .../Action/Collection/AddEditAction.php | 10 +- .../Action/Collection/CollectionAction.php | 14 +- .../Action/Collection/DeleteAction.php | 12 +- src/Service/Action/CrudAction.php | 26 +- src/Service/Action/CrudAddAction.php | 12 +- src/Service/Action/CrudDeleteAction.php | 6 +- src/Service/Action/CrudDescribeAction.php | 6 +- src/Service/Action/CrudEditAction.php | 12 +- src/Service/Action/CrudIndexAction.php | 10 +- src/Service/Action/CrudViewAction.php | 6 +- src/Service/Action/DescribeAction.php | 11 +- src/Service/Action/DummyAction.php | 10 +- .../Auth/UserFormattingExtension.php | 8 +- .../Extension/AuthenticationExtension.php | 31 +- .../Extension/AuthorizationExtension.php_ | 350 ----------- .../Action/Extension/CorsExtension.php | 8 +- .../CrudAutocompleteListExtension.php | 6 +- .../Action/Extension/CrudHateoasExtension.php | 20 +- .../Extension/CrudRelationsExtension.php | 20 +- .../Extension/CursorPaginateExtension.php | 22 +- .../Extension/ExtendedSortExtension.php | 28 +- src/Service/Action/Extension/Extension.php | 10 +- .../Action/Extension/FilterExtension.php | 6 +- .../Action/Extension/NestedExtension.php | 6 +- .../Action/Extension/PaginateExtension.php | 15 +- .../Action/Extension/SortExtension.php | 18 +- .../Action/Extension/SortableTrait.php | 96 ++- src/Service/Action/ExtensionRegistry.php | 10 +- src/Service/Action/ListAction.php | 10 +- .../Action/Recaptcha/ValidateAction.php | 8 +- src/Service/Action/Result.php | 20 +- src/Service/Action/Traits/ReCaptchaTrait.php | 23 +- src/Service/Attribute/ApiActions.php | 8 +- src/Service/Attribute/ApiDelete.php | 6 +- src/Service/Attribute/ApiGet.php | 6 +- src/Service/Attribute/ApiOptions.php | 6 +- src/Service/Attribute/ApiPatch.php | 6 +- src/Service/Attribute/ApiPost.php | 6 +- src/Service/Attribute/ApiPut.php | 6 +- src/Service/Attribute/ApiResource.php | 6 +- src/Service/Attribute/ApiRoute.php | 8 +- src/Service/Attribute/ApiScope.php | 6 +- .../Attribute/ServiceAttributeConnector.php | 17 +- src/Service/Auth/Auth.php | 18 +- src/Service/Auth/AuthenticateTrait.php | 20 +- ...ltOneTimePasswordAuthenticationChecker.php | 6 +- ...DefaultWebauthn2fAuthenticationChecker.php | 6 +- ...mePasswordAuthenticationCheckerFactory.php | 9 +- ...PasswordAuthenticationCheckerInterface.php | 6 +- ...Webauthn2fAuthenticationCheckerFactory.php | 9 +- ...bauthn2fAuthenticationCheckerInterface.php | 6 +- src/Service/AuthService.php | 11 +- src/Service/ConfigReader.php | 63 +- src/Service/CrudService.php | 27 +- src/Service/DescribeService.php | 12 +- .../Exception/MissingActionException.php | 10 +- .../Exception/MissingExtensionException.php | 10 +- .../Exception/MissingParserException.php | 10 +- .../Exception/MissingRendererException.php | 10 +- src/Service/Extension/CollectionExtension.php | 9 +- src/Service/Extension/Extension.php | 10 +- src/Service/Extension/LogExtension.php | 16 +- .../Extension/OptionsHandlerExtension.php | 12 +- src/Service/ExtensionRegistry.php | 10 +- src/Service/FallbackService.php | 11 +- src/Service/ListingService.php | 12 +- src/Service/Locator/LocatorAwareTrait.php | 12 +- src/Service/Locator/LocatorInterface.php | 8 +- src/Service/Locator/ServiceLocator.php | 104 +++- src/Service/NestedCrudService.php | 9 +- src/Service/RecaptchaService.php | 9 +- src/Service/Renderer/BaseRenderer.php | 10 +- src/Service/Renderer/FileRenderer.php | 23 +- src/Service/Renderer/FlysystemRenderer.php | 82 ++- src/Service/Renderer/JSendRenderer.php | 9 +- src/Service/Renderer/JsonRenderer.php | 6 +- src/Service/Renderer/RawRenderer.php | 6 +- src/Service/Renderer/XmlRenderer.php | 55 +- src/Service/RequestParser/BaseParser.php | 10 +- src/Service/RequestParser/FormParser.php | 13 +- src/Service/Service.php | 62 +- src/Service/ServiceRegistry.php | 12 +- src/Service/Utility/ReverseRouting.php | 14 +- src/TestSuite/IntegrationTestCase.php | 19 +- src/TestSuite/TestCase.php | 6 +- src/Transformer/AbstractTransformer.php | 12 +- src/Transformer/TransformerInterface.php | 6 +- src/Utility/LegacyMemberGuard.php | 223 +++++++ src/Utility/RequestParser.php | 6 +- src/Webauthn/AuthenticateAdapter.php | 119 ++-- src/Webauthn/Base64Utility.php | 6 +- src/Webauthn/BaseAdapter.php | 291 +++++++-- src/Webauthn/PublicKeyCredentialLoader.php | 38 -- src/Webauthn/RegisterAdapter.php | 114 ++-- .../UserCredentialSourceRepository.php | 110 +++- src/Webauthn/WebauthnSerializer.php | 45 ++ structarmed.php | 39 +- tests/App/Application.php | 12 +- tests/App/CachedApiInitializer.php | 56 ++ tests/App/Controller/AppController.php | 6 +- tests/App/DI/Service/TestService.php | 10 + tests/App/Model/Entity/Article.php | 6 +- tests/App/Model/Table/ArticlesTable.php | 19 +- tests/App/Model/Table/ArticlesTagsTable.php | 6 +- tests/App/Model/Table/AuthorsTable.php | 6 +- tests/App/Model/Table/PostsTable.php | 9 +- tests/App/Model/Table/TagsTable.php | 6 +- .../Service/Action/ArticlesAboutAction.php | 32 + .../App/Service/Action/ArticlesDataAction.php | 13 +- .../App/Service/Action/ArticlesTagAction.php | 13 +- .../Service/Action/ArticlesUntagAction.php | 9 +- .../Service/Action/AttributeEchoAction.php | 53 ++ .../Action/AttributeFeaturedAction.php | 6 +- .../Action/AttributeScopedCodeAction.php | 24 + .../Action/AttributeScopedPlainAction.php | 24 + .../Action/AttributeScopedTaggedAction.php | 24 + .../Action/AttributeVerbDeleteAction.php | 24 + .../Action/AttributeVerbOptionsAction.php | 24 + .../Action/AttributeVerbPatchAction.php | 24 + .../Action/AttributeVerbPostAction.php | 38 ++ .../Service/Action/AttributeVerbPutAction.php | 24 + .../Action/AttributeVerbRepeatedAction.php | 28 + .../Action/AttributeVerbRouteAction.php | 33 + .../Service/Action/AttributesItemAction.php | 6 +- .../App/Service/Action/Author/IndexAction.php | 11 +- tests/App/Service/Action/FeaturedAction.php | 6 +- .../Service/Action/FilesDownloadAction.php | 31 + tests/App/Service/Action/FilesStampAction.php | 33 + .../App/Service/Action/FilesStoredAction.php | 40 ++ tests/App/Service/Action/FilesTextAction.php | 29 + .../Action/UntypedCollectionAction.php | 40 ++ .../App/Service/ArticlesCollectionService.php | 9 +- tests/App/Service/ArticlesService.php | 12 +- .../App/Service/AttributeScopeBaseService.php | 25 + tests/App/Service/AttributesService.php | 6 +- tests/App/Service/CollectionsService.php | 11 +- tests/App/Service/CoreCollisionService.php | 32 + .../Service/Extension/CoreProbeExtension.php | 58 ++ tests/App/Service/FilesService.php | 47 ++ tests/App/Service/PostsService.php | 9 +- tests/App/Service/ScopedService.php | 35 ++ tests/App/Service/VerbsService.php | 53 ++ tests/App/Service/v1/ArticlesService.php | 21 +- tests/App/Transformer/ArticleTransformer.php | 6 +- tests/Base/BaseTraitTest.php | 9 +- tests/Config/api.php | 23 +- tests/Config/api_permissions.php | 10 + tests/Config/bootstrap.php | 8 +- tests/Config/routes.php | 6 +- tests/Config/users.php | 18 +- tests/ConfigTrait.php | 9 +- tests/Fixture/ArticlesFixture.php | 9 +- tests/Fixture/ArticlesTagsFixture.php | 6 +- tests/Fixture/AttributesFixture.php | 6 +- tests/Fixture/AuthStoreFixture.php | 6 +- tests/Fixture/AuthorsFixture.php | 6 +- tests/Fixture/JwtRefreshTokensFixture.php | 6 +- tests/Fixture/PostsFixture.php | 9 +- tests/Fixture/SocialAccountsFixture.php | 6 +- tests/Fixture/TagsFixture.php | 23 +- tests/Fixture/UsersFixture.php | 7 +- tests/Fixture/files/report.csv | 3 + tests/FixturesTrait.php | 6 +- tests/Settings.php | 6 +- tests/TestCase/ClassLoadingTest.php | 59 ++ .../Command/ServiceRoutesCommandTest.php | 179 ++++++ tests/TestCase/Exception/ExceptionTest.php | 40 +- .../Integration/CachedApiRbacPipelineTest.php | 265 ++++++++ .../Integration/LegacyFallbackService.php | 32 + .../LegacyMemberGuardPipelineTest.php | 91 +++ .../Service/Action/ArticlesDataActionTest.php | 6 +- .../Service/Action/AttributeRoutingTest.php | 6 +- .../Action/AttributeVerbRoutingTest.php | 255 ++++++++ .../Action/Auth/JwtLoginActionTest.php | 6 +- .../Action/Auth/JwtRefreshActionTest.php | 191 +++++- .../Service/Action/Auth/LoginActionTest.php | 6 +- .../Service/Action/Auth/OtpVerifyFlowTest.php | 255 ++++++++ .../Action/Auth/RegisterActionTest.php | 6 +- .../Action/Auth/ResetPasswordActionTest.php | 81 ++- .../Auth/ResetPasswordRequestActionTest.php | 22 +- .../Auth/SecondFactorEnrollmentTest.php | 4 +- .../Action/Auth/SocialLoginActionTest.php | 196 ++++++ .../Action/Auth/SocialLoginJwtActionTest.php | 247 ++++++++ .../Auth/SoftwareAuthenticatorTrait.php | 17 +- .../Action/Auth/TwoFactorAuthActionTest.php | 143 +++++ .../Action/Auth/ValidateAccountActionTest.php | 52 +- .../Auth/ValidateAccountRequestActionTest.php | 33 +- .../Action/Auth/Webauthn2faFlowTest.php | 588 ++++++++++++++++++ .../Service/Action/CollectionActionsTest.php | 6 +- .../Service/Action/DescribeEndpointTest.php | 6 +- .../Action/Extension/CorsExtensionTest.php | 6 +- .../Action/Extension/CorsPreflightTest.php | 6 +- .../Extension/CrudAuthorizeExtensionTest.php | 6 +- .../CrudAutocompleteListExtensionTest.php | 6 +- .../Action/Extension/CrudExtensionTest.php | 6 +- .../Extension/CrudHateoasExtensionTest.php | 60 +- .../Extension/CrudRelationsExtensionTest.php | 6 +- .../CursorPaginationExtensionTest.php | 16 +- .../Extension/ExtendedSortExtensionTest.php | 99 ++- .../Extension/FallbackExtensionTest.php | 6 +- .../Action/Extension/FilterExtensionTest.php | 6 +- .../Extension/NestedCrudExtensionTest.php | 6 +- .../Extension/PaginationExtensionTest.php | 36 +- .../Action/Extension/SortExtensionTest.php | 158 ++++- .../Service/Action/HttpErrorBodiesTest.php | 6 +- .../Service/Action/PostsCrudTest.php | 9 +- .../Service/Action/PostsExtensionsTest.php | 6 +- .../Service/Action/PostsNestedTagsTest.php | 6 +- .../Service/Action/PostsRouteAliasTest.php | 6 +- .../Service/Action/RecaptchaValidateTest.php | 110 +++- .../Service/Action/TransformerActionTest.php | 6 +- .../Extension/CollectionExtensionTest.php | 195 ++++++ .../Service/Extension/LogExtensionTest.php | 135 ++++ .../Extension/OptionsHandlerExtensionTest.php | 177 ++++++ .../Service/FallbackServiceTest.php | 6 +- .../Integration/Service/RendererTest.php | 304 +++++++++ .../Integration/Service/VersioningTest.php | 263 ++++++++ .../ParseApiRequestMiddlewareTest.php | 136 +++- .../ProcessApiRequestMiddlewareTest.php | 18 +- .../ApiExceptionHandlerTest.php | 105 ++++ tests/TestCase/Model/AuthStoreTest.php | 16 +- .../TestCase/Model/EntityDescriptionStub.php | 6 +- tests/TestCase/Model/EntityInterfacesTest.php | 6 +- tests/TestCase/Model/JwtRefreshTokensTest.php | 11 +- tests/TestCase/Model/MigrationsSchemaTest.php | 90 +++ tests/TestCase/Rbac/AlwaysFalseRule.php | 9 +- tests/TestCase/Rbac/AlwaysTrueRule.php | 9 +- tests/TestCase/Rbac/ApiConfigProviderTest.php | 6 +- tests/TestCase/Rbac/ApiRbacKeyOrderTest.php | 180 ++---- tests/TestCase/Rbac/ApiRbacTest.php | 6 +- tests/TestCase/Rbac/CachedApiRbacTest.php | 142 ++++- tests/TestCase/Rbac/RoleEnum.php | 23 + .../Rbac/TwoFactorPassedScopeTest.php | 11 +- tests/TestCase/Rbac/TwoFactorScopeTest.php | 11 +- .../Fixture/crud_action_override.php.inc | 47 ++ .../Rector/Fixture/extension_own_call.php.inc | 43 ++ .../Rector/Fixture/property_type.php.inc | 25 + .../Rector/Fixture/removed_classes.php.inc | 27 + .../Fixture/second_factor_override.php.inc | 41 ++ .../Rector/Fixture/service_properties.php.inc | 37 ++ .../Fixture/skip_unrelated_class.php.inc | 20 + .../Fixture/sort_extension_override.php.inc | 43 ++ .../Fixture/typed_action_properties.php.inc | 37 ++ .../typed_properties_without_default.php.inc | 33 + .../Fixture/typed_service_properties.php.inc | 41 ++ tests/TestCase/Rector/UpgradeChangesTest.php | 123 ++++ tests/TestCase/Rector/UpgradeSetTest.php | 40 ++ .../TestCase/Routing/ApiRouteBuilderTest.php | 145 +++++ tests/TestCase/Service/Action/ActionTest.php | 396 +++++++++++- .../Service/Action/Auth/AuthActionTrait.php | 66 ++ .../Service/Action/Auth/LoginActionTest.php | 83 +++ .../Action/Auth/OtpVerifyActionTest.php | 187 ++++++ .../Action/Auth/RegisterActionTest.php | 148 +++++ .../Action/Auth/ResetPasswordActionTest.php | 120 ++++ .../Auth/ResetPasswordRequestActionTest.php | 126 ++++ .../Action/Auth/SecondFactorTraitTest.php | 119 ++++ .../Action/Collection/AddEditActionTest.php | 34 +- .../Action/Collection/DeleteActionTest.php | 13 +- .../Collection/SubclassCompatibilityTest.php | 30 + .../Service/Action/CrudActionTest.php | 256 ++++++++ .../Service/Action/CrudAddActionTest.php | 8 +- .../Service/Action/CrudDeleteActionTest.php | 11 +- .../Service/Action/CrudEditActionTest.php | 45 +- .../Service/Action/CrudIndexActionTest.php | 8 +- .../Service/Action/CrudViewActionTest.php | 8 +- .../Service/Action/DescribeActionTest.php | 8 +- .../Action/Extension/SortableHarness.php | 23 +- .../Action/Extension/SortableTraitTest.php | 136 +++- .../Service/Action/ExtensionRegistryTest.php | 6 +- .../Service/Action/ListActionTest.php | 8 +- .../Action/Recaptcha/ValidateActionTest.php | 90 +++ tests/TestCase/Service/Action/ResultTest.php | 94 +++ .../Action/Traits/ReCaptchaTraitTest.php | 217 ------- tests/TestCase/Service/ApiRouterTest.php | 6 +- .../ServiceAttributeConnectorTest.php | 259 ++++++++ tests/TestCase/Service/AuthTest.php | 12 +- tests/TestCase/Service/ConfigReaderTest.php | 153 ++++- .../Extension/OptionsHandlerExtensionTest.php | 101 +++ .../TestCase/Service/ExtensionLoadingTest.php | 72 +++ .../Service/ExtensionRegistryTest.php | 154 +++++ tests/TestCase/Service/JwtTokenHarness.php | 9 +- tests/TestCase/Service/JwtTokenTraitTest.php | 290 ++++++--- tests/TestCase/Service/ListingServiceTest.php | 6 +- .../Service/LocatorAwareTraitTest.php | 51 ++ .../Service/RecaptchaTraitHarness.php | 10 +- tests/TestCase/Service/RecaptchaTraitTest.php | 75 ++- .../Service/Renderer/FileRendererTest.php | 239 +++++++ .../Renderer/FlysystemRendererTest.php | 118 +++- .../Service/Renderer/JSendRendererTest.php | 48 +- .../Service/Renderer/JsonRendererTest.php | 95 ++- .../Service/Renderer/RawRendererTest.php | 15 +- .../Service/Renderer/XmlRendererTest.php | 279 ++++++++- tests/TestCase/Service/RequestParserTest.php | 6 +- tests/TestCase/Service/ReverseRoutingTest.php | 6 +- tests/TestCase/Service/ServiceEventsTest.php | 20 +- tests/TestCase/Service/ServiceLocatorTest.php | 22 +- .../TestCase/Service/ServiceRegistryTest.php | 46 +- tests/TestCase/Service/ServiceRoutingTest.php | 38 +- tests/TestCase/Service/ServiceTest.php | 344 +++++++++- .../Service/TwoFactorAuthenticationTest.php | 16 +- .../Transformer/AbstractTransformerTest.php | 28 +- .../TestCase/Transformer/TestTransformer.php | 6 +- .../Utility/LegacyMemberGuardTest.php | 265 ++++++++ tests/TestCase/Utility/LegacyScopeTrait.php | 30 + tests/TestCase/Webauthn/Base64UtilityTest.php | 45 +- .../TestCase/Webauthn/RegisterAdapterTest.php | 142 +++++ .../UserCredentialSourceRepositoryTest.php | 190 ++++++ tests/bootstrap.php | 40 +- tests/schema.php | 12 +- webroot/empty | 0 414 files changed, 15861 insertions(+), 3607 deletions(-) delete mode 100644 .semver delete mode 100644 .travis.yml create mode 100644 config/rector/AddInheritedPropertyTypeRector.php create mode 100644 config/rector/RenameInheritedCallRector.php create mode 100644 config/rector/cakephp-api-13-changes.php create mode 100644 config/rector/cakephp-api-13.php delete mode 100644 docs/Documentation/Renderers/json.md delete mode 100644 docs/Documentation/Renderers/raw.md delete mode 100644 docs/Documentation/Renderers/xml.md create mode 100644 docs/Documentation/roadmap.md create mode 100644 docs/Documentation/upgrading.md delete mode 100644 docs/home.md delete mode 100644 patches/endroid-qr-code-nullable.patch delete mode 100644 patches/flysystem-nullable.patch delete mode 100644 patches/flysystem-vfs-null-str-replace.patch delete mode 100644 phpcs.xml.dist delete mode 100644 psalm.xml delete mode 100644 src/Middleware/RequestHandlerMiddleware.php delete mode 100644 src/Plugin.php create mode 100644 src/Routing/ApiRouteBuilder.php delete mode 100644 src/Service/Action/Extension/AuthorizationExtension.php_ create mode 100644 src/Utility/LegacyMemberGuard.php delete mode 100644 src/Webauthn/PublicKeyCredentialLoader.php create mode 100644 src/Webauthn/WebauthnSerializer.php create mode 100644 tests/App/CachedApiInitializer.php create mode 100644 tests/App/Service/Action/ArticlesAboutAction.php create mode 100644 tests/App/Service/Action/AttributeEchoAction.php create mode 100644 tests/App/Service/Action/AttributeScopedCodeAction.php create mode 100644 tests/App/Service/Action/AttributeScopedPlainAction.php create mode 100644 tests/App/Service/Action/AttributeScopedTaggedAction.php create mode 100644 tests/App/Service/Action/AttributeVerbDeleteAction.php create mode 100644 tests/App/Service/Action/AttributeVerbOptionsAction.php create mode 100644 tests/App/Service/Action/AttributeVerbPatchAction.php create mode 100644 tests/App/Service/Action/AttributeVerbPostAction.php create mode 100644 tests/App/Service/Action/AttributeVerbPutAction.php create mode 100644 tests/App/Service/Action/AttributeVerbRepeatedAction.php create mode 100644 tests/App/Service/Action/AttributeVerbRouteAction.php create mode 100644 tests/App/Service/Action/FilesDownloadAction.php create mode 100644 tests/App/Service/Action/FilesStampAction.php create mode 100644 tests/App/Service/Action/FilesStoredAction.php create mode 100644 tests/App/Service/Action/FilesTextAction.php create mode 100644 tests/App/Service/Action/UntypedCollectionAction.php create mode 100644 tests/App/Service/AttributeScopeBaseService.php create mode 100644 tests/App/Service/CoreCollisionService.php create mode 100644 tests/App/Service/Extension/CoreProbeExtension.php create mode 100644 tests/App/Service/FilesService.php create mode 100644 tests/App/Service/ScopedService.php create mode 100644 tests/App/Service/VerbsService.php create mode 100644 tests/Fixture/files/report.csv create mode 100644 tests/TestCase/ClassLoadingTest.php create mode 100644 tests/TestCase/Integration/CachedApiRbacPipelineTest.php create mode 100644 tests/TestCase/Integration/LegacyFallbackService.php create mode 100644 tests/TestCase/Integration/LegacyMemberGuardPipelineTest.php create mode 100644 tests/TestCase/Integration/Service/Action/AttributeVerbRoutingTest.php create mode 100644 tests/TestCase/Integration/Service/Action/Auth/OtpVerifyFlowTest.php create mode 100644 tests/TestCase/Integration/Service/Action/Auth/SocialLoginActionTest.php create mode 100644 tests/TestCase/Integration/Service/Action/Auth/SocialLoginJwtActionTest.php create mode 100644 tests/TestCase/Integration/Service/Action/Auth/TwoFactorAuthActionTest.php create mode 100644 tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php create mode 100644 tests/TestCase/Integration/Service/Extension/CollectionExtensionTest.php create mode 100644 tests/TestCase/Integration/Service/Extension/LogExtensionTest.php create mode 100644 tests/TestCase/Integration/Service/Extension/OptionsHandlerExtensionTest.php create mode 100644 tests/TestCase/Integration/Service/RendererTest.php create mode 100644 tests/TestCase/Integration/Service/VersioningTest.php create mode 100644 tests/TestCase/Middleware/UnauthorizedHandler/ApiExceptionHandlerTest.php create mode 100644 tests/TestCase/Model/MigrationsSchemaTest.php create mode 100644 tests/TestCase/Rbac/RoleEnum.php create mode 100644 tests/TestCase/Rector/Fixture/crud_action_override.php.inc create mode 100644 tests/TestCase/Rector/Fixture/extension_own_call.php.inc create mode 100644 tests/TestCase/Rector/Fixture/property_type.php.inc create mode 100644 tests/TestCase/Rector/Fixture/removed_classes.php.inc create mode 100644 tests/TestCase/Rector/Fixture/second_factor_override.php.inc create mode 100644 tests/TestCase/Rector/Fixture/service_properties.php.inc create mode 100644 tests/TestCase/Rector/Fixture/skip_unrelated_class.php.inc create mode 100644 tests/TestCase/Rector/Fixture/sort_extension_override.php.inc create mode 100644 tests/TestCase/Rector/Fixture/typed_action_properties.php.inc create mode 100644 tests/TestCase/Rector/Fixture/typed_properties_without_default.php.inc create mode 100644 tests/TestCase/Rector/Fixture/typed_service_properties.php.inc create mode 100644 tests/TestCase/Rector/UpgradeChangesTest.php create mode 100644 tests/TestCase/Rector/UpgradeSetTest.php create mode 100644 tests/TestCase/Routing/ApiRouteBuilderTest.php create mode 100644 tests/TestCase/Service/Action/Auth/AuthActionTrait.php create mode 100644 tests/TestCase/Service/Action/Auth/LoginActionTest.php create mode 100644 tests/TestCase/Service/Action/Auth/OtpVerifyActionTest.php create mode 100644 tests/TestCase/Service/Action/Auth/RegisterActionTest.php create mode 100644 tests/TestCase/Service/Action/Auth/ResetPasswordActionTest.php create mode 100644 tests/TestCase/Service/Action/Auth/ResetPasswordRequestActionTest.php create mode 100644 tests/TestCase/Service/Action/Auth/SecondFactorTraitTest.php create mode 100644 tests/TestCase/Service/Action/Collection/SubclassCompatibilityTest.php create mode 100644 tests/TestCase/Service/Action/CrudActionTest.php create mode 100644 tests/TestCase/Service/Action/Recaptcha/ValidateActionTest.php create mode 100644 tests/TestCase/Service/Action/ResultTest.php delete mode 100644 tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php create mode 100644 tests/TestCase/Service/Attribute/ServiceAttributeConnectorTest.php create mode 100644 tests/TestCase/Service/Extension/OptionsHandlerExtensionTest.php create mode 100644 tests/TestCase/Service/ExtensionLoadingTest.php create mode 100644 tests/TestCase/Service/ExtensionRegistryTest.php create mode 100644 tests/TestCase/Service/LocatorAwareTraitTest.php create mode 100644 tests/TestCase/Service/Renderer/FileRendererTest.php create mode 100644 tests/TestCase/Utility/LegacyMemberGuardTest.php create mode 100644 tests/TestCase/Utility/LegacyScopeTrait.php create mode 100644 tests/TestCase/Webauthn/RegisterAdapterTest.php create mode 100644 tests/TestCase/Webauthn/Repository/UserCredentialSourceRepositoryTest.php delete mode 100644 webroot/empty diff --git a/.cbmignore b/.cbmignore index 68d6eaaf..c756855c 100644 --- a/.cbmignore +++ b/.cbmignore @@ -6,7 +6,6 @@ tests/ phpunit.xml phpunit.xml.dist phpunit.xml.dist.bak -webroot/ workspace/ # junk / backups from previous refactors (do not index) diff --git a/.gitattributes b/.gitattributes index 0a6532ca..a33fc499 100644 --- a/.gitattributes +++ b/.gitattributes @@ -34,13 +34,11 @@ .gitattributes export-ignore .gitignore export-ignore .stickler.yml export-ignore -.travis.yml export-ignore CONTRIBUTING.md export-ignore Dockerfile export-ignore docs.Dockerfile export-ignore -phpcs.xml.dist export-ignore +phpcs.xml export-ignore phpstan.neon export-ignore phpunit.xml.dist export-ignore -psalm.xml export-ignore /.github export-ignore /tests export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 656fe13b..9a79ceec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,9 @@ on: branches: - '*' +permissions: + contents: read # to fetch code (actions/checkout) + jobs: testsuite: runs-on: ubuntu-24.04 @@ -15,74 +18,85 @@ jobs: matrix: php-version: ['8.3', '8.4', '8.5'] db-type: [sqlite, mysql, pgsql] - prefer-lowest: [''] + dependencies: [highest] + include: + - php-version: '8.3' + db-type: sqlite + dependencies: lowest + + services: + mysql: + image: ${{ matrix.db-type == 'mysql' && 'mysql:8.4' || '' }} + env: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: cakephp + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping -h 127.0.0.1 -proot" + --health-interval=5s + --health-timeout=5s + --health-retries=20 + postgres: + image: ${{ matrix.db-type == 'pgsql' && 'postgres:18' || '' }} + env: + POSTGRES_PASSWORD: postgres + POSTGRES_DB: cakephp + ports: + - 5432:5432 + options: >- + --health-cmd="pg_isready -U postgres" + --health-interval=5s + --health-timeout=5s + --health-retries=20 steps: - - name: Setup MySQL latest - if: matrix.db-type == 'mysql' - run: docker run --rm --name=mysqld -e MYSQL_ROOT_PASSWORD=root -e MYSQL_DATABASE=cakephp -p 3306:3306 -d mysql --default-authentication-plugin=mysql_native_password --disable-log-bin - - - name: Setup PostgreSQL latest - if: matrix.db-type == 'pgsql' - run: docker run --rm --name=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=cakephp -p 5432:5432 -d postgres - - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: ${{ matrix.php-version }} - extensions: mbstring, intl, apcu, sqlite, pdo_sqlite, pdo_${{ matrix.db-type }}, ${{ matrix.db-type }} - ini-values: apc.enable_cli = 1 - coverage: pcov - - - name: Get composer cache directory - id: composer-cache - run: echo "::set-output name=dir::$(composer config cache-files-dir)" - - - name: Get date part for cache key - id: key-date - run: echo "::set-output name=date::$(date +'%Y-%m')" - - - name: Cache composer dependencies - uses: actions/cache@v4 + extensions: mbstring, intl, apcu, pdo_sqlite, pdo_${{ matrix.db-type }} + ini-values: apc.enable_cli = 1, zend.assertions = 1 + coverage: ${{ (matrix.php-version == '8.3' && matrix.db-type == 'mysql') && 'pcov' || 'none' }} + + - name: Composer install + uses: ramsey/composer-install@v3 + env: + # test the declared floors: Composer's advisory blocking would silently raise them + COMPOSER_NO_SECURITY_BLOCKING: ${{ matrix.dependencies == 'lowest' && '1' || '0' }} with: - path: ${{ steps.composer-cache.outputs.dir }} - key: ${{ runner.os }}-composer-${{ steps.key-date.outputs.date }}-${{ hashFiles('composer.json') }}-${{ matrix.prefer-lowest }} - - - name: composer install - run: | - if ${{ matrix.prefer-lowest == 'prefer-lowest' }}; then - composer update --prefer-lowest --prefer-stable - else - composer update - fi - - - name: Setup problem matchers for PHPUnit - if: matrix.php-version == '8.3' && matrix.db-type == 'mysql' - run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + dependency-versions: ${{ matrix.dependencies }} - name: Run PHPUnit run: | - if [[ ${{ matrix.db-type }} == 'sqlite' ]]; then export DB_URL='sqlite:///:memory:'; fi - if [[ ${{ matrix.db-type }} == 'mysql' ]]; then export DB_URL='mysql://root:root@127.0.0.1/cakephp?encoding=utf8'; fi - if [[ ${{ matrix.db-type }} == 'pgsql' ]]; then export DB_URL='postgres://postgres:postgres@127.0.0.1/postgres'; fi - if [[ ${{ matrix.php-version }} == '8.3' ]]; then - export CODECOVERAGE=1 && vendor/bin/phpunit --display-deprecations --display-incomplete --display-skipped --coverage-clover=coverage.xml + if [[ ${{ matrix.db-type }} == 'sqlite' ]]; then export db_dsn='sqlite:///:memory:'; fi + if [[ ${{ matrix.db-type }} == 'mysql' ]]; then export db_dsn='mysql://root:root@127.0.0.1/cakephp?encoding=utf8'; fi + if [[ ${{ matrix.db-type }} == 'pgsql' ]]; then export db_dsn='postgres://postgres:postgres@127.0.0.1/cakephp'; fi + FLAGS="--display-all-issues --fail-on-all-issues --do-not-fail-on-skipped --do-not-fail-on-incomplete" + if [[ ${{ matrix.php-version }} == '8.3' && ${{ matrix.db-type }} == 'mysql' ]]; then + export CODECOVERAGE=1 && vendor/bin/phpunit $FLAGS --coverage-clover=coverage.xml else - vendor/bin/phpunit + vendor/bin/phpunit $FLAGS fi - name: Submit code coverage - if: matrix.php-version == '8.3' + if: success() && matrix.php-version == '8.3' && matrix.db-type == 'mysql' uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} cs-stan: name: Coding Standard & Static Analysis - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 + with: + persist-credentials: false - name: Setup PHP uses: shivammathur/setup-php@v2 @@ -90,23 +104,20 @@ jobs: php-version: '8.3' extensions: mbstring, intl, apcu coverage: none + tools: cs2pr - - name: Get composer cache directory - id: composer-cache - run: echo "::set-output name=dir::$(composer config cache-files-dir)" + - name: Composer install + uses: ramsey/composer-install@v3 - - name: Get date part for cache key - id: key-date - run: echo "::set-output name=date::$(date +'%Y-%m')" - - - name: Cache composer dependencies - uses: actions/cache@v4 - with: - path: ${{ steps.composer-cache.outputs.dir }} - key: ${{ runner.os }}-composer-${{ steps.key-date.outputs.date }}-${{ hashFiles('composer.json') }}-cs-stan + - name: Run phpcs + if: ${{ !cancelled() }} + shell: bash + run: vendor/bin/phpcs --report=checkstyle | cs2pr - - name: composer install - run: composer install --prefer-dist --no-progress + - name: Run phpstan + if: ${{ !cancelled() }} + run: vendor/bin/phpstan analyse src/ --error-format=github - - name: Run All Gates - run: composer check + - name: Run rector + if: ${{ !cancelled() }} + run: composer rector-check diff --git a/.gitignore b/.gitignore index 44556277..7a6dfd96 100644 --- a/.gitignore +++ b/.gitignore @@ -7,7 +7,6 @@ vendor/ composer.lock tmp pmip -webroot/coverage .php_cs.cache .phpunit.cache/ .repowise diff --git a/.semver b/.semver deleted file mode 100644 index 9d5c75f7..00000000 --- a/.semver +++ /dev/null @@ -1,5 +0,0 @@ ---- -:major: 10 -:minor: 0 -:patch: 0 -:special: '' diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index ef936a52..00000000 --- a/.travis.yml +++ /dev/null @@ -1,59 +0,0 @@ -language: php - -dist: xenial - -os: linux - -php: - - 7.4 - - 8.0 - -services: - - postgresql - - mysql - -cache: - directories: - - vendor - - $HOME/.composer/cache - -env: - jobs: - - DB=mysql db_dsn='mysql://root@127.0.0.1/cakephp_test?init[]=SET sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"' - - DB=pgsql db_dsn='postgres://postgres@127.0.0.1/cakephp_test' - - DB=sqlite db_dsn='sqlite:///:memory:' - - global: - - DEFAULT=1 - -jobs: - fast_finish: true - - include: - - php: 7.4 - env: COVERAGE=1 DB=mysql db_dsn='mysql://travis@0.0.0.0/cakephp_test' - - - php: 7.4 - env: PHPCS=1 DEFAULT=0 - - - php: 7.4 - env: PHPSTAN=1 DEFAULT=0 - -before_script: - - composer self-update - - composer install --prefer-dist --no-interaction - - if [[ $DB == 'mysql' ]]; then mysql -u root -e 'CREATE DATABASE cakephp_test;'; fi - - if [[ $DB == 'pgsql' ]]; then psql -c 'CREATE DATABASE cakephp_test;' -U postgres; fi - - if [[ $PHPSTAN = 1 ]]; then composer stan-setup; fi - -script: - - if [[ $DEFAULT = 1 ]]; then composer test; fi - - if [[ $COVERAGE = 1 ]]; then composer coverage-test; fi - - if [[ $PHPCS = 1 ]]; then composer cs-check; fi - - if [[ $PHPSTAN = 1 ]]; then composer stan; fi - -after_success: - - if [[ $COVERAGE = 1 ]]; then bash <(curl -s https://codecov.io/bash); fi - -notifications: - email: false diff --git a/CHANGELOG.md b/CHANGELOG.md index 74be2c5c..6cf825f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,45 @@ Changelog Releases for CakePHP 5.4 ------------- +* 14.0.0 + * Breaking: removed the deprecated `CakeDC\Api\Plugin` (use `CakeDC\Api\ApiPlugin`) and `CakeDC\Api\Middleware\RequestHandlerMiddleware` (use `Cake\Http\Middleware\BodyParserMiddleware`). See [Upgrading to 14.x](docs/Documentation/upgrading.md) for every change that needs action. + * Breaking: FlysystemRenderer uses Flysystem v3 (`league/flysystem` ^3.35.3, which includes the fix for CVE-2026-102601). The result `filesystem` must be a `League\Flysystem\FilesystemOperator`, `deliverAsset()` now takes the filesystem and path instead of a v1 `File`, and `getFile()` is removed. A missing file or an invalid path gives a 404; other storage errors, such as an unreachable backend, now reach the error renderer instead. Flysystem v1 and the composer patches for it are dropped. + * Breaking: the OTP 2FA actions need `robthree/twofactorauth` ^3.0.1 and `endroid/qr-code` ^5.0 || ^6.0; versions 1 and 2 of `robthree/twofactorauth` no longer work. A string `algorithm` setting (for example `'sha1'`) is still accepted. `robthree/twofactorauth` 3 requires a QR code provider, so when `OneTimePasswordAuthenticator.qrcodeprovider` is null every OTP action fails in `initialize()`, including `otp_verify_check`, which does not use a QR code. The `cakedc/users` default config sets an `EndroidQrCodeProvider`; an app that overrides `OneTimePasswordAuthenticator` must keep a provider. + * Breaking: the members that lost their leading underscore in 13.0.0, for example `_getEntitiesQuery()` and `$_table`, are now checked. An override that keeps an old name is silently never called, so the constructors of actions, services, extensions, renderers and parsers now throw a `CakeException` listing such members. A member is reported only when the plugin class that the class extends, or a plugin trait that the class uses, has the new name; private members and the old names of traits from other packages, such as `_getReCaptchaInstance()` of cakedc/auth, are not. `Api.legacyMemberGuard` set to the boolean `false` in the application configuration turns the check off. See the full list in [Upgrading to 14.x](docs/Documentation/upgrading.md#renamed-protected-members). + * Breaking: `OtpVerifyGetAction::onVerifyGetSecret()` no longer types its `$user` parameter as `array`, because the identity is an entity; an override must drop the `array` type. A subclass of `JwtRefreshAction` that reads `$this->payload` gets an array instead of an object; this changed in 13.0.1 and was not listed there. `SecondFactorTrait::hasVerifiedOtp()` and `hasWebauthnCredential()` type their parameter as `EntityInterface|array|null`, so a call with an identity of another type fails with a `TypeError`. WebAuthn no longer offers the non-standard `Ed256` and `Ed512` algorithms; `EdDSA` (Ed25519) is offered instead. + * Breaking: WebAuthn two-factor authentication needs `web-auth/webauthn-lib` ^5.3.13, the first release without open security advisories; 4.x is no longer supported. Registered keys keep working: stored credentials are read as they are, and are still written in a form that 13.x can read. A registration or login that was started before the upgrade must be started again, because only the challenge is stored between the two requests now, not a serialized options object. The JSON that clients receive and send keeps its shape, and standard base64 is still accepted in responses. A response sent from a cross-origin frame (one that carries `topOrigin`) is refused. For code that extends the plugin: `CakeDC\Api\Webauthn\PublicKeyCredentialLoader` is removed; `UserCredentialSourceRepository` no longer implements the library's removed repository interface and works with `Webauthn\CredentialRecord`; `verifyResponse()` of both adapters returns a `CredentialRecord`; and the `webauthn2fa_register_options` and `webauthn2fa_auth_options` actions return the options as an array, built by the new `BaseAdapter::getOptionsData()`. `cakedc/users` ^17.1 is now required: 17.1 uses the same `web-auth/webauthn-lib` version, so the WebAuthn pages of that plugin and the WebAuthn endpoints of this one work in the same application. See [Upgrading to 14.x](docs/Documentation/upgrading.md#webauthn-with-web-authwebauthn-lib-5). + * WebAuthn: a domain without an `Api.Webauthn2fa.` entry is answered with code 400 and "WebAuthn is not configured for this domain" instead of failing with a `TypeError`; a credential id that is already registered is refused; and registration options requested a second time with the same token are now stored, so the retry no longer fails with an invalid challenge. + * Require `firebase/php-jwt` ^7.0 (used by the `Authentication.Jwt` authenticator), which includes the fix for CVE-2025-45769. + * Require `cakephp/authentication` ^4.2 directly, the version `cakedc/users` 17 requires. The plugin uses it in several classes but only required it through `cakedc/users`. + * Require `crustum/cakephp-attribute-resolver` ^1.0.3 instead of ^1.0. Versions before 1.0.3 can scan the same file twice when one directory is reachable through two paths (a symlink or a Composer path repository), so each `#[ApiScope]` was applied twice and its path prefix doubled. + * Remove the `lcobucci/jwt` and `lcobucci/clock` requirements. JWT tokens are now signed with `firebase/php-jwt`, the library that already verifies them, so the plugin needs one JWT library instead of two. The tokens are the same, byte for byte: the same header, claims and claim order, dates with microseconds as floats, and characters outside ASCII unescaped; tokens issued before the upgrade stay valid. + * Breaking: a JWT secret shorter than 64 bytes is still refused when a token is issued, now with an `InvalidArgumentException` instead of `Lcobucci\JWT\Signer\InvalidKeyProvided` (which extends it). An application that uses `Lcobucci\JWT` or `lcobucci/clock` in its own code, for example in an override of `generateAccessToken()` or `generateRefreshToken()`, must require the package itself; `lcobucci/clock` 3 can now be installed, which the plugin's `<2.3.0` limit prevented. + * Add `suggest` entries for the optional feature packages, and `conflict` rules that allow only the versions the plugin supports: `cakephp/migrations` ^4.5 || ^5.0, `league/flysystem` ^3.35.3, `robthree/twofactorauth` ^3.0.1, `endroid/qr-code` ^5.0 || ^6.0, `google/recaptcha` ^1.3 || ^2.1, and `web-auth/webauthn-lib` ^5.3.13. With these versions `composer audit` reports no security advisory for the plugin's dependencies. + * Rector set `config/rector/cakephp-api-13.php` for applications that upgrade from 12.x: it renames the members that lost their leading underscore in subclasses and their calls, replaces the removed classes, and adds the return and property types that overrides now need. See [Upgrading to 14.x](docs/Documentation/upgrading.md#automated-upgrade-with-rector). + * Sort and ExtendedSort extensions: add the `order` setting for a default order, appended after the request sort as a tie-breaker. Ignored sort fields and invalid ExtendedSort JSON are logged at `debug` level with the `api` scope. ExtendedSort entries with a non-string order now fall back to `asc` instead of being skipped, like an unknown order string. `SortableTrait` gains the protected methods `order()`, `logIgnoredSort()`, `logValue()` and `ignoredSortField()`; a subclass of `SortExtension` or `ExtendedSortExtension` that declares a method with one of these names must use a compatible signature. + * JWT refresh: refresh tokens carry an `auth_time` claim with the time of login or of completing the second factor, kept across refreshes. The new `Api.Jwt.RefreshToken.maxSessionLifetime` setting (seconds, default `null` = unlimited) refuses a refresh once the session is older, which also bounds how long a session keeps the 2FA state it had at login. Refresh tokens issued before this release never get the claim, so they are refused as soon as the setting is on. The stored refresh token is now compared in constant time. A string of digits, as read from an environment variable, is accepted. Any other value except `null` and `false`, such as `0` or a negative number, makes every refresh fail with an `InvalidArgumentException`. + * Routing: the `patterns`, `pass` and `name` options of a route now take effect, and its other keys become route defaults. This applies to routes added with `Service::mapAction()` and to attribute routes (`#[ApiRoute]`, `#[ApiGet]` and the other verb attributes), which are connected through `mapAction()`; these keys used to be ignored. The `defaults` of `#[ApiScope]` are now applied to the routes of the service. + * Upgrade note: attribute routes that set `patterns`, `pass`, `name` or `defaults`, also through `#[ApiScope]`, behave differently than in 13.x, where these options had no effect. A route with a pattern no longer matches URLs that the pattern excludes. + * reCAPTCHA: a missing or non-string `g-recaptcha-response` now fails validation instead of raising a `TypeError` with `google/recaptcha` 2.x. + * Paginate and CursorPaginate extensions: a `limit` or `count` below 1 falls back to the configured maximum, and a `page` below 1 to the first page. A negative limit used to reach the query, which failed on MySQL and PostgreSQL and returned every row on SQLite, and a page below 1 caused an error response. + * WebAuthn 2FA: a failed verification (wrong signature, challenge or origin, a malformed request, or no options requested first) now fails with code 401 for `webauthn2fa_auth` and 400 for `webauthn2fa_register`, and the generic messages "WebAuthn authentication failed" and "WebAuthn registration failed". It used to fail with code 500, or with an HTTP 500 and no JSend body when the options had not been requested. The reason is logged at `debug` level with the `api` scope. + * OTP 2FA: a missing or non-scalar `code` in `otp_verify_check` now fails as an invalid code instead of an HTTP 500 caused by a `TypeError`. + * Fixes: services now load the extensions listed in their `$extensions` property; `Service::addAction()` maps the CORS action when `mapCors` is set; `OptionsHandlerExtension` sets its result on the event (its listener now always returns null); `LogExtension` logs the method of the service request instead of `REQUEST_METHOD`; `XmlRenderer` outputs Chronos dates and times instead of dropping them, and formats native dates as RFC 3339 (`+00:00` instead of `+0000`); `SocialLoginAction` calls `socialLogin()` through the Social behavior, as CakePHP 5.3 requires; `bin/cake service routes` gains a `--sort` option and lists the right columns for route collisions. + * Fix `RegisterAction`: after saving the user it dispatched `Users.Global.beforeRegister` again instead of `Users.Global.afterRegister`, so afterRegister listeners never ran and beforeRegister listeners ran twice. + * Upgrade note (fix): listeners that used the second `Users.Global.beforeRegister` call to change the saved user must listen to `Users.Global.afterRegister` instead. + * Fix the WebAuthn adapters failing with a `TypeError` (HTTP 500) when the request has no `Authorization` header, for example OTP enrollment with a session login. WebAuthn registration and authentication options now need a bearer token and are answered with code 400 without one, instead of storing the challenge where other such requests share it. For code that extends the adapters: without a bearer token `BaseAdapter::saveStore()` throws a `BadRequestException`, `readStore()` returns a new, empty entity and `deleteStore()` returns `false`. `UserCredentialSourceRepository::__construct()` takes the WebAuthn serializer as an optional fourth argument. + * Fix `FileRenderer` answering HTTP 400 for a missing file; it now answers 404 with the error body. + * Fix a service that cannot be built being answered with an empty HTTP 400 and nothing in the logs. `ParseApiRequestMiddleware` now passes the exception on to the application's error handling. This is also where the check for pre-13.0 member names reports a service, a service extension, a renderer or a parser. An `UnauthenticatedException` thrown before the service is built is still answered with an empty HTTP 400. + * Fix the check for pre-13.0 member names and the Rector set leaving out the second-factor checks of `SecondFactorTrait`: `_hasVerifiedOtp()`, `_hasWebauthnCredential()` and `_refuseEnrollmentIf()`, which had an underscore only in 12.0.2 and 12.0.3, are now reported and renamed. The members of `CachedApiRbac` that had an underscore in those two releases are covered by neither; rename them by hand, see [Upgrading to 14.x](docs/Documentation/upgrading.md#renamed-protected-members). + * Fix `CrudAction`: a `table` action option given as a table name failed with a `TypeError`; the table is now loaded from the table locator. + * Fix `Action::transform()`: an empty list is now transformed as an empty collection and gives an empty list; it used to be passed to the transformer as one item. + * Fix versioning: a version without its own service class, such as `/api/v2/articles`, was served by the generic `FallbackService` instead of the app's unversioned `ArticlesService`, so the app's actions and routes were missing and the table's default CRUD actions were exposed. `useVersioning` without `Api.defaultVersion` looked services up in a `Service/v` namespace, so every unversioned app service fell back to `FallbackService`. A URL without a version took the class of `Api.defaultVersion` but not its version, so versioned options in `Api.Service` did not apply. + * Upgrade note (fix): with `useVersioning`, versions and URLs without their own class are now served by the unversioned service class before `FallbackService`. With `Api.defaultVersion` set, a URL without a version now reports that version and gets its `Api.Service` options. The default version, and a version without a service class of its own, read both the unversioned `Api.Service.` options and the options under the version key (`Api.Service.v1.`, `Api.Service.v1.default`); on a conflict the version key wins. An option set for a service, such as an extension that scopes the query, can therefore not be skipped by asking for another version number. In action options, list values such as `sortableFields` and `Extension` are joined; in service `options`, a key under the version replaces the unversioned key whole, an `Extension` list included. This is new for a URL that names the default version, such as `/api/v1/articles`, or a version without its own class, such as `/api/v7/articles`: they read only the version key before, so an unversioned setting that loosens a check now applies there too. A version with its own service class reads only the options under its version key and `Api.Service.default`. + * Fix `Action`: an extension listed without a plugin prefix, such as `Sort`, failed to load with a `TypeError`; an attachable extension on an action without a matching property raised a PHP 8.2 dynamic property deprecation; and `setExtensions()` without an argument dropped the action's extension registry instead of keeping it. + * Fix `ApiRbac` and `CachedApiRbac` failing with a `TypeError` (HTTP 500) for a user whose role is not a string, such as a role stored in an integer column; the role is now matched as a string, and a role mapped to an enum is matched by the value of its case. A role that is neither, such as an array, cannot be matched: the request is denied and a warning is logged. Only a user without a role gets `default_role`. + * Deprecated, to be removed in 15.0.0: the pre-10.0 auth layer `CakeDC\Api\Service\Auth\Auth`, `CakeDC\Api\Service\Auth\AuthenticateTrait`, `CakeDC\Api\Service\Action\Extension\AuthenticationExtension` (which now raises a deprecation warning when enabled), and `Action::$Auth`, `Action::initializeAuth()` and `Action::authConfig()`. `Auth::allow()` never controlled access: public endpoints come from the rules in `api_permissions.php` (`bypassAuth`, or an `allowed` callable that does not check the user). The plugin's own actions no longer call `Auth::allow()`. `LoginAction` reads the identity with `Action::getIdentity()`, so an `identityAttribute` set by an `authConfig()` override no longer applies to the login. + * Remove `Api.Jwt.enabled` and the `require_ssl` option of the default action's `Auth` settings from `config/api.php`. Neither was ever read: the JWT actions and the JWT authenticator are always registered, and the plugin has no HTTPS check. Correct the comment that called `'allow' => '*'` in those `Auth` settings the switch for public access: access is decided by the rules in `config/api_permissions.php`. + * 13.0.1 * Security: refreshing a JWT issued before the second factor was completed returned tokens that no longer required 2FA; refresh now preserves the token audience. * Upgrade note: if 2FA is enabled, invalidate existing refresh tokens after upgrading, by emptying the `jwt_refresh_tokens` table or rotating `Api.Jwt.RefreshToken.secret`. Until you do, tokens that were already escalated before the upgrade keep their privileged audience: the access tokens stay valid for the rest of their lifetime, and their refresh tokens keep minting privileged ones. Rotating `Api.Jwt.AccessToken.secret` also ends current access tokens. @@ -25,6 +64,12 @@ Releases for CakePHP 5.4 * WebAuthn: keys are stored again under `additional_data.api.`, where they are read. Keys registered with 13.0.0 were stored without the `api` level and could not be used; those users register their key again. * OTP: setting up OTP (`otp_verify`) no longer fails with HTTP 500. In 13.0.0 the identity, an entity, was passed to `OtpVerifyGetAction::onVerifyGetSecret()`, which takes an array. +* 13.0.0 + * Attribute routing: services can declare their actions and routes with PHP attributes (`#[ApiActions]`, `#[ApiRoute]`, `#[ApiGet]`, `#[ApiScope]` and others), resolved through `crustum/cakephp-attribute-resolver`. See [Attribute Routing](docs/index.md#attribute-routing). + * Breaking: protected (and a few public) methods and properties of the plugin classes lost their leading underscore, for example `_getEntitiesQuery()` is now `getEntitiesQuery()` and `$_table` is now `$table`. See the full list in [Upgrading to 14.x](docs/Documentation/upgrading.md#renamed-protected-members). + * Breaking: most public and protected methods now declare native parameter and return types, for example `Action::execute(): mixed` and `CrudAction::getEntitiesQuery(): SelectQuery`. Overrides must use compatible signatures. See [Upgrading to 14.x](docs/Documentation/upgrading.md#native-types). + * Breaking: require PHP 8.3 or newer, `cakephp/cakephp` ^5.4 and `cakedc/users` ^17.0. + Releases for CakePHP 5.0 ------------- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 26f53081..e5d27122 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,4 +1,4 @@ Contributing ============ -This repository follows the [CakeDC Plugin Standard](http://cakedc.com/plugin-standard). If you'd like to contribute new features, enhancements or bug fixes to the plugin, please read our [Contribution Guidelines](http://cakedc.com/contribution-guidelines) for detailed instructions. +This repository follows the [CakeDC Plugin Standard](https://cakedc.com/plugin-standard). If you'd like to contribute new features, enhancements or bug fixes to the plugin, please read our [Contribution Guidelines](https://cakedc.com/contribution-guidelines) for detailed instructions. diff --git a/LICENSE.txt b/LICENSE.txt index e6a88c31..dc310aa1 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -5,7 +5,7 @@ Cake Development Corporation 1785 E. Sahara Avenue, Suite 490-423 Las Vegas, Nevada 89104 Phone: +1 702 425 5085 -http://cakedc.com +https://cakedc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), diff --git a/README.md b/README.md index 0148c9b6..0c3ff0ac 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,48 @@ API Plugin for CakePHP ====================== -[![Bake Status](https://api.travis-ci.com/CakeDC/cakephp-api.png?branch=master)](https://travis-ci.com/CakeDC/cakephp-api) +[![CI](https://github.com/CakeDC/cakephp-api/actions/workflows/ci.yml/badge.svg)](https://github.com/CakeDC/cakephp-api/actions/workflows/ci.yml) [![Downloads](https://poser.pugx.org/CakeDC/cakephp-api/d/total.png)](https://packagist.org/packages/CakeDC/cakephp-api) [![Latest Version](https://poser.pugx.org/CakeDC/cakephp-api/v/stable.png)](https://packagist.org/packages/CakeDC/cakephp-api) [![License](https://poser.pugx.org/CakeDC/cakephp-api/license.svg)](https://packagist.org/packages/CakeDC/cakephp-api) -[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/CakeDC/cakephp-api/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/CakeDC/cakephp-api/?branch=master) -[![Code Coverage](https://scrutinizer-ci.com/g/CakeDC/cakephp-api/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/CakeDC/cakephp-api/?branch=master) The **CakePHP-API** Plugin allows to easily expose a versioned API in a few lines of code. Versions and branches --------------------- -| CakePHP | CakeDC Api Plugin | Tag | Notes | -| :-------------: | :------------------------: | :--: | :---- | -| 5.0 | [10.x-cake5.0](https://github.com/cakedc/cakephp-api/tree/10.x-cake5.0) | 10.0.0 | unstable | -| 4.3 | [9.x-cake4.3](https://github.com/cakedc/cakephp-api/tree/9.x-cake4.3) | 9.0.1 | unstable | -| 4.0 | [8.x](https://github.com/cakedc/cakephp-api/tree/8.x) | 8.0.14 | unstable | -| ^3.7 | [master](https://github.com/cakedc/cakephp-api/tree/master) | 7.0.0 | stable | -| ^3.7 <4.0 | [7.x](https://github.com/cakedc/cakephp-api/tree/7.x) | 7.1.0 | stable | -| 3.6 | [6.x](https://github.com/cakedc/cakephp-api/tree/6.x) | 6.0.1 | stable | -| 3.5 | [5.x](https://github.com/cakedc/cakephp-api/tree/5.0.0) | 5.0.0 | stable | -| 3.4 | [4.x](https://github.com/cakedc/cakephp-api/tree/4.0.0) | 4.0.0 | stable | -| 3.3 | [3.x](https://github.com/cakedc/cakephp-api/tree/3.3) | 3.3 | stable | +Two versions are maintained and receive security fixes: 14.x for CakePHP 5 and 11.x for CakePHP 4. All other versions are end of life: they receive no fixes, including security fixes, so upgrade to a maintained version. For the two maintained versions, the CakePHP and PHP columns are the minimum versions that the release and its dependencies require. For the end-of-life rows they are the CakePHP major version and the lowest PHP version in the group. + +| Version | Branch | CakePHP | PHP | Notes | +| :-----: | :----- | :-----: | :-: | :---- | +| 14.0.0 | [14.x-cake5.4](https://github.com/cakedc/cakephp-api/tree/14.x-cake5.4) | ^5.4 | >= 8.3 | Active. The only maintained version for CakePHP 5. [Upgrading from 13.x or 12.x](docs/Documentation/upgrading.md) | +| 11.1.3 | [11.next-cake4.5](https://github.com/cakedc/cakephp-api/tree/11.next-cake4.5) | ^4.5 | >= 7.4 | Security fixes. The only maintained version for CakePHP 4. CakePHP 4.5 is required through `cakedc/users` ^13 | +| 13.x, 12.x, 10.x | | 5.x | >= 8.1 | End of life. Upgrade to 14.x | +| 9.x, 8.x | | 4.x | >= 7.2 | End of life. Upgrade to 11.x | +| 7.x and older | | 3.x | >= 5.4.16 | End of life | + +The releases of the versions that are end of life stay available through their [tags](https://github.com/CakeDC/cakephp-api/tags). Documentation ------------- -For documentation, see the [Docs](docs/index.md) directory of this repository. +For documentation, see the [Docs](docs/index.md) directory of this repository. Upgrading from 13.x or 12.x: see [Upgrading to 14.x](docs/Documentation/upgrading.md). For upgrades from 12.x, a [Rector set](docs/Documentation/upgrading.md#automated-upgrade-with-rector) renames the members that lost their leading underscore and adds the native types your overrides need. Support ------- For bugs and feature requests, please use the [issues](https://github.com/CakeDC/cakephp-api/issues) section of this repository. -Commercial support is also available, [contact us](http://cakedc.com/contact) for more information. +Commercial support is also available, [contact us](https://cakedc.com/contact) for more information. Contributing ------------ -This repository follows the [CakeDC Plugin Standard](http://cakedc.com/plugin-standard). If you'd like to contribute new features, enhancements or bug fixes to the plugin, please read our [Contribution Guidelines](http://cakedc.com/contribution-guidelines) for detailed instructions. +This repository follows the [CakeDC Plugin Standard](https://cakedc.com/plugin-standard). If you'd like to contribute new features, enhancements or bug fixes to the plugin, please read our [Contribution Guidelines](https://cakedc.com/contribution-guidelines) for detailed instructions. License ------- -Copyright 2016-2023 Cake Development Corporation (CakeDC). All rights reserved. +Copyright 2016-2026 Cake Development Corporation (CakeDC). All rights reserved. -Licensed under the [MIT](http://www.opensource.org/licenses/mit-license.php) License. Redistributions of the source code included in this repository must retain the copyright notice found in each file. +Licensed under the [MIT](https://www.opensource.org/licenses/mit-license.php) License. Redistributions of the source code included in this repository must retain the copyright notice found in each file. diff --git a/composer.json b/composer.json index aea06a4e..c3cd4376 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "authors": [ { "name": "CakeDC", - "homepage": "http://www.cakedc.com", + "homepage": "https://www.cakedc.com", "role": "Author" }, { @@ -29,28 +29,44 @@ "require": { "php": ">=8.3", "ext-json": "*", + "cakephp/authentication": "^4.2", "cakephp/cakephp": "^5.4", - "cakedc/users": "^17.0", - "crustum/cakephp-attribute-resolver": "^1.0", - "lcobucci/clock": "^2.2.0,<2.3.0", - "lcobucci/jwt": "^5.5.0", - "firebase/php-jwt": "^6.3 || ^7.0" + "cakedc/users": "^17.1", + "crustum/cakephp-attribute-resolver": "^1.0.3", + "firebase/php-jwt": "^7.0" }, "require-dev": { "boundwize/structarmed": "^0.14", "cakedc/cakephp-phpstan": "^4.3", - "cakephp/cakephp-codesniffer": "^4.5", - "cweagans/composer-patches": "^1.7", - "endroid/qr-code": "^4", - "google/recaptcha": "@stable", + "cakephp/cakephp-codesniffer": "^5.3", + "cakephp/migrations": "^4.5 || ^5.0", + "endroid/qr-code": "^5.0 || ^6.0", + "google/recaptcha": "^1.3 || ^2.1", "laminas/laminas-diactoros": "^3.0", - "league/flysystem-vfs": "^1.0", - "phpunit/phpunit": "^11.5 || ^12.5", - "phpstan/phpstan": "^2.2.2,<2.2.6", - "rector/rector": "^2.5", - "robthree/twofactorauth": "^1.6", - "vlucas/phpdotenv": "^3.3", - "web-auth/webauthn-lib": "^4.4" + "league/flysystem": "^3.35.3", + "league/flysystem-memory": "^3.0", + "phpunit/phpunit": "^12.5.22 || ^13.3", + "phpstan/phpstan": "^2.2.16", + "rector/rector": "^2.6", + "squizlabs/php_codesniffer": "^4.0.2", + "robthree/twofactorauth": "^3.0.1", + "web-auth/webauthn-lib": "^5.3.13" + }, + "suggest": { + "cakephp/migrations": "Required to create the plugin tables with bin/cake migrations migrate -p CakeDC/Api (^4.5 || ^5.0)", + "google/recaptcha": "Required for the recaptcha service (^1.3 || ^2.1)", + "league/flysystem": "Required for the Flysystem renderer (^3.35.3)", + "robthree/twofactorauth": "Required for OTP two-factor authentication (^3.0.1), together with endroid/qr-code", + "endroid/qr-code": "Required by the default OTP QR code provider, robthree's EndroidQrCodeProvider (^5.0 || ^6.0)", + "web-auth/webauthn-lib": "Required for WebAuthn two-factor authentication (^5.3.13)" + }, + "conflict": { + "cakephp/migrations": "<4.5 || >=6.0", + "endroid/qr-code": "<5.0 || >=7.0", + "google/recaptcha": "<1.3 || >=2.0 <2.1 || >=3.0", + "league/flysystem": "<3.35.3 || >=4.0", + "robthree/twofactorauth": "<3.0.1 || >=4.0", + "web-auth/webauthn-lib": "<5.3.13 || >=6.0" }, "autoload": { "psr-4": { @@ -65,35 +81,9 @@ } }, "prefer-stable": true, - "extra": { - "patches": { - "endroid/qr-code": { - "Fix implicit nullable params in PHP 8.4": "patches/endroid-qr-code-nullable.patch" - }, - "league/flysystem": { - "Fix implicit nullable params in PHP 8.4": "patches/flysystem-nullable.patch" - }, - "league/flysystem-vfs": { - "Fix null passed to str_replace in PHP 8.1+": "patches/flysystem-vfs-null-str-replace.patch" - } - } - }, "config": { "sort-packages": true, - "audit": { - "ignore": [ - "PKSA-w9tt-7782-78jx" - ] - }, - "policy": { - "advisories": { - "ignore": [ - "league/flysystem" - ] - } - }, "allow-plugins": { - "cweagans/composer-patches": true, "dealerdirect/phpcodesniffer-composer-installer": true } }, @@ -113,8 +103,8 @@ "analyse": [ "@stan" ], - "cs-check": "vendor/bin/phpcs -p --standard=phpcs.xml src/ tests/", - "cs-fix": "vendor/bin/phpcbf --standard=phpcs.xml src/ tests/", + "cs-check": "vendor/bin/phpcs -p", + "cs-fix": "vendor/bin/phpcbf", "fix-eol": "powershell -NoProfile -ExecutionPolicy Bypass -File tools/fix-lineendings.ps1", "test": "phpunit --stderr", "rector-check": "vendor/bin/rector process --dry-run", diff --git a/config/Migrations/20180313201241_initial_jwt_auth.php b/config/Migrations/20180313201241_initial_jwt_auth.php index d89171dd..14a6bf66 100644 --- a/config/Migrations/20180313201241_initial_jwt_auth.php +++ b/config/Migrations/20180313201241_initial_jwt_auth.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ use Migrations\BaseMigration; diff --git a/config/Migrations/20231003201241_auth_store.php b/config/Migrations/20231003201241_auth_store.php index 102442e5..cdcb847c 100644 --- a/config/Migrations/20231003201241_auth_store.php +++ b/config/Migrations/20231003201241_auth_store.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ use Migrations\BaseMigration; diff --git a/config/api.php b/config/api.php index b2d6820c..84bc4c1f 100644 --- a/config/api.php +++ b/config/api.php @@ -1,12 +1,12 @@ null, 'lookupMode' => 'underscore', + // `legacyMemberGuard` is on unless the application sets it to the boolean false: application + // classes that still override a member by its pre-13.0 underscore name, which the plugin no + // longer calls, are refused. It has no default here, so that a value set in the application + // configuration is kept. See docs/Documentation/upgrading.md before turning it off. + '2fa' => [ 'enabled' => false, ], @@ -59,8 +64,9 @@ ], ], + // The JWT actions (jwt_login, jwt_refresh) and the JWT authenticator are always registered. + // They need both secrets, and the permission rules decide who may call them. 'Jwt' => [ - 'enabled' => false, 'AccessToken' => [ 'lifetime' => 600, 'secret' => '', @@ -68,6 +74,9 @@ 'RefreshToken' => [ 'lifetime' => 14 * 86400, 'secret' => '', + // Maximum age of a session in seconds, counted from login across all refreshes. + // null lets a session be refreshed forever, as long as each refresh is in time. + 'maxSessionLifetime' => null, ], ], 'Middleware' => [ @@ -102,16 +111,17 @@ 'options' => [], 'Action' => [ 'default' => [ - //auth configuration + // Configuration of the deprecated `Action::$Auth` object (removed in 15.0.0). + // It does NOT control access: the request lifecycle never reads it. Access is + // decided by the authentication middleware and by the rules in + // config/api_permissions.php, so removing `allow` secures nothing. 'Auth' => [ - 'allow' => '*', // PUBLIC ACCESS for all API endpoints, remove this line to secure + 'allow' => '*', 'authorize' => [ 'CakeDC/Api.Crud' => [] ], 'authenticate' => [ - 'CakeDC/Api.Token' => [ - 'require_ssl' => false, - ] + 'CakeDC/Api.Token' => [], ], ], // default app extensions diff --git a/config/api_permissions.php.default b/config/api_permissions.php.default index 2fdc9e59..a81e6597 100644 --- a/config/api_permissions.php.default +++ b/config/api_permissions.php.default @@ -1,13 +1,22 @@ [ - [ - 'role' => '*', - 'service' => '*', - 'action' => '*', - 'method' => '*', - 'bypassAuth' => true, - ], - ] + [ + 'role' => '*', + 'service' => '*', + 'action' => '*', + 'method' => '*', + 'bypassAuth' => true, + ], + ], ]; diff --git a/config/bootstrap.php b/config/bootstrap.php index bb8ed51b..280a603e 100644 --- a/config/bootstrap.php +++ b/config/bootstrap.php @@ -1,12 +1,12 @@ + */ + private array $namespaces = []; + + /** + * @inheritDoc + */ + public function getRuleDefinition(): RuleDefinition + { + return new RuleDefinition('Add the type of a parent property to the property a subclass redeclares', [ + new ConfiguredCodeSample( + 'protected $idName = \'uuid\';', + 'protected string $idName = \'uuid\';', + ['CakeDC\Api\\'], + ), + ]); + } + + /** + * @inheritDoc + */ + public function getNodeTypes(): array + { + return [Property::class]; + } + + /** + * @param \PhpParser\Node\Stmt\Property $node + * @return \PhpParser\Node|null + */ + public function refactor(Node $node): ?Node + { + // a typed property is left alone, and one statement with several properties has one type + if ($node->type !== null || count($node->props) !== 1) { + return null; + } + $class = ScopeFetcher::fetch($node)->getClassReflection(); + if (!$class instanceof ClassReflection) { + return null; + } + $parent = $this->findParent($class); + if (!$parent instanceof ClassReflection) { + return null; + } + $name = (string)$this->getName($node); + $native = $parent->getNativeReflection(); + // the property may still have its old name here: the rename happens in the same run + foreach (array_unique([$name, ltrim($name, '_')]) as $candidate) { + if ($candidate === '' || !$native->hasProperty($candidate)) { + continue; + } + $property = $native->getProperty($candidate); + $type = $this->typeNode($property); + if ($type instanceof Node) { + $node->type = $type; + // without a type the property was null until set; with a type and no default it would be + // uninitialized, and reading it would stop PHP with an error + if ($node->props[0]->default === null && $property->getType()?->allowsNull()) { + $node->props[0]->default = new ConstFetch(new Name('null')); + } + + return $node; + } + } + + return null; + } + + /** + * @param array $configuration Namespace prefixes, such as `CakeDC\Api\`. + * @return void + */ + public function configure(array $configuration): void + { + $this->namespaces = $configuration; + } + + /** + * The nearest parent class that belongs to one of the configured namespaces. + * + * @param \PHPStan\Reflection\ClassReflection $class Class of the property. + * @return \PHPStan\Reflection\ClassReflection|null + */ + private function findParent(ClassReflection $class): ?ClassReflection + { + $parent = $class->getParentClass(); + while ($parent instanceof ClassReflection) { + foreach ($this->namespaces as $namespace) { + if (str_starts_with($parent->getName(), $namespace)) { + return $parent; + } + } + $parent = $parent->getParentClass(); + } + + return null; + } + + /** + * Builds the type node of a property's native type. + * + * @param \ReflectionProperty $property Property of the plugin class. + * @return \PhpParser\Node\Identifier|\PhpParser\Node\Name|\PhpParser\Node\ComplexType|null Null when the + * property has no type, or a type this rule does not write (an intersection type). + */ + private function typeNode(ReflectionProperty $property): Identifier|Name|ComplexType|null + { + $type = $property->getType(); + if ($type instanceof ReflectionNamedType) { + $node = $this->namedTypeNode($type, $property); + // `mixed` and `null` include null already and cannot be written with `?` + $plain = in_array($type->getName(), ['mixed', 'null'], true); + + return $type->allowsNull() && !$plain ? new NullableType($node) : $node; + } + if ($type instanceof ReflectionUnionType) { + $types = []; + foreach ($type->getTypes() as $member) { + if (!$member instanceof ReflectionNamedType) { + return null; + } + $types[] = $this->namedTypeNode($member, $property); + } + + return new UnionType($types); + } + + return null; + } + + /** + * @param \ReflectionNamedType $type Named type. + * @param \ReflectionProperty $property Property that declares it. + * @return \PhpParser\Node\Identifier|\PhpParser\Node\Name + */ + private function namedTypeNode(ReflectionNamedType $type, ReflectionProperty $property): Identifier|Name + { + $name = $type->getName(); + if ($type->isBuiltin()) { + return new Identifier($name); + } + // `self` in the plugin class means that class, not the subclass that redeclares the property + if (in_array($name, ['self', 'static'], true)) { + $name = $property->getDeclaringClass()->getName(); + } + + return new FullyQualified($name); + } +} diff --git a/config/rector/RenameInheritedCallRector.php b/config/rector/RenameInheritedCallRector.php new file mode 100644 index 00000000..1ee04068 --- /dev/null +++ b/config/rector/RenameInheritedCallRector.php @@ -0,0 +1,139 @@ +_x()` while the class still declares `_x()`, + * which is the case until the declaration itself is renamed in the same run. + */ +final class RenameInheritedCallRector extends AbstractRector implements ConfigurableRectorInterface +{ + /** + * @var array<\Rector\Renaming\ValueObject\MethodCallRename> + */ + private array $renames = []; + + /** + * @inheritDoc + */ + public function getRuleDefinition(): RuleDefinition + { + return new RuleDefinition('Rename the calls a subclass makes to renamed methods of its parents', [ + new ConfiguredCodeSample( + 'return parent::_getEntitiesQuery();', + 'return parent::getEntitiesQuery();', + [new MethodCallRename('CakeDC\Api\Service\Action\CrudAction', '_getEntitiesQuery', 'getEntitiesQuery')], + ), + ]); + } + + /** + * @inheritDoc + */ + public function getNodeTypes(): array + { + return [MethodCall::class, StaticCall::class]; + } + + /** + * @param \PhpParser\Node\Expr\MethodCall|\PhpParser\Node\Expr\StaticCall $node + * @return \PhpParser\Node|null + */ + public function refactor(Node $node): ?Node + { + $name = $this->getName($node->name); + if ($name === null) { + return null; + } + $class = ScopeFetcher::fetch($node)->getClassReflection(); + if (!$class instanceof ClassReflection) { + return null; + } + if ($node instanceof MethodCall) { + if (!$node->var instanceof Variable || !$this->isName($node->var, 'this')) { + return null; + } + $target = $class; + } elseif ($node->class instanceof Name && $this->isName($node->class, 'parent')) { + $target = $class->getParentClass(); + } elseif ($node->class instanceof Name && $this->isNames($node->class, ['self', 'static'])) { + $target = $class; + } else { + return null; + } + if (!$target instanceof ClassReflection) { + return null; + } + foreach ($this->renames as $rename) { + if ($rename->getOldMethod() !== $name || !$target->is($rename->getClass())) { + continue; + } + $new = $rename->getNewMethod(); + // the plugin must have the new name, and a class that declares both names keeps its calls + if (!$target->hasMethod($new) || $this->declaresBoth($target, $name, $new)) { + continue; + } + $node->name = new Identifier($new); + + return $node; + } + + return null; + } + + /** + * @param array<\Rector\Renaming\ValueObject\MethodCallRename> $configuration Method renames. + * @return void + */ + public function configure(array $configuration): void + { + $this->renames = $configuration; + } + + /** + * Whether the class itself declares both the old and the new method. + * + * @param \PHPStan\Reflection\ClassReflection $class Class reflection. + * @param string $old Old method name. + * @param string $new New method name. + * @return bool + */ + private function declaresBoth(ClassReflection $class, string $old, string $new): bool + { + $native = $class->getNativeReflection(); + if (!$native->hasMethod($old) || !$native->hasMethod($new)) { + return false; + } + + return $native->getMethod($old)->getDeclaringClass()->getName() === $class->getName() + && $native->getMethod($new)->getDeclaringClass()->getName() === $class->getName(); + } +} diff --git a/config/rector/cakephp-api-13-changes.php b/config/rector/cakephp-api-13-changes.php new file mode 100644 index 00000000..e1c45107 --- /dev/null +++ b/config/rector/cakephp-api-13-changes.php @@ -0,0 +1,265 @@ + [ + 'CakeDC\\Api\\Plugin' => 'CakeDC\\Api\\ApiPlugin', + 'CakeDC\\Api\\Middleware\\RequestHandlerMiddleware' => 'Cake\\Http\\Middleware\\BodyParserMiddleware', + ], + 'methods' => [ + ParseApiRequestMiddleware::class => [ + '_matchRequest', + ], + ApiRbac::class => [ + '_camelizeByChars', '_matchOrAsterisk', '_matchPermission', '_startsWith', '_terminalKeysLast', + ], + ApiConfigProvider::class => [ + '_loadPermissions', + ], + Action::class => [ + '_authConfig', '_executeAction', '_initializeAuth', '_loadExtensions', + ], + LoginAction::class => [ + '_afterIdentifyUser', + ], + RegisterAction::class => [ + '_afterRegister', '_registerOptions', + ], + ResetPasswordAction::class => [ + '_changePassword', + ], + // 12.0.2 and 12.0.3 named the second-factor checks with an underscore + OtpVerifyAction::class => [ + '_hasVerifiedOtp', '_hasWebauthnCredential', '_refuseEnrollmentIf', + ], + TwoFactorAuthAction::class => [ + '_hasVerifiedOtp', '_hasWebauthnCredential', '_refuseEnrollmentIf', + ], + Webauthn2faRegisterAction::class => [ + '_hasVerifiedOtp', '_hasWebauthnCredential', '_refuseEnrollmentIf', + ], + Webauthn2faRegisterOptionsAction::class => [ + '_hasVerifiedOtp', '_hasWebauthnCredential', '_refuseEnrollmentIf', + ], + SecondFactorTrait::class => [ + '_hasVerifiedOtp', '_hasWebauthnCredential', '_refuseEnrollmentIf', + ], + CollectionAction::class => [ + '_newEntities', '_saveMany', '_validateDataIsArray', '_validateMany', + ], + DeleteAction::class => [ + '_deleteMany', + ], + CrudAction::class => [ + '_buildViewCondition', '_describe', '_getEntities', '_getEntitiesQuery', '_getEntity', + '_getEntityQuery', '_newEntity', '_patchEntity', '_save', + ], + UserFormattingExtension::class => [ + '_userCleanup', + ], + CrudAutocompleteListExtension::class => [ + '_autocompleteList', + ], + CrudHateoasExtension::class => [ + '_buildIndexLinks', '_buildViewLinks', + ], + CrudRelationsExtension::class => [ + '_attachAssociations', '_includeAssociations', '_includeDirectAssociations', '_isRelationAccessible', + '_relatedServiceName', + ], + CursorPaginateExtension::class => [ + '_count', '_maxId', '_sinceId', + ], + PaginateExtension::class => [ + '_limit', '_page', + ], + SortExtension::class => [ + '_qualifyField', '_sortDirection', '_sortField', + ], + ExtendedSortExtension::class => [ + '_qualifyField', '_sortDirection', '_sortField', + ], + SortableTrait::class => [ + '_qualifyField', '_sortDirection', '_sortField', + ], + ValidateAction::class => [ + '_getReCaptchaInstance', + ], + ReCaptchaTrait::class => [ + '_getReCaptchaInstance', + ], + Auth::class => [ + '_isAllowed', '_setDefaults', + ], + ConfigReader::class => [ + '_checkServiceOptions', '_mergeWithDefaults', + ], + LogExtension::class => [ + '_redact', + ], + ServiceLocator::class => [ + '_compareOptions', '_create', '_getClassName', + ], + BaseRenderer::class => [ + '_buildMessage', '_stackTrace', + ], + FileRenderer::class => [ + '_encode', + ], + JSendRenderer::class => [ + '_fail', '_format', '_mapStatus', '_success', + ], + JsonRenderer::class => [ + '_encode', + ], + XmlRenderer::class => [ + '_array', '_encode', '_format', '_object', + ], + Service::class => [ + '_actionOptions', '_initializeParser', '_initializeRenderer', '_loadExtensions', '_prepareAction', + '_processAction', '_routesWrapper', + ], + IntegrationTestCase::class => [ + '_appendGetParam', '_userToken', + ], + ], + 'properties' => [ + Action::class => [ + '_name', '_route', '_service', + ], + LoginAction::class => [ + '_identifiedField', '_passwordField', + ], + CrudAction::class => [ + '_finder', '_id', '_idName', '_parentId', '_parentIdName', '_table', + ], + ActionExtensionRegistry::class => [ + '_action', + ], + CrudHateoasExtension::class => [ + '_reverseRouter', + ], + CursorPaginateExtension::class => [ + '_reverseRouter', + ], + ActionExtension::class => [ + '_registry', + ], + Result::class => [ + '_code', '_data', '_exception', '_payload', + ], + Auth::class => [ + '_action', '_authentication', '_registry', '_service', + ], + AuthenticateTrait::class => [ + '_authentication', + ], + CrudService::class => [ + '_idName', '_table', + ], + ServiceExtensionRegistry::class => [ + '_service', + ], + CollectionExtension::class => [ + '_service', + ], + ServiceExtension::class => [ + '_registry', + ], + LogExtension::class => [ + '_action', '_service', '_timer', + ], + LocatorAwareTrait::class => [ + '_serviceLocator', + ], + ServiceLocator::class => [ + '_config', '_fallbacked', '_instances', '_options', + ], + NestedCrudService::class => [ + '_parentIdName', + ], + BaseRenderer::class => [ + '_service', + ], + BaseParser::class => [ + '_service', + ], + Service::class => [ + '_action', '_actions', '_actionsClassMap', '_baseUrl', '_corsSuffix', '_innerServices', '_name', + '_parentService', '_parser', '_parserClass', '_renderer', '_rendererClass', '_request', '_response', + '_result', '_routeExtensions', '_routePrefix', '_version', + ], + ServiceRegistry::class => [ + '_defaultLocatorClass', '_locator', + ], + IntegrationTestCase::class => [ + '_defaultUserId', + ], + ], +]; diff --git a/config/rector/cakephp-api-13.php b/config/rector/cakephp-api-13.php new file mode 100644 index 00000000..0bc609e9 --- /dev/null +++ b/config/rector/cakephp-api-13.php @@ -0,0 +1,64 @@ +ruleWithConfiguration(RenameClassRector::class, $changes['classes']); + + $methodRenames = []; + foreach ($changes['methods'] as $class => $names) { + foreach ($names as $name) { + $methodRenames[] = new MethodCallRename($class, $name, substr($name, 1)); + } + } + $rectorConfig->ruleWithConfiguration(RenameMethodRector::class, $methodRenames); + // RenameMethodRector misses `parent::` calls, and `$this->` calls while the old declaration exists + $rectorConfig->ruleWithConfiguration(RenameInheritedCallRector::class, $methodRenames); + + $propertyRenames = []; + foreach ($changes['properties'] as $class => $names) { + foreach ($names as $name) { + $propertyRenames[] = new RenameProperty($class, $name, substr($name, 1)); + } + } + $rectorConfig->ruleWithConfiguration(RenamePropertyRector::class, $propertyRenames); + + // a redeclared property must repeat the type the plugin class now declares; Rector's own + // AddPropertyTypeDeclarationRector is deprecated and throws since Rector 2.8 + $rectorConfig->ruleWithConfiguration(AddInheritedPropertyTypeRector::class, ['CakeDC\\Api\\']); + + // an override must declare the native return type that the plugin method now has + $rectorConfig->rule(AddReturnTypeDeclarationBasedOnParentClassMethodRector::class); +}; diff --git a/config/routes.php b/config/routes.php index dd004949..83b79d31 100644 --- a/config/routes.php +++ b/config/routes.php @@ -1,12 +1,12 @@ [ - // token expiration, - // - 3600 seconds - // - 24 hours - // - 31 days - 'Token' => [ - 'expiration' => 3600 * 24 * 31 - ], - 'Api' => [ - // if service class is not defined we use crud fallback service - 'ServiceFallback' => '\\CakeDC\\Api\\Service\\FallbackService', - // response rendered as JSend - 'renderer' => 'CakeDC/Api.JSend', - // Data parse from cakephp request object - 'parser' => 'CakeDC/Api.Form', - - //routes inflector: specify underscore, dasherize, or false for neither/no inflection - 'routesInflectorMethod' => false, - - // version is not used - 'useVersioning' => false, - 'versionPrefix' => 'v', - - // auth permission uses require auth strategy - 'Auth' => [ - 'Crud' => [ - 'default' => 'auth' - ], - ], - - 'Service' => [ - 'default' => [ - 'options' => [], - 'Action' => [ - 'default' => [ - //auth configuration - 'Auth' => [ - 'storage' => 'Memory', - 'authorize' => [ - 'CakeDC/Api.SimpleRbac' - ], - 'authenticate' => [ - 'CakeDC/Api.Jwt' => [ - 'userModel' => 'CakeDC/Users.Users', - 'require_ssl' => false, - ], - ], - ], - // default app extensions - 'Extension' => [ - // allow request from other domains - 'CakeDC/Api.Cors', - // enable sort - 'CakeDC/Api.Sort', - // load Hateoas - 'CakeDC/Api.CrudHateoas', - // enable relations - 'CakeDC/Api.CrudRelations', - ] - ], - // all index actions configuration - 'Index' => [ - 'Extension' => [ - // enable pagination for index actions - 'CakeDC/Api.Paginate', - ], - ], - ], - ], - ], - 'Log' => [ - 'className' => 'File', - 'scopes' => ['api'], - 'levels' => ['error', 'info'], - 'file' => 'api.log', - ] - ] - ]; - ``` -2. Extend the **AuthService** in `src/Service/Action/.php` - ````php - ['POST'], 'mapCors' => true]; - $this->mapAction('login', LoginAction::class, $methods); - } - } - ```` +1. Read about [Installation](../installation.md) and [configuration](../configuration.md), and create the plugin tables: +refresh tokens are stored in the `jwt_refresh_tokens` table. + + ```bash + bin/cake migrations migrate -p CakeDC/Api + ``` + +2. Set the two secrets in your configuration. Tokens are signed with HS512, so each secret needs at least 64 bytes. -3. Extend and Rewriting the **LoginAction** in `src/Service/Action/Auth/LoginAction.php` ```php - dispatchEvent(UsersAuthComponent::EVENT_BEFORE_LOGIN); - if (is_array($event->result)) { - $user = $this->_afterIdentifyUser($event->result); - } else { - $user = $this->Auth->identify(); - $user = $this->_afterIdentifyUser($user, $socialLogin); - } - if (empty($user)) { - throw new UserNotFoundException(__d('CakeDC/Api', 'User not found'), 401); - } - - $result = [ - 'success' => true, - 'data' => [ - 'token' => JWT::encode( - [ - 'username' => $user['username'], - 'email' => $user['email'], - 'name' => $user['first_name'], - 'sub' => $user['id'], - 'exp' => time() + Configure::read('Users.Token.expiration') - ], - Security::getSalt() - ) - ], - '_serialize' => ['success', 'data'] - ]; - - return $result; - } - - } + 'Api' => [ + 'Jwt' => [ + 'AccessToken' => [ + 'lifetime' => 600, + 'secret' => env('JWT_SECRET'), + ], + 'RefreshToken' => [ + 'lifetime' => 14 * 86400, + 'secret' => env('JWT_REFRESH_SECRET'), + // seconds from login or second factor, null = unlimited + 'maxSessionLifetime' => null, + ], + ], + ], ``` -4. Extend and Rewriting the **RegisterAction** in `src/Service/Action/Auth/RegisterAction.php` + +3. The permission rules in `config/api_permissions.php` decide who may call the actions. A client calls them before it +has an access token, so allow them with a `bypassAuth` rule: + ```php - getUsersTable(); - $user = $usersTable->newEntity(); - $options = $this->_registerOptions(); - $requestData = $this->getData(); - $event = $this->dispatchEvent(UsersAuthComponent::EVENT_BEFORE_REGISTER, [ - 'usersTable' => $usersTable, - 'options' => $options, - 'userEntity' => $user, - ]); - - if ($event->result instanceof EntityInterface) { - if ($userSaved = $usersTable->register($user, $event->result->toArray(), $options)) { - return $this->_afterRegister($userSaved); - } - } - if ($event->isStopped()) { - return false; - } - $userSaved = $usersTable->register($user, $requestData, $options); - if (!$userSaved) { - throw new ValidationException(__d('CakeDC/Api', 'The user could not be saved'), 0, null, $user->getErrors()); - } - - return $this->_afterRegister($userSaved); - } - - /** - * Prepare flash messages after registration, and dispatch afterRegister event - * - * @param EntityInterface $userSaved User entity saved - * @return EntityInterface - */ - protected function _afterRegister(EntityInterface $userSaved) - { - $validateEmail = (bool)Configure::read('Users.Email.validate'); - $message = __d('CakeDC/Api', 'You have registered successfully, please log in'); - if ($validateEmail) { - $message = __d('CakeDC/Api', 'Please validate your account before log in'); - } - $event = $this->dispatchEvent(UsersAuthComponent::EVENT_AFTER_REGISTER, [ - 'user' => $userSaved - ]); - if ($event->result instanceof EntityInterface) { - $userSaved = $event->result; - } - - $event = $this->dispatchEvent('Action.Auth.onRegisterFormat', ['user' => $userSaved]); - if ($event->result) { - $userSaved = $event->result; - } - - $result = [ - 'message' => $message, - 'success' => true, - 'data' => [ - 'token' => JWT::encode( - [ - 'username' => $userSaved['username'], - 'email' => $userSaved['email'], - 'name' => $userSaved['first_name'], - 'sub' => $userSaved['id'], - 'exp' => time() + Configure::read('Users.Token.expiration') - ], - Security::getSalt() - ) - ], - '_serialize' => ['message', 'success', 'data'] - ]; - - return $result; - } - } + [ + 'role' => '*', + 'service' => 'auth', + 'action' => ['jwt_login', 'jwt_refresh'], + 'bypassAuth' => true, + ], ``` - - - - - \ No newline at end of file + + ### Usage + +* `POST /api/auth/jwt_login` with `username` and `password` returns the user with `access_token`, `refresh_token` +and `expired`. +* Send the access token with each request in the `Authorization: Bearer ` header. +* `POST /api/auth/jwt_refresh` with the refresh token in the `Authorization: Bearer ` header returns new tokens. + +See [JWT Authentication](../../index.md#jwt-authentication) for the responses and the two-factor flow. diff --git a/docs/Documentation/Renderers/jsend.md b/docs/Documentation/Renderers/jsend.md index 32eb2f04..051848f8 100644 --- a/docs/Documentation/Renderers/jsend.md +++ b/docs/Documentation/Renderers/jsend.md @@ -14,7 +14,7 @@ Response Types **GET** -When you use this route */api/list* and you have two controllers "Articles" and "Posts" for example you shall get this result. +When you use this route */api/listing* and you have two tables "Articles" and "Posts" for example you shall get this result. ``` { @@ -31,11 +31,9 @@ When you use this route */api/list* and you have two controllers "Articles" and When you use this route */api/describe?token=YOUR_AUTH_TOKEN*. It'll describe your service. Here we are show an example using a service of the plugin. -We need to send three fields in the post to do this request. +We need to send the `service` field in the post to do this request. ``` -username: user -password: password service: listing ``` diff --git a/docs/Documentation/Renderers/json.md b/docs/Documentation/Renderers/json.md deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/Documentation/Renderers/raw.md b/docs/Documentation/Renderers/raw.md deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/Documentation/Renderers/xml.md b/docs/Documentation/Renderers/xml.md deleted file mode 100644 index e69de29b..00000000 diff --git a/docs/Documentation/actions.md b/docs/Documentation/actions.md index c6881d9a..ad9a92c8 100644 --- a/docs/Documentation/actions.md +++ b/docs/Documentation/actions.md @@ -28,10 +28,10 @@ Such service based on api plugin configuration will accesible using /api/blogs/. Of course needed to define what actions are supported by the service and inject them into the service router. -One way to do it - use intialize method in service class. +One way to do it - use initialize method in service class. ```php - public function initialize() + public function initialize(): void { parent::initialize(); $this->mapAction('stats', \App\Service\Blogs\StatsAction::class, ['method' => ['GET'], 'mapCors' => true]); @@ -47,7 +47,7 @@ Let's define it here: ```php -namespace App\Api\Service\Action\Stats; +namespace App\Service\Blogs; use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Action; @@ -55,12 +55,12 @@ use CakeDC\Api\Service\Action\Action; class StatsAction extends Action { - public function validates() + public function validates(): bool { return true; } - public function execute() + public function execute(): mixed { return [ 'stats' => 'everything good' diff --git a/docs/Documentation/auth.md b/docs/Documentation/auth.md index 208ebd17..dd084e1e 100644 --- a/docs/Documentation/auth.md +++ b/docs/Documentation/auth.md @@ -1,79 +1,62 @@ ## Authentication and Authorization. -Auth system was inspired from cakephp framework auth component, and follow ideas that put into this system. +Authentication and authorization run in the middleware listed in `Api.Middleware` (see [Middlewares](middleware.md)). +The cakephp/authentication plugin identifies the user, and the cakephp/authorization plugin checks the RBAC rules. -IMPORTANT: Auth is configured to ALLOW all API endpoints by default, if you need to enable Auth, please remove -the `allow => '*'` rule from `Auth` configuration key and configure Auth as explained below: +IMPORTANT: access is decided by the `AuthenticationMiddleware` and by the RBAC rules in `config/api_permissions.php`. +A request without an authenticated user is allowed in two cases only: a matching rule has `'bypassAuth' => true`, or the +`allowed` (or `bypassAuth`) value of a matching rule is a callable, a `Rule` object or a `className` rule that returns true. +Such a value is called for every request the rule matches, also without a user: `$user` is then empty and `$role` is the +default role, so a check that must not open the endpoint has to test `$user` itself. A boolean `'allowed' => true` never +allows a request without a user. The shipped `api_permissions.php.default` makes every endpoint public; replace its rule +before production. The `Auth` key of the action configuration +(`allow`, `authorize`, `authenticate`) is not read by the request lifecycle and is deprecated in 14.0: +removing `'allow' => '*'` does not protect anything. ## Auth Configuration -Auth configuration should be defined as part of current Action configuration module. -The default strategy for reading Action configuration described in previous step. +Authentication is built by the class and method named in `Api.Middleware.authentication` (`request` and `method`, +default `CakeDC\Api\ApiInitializer::getAuthenticationService()`). It loads these authenticators: -So global Auth configuration one should put into `Api.Service.default.Action.default.Auth`. +* `Authentication.Session` - the session of the application. +* `CakeDC/Auth.Form` - username and password against the users table. +* `Authentication.Token` - a static token, see below. +* `Authentication.Jwt` - JWT bearer tokens, see below. + +To change them, point `request` and `method` to your own class that returns an `AuthenticationService`. + +Authorization is built by `ApiInitializer::getAuthorizationService()` and uses the rules in `config/api_permissions.php`. + + ### Token authentication + + The `Authentication.Token` authenticator reads the token from the `token` query parameter and matches it against + the `api_token` field of the user. + + The plugin does not check that the request uses HTTPS; enforce HTTPS in the application or the web server. + You should always require HTTPS to use tokens for Auth. + + ### RBAC authorization (`ApiRbac`) + + `ApiRbac` is based on CakeDC Users plugin Simple Rbac Authorize with modification to api structure. + The rules are read from `config/api_permissions.php`, see [Middlewares](middleware.md). -* `allow` - defines list of allowed for current service actions (could be action name, array of names, or ```'*'```). -* `authorize` - defines what authorizes should be loaded to Authorize access. -* `authenticate` - defines authentication strategy. - - Example: - - ```php - 'Auth' => [ - 'allow' => '*', //public access - 'authorize' => [ - 'CakeDC/Api.Crud' => [] - ], - 'authenticate' => [ - 'CakeDC/Api.Token' => [ - 'require_ssl' => false, - ] - ], - ], - ``` - ### TokenAuthenticate - -#### Setup - - TokenAuthenticate default configuration is - ```php - protected $_defaultConfig = [ - //type, can be either querystring or header - 'type' => self::TYPE_QUERYSTRING, - //name to retrieve the api key value from - 'name' => 'token', - //db table where the key is stored - 'table' => 'users', - //db field where the key is stored - 'field' => 'api_token', - //require SSL to pass the token. You should always require SSL to use tokens for Auth - 'require_ssl' => true, - ]; - ``` - - We are using query strings for passing the api_token token. And we require SSL by default. - Note you can override these options, passing settings in Auth configuration for TokenAuthenticate. - - - ### Simple Rbac Authorize. - - Simple Rbac Authorize is based on CakeDC Users plugin Simple Rbac Authorize with modification to api structure. - #### Permission rules syntax - + * Rules are evaluated top-down, first matching rule will apply * Each rule is defined: ```php [ - 'role' => 'REQUIRED_NAME_OF_THE_ROLE_OR_[]_OR_*', - 'version' => 'OPTIONAL_VERSION_USED_OR_[]_OR_*_DEFAULT_NULL', - 'service' => 'REQUIRED_NAME_OF_THE_SERVICE_OR_[]_OR_*' + 'role' => 'OPTIONAL_NAME_OF_THE_ROLE_OR_[]_OR_*', + 'service' => 'REQUIRED_NAME_OF_THE_SERVICE_OR_[]_OR_*', 'action' => 'REQUIRED_NAME_OF_ACTION_OR_[]_OR_*', - 'allowed' => 'OPTIONAL_BOOLEAN_OR_CALLABLE_OR_INSTANCE_OF_RULE_DEFAULT_TRUE' + 'method' => 'OPTIONAL_HTTP_METHOD_OR_[]_OR_*', + 'allowed' => 'OPTIONAL_BOOLEAN_OR_CALLABLE_OR_INSTANCE_OF_RULE_DEFAULT_TRUE', + 'bypassAuth' => 'OPTIONAL_TRUE_ALLOWS_THE_REQUEST_WITHOUT_AUTHENTICATION', ] ``` + * Any other key is compared with the user field of that name. There is no `version` key. * If no rule allowed = true is matched for a given user role and url, default return value will be false - + ### JWT (Json Web Token Authentication). - - * [Example tutorial](Documentation/Auth/jwt.md) \ No newline at end of file + + * [JWT authentication](Auth/jwt.md) diff --git a/docs/Documentation/configuration.md b/docs/Documentation/configuration.md index 332fafd6..4717bcb5 100644 --- a/docs/Documentation/configuration.md +++ b/docs/Documentation/configuration.md @@ -2,8 +2,8 @@ ## Configuration -* Api.defaultVersion - keep default api version (used if route does not contain version). -* Api.useVersioning - enable versions support. Numeric. +* Api.defaultVersion - number of the default version, without the prefix (`1` for `v1`); used when the URL has no version. +* Api.useVersioning - enable versions support. Boolean, default `false`. * Api.versionPrefix - by default version in routes is /v\d+/ Api.ServiceFallback - if defined class name service will loaded using this fallback class if service does not exists. @@ -27,13 +27,14 @@ Now let consider case we have service with defined version number 2. In this cas * one can define default options for any service in the application in `Api.Service.default.options` section. * one can define default options for any service for defined version, and in this case you will user `Api.Service.v2.default.options` section. * one can define options for specific (`articles`) service for defined version in the application in `Api.Service.v2.articles.options` section. +* the default version (`Api.defaultVersion`), and a version without its own service class, also read the unversioned `Api.Service.articles.options`; keys under the version win. All defined options are overridden from up to down in described order. This allow to have common service settings, and overwrite then in bottom level. - * Api.Service.classMap - defines name map, that allows define services action classes with custom location logic. + * `Api.Service..options.classMap` - map of action names to action class names, merged into the service's actions class map. It allows define services action classes with custom location logic. ## Actions configuration. @@ -45,21 +46,29 @@ Lets consider how one can configure options for `IndexAction` of `ArticlesServic Configuration are hierarchical in the next sense: * one can define default options for any action for all services in the application in `Api.Service.default.Action.default` section. -* one can define default options for `index` action for all services in the application in `Api.Service.default.Action.index` section. +* one can define default options for `index` action for all services in the application in `Api.Service.default.Action.Index` section. * one can define options for any action in the specific (`articles`) service in `Api.Service.articles.Action.default` section. -* one can define options for `index` action in the specific (`articles`) service in `Api.Service.articles.Action.index` section. +* one can define options for `index` action in the specific (`articles`) service in `Api.Service.articles.Action.Index` section. Now let consider case we have service with defined version number 1. In this case there are more ways to configure action supported: * one can define default options for any action for all services in the application in `Api.Service.default.Action.default` section. -* one can define default options for `index` action for all services in the application in `Api.Service.default.Action.index` section. +* one can define default options for `index` action for all services in the application in `Api.Service.default.Action.Index` section. * one can define default options for any action for all services for defined version of the application in `Api.Service.v1.default.Action.default` section. -* one can define default options for `index` action for all services for defined version of the application in `Api.Service.v1.default.Action.index` section. -* one can define options for any action in the specific (`articles`) service for defined version in `Api.Service.v1.articles.Action.index` section. -* one can define options for `index` action in the specific (`articles`) service for defined version in `Api.Service.articles.Action.index` section. +* one can define default options for `index` action for all services for defined version of the application in `Api.Service.v1.default.Action.Index` section. +* one can define options for any action in the specific (`articles`) service for defined version in `Api.Service.v1.articles.Action.default` section. +* one can define options for `index` action in the specific (`articles`) service for defined version in `Api.Service.v1.articles.Action.Index` section. +* the default version (`Api.defaultVersion`), and a version without its own service class, also read the unversioned `Api.Service.articles.Action.default` and `Api.Service.articles.Action.Index` sections. -All defined options are merged from up to down in described order. +The action name key is camelized: use `Index`, not `index`. + +All defined options are merged. List values such as `Extension` are joined across all levels. +When the same single-value key is set on several levels, the order of precedence is, highest first: + +* without a version: `.Action.default`, `.Action.`, `default.Action.`, `default.Action.default`. +* with a version: `.default.Action.default`, `.default.Action.`, `..Action.default`, `..Action.`, then the unversioned `` keys (when they are read) and the `default` keys, in the order above. + This allow to configure shared behavior for all actions or for specific subset of actions provided by the services. ## Auth configuration diff --git a/docs/Documentation/crud.md b/docs/Documentation/crud.md index 4bacced6..e139da7f 100644 --- a/docs/Documentation/crud.md +++ b/docs/Documentation/crud.md @@ -33,7 +33,7 @@ CREATE TABLE `posts` ( ### Success request. ```bash -curl -i https://myapi.com/api/blogs?limit=1 +curl -i https://myapi.com/api/blogs?limit=4 ``` ```json @@ -103,7 +103,7 @@ curl -i https://myapi.com/api/blogs/9999 ```json { "status": "error", - "message": "Record not found in table \"blogs\"", + "message": "Record not found in table `blogs`.", "code": 404, "data": null } @@ -154,7 +154,7 @@ curl --data "description=Jorge best blog" https://myapi.com/api/blogs/25 ```json { "status": "error", - "message": "A route matching \"\/blogs\/26\" could not be found.", + "message": "A route matching `\/blogs\/25` could not be found.", "code": 404 } ``` @@ -202,7 +202,7 @@ curl -X DELETE https://myapi.com/api/blogs/9999 ```json { "status": "error", - "message": "Record not found in table \"blogs\"", + "message": "Record not found in table `blogs`.", "code": 404, "data": null } @@ -248,6 +248,9 @@ curl -i https://myapi.com/api/blogs/1/posts ### Failed auth request +A request that no rule of `config/api_permissions.php` allows is answered with code 403. +With the rule of the shipped `api_permissions.php.default` every request is allowed, also with a wrong token. + ```bash curl -i https://myapi.com/api/blogs/1/posts?token=WrongToken ``` @@ -256,7 +259,7 @@ curl -i https://myapi.com/api/blogs/1/posts?token=WrongToken { "status": "error", - "message": "Unauthenticated", + "message": "Forbidden authorization request", "code": 403, "data": null } diff --git a/docs/Documentation/di.md b/docs/Documentation/di.md index 8d0478b1..85b7baf0 100644 --- a/docs/Documentation/di.md +++ b/docs/Documentation/di.md @@ -7,6 +7,8 @@ The CakePHP service container enables you to manage class dependencies for your First of all, needs to load ContainerInjector middleware from App\Application class. ```php +use CakeDC\Api\Middleware\ContainerInjectorMiddleware; + class Application extends BaseApplication { @@ -17,6 +19,9 @@ class Application extends BaseApplication ->add(new ContainerInjectorMiddleware($this->getContainer())) // .... ; + + return $middleware; } +} ``` diff --git a/docs/Documentation/extensions.md b/docs/Documentation/extensions.md index 6e906372..d86b84fa 100644 --- a/docs/Documentation/extensions.md +++ b/docs/Documentation/extensions.md @@ -6,7 +6,7 @@ All actions are decorated by some functionality, attached to their life flow. Su * Cors Purpose - all actions. Purpose to provide access to the API from another domain. -@todo implement configuration from extension config. +Settings: `origin`, `methods`, `headers`, `maxAge`. * CrudAutocompleteList Preparing lists for autocompleters on the client side. @@ -21,11 +21,11 @@ Listen for `include_relations` parameter and if it is present, add related model An association is added only when the current user may access the `index` action of the related service with a GET request, as the permission rules decide; other associations are left out. The related service is the one named after the table class of the association's target (`AuthorsTable` → `authors`), also for an aliased association such as `Writers` with `className` `Authors`; a generic table is named after its database table. Every step of a dotted path is checked, and when no check can be made the association is embedded and a `debug` message is logged with the `api` scope. The check runs through the request's authorization service with the `ApiRbac::TARGET_ATTRIBUTE` request attribute, which names the service and action to check; a custom request policy has to honour that attribute, and so do callables and `Rule` objects that inspect the request, which otherwise see the current action. The same applies to a custom RBAC adapter, set with the `rbac` request attribute or the `adapter` setting of `RbacPolicy`: if it ignores the attribute, it checks the current action, and every requested association is embedded without a check. A `debug` message is logged when the request's `rbac` attribute is not an `ApiRbac`. Set the extension's `checkPermissions` setting to `false` to embed requested associations without this check. * CrudHateoas -Purpose - all CRUD actions. +Purpose - index and view actions. Metadata - `links`. -For each of CRUD actions populate `links` metadata (see metadata section in this document). +For the index and view actions populate `links` metadata (see metadata section in this document). Each action have diferent links associated. They are similar to what we have in baked view pages. -So index action has a link to add page, and edit page has links to view, delete and index. +So index action has links to itself and to add, and view action has links to itself, edit, delete and index. Additionaly if this service has nested services, links to them also will be appended in a similar way. * Filter @@ -33,11 +33,6 @@ Purpose - index action. Listen for parameters named the same as field names and construct conditions. Allows diferent suffixes to field names to specify like or comparissons. @todo discuss structures. -* FilterParameter -Purpose - index action. -Listen for `filters` parameter which describes complex queries as JSON object and construct condition. -@todo discuss structures. - * CursorPaginate Purpose - index action. Listen for `count`, `max_id` or `since_id` params by default, but allow to override it with settings. @@ -54,8 +49,8 @@ Purpose - index action. Listen for `sort` param by default, but allow to override it with settings. Accept sort options as JSON object. Modify query for index action using ORM `orderBy()` method based on `sort`. Where data in sort params are JSON packed object with fields and orders as key and values. Orders can be one of 'asc' or 'desc'. -Invalid JSON is ignored. Entries with an invalid field or a non-string order are skipped. Only the object form is accepted: a JSON list such as `["title"]` or a numeric key is ignored, use `{"title": "asc"}`. -Supports the `sortableFields` setting, see Sort below. +Invalid JSON is ignored. Entries with an invalid field are skipped, and an unknown or non-string order falls back to 'asc'. Only the object form is accepted: a JSON list such as `["title"]` or a numeric key is ignored, use `{"title": "asc"}`. +Supports the `order` and `sortableFields` settings, see Sort below. * Sort Purpose - index action. @@ -66,11 +61,26 @@ An unknown `direction` falls back to 'asc'. Settings: - `sortField` - request param with the sort field. Default `sort`. - `directionField` - request param with the sort direction. Default `direction`. +- `order` - default order. Same format as the ORM `orderBy()` array, for example `['Articles.title' => 'asc']`. When the request has a valid sort, the default order is appended after it as a tie-breaker, and entries for the same field (string keys only) are skipped. Unqualified columns of the action table are qualified with the table alias, so a joined association cannot make them ambiguous; write other fields qualified. When the request has no valid sort, only the default order is used. This value is trusted and is not validated. - `sortableFields` - list of allowed sort fields, for example `['Articles.title', 'Authors.last_name']`. When empty, only columns of the action table are allowed, as `field` or `Alias.field`. Other fields are ignored. An action that is not a CRUD action has no table, so it accepts only fields listed here. Columns the entity hides from output (`$_hidden`, such as password or token columns) are not sortable by default, because the row order would reveal their values; list them here to allow them. Request sort fields are validated. A field is used only when it is a column of the action table that the entity does not hide or, when `sortableFields` is not empty, when it is listed there. Anything else is ignored, so a sort param can never add SQL to the query. Field names must match the column exactly, including case. -`sortableFields` replaces the default allowance rather than extending it. Once it is not empty only the listed fields are accepted, so list the action's own sortable columns as well: +To sort by an associated table field, add the field to `sortableFields`. The associated table must be joined in the main query, as belongsTo and hasOne associations are when contained (for example through CrudRelations). A hasMany association is loaded in a separate query, so its fields cannot be used for sorting. If the request does not load the association (for example a client omits `include_relations`), sorting by its field makes the query fail. + +When a `sortableFields` entry is also a column of the action table, it is qualified with the table alias, so the column wins over a computed select alias with the same name. Give computed select aliases names that are not columns. + +Ignored sort fields and invalid ExtendedSort JSON are logged at `debug` level with the `api` scope, one line per request, so a client whose sort has no effect can be diagnosed. The default `Api.Log` config writes only `error` and `info`; add `debug` to its `levels` to see them. + +Load only one of Sort and ExtendedSort for an action, because both read the `sort` param. + +Do not set `order` for an action that uses CursorPaginate. The default order is applied before the cursor field order and breaks cursor paging. + +`sortableFields` replaces the default allowance rather than extending it. Once it is not empty only the listed fields are accepted, so list the action's own sortable columns as well. + +Extension settings from `Api.Service.default.Action.default` and per-action settings are merged, not replaced: the more general `order` entries come first, and `sortableFields` lists are joined. Set both settings per action. + +Default order and allowed sort fields for the articles index action: ```php 'Api' => [ @@ -80,6 +90,7 @@ Request sort fields are validated. A field is used only when it is a column of t 'Index' => [ 'Extension' => [ 'CakeDC/Api.Sort' => [ + 'order' => ['Articles.title' => 'asc'], 'sortableFields' => ['Articles.title', 'Articles.created', 'Authors.last_name'], ], ], @@ -92,6 +103,14 @@ Request sort fields are validated. A field is used only when it is a column of t The action name key is camelized: use `Index`, not `index`. -To sort by an associated table field, add the field to `sortableFields`. The associated table must be joined in the main query, as belongsTo and hasOne associations are when contained (for example through CrudRelations). A hasMany association is loaded in a separate query, so its fields cannot be used for sorting. +A custom index action gets sorting and pagination when it overrides `getEntitiesQuery()` and returns `getEntities()` from `execute()`. Do not dispatch the `Action.Crud.*` events by hand. -Load only one of Sort and ExtendedSort for an action, because both read the `sort` param. +```php +class ArticlesIndexAction extends CrudIndexAction +{ + protected function getEntitiesQuery(): SelectQuery + { + return $this->getTable()->find('search', search: $this->getData()); + } +} +``` diff --git a/docs/Documentation/installation.md b/docs/Documentation/installation.md index 5645ab13..76b88308 100644 --- a/docs/Documentation/installation.md +++ b/docs/Documentation/installation.md @@ -13,24 +13,39 @@ composer require cakedc/cakephp-api ## Load the Plugin -Ensure the API Plugin is loaded in your config/bootstrap.php file +Load the plugin with the command line: + +``` +bin/cake plugin load CakeDC/Api +``` + +or in your `src/Application.php` file: ```php -Plugin::load('CakeDC/Api', ['bootstrap' => true, 'routes' => true]); +public function bootstrap(): void +{ + parent::bootstrap(); + $this->addPlugin('CakeDC/Api'); +} +``` + +## Create the database tables + +JWT login stores refresh tokens in the `jwt_refresh_tokens` table, and the WebAuthn second factor stores its state in the `auth_store` table. Create both with the plugin migrations. They need [cakephp/migrations](https://github.com/cakephp/migrations) (^4.5 or ^5.0) in your application: + +```bash +bin/cake migrations migrate -p CakeDC/Api ``` +You can skip this step if your API uses neither JWT login nor WebAuthn. + ## Configuration You can configure the api overwriting the api.php, how? we need to create an **api.php** file in the *config* folder. You can copy the existing configuration file under `vendor/cakedc/cakephp-api/config/api.php` and customize it for your application. -Remember to load the new configuration file in `bootstrap.php` - -```php -Plugin::load('CakeDC/Api', ['bootstrap' => false, 'routes' => true]); -Configure::load('api'); -``` +Remember to name the new configuration file in `Api.config` before the plugin is loaded. -CakePHP 4.x configuration loading form Application class: +Configuration loading from the Application class: ```php Configure::write('Api.config', ['api']); @@ -56,15 +71,15 @@ Configure::write('Api.config', ['api' => true, 'api_mw' => false]); $this->addPlugin('CakeDC/Api', ['bootstrap' => true, 'routes' => true]); ``` -## OPTIONAL: User Plugin +## Users Plugin -We rely on CakeDC/Users plugin for Auth, in case you need to define Auth for your API, -ensure *CakeDC/Users* plugin is installed and loaded from your `bootstrap.php`. +We rely on CakeDC/Users plugin for Auth. `cakedc/users` (^17.1) is installed with this plugin. +Load it from your `src/Application.php` when your API authenticates users. ### Configuration and Loading ``` Configure::write('Users.config', ['users']); -Plugin::load('CakeDC/Users', ['bootstrap' => false, 'routes' => true]); +$this->addPlugin('CakeDC/Users'); ``` Check more details about how CakeDC/Users plugin could be configured here: https://github.com/CakeDC/users/blob/master/Docs/Documentation/Configuration.md diff --git a/docs/Documentation/middleware.md b/docs/Documentation/middleware.md index 50e6daaf..6e2bdef7 100644 --- a/docs/Documentation/middleware.md +++ b/docs/Documentation/middleware.md @@ -4,7 +4,7 @@ Middleware defined by plugin: Initial `ApiMiddleware` was splited into parts to allow inject authorization middleware from Authorization plugin. -* ParseApiRequestMiddleware - perform url analyze and creates service instance and store it into request parameters. +* ParseApiRequestMiddleware - perform url analyze and creates service instance and stores it in the `service` request attribute. * ProcessApiRequestMiddleware - perform api request. @@ -13,9 +13,12 @@ Initial `ApiMiddleware` was splited into parts to allow inject authorization mid By default it looks next way: ``` + 'bodyParser' => [ + 'class' => BodyParserMiddleware::class, + ], 'authentication' => [ 'class' => AuthenticationMiddleware::class, - 'request' => CakeDC\Api\ApiInitializer::class, + 'request' => ApiInitializer::class, 'method' => 'getAuthenticationService', ], 'apiParser' => [ @@ -51,6 +54,9 @@ Defined schema allow user to use Authorization plugin both for request authoriza Rbac for authorize middlware setup performed by copy file cakephp-api/config/api_permissions.php.default to config/api_permissions.php and defining needed permissions. -By default it is allowed everything for unauthorized users. +The `.default` file allows every request without authentication; replace its rule before production. +Without `config/api_permissions.php` the built-in rules apply: the public `auth` actions (login, register, social login, +account validation, password reset) need no authentication, role `admin` may do everything, and role `user` may send +GET requests. -A rule applies when all its keys other than `allowed` and `bypassAuth` match; those two then give the result. They are checked after the other keys, wherever they appear in the rule, so a rule always applies only to the roles, services, actions and methods it names. Only `'bypassAuth' => true` allows a request without authentication; with any other value the rule still applies and its `allowed` value decides the result. +A rule applies when all its keys other than `allowed` and `bypassAuth` match; those two then give the result. They are checked after the other keys, wherever they appear in the rule, so a rule always applies only to the roles, services, actions and methods it names. A boolean `allowed` allows a request only when it has an authenticated user, and `'bypassAuth' => true` allows it without one. A callable, a `Rule` object or a `className` rule as the value of `allowed` or `bypassAuth` is called for every request the rule applies to, also for one without a user (`$user` is empty and `$role` is the default role), and its result is final: such a check must test `$user` itself, or it opens the endpoint to everyone. diff --git a/docs/Documentation/overview.md b/docs/Documentation/overview.md index 5640197c..7c2fcb3a 100644 --- a/docs/Documentation/overview.md +++ b/docs/Documentation/overview.md @@ -35,32 +35,32 @@ The filename should follow the same nomenclature. However, the location of the f Service layer contemplates a versioned API if it is enabled by settings. Enabling it allow you to scale your **Services** by versioning them as your applications grows. The benefit of this isn't so obvious when developing your application internally, yet becomes very important if you expose your service as an external API. -The *version* of your **Service** is determined by convention, this being the name of the subdirectory under ```app/Service/```, or in a plugin. For example, if the first version of your ```ExampleService``` were to be "v1", you'd create file ```app/Service/v1/ExampleService.php``` in ```App\Service\v1``` namespace. +The *version* of your **Service** is determined by convention, this being the name of the subdirectory under ```src/Service/```, or in a plugin. For example, if the first version of your ```ExampleService``` were to be "v1", you'd create file ```src/Service/v1/ExampleService.php``` in ```App\Service\v1``` namespace. -You can then create a new version of your **Service** by simply creating a new class under ```app/Service/v2/ExampleService.php```. **Services** may also be loaded from plugins using dot notation. +You can then create a new version of your **Service** by simply creating a new class under ```src/Service/v2/ExampleService.php```. **Services** may also be loaded from plugins using dot notation. ### Routing -Returning back to newly created FooService class. It must have declared ```loadRoutes``` method that defines this service behavior. Inside this method we should not use default Router class, because we should not rewrite current cakephp router states during our service url analyze. Instead api plugin provide ```ApiRouter```. +Returning back to newly created FooService class. It can override the ```loadRoutes``` method that defines this service behavior. Inside this method we should not use default Router class, because we should not rewrite current cakephp router states during our service url analyze. Instead api plugin provide ```ApiRouter```. Imagine we want to have /foo/publish action that should accept HTTP POST requests. In this case we define next ```loadRoutes``` function. ```php - public function loadRoutes() + public function loadRoutes(): void { - ApiRouter::scope('/', $this->routerDefaultOptions(), function (RouteBuilder $routes) { - $routes->extensions($this->_extensions); - $options = [ + $builder = ApiRouter::createRouteBuilder('/', []); + $builder->scope('/', function (RouteBuilder $routes): void { + $routes->setExtensions($this->routeExtensions); + $routes->resources($this->getName(), [ 'map' => [ - 'publish' => ['action' => 'publish', 'method' => 'POST', 'path' => ''], - ] - ]; - $routes->resources($this->name(), $options); + 'publish' => ['action' => 'publish', 'method' => 'POST', 'path' => 'publish'], + ], + ]); }); - } + } ``` ### Action loading and mapping @@ -72,10 +72,10 @@ In this case all actions supposed to located in Action sub-namespace. So if we have ```App\Service\FooService``` service and want to add ```publish``` action then we should create file ```App\Service\Action\FooPublishAction```, where ```Action``` that belongs to namespace ```App\Service\Action``` and class defined is 3 parts: **Foo** is a camelized service name, **Publish** is a camelized action name, and **Action** is a suffix. -Second loading strategy could be achieved used ``` $_actionsClassMap ``` property. It contains map of action names and full class names, eg. +Second loading strategy could be achieved used ``` $actionsClassMap ``` property. It contains map of action names and full class names, eg. ```php - protected $_actionsClassMap = [ + protected array $actionsClassMap = [ 'index' => '\CakeDC\Api\Service\Action\CrudIndexAction', 'view' => '\CakeDC\Api\Service\Action\CrudViewAction', ]; @@ -162,10 +162,12 @@ Suported next renderers: * JSend JSON object in JSend format. This is default renderer that configured in config/api.php configuration file. * Raw - returns data as it is provided. * Xml - format result data as xml. +* File - sends a file from disk. +* Flysystem - sends a file from a league/flysystem 3 filesystem. ### JSend Response structure -Each JSend object on top level has result and data items. +Each JSend object on top level has status and data items. Additionally all metadata appended here too. ### Exceptions @@ -175,10 +177,8 @@ Additionally all metadata appended here too. Links is a information how current api endpoint related with other endpoints. If we will talk about crud actions there defined next links: -* index - have links to add action. -* add - have links to index action. -* edit - have links to edit, delete and index actions. -* view - have links to edit, delete and index actions. Have links to index action of all nested services. +* index - have links to itself and to add action. +* view - have links to itself, edit, delete and index actions. Have links to index action of all nested services. #### Pagination/ @@ -188,7 +188,7 @@ By default the **Service** automatically handles many of the common errors in a * **401 Unauthorized:** If authentication is required but fails for the request. * **403 Forbidden:** If a private method is requested or the action is blacklisted. -* **404 Not Found:** If the method is not defined on the **Service** class. -* **405 Method Not Allowed:** If an invalid HTTP method is used for the request. +* **404 Not Found:** If no route or record matches, also for a wrong HTTP method. +* **422 Unprocessable Entity:** If the action input fails validation. * **409 Conflict:** If required arguments are missing from the request. * **500 Internal Server Error:** If an error is thrown and not handled by the **Service**. diff --git a/docs/Documentation/plans.md b/docs/Documentation/plans.md index b0b31778..e95eb111 100644 --- a/docs/Documentation/plans.md +++ b/docs/Documentation/plans.md @@ -12,11 +12,12 @@ * Index query since-limit Pagination support (twitter style) * Self documentation using OPTIONS service method. * HATEOAS partially done support. -* Raw, JSON (plain and JSend), XML Rendering of response output. Custom renderers supported +* Raw, JSON (plain and JSend), XML, File and Flysystem Rendering of response output. Custom renderers supported * CORS Cross-Origin Resource Sharing (extension provided) * Any action could be library driven or execute custom user code stored in separate class. -* Auth done as custom Autenticate+Authorize system based on cakephp AuthComponent but for auth Services and Actions. +* Auth through the cakephp/authentication and cakephp/authorization middleware, with RBAC rules. +* Bulk add, edit and delete with the collection actions. ## Extensions @@ -26,7 +27,6 @@ * CrudRelations * Nested * Filter -* FilterParameter * CursorPaginate * Paginate * ExtendedSort @@ -43,9 +43,7 @@ # LIST DESIRED FEATURES -* Bulk Inserts * HATEOAS (we already have EntityDescriptionInterface and EntityLabelsInterface). * Rate Limiting and throttling extension -* File Storage api -* Migrate to middleware system +* File Storage api (the File and Flysystem renderers already send files) diff --git a/docs/Documentation/renderers.md b/docs/Documentation/renderers.md index 40229139..aeece184 100644 --- a/docs/Documentation/renderers.md +++ b/docs/Documentation/renderers.md @@ -3,11 +3,13 @@ Renderers What are the renderers? -There we have four renderers available for your API. They are: +There we have six renderers available for your API. They are: * **[JSend](Renderers/jsend.md)**: JSend is a specification that lays down some rules for how JSON responses from web servers should be formatted. JSend focuses on application-level (as opposed to protocol- or transport-level) messaging which makes it ideal for use in REST-style applications and APIs. You can see more details [here](https://labs.omniti.com/labs/jsend) -* **[Json](Renderers/json.md)**: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers. In this [link](http://json.org/) you can see more details. -* **[Xml](Renderers/xml.md)**: It is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. [Here](https://en.wikipedia.org/wiki/XML) you can check more details -* **[Raw](Renderers/raw.md)**: This is an unformatted response. +* **Json**: JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers. In this [link](http://json.org/) you can see more details. +* **Xml**: It is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. [Here](https://en.wikipedia.org/wiki/XML) you can check more details +* **Raw**: This is an unformatted response. +* **File**: Sends a file from disk. +* **Flysystem**: Sends a file from a league/flysystem 3 filesystem. -Above you saw what are the available renderers, then you can click in the links to see how they works. +Above you saw what are the available renderers, then you can click in the JSend link to see how it works. diff --git a/docs/Documentation/roadmap.md b/docs/Documentation/roadmap.md new file mode 100644 index 00000000..c6d89f57 --- /dev/null +++ b/docs/Documentation/roadmap.md @@ -0,0 +1,29 @@ +Roadmap +======= + +This page lists work that is known but not done yet. Items for 14.1 can ship in a minor release; items for 15.0 break backward compatibility. + +14.1 +---- + +### Two-factor authentication + +- **Meaning of `hasRegistered2fa`.** In the `auth/two_factor_auth` response, `hasRegistered2fa` is true only when the user has registered both OTP and WebAuthn. Since 13.0.1 a user can enroll only one factor through the plugin, so it is false for nearly every user. Decide whether it should mean "any factor", then document it and add a test for the single-factor case. +- **Allowed WebAuthn origins.** A WebAuthn response is accepted from the relying party id and from every HTTPS subdomain of it. Add an `Api.Webauthn2fa.` setting that lists the allowed origins and pass it to the library's allowed-origins check. The check used today is deprecated in web-auth/webauthn-lib 5.2 and removed in 6.0, and a list of origins also allows a plain `http://localhost` origin in development. + +### Tests + +- Cover the `WrongPasswordException` branch of `ResetPasswordAction::changePassword()`. +- `ResetPasswordAction` catches `UserAlreadyActiveException`, which the reset flow does not seem to throw. Confirm this, then remove the catch or cover it with a test. + +### Development tools + +- PHPStan runs at level 5 with no errors. Level 6 reports about 430 errors, almost all of them missing iterable value types in docblocks. Fix them and raise the level. +- Decide whether Rector stays a CI gate. + +15.0 +---- + +- Add native parameter and return types to the remaining public and protected signatures. The type sniffs in `phpcs.xml` and the type rules in `rector.php` are off until then, because adding them breaks app subclasses. +- `OptionsHandlerExtension::onDispatch()` always returns null since 14.0; declare it `void`. +- Remove the auth layer deprecated in 14.0: `CakeDC\Api\Service\Auth\Auth`, `CakeDC\Api\Service\Auth\AuthenticateTrait`, `CakeDC\Api\Service\Action\Extension\AuthenticationExtension`, and `Action::$Auth`, `Action::initializeAuth()` and `Action::authConfig()`. See [Upgrading](upgrading.md#deprecated-in-140). diff --git a/docs/Documentation/services.md b/docs/Documentation/services.md index ddd5525d..d217530d 100644 --- a/docs/Documentation/services.md +++ b/docs/Documentation/services.md @@ -9,13 +9,13 @@ Fallback service defined by setting Api.ServiceFallback and by default this is \ ## Define routes -### Define using `$_actionsClassMap` +### Define using `$actionsClassMap` -Most trival way to define custom action namespace for CRUD action is using of $_actionsClassMap that defines map between action type and namespace. +Most trival way to define custom action namespace for CRUD action is using of $actionsClassMap that defines map between action type and namespace. ``` - protected $_actionsClassMap = [ - 'index' => '\App\Service\Blogs\IndexAction', + protected array $actionsClassMap = [ + 'index' => \App\Service\Blogs\IndexAction::class, ]; ``` @@ -23,23 +23,23 @@ Redefining this variable it is easy to disable default CRUD actions like DELETE. ### Define routes with `mapAction`. -More complex routes defined with mapAction method. that accept action's alias, action class name, and router config. Most logical way to define routes is Service::intialize method. +More complex routes defined with mapAction method. that accept action's alias, action class name, and router config. Most logical way to define routes is Service::initialize method. -Lets define /posts/:id/:flagtype route that accept POST request. +Lets define /posts/{id}/{flag} route that accept POST request. ``` use App\Posts\FlagAction; ... - public function initialize() + public function initialize(): void { parent::initialize(); $this->mapAction('flag', FlagAction::class, [ 'method' => ['POST'], 'mapCors' => true, - 'path' => ':id/:flag' + 'path' => '{id}/{flag}' ]); } ``` @@ -49,7 +49,7 @@ In some cases you want to define route variable type. What if we want accept onl In this case we should define variable regex and pass it to router definition. ``` - public function routerDefaultOptions() + public function routerDefaultOptions(): array { $options = parent::routerDefaultOptions(); $append = [ @@ -66,19 +66,32 @@ In this case we should define variable regex and pass it to router definition. Defining router this way requests with other values in flag field would be completely rejected and action execution would not happen. +The router config of `mapAction()` can also set the options of that one route: `patterns` (regular expressions of the +route variables), `pass` (the variables passed to the action, instead of `['id']`) and `name` (the route name). Any other +key is a route default, read from the parsed route like the route variables. + +``` + $this->mapAction('flag', FlagAction::class, [ + 'method' => ['POST'], + 'path' => '{id}/{flag}', + 'patterns' => ['flag' => 'spam|inappropriate'], + 'name' => 'postsFlag', + ]); +``` + ## Accessing router variables values from action. Access to variables defined in action router very simple. -First of all in actions that has :id param, most obsious way is get this value from `$_id` property. +First of all in actions that has `{id}` param, most obvious way is `getId()` (or the `$id` property) of a `CrudAction`. In case we need read additional parameters from parsed router he should read then from parsed route data available from actions using `getRoute()` method. So if we want read flag type in action we could do next: ``` - public function execute() + public function execute(): mixed { $flag = Hash::get($this->getRoute(), 'flag'); ... diff --git a/docs/Documentation/transformers.md b/docs/Documentation/transformers.md index 19bf41f5..d936049d 100644 --- a/docs/Documentation/transformers.md +++ b/docs/Documentation/transformers.md @@ -51,9 +51,9 @@ use CakeDC\Api\Service\Action\CrudAction; class ViewAction extends CrudAction { - public function execute() + public function execute(): mixed { - $user = $this->_getEntity($this->_id); + $user = $this->getEntity($this->id); return $this->transform($user, UserTransformer::class); } @@ -69,19 +69,21 @@ The `transform()` method automatically handles collections: namespace App\Service\AppUsers; use App\Transformer\UserTransformer; -use CakeDC\Api\Service\Action\CrudIndexAction; +use CakeDC\Api\Service\Action\CrudAction; -class IndexAction extends CrudIndexAction +class IndexAction extends CrudAction { - public function execute() + public function execute(): mixed { - $users = $this->_getEntities(); + $users = $this->getEntities(); return $this->transform($users, UserTransformer::class); } } ``` +Extend `CrudAction`, not `CrudIndexAction`: `CrudIndexAction::execute()` must return a `ResultSetInterface`, so a subclass cannot return the transformed array. + ## Helper Methods ### `get($data, $key, $default = null)` @@ -306,9 +308,9 @@ use CakeDC\Api\Service\Action\CrudAction; class ViewAction extends CrudAction { - public function execute() + public function execute(): mixed { - $user = $this->_getEntity($this->_id); + $user = $this->getEntity($this->id); $identity = $this->getIdentity(); $transformer = new SecureUserTransformer(); @@ -324,29 +326,29 @@ class ViewAction extends CrudAction ## Paginated Results -The `transform()` method automatically preserves pagination metadata: +The Paginate extension adds `pagination` to the result payload, not to the value that `getEntities()` returns, so it is kept when the action returns transformed rows: ```php [...], 'pagination' => [...]] - $result = $this->_getEntities(); + // the Paginate extension limits the query and sets `pagination` on the result + $result = $this->getEntities(); - // transform() preserves pagination structure return $this->transform($result, UserTransformer::class); } } ``` +An array that already has the `data` and `pagination` keys is kept in that shape: `transform()` transforms the rows under `data` only. + ## Best Practices 1. **Keep transformers focused**: Each transformer should handle one entity type @@ -363,7 +365,7 @@ All transformers must implement `TransformerInterface`: ```php interface TransformerInterface { - public function transform($data): array; + public function transform(mixed $data): array; } ``` diff --git a/docs/Documentation/upgrading.md b/docs/Documentation/upgrading.md new file mode 100644 index 00000000..276f35a1 --- /dev/null +++ b/docs/Documentation/upgrading.md @@ -0,0 +1,347 @@ +Upgrading to 14.x +================= + +This page lists what an application must check or change when it upgrades to 14.x. The full list of changes is in the [CHANGELOG](../../CHANGELOG.md). + +- From 13.x (13.0.0 or 13.0.1): read [Upgrading from 13.x](#upgrading-from-13x). +- From 12.x: read [Upgrading from 12.x](#upgrading-from-12x) first, then [Upgrading from 13.x](#upgrading-from-13x). Both apply. + +```bash +composer require cakedc/cakephp-api:^14.0 +``` + +Upgrading from 13.x +------------------- + +14.x supports the same CakePHP (5.4 or newer) and PHP (8.3 or newer) versions as 13.x. + +### Requirements + +- `cakedc/users` 17.1 or newer (13.x allowed 17.0). `cakephp/authentication` 4.2 or newer is now required directly; 13.x got it through `cakedc/users`. +- `firebase/php-jwt` 7. Version 6 is no longer allowed. +- `crustum/cakephp-attribute-resolver` 1.0.3 or newer (13.x allowed 1.0.0). Older versions can read the same attribute twice, which doubles the path of an `#[ApiScope]`. +- `lcobucci/jwt` and `lcobucci/clock` are no longer required. The plugin signs its JWT tokens with `firebase/php-jwt`, which already verified them. The tokens are the same, byte for byte, and tokens issued before the upgrade stay valid, so clients notice nothing. Two things can concern your code: + - If it uses `Lcobucci\JWT` or `lcobucci/clock` itself, for example in an override of `generateAccessToken()` or `generateRefreshToken()`, add the package to your own `composer.json`. `lcobucci/clock` 3 can now be installed, which the plugin's `<2.3.0` limit prevented. + - A JWT secret shorter than 64 bytes is still refused when a token is issued, but with an `InvalidArgumentException`. A `catch` of `Lcobucci\JWT\Signer\InvalidKeyProvided` no longer matches; a `catch` of `InvalidArgumentException` still does. + +### Removed classes + +| Removed | Use instead | +| --- | --- | +| `CakeDC\Api\Plugin` | `CakeDC\Api\ApiPlugin`. `addPlugin('CakeDC/Api')` already loads `ApiPlugin`, so only code that names the old class changes. | +| `CakeDC\Api\Middleware\RequestHandlerMiddleware` | `Cake\Http\Middleware\BodyParserMiddleware`, which it only extended. Update `Api.Middleware` if your config lists the old class; the plugin's own `config/api.php` already uses `BodyParserMiddleware`. | + +The [Rector set](#automated-upgrade-with-rector) replaces both classes in your code. + +### Members with a pre-13.0 name now fail + +13.0.0 dropped the leading underscore from protected members of the plugin classes, see [Renamed protected members](#renamed-protected-members). A subclass that still declares an old name, such as `_getEntitiesQuery()` or `$_table`, is never called or read in 13.x, so for example a query scope silently stops applying. + +Since 14.0 the constructors of actions, services, extensions, renderers and parsers throw a `CakeException` that lists the members of your classes that still override an old name. Rename them by hand or with the [Rector set](#automated-upgrade-with-rector). + +Where to look for the message: for an action or an action extension it is the API answer, an error with code 500. For a service, a service extension, a renderer or a parser the service cannot be built, so the exception goes to the error handling of your application: the error log, and the error page in debug mode. + +- A member is reported when the plugin class that your class extends has the new name, or when a plugin trait that your class uses has it. So `_getEntitiesQuery()` is reported in a subclass of `CrudAction`, also when it comes from a trait of your application, and `_sortField()` is reported in an extension that uses `SortableTrait`. +- Private members are not reported, and neither are old names that this plugin code does not have. An action that extends `Action` can therefore use the `ReCaptchaTrait` of cakedc/auth or cakedc/users, which still declare `_getReCaptchaInstance()`. +- Classes of the other kinds are not checked. For example, an override of `ApiRbac::_matchPermission()`, `ApiConfigProvider::_loadPermissions()`, `ParseApiRequestMiddleware::_matchRequest()`, or of a member of `ConfigReader`, `ServiceLocator`, `ServiceRegistry`, the extension registries, `Result`, `Auth` or `IntegrationTestCase` is still silently unused. Check every class of the list below that is not an action, service, extension, renderer or parser by hand. +- If the check refuses a class you cannot change, for example a class of another package, set `Api.legacyMemberGuard` to the boolean `false` in the configuration of your application (`config/app.php`, `Application::bootstrap()` or a file listed in `Api.config`). That turns the check off for every class. Any other value, such as the string `'false'` from an environment variable, leaves it on. + +### Changed signatures + +| Member | Change | +| :----- | :----- | +| `OtpVerifyGetAction::onVerifyGetSecret()` | `onVerifyGetSecret($user): string`. The parameter is no longer typed `array`, because the identity is an entity; an override that types `$user` as `array` stops PHP with a fatal error. | +| `JwtRefreshAction::$payload` | An array, not an object. This changed in 13.0.1, so only an upgrade from 13.0.0 or 12.x sees it. | +| `SecondFactorTrait::hasVerifiedOtp()`, `SecondFactorTrait::hasWebauthnCredential()` | The parameter is typed `EntityInterface\|array\|null`. A call with an identity of another type stops with a `TypeError`. | + +### Deprecated in 14.0 + +These still work in 14.x and will be removed in 15.0.0. They are left over from the auth layer that cakephp/authentication replaced in 10.0. + +| Deprecated | Use instead | +| --- | --- | +| `CakeDC\Api\Service\Auth\Auth`, `Action::$Auth`, `Action::initializeAuth()`, `Action::authConfig()` | The `AuthenticationMiddleware` in `Api.Middleware` and the RBAC rules in `api_permissions.php`. | +| `CakeDC\Api\Service\Auth\AuthenticateTrait` | `Action::getIdentity()`, or the request's `identity` attribute. | +| `CakeDC\Api\Service\Action\Extension\AuthenticationExtension` | The `AuthenticationMiddleware`. Enabling the extension now raises a deprecation warning. | + +`$this->Auth->allow(...)` in an action has never controlled access: nothing reads the allow list. An endpoint is public only through a rule in `api_permissions.php`: one with `'bypassAuth' => true`, or one whose `allowed` value is a callable or a `Rule` that returns true without checking the user. So you can delete these calls. The plugin's own actions no longer make them. + +`LoginAction` now reads the identity with `Action::getIdentity()`, from the `identity` attribute of the request, and no longer through `$this->Auth`. An `identityAttribute` that an `authConfig()` override sets no longer applies to the login. + +The plugin's `config/api.php` changed in the same area. None of these settings was ever read, so removing them from your own configuration changes nothing: + +- `Api.Jwt.enabled` is removed. The JWT actions (`jwt_login`, `jwt_refresh`) and the JWT authenticator are always registered; the rules in `config/api_permissions.php` decide who may call them. +- `require_ssl`, under the `Auth` settings of the default action (`authenticate` > `CakeDC/Api.Token`), is removed. The plugin has no HTTPS check; enforce HTTPS in your application or web server. +- The comment that called `'allow' => '*'` in those `Auth` settings the switch for public access is corrected. Removing that line secures nothing: access is decided by the authentication middleware and by the rules in `config/api_permissions.php`. Check that file if you relied on the comment. + +### Sort and ExtendedSort + +- The new `order` setting gives a default order. It is appended after the request sort as a tie-breaker. See [Extensions](extensions.md). +- Ignored sort fields and invalid ExtendedSort JSON are logged at `debug` level with the `api` scope. +- An ExtendedSort entry with an order that is not a string now sorts ascending. 13.x skipped the entry. +- `SortableTrait` has the new protected methods `order()`, `logIgnoredSort()`, `logValue()` and `ignoredSortField()`. A subclass of `SortExtension` or `ExtendedSortExtension` that already declares a method with one of these names must give it a compatible signature, or rename it. + +### JWT and two-factor authentication + +- `Api.Jwt.RefreshToken.maxSessionLifetime` (seconds, default `null` = unlimited) is new. It ends a session that long after login or after completing the second factor, however often it is refreshed. Refresh tokens issued by 13.x or older carry no `auth_time` claim, so they are refused once that setting is on. Set it to `null`, a positive integer or a string of digits. Any other value except `false`, such as `0` or a negative number, does not mean unlimited: every refresh then fails with an `InvalidArgumentException`. +- A failed WebAuthn verification now returns code 401 (`webauthn2fa_auth`) or 400 (`webauthn2fa_register`) with a generic message, instead of code 500 with the library's reason. Clients that matched messages such as `Invalid signature` should check the code instead. +- WebAuthn registration and authentication options need a bearer token and are answered with code 400 without one. +- WebAuthn no longer offers the non-standard `Ed256` and `Ed512` algorithms; `EdDSA` (Ed25519) is offered instead. +- A missing or non-scalar `code` in `otp_verify_check` is an invalid code, not an HTTP 500. + +### WebAuthn with web-auth/webauthn-lib 5 + +Applications that use the WebAuthn endpoints install the new library version: + +```bash +composer require web-auth/webauthn-lib:^5.3.13 +``` + +Remove any `policy.advisories` or `audit.ignore` entry your `composer.json` has for `web-auth/webauthn-lib` or `web-auth/metadata-service`; it is no longer needed. + +What stays the same: + +- Registered keys keep working. Stored credentials are read as they are. +- The endpoints, and the JSON that clients receive and send. Responses in standard base64 are still accepted, and the relying party name is still the `appName` setting of the domain. +- Going back to 13.x: credentials saved by 14.x are written in a form that 13.x reads. + +What changes: + +- A registration or login that was started before the deploy must be started again. Between the two requests only the challenge is stored now, not a serialized options object. +- A response sent from a cross-origin frame (one that carries `topOrigin`) is refused. +- A domain without an `Api.Webauthn2fa.` entry is answered with code 400, "WebAuthn is not configured for this domain". +- `cakedc/users` 17.1 or newer is required. It uses the same `web-auth/webauthn-lib` version, so its WebAuthn pages and the WebAuthn endpoints of this plugin work in the same application. `cakedc/users` 17.0 was written for `web-auth/webauthn-lib` 4.x. + +If your application extends the WebAuthn classes of the plugin: + +| Class or method | Change | +| :-------------- | :----- | +| `CakeDC\Api\Webauthn\PublicKeyCredentialLoader` | Removed. `BaseAdapter::loadPublicKeyCredential()` reads the client response | +| `BaseAdapter::createPublicKeyCredentialLoader()` | Removed. Use `getSerializer()` and `getCeremonyStepManagerFactory()` | +| `RegisterAdapter::verifyResponse()`, `AuthenticateAdapter::verifyResponse()` | Return a `Webauthn\CredentialRecord` instead of a `PublicKeyCredentialSource` | +| `UserCredentialSourceRepository` | No longer implements `Webauthn\PublicKeyCredentialSourceRepository`, which the library removed. `findOneByCredentialId()`, `findAllForUserEntity()` and `saveCredentialSource()` work with `CredentialRecord` | +| `Webauthn2faRegisterOptionsAction::execute()`, `Webauthn2faAuthOptionsAction::execute()` | Return `array`, from `BaseAdapter::getOptionsData()` | +| Auth store entries `registerOptions`, `authenticateOptions` | Replaced by `registerChallenge` and `authenticateChallenge` | +| `BaseAdapter::saveStore()`, `readStore()`, `deleteStore()` | For a request without a bearer token: `saveStore()` throws a `BadRequestException`, `readStore()` returns a new, empty entity, and `deleteStore()` returns `false` | +| `UserCredentialSourceRepository::__construct()` | Takes the WebAuthn serializer as an optional fourth argument | + +### Versioning + +With `useVersioning`, a version or URL without its own service class is now served by the unversioned service class of the application before `FallbackService`. In 13.x such a request, for example `/api/v2/articles`, reached `FallbackService`, so the default CRUD actions of the table were exposed instead of the actions of your `ArticlesService`. With `Api.defaultVersion` set, a URL without a version now reports that version and gets its `Api.Service` options. + +Options are read as follows: + +- Two kinds of version read the unversioned `Api.Service.` keys together with the keys under the version (`Api.Service.v1.` and `Api.Service.v1.default`): the default version, and a version that has no service class of its own for the service, which the unversioned class serves. So an option set for the service, such as an extension that scopes the query, cannot be skipped by asking for another version number. On a conflict the keys under the version win, also `Api.Service.v1.default` over an unversioned key of the service. Lists differ by level: + - In action options (`Action.*`), list values are joined, not replaced: `sortableFields` and `Extension` lists under both keys add up. + - In service `options`, a key under the version replaces the unversioned key whole, an `Extension` list included. Repeat under the version the service extensions that must keep running. +- A version with its own service class, such as `Service/v2/ArticlesService`, reads only the keys under its version and `Api.Service.default`, unless it is the default version. + +This changes three cases against 13.x; check them if your configuration has keys both under `Api.Service.` and under a version: + +| URL | 13.x read | 14.x reads | +| --- | --- | --- | +| Without a version, with `Api.defaultVersion` set: `/api/articles` | Only the unversioned keys | The unversioned keys and the keys of the default version | +| Names the default version: `/api/v1/articles` | Only the keys of that version | The keys of that version and the unversioned keys | +| Names a version without its own service class: `/api/v7/articles` | Only the keys of that version, and `FallbackService` served it | The keys of that version and the unversioned keys | + +For the last two cases, an unversioned setting that loosens a check, such as `checkPermissions => false` for CrudRelations or a longer `sortableFields` list, now also applies to those URLs. + +### Other behaviour changes + +- `RegisterAction` dispatches `Users.Global.afterRegister` after saving the user. It used to dispatch `Users.Global.beforeRegister` a second time; listeners that relied on that second call must listen to `Users.Global.afterRegister`. +- `FileRenderer` answers 404, not 400, for a missing file. +- Paginate and CursorPaginate: a `limit` or `count` below 1 falls back to the configured maximum, and a `page` below 1 to the first page. +- A role that is not a string, such as a role from an integer column, is matched as its string form instead of failing with a `TypeError`. A role mapped to an enum is matched by the value of its case. Any other role, such as an array, is denied and logged as a warning; it does not fall back to `default_role`. +- `OptionsHandlerExtension` sets its result on the event; its listener returns null. +- A service that cannot be built, for example because of a wrong setting or a missing extension class, is no longer answered with an empty HTTP 400. The exception is passed on to the error handling of your application, which logs it and answers with a 500. An `UnauthenticatedException` thrown before the service is built is still answered with an empty HTTP 400. +- Attribute routes: `patterns`, `pass`, `name` and `defaults` of `#[ApiRoute]` and the verb attributes, and `patterns` and `defaults` of `#[ApiScope]`, were ignored in 13.x and now take effect. A route with a pattern no longer matches URLs that the pattern excludes. +- An action that has a transformer and returns an empty list now answers with an empty list. 13.x passed the empty array to the transformer as one item. + +### Optional packages + +| Package | Change | +| --- | --- | +| `league/flysystem` | Version 3 (^3.35.3) instead of 1. The result `filesystem` must be a `League\Flysystem\FilesystemOperator`, `FlysystemRenderer::deliverAsset()` takes the filesystem and the path, and `getFile()` is removed. Storage errors other than a missing file now produce an error response instead of a 404. | +| `robthree/twofactorauth` | Version 3 (^3.0.1) instead of 1. `OneTimePasswordAuthenticator.qrcodeprovider` must not be null, or every OTP action fails; the `cakedc/users` default config sets one. `endroid/qr-code` 5 and 6 are supported. | +| `web-auth/webauthn-lib` | Version 5 (^5.3.13) instead of 4.x. It has no open security advisory, and it brings `symfony/serializer`, `symfony/property-info` and `symfony/property-access`. See [WebAuthn with web-auth/webauthn-lib 5](#webauthn-with-web-authwebauthn-lib-5). | +| `google/recaptcha` | ^1.3 or ^2.1. A missing or non-string response token now fails validation. | +| `cakephp/migrations` | Needed to run the plugin migrations, ^4.5 or ^5.0. | + +Composer `conflict` rules block versions outside these ranges. + +Upgrading from 12.x +------------------- + +The changes in this section shipped in 13.0.0 and 13.0.1. After them, apply [Upgrading from 13.x](#upgrading-from-13x). + +### Automated upgrade with Rector + +The plugin ships a [Rector](https://getrector.com) set that does the mechanical part of this upgrade in your application code: + +- It renames the members listed under [Renamed protected members](#renamed-protected-members), except those of `CachedApiRbac`, in your subclasses, in their `parent::`, `$this->`, `self::` and `static::` calls, and in calls on variables whose type Rector knows. +- It replaces the removed `CakeDC\Api\Plugin` and `CakeDC\Api\Middleware\RequestHandlerMiddleware` classes. +- It adds the native return types that overrides now need, and the types of redeclared properties. + +Install 14.x first, so that Rector reads the new signatures, and Rector 2: + +```bash +composer require cakedc/cakephp-api:^14.0 +composer require --dev rector/rector:^2.6 +``` + +Add the set to the `rector.php` of your application: + +```php +use Rector\Config\RectorConfig; + +return RectorConfig::configure() + ->withPaths([__DIR__ . '/src', __DIR__ . '/tests']) + ->withSets([__DIR__ . '/vendor/cakedc/cakephp-api/config/rector/cakephp-api-13.php']); +``` + +Run `vendor/bin/rector process --dry-run`, review the diff, then run `vendor/bin/rector process`. Added types are written fully qualified, such as `\Cake\Datasource\ResultSetInterface`; add `->withImportNames()` to the configuration, or run phpcbf, to import them. + +The set does not change: + +- calls on variables whose type Rector cannot infer, such as `$action->_getEntitiesQuery()` on an untyped `$action`; the `CakeException` described under [Members with a pre-13.0 name now fail](#members-with-a-pre-130-name-now-fail) still reports overrides with an old name; +- class names written as strings, for example in `Api.Middleware`; +- the configuration and behaviour changes described in the rest of this page. + +### Requirements + +- PHP 8.3 or newer (12.x required 8.2). +- CakePHP 5.4 or newer (12.x required 5.1). +- `cakedc/users` 17.1 or newer (12.x required 16) and `cakephp/authentication` 4.2 or newer (12.x got 3.x through `cakedc/users` 16). + +### Renamed protected members + +Protected (and a few public) methods and properties of the plugin classes lost their leading underscore: `_getEntitiesQuery()` is now `getEntitiesQuery()`, `$_table` is now `$table`, and so on. Nothing else about them changed. + +Rename the members your subclasses override or set. This matters most for hooks such as `getEntitiesQuery()`: an override that keeps the old name is never called, so for example a query scope stops applying. + +| Class | Members whose leading `_` was dropped | +| :---- | :---- | +| `CakeDC\Api\Middleware\ParseApiRequestMiddleware` | `_matchRequest()` | +| `CakeDC\Api\Rbac\ApiRbac` | `_matchPermission()`, `_terminalKeysLast()`, `_matchOrAsterisk()`, `_camelizeByChars()`, `_startsWith()` | +| `CakeDC\Api\Rbac\CachedApiRbac` | `_loadPermissionsMap()`, `_cacheKey()`, `_keyData()`, `_isIndexable()`, `_isRefused()`, `_matchesAnyService()` (12.0.2 and 12.0.3 only) | +| `CakeDC\Api\Rbac\Permissions\ApiConfigProvider` | `_loadPermissions()` | +| `CakeDC\Api\Service\Action\Action` | `$_service`, `$_route`, `$_name`, `_executeAction()`, `_loadExtensions()`, `_initializeAuth()`, `_authConfig()` | +| `CakeDC\Api\Service\Action\Auth\JwtLoginAction` | `_afterIdentifyUser()` | +| `CakeDC\Api\Service\Action\Auth\LoginAction` | `$_identifiedField`, `$_passwordField`, `_afterIdentifyUser()`, `_authConfig()` | +| `CakeDC\Api\Service\Action\Auth\RegisterAction` | `_afterRegister()`, `_authConfig()`, `_registerOptions()` | +| `CakeDC\Api\Service\Action\Auth\ResetPasswordAction` | `_changePassword()`, `_authConfig()` | +| `CakeDC\Api\Service\Action\Auth\ResetPasswordRequestAction` | `_authConfig()` | +| `CakeDC\Api\Service\Action\Auth\SecondFactorTrait` (`OtpVerifyAction`, `TwoFactorAuthAction`, `Webauthn2faRegisterAction`, `Webauthn2faRegisterOptionsAction`) | `_hasVerifiedOtp()`, `_hasWebauthnCredential()`, `_refuseEnrollmentIf()` (12.0.2 and 12.0.3 only) | +| `CakeDC\Api\Service\Action\Auth\SocialLoginAction` | `_authConfig()` | +| `CakeDC\Api\Service\Action\Auth\ValidateAccountAction` | `_authConfig()` | +| `CakeDC\Api\Service\Action\Auth\ValidateAccountRequestAction` | `_authConfig()` | +| `CakeDC\Api\Service\Action\Collection\CollectionAction` | `_validateMany()`, `_saveMany()`, `_newEntities()`, `_validateDataIsArray()` | +| `CakeDC\Api\Service\Action\Collection\DeleteAction` | `_deleteMany()` | +| `CakeDC\Api\Service\Action\CrudAction` | `$_table`, `$_id`, `$_idName`, `$_service`, `$_parentId`, `$_parentIdName`, `$_finder`, `_newEntity()`, `_patchEntity()`, `_getEntities()`, `_getEntitiesQuery()`, `_getEntity()`, `_getEntityQuery()`, `_buildViewCondition()`, `_save()`, `_describe()` | +| `CakeDC\Api\Service\Action\Extension\Auth\UserFormattingExtension` | `_userCleanup()` | +| `CakeDC\Api\Service\Action\Extension\CrudAutocompleteListExtension` | `_autocompleteList()` | +| `CakeDC\Api\Service\Action\Extension\CrudHateoasExtension` | `$_reverseRouter`, `_buildIndexLinks()`, `_buildViewLinks()` | +| `CakeDC\Api\Service\Action\Extension\CrudRelationsExtension` | `_includeAssociations()`, `_includeDirectAssociations()`, `_attachAssociations()`, `_isRelationAccessible()`, `_relatedServiceName()` | +| `CakeDC\Api\Service\Action\Extension\CursorPaginateExtension` | `$_reverseRouter`, `_sinceId()`, `_maxId()`, `_count()` | +| `CakeDC\Api\Service\Action\Extension\Extension` | `$_registry` | +| `CakeDC\Api\Service\Action\Extension\PaginateExtension` | `_page()`, `_limit()` | +| `CakeDC\Api\Service\Action\Extension\SortableTrait` (`SortExtension`, `ExtendedSortExtension`) | `_sortField()`, `_qualifyField()`, `_sortDirection()` | +| `CakeDC\Api\Service\Action\ExtensionRegistry` | `$_action` | +| `CakeDC\Api\Service\Action\Result` | `$_code`, `$_data`, `$_payload`, `$_exception` | +| `CakeDC\Api\Service\Action\Traits\ReCaptchaTrait` | `_getReCaptchaInstance()` | +| `CakeDC\Api\Service\Auth\Auth` | `$_registry`, `$_service`, `$_action`, `_setDefaults()`, `_isAllowed()` | +| `CakeDC\Api\Service\Auth\AuthenticateTrait` | `$_authentication` | +| `CakeDC\Api\Service\AuthService` | `_actionOptions()` | +| `CakeDC\Api\Service\ConfigReader` | `_checkServiceOptions()`, `_mergeWithDefaults()` | +| `CakeDC\Api\Service\CrudService` | `$_actionsClassMap`, `$_table`, `$_idName`, `_actionOptions()` | +| `CakeDC\Api\Service\DescribeService` | `$_actionsClassMap` | +| `CakeDC\Api\Service\Extension\CollectionExtension` | `$_service` | +| `CakeDC\Api\Service\Extension\Extension` | `$_registry` | +| `CakeDC\Api\Service\Extension\LogExtension` | `$_service`, `$_action`, `$_timer`, `_redact()` | +| `CakeDC\Api\Service\ExtensionRegistry` | `$_service` | +| `CakeDC\Api\Service\FallbackService` | `$_table` | +| `CakeDC\Api\Service\ListingService` | `$_actionsClassMap` | +| `CakeDC\Api\Service\Locator\LocatorAwareTrait` | `$_serviceLocator` | +| `CakeDC\Api\Service\Locator\ServiceLocator` | `$_config`, `$_instances`, `$_fallbacked`, `$_options`, `_getClassName()`, `_create()`, `_compareOptions()` | +| `CakeDC\Api\Service\NestedCrudService` | `$_parentIdName`, `_actionOptions()` | +| `CakeDC\Api\Service\Renderer\BaseRenderer` | `$_service`, `_buildMessage()`, `_stackTrace()` | +| `CakeDC\Api\Service\Renderer\FileRenderer` | `_encode()` | +| `CakeDC\Api\Service\Renderer\JSendRenderer` | `_format()`, `_success()`, `_fail()`, `_mapStatus()` | +| `CakeDC\Api\Service\Renderer\JsonRenderer` | `_encode()` | +| `CakeDC\Api\Service\Renderer\XmlRenderer` | `_format()`, `_object()`, `_array()`, `_encode()` | +| `CakeDC\Api\Service\RequestParser\BaseParser` | `$_service` | +| `CakeDC\Api\Service\Service` | `$_actions`, `$_actionsClassMap`, `$_routeExtensions`, `$_routePrefix`, `$_name`, `$_version`, `$_parser`, `$_renderer`, `$_parserClass`, `$_rendererClass`, `$_innerServices`, `$_parentService`, `$_result`, `$_baseUrl`, `$_request`, `$_response`, `$_corsSuffix`, `$_action`, `_routesWrapper()`, `_prepareAction()`, `_processAction()`, `_actionOptions()`, `_loadExtensions()`, `_initializeParser()`, `_initializeRenderer()` | +| `CakeDC\Api\Service\ServiceRegistry` | `$_locator`, `$_defaultLocatorClass` | +| `CakeDC\Api\TestSuite\IntegrationTestCase` | `$_defaultUserId`, `_userToken()`, `_appendGetParam()` | + +The members of `CachedApiRbac` in this table had an underscore only in 12.0.2 and 12.0.3. They are the only members of the table that the Rector set does not rename, and the constructor check does not report them, so rename them by hand. `cacheKey()` was protected and is now public; it is still static. + +### Native types + +Most public and protected methods now declare native parameter and return types. An override must use a compatible signature, otherwise PHP stops with a fatal error when the class is loaded. Common ones: + +| Method | Signature since 13.0 | +| :----- | :------------------- | +| `Action::execute()` | `execute(): mixed` (the CRUD actions narrow it, for example `CrudIndexAction::execute(): ResultSetInterface`) | +| `Action::validates()` | `validates(): bool` | +| `Action::process()` | `process(): mixed` | +| `Action::getData()` | `getData($name = null, $default = null): mixed` | +| `Action::getService()` | `getService(): Service` (`CrudAction::getService(): CrudService`) | +| `CrudAction::getEntitiesQuery()` | `getEntitiesQuery(): SelectQuery` | +| `CrudAction::getEntityQuery()` | `getEntityQuery($primaryKey): SelectQuery` | +| `CrudAction::getEntity()` | `getEntity($primaryKey): EntityInterface\|array` | +| `CrudAction::newEntity()`, `patchEntity()`, `save()` | return `EntityInterface` | +| `TransformerInterface::transform()` | `transform(mixed $data): array` | + +### Sort field validation + +Sort fields from the request are now validated. Without configuration only columns of the action's own table are accepted, except columns the entity hides from output (`$_hidden`). + +- To sort by an associated table field, a computed select alias, or a hidden column, list it in the new `sortableFields` setting. The associated table must be joined in the main query. +- `sortableFields` replaces the default allowance instead of extending it: once it is set, list the action's own sortable columns too. +- Fields that are not allowed are ignored, so such a request returns HTTP 200 with unsorted results instead of an error. Check the clients of your list endpoints after upgrading. +- ExtendedSort accepts only the JSON object form, for example `{"title": "asc"}`. The list form `["title"]` and numeric keys are ignored. + +```php +'Api' => [ + 'Service' => [ + 'articles' => [ + 'Action' => [ + 'Index' => [ + 'Extension' => [ + 'CakeDC/Api.Sort' => [ + 'sortableFields' => ['id', 'title', 'created', 'Authors.last_name'], + ], + ], + ], + ], + ], + ], +], +``` + +See [Extensions](extensions.md) for the `sortableFields` setting. + +### JWT and two-factor authentication (13.0.1) + +- In `JwtTokenTrait` a `null` token type now means a refresh and requires a payload with a non-empty string `aud`; otherwise it throws a 401 `ValidationException`. Custom actions that issue new tokens must pass `'login'`, or `'2fa'` once the second factor is completed. +- If 2FA is enabled, invalidate the refresh tokens issued before the upgrade: empty the `jwt_refresh_tokens` table, rotate `Api.Jwt.RefreshToken.secret`, or set `Api.Jwt.RefreshToken.maxSessionLifetime`. +- A user can enroll a second factor only while no other factor is registered: WebAuthn registration is refused when OTP is verified, and a new OTP secret is refused when a WebAuthn credential exists. Users who should have both must enroll the second one in a flow you control. +- WebAuthn keys are stored per domain, and the domain can come from the client's `Referer` header. A key registered under any domain now counts as a registered second factor, so a user who has a key under one domain cannot register another key, or OTP, under a different domain of `Api.Webauthn2fa`. +- reCaptcha: `Api.reCaptcha..disabled` no longer turns validation off, because the domain can come from the client's `Referer` header; it is ignored and a warning is logged. Set `Api.reCaptcha.disabled` to `true` instead, in the configuration of the environments where validation should be off. +- WebAuthn credentials registered while the application ran 13.0.0 were saved where they are never read, so they are lost: those users register their authenticator again. Credentials registered with 12.x are stored under `additional_data.api.`, where 14.x reads them. Their format was not tested against data written by 12.x, so test a login with such a key after the upgrade. Registration no longer replaces the rest of `additional_data`. + +### Permission rules and embedded associations (13.0.1) + +- `allowed` and `bypassAuth` are now checked after the other keys of a rule in `api_permissions.php`, wherever they appear. A rule that listed one of them first used to match every request; it now applies only to the roles, services, actions and methods it names. Keys after `allowed`/`bypassAuth` are now checked too, including keys used as notes (`'note' => '...'`), which are matched against the user record. Check rules that do not list these keys last. +- CrudRelations embeds an association named in `include_relations` / `include_associations`, or added by `include_direct`, only when the user may access the `index` action of the related service. Otherwise it is left out of the response, which is still HTTP 200. Allow that action for the roles that need the embedded data, or keep the old behaviour with: + +```php +'Api' => ['Service' => ['default' => ['Action' => ['default' => ['Extension' => [ + 'CakeDC/Api.CrudRelations' => ['checkPermissions' => false], +]]]]]], +``` + + Set it per action under `Api.Service..Action..Extension` to keep the check elsewhere. +- The Log extension masks values whose key contains `password`, `token`, `secret` or `authorization`, and no longer writes the exception trace to `api.log`. +- `CachedApiRbac` now checks the rules in the order of `api_permissions.php`, like `ApiRbac`: the first matching rule decides. Before, the rules of the user's role and of the requested service were checked before the `*` rules, so a later role or service rule could override an earlier `*` rule. Check rule lists that relied on that, and note that a rule for a service written in another form, such as `Auth`, now applies to the `auth` service, and that rules for the inner service of nested routes, such as `articles` in `/authors/1/articles`, now apply there. A rule without `service` or `action`, or with a `user` key, denies every request that reaches it, as in `ApiRbac`, and is logged as a warning when the map is built. A role or service named like a PHP function, such as `file`, is called as that function, as in `ApiRbac`. The map holds rule positions only and its cache key depends on the rules, so no cache clear is needed after the upgrade or after a change of the rules, and rules with closures work with every cache engine. diff --git a/docs/Documentation/versioning.md b/docs/Documentation/versioning.md index 3552af4b..8d17c14d 100644 --- a/docs/Documentation/versioning.md +++ b/docs/Documentation/versioning.md @@ -17,12 +17,15 @@ To enable it, you just need to turn true the configuration in the `config/api.ph ```'useVersioning' => true,``` -### Testing - -If you want to use versioingn on testing. Enable it in the `test/Config/api.php` - -```'useVersioning' => true,``` +## Version classes and options +- A version class lives in `src/Service//`, for example `App\Service\v2\ArticlesService` in `src/Service/v2/ArticlesService.php`. +- A version without its own class for a service is served by the unversioned class (`App\Service\ArticlesService`), and only then by `Api.ServiceFallback`. +- With `Api.defaultVersion` set (a number without the prefix, such as `1`), a URL without a version is served as that version. +- A service reads `Api.Service..` and `Api.Service..default`. The default version, and a version without its own service class, also read the unversioned `Api.Service.` keys; keys under the version win. See [Configuration](configuration.md) and [Upgrading](upgrading.md#versioning). +### Testing +If you want to use versioning on testing. Enable it in the `tests/Config/api.php` +```'useVersioning' => true,``` diff --git a/docs/attributes.md b/docs/attributes.md index d7e75030..3860bc50 100644 --- a/docs/attributes.md +++ b/docs/attributes.md @@ -86,14 +86,14 @@ class PublishAction extends CrudAction { public function execute(): mixed { - // $this->request->getParam('id') + // $this->getRoute()['id'] } } ``` > [!NOTE] -> The `/api` base path and the version prefix are **config-driven** -> (`Api.routeBase`, `Api.useVersioning`, `Api.versionPrefix`). Attribute paths are +> The `/api` base path comes from the plugin routes (`config/routes.php`), and the +> version prefix from `Api.useVersioning` and `Api.versionPrefix`. Attribute paths are > relative to the service resource and must not include `/api` or a version segment. Attribute routing is **fully optional** and composes with the existing actions map. @@ -142,7 +142,7 @@ class ArticlesService extends FallbackService > [!TIP] > `ApiScope::path` only adds a sub-path **within** the service resource > (`/api/{service}/{scope}/{action}`). Use it for grouping actions, not for the -> API or version base — those come from `Api.routeBase` / `Api.useVersioning`. +> API or version base — those come from the plugin routes and `Api.useVersioning`. ### ApiResource @@ -153,7 +153,7 @@ class ArticlesService extends FallbackService ```php use CakeDC\Api\Service\Attribute\ApiResource; -#[ApiResource(only: ['index', 'view', 'featured'])] +#[ApiResource(only: ['index', 'view', 'featured', 'featured_cors'])] class ArticlesService extends FallbackService { } @@ -163,13 +163,16 @@ class ArticlesService extends FallbackService |---|---|---| | `path` | `string\|null` | Override the resource URL path. | | `only` | `array` | Limit which routes are generated (index/view/add/edit/delete + custom). | -| `actions` | `array` | Map REST actions to custom action classes. | -| `map` | `array` | Additional non-standard resource routes. | -| `id` | `string` | Regex pattern for the resource identifier. | +| `actions` | `array` | Rename REST actions, as the `actions` option of `$routes->resources()` (`['index' => 'list']`). | +| `map` | `array` | Not applied: the service's own actions map replaces it. Declare extra routes with `ApiActions`. | +| `id` | `string` | Regex pattern for the resource identifier. Default `[0-9]+`; set it (for example to a UUID pattern) when ids are not integers. | > [!WARNING] -> `only` filters **all** resource routes, including actions declared via -> `ApiActions`. List every custom action name in `only` when using both. +> `only` filters **all** resource routes by action name: the CRUD routes, actions +> declared via `ApiActions`, their CORS routes and the `describe` routes of +> `FallbackService`. List every custom action name, add `_cors` for each +> action with `mapCors: true` (for example `featured_cors`), and add `describe` and +> `describeId` to keep the OPTIONS describe routes. ## Declaring Actions @@ -197,8 +200,8 @@ class ArticlesService extends FallbackService } ``` -Pass the action classes as an **array**. Each listed action class must carry at -least one route attribute. +Pass the action classes as an **array**; a single class name is accepted too. +Each listed action class must carry at least one route attribute. ### ApiRoute on Action Classes @@ -246,8 +249,8 @@ These accept the same parameters as `#[ApiRoute]` except `method`. ### Placeholders -`{placeholder}` segments in `path` become route params, read inside the action -via `$this->request->getParam('name')` (or the `id` param for `CrudAction`): +`{placeholder}` segments in `path` become route values, read inside the action +via `$this->getRoute()['name']` (a `CrudAction` also has `getId()` for `id`): ```php #[ApiGet(action: 'view', path: '/{id}')] @@ -255,7 +258,7 @@ class ViewAction extends CrudAction { public function execute(): mixed { - $id = $this->request->getParam('id'); + $id = $this->getRoute()['id']; } } ``` @@ -278,8 +281,9 @@ Shared patterns can be set at the service level via `ApiScope`. ### Pass -`pass` controls which placeholders are passed to the action as positional -arguments. When omitted, placeholders are available as route params: +`pass` sets which placeholders the route lists under `pass` in `getRoute()`, +instead of the default `['id']`. Placeholders are always available by name in +`getRoute()`: ```php #[ApiGet(action: 'view', path: '/{id}', pass: ['id'])] @@ -317,7 +321,8 @@ Service-level attributes support class inheritance: - `#[ApiScope]` **stacks** — parent and child scope paths/defaults/patterns are concatenated/merged (parent first). -- `#[ApiResource]` and `#[ApiActions]` on a child **override** the parent's. +- `#[ApiResource]` on a child **overrides** the parent's. +- `#[ApiActions]` lists **add up**: the child gets the parent's actions and its own. - Abstract service classes are skipped (their routes are only connected through concrete subclasses). @@ -388,7 +393,7 @@ AttributeResolver::setConfig('default', [ If you re-configure the resolver with a different `paths`/`basePath`/`excludePaths` (not just on boot), the cached collection is stale. Invalidate it before -re-configuring, mirroring the Codex `CommandBus` pattern: +re-configuring: ```php if (AttributeResolver::getConfig('default') !== null) { @@ -414,6 +419,6 @@ All attributes live in the `CakeDC\Api\Service\Attribute` namespace. | `#[ApiScope]` | Service class | Yes | Path prefix, defaults, patterns. | | `#[ApiResource]` | Service class | No | REST resource route options. | -Dependencies: `crustum/cakephp-attribute-resolver` (`^1.0`) drives attribute +Dependencies: `crustum/cakephp-attribute-resolver` (`^1.0.3`) drives attribute discovery and caching; the connector requires a resolver configuration (see [Caching](#caching)). diff --git a/docs/home.md b/docs/home.md deleted file mode 100644 index e9e097d5..00000000 --- a/docs/home.md +++ /dev/null @@ -1,28 +0,0 @@ -Home -==== - -The **CakePHP-API** Plugin allows to easily expose a versioned API in a few lines of code. - -Requirements ------------- - -* CakePHP 3.2.9+ -* PHP 5.6.9+ - -Documentation -------------- - -* [Overview](Documentation/overview.md) -* [Installation](Documentation/installation.md) -* [Configuration](Documentation/configuration.md) -* [Routing](Documentation/routing.md) -* [Services](Documentation/services.md) -* [Actions](Documentation/actions.md) -* [Extensions](Documentation/extensions.md) -* [Renderers](Documentation/renderers.md) -* [Statuses](Documentation/status.md) -* [Versioning](Documentation/versioning.md) -* [Collections](Documentation/collections.md) - - - diff --git a/docs/index.md b/docs/index.md index a256a204..3a00feda 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,17 +3,19 @@ - [Introduction](#introduction) - [Quickstart](#quickstart) - [Installing the Plugin](#installing-the-plugin) + - [Creating the Database Tables](#database-tables) - [Configuration](#configuration) - [Exposing Your First Resource](#exposing-your-first-resource) - [Next Steps](#quickstart-next-steps) - [Request Lifecycle](#request-lifecycle) + - [Overloaded Router (`ApiRouter`)](#overloaded-router) - [Services](#services) - [Service Types](#service-types) - [Resolving Services](#resolving-services) - [Defining a Custom Service](#defining-a-custom-service) - [Actions Map](#actions-map) - - [Service Extensions](#service-extensions) - [Attribute Routing](#attribute-routing) + - [Service Extensions](#service-extensions) - [Renderers](#renderers) - [JSend (Default)](#jsend-default) - [Json](#json) @@ -62,7 +64,10 @@ - [Model & JWT Refresh Tokens](#model-jwt-refresh-tokens) - [Testing](#testing) - [Console Commands](#console-commands) + - [`service routes`](#service-routes-command) - [Legacy & Obsolete Components](#legacy-obsolete-components) +- [Upgrading to 14.x](Documentation/upgrading.md) +- [Roadmap](Documentation/roadmap.md) ## Introduction @@ -76,7 +81,7 @@ The **CakePHP API** plugin exposes your CakePHP application as a REST API with a - **Optional versioning** — versioned service namespaces (`Service/v1`, `Service/v2`, …). - **Reusable extensions** — pagination, sorting, filtering, HATEOAS links, relations, CORS and nested resources. -The plugin targets **CakePHP 5.x**. +Version 14.x of the plugin needs **CakePHP 5.4** or newer and **PHP 8.3** or newer. ## Quickstart @@ -96,14 +101,7 @@ Load the plugin and its configuration: bin/cake plugin load CakeDC/Api ``` -> [!NOTE] -> The plugin ships its default configuration in `config/api.php`. Load it in your application's `config/bootstrap.php` (or via the manifest system) so `Configure::read('Api.*')` is populated: - -```php -Cake\Core\Configure::load('api'); -``` - -Alternatively, load the plugin and configure it in `Application::bootstrap()`: +Alternatively, load the plugin in `Application::bootstrap()`: ```php // In src/Application.php @@ -115,6 +113,20 @@ public function bootstrap(): void } ``` +> [!NOTE] +> The plugin loads its default configuration (its own `config/api.php`) when it bootstraps. To change settings, create `config/api.php` in your application and name it in `Application::bootstrap()`: `Configure::write('Api.config', ['api']);`. The plugin then loads it after its defaults. + + +### Creating the Database Tables + +JWT login stores refresh tokens in the `jwt_refresh_tokens` table, and the WebAuthn second factor stores its state in the `auth_store` table. Create both with the plugin migrations. They need [cakephp/migrations](https://github.com/cakephp/migrations) (^4.5 or ^5.0) in your application: + +```bash +bin/cake migrations migrate -p CakeDC/Api +``` + +You can skip this step if your API uses neither JWT login nor WebAuthn. + ### Configuration @@ -139,9 +151,8 @@ All plugin configuration lives under the `Api` configuration key. The important // Service class lookup 'lookupMode' => 'underscore', - // JWT tokens (disabled by default) + // JWT tokens: set both secrets to use them 'Jwt' => [ - 'enabled' => false, 'AccessToken' => ['lifetime' => 600, 'secret' => ''], 'RefreshToken' => ['lifetime' => 14 * 86400, 'secret' => ''], ], @@ -151,7 +162,7 @@ All plugin configuration lives under the `Api` configuration key. The important ``` > [!TIP] -> JWT and 2FA are **off** by default. Enable them only when your application needs them. +> 2FA is **off** by default. The plugin does not read `Api.Jwt.enabled`: the JWT actions and the JWT authenticator are always registered. They need `Api.Jwt.AccessToken.secret` and `Api.Jwt.RefreshToken.secret`, and your permission rules decide who may call them. ### Exposing Your First Resource @@ -162,7 +173,7 @@ No service class is required for a basic CRUD resource. If your application has GET /api/articles -> articles index GET /api/articles/1 -> view article 1 POST /api/articles -> add an article -PUT /api/articles/1 -> edit article 1 +PUT /api/articles/1 -> edit article 1 (PATCH works too) DELETE /api/articles/1 -> delete article 1 ``` @@ -183,12 +194,12 @@ A `GET /api/articles` response (JSend): } ``` -By default the plugin is configured for **public access** (`Auth.allow = '*'`). Read [Authorization & Permissions](#authorization-permissions) to restrict access. +Access is decided by the RBAC rules in `config/api_permissions.php`, not by `Auth.allow`. Without that file the plugin uses its built-in rules: the login, register, password reset and account validation actions of `auth` are public, the `admin` role may do everything, the `user` role may send GET requests, and every other request is refused. If you copy `config/api_permissions.php.default` unchanged, every endpoint is public. Read [Authorization & Permissions](#authorization-permissions) before you expose data. > [!WARNING] > **The fallback service exposes any table by its URL — this is unsafe without an auth layer.** > -> Any request to `/api/{name}` that has no service class resolves to a `FallbackService` over the table `{Name}` (pluralized). Because the default configuration is public (`Auth.allow = '*'`), an unauthenticated request to `/api/users` would return the **entire users table** — including password hashes, `api_token` values, and anything else the entity serializes. +> Any request to `/api/{name}` that has no service class resolves to a `FallbackService` over the table `{Name}` (the camelized service name). With a rule that allows it (the shipped `api_permissions.php.default` allows every request without authentication), an unauthenticated request to `/api/users` would return the **entire users table** — including password hashes, `api_token` values, and anything else the entity serializes. > > Before going to production you **must**: > @@ -208,10 +219,11 @@ Once your first endpoint works, read about [Services](#services), [Authenticatio A request to `/api/articles/1` is processed by the middleware chain registered in `Api.Middleware`: 1. **`BodyParserMiddleware`** — parses the request body into `$request->getData()`. -2. **`AuthenticationMiddleware`** — resolves the identity (session, form, token or JWT) and stores it in the `authentication` request attribute. -3. **`ParseApiRequestMiddleware`** — matches the URL against `#/api/{service}{base}#` (or the versioned pattern), resolves the service, and attaches it to the request as the `service` attribute. If no service resolves, it responds with the error directly. -4. **`AuthorizationMiddleware`** (RBAC) — checks the request against the [permissions](#authorization-permissions). -5. **`ProcessApiRequestMiddleware`** — executes the service action and renders the result through the configured [renderer](#renderers). +2. **`AuthenticationMiddleware`** — resolves the identity (session, form, token or JWT) and stores it in the `identity` request attribute; the `authentication` attribute holds the authentication service. +3. **`ParseApiRequestMiddleware`** — matches the URL against `#/api/{service}{base}#` (or the versioned pattern), resolves the service, and attaches it to the request as the `service` attribute. If the action cannot be prepared, for example for an unknown route, it responds with the error directly. An exception thrown while the service is built goes to the error handling of the application. +4. **`AuthorizationMiddleware`** — adds the authorization service (RBAC) to the request. +5. **`RequestAuthorizationMiddleware`** — checks the request against the [permissions](#authorization-permissions). +6. **`ProcessApiRequestMiddleware`** — executes the service action and renders the result through the configured [renderer](#renderers). The URL structure is: @@ -226,7 +238,7 @@ Service and action names are **underscored** by default. For example `/api/auth/ The plugin **overloads** the CakePHP `Router` with `CakeDC\Api\Routing\ApiRouter`. It is what turns a service's actions map into real resource routes at runtime: -- **`resources($serviceName, $options)`** — generates the collection + item routes (`/articles`, `/articles/{id}`) from the service's actions map and HTTP methods. +- **`ApiRouteBuilder::resources($serviceName, $options)`** (the builder that `ApiRouter::createRouteBuilder()` returns) — generates the collection + item routes (`/articles`, `/articles/{id}`) from the service's actions map and HTTP methods. - **`parseRequest($request)`** — resolves a URL into routing params (controller/action/pass/`_method`); it is what `Service::parseRoute()` delegates to. - **Reverse routing** — `ApiRouter::reverse($params)` / `ApiRouter::url($route)` rebuild a URL from route params; services expose this via `routeReverse()` and `routeUrl()`. The HATEOAS links produced by `CrudHateoas` and `ReverseRouting` rely on it. - **Named expressions** — `ID`, `UUID`, `YEAR`, `MONTH`, `DAY`, `ACTION` constants for route templates (e.g. `'/articles/{id}'`). @@ -252,7 +264,7 @@ A **service** is the unit that owns an endpoint. It is responsible for: | `CrudService` | Abstract base for services that expose CRUD actions. | | `NestedCrudService` | Adds nested-resource support (e.g. `/authors/1/articles`). | | `AuthService` | Authentication actions: `login`, `register`, `jwt_login`, `otp_verify`, … | -| `DescribeService` / `ListingService` | Introspection endpoints (`/api/describe`, `/api/list`). | +| `DescribeService` / `ListingService` | Introspection endpoints (`/api/describe`, `/api/listing`). | | `RecaptchaService` | `validate` action using the reCaptcha trait. | @@ -271,6 +283,29 @@ $service = ServiceRegistry::getServiceLocator()->get('articles', [ ]); ``` +In your own classes, such as a command or a custom action, you can use `CakeDC\Api\Service\Locator\LocatorAwareTrait` instead. Its `getServiceLocator()` returns the same `ServiceRegistry` locator, and `setServiceLocator()` replaces it for that object, for example with a test double: + +```php +use Cake\Http\Response; +use Cake\Http\ServerRequest; +use CakeDC\Api\Service\Locator\LocatorAwareTrait; + +class ArticlesReport +{ + use LocatorAwareTrait; + + public function build(ServerRequest $request, Response $response): array + { + $service = $this->getServiceLocator()->get('articles', [ + 'request' => $request, + 'response' => $response, + ]); + + // ... + } +} +``` + Resolution order (`lookupMode = underscore`): 1. A class named `{App}\Service\ArticlesService` (camelized alias + `Service` suffix). @@ -278,7 +313,7 @@ Resolution order (`lookupMode = underscore`): 3. The **fallback service** (`Api.ServiceFallback`, i.e. `FallbackService`) — a generic CRUD service over the `Articles` table. > [!WARNING] -> **The fallback is a catch-all.** Any endpoint with no service class silently falls back to CRUD over the matching table (`/api/users` → the `Users` table, `/api/orders` → the `Orders` table, …). Combined with the default public `Auth.allow = '*'` configuration this lets unauthenticated requests read every serialized field of those tables (e.g. `GET /api/users`). +> **The fallback is a catch-all.** Any endpoint with no service class silently falls back to CRUD over the matching table (`/api/users` → the `Users` table, `/api/orders` → the `Orders` table, …). Combined with a permissive `api_permissions.php`, such as the unchanged `.default` file, this lets unauthenticated requests read every serialized field of those tables (e.g. `GET /api/users`). > > Treat the fallback as **development convenience only**. For production: > @@ -307,20 +342,13 @@ class ArticlesService extends FallbackService 'featured' => ['method' => ['GET'], 'path' => 'featured'], 'data' => ['method' => ['GET'], 'path' => 'data'], ]; - - public function initialize(): void - { - parent::initialize(); - - $this->setTable('Articles'); - } } ``` -Now `/api/articles/featured` and `/api/articles/data` are available in addition to the CRUD routes. +Now `/api/articles/featured` and `/api/articles/data` are available in addition to the CRUD routes. Each action needs a class: `App\Service\Action\ArticlesFeaturedAction` and `App\Service\Action\ArticlesDataAction` (service name, action name, `Action`), or a class registered with `mapAction()`. > [!NOTE] -> `FallbackService::initialize()` infers the table from the service name (`articles` → `ArticlesTable`). Override with `setTable()` when the table name differs. +> The table is named after the service: the camelized service name (`articles` → `Articles`), not pluralized. When the table name differs, pass the `table` option, for example in the constructor: `parent::__construct($config + ['table' => 'Posts']);`. A `setTable()` call in `initialize()` has no effect, because the constructor sets the table after it. ### Actions Map @@ -377,7 +405,9 @@ Each route also registers an OPTIONS (CORS) counterpart. #### Log -Logs request timing for the service. Starts a timer on `Service.beforeDispatch` and logs the elapsed time (and outcome) on `Service.afterDispatch`. Useful for profiling API endpoints in development. +Logs each request to the `api` log scope (`logs/api.log` by default): the URL, method, duration, request input and result. Starts a timer on `Service.beforeDispatch` and writes the entry on `Service.afterDispatch`. Not enabled by default; add `CakeDC/Api.Log` to a service's extensions. + +Values whose key contains `password`, `token`, `secret` or `authorization` are replaced with `***` in both the input and the result. The `redact` setting adds words to that list. Plain objects and traversable values are redacted too, and the exception trace, which can hold call arguments, is not logged. #### OptionsHandler @@ -400,7 +430,7 @@ All renderers extend `CakeDC\Api\Service\Renderer\BaseRenderer` and implement th - `response(?Result $result)` — build the success body from a `Result` (data + payload). - `error(Exception $exception)` — build the error body when a service call throws. -BaseRenderer also provides the shared `buildMessage()`, `stackTrace()`, and JSON `encode()` helpers used by the JSON-family renderers. +BaseRenderer also provides the shared `buildMessage()` and `stackTrace()` helpers. The Json, File and Xml renderers each have their own `encode()`. #### JSend (Default) @@ -462,17 +492,17 @@ The HTTP status is set from the result code. Errors fall back to a JSON error bo #### Flysystem -`CakeDC/Api.Flysystem` extends the file renderer to stream a file from a [Flysystem](https://flysystem.thephpleague.com) filesystem. The result data must contain: +`CakeDC/Api.Flysystem` extends the file renderer to stream a file from a [Flysystem](https://flysystem.thephpleague.com) v3 filesystem. Install `league/flysystem` ^3.35.3 to use it. The result data must contain: ```php return [ - 'filesystem' => $filesystem, // League\Flysystem\Filesystem + 'filesystem' => $filesystem, // League\Flysystem\FilesystemOperator 'path' => 'reports/report.pdf', 'name' => 'report.pdf', // download name ]; ``` -A missing file yields an HTTP `404`. +A missing file yields an HTTP `404`. The `Content-Type` comes from the filesystem MIME type detection, with `application/octet-stream` as fallback. ### Responses @@ -505,10 +535,10 @@ Validation failures return the field errors under the response `data` key: ```json { "status": "error", - "message": "Validation failed", + "message": "Validation on Articles failed", "code": 422, "data": { - "title": ["This field is required"] + "title": {"_required": "This field is required"} } } ``` @@ -528,7 +558,7 @@ The `FallbackService`/`CrudService` provide these actions out of the box: | `index` | `/api/articles` | GET | | `view` | `/api/articles/{id}` | GET | | `add` | `/api/articles` | POST | -| `edit` | `/api/articles/{id}` | PUT | +| `edit` | `/api/articles/{id}` | PUT, PATCH | | `delete` | `/api/articles/{id}` | DELETE | | `describe` | `/api/articles` | OPTIONS | @@ -551,9 +581,12 @@ The `AuthService` exposes these endpoints under `/api/auth`: | `jwt_social_login` | POST | Social login issuing JWT tokens. | | `otp_verify` | GET | Fetch/verify the OTP shared secret (QR code). | | `otp_verify_check` | POST | Verify an OTP code. | -| `webauthn2fa` | GET | 2FA status. | -| `webauthn2fa_register` / `webauthn2fa_register_options` | GET/POST | Webauthn registration. | -| `webauthn2fa_auth` / `webauthn2fa_auth_options` | GET/POST | Webauthn authentication. | +| `two_factor_auth` | GET | 2FA status: which factors are registered and enabled. | +| `webauthn2fa` | GET | WebAuthn status: whether the user still has to register a key. | +| `webauthn2fa_register_options` | GET | Options for a WebAuthn registration. | +| `webauthn2fa_register` | POST | Complete a WebAuthn registration. | +| `webauthn2fa_auth_options` | GET | Options for a WebAuthn login. | +| `webauthn2fa_auth` | POST | Complete a WebAuthn login. | > [!NOTE] > The users table is provided by the **CakeDC/Users** plugin. `ApiInitializer` resolves identities against `CakeDC/Users.Users` with the `active` finder. @@ -653,7 +686,8 @@ Orders index queries by a single field. - Query params: `sort` and `direction` (field names via `sortField` / `directionField`). - Default direction: `asc`. -- Listens to `Action.Crud.onFindEntities` and applies `orderBy`. +- The field is checked: with the `sortableFields` setting only the listed fields are accepted, otherwise only columns of the action table that the entity does not hide. Another field is ignored and logged at debug level with the `api` scope. +- Listens to `Action.Crud.onFindEntities` and applies `orderBy`. The `order` setting is applied after the request order. ``` GET /api/posts?sort=title&direction=desc @@ -692,7 +726,7 @@ Cursor-based pagination, better suited to large/fast-changing datasets than page #### ExtendedSort -Multi-field sorting. The `sort` param is a JSON-encoded associative array passed straight to `orderBy`: +Multi-field sorting. The `sort` param is a JSON object of field and direction. Each field is checked: with the `sortableFields` setting only the listed fields are accepted, otherwise only columns of the action table that the entity does not hide. Other entries, list entries and invalid JSON are ignored and logged at debug level with the `api` scope. A direction other than `asc` or `desc` becomes `asc`. The `order` setting is applied after the request order: ``` GET /api/posts?sort={"title":"asc","created":"desc"} @@ -713,7 +747,11 @@ Adds a `links` collection to `index`/`view` responses describing the available a #### CrudRelations -Eager-loads **HasOne** and **BelongsTo** associations so related entities are included in `index`, `view`, and `edit` responses. Listens to `Action.Crud.onFindEntities` / `Action.Crud.onFindEntity`. +Embeds associations on request, in `index` and `view` responses: the associations named in the `include_relations` (or `include_associations`) param, as a comma-separated list or an array, or every **HasOne** and **BelongsTo** association with `include_direct=1`. Listens to `Action.Crud.onFindEntities` / `Action.Crud.onFindEntity`. + +An association is embedded only when the current user may access the `index` action of the related service with a GET request, as decided by the request's authorization service (the `api_permissions.php` rules); other associations are left out. The related service is the one named after the table class of the association's target (`AuthorsTable` → `authors`), also for an aliased association such as `Writers` with `className` `Authors`; a generic table is named after its database table. Every step of a dotted path is checked, and nested routes such as `/authors/1/articles` are covered. Without the authorization middleware, associations are embedded as before, and a `debug` message is logged with the `api` scope. Set `checkPermissions` to `false` to embed requested associations without the check. + +The check sends the request through the authorization service with the `ApiRbac::TARGET_ATTRIBUTE` request attribute, which names the service and action to check. `ApiRbac` and `CachedApiRbac` honour it; a custom request policy or rule that reads the `service` attribute sees the current service instead. #### Nested @@ -728,15 +766,17 @@ Appends CORS headers to the response (see [CORS](#cors)). Listens to `Action.bef #### CrudAutocompleteList -Transforms an index query into an autocomplete list. When the request carries an `autocomplete_list` param, the query selects only the id + display fields. +Transforms an index query into an autocomplete list. When the request carries a non-empty `autocomplete_list` param, the query selects only the primary key and the display field of the table. ``` -GET /api/articles?autocomplete_list=title +GET /api/articles?autocomplete_list=1 ``` #### Authentication +Deprecated in 14.0.0, removed in 15.0.0. Authentication runs in the `AuthenticationMiddleware`. + Provides per-action authentication for the action layer: - Config: `requireIdentity` (default `true`), `identityAttribute` (`identity`), `logoutRedirect`. @@ -815,7 +855,7 @@ How nesting works: - **`NestedExtension`** scopes every query by the parent foreign key — on `onFindEntities` / `onFindEntity` it adds `where([$parentIdName => $parentId])`, and on `onPatchEntity` it enforces the parent when patching. - **Parent resolution** — when the route's controller matches one of the parent's `innerServices`, the plugin resolves the child service through `ServiceRegistry`, calls `setParentService($parent)` on it, and the child exposes `getParentService()`. `innerServices` is populated automatically from the parent table's `HasMany` associations. - **HATEOAS** — nested index/view responses include a parent link (`authors:view`) pointing back to the parent resource. -- **Arbitrary nesting depth** — because each level resolves a child service with its own parent, `/api/authors/1/articles/2/tags` works the same way. +- **One level of nesting** — routes are registered for the HasMany associations of the service's own table (`/api/authors/1/articles`, `/api/authors/1/articles/2`). Deeper URLs such as `/api/authors/1/articles/2/tags` have no route. Use `getParentService()` inside actions when you need access to the parent record or its id. @@ -897,12 +937,11 @@ The following authenticators are loaded: ### JWT Authentication -Enable JWT in your configuration: +Set the JWT secrets in your configuration: ```php 'Api' => [ 'Jwt' => [ - 'enabled' => true, 'AccessToken' => [ 'lifetime' => 600, 'secret' => env('JWT_SECRET'), // >= 512 bits for HS512 @@ -910,13 +949,14 @@ Enable JWT in your configuration: 'RefreshToken' => [ 'lifetime' => 14 * 86400, 'secret' => env('JWT_REFRESH_SECRET'), + 'maxSessionLifetime' => null, // seconds from login or second factor, null = unlimited ], ], ], ``` > [!IMPORTANT] -> HS512 requires a signing key of **at least 512 bits** (64 bytes). Shorter secrets cause `Lcobucci\JWT\Signer\InvalidKeyProvided`. +> HS512 requires a signing key of **at least 512 bits** (64 bytes). A shorter secret is refused with an `InvalidArgumentException` when a token is issued. Login issues both tokens: @@ -936,7 +976,7 @@ POST /api/auth/jwt_login "username": "user-1", "access_token": "eyJ0eXAi...", "refresh_token": "eyJ0eXAi...", - "expired": "2026-08-15T12:00:00+00:00", + "expired": {"date": "2026-08-15 12:00:00.000000", "timezone_type": 3, "timezone": "UTC"}, "enabled2FA": false, "enabledWebauthn": false, "enabledOtp": false @@ -949,6 +989,10 @@ POST /api/auth/jwt_login Refresh tokens are persisted in the `jwt_refresh_tokens` table (upserted per `model` + `foreign_key`). +Each refresh token carries an `auth_time` claim with the time of login, or of completing the second factor, and a refresh keeps it. Set `Api.Jwt.RefreshToken.maxSessionLifetime` to a positive number of seconds to refuse a refresh once that much time has passed since then, so the user must log in again. Access tokens issued by the last allowed refresh stay valid for up to `Api.Jwt.AccessToken.lifetime` longer. This also bounds how long a session keeps the 2FA state it had at login: a session that started before the user enabled 2FA, or a `/2fa` session after 2FA was disabled, ends at that limit. Refresh tokens issued before the `auth_time` claim existed never get one, so they are refused as soon as the setting is on, even if they were refreshed in the meantime. + +A refresh keeps the audience the session was issued with, so changing `App.fullBaseUrl` leaves existing sessions with an audience no scope accepts: users must log in again, or empty the `jwt_refresh_tokens` table. + ### Token Responses @@ -958,6 +1002,8 @@ The JWT `aud` claim depends on 2FA state: - Normal login → `Router::url('/', true)`. - 2FA-enabled login (`type = login` with 2FA active) → `Router::url('/2fa', true)` — this is what the RBAC `TwoFactorScope` checks. +- Completing OTP or WebAuthn (`type = 2fa`) → `Router::url('/', true)`. +- Refresh → the audience of the refresh token, unchanged. ## Two-Factor Authentication @@ -980,7 +1026,7 @@ The JWT `aud` claim depends on 2FA state: ### One-Time Passwords -OTP uses `RobThree\Auth\TwoFactorAuth` (TOTP, base32 shared secret). +OTP uses `RobThree\Auth\TwoFactorAuth` (TOTP, base32 shared secret). Install `robthree/twofactorauth` ^3.0.1 and a QR code provider, for example `endroid/qr-code` ^5.0 || ^6.0 for robthree's `EndroidQrCodeProvider`. `OneTimePasswordAuthenticator.qrcodeprovider` must not be null: the `cakedc/users` default config sets it, and without it every OTP action fails, including `otp_verify_check`. - `GET /api/auth/otp_verify` — returns the shared secret and a QR-code data URI (`secretDataUri`) until the secret is marked verified. - `POST /api/auth/otp_verify_check` — verifies a code against the secret and marks `secret_verified`. @@ -995,7 +1041,9 @@ $checker->isRequired($user); // non-empty user && enabled ### Webauthn -Webauthn registration and authentication are exposed through the `webauthn2fa_*` actions. The checker reads `Api.Webauthn2fa.enabled`; custom checkers can be injected via the `checker` config keys. +Webauthn registration and authentication are exposed through the `webauthn2fa_*` actions. Install `web-auth/webauthn-lib` ^5.3.13 to use it. The checker reads `Api.Webauthn2fa.enabled`; custom checkers can be injected via the `checker` config keys. + +The relying party name and id come from `Api.Webauthn2fa.` (`appName`, `id`), and the keys are stored per domain in the user's `additional_data`. The domain is the host of the `Referer` header when the request has one (`app.example.com` → `app$example$com`), otherwise the domain of the request host without its subdomains (`app.example.com` → `example$com`), with dots replaced by `$`. A key registered under any domain counts as the user's registered second factor: the user cannot register another key, or OTP, under a different domain. ### RBAC Scopes @@ -1007,12 +1055,16 @@ Two RBAC rules gate 2FA flows (used inside permissions as `rule` entries): | `CakeDC\Api\Rbac\Rules\TwoFactorScope` | the JWT `aud` claim equals `Router::url('/2fa', true)` | | `CakeDC\Api\Rbac\Rules\TwoFactorPassedScope` | the JWT `aud` claim equals `Router::url('/', true)` | -A typical permission grants the 2FA endpoints only to tokens whose audience is `/2fa`, and everything else to fully-verified tokens: +A typical permission grants the 2FA endpoints (the status, OTP and WebAuthn actions) only to tokens whose audience is `/2fa`, and everything else to fully-verified tokens. Leave out the actions of a factor you do not offer: ```php return [ 'CakeDC/Auth.api_permissions' => [ - ['role' => '*', 'service' => 'Auth', 'action' => ['OtpVerify', 'OtpVerifyCheck'], 'rule' => [ + ['role' => '*', 'service' => 'Auth', 'action' => [ + 'TwoFactorAuth', 'OtpVerify', 'OtpVerifyCheck', + 'Webauthn2fa', 'Webauthn2faRegisterOptions', 'Webauthn2faRegister', + 'Webauthn2faAuthOptions', 'Webauthn2faAuth', + ], 'rule' => [ 'className' => \CakeDC\Api\Rbac\Rules\TwoFactorScope::class, ]], ['role' => '*', 'service' => '*', 'action' => '*', 'rule' => [ @@ -1056,13 +1108,15 @@ A permission entry is a plain array: | `action` | Action name(s); `*` matches any. | | `method` | HTTP method (`GET`, `POST`, …). | | `bypassAuth` | `true` → allow without authentication. | -| `allowed` | Explicit `true`/`false`; defaults to `true`. | +| `allowed` | `true`/`false` (defaults to `true`; needs an authenticated user), or a callable, `Rule` instance or `className` rule, which is also called without a user. | | `rule` | Callable, `Rule` instance, or `['className' => ..., 'options' => [...]]`. | | any other key | Matched against the user array (e.g. `'id' => 1`). | - Action names in config use **camelized** form (`MyAction`), matching the route's underscored `my_action`. -- Keys prefixed with `*` are **inverted** (`'*service' => 'articles'` denies when the service is `articles`). -- A permission missing both `service` and `action` is rejected (`cannot evaluate`). +- A key prefixed with `*` is **inverted**: `'*service' => 'articles'` makes the rule apply to every service except `articles`. It does not deny `articles`; a later rule can still allow it. +- A rule without `service` or without `action` (plain or `*`-prefixed), or with a `user` key, cannot be evaluated: it denies every request that reaches it, and the rules after it are not checked. +- A rule applies when all its keys other than `allowed` and `bypassAuth` match; those two then give the result, and they are checked after the other keys wherever they appear. +- A boolean `allowed` allows a request only when it has an authenticated user; `'bypassAuth' => true` allows it without one. A callable, a `Rule` instance or a `className` rule as the value of `allowed` or `bypassAuth` is called for every request the rule applies to, **also for one without a user** (`$user` is empty, `$role` is the default role), and its result is final. Such a check must test `$user` itself, or it opens the endpoint to everyone. ### Rules @@ -1084,14 +1138,75 @@ A permission entry is a plain array: ### Cached RBAC -For high-throughput applications, `CachedApiRbac` precomputes a permissions map (keyed by role → service) and stores it in the cache engine `_cakedc_api_auth_`: +For high-throughput applications, `CachedApiRbac` precomputes a permissions map (role → service → positions of the rules) and stores it in the cache engine `_cakedc_api_auth_`: ```php +map( + ServerRequest::class, + new CollectionPolicy([ + new RbacPolicy(['adapter' => new CachedApiRbac()]), + ]) + ); + + return new AuthorizationService(new ResolverCollection([$map, new OrmResolver()])); + } +} ``` +Point the authorization middleware at the new initializer in your `config/api.php`: + +```php +'Api' => [ + 'Middleware' => [ + // ... + 'apiAuthorize' => [ + 'class' => AuthorizationMiddleware::class, + 'request' => \App\CachedApiInitializer::class, + 'params' => [ + 'unauthorizedHandler' => 'CakeDC/Api.ApiException', + ], + ], + ], +], +``` + +and configure the cache engine, for example in `config/app.php`: + +```php +'Cache' => [ + '_cakedc_api_auth_' => [ + 'className' => FileEngine::class, + 'prefix' => 'myapp_cakedc_api_auth_', + 'path' => CACHE . 'persistent' . DS, + 'duration' => '+1 hours', + ], +], +``` + +The map is built once and read from the cache on the next requests. The map holds rule positions only: the rules, including the options of Rule objects and closures, are read from the current permissions list, so every cache engine works, File and Redis included. Its cache key depends on the rules, so a changed permissions list builds a new map; the old maps stay in the engine until they expire or you clear it (`bin/cake cache clear _cakedc_api_auth_`). + > [!NOTE] > The cache engine name is currently hardcoded to `_cakedc_api_auth_`; configure that engine (or an Array engine in tests) before using `CachedApiRbac`. @@ -1117,7 +1232,7 @@ return new AuthorizationService($resolver); What that gives you: - **`RbacPolicy`** evaluates every API request against the permissions (see [Authorization & Permissions](#authorization-permissions)); the `adapter` is the plugin's `ApiRbac`. -- **Cached case** — swap the adapter for `CachedApiRbac`: it precomputes a permissions map (role → service → rules) once via `buildPermissionsMap()`, stores it under the `_cakedc_api_auth_` cache engine, and `checkPermissions()` walks the cached map instead of re-evaluating every rule — useful for high-traffic APIs. +- **Cached case** — swap the adapter for `CachedApiRbac`: it precomputes a permissions map (role → service → rule positions) once via `buildPermissionsMap()`, stores it under the `_cakedc_api_auth_` cache engine, and `checkPermissions()` evaluates only the rules the map lists for the user's role and the service, in their order, instead of every rule — useful for high-traffic APIs. - **2FA-aware rules** — the same `RbacPolicy` accepts the plugin's `TwoFactorScope` / `TwoFactorPassedScope` rules for gating 2FA endpoints (see [RBAC Scopes](#rbac-scopes)). - Permissions load from `CakeDC/Auth.api_permissions` via `ApiConfigProvider`, with a sensible default when the config file is missing. @@ -1152,9 +1267,11 @@ class ArticlesService extends BaseArticlesService ``` > [!NOTE] -> The version directory mirrors the version string (`v1` → `Service/v1`). An unresolvable version falls back to `FallbackService`. `Api.defaultVersion` provides the version used when none is given. +> The version directory mirrors the version string (`v1` → `Service/v1`). A version without its own class is served by the unversioned class (`App\Service\ArticlesService`), and only when there is none by `FallbackService`. A URL without a version is served as `Api.defaultVersion` when it is set, and by the unversioned classes when it is not. +> +> Options: the default version, and a version without a service class of its own, read the unversioned `Api.Service.` keys and the keys under the version (`Api.Service.v1.`, `Api.Service.v1.default`). On a conflict the keys under the version win. In action options, list values such as `sortableFields` are joined; in service `options`, a key under the version replaces the unversioned key whole, an `Extension` list included. A version with its own service class reads only the keys under its version, unless it is the default version. `Api.Service.default` applies to all of them. -`/api/describe` and `/api/list` also honor the version prefix when versioning is enabled. +`/api/describe` and `/api/listing` also honor the version prefix when versioning is enabled. ## Model & JWT Refresh Tokens @@ -1164,7 +1281,7 @@ The plugin ships two ORM tables: | Table | Purpose | | --- | --- | | `jwt_refresh_tokens` | Persists refresh tokens (`model`, `foreign_key`, `token`, `expired`); the `token` is hidden from JSON serialization. | -| `auth_store` | Stores serialized authentication state (used by the Webauthn adapters); the `store` column is typed as JSON. | +| `auth_store` | Keeps the challenge of a WebAuthn registration or login between its two requests, under the bearer token; the `store` column is typed as JSON. | > [!NOTE] > `AuthStore`'s validator uses `scalar('store')`, so array payloads are rejected by the standard marshalling path — pass a scalar (e.g. a JSON string) or save with `['validate' => false]`. @@ -1172,13 +1289,13 @@ The plugin ships two ORM tables: ## Testing -The plugin ships an `IntegrationTestCase` that boots the real HTTP stack. The test application under `tests/App` provides sample services (`ArticlesService`, `PostsService`, `TagsService`) and fixtures. +The plugin ships `CakeDC\Api\TestSuite\IntegrationTestCase`, which boots the real HTTP stack. The example below is a test of the plugin's own suite: `ConfigTrait`, `Settings`, the fixtures and the test application under `tests/App` (`ArticlesService`, `PostsService`) are not installed with the package. In your application, use your own fixtures and a `config/api.php`, which `sendRequest()` loads. ```php sendRequest('/articles', 'POST', ['title' => '']); $result = $this->getJsonResponse(); $this->assertError($result, 422); - $this->assertErrorMessage($result, 'Validation failed'); + $this->assertErrorMessage($result, 'Validation on Articles failed'); } } ``` @@ -1240,12 +1358,17 @@ bin/cake service routes articles Output (as a console table): ``` -+--------------+-------------+------------------+----------+--------+----------+ -| Route name | Method(s) | URI template | Service | Action | Plugin | -+--------------+-------------+------------------+----------+--------+----------+ -| | GET, POST | /articles | articles | index | | -| | GET, PUT, DELETE | /articles/:id | articles | view | | -+--------------+-------------+------------------+----------+--------+----------+ ++-------------------+------------+----------------+----------+----------+--------+ +| Route name | Method(s) | URI template | Service | Action | Plugin | ++-------------------+------------+----------------+----------+----------+--------+ +| articles:view | GET | /articles/{id} | articles | view | | +| articles:edit | PUT, PATCH | /articles/{id} | articles | edit | | +| articles:delete | DELETE | /articles/{id} | articles | delete | | +| articles:describe | OPTIONS | /articles/{id} | articles | describe | | +| articles:index | GET | /articles | articles | index | | +| articles:add | POST | /articles | articles | add | | +| articles:describe | OPTIONS | /articles | articles | describe | | ++-------------------+------------+----------------+----------+----------+--------+ ``` Options: @@ -1263,7 +1386,8 @@ The following components originate from the CakePHP 2/3 era. They are **kept** b | Component | Status | | --- | --- | -| `CakeDC\Api\Service\Auth\Auth` (`allow`/`deny`) | Old Cake2-style auth layer. | -| `Middleware\RequestHandlerMiddleware` | Deprecated no-op subclass of `BodyParserMiddleware`; use `BodyParserMiddleware` directly. | +| `CakeDC\Api\Service\Auth\Auth` (`allow`/`deny`), `Action::$Auth` | Old Cake2-style auth layer. Deprecated in 14.0.0, removed in 15.0.0. `allow()` never controlled access; use `bypassAuth` rules in `api_permissions.php`. | +| `CakeDC\Api\Service\Auth\AuthenticateTrait` | Used only by `Auth`. Deprecated in 14.0.0; use `Action::getIdentity()`. | +| `CakeDC\Api\Service\Action\Extension\AuthenticationExtension` | Per-action authentication, duplicated by the `AuthenticationMiddleware`. Deprecated in 14.0.0. | Do not remove these without a major-version compatibility plan. diff --git a/patches/endroid-qr-code-nullable.patch b/patches/endroid-qr-code-nullable.patch deleted file mode 100644 index 79e7d969..00000000 --- a/patches/endroid-qr-code-nullable.patch +++ /dev/null @@ -1,22 +0,0 @@ -diff --git a/src/QrCode.php b/src/QrCode.php ---- a/src/QrCode.php -+++ b/src/QrCode.php -@@ -23,13 +23,13 @@ final class QrCode implements QrCodeInterface - - public function __construct( - private string $data, -- EncodingInterface $encoding = null, -- ErrorCorrectionLevelInterface $errorCorrectionLevel = null, -+ ?EncodingInterface $encoding = null, -+ ?ErrorCorrectionLevelInterface $errorCorrectionLevel = null, - private int $size = 300, - private int $margin = 10, -- RoundBlockSizeModeInterface $roundBlockSizeMode = null, -- ColorInterface $foregroundColor = null, -- ColorInterface $backgroundColor = null -+ ?RoundBlockSizeModeInterface $roundBlockSizeMode = null, -+ ?ColorInterface $foregroundColor = null, -+ ?ColorInterface $backgroundColor = null - ) { - $this->encoding = $encoding ?? new Encoding('UTF-8'); - $this->errorCorrectionLevel = $errorCorrectionLevel ?? new ErrorCorrectionLevelLow(); diff --git a/patches/flysystem-nullable.patch b/patches/flysystem-nullable.patch deleted file mode 100644 index 5d30da6a..00000000 --- a/patches/flysystem-nullable.patch +++ /dev/null @@ -1,72 +0,0 @@ -diff --git a/src/FileExistsException.php b/src/FileExistsException.php ---- a/src/FileExistsException.php -+++ b/src/FileExistsException.php -@@ -18,7 +18,7 @@ class FileExistsException extends Exception - * @param int $code - * @param BaseException $previous - */ -- public function __construct($path, $code = 0, BaseException $previous = null) -+ public function __construct($path, $code = 0, ?BaseException $previous = null) - { - $this->path = $path; - -diff --git a/src/FileNotFoundException.php b/src/FileNotFoundException.php ---- a/src/FileNotFoundException.php -+++ b/src/FileNotFoundException.php -@@ -18,7 +18,7 @@ class FileNotFoundException extends Exception - * @param int $code - * @param \Exception $previous - */ -- public function __construct($path, $code = 0, BaseException $previous = null) -+ public function __construct($path, $code = 0, ?BaseException $previous = null) - { - $this->path = $path; - -diff --git a/src/Filesystem.php b/src/Filesystem.php ---- a/src/Filesystem.php -+++ b/src/Filesystem.php -@@ -360,7 +360,7 @@ class Filesystem implements FilesystemInterface - /** - * @inheritdoc - */ -- public function get($path, Handler $handler = null) -+ public function get($path, ?Handler $handler = null) - { - $path = Util::normalizePath($path); - -diff --git a/src/FilesystemInterface.php b/src/FilesystemInterface.php ---- a/src/FilesystemInterface.php -+++ b/src/FilesystemInterface.php -@@ -271,7 +271,7 @@ interface FilesystemInterface - * - * @return Handler Either a file or directory handler. - */ -- public function get($path, Handler $handler = null); -+ public function get($path, ?Handler $handler = null); - - /** - * Register a plugin. -diff --git a/src/Handler.php b/src/Handler.php ---- a/src/Handler.php -+++ b/src/Handler.php -@@ -25,7 +25,7 @@ abstract class Handler - * @param FilesystemInterface $filesystem - * @param string $path - */ -- public function __construct(FilesystemInterface $filesystem = null, $path = null) -+ public function __construct(?FilesystemInterface $filesystem = null, $path = null) - { - $this->path = $path; - $this->filesystem = $filesystem; -diff --git a/src/MountManager.php b/src/MountManager.php ---- a/src/MountManager.php -+++ b/src/MountManager.php -@@ -639,7 +639,7 @@ class MountManager implements FilesystemInterface - * - * @return Handler Either a file or directory handler. - */ -- public function get($path, Handler $handler = null) -+ public function get($path, ?Handler $handler = null) - { - list($prefix, $path) = $this->getPrefixAndPath($path); - diff --git a/patches/flysystem-vfs-null-str-replace.patch b/patches/flysystem-vfs-null-str-replace.patch deleted file mode 100644 index 67a6aec2..00000000 --- a/patches/flysystem-vfs-null-str-replace.patch +++ /dev/null @@ -1,11 +0,0 @@ ---- a/src/VfsAdapter.php -+++ b/src/VfsAdapter.php -@@ -106,7 +106,7 @@ class VfsAdapter extends Local - protected function wrapPath($path) - { - $scheme = $this->vfs->scheme().'://'; -- $path = str_replace($scheme, null, $path); -+ $path = str_replace($scheme, '', $path ?? ''); - - return $scheme.$path; - } diff --git a/phpcs.xml b/phpcs.xml index e3455f8c..cd8270fc 100644 --- a/phpcs.xml +++ b/phpcs.xml @@ -1,17 +1,29 @@ - - CakePHP Explorator Plugin coding standard - - + + + - - - - - */src/Controller/* + + + + 0 + + + 0 - - templates/* + + 0 + + config/rector/ + src/ + tests/ + + + tests/TestCase/Rector/Fixture/* diff --git a/phpcs.xml.dist b/phpcs.xml.dist deleted file mode 100644 index df121698..00000000 --- a/phpcs.xml.dist +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 06e218f7..8016035f 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,13 +1,4 @@ - diff --git a/psalm.xml b/psalm.xml deleted file mode 100644 index ec8486af..00000000 --- a/psalm.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/rector.php b/rector.php index a996ff24..ff091d9b 100644 --- a/rector.php +++ b/rector.php @@ -4,11 +4,9 @@ use Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector; use Rector\Config\RectorConfig; -use Rector\CodingStyle\Rector\Stmt\NewlineAfterStatementRector; use Rector\DeadCode\Rector\ClassMethod\RemoveNullTagValueNodeRector; use Rector\DeadCode\Rector\For_\RemoveDeadIfForeachForRector; use Rector\DeadCode\Rector\For_\RemoveDeadLoopRector; -use Rector\DeadCode\Rector\ClassMethod\RemoveDuplicatedReturnSelfDocblockRector; use Rector\DeadCode\Rector\ClassMethod\RemoveMixedDocblockOverruledByNativeTypeRector; use Rector\DeadCode\Rector\ClassMethod\RemoveReturnTagIncompatibleWithNativeTypeRector; use Rector\DeadCode\Rector\ClassMethod\RemoveUselessParamTagRector; @@ -18,12 +16,6 @@ use Rector\Php70\Rector\StmtsAwareInterface\IfIssetToCoalescingRector; use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector; use Rector\Php81\Rector\Property\ReadOnlyPropertyRector; -use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector; -use Rector\TypeDeclaration\Rector\ClassMethod\ReturnNeverTypeRector; -use Rector\TypeDeclaration\Rector\ClassMethod\ReturnTypeFromStrictFluentReturnRector; -use Rector\TypeDeclaration\Rector\FuncCall\AddArrayFunctionClosureParamTypeRector; -use Rector\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayMapRector; -use Rector\TypeDeclaration\Rector\FunctionLike\AddClosureParamTypeForArrayReduceRector; use Rector\TypeDeclaration\Rector\StmtsAwareInterface\SafeDeclareStrictTypesRector; return RectorConfig::configure() @@ -33,35 +25,27 @@ ]) ->withSkip([ ReadOnlyPropertyRector::class, - DisallowedEmptyRuleFixerRector::class, ClassPropertyAssignToConstructorPromotionRector::class, - AddClosureParamTypeForArrayMapRector::class, - AddClosureParamTypeForArrayReduceRector::class, - AddArrayFunctionClosureParamTypeRector::class, RemoveDeadLoopRector::class, RemoveDeadIfForeachForRector::class, RemoveUselessReturnTagRector::class, RemoveUselessParamTagRector::class, RemoveUselessVarTagRector::class, RemoveUselessUnionReturnDocblockRector::class, - RemoveDuplicatedReturnSelfDocblockRector::class, RemoveMixedDocblockOverruledByNativeTypeRector::class, RemoveReturnTagIncompatibleWithNativeTypeRector::class, // conflicts with phpcs: cs requires a @return tag, this rule removes @return null RemoveNullTagValueNodeRector::class, - ReturnTypeFromStrictFluentReturnRector::class, - ReturnNeverTypeRector::class, SafeDeclareStrictTypesRector::class, IssetOnPropertyObjectToPropertyExistsRector::class, IfIssetToCoalescingRector::class, - // conflicts with phpcbf on Windows: blank-line churn (144 files in dry-run) - NewlineAfterStatementRector::class, ]) ->withPreparedSets( deadCode: true, codeQuality: true, codingStyle: true, - typeDeclarations: true, - earlyReturn: true, + // Off for the same reason as the native type sniffs in phpcs.xml: adding native types to + // public plugin classes breaks app subclasses. Enable it in the next major version. + typeDeclarations: false, ) ->withPhpSets(php81: true); diff --git a/src/ApiInitializer.php b/src/ApiInitializer.php index 3a0d5ade..ed9253f5 100644 --- a/src/ApiInitializer.php +++ b/src/ApiInitializer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api; @@ -89,7 +89,7 @@ public function getAuthorizationService(ServerRequestInterface $request): ASI new RbacPolicy([ 'adapter' => $rbac, ]), - ]) + ]), ); $orm = new OrmResolver(); diff --git a/src/ApiPlugin.php b/src/ApiPlugin.php index d08a81e4..84a0abd4 100644 --- a/src/ApiPlugin.php +++ b/src/ApiPlugin.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api; @@ -17,7 +17,11 @@ use Cake\Core\BasePlugin; use Cake\Core\Configure; use Cake\Core\ContainerInterface; +use Cake\Routing\RouteBuilder; use CakeDC\Api\Command\ServiceRoutesCommand; +use Closure; +use Override; +use Psr\Http\Server\MiddlewareInterface; /** * Api plugin @@ -29,8 +33,8 @@ class ApiPlugin extends BasePlugin /** * @inheritDoc */ - #[\Override] - public function routes(\Cake\Routing\RouteBuilder $routes): void + #[Override] + public function routes(RouteBuilder $routes): void { $middlewares = Configure::read('Api.Middleware', []); foreach ($middlewares as $alias => $middleware) { @@ -66,7 +70,7 @@ public function routes(\Cake\Routing\RouteBuilder $routes): void * @param string $class Middleware class instance. * @return void */ - protected function registerMiddleware($routes, string $alias, \Psr\Http\Server\MiddlewareInterface|\Closure|string $class): void + protected function registerMiddleware($routes, string $alias, MiddlewareInterface|Closure|string $class): void { $routes->registerMiddleware($alias, $class); $this->middlewares[$alias] = $class; @@ -91,7 +95,7 @@ public function services(ContainerInterface $container): void * @param \Cake\Console\CommandCollection $commands The command collection to update * @return \Cake\Console\CommandCollection */ - #[\Override] + #[Override] public function console(CommandCollection $commands): CommandCollection { return $commands->add('service routes', ServiceRoutesCommand::class); diff --git a/src/Command/ServiceRoutesCommand.php b/src/Command/ServiceRoutesCommand.php index ff1781da..685b0637 100644 --- a/src/Command/ServiceRoutesCommand.php +++ b/src/Command/ServiceRoutesCommand.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2024, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2024, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Command; @@ -18,6 +18,7 @@ use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use CakeDC\Api\Service\ServiceRegistry; +use Override; /** * Provides interactive CLI tools for CakeDC Api routing. @@ -27,7 +28,7 @@ class ServiceRoutesCommand extends Command /** * @inheritDoc */ - #[\Override] + #[Override] public static function defaultName(): string { return 'service routes'; @@ -39,7 +40,7 @@ public static function defaultName(): string * @param \Cake\Console\ConsoleOptionParser $parser The option parser to update * @return \Cake\Console\ConsoleOptionParser */ - #[\Override] + #[Override] protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser { $parser = parent::buildOptionParser($parser); @@ -48,6 +49,11 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption 'help' => __('The name of the service to display routes for.'), 'required' => true, ]); + $parser->addOption('sort', [ + 'help' => __('Sorts alphabetically by route name A-Z'), + 'short' => 's', + 'boolean' => true, + ]); return $parser; } @@ -93,9 +99,7 @@ public function execute(Arguments $args, ConsoleIo $io): ?int $output[] = $item; foreach ($methods as $method) { - if (!isset($duplicateRoutesCounter[$route->template][$method])) { - $duplicateRoutesCounter[$route->template][$method] = 0; - } + $duplicateRoutesCounter[$route->template][$method] ??= 0; $duplicateRoutesCounter[$route->template][$method]++; } @@ -123,12 +127,11 @@ public function execute(Arguments $args, ConsoleIo $io): ?int ) { $duplicateRoutes[] = [ $route->options['_name'] ?? $route->getName(), + implode(', ', $methods), $route->template, - $route->defaults['plugin'] ?? '', - $route->defaults['prefix'] ?? '', $route->defaults['controller'] ?? '', $route->defaults['action'] ?? '', - implode(', ', $methods), + $route->defaults['plugin'] ?? '', ]; break; @@ -137,7 +140,7 @@ public function execute(Arguments $args, ConsoleIo $io): ?int } if ($duplicateRoutes !== []) { - array_unshift($duplicateRoutes, $header); + array_unshift($duplicateRoutes, array_slice($header, 0, 6)); $io->warning('The following possible route collisions were detected.'); $io->helper('table')->output($duplicateRoutes); $io->out(); diff --git a/src/Controller/AppController.php b/src/Controller/AppController.php index 1132838d..01389d50 100644 --- a/src/Controller/AppController.php +++ b/src/Controller/AppController.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Controller; diff --git a/src/Exception/MethodNotAllowedException.php b/src/Exception/MethodNotAllowedException.php index 7c0ee924..fbc91120 100644 --- a/src/Exception/MethodNotAllowedException.php +++ b/src/Exception/MethodNotAllowedException.php @@ -2,24 +2,27 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Exception; +use Cake\Core\Exception\CakeException; +use Throwable; + /** * Class MethodNotAllowedException * Used to configure an exception for a service error. * * @package CakeDC\Api\Exception */ -class MethodNotAllowedException extends \Cake\Core\Exception\CakeException +class MethodNotAllowedException extends CakeException { /** * MethodNotAllowedException constructor. @@ -28,7 +31,7 @@ class MethodNotAllowedException extends \Cake\Core\Exception\CakeException * @param int $code The code of the error * @param \Exception|null $previous the previous exception. */ - public function __construct(array|string|null $message = null, ?int $code = 405, ?\Throwable $previous = null) + public function __construct(array|string|null $message = null, ?int $code = 405, ?Throwable $previous = null) { if (empty($message)) { $message = 'Method not allowed'; diff --git a/src/Exception/ServiceException.php b/src/Exception/ServiceException.php index 037c30b8..2422385f 100644 --- a/src/Exception/ServiceException.php +++ b/src/Exception/ServiceException.php @@ -2,24 +2,27 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Exception; +use Cake\Core\Exception\CakeException; +use Throwable; + /** * Class ServiceException * Used to configure an exception for a service error. * * @package CakeDC\Api\Exception */ -class ServiceException extends \Cake\Core\Exception\CakeException +class ServiceException extends CakeException { /** * ServiceException constructor. @@ -28,7 +31,7 @@ class ServiceException extends \Cake\Core\Exception\CakeException * @param int $code The code of the error * @param \Exception|null $previous the previous exception. */ - public function __construct(array|string|null $message = null, ?int $code = 500, ?\Throwable $previous = null) + public function __construct(array|string|null $message = null, ?int $code = 500, ?Throwable $previous = null) { if (empty($message)) { $message = 'Service exception'; diff --git a/src/Exception/UnauthenticatedException.php b/src/Exception/UnauthenticatedException.php index 58d514db..ed5cb7e7 100644 --- a/src/Exception/UnauthenticatedException.php +++ b/src/Exception/UnauthenticatedException.php @@ -2,24 +2,27 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Exception; +use Cake\Core\Exception\CakeException; +use Throwable; + /** * Class UnauthenticatedException * Used to configure an exception for a service error. * * @package CakeDC\Api\Exception */ -class UnauthenticatedException extends \Cake\Core\Exception\CakeException +class UnauthenticatedException extends CakeException { /** * UnauthenticatedException constructor. @@ -28,7 +31,7 @@ class UnauthenticatedException extends \Cake\Core\Exception\CakeException * @param int $code The code of the error * @param \Exception|null $previous the previous exception. */ - public function __construct(array|string|null $message = null, ?int $code = 401, ?\Throwable $previous = null) + public function __construct(array|string|null $message = null, ?int $code = 401, ?Throwable $previous = null) { if (empty($message)) { $message = 'Unauthenticated'; diff --git a/src/Exception/UnauthorizedException.php b/src/Exception/UnauthorizedException.php index 3bb18ddd..95621f2e 100644 --- a/src/Exception/UnauthorizedException.php +++ b/src/Exception/UnauthorizedException.php @@ -2,23 +2,26 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Exception; +use Cake\Core\Exception\CakeException; +use Throwable; + /** * Class UnauthorizedException * * @package CakeDC\Api\Exception */ -class UnauthorizedException extends \Cake\Core\Exception\CakeException +class UnauthorizedException extends CakeException { /** * UnauthorizedException constructor. @@ -27,7 +30,7 @@ class UnauthorizedException extends \Cake\Core\Exception\CakeException * @param int $code The code of the error * @param \Exception|null $previous the previous exception. */ - public function __construct(array|string|null $message = null, ?int $code = 403, ?\Throwable $previous = null) + public function __construct(array|string|null $message = null, ?int $code = 403, ?Throwable $previous = null) { if (empty($message)) { $message = 'Unauthorized'; diff --git a/src/Exception/ValidationException.php b/src/Exception/ValidationException.php index 3ce51df2..34796a1f 100644 --- a/src/Exception/ValidationException.php +++ b/src/Exception/ValidationException.php @@ -2,17 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Exception; +use Throwable; + /** * Used to return validation errors. */ @@ -36,8 +38,8 @@ class ValidationException extends ServiceException public function __construct( array|string $message = 'Validation errors', ?int $code = 0, - ?\Throwable $previous = null, - array $validationErrors = [] + ?Throwable $previous = null, + array $validationErrors = [], ) { if ($code === 0) { $code = $this->_defaultCode; diff --git a/src/Middleware/ContainerInjectorMiddleware.php b/src/Middleware/ContainerInjectorMiddleware.php index 8edd460e..0b492d65 100644 --- a/src/Middleware/ContainerInjectorMiddleware.php +++ b/src/Middleware/ContainerInjectorMiddleware.php @@ -1,6 +1,16 @@ container instanceof \Cake\Core\ContainerInterface) { + if (!$this->container instanceof ContainerInterface) { $this->container = $request->getAttribute('container'); } $prefix = Configure::read('Api.prefix'); @@ -95,11 +97,19 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface * @param array $matches Matches definition. * @return \Cake\Http\Response|\Psr\Http\Message\ResponseInterface */ - protected function matchRequest(ServerRequestInterface $request, RequestHandlerInterface $handler, array $matches): \Psr\Http\Message\ResponseInterface|\Cake\Http\Response - { + protected function matchRequest( + ServerRequestInterface $request, + RequestHandlerInterface $handler, + array $matches, + ): ResponseInterface|Response { $service = null; $response = null; $version = $matches['version'] ?? null; + $defaultVersion = (string)Configure::read('Api.defaultVersion'); + if ($version === null && Configure::read('Api.useVersioning') && $defaultVersion !== '') { + // a URL without a version is served as the default version, with its options + $version = (Configure::read('Api.versionPrefix') ?: 'v') . $defaultVersion; + } $serviceName = $matches['service']; $url = '/' . $serviceName; @@ -120,7 +130,7 @@ protected function matchRequest(ServerRequestInterface $request, RequestHandlerI ->get($serviceName, $options); $result = $service->dispatchPrepareAction(); - if ($result instanceof \CakeDC\Api\Service\Action\Result) { + if ($result instanceof Result) { $response = $service->respond($result); } else { $request = $request->withAttribute('service', $service); @@ -128,7 +138,7 @@ protected function matchRequest(ServerRequestInterface $request, RequestHandlerI return $handler->handle($request); } } catch (UnauthenticatedException $e) { - if ($service instanceof \CakeDC\Api\Service\Service) { + if ($service instanceof Service) { $service->getResult() ->setCode(401); $service->getResult() @@ -136,15 +146,18 @@ protected function matchRequest(ServerRequestInterface $request, RequestHandlerI $response = $service->respond(); } } catch (Exception $e) { - if ($service instanceof \CakeDC\Api\Service\Service) { - $service->getResult() - ->setCode(400); - $service->getResult() - ->setException($e); - $response = $service->respond(); + if (!$service instanceof Service) { + // the service could not be built, so nothing can render the error as an API answer; + // pass it on, so that the application logs it and answers with its message + throw $e; } + $service->getResult() + ->setCode(400); + $service->getResult() + ->setException($e); + $response = $service->respond(); } - if (!$response instanceof \Cake\Http\Response) { + if (!$response instanceof Response) { return (new Response())->withStatus(400); } diff --git a/src/Middleware/ProcessApiRequestMiddleware.php b/src/Middleware/ProcessApiRequestMiddleware.php index e7026b2e..d743c612 100644 --- a/src/Middleware/ProcessApiRequestMiddleware.php +++ b/src/Middleware/ProcessApiRequestMiddleware.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Middleware; diff --git a/src/Middleware/RequestHandlerMiddleware.php b/src/Middleware/RequestHandlerMiddleware.php deleted file mode 100644 index 0642b62d..00000000 --- a/src/Middleware/RequestHandlerMiddleware.php +++ /dev/null @@ -1,26 +0,0 @@ -getAttribute('service'); if ($service !== null) { - $result = $service->triggerBeforeDispatch(true); + $service->triggerBeforeDispatch(true); if ($exception instanceof ForbiddenException) { $service->getResult()->setCode(403); $service->getResult()->setException(new Exception(__('Forbidden authorization request'), 403)); diff --git a/src/Model/Entity/AuthStore.php b/src/Model/Entity/AuthStore.php index cfbbb60a..5468a2e0 100644 --- a/src/Model/Entity/AuthStore.php +++ b/src/Model/Entity/AuthStore.php @@ -1,6 +1,16 @@ 'user', // Class used to provide the RBAC rules, by default from a config file, must extend AbstractProvider - 'permissions_provider_class' => \CakeDC\Api\Rbac\Permissions\ApiConfigProvider::class, + 'permissions_provider_class' => ApiConfigProvider::class, // Used to set permissions array from configuration, ignoring the permissionsProvider 'permissions' => null, // 'log' will match the value of 'debug' if not set on configuration @@ -72,7 +77,7 @@ class ApiRbac implements RbacInterface /** * A list of rules * - * @var array[] rules array + * @var array rules array */ protected ?array $permissions = null; @@ -83,9 +88,7 @@ class ApiRbac implements RbacInterface */ public function __construct(array $config = []) { - if (!isset($config['log'])) { - $config['log'] = Configure::read('debug'); - } + $config['log'] ??= Configure::read('debug'); $this->setConfig($config); $permissions = $this->getConfig('api_permissions'); if ($permissions !== null) { @@ -94,7 +97,7 @@ public function __construct(array $config = []) $permissionsProviderClass = $this->getConfig('permissions_provider_class'); if (!is_subclass_of($permissionsProviderClass, AbstractProvider::class)) { $message = sprintf('Class "%s" must extend AbstractProvider', $permissionsProviderClass); - throw new \RuntimeException($message); + throw new RuntimeException($message); } $permissionsProvider = new $permissionsProviderClass([ 'autoload_config' => $this->getConfig('autoload_config'), @@ -120,19 +123,54 @@ public function setPermissions(array $permissions): void $this->permissions = $permissions; } + /** + * The role of the user, as the name that the `role` key of the rules is matched against. + * + * A user without a role has the `default_role`. A role from an integer column is its string + * form, and a role mapped to an enum is the value of its case, or the name of a case without + * a value. Any other role cannot be matched: it is logged as a warning and the user gets no + * role, not the default one, so that a rule for the default role does not apply by accident. + * + * @param \ArrayAccess|array $user current user array + * @return string|null The role, or null when it cannot be matched. + */ + protected function userRole(array|ArrayAccess $user): ?string + { + $roleField = (string)$this->getConfig('role_field'); + $role = Hash::get($user, $roleField, $this->getConfig('default_role')); + if ($role instanceof BackedEnum) { + return (string)$role->value; + } + if ($role instanceof UnitEnum) { + return $role->name; + } + if (is_scalar($role) || $role instanceof Stringable) { + return (string)$role; + } + $this->log(sprintf( + 'The role field `%s` of the user holds a value of type %s, which no permission rule can match; ' + . 'access is denied', + $roleField, + get_debug_type($role), + ), LogLevel::WARNING); + + return null; + } + /** * Match against permissions, return if matched * Permissions are processed based on the 'permissions' config values * - * @param array|\ArrayAccess $user current user array + * @param \ArrayAccess|array $user current user array * @param \Psr\Http\Message\ServerRequestInterface $request request * @return bool true if there is a match in permissions */ public function checkPermissions(array|ArrayAccess $user, ServerRequestInterface $request): bool { - $roleField = $this->getConfig('role_field'); - $defaultRole = $this->getConfig('default_role'); - $role = Hash::get($user, $roleField, $defaultRole); + $role = $this->userRole($user); + if ($role === null) { + return false; + } if ($this->permissions === null) { return false; @@ -140,7 +178,7 @@ public function checkPermissions(array|ArrayAccess $user, ServerRequestInterface foreach ($this->permissions as $permission) { $matchResult = $this->matchPermission($permission, $user, $role, $request); - if ($matchResult instanceof \CakeDC\Auth\Rbac\PermissionMatchResult) { + if ($matchResult instanceof PermissionMatchResult) { if ($this->getConfig('log')) { $this->log($matchResult->getReason(), LogLevel::DEBUG); } @@ -156,14 +194,18 @@ public function checkPermissions(array|ArrayAccess $user, ServerRequestInterface * Match the rule for current permission * * @param array $permission The permission configuration - * @param array|\ArrayAccess $user Current user data + * @param \ArrayAccess|array $user Current user data * @param string $role Effective user's role * @param \Psr\Http\Message\ServerRequestInterface $request Current request - * @return null|\CakeDC\Auth\Rbac\PermissionMatchResult Null if permission is discarded, PermissionMatchResult if a final + * @return \CakeDC\Auth\Rbac\PermissionMatchResult|null Null if permission is discarded, PermissionMatchResult if a final * result is produced */ - protected function matchPermission(array $permission, array|\ArrayAccess $user, string $role, ServerRequestInterface $request): ?\CakeDC\Auth\Rbac\PermissionMatchResult - { + protected function matchPermission( + array $permission, + array|ArrayAccess $user, + string $role, + ServerRequestInterface $request, + ): ?PermissionMatchResult { $issetService = isset($permission['service']) || isset($permission['*service']); $issetAction = isset($permission['action']) || isset($permission['*action']); $issetUser = isset($permission['user']) || isset($permission['*user']); @@ -197,9 +239,9 @@ protected function matchPermission(array $permission, array|\ArrayAccess $user, ]; foreach ($permission as $key => $value) { - $inverse = $this->startsWith($key, '*'); + $inverse = is_string($key) && $this->startsWith($key, '*'); if ($inverse) { - $key = ltrim((string)$key, '*'); + $key = ltrim($key, '*'); } if (is_callable($value)) { @@ -237,7 +279,7 @@ protected function matchPermission(array $permission, array|\ArrayAccess $user, 'For %s --> Rule matched %s with result = %s', json_encode($reserved, JSON_THROW_ON_ERROR), json_encode($permission, JSON_THROW_ON_ERROR), - $return + $return, ); return new PermissionMatchResult($return, $reason); @@ -275,8 +317,8 @@ protected function terminalKeysLast(array $permission): array /** * Check if rule matched or '*' present in rule matching anything * - * @param string|array|null $possibleValues Values that are accepted (from permission config) - * @param string|mixed|null $value Value to check with. We'll check the 'dasherized' value too + * @param array|string|null $possibleValues Values that are accepted (from permission config) + * @param mixed|string|null $value Value to check with. We'll check the 'dasherized' value too * @param bool $allowEmpty If true and $value is null, the rule will pass * @return bool */ diff --git a/src/Rbac/CachedApiRbac.php b/src/Rbac/CachedApiRbac.php index 2a464f4c..202c44bd 100644 --- a/src/Rbac/CachedApiRbac.php +++ b/src/Rbac/CachedApiRbac.php @@ -2,19 +2,21 @@ declare(strict_types=1); /** - * Copyright 2010 - 2025, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2025, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Rbac; +use ArrayAccess; use Cake\Cache\Cache; -use Cake\Utility\Hash; +use CakeDC\Auth\Rbac\PermissionMatchResult; +use Override; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LogLevel; @@ -28,7 +30,7 @@ class CachedApiRbac extends ApiRbac { /** * Prefix of the cache key of the permissions map. The key also depends on the rules, so a changed - * rule list builds a new map, and maps cached by earlier versions are not read. + * rule list builds a new map, and maps cached by older versions are not read. */ public const CACHE_KEY = 'api_permissions_map_ordered'; @@ -54,7 +56,7 @@ public function __construct(array $config = []) * @param array $permissions permissions * @return void */ - #[\Override] + #[Override] public function setPermissions(array $permissions): void { parent::setPermissions($permissions); @@ -68,8 +70,11 @@ public function setPermissions(array $permissions): void */ protected function loadPermissionsMap(): void { - $key = static::cacheKey((array)$this->permissions); - $this->permissionsMap = Cache::remember($key, fn(): array => $this->buildPermissionsMap(), '_cakedc_api_auth_'); + $this->permissionsMap = Cache::remember( + static::cacheKey((array)$this->permissions), + fn(): array => $this->buildPermissionsMap(), + '_cakedc_api_auth_', + ); } /** @@ -92,7 +97,7 @@ public static function cacheKey(array $permissions): string * @param mixed $value Rule list, rule or rule value. * @return mixed */ - protected static function keyData($value): mixed + protected static function keyData(mixed $value): mixed { if (is_object($value)) { return ['__object' => $value::class]; @@ -108,7 +113,7 @@ protected static function keyData($value): mixed * Build permissions map for caching * * The map holds the position of each rule in the permissions list, not the rule, so the rules are - * always read from the current list. + * always read from the current list, in the same order as ApiRbac checks them. * * @return array>> */ @@ -118,7 +123,8 @@ public function buildPermissionsMap(): array if ($default !== null && !array_key_exists($key, $permission)) { return [$default, '_']; } - if (!array_key_exists($key, $permission) || $permission[$key] == false || $permission[$key] == null) { + // the loose comparison also covers null, an empty string and an empty array + if (!array_key_exists($key, $permission) || $permission[$key] == false) { return ['_']; } $item = $permission[$key]; @@ -136,7 +142,7 @@ public function buildPermissionsMap(): array $this->log(sprintf( 'Permission rule %d has no `service` or `action`, or has a `user` key: ' . 'it denies every request that reaches it', - $index + 1 + $index + 1, ), LogLevel::WARNING); } if (!$this->isIndexable($permission)) { @@ -159,16 +165,17 @@ public function buildPermissionsMap(): array /** * Match against permissions using cached map * - * @param array|\ArrayAccess $user current user array + * @param \ArrayAccess|array $user current user array * @param \Psr\Http\Message\ServerRequestInterface $request request * @return bool true if there is a match in permissions */ - #[\Override] - public function checkPermissions(array|\ArrayAccess $user, ServerRequestInterface $request): bool + #[Override] + public function checkPermissions(array|ArrayAccess $user, ServerRequestInterface $request): bool { - $roleField = $this->getConfig('role_field'); - $defaultRole = $this->getConfig('default_role'); - $role = Hash::get($user, $roleField, $defaultRole); + $role = $this->userRole($user); + if ($role === null) { + return false; + } $service = $request->getAttribute('service'); if ($service === null) { @@ -176,24 +183,15 @@ public function checkPermissions(array|\ArrayAccess $user, ServerRequestInterfac } $target = (array)$request->getAttribute(self::TARGET_ATTRIBUTE); - $candidates = $target['service'] ?? null; - if ($candidates === null) { - // ApiRbac checks the service of the action, which is the inner service on nested routes - $candidates = [$service->getName()]; - $action = $service->getAction(); - if ($action !== null) { - $candidates[] = $action->getService()->getName(); - } - } - $candidates = (array)$candidates; + // ApiRbac checks the service of the action, which is the inner service on nested routes + $candidates = (array)($target['service'] + ?? [$service->getName(), $service->getAction()->getService()->getName()]); - // the map only narrows down the rules; each one is still matched, in the order of the - // permissions list, so the first matching rule decides as in ApiRbac + // the map only narrows down the rules; matchPermission() still checks each one, in the + // order of the permissions list, so the first matching rule decides as in ApiRbac $rules = []; - // a role that is not a plain name, such as a list of roles, is left to the rule matching - $anyRole = !is_string($role) && !is_int($role); foreach ($this->permissionsMap as $mapRole => $services) { - if (!$anyRole && !$this->matchOrAsterisk((string)$mapRole, $role, true)) { + if (!$this->matchOrAsterisk((string)$mapRole, $role, true)) { continue; } foreach ($services as $mapService => $serviceRules) { @@ -211,7 +209,7 @@ public function checkPermissions(array|\ArrayAccess $user, ServerRequestInterfac } $permission = $permissions[$index]; $matchResult = $this->matchPermission($permission, $user, $role, $request); - if ($matchResult instanceof \CakeDC\Auth\Rbac\PermissionMatchResult) { + if ($matchResult instanceof PermissionMatchResult) { if ($this->getConfig('log')) { $this->log($matchResult->getReason(), LogLevel::DEBUG); } @@ -226,8 +224,8 @@ public function checkPermissions(array|\ArrayAccess $user, ServerRequestInterfac /** * Whether a rule can be stored under its role and service keys. * - * Rules that ApiRbac refuses for every request (no `service` or `action`, or a `user` key), and - * rules whose role or service is not a plain name, such as a callable, are not. + * Rules that ApiRbac refuses for every request, and rules whose role or service is not a plain + * name, such as a callable or a Rule, are not. * * @param array $permission Permission rule. * @return bool @@ -242,12 +240,9 @@ protected function isIndexable(array $permission): bool continue; } $value = $permission[$key]; - // a `className` array is a Rule, which ApiRbac evaluates for every request - if (is_array($value) && isset($value['className'])) { - return false; - } - // so is a callable, including a function name such as `'file'` - if (is_callable($value)) { + // a `className` array is a Rule, and a callable (a function name such as `'file'` too) is + // called: ApiRbac evaluates both for every request + if ((is_array($value) && isset($value['className'])) || is_callable($value)) { return false; } foreach (is_array($value) ? $value : [$value] as $name) { @@ -279,10 +274,10 @@ protected function isRefused(array $permission): bool * Whether rules stored under a service key can apply to one of the service names. * * Uses the same comparison as ApiRbac, so `Auth` matches the `auth` service. Rules with an - * empty service (key `_`) are kept and left to the rule matching. + * empty service (key `_`) are kept and left to matchPermission(). * * @param string $mapService Service key of the map. - * @param array $candidates Service names of the request. + * @param array $candidates Service names of the request. * @return bool */ protected function matchesAnyService(string $mapService, array $candidates): bool diff --git a/src/Rbac/Permissions/AbstractProvider.php b/src/Rbac/Permissions/AbstractProvider.php index 41f52992..0284dfb4 100644 --- a/src/Rbac/Permissions/AbstractProvider.php +++ b/src/Rbac/Permissions/AbstractProvider.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Rbac\Permissions; diff --git a/src/Rbac/Permissions/ApiConfigProvider.php b/src/Rbac/Permissions/ApiConfigProvider.php index ca208746..931c0de4 100644 --- a/src/Rbac/Permissions/ApiConfigProvider.php +++ b/src/Rbac/Permissions/ApiConfigProvider.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Rbac\Permissions; use Cake\Core\Configure; +use Exception; use Psr\Log\LogLevel; /** @@ -59,7 +60,7 @@ protected function loadPermissions(string $key): array try { Configure::load($key, 'default'); $permissions = Configure::read('CakeDC/Auth.api_permissions'); - } catch (\Exception) { + } catch (Exception) { $msg = sprintf('Missing configuration file: "config/%s.php". Using default permissions', $key); $this->log($msg, LogLevel::WARNING); } diff --git a/src/Rbac/Rules/TwoFactorPassedScope.php b/src/Rbac/Rules/TwoFactorPassedScope.php index af4e7336..627c6e53 100644 --- a/src/Rbac/Rules/TwoFactorPassedScope.php +++ b/src/Rbac/Rules/TwoFactorPassedScope.php @@ -2,16 +2,17 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Rbac\Rules; +use ArrayAccess; use Authentication\Authenticator\JwtAuthenticator; use Cake\Routing\Router; use CakeDC\Auth\Rbac\Rules\AbstractRule; @@ -28,7 +29,7 @@ class TwoFactorPassedScope extends AbstractRule /** * @inheritDoc */ - public function allowed(array|\ArrayAccess $user, string $role, ServerRequestInterface $request): bool + public function allowed(array|ArrayAccess $user, string $role, ServerRequestInterface $request): bool { $authentication = $request->getAttribute('authentication'); if ($authentication === null) { diff --git a/src/Rbac/Rules/TwoFactorScope.php b/src/Rbac/Rules/TwoFactorScope.php index 7b96faca..53cdf088 100644 --- a/src/Rbac/Rules/TwoFactorScope.php +++ b/src/Rbac/Rules/TwoFactorScope.php @@ -2,16 +2,17 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Rbac\Rules; +use ArrayAccess; use Authentication\Authenticator\JwtAuthenticator; use Cake\Routing\Router; use CakeDC\Auth\Rbac\Rules\AbstractRule; @@ -28,7 +29,7 @@ class TwoFactorScope extends AbstractRule /** * @inheritDoc */ - public function allowed(array|\ArrayAccess $user, string $role, ServerRequestInterface $request): bool + public function allowed(array|ArrayAccess $user, string $role, ServerRequestInterface $request): bool { $authentication = $request->getAttribute('authentication'); if ($authentication === null) { diff --git a/src/Routing/ApiRouteBuilder.php b/src/Routing/ApiRouteBuilder.php new file mode 100644 index 00000000..67e46104 --- /dev/null +++ b/src/Routing/ApiRouteBuilder.php @@ -0,0 +1,153 @@ + + */ + protected const array RESOURCE_KEYS = ['method', 'path', 'action']; + + /** + * Keys of a `map` entry that are route options rather than route defaults. + * + * @var list + */ + protected const array ROUTE_OPTION_KEYS = ['patterns', 'pass', 'name']; + + /** + * Generate REST resource routes for the given controller(s). + * + * When a `map` entry carries route options, every route of the resource is + * connected on its own, in the order `RouteBuilder::resources()` connects them. + * + * @param string $name A controller name to connect resource routes for. + * @param \Closure|array $options Options to use when generating REST routes, or a callback. + * @param \Closure|null $callback An optional callback to be executed in a nested scope. + * @return $this + */ + #[Override] + public function resources(string $name, Closure|array $options = [], ?Closure $callback = null) + { + if (!is_array($options) || !$this->hasRouteOptions((array)($options['map'] ?? []))) { + return parent::resources($name, $options, $callback); + } + + $options += [ + 'connectOptions' => [], + 'inflect' => 'dasherize', + 'only' => [], + 'path' => null, + ]; + $resourceMap = array_merge(static::$_resourceMap, $options['map']); + $only = (array)$options['only']; + if ($only === []) { + $only = array_keys($resourceMap); + } + + foreach (array_keys($resourceMap) as $alias) { + if (in_array($alias, $only, true)) { + $this->connectResource($name, (string)$alias, $options); + } + } + + if ($callback instanceof Closure) { + $path = $options['path']; + if (empty($path)) { + $method = $options['inflect']; + $path = Inflector::$method($name); + } + $idName = Inflector::singularize(Inflector::underscore($name)) . '_id'; + $this->scope('/' . $path . '/{' . $idName . '}', [], $callback); + } + + return $this; + } + + /** + * Check whether any `map` entry carries route options. + * + * @param array $map Resource map. + * @return bool + */ + protected function hasRouteOptions(array $map): bool + { + foreach ($map as $entry) { + if (array_diff_key((array)$entry, array_flip(static::RESOURCE_KEYS)) !== []) { + return true; + } + } + + return false; + } + + /** + * Connect one route of a resource with the route options of its `map` entry. + * + * @param string $name A controller name to connect resource routes for. + * @param string $alias Resource map key. + * @param array $options Resource options. + * @return void + */ + protected function connectResource(string $name, string $alias, array $options): void + { + $entry = (array)($options['map'][$alias] ?? []); + $resource = ['only' => [$alias], 'map' => []] + $options; + if (isset($options['map'][$alias])) { + $resource['map'] = [$alias => array_intersect_key($entry, array_flip(static::RESOURCE_KEYS))]; + } + + $connectOptions = (array)($entry['patterns'] ?? []); + if (isset($entry['pass'])) { + $connectOptions['pass'] = (array)$entry['pass']; + } + if (isset($entry['name'])) { + $connectOptions['_name'] = $entry['name']; + } + $resource['connectOptions'] = $connectOptions + $options['connectOptions']; + + $defaults = array_diff_key($entry, array_flip([...static::RESOURCE_KEYS, ...static::ROUTE_OPTION_KEYS])); + if ($defaults === []) { + parent::resources($name, $resource); + + return; + } + + $this->scope('/', $defaults, function (RouteBuilder $routes) use ($name, $resource): void { + $routes->resources($name, $resource); + }); + } +} diff --git a/src/Routing/ApiRouter.php b/src/Routing/ApiRouter.php index 2b5f17f2..86372fe0 100644 --- a/src/Routing/ApiRouter.php +++ b/src/Routing/ApiRouter.php @@ -2,21 +2,23 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Routing; use Cake\Http\ServerRequest; use Cake\Routing\Route\Route; +use Cake\Routing\RouteBuilder; use Cake\Routing\RouteCollection; use Cake\Routing\Router; +use Override; /** * Class ApiRouter @@ -144,4 +146,25 @@ class ApiRouter extends Router * @var array */ protected static array $_defaultExtensions = []; + + /** + * Create an ApiRouteBuilder for the provided path. + * + * @param string $path The path to set the builder to. + * @param array $options The options for the builder + * @return \Cake\Routing\RouteBuilder + */ + #[Override] + public static function createRouteBuilder(string $path, array $options = []): RouteBuilder + { + $options += [ + 'routeClass' => static::defaultRouteClass(), + 'extensions' => static::$_defaultExtensions, + ]; + + return new ApiRouteBuilder(static::$_collection, $path, [], [ + 'routeClass' => $options['routeClass'], + 'extensions' => $options['extensions'], + ]); + } } diff --git a/src/Service/Action/Action.php b/src/Service/Action/Action.php index 9ac50259..1c4db9d0 100644 --- a/src/Service/Action/Action.php +++ b/src/Service/Action/Action.php @@ -2,17 +2,18 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; +use AllowDynamicProperties; use Authentication\IdentityInterface; use Cake\Core\InstanceConfigTrait; use Cake\Datasource\EntityInterface; @@ -28,15 +29,20 @@ use CakeDC\Api\Service\Auth\Auth; use CakeDC\Api\Service\Service; use CakeDC\Api\Transformer\TransformerInterface; +use CakeDC\Api\Utility\LegacyMemberGuard; use Exception; +use InvalidArgumentException; use ReflectionMethod; /** * Class Action * + * Attachable extensions are set as properties named after them, such as `$this->Cors`. + * * @package CakeDC\Api\Service\Action * @implements \Cake\Event\EventDispatcherInterface<\CakeDC\Api\Service\Action\Action> */ +#[AllowDynamicProperties] abstract class Action implements EventListenerInterface, EventDispatcherInterface { /** @@ -56,8 +62,10 @@ abstract class Action implements EventListenerInterface, EventDispatcherInterfac /** * An Auth instance. + * + * @deprecated 14.0.0 See \CakeDC\Api\Service\Auth\Auth. Will be removed in 15.0.0. */ - public ?\CakeDC\Api\Service\Auth\Auth $Auth = null; + public ?Auth $Auth = null; /** * Default Action options. @@ -79,7 +87,7 @@ abstract class Action implements EventListenerInterface, EventDispatcherInterfac /** * Extension registry. */ - protected ?\CakeDC\Api\Service\Action\ExtensionRegistry $_extensions = null; + protected ?ExtensionRegistry $_extensions = null; /** * Action name. @@ -94,6 +102,7 @@ abstract class Action implements EventListenerInterface, EventDispatcherInterfac */ public function __construct(array $config = []) { + LegacyMemberGuard::check($this, LegacyMemberGuard::ACTION); if (!empty($config['name'])) { $this->setName($config['name']); } @@ -179,7 +188,7 @@ public function setRoute(array $route): self /** * @return \CakeDC\Api\Service\Service */ - public function getService(): \CakeDC\Api\Service\Service + public function getService(): Service { return $this->service; } @@ -363,10 +372,10 @@ public function getIdentity(): mixed */ public function setExtensions(?ExtensionRegistry $extensions = null): self { - if (!$extensions instanceof \CakeDC\Api\Service\Action\ExtensionRegistry && !$this->_extensions instanceof \CakeDC\Api\Service\Action\ExtensionRegistry) { - $this->_extensions = new ExtensionRegistry($this); - } else { + if ($extensions instanceof ExtensionRegistry) { $this->_extensions = $extensions; + } elseif (!$this->_extensions instanceof ExtensionRegistry) { + $this->_extensions = new ExtensionRegistry($this); } return $this; @@ -393,7 +402,8 @@ protected function loadExtensions(): void $extensions = $registry->normalizeArray($this->extensions); foreach ($extensions as $name => $properties) { - $instance = $registry->load($properties['className'], $properties); + // an extension listed without a plugin prefix, such as `Sort`, has no `className` key + $instance = $registry->load((string)$name, $properties); $this->_eventManager->on($instance); if ($instance->attachable()) { [, $prop] = pluginSplit($name); @@ -406,6 +416,7 @@ protected function loadExtensions(): void * Initialize auth. * * @return \CakeDC\Api\Service\Auth\Auth + * @deprecated 14.0.0 See \CakeDC\Api\Service\Auth\Auth. Will be removed in 15.0.0. */ protected function initializeAuth(): Auth { @@ -424,6 +435,7 @@ protected function initializeAuth(): Auth * Prepare Auth configuration. * * @return array + * @deprecated 14.0.0 See \CakeDC\Api\Service\Auth\Auth. Will be removed in 15.0.0. */ protected function authConfig(): array { @@ -454,11 +466,13 @@ protected function authConfig(): array protected function transform($data, string $transformerClass): array { if (!class_exists($transformerClass)) { - throw new \InvalidArgumentException(sprintf('Transformer class %s does not exist', $transformerClass)); + throw new InvalidArgumentException(sprintf('Transformer class %s does not exist', $transformerClass)); } if (!is_subclass_of($transformerClass, TransformerInterface::class)) { - throw new \InvalidArgumentException(sprintf('Transformer class %s must implement ', $transformerClass) . TransformerInterface::class); + throw new InvalidArgumentException( + sprintf('Transformer class %s must implement %s', $transformerClass, TransformerInterface::class), + ); } $transformer = new $transformerClass(); @@ -478,7 +492,7 @@ protected function transform($data, string $transformerClass): array } if (is_array($data)) { - if (array_keys($data) === range(0, count($data) - 1)) { + if (array_is_list($data)) { return $this->transformCollection($data, $transformer); } diff --git a/src/Service/Action/Auth/JwtLoginAction.php b/src/Service/Action/Auth/JwtLoginAction.php index 75e62897..552650d6 100644 --- a/src/Service/Action/Auth/JwtLoginAction.php +++ b/src/Service/Action/Auth/JwtLoginAction.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; use CakeDC\Api\Service\Action\Auth\LoginAction as Action; +use Override; /** * Class LoginAction @@ -31,7 +32,7 @@ class JwtLoginAction extends Action * @param bool $socialLogin is social login * @return array */ - #[\Override] + #[Override] protected function afterIdentifyUser(?array $user, bool $socialLogin = false): array { $user = parent::afterIdentifyUser($user, $socialLogin); diff --git a/src/Service/Action/Auth/JwtRefreshAction.php b/src/Service/Action/Auth/JwtRefreshAction.php index 4995542a..9792d76f 100644 --- a/src/Service/Action/Auth/JwtRefreshAction.php +++ b/src/Service/Action/Auth/JwtRefreshAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -20,6 +20,8 @@ use Cake\ORM\TableRegistry; use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Action; +use InvalidArgumentException; +use Override; /** * Class RefreshAction @@ -35,6 +37,9 @@ class JwtRefreshAction extends Action */ protected $user; + /** + * @var array + */ protected $payload; /** @@ -43,7 +48,7 @@ class JwtRefreshAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); @@ -54,7 +59,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $authHeader = $this->getService()->getRequest()->getHeader('Authorization'); @@ -94,7 +99,7 @@ public function validates(): bool ])->first(); $authHeader = str_ireplace($options['tokenPrefix'] . ' ', '', $authHeader); - if (!$entity || $entity->get('token') != $authHeader) { + if (!$entity || !is_string($authHeader) || !hash_equals((string)$entity->get('token'), $authHeader)) { throw new ValidationException('Invalid token provided', 401); } @@ -105,6 +110,24 @@ public function validates(): bool if (!is_string($this->payload['aud'] ?? null) || $this->payload['aud'] === '') { throw new ValidationException('Invalid token provided', 401); } + // Bound the whole session, not only this refresh token: `auth_time` is set at login and + // carried through every refresh. A token without it predates the claim and is refused. + $maxSessionLifetime = Configure::read('Api.Jwt.RefreshToken.maxSessionLifetime'); + // a value read from an environment variable is a string of digits + if (is_string($maxSessionLifetime) && ctype_digit($maxSessionLifetime)) { + $maxSessionLifetime = (int)$maxSessionLifetime; + } + if ($maxSessionLifetime !== null && $maxSessionLifetime !== false) { + if (!is_int($maxSessionLifetime) || $maxSessionLifetime <= 0) { + throw new InvalidArgumentException( + 'Api.Jwt.RefreshToken.maxSessionLifetime must be null or a positive number of seconds.', + ); + } + $authTime = $this->payload['auth_time'] ?? null; + if (!is_int($authTime) || $authTime + $maxSessionLifetime < time()) { + throw new ValidationException('Invalid token provided', 401); + } + } return true; } @@ -112,7 +135,7 @@ public function validates(): bool /** * Execute action. * - * @return false|array + * @return array|false */ public function execute(): false|array { diff --git a/src/Service/Action/Auth/JwtSocialLoginAction.php b/src/Service/Action/Auth/JwtSocialLoginAction.php index 0e5d3580..ea7346ed 100644 --- a/src/Service/Action/Auth/JwtSocialLoginAction.php +++ b/src/Service/Action/Auth/JwtSocialLoginAction.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; use CakeDC\Api\Service\Action\Auth\SocialLoginAction as Action; +use Override; /** * Class SocialLoginAction @@ -27,10 +28,10 @@ class JwtSocialLoginAction extends Action /** * Execute action. * - * @return false|array + * @return array|false * @throws \Exception */ - #[\Override] + #[Override] public function execute(): false|array { $user = parent::execute(); diff --git a/src/Service/Action/Auth/JwtTokenTrait.php b/src/Service/Action/Auth/JwtTokenTrait.php index 4a6c0657..178caf7c 100644 --- a/src/Service/Action/Auth/JwtTokenTrait.php +++ b/src/Service/Action/Auth/JwtTokenTrait.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -24,9 +24,9 @@ use CakeDC\Api\Service\Auth\TwoFactorAuthentication\Webauthn2fAuthenticationCheckerInterface; use DateInterval; use DateTimeImmutable; -use Lcobucci\JWT\Configuration; -use Lcobucci\JWT\Signer\Hmac\Sha512; -use Lcobucci\JWT\Signer\Key\InMemory; +use Firebase\JWT\JWT; +use InvalidArgumentException; +use SensitiveParameter; /** * JwtTokenTrait @@ -85,9 +85,9 @@ public function generateRefreshTokenResponse(array $user, $payload): array * refresh and requires a payload with a non-empty string `aud`. * @param object|array|null $payload Additional payload data. * @throws \CakeDC\Api\Exception\ValidationException When a refresh payload has no non-empty string audience. - * @return false|string + * @return string|false */ - public function generateAccessToken($user, \DateTimeImmutable $timestamp, $type, $payload = null): false|string + public function generateAccessToken($user, DateTimeImmutable $timestamp, $type, $payload = null): false|string { if (empty($user)) { return false; @@ -96,20 +96,58 @@ public function generateAccessToken($user, \DateTimeImmutable $timestamp, $type, $subject = $user['id']; $audience = $this->getAudience($user, $type, $payload); $issuer = Router::url('/', true); - $signer = new Sha512(); - $secret = Configure::read('Api.Jwt.AccessToken.secret'); - $config = Configuration::forSymmetricSigner($signer, InMemory::plainText($secret)); + return $this->signToken([ + 'iss' => $issuer, + 'iat' => $this->claimDate($timestamp), + 'aud' => $audience, + 'exp' => $this->claimDate($this->accessTokenLifeTime($timestamp)), + 'sub' => (string)$subject, + ], Configure::read('Api.Jwt.AccessToken.secret')); + } - $token = $config->builder() - ->issuedBy($issuer) - ->issuedAt($timestamp) // Configures the time that the token was issue (iat claim) - ->permittedFor($audience) // Configures the audience (aud claim) - ->expiresAt($this->accessTokenLifeTime($timestamp)) // Configures the expiration time of the token (nbf claim) - ->relatedTo((string)$subject) // Configures a new claim, called "sub" - ->getToken($config->signer(), $config->signingKey()); // Retrieves the generated token + /** + * Signs the claims as a JWT with HS512. + * + * The token is the same, byte for byte, as the one lcobucci/jwt built before 14.0: the same header, + * the claims in the given order, and JSON with slashes and characters outside ASCII left as they are + * (`JWT::encode()` would escape those characters). + * + * @param array $claims Claims of the token. + * @param string $secret Signing secret. + * @return string + * @throws \InvalidArgumentException When the secret is shorter than the 512 bits that HS512 needs. + */ + private function signToken(array $claims, #[SensitiveParameter] string $secret): string + { + if (strlen($secret) < 64) { + throw new InvalidArgumentException(sprintf( + 'The JWT secret is too short: HS512 needs at least 64 bytes (512 bits), %d given.', + strlen($secret), + )); + } + $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR; + $message = JWT::urlsafeB64Encode(json_encode(['typ' => 'JWT', 'alg' => 'HS512'], $flags)) + . '.' . JWT::urlsafeB64Encode(json_encode($claims, $flags)); + + return $message . '.' . JWT::urlsafeB64Encode(JWT::sign($message, $secret, 'HS512')); + } + + /** + * Converts a time to the value of a date claim (`iat`, `exp`). + * + * A time with microseconds becomes a float, as in the tokens issued before 14.0. + * + * @param \DateTimeImmutable $date Time. + * @return float|int + */ + private function claimDate(DateTimeImmutable $date): int|float + { + if ($date->format('u') === '000000') { + return $date->getTimestamp(); + } - return $token->toString(); + return (float)$date->format('U.u'); } /** @@ -216,9 +254,9 @@ protected function getWebauthn2fAuthenticationChecker(): Webauthn2fAuthenticatio * refresh and requires a payload with a non-empty string `aud`. * @param object|array|null $payload Additional payload data. * @throws \CakeDC\Api\Exception\ValidationException When a refresh payload has no non-empty string audience. - * @return false|string + * @return string|false */ - public function generateRefreshToken($user, \DateTimeImmutable $timestamp, $type, $payload = null): false|string + public function generateRefreshToken($user, DateTimeImmutable $timestamp, $type, $payload = null): false|string { if (empty($user)) { return false; @@ -227,20 +265,19 @@ public function generateRefreshToken($user, \DateTimeImmutable $timestamp, $type $subject = $user['id']; $audience = $this->getAudience($user, $type, $payload); $issuer = Router::url('/', true); - $signer = new Sha512(); - $secret = Configure::read('Api.Jwt.RefreshToken.secret'); - - $config = Configuration::forSymmetricSigner($signer, InMemory::plainText($secret)); - - $token = $config->builder() - ->issuedBy($issuer) - ->issuedAt($timestamp) // Configures the time that the token was issue (iat claim) - ->permittedFor($audience) // Configures the audience (aud claim) - ->expiresAt($this->refreshTokenLifeTime($timestamp)) // Configures the expiration time of the token (nbf claim) - ->relatedTo((string)$subject) // Configures a new claim, called "sub" - ->getToken($config->signer(), $config->signingKey()); // Retrieves the generated token - $rawToken = $token->toString(); + $claims = [ + 'iss' => $issuer, + 'iat' => $this->claimDate($timestamp), + 'aud' => $audience, + 'exp' => $this->claimDate($this->refreshTokenLifeTime($timestamp)), + 'sub' => (string)$subject, + ]; + $authTime = $this->authTime($type, $payload, $timestamp); + if ($authTime !== null) { + $claims['auth_time'] = $authTime; + } + $rawToken = $this->signToken($claims, Configure::read('Api.Jwt.RefreshToken.secret')); $modelAlias = Configure::read('Users.table'); $UsersTable = TableRegistry::getTableLocator()->get($modelAlias); @@ -269,6 +306,30 @@ public function generateRefreshToken($user, \DateTimeImmutable $timestamp, $type return $rawToken; } + /** + * Returns when the session was authenticated, as a unix timestamp. + * + * A login, or completing the second factor, starts a new session. A refresh keeps the + * `auth_time` of the refresh token, so `Api.Jwt.RefreshToken.maxSessionLifetime` bounds the + * session however often it is refreshed. A refresh token issued before this claim existed + * stays without it, so enabling the setting later still ends such a session. + * + * @param string|null $type The type of token being generated, null for a refresh. + * @param object|array|null $payload Payload of the refresh token. + * @param \DateTimeImmutable $timestamp Timestamp. + * @return int|null + */ + private function authTime($type, $payload, DateTimeImmutable $timestamp): ?int + { + if ($type !== null) { + return $timestamp->getTimestamp(); + } + $payload = is_object($payload) ? (array)$payload : $payload; + $authTime = is_array($payload) ? $payload['auth_time'] ?? null : null; + + return is_int($authTime) ? $authTime : null; + } + /** * Generates access token with life time. * diff --git a/src/Service/Action/Auth/LoginAction.php b/src/Service/Action/Auth/LoginAction.php index 714ca4ef..71236176 100644 --- a/src/Service/Action/Auth/LoginAction.php +++ b/src/Service/Action/Auth/LoginAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -22,6 +22,7 @@ use CakeDC\Api\Service\Action\Action; use CakeDC\Users\Controller\Traits\LoginTrait; use CakeDC\Users\Exception\UserNotFoundException; +use Override; /** * Class LoginAction @@ -43,7 +44,7 @@ class LoginAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { if (isset($config['identifiedField'])) { @@ -53,7 +54,6 @@ public function initialize(array $config): void $this->passwordField = $config['passwordField']; } parent::initialize($config); - $this->Auth->allow($this->getName()); } /** @@ -61,7 +61,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -87,7 +87,7 @@ public function validates(): bool public function execute(): mixed { $socialLogin = false; - $user = $this->Auth->getIdentity(); + $user = $this->getIdentity(); if ($user instanceof IdentityInterface) { $user = $user->getOriginalData(); @@ -132,7 +132,7 @@ protected function afterIdentifyUser(?array $user, bool $socialLogin = false): a * * @return array */ - #[\Override] + #[Override] protected function authConfig(): array { return Hash::merge(parent::authConfig(), [ diff --git a/src/Service/Action/Auth/OtpVerifyAction.php b/src/Service/Action/Auth/OtpVerifyAction.php index 96b42da8..f2b1e4d5 100644 --- a/src/Service/Action/Auth/OtpVerifyAction.php +++ b/src/Service/Action/Auth/OtpVerifyAction.php @@ -2,21 +2,26 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; use Cake\Core\Configure; +use Cake\Log\Log; use CakeDC\Api\Service\Action\Action; use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; +use Override; +use RobThree\Auth\Algorithm; use RobThree\Auth\TwoFactorAuth; +use RuntimeException; +use Throwable; /** * Class LoginAction @@ -31,7 +36,7 @@ abstract class OtpVerifyAction extends Action /** * @var \RobThree\Auth\TwoFactorAuth $tfa */ - public ?\RobThree\Auth\TwoFactorAuth $tfa = null; + public ?TwoFactorAuth $tfa = null; /** * initialize @@ -39,17 +44,31 @@ abstract class OtpVerifyAction extends Action * @param array $config Configuration. * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { - $this->tfa = new TwoFactorAuth( - Configure::read('OneTimePasswordAuthenticator.issuer'), - Configure::read('OneTimePasswordAuthenticator.digits'), - Configure::read('OneTimePasswordAuthenticator.period'), - Configure::read('OneTimePasswordAuthenticator.algorithm'), - Configure::read('OneTimePasswordAuthenticator.qrcodeprovider'), - Configure::read('OneTimePasswordAuthenticator.rngprovider') - ); + try { + $algorithm = Configure::read('OneTimePasswordAuthenticator.algorithm') ?? Algorithm::Sha1; + if (is_string($algorithm)) { + $algorithm = Algorithm::tryFrom(strtolower($algorithm)) ?? $algorithm; + } + $this->tfa = new TwoFactorAuth( + qrcodeprovider: Configure::read('OneTimePasswordAuthenticator.qrcodeprovider'), + issuer: Configure::read('OneTimePasswordAuthenticator.issuer'), + digits: Configure::read('OneTimePasswordAuthenticator.digits') ?? 6, + period: Configure::read('OneTimePasswordAuthenticator.period') ?? 30, + algorithm: $algorithm, + rngprovider: Configure::read('OneTimePasswordAuthenticator.rngprovider'), + ); + } catch (Throwable $throwable) { + Log::error(sprintf('OneTimePasswordAuthenticator configuration failed: %s', $throwable->getMessage())); + throw new RuntimeException(__d( + 'cake_d_c/api', + 'An error has occurred configuring OneTimePasswordAuthenticator. ' . + 'Please ensure you have installed robthree/twofactorauth and endroid/qr-code ' . + '(or your preferred QR provider), and that OneTimePasswordAuthenticator.qrcodeprovider is set.', + ), (int)$throwable->getCode(), previous: $throwable); + } } /** @@ -67,12 +86,17 @@ public function createSecret(): string * Verifying tfa code with shared secret * * @param string $secret of the user - * @param string $code from verification form + * @param mixed $code from verification form; a JSON body may give an int, or nothing * @return bool */ public function verifyCode($secret, $code): bool { - return $this->tfa->verifyCode($secret, $code); + // robthree requires strings; a missing or non-scalar code is simply not a valid code + if (!is_string($code) && !is_int($code)) { + return false; + } + + return $this->tfa->verifyCode((string)$secret, (string)$code); } /** diff --git a/src/Service/Action/Auth/OtpVerifyCheckAction.php b/src/Service/Action/Auth/OtpVerifyCheckAction.php index cb4ae388..63b9b0a7 100644 --- a/src/Service/Action/Auth/OtpVerifyCheckAction.php +++ b/src/Service/Action/Auth/OtpVerifyCheckAction.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; +use Exception; /** * Class LoginAction @@ -46,7 +47,7 @@ public function execute(): mixed } if (!$codeVerified) { - throw new \Exception(__d('cake_d_c/api', 'Verification code is invalid. Try again')); + throw new Exception(__d('cake_d_c/api', 'Verification code is invalid. Try again')); } unset($user['secret']); diff --git a/src/Service/Action/Auth/OtpVerifyGetAction.php b/src/Service/Action/Auth/OtpVerifyGetAction.php index d28f7dee..694a9e9b 100644 --- a/src/Service/Action/Auth/OtpVerifyGetAction.php +++ b/src/Service/Action/Auth/OtpVerifyGetAction.php @@ -2,19 +2,19 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; -use Cake\Datasource\EntityInterface; use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; +use Exception; /** * Class LoginAction @@ -37,11 +37,9 @@ public function execute(): array // showing QR-code until shared secret is verified if (!$secretVerified) { $this->refuseEnrollmentIf($this->hasWebauthnCredential($user)); - // onVerifyGetSecret() takes an array, and the identity is an entity that hides `secret` - $userData = $user instanceof EntityInterface ? ['secret' => $user->get('secret')] + $user->toArray() : (array)$user; - $secret = $this->onVerifyGetSecret($userData); + $secret = $this->onVerifyGetSecret($user); if (empty($secret)) { - throw new \Exception('Secret generation issue, please try again'); + throw new Exception('Secret generation issue, please try again'); } $secretDataUri = $this->getQRCodeImageAsDataUri($user['email'], $secret); @@ -58,10 +56,10 @@ public function execute(): array /** * onVerifyGetSecret * - * @param array $user User. + * @param \Cake\Datasource\EntityInterface|array $user The identity, usually the user entity. * @return string */ - protected function onVerifyGetSecret(array $user): string + protected function onVerifyGetSecret($user): string { if (isset($user['secret']) && $user['secret']) { return $user['secret']; @@ -74,10 +72,10 @@ protected function onVerifyGetSecret(array $user): string ->set(['secret' => $secret]) ->where(['id' => $user['id']]); $query->execute(); - } catch (\Exception) { + } catch (Exception) { $message = __d('cake_d_c/api', 'Could not verify, please try again'); - throw new \Exception($message); + throw new Exception($message); } return $secret; diff --git a/src/Service/Action/Auth/RegisterAction.php b/src/Service/Action/Auth/RegisterAction.php index 8c2349ee..5c02f7e8 100644 --- a/src/Service/Action/Auth/RegisterAction.php +++ b/src/Service/Action/Auth/RegisterAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -21,6 +21,7 @@ use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; use CakeDC\Users\Controller\Traits\RegisterTrait; use CakeDC\Users\Plugin; +use Override; /** * Class RegisterAction @@ -38,11 +39,10 @@ class RegisterAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); - $this->Auth->allow($this->getName()); } /** @@ -50,7 +50,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { /** @var \CakeDC\Users\Model\Behavior\RegisterBehavior $registerBehavior */ @@ -115,7 +115,7 @@ protected function afterRegister(EntityInterface $userSaved): EntityInterface|ar if ($validateEmail) { $message = __d('CakeDC/Api', 'Please validate your account before log in'); } - $event = $this->dispatchEvent(Plugin::EVENT_BEFORE_REGISTER, [ + $event = $this->dispatchEvent(Plugin::EVENT_AFTER_REGISTER, [ 'user' => $userSaved, ]); if ($event->getResult() instanceof EntityInterface) { @@ -137,7 +137,7 @@ protected function afterRegister(EntityInterface $userSaved): EntityInterface|ar * * @return array */ - #[\Override] + #[Override] protected function authConfig(): array { return Hash::merge(parent::authConfig(), [ diff --git a/src/Service/Action/Auth/ResetPasswordAction.php b/src/Service/Action/Auth/ResetPasswordAction.php index c1c9da05..57b15fa6 100644 --- a/src/Service/Action/Auth/ResetPasswordAction.php +++ b/src/Service/Action/Auth/ResetPasswordAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -23,6 +23,7 @@ use CakeDC\Users\Exception\UserNotFoundException; use CakeDC\Users\Exception\WrongPasswordException; use Exception; +use Override; /** * Class ResetPasswordAction @@ -39,11 +40,10 @@ class ResetPasswordAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); - $this->Auth->allow($this->getName()); } /** @@ -51,7 +51,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -71,7 +71,7 @@ public function validates(): bool 'rule' => ['compareWith', 'password_confirm'], 'message' => __d( 'cake_d_c/users', - 'Your password does not match your confirm password. Please try again' + 'Your password does not match your confirm password. Please try again', ), 'allowEmpty' => false, ]]); @@ -146,7 +146,7 @@ protected function changePassword($userId): string * * @return array */ - #[\Override] + #[Override] protected function authConfig(): array { return Hash::merge(parent::authConfig(), [ diff --git a/src/Service/Action/Auth/ResetPasswordRequestAction.php b/src/Service/Action/Auth/ResetPasswordRequestAction.php index 58839ac2..5d592ca3 100644 --- a/src/Service/Action/Auth/ResetPasswordRequestAction.php +++ b/src/Service/Action/Auth/ResetPasswordRequestAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -22,6 +22,7 @@ use CakeDC\Users\Exception\UserNotActiveException; use CakeDC\Users\Exception\UserNotFoundException; use Exception; +use Override; /** * Class ResetPasswordAction @@ -38,11 +39,10 @@ class ResetPasswordRequestAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); - $this->Auth->allow($this->getName()); } /** @@ -50,7 +50,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -110,7 +110,7 @@ public function execute(): mixed * * @return array */ - #[\Override] + #[Override] protected function authConfig(): array { return Hash::merge(parent::authConfig(), [ diff --git a/src/Service/Action/Auth/SecondFactorTrait.php b/src/Service/Action/Auth/SecondFactorTrait.php index 38f66960..42770f35 100644 --- a/src/Service/Action/Auth/SecondFactorTrait.php +++ b/src/Service/Action/Auth/SecondFactorTrait.php @@ -16,13 +16,14 @@ use Cake\Datasource\EntityInterface; use Cake\Http\Exception\BadRequestException; use CakeDC\Api\Webauthn\Repository\UserCredentialSourceRepository; -use Webauthn\PublicKeyCredentialSource; +use Webauthn\PublicKeyCredential; /** * Checks which second factors an identity has registered. * * A password login gives a `/2fa` token, and that token can enroll a factor. Once one factor is - * registered, the token enrolls no other one. + * registered, enrolling another with the same token would let whoever knows only the password add + * their own factor and pass the second step with it, so enrollment is refused. * * Expects the using class to provide `getService()` and `getUsersTable()`. */ @@ -34,16 +35,13 @@ trait SecondFactorTrait * @param \Cake\Datasource\EntityInterface|array|null $identity Identity. * @return bool */ - protected function hasVerifiedOtp($identity): bool + protected function hasVerifiedOtp(EntityInterface|array|null $identity): bool { // toArray() leaves out hidden fields such as `secret`, so read the fields one by one - if ($identity instanceof EntityInterface) { - $secret = $identity->get('secret'); - $verified = $identity->get('secret_verified'); - } else { - $secret = $identity['secret'] ?? null; - $verified = $identity['secret_verified'] ?? null; - } + $secret = $identity instanceof EntityInterface ? $identity->get('secret') : ($identity['secret'] ?? null); + $verified = $identity instanceof EntityInterface + ? $identity->get('secret_verified') + : ($identity['secret_verified'] ?? null); return !empty($secret) && !empty($verified); } @@ -54,10 +52,10 @@ protected function hasVerifiedOtp($identity): bool * @param \Cake\Datasource\EntityInterface|array|null $identity Identity. * @return bool */ - protected function hasWebauthnCredential($identity): bool + protected function hasWebauthnCredential(EntityInterface|array|null $identity): bool { // web-auth/webauthn-lib is optional; without it no credential can have been registered - if (empty($identity) || !class_exists(PublicKeyCredentialSource::class)) { + if (empty($identity) || !class_exists(PublicKeyCredential::class)) { return false; } // read the stored keys from the user record; a WebAuthn adapter would need the WebAuthn @@ -83,7 +81,7 @@ protected function refuseEnrollmentIf(bool $otherFactorRegistered): void { if ($otherFactorRegistered) { throw new BadRequestException( - __d('cake_d_c/api', 'Another second factor is already registered; verify with it instead') + __d('cake_d_c/api', 'Another second factor is already registered; verify with it instead'), ); } } diff --git a/src/Service/Action/Auth/SocialLoginAction.php b/src/Service/Action/Auth/SocialLoginAction.php index cd81ccfa..227fedf9 100644 --- a/src/Service/Action/Auth/SocialLoginAction.php +++ b/src/Service/Action/Auth/SocialLoginAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -25,6 +25,7 @@ use CakeDC\Users\Exception\UserNotActiveException; use CakeDC\Users\Exception\UserNotFoundException; use Exception; +use Override; /** * Class SocialLoginAction @@ -41,11 +42,10 @@ class SocialLoginAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); - $this->Auth->allow($this->getName()); } /** @@ -53,7 +53,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -82,9 +82,9 @@ public function execute(): mixed $options = $input['options']; try { - /** @var \CakeDC\Users\Model\Table\UsersTable $usersTable */ - $usersTable = $this->getUsersTable(); - $result = $usersTable->socialLogin($data, $options); + /** @var \CakeDC\Users\Model\Behavior\SocialBehavior $socialBehavior */ + $socialBehavior = $this->getUsersTable()->getBehavior('Social'); + $result = $socialBehavior->socialLogin($data, $options); if ($result instanceof EntityInterface) { return $result->toArray(); } @@ -100,7 +100,7 @@ public function execute(): mixed throw new Exception($ex->getMessage(), 504, $ex); } catch (MissingEmailException $ex) { throw new Exception($ex->getMessage(), 505, $ex); - } catch (\Exception $ex) { + } catch (Exception $ex) { throw new Exception($ex->getMessage(), 500, $ex); } } @@ -110,7 +110,7 @@ public function execute(): mixed * * @return array */ - #[\Override] + #[Override] protected function authConfig(): array { return Hash::merge(parent::authConfig(), [ diff --git a/src/Service/Action/Auth/TwoFactorAuthAction.php b/src/Service/Action/Auth/TwoFactorAuthAction.php index b1cfdddb..7072fdc9 100644 --- a/src/Service/Action/Auth/TwoFactorAuthAction.php +++ b/src/Service/Action/Auth/TwoFactorAuthAction.php @@ -2,17 +2,18 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; +use Cake\Datasource\EntityInterface; use CakeDC\Api\Service\Action\Action; use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; @@ -34,18 +35,17 @@ class TwoFactorAuthAction extends Action */ public function execute(): array { - $user = $this->getIdentity(); - // keys of every domain count, and a verified secret counts as OTP - $hasWebauthn = $this->hasWebauthnCredential($user); - $hasOtp = $this->hasVerifiedOtp($user); - $user = $user->toArray(); + $identity = $this->getIdentity(); + $hasWebauthn = $this->hasWebauthnCredential($identity); + $hasOtp = $this->hasVerifiedOtp($identity); + $user = $identity instanceof EntityInterface ? $identity->toArray() : (array)$identity; return [ 'hasRegistered2fa' => $hasWebauthn && $hasOtp, 'hasOtp' => $hasOtp, 'hasWebauthn' => $hasWebauthn, - 'enabledWebauthn' => $this->isEnabledWebauthn2faAuthentication((array)$user), - 'enabledOtp' => $this->isEnabledOneTimePasswordAuthentication((array)$user), + 'enabledWebauthn' => $this->isEnabledWebauthn2faAuthentication($user), + 'enabledOtp' => $this->isEnabledOneTimePasswordAuthentication($user), ]; } } diff --git a/src/Service/Action/Auth/ValidateAccountAction.php b/src/Service/Action/Auth/ValidateAccountAction.php index 0e2b51e1..3ea6c943 100644 --- a/src/Service/Action/Auth/ValidateAccountAction.php +++ b/src/Service/Action/Auth/ValidateAccountAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -22,6 +22,7 @@ use CakeDC\Users\Exception\UserAlreadyActiveException; use CakeDC\Users\Exception\UserNotFoundException; use Exception; +use Override; /** * Class ValidateAccountAction @@ -38,11 +39,10 @@ class ValidateAccountAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); - $this->Auth->allow($this->getName()); } /** @@ -50,7 +50,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -97,7 +97,7 @@ public function execute(): mixed * * @return array */ - #[\Override] + #[Override] protected function authConfig(): array { return Hash::merge(parent::authConfig(), [ diff --git a/src/Service/Action/Auth/ValidateAccountRequestAction.php b/src/Service/Action/Auth/ValidateAccountRequestAction.php index 3b7e802e..f5b4aa51 100644 --- a/src/Service/Action/Auth/ValidateAccountRequestAction.php +++ b/src/Service/Action/Auth/ValidateAccountRequestAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -22,6 +22,7 @@ use CakeDC\Users\Exception\UserAlreadyActiveException; use CakeDC\Users\Exception\UserNotFoundException; use Exception; +use Override; /** * Class ValidateAccountRequestAction @@ -38,11 +39,10 @@ class ValidateAccountRequestAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); - $this->Auth->allow($this->getName()); } /** @@ -50,7 +50,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -103,7 +103,7 @@ public function execute(): mixed * * @return array */ - #[\Override] + #[Override] protected function authConfig(): array { return Hash::merge(parent::authConfig(), [ diff --git a/src/Service/Action/Auth/Webauthn2faAction.php b/src/Service/Action/Auth/Webauthn2faAction.php index 5db6d131..225aa58c 100644 --- a/src/Service/Action/Auth/Webauthn2faAction.php +++ b/src/Service/Action/Auth/Webauthn2faAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; diff --git a/src/Service/Action/Auth/Webauthn2faAuthAction.php b/src/Service/Action/Auth/Webauthn2faAuthAction.php index c37ce4a8..2c929054 100644 --- a/src/Service/Action/Auth/Webauthn2faAuthAction.php +++ b/src/Service/Action/Auth/Webauthn2faAuthAction.php @@ -2,21 +2,25 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; +use Cake\Http\Exception\BadRequestException; +use Cake\Http\Exception\UnauthorizedException; use Cake\Log\Log; use CakeDC\Api\Service\Action\Action; use CakeDC\Api\Webauthn\AuthenticateAdapter; use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; +use InvalidArgumentException; +use Webauthn\Exception\WebauthnException; /** * Class LoginAction @@ -32,22 +36,23 @@ class Webauthn2faAuthAction extends Action * Execute action. * * @return array - * @throws \Throwable + * @throws \Cake\Http\Exception\UnauthorizedException When the assertion does not verify. */ public function execute(): array { + $user = $this->getIdentity(); + $adapter = new AuthenticateAdapter($this->getService()->getRequest(), $this->getUsersTable(), $user); try { - $user = $this->getIdentity(); - $adapter = new AuthenticateAdapter($this->getService()->getRequest(), $this->getUsersTable(), $user); $adapter->verifyResponse(); - $adapter->deleteStore(); + } catch (WebauthnException | BadRequestException | InvalidArgumentException $exception) { + // a failed verification is a client error; the reason stays in the log, not in the response + $reason = sprintf('user id %s: %s', $user['id'] ?? 'empty', $exception->getMessage()); + Log::debug('WebAuthn authentication failed for ' . $reason, ['scope' => ['api']]); - return $this->generateTokenResponse($user->toArray(), '2fa'); - } catch (\Throwable $throwable) { - $user = $this->getIdentity(); - $message = __d('cake_d_c/api', 'Register error with webauthn for user id: {0}', $user['id'] ?? 'empty'); - Log::debug($message); - throw $throwable; + throw new UnauthorizedException(__d('cake_d_c/api', 'WebAuthn authentication failed'), 401, $exception); } + $adapter->deleteStore(); + + return $this->generateTokenResponse($user->toArray(), '2fa'); } } diff --git a/src/Service/Action/Auth/Webauthn2faAuthOptionsAction.php b/src/Service/Action/Auth/Webauthn2faAuthOptionsAction.php index c2909909..abc07a46 100644 --- a/src/Service/Action/Auth/Webauthn2faAuthOptionsAction.php +++ b/src/Service/Action/Auth/Webauthn2faAuthOptionsAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -29,13 +29,13 @@ class Webauthn2faAuthOptionsAction extends Action /** * Execute action. * - * @return \Webauthn\PublicKeyCredentialRequestOptions + * @return array The request options as the client expects them. */ - public function execute(): \Webauthn\PublicKeyCredentialRequestOptions + public function execute(): array { $request = $this->getService()->getRequest(); $adapter = new AuthenticateAdapter($request, $this->getUsersTable(), $this->getIdentity()); - return $adapter->getOptions(); + return $adapter->getOptionsData($adapter->getOptions()); } } diff --git a/src/Service/Action/Auth/Webauthn2faRegisterAction.php b/src/Service/Action/Auth/Webauthn2faRegisterAction.php index 5b159b6b..9111ef0c 100644 --- a/src/Service/Action/Auth/Webauthn2faRegisterAction.php +++ b/src/Service/Action/Auth/Webauthn2faRegisterAction.php @@ -2,21 +2,24 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; use Cake\Http\Exception\BadRequestException; +use Cake\Log\Log; use CakeDC\Api\Service\Action\Action; use CakeDC\Api\Webauthn\RegisterAdapter; use CakeDC\Users\Controller\Traits\CustomUsersTableTrait; +use InvalidArgumentException; +use Webauthn\Exception\WebauthnException; /** * Class LoginAction @@ -41,13 +44,21 @@ public function execute(): mixed // a key registered under another domain counts too: the domain can come from the Referer if (!$adapter->hasCredentialOnAnyDomain()) { - $adapter->verifyResponse(); + try { + $adapter->verifyResponse(); + } catch (WebauthnException | BadRequestException | InvalidArgumentException $exception) { + // a failed verification is a client error; the reason stays in the log, not in the response + $reason = sprintf('user id %s: %s', $user['id'] ?? 'empty', $exception->getMessage()); + Log::debug('WebAuthn registration failed for ' . $reason, ['scope' => ['api']]); + + throw new BadRequestException(__d('cake_d_c/api', 'WebAuthn registration failed'), 400, $exception); + } return ['success' => true]; } throw new BadRequestException( - __d('cake_d_c/api', 'User already has configured webauthn2fa') + __d('cake_d_c/api', 'User already has configured webauthn2fa'), ); } } diff --git a/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php b/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php index 2291f1f5..d18fe8d3 100644 --- a/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php +++ b/src/Service/Action/Auth/Webauthn2faRegisterOptionsAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Auth; @@ -31,9 +31,9 @@ class Webauthn2faRegisterOptionsAction extends Action /** * Execute action. * - * @return \Webauthn\PublicKeyCredentialCreationOptions + * @return array The creation options as the client expects them. */ - public function execute(): \Webauthn\PublicKeyCredentialCreationOptions + public function execute(): array { $user = $this->getIdentity(); $this->refuseEnrollmentIf($this->hasVerifiedOtp($user)); @@ -41,10 +41,10 @@ public function execute(): \Webauthn\PublicKeyCredentialCreationOptions // a key registered under another domain counts too: the domain can come from the Referer if (!$adapter->hasCredentialOnAnyDomain()) { - return $adapter->getOptions(); + return $adapter->getOptionsData($adapter->getOptions()); } throw new BadRequestException( - __d('cake_d_c/api', 'User already has configured webauthn2fa') + __d('cake_d_c/api', 'User already has configured webauthn2fa'), ); } } diff --git a/src/Service/Action/Collection/AddEditAction.php b/src/Service/Action/Collection/AddEditAction.php index cd057256..c582fe8c 100644 --- a/src/Service/Action/Collection/AddEditAction.php +++ b/src/Service/Action/Collection/AddEditAction.php @@ -2,17 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Collection; +use Override; + /** * Class AddEditAction, uses POST and an array of entity data to either add or edit * Pass a not null primary key for edit, null for adding a new row @@ -35,7 +37,7 @@ class AddEditAction extends CollectionAction * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { return $this->validateMany(); diff --git a/src/Service/Action/Collection/CollectionAction.php b/src/Service/Action/Collection/CollectionAction.php index 24e9d7ba..293b2495 100644 --- a/src/Service/Action/Collection/CollectionAction.php +++ b/src/Service/Action/Collection/CollectionAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Collection; @@ -57,8 +57,8 @@ protected function validateMany(): bool /** * Save many entities * - * @param \Cake\Datasource\EntityInterface[] $entities entities - * @return \Cake\Datasource\EntityInterface[]|\Cake\Datasource\ResultSetInterface|array of entities saved + * @param array<\Cake\Datasource\EntityInterface> $entities entities + * @return \Cake\Datasource\ResultSetInterface|array<\Cake\Datasource\EntityInterface>|array of entities saved * @throws \Exception */ protected function saveMany(iterable $entities) @@ -68,7 +68,7 @@ protected function saveMany(iterable $entities) } $errors = collection($entities)->reduce( fn($errors, EntityInterface $entity): array => array_merge($errors, $entity->getErrors()), - [] + [], ); $message = __('Validation on {0} failed', $this->getTable()->getAlias()); throw new ValidationException($message, 0, null, $errors); @@ -78,7 +78,7 @@ protected function saveMany(iterable $entities) * Create entities from the posted data * * @param array $patchOptions options to use in patch - * @return \Cake\Datasource\EntityInterface[] entities + * @return array<\Cake\Datasource\EntityInterface> entities */ protected function newEntities(array $patchOptions = []): array { diff --git a/src/Service/Action/Collection/DeleteAction.php b/src/Service/Action/Collection/DeleteAction.php index 470df0a9..b3f1b5fc 100644 --- a/src/Service/Action/Collection/DeleteAction.php +++ b/src/Service/Action/Collection/DeleteAction.php @@ -2,19 +2,21 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Collection; use Cake\Utility\Hash; use CakeDC\Api\Exception\ValidationException; +use InvalidArgumentException; +use Override; /** * Class DeleteAction, uses POST and an array of entity ids to delete @@ -26,7 +28,7 @@ class DeleteAction extends CollectionAction /** * @inheritDoc */ - #[\Override] + #[Override] public function validates(): bool { $data = $this->getData(); @@ -97,7 +99,7 @@ protected function deleteMany(array $entities): array $entity->setNew(false); try { $this->getTable()->deleteOrFail($entity, ['atomic' => false]); - } catch (\InvalidArgumentException $ex) { + } catch (InvalidArgumentException $ex) { $errors[$index] = [ $entity->id ?? '' => $ex->getMessage(), ]; diff --git a/src/Service/Action/CrudAction.php b/src/Service/Action/CrudAction.php index 110b1fe7..6355fd22 100644 --- a/src/Service/Action/CrudAction.php +++ b/src/Service/Action/CrudAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; @@ -22,7 +22,10 @@ use Cake\ORM\TableRegistry; use Cake\Utility\Inflector; use CakeDC\Api\Exception\ValidationException; +use CakeDC\Api\Service\CrudService; use CakeDC\Api\Service\Utility\ReverseRouting; +use CakeDC\Api\Utility\LegacyMemberGuard; +use Override; /** * Class CrudAction @@ -31,7 +34,7 @@ */ abstract class CrudAction extends Action { - protected ?\Cake\ORM\Table $table = null; + protected ?Table $table = null; /** * Object Identifier @@ -78,6 +81,8 @@ abstract class CrudAction extends Action */ public function __construct(array $config = []) { + // CrudAction reads its properties before calling the parent constructor + LegacyMemberGuard::check($this, LegacyMemberGuard::ACTION); if (!empty($config['service'])) { $this->setService($config['service']); } @@ -103,9 +108,6 @@ public function __construct(array $config = []) if (!empty($config['parentIdName'])) { $this->parentIdName = $config['parentIdName']; } - if (!empty($config['table'])) { - $this->setTable($config['table']); - } parent::__construct($config); } @@ -135,8 +137,8 @@ public function setTable(Table $table) /** * @return \CakeDC\Api\Service\CrudService */ - #[\Override] - public function getService(): \CakeDC\Api\Service\CrudService + #[Override] + public function getService(): CrudService { return $this->service; } @@ -251,7 +253,7 @@ protected function getEntitiesQuery(): SelectQuery * @param mixed $primaryKey Primary key. * @return \Cake\Datasource\EntityInterface|array */ - protected function getEntity($primaryKey): \Cake\Datasource\EntityInterface|array + protected function getEntity($primaryKey): EntityInterface|array { $query = $this->getEntityQuery($primaryKey); if ($this->finder !== null) { @@ -277,7 +279,7 @@ protected function getEntity($primaryKey): \Cake\Datasource\EntityInterface|arra * @param mixed $primaryKey Primary key. * @return \Cake\ORM\Query\SelectQuery */ - protected function getEntityQuery($primaryKey): \Cake\ORM\Query\SelectQuery + protected function getEntityQuery($primaryKey): SelectQuery { return $this->getTable()->find('all')->where($this->buildViewCondition($primaryKey)); } @@ -304,7 +306,7 @@ protected function buildViewCondition($primaryKey): array $msg = sprintf( 'Record not found in table "%s" with primary key [%s]', $table->getTable(), - implode(', ', $primaryKey) + implode(', ', $primaryKey), ); throw new InvalidPrimaryKeyException($msg); } diff --git a/src/Service/Action/CrudAddAction.php b/src/Service/Action/CrudAddAction.php index c6eb2e44..61d96d31 100644 --- a/src/Service/Action/CrudAddAction.php +++ b/src/Service/Action/CrudAddAction.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; +use Cake\Datasource\EntityInterface; use CakeDC\Api\Exception\ValidationException; +use Override; /** * Class CrudAddAction @@ -27,7 +29,7 @@ class CrudAddAction extends CrudAction * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = $this->getTable()->getValidator(); @@ -44,7 +46,7 @@ public function validates(): bool * * @return \Cake\Datasource\EntityInterface */ - public function execute(): \Cake\Datasource\EntityInterface + public function execute(): EntityInterface { $entity = $this->newEntity(); $entity = $this->patchEntity($entity, $this->getData()); diff --git a/src/Service/Action/CrudDeleteAction.php b/src/Service/Action/CrudDeleteAction.php index 998f7315..511ff9e3 100644 --- a/src/Service/Action/CrudDeleteAction.php +++ b/src/Service/Action/CrudDeleteAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; diff --git a/src/Service/Action/CrudDescribeAction.php b/src/Service/Action/CrudDescribeAction.php index 5ea2e71c..3cadf77e 100644 --- a/src/Service/Action/CrudDescribeAction.php +++ b/src/Service/Action/CrudDescribeAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; diff --git a/src/Service/Action/CrudEditAction.php b/src/Service/Action/CrudEditAction.php index 21d0f7a9..845b925e 100644 --- a/src/Service/Action/CrudEditAction.php +++ b/src/Service/Action/CrudEditAction.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; +use Cake\Datasource\EntityInterface; use CakeDC\Api\Exception\ValidationException; +use Override; /** * Class CrudEditAction @@ -27,7 +29,7 @@ class CrudEditAction extends CrudAction * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = $this->getTable()->getValidator(); @@ -44,7 +46,7 @@ public function validates(): bool * * @return \Cake\Datasource\EntityInterface */ - public function execute(): \Cake\Datasource\EntityInterface + public function execute(): EntityInterface { $entity = $this->getEntity($this->id); $entity = $this->patchEntity($entity, $this->getData()); diff --git a/src/Service/Action/CrudIndexAction.php b/src/Service/Action/CrudIndexAction.php index adbd4138..9860a4c5 100644 --- a/src/Service/Action/CrudIndexAction.php +++ b/src/Service/Action/CrudIndexAction.php @@ -2,17 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; +use Cake\Datasource\ResultSetInterface; + /** * Class CrudIndexAction * @@ -27,7 +29,7 @@ class CrudIndexAction extends CrudAction * * @return \Cake\Datasource\ResultSetInterface */ - public function execute(): \Cake\Datasource\ResultSetInterface + public function execute(): ResultSetInterface { return $this->getEntities(); } diff --git a/src/Service/Action/CrudViewAction.php b/src/Service/Action/CrudViewAction.php index 1194ba11..8cf7375f 100644 --- a/src/Service/Action/CrudViewAction.php +++ b/src/Service/Action/CrudViewAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; diff --git a/src/Service/Action/DescribeAction.php b/src/Service/Action/DescribeAction.php index d3c57ecf..3874e8ca 100644 --- a/src/Service/Action/DescribeAction.php +++ b/src/Service/Action/DescribeAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; @@ -17,6 +17,7 @@ use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\CrudService; use CakeDC\Api\Service\ServiceRegistry; +use Override; /** * Class DescribeAction @@ -30,7 +31,7 @@ class DescribeAction extends Action * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -65,7 +66,7 @@ public function execute(): mixed 'map' => [], '_matchedRoute' => '/' . $serviceName, ]; - $action = $service->buildActionClass(\CakeDC\Api\Service\Action\CrudDescribeAction::class, $route); + $action = $service->buildActionClass(CrudDescribeAction::class, $route); $service->setRequest($this->getService()->getRequest()); $service->setResponse($this->getService()->getResponse()); diff --git a/src/Service/Action/DummyAction.php b/src/Service/Action/DummyAction.php index afcf6129..3f1686ca 100644 --- a/src/Service/Action/DummyAction.php +++ b/src/Service/Action/DummyAction.php @@ -2,17 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; +use Override; + /** * Class DummyAction * @@ -25,7 +27,7 @@ class DummyAction extends Action * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { return true; diff --git a/src/Service/Action/Extension/Auth/UserFormattingExtension.php b/src/Service/Action/Extension/Auth/UserFormattingExtension.php index 8d26f1de..0f49b68e 100644 --- a/src/Service/Action/Extension/Auth/UserFormattingExtension.php +++ b/src/Service/Action/Extension/Auth/UserFormattingExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension\Auth; @@ -70,7 +70,7 @@ public function onRegisterFormat(Event $event): void } /** - * @param array|\Cake\Datasource\EntityInterface|null $user User data + * @param \Cake\Datasource\EntityInterface|array|null $user User data * @return array|null */ protected function userCleanup($user): ?array diff --git a/src/Service/Action/Extension/AuthenticationExtension.php b/src/Service/Action/Extension/AuthenticationExtension.php index b421a162..59d1a698 100644 --- a/src/Service/Action/Extension/AuthenticationExtension.php +++ b/src/Service/Action/Extension/AuthenticationExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2018, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2018, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -22,13 +22,16 @@ use Cake\Event\EventListenerInterface; use Cake\Utility\Hash; use CakeDC\Api\Service\Action\Action; +use CakeDC\Api\Service\Action\ExtensionRegistry; use Exception; use RuntimeException; /** - * Class UserFormattingExtension + * Class AuthenticationExtension * - * @package CakeDC\Api\Service\Action\Extension\Auth + * @deprecated 14.0.0 Authentication runs in the AuthenticationMiddleware of `Api.Middleware`; this extension + * duplicates it per action. Will be removed in 15.0.0. + * @package CakeDC\Api\Service\Action\Extension */ class AuthenticationExtension extends Extension implements EventListenerInterface { @@ -55,6 +58,20 @@ class AuthenticationExtension extends Extension implements EventListenerInterfac */ protected array $unauthenticatedActions = []; + /** + * @param \CakeDC\Api\Service\Action\ExtensionRegistry $registry Extension registry. + * @param array $config Configuration. + */ + public function __construct(ExtensionRegistry $registry, array $config = []) + { + deprecationWarning( + '14.0.0', + 'The CakeDC/Api.Authentication action extension is deprecated and will be removed in 15.0.0. ' + . 'Authentication runs in the AuthenticationMiddleware of Api.Middleware.', + ); + parent::__construct($registry, $config); + } + /** * Returns a list of events this object is implementing. When the class is registered * in an event manager, each individual method will be associated with the respective event. @@ -190,7 +207,7 @@ public function getIdentityData(array|string|int|null $path): mixed { $identity = $this->getIdentity(); - if (!$identity instanceof \Authentication\IdentityInterface) { + if (!$identity instanceof IdentityInterface) { throw new RuntimeException('The identity has not been found.'); } @@ -218,7 +235,7 @@ public function setIdentity(ArrayAccess $identity) $result = $this->getAuthenticationService()->persistIdentity( $this->getAction()->getService()->getRequest(), $this->getAction()->getService()->getResponse(), - $identity + $identity, ); /** @var \Cake\Http\ServerRequest $request */ diff --git a/src/Service/Action/Extension/AuthorizationExtension.php_ b/src/Service/Action/Extension/AuthorizationExtension.php_ deleted file mode 100644 index 060001d4..00000000 --- a/src/Service/Action/Extension/AuthorizationExtension.php_ +++ /dev/null @@ -1,350 +0,0 @@ - 'identity', - 'serviceAttribute' => 'authorization', - 'authorizationEvent' => 'Action.Auth.onAuthorization', - 'skipAuthorization' => [], - 'authorizeModel' => [], - 'actionMap' => [], - ]; - - /** - * Check the policy for $resource, raising an exception on error. - * - * If $action is left undefined, the current controller action will - * be used. - * - * @param mixed $resource The resource to check authorization on. - * @param string|null $action The action to check authorization for. - * @return void - * @throws \Authorization\Exception\ForbiddenException when policy check fails. - */ - public function authorize($resource, ?string $action = null): void - { - if ($action === null) { - $request = $this->getAction()->getService()->getRequest(); - $action = $this->getDefaultAction($request); - } - - $result = $this->canResult($resource, $action); - if ($result->getStatus()) { - return; - } - - if (is_object($resource)) { - $name = get_class($resource); - } elseif (is_string($resource)) { - $name = $resource; - } else { - $name = gettype($resource); - } - throw new ForbiddenException($result, [$action, $name]); - } - - /** - * Check the policy for $resource, returns true if the action is allowed - * - * If $action is left undefined, the current controller action will - * be used. - * - * @param mixed $resource The resource to check authorization on. - * @param string|null $action The action to check authorization for. - * @return bool - */ - public function can($resource, ?string $action = null): bool - { - return $this->performCheck($resource, $action); - } - - /** - * Check the policy for $resource, returns true if the action is allowed - * - * If $action is left undefined, the current controller action will - * be used. - * - * @param mixed $resource The resource to check authorization on. - * @param string|null $action The action to check authorization for. - * @return \Authorization\Policy\ResultInterface - */ - public function canResult($resource, ?string $action = null): ResultInterface - { - return $this->performCheck($resource, $action, 'canResult'); - } - - /** - * Check the policy for $resource. - * - * @param mixed $resource The resource to check authorization on. - * @param string|null $action The action to check authorization for. - * @param string $method The method to use, either "can" or "canResult". - * @return bool|\Authorization\Policy\ResultInterface - */ - protected function performCheck($resource, ?string $action = null, string $method = 'can') - { - $request = $this->getAction()->getService()->getRequest(); - if ($action === null) { - $action = $this->getDefaultAction($request); - } - - $identity = $this->getIdentity($request); - if (empty($identity)) { - return $this->getService($request)->{$method}(null, $action, $resource); - } - - return $identity->{$method}($action, $resource); - } - - /** - * Applies a scope for $resource. - * - * If $action is left undefined, the current controller action will - * be used. - * - * @param mixed $resource The resource to apply a scope to. - * @param string|null $action The action to apply a scope for. - * @return mixed - */ - public function applyScope($resource, ?string $action = null) - { - $request = $this->getAction()->getService()->getRequest(); - if ($action === null) { - $action = $this->getDefaultAction($request); - } - $identity = $this->getIdentity($request); - - return $identity->applyScope($action, $resource); - } - - /** - * Skips the authorization check. - * - * @return $this - */ - public function skipAuthorization() - { - $request = $this->getAction()->getService()->getRequest(); - $service = $this->getService($request); - - $service->skipAuthorization(); - - return $this; - } - - /** - * Allows to map controller action to another authorization policy action. - * - * For instance you may want to authorize `add` action with `create` authorization policy. - * - * @param string $controllerAction Controller action. - * @param string $policyAction Policy action. - * @return $this - */ - public function mapAction(string $controllerAction, string $policyAction) - { - $this->config['actionMap'][$controllerAction] = $policyAction; - - return $this; - } - - /** - * Allows to map controller actions to policy actions. - * - * @param array $actions Map of controller action to policy action. - * @param bool $overwrite Set to true to override configuration. False will merge with current configuration. - * @return $this - */ - public function mapActions(array $actions, bool $overwrite = false) - { - $this->setConfig('actionMap', $actions, !$overwrite); - - return $this; - } - - /** - * Adds an action to automatic model authorization checks. - * - * @param string ...$actions Controller action to authorize against table policy. - * @return $this - */ - public function authorizeModel(string ...$actions) - { - $this->config['authorizeModel'] = array_merge($this->config['authorizeModel'], $actions); - - return $this; - } - - /** - * Get the authorization service from a request. - * - * @param \Psr\Http\Message\ServerRequestInterface $request The request - * @return \Authorization\AuthorizationServiceInterface - * @throws \InvalidArgumentException When invalid authorization service encountered. - */ - protected function getService(ServerRequestInterface $request): \Authorization\AuthorizationServiceInterface - { - $serviceAttribute = $this->getConfig('serviceAttribute'); - $service = $request->getAttribute($serviceAttribute); - if (!$service instanceof AuthorizationServiceInterface) { - $type = is_object($service) ? get_class($service) : gettype($service); - throw new InvalidArgumentException(sprintf( - 'Expected that `%s` would be an instance of %s, but got %s', - $serviceAttribute, - AuthorizationServiceInterface::class, - $type - )); - } - - return $service; - } - - /** - * Get the identity from a request. - * - * @param \Psr\Http\Message\ServerRequestInterface $request The request - * @return \Authorization\IdentityInterface|null - * @throws \Authorization\Exception\MissingIdentityException When identity is not present in a request. - * @throws \InvalidArgumentException When invalid identity encountered. - */ - protected function getIdentity(ServerRequestInterface $request): ?IdentityInterface - { - $identityAttribute = $this->getConfig('identityAttribute'); - $identity = $request->getAttribute($identityAttribute); - if ($identity === null) { - return $identity; - } - if (!$identity instanceof IdentityInterface) { - $type = is_object($identity) ? get_class($identity) : gettype($identity); - throw new InvalidArgumentException(sprintf( - 'Expected that `%s` would be an instance of %s, but got %s', - $identityAttribute, - IdentityInterface::class, - $type - )); - } - - return $identity; - } - - /** - * Action authorization handler. - * - * Checks identity and model authorization. - * - * @return void - */ - public function authorizeAction(): void - { - // @TODO WHOLE METHOD LOGIC - $request = $this->getAction()->getService()->getRequest(); - $action = $this->getAction()->getName(); - $skipAuthorization = $this->checkAction($action, 'skipAuthorization'); - if ($skipAuthorization) { - $this->skipAuthorization(); - - return; - } - - $authorizeModel = $this->checkAction($action, 'authorizeModel'); - if ($authorizeModel) { - // @TODO - // $this->authorize($this->getController()->loadModel()); - } - } - - /** - * Checks whether an action should be authorized according to the config key provided. - * - * @param string $action Action name. - * @param string $configKey Configuration key with actions. - * @return bool - */ - protected function checkAction(string $action, string $configKey): bool - { - $actions = (array)$this->getConfig($configKey); - - return in_array($action, $actions, true); - } - - /** - * Returns authorization action name for a controller action resolved from the request. - * - * @param \Cake\Http\ServerRequest $request Server request. - * @return string - * @throws \UnexpectedValueException When invalid action type encountered. - */ - protected function getDefaultAction(ServerRequest $request): string - { - $action = $this->getAction()->getName(); - $name = $this->getConfig('actionMap.' . $action); - - if ($name === null) { - return $action; - } - if (!is_string($name)) { - $type = is_object($name) ? get_class($name) : gettype($name); - $message = sprintf('Invalid action type for `%s`. Expected `string` or `null`, got `%s`.', $action, $type); - throw new UnexpectedValueException($message); - } - - return $name; - } - - /** - * Returns model authorization handler if model authorization is enabled. - * - * @return array - */ - public function implementedEvents(): array - { - return [ - $this->getConfig('authorizationEvent') => 'authorizeAction', - 'Action.onAuth' => 'authorizeAction', - ]; - } - - /** - * @return \CakeDC\Api\Service\Action\Action - */ - public function getAction() - { - return $this->getConfig('action'); - } -} diff --git a/src/Service/Action/Extension/CorsExtension.php b/src/Service/Action/Extension/CorsExtension.php index be6d77fc..fbf9aee7 100644 --- a/src/Service/Action/Extension/CorsExtension.php +++ b/src/Service/Action/Extension/CorsExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -61,7 +61,7 @@ public function onAction(Event $Event): void ]) ->allowCredentials() ->maxAge($this->getConfig('maxAge') ?: 300) - ->build() + ->build(), ); } } diff --git a/src/Service/Action/Extension/CrudAutocompleteListExtension.php b/src/Service/Action/Extension/CrudAutocompleteListExtension.php index 8bc91196..210ca07b 100644 --- a/src/Service/Action/Extension/CrudAutocompleteListExtension.php +++ b/src/Service/Action/Extension/CrudAutocompleteListExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; diff --git a/src/Service/Action/Extension/CrudHateoasExtension.php b/src/Service/Action/Extension/CrudHateoasExtension.php index e6a86b1d..6546bb56 100644 --- a/src/Service/Action/Extension/CrudHateoasExtension.php +++ b/src/Service/Action/Extension/CrudHateoasExtension.php @@ -2,23 +2,25 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; use Cake\Event\Event; use Cake\Event\EventListenerInterface; +use Cake\Routing\Route\Route; use Cake\Utility\Inflector; use CakeDC\Api\Service\Action\Action; use CakeDC\Api\Service\Action\CrudAction; use CakeDC\Api\Service\Action\ExtensionRegistry; +use CakeDC\Api\Service\Service; use CakeDC\Api\Service\Utility\ReverseRouting; /** @@ -28,7 +30,7 @@ */ class CrudHateoasExtension extends Extension implements EventListenerInterface { - protected \CakeDC\Api\Service\Utility\ReverseRouting $reverseRouter; + protected ReverseRouting $reverseRouter; /** * CrudHateous Extension constructor. @@ -101,7 +103,7 @@ protected function buildIndexLinks(Action $action): array $links[] = $this->reverseRouter->link('self', $path, $indexRoute['_method'], $version); $links[] = $this->reverseRouter->link($action->getService()->getName() . ':add', $path, 'POST', $version); - if ($parent instanceof \CakeDC\Api\Service\Service) { + if ($parent instanceof Service) { $parentName = $parent->getName() . ':view'; $path = $this->reverseRouter->parentViewPath($parentName, $action, 'view'); $links[] = $this->reverseRouter->link($parentName, $path, 'GET', $version); @@ -124,10 +126,10 @@ protected function buildViewLinks(Action $action): array $version = $service->getVersion(); $parent = $action->getService()->getParentService(); $path = null; - if ($parent instanceof \CakeDC\Api\Service\Service) { + if ($parent instanceof Service) { $parentRoutes = $parent->routes(); $currentRoute = $this->reverseRouter->findRoute($viewRoute, $parentRoutes); - if ($currentRoute instanceof \Cake\Routing\Route\Route) { + if ($currentRoute instanceof Route) { $path = $parent->routeReverse($viewRoute); array_pop($viewRoute['pass']); @@ -153,7 +155,7 @@ protected function buildViewLinks(Action $action): array $links[] = $this->reverseRouter->link($routeName, $indexPath, 'GET', $version); } - if (!$parent instanceof \CakeDC\Api\Service\Service && $action instanceof CrudAction) { + if (!$parent instanceof Service && $action instanceof CrudAction) { $table = $action->getTable(); $hasMany = $table->associations()->getByType('HasMany'); foreach ($hasMany as $assoc) { @@ -186,7 +188,7 @@ protected function buildViewLinks(Action $action): array } } - if ($parent instanceof \CakeDC\Api\Service\Service) { + if ($parent instanceof Service) { $parentName = $parent->getName() . ':view'; $path = $this->reverseRouter->parentViewPath($parentName, $action, 'view'); $links[] = $this->reverseRouter->link($parentName, $path, 'GET', $version); diff --git a/src/Service/Action/Extension/CrudRelationsExtension.php b/src/Service/Action/Extension/CrudRelationsExtension.php index eec5a244..13fb7502 100644 --- a/src/Service/Action/Extension/CrudRelationsExtension.php +++ b/src/Service/Action/Extension/CrudRelationsExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -28,6 +28,7 @@ use Cake\Utility\Inflector; use CakeDC\Api\Rbac\ApiRbac; use CakeDC\Api\Service\Action\CrudAction; +use CakeDC\Api\Service\Service; /** * Class CrudRelationsExtension @@ -101,7 +102,7 @@ public function findEntities(Event $event): void * Checks if endpoint returns additional associations. * * @param \CakeDC\Api\Service\Action\CrudAction $action A CrudAction instance. - * @return false|array + * @return array|false */ protected function includeAssociations(CrudAction $action): false|array { @@ -162,7 +163,10 @@ protected function attachAssociations(CrudAction $action, SelectQuery $query): S ->map(fn(string $name): string => Inflector::camelize($name)) ->toArray(); // embed only the associations whose service the current user may access - $tables = array_values(array_filter($tables, fn($name): bool => $this->isRelationAccessible($action, (string)$name))); + $tables = array_values(array_filter( + $tables, + fn($name): bool => $this->isRelationAccessible($action, (string)$name), + )); if ($tables === []) { return $query; } @@ -197,11 +201,11 @@ protected function isRelationAccessible(CrudAction $action, string $path): bool } // a nested service keeps the request from before authorization; the root service has the current one $service = $action->getService(); - while ($service->getParentService() instanceof \CakeDC\Api\Service\Service) { + while ($service->getParentService() instanceof Service) { $service = $service->getParentService(); } $request = $service->getRequest(); - $authorization = $request instanceof \Cake\Http\ServerRequest ? $request->getAttribute('authorization') : null; + $authorization = $request?->getAttribute('authorization'); if (!$authorization instanceof AuthorizationServiceInterface) { Log::debug(sprintf('CrudRelations embeds %s without a permission check: no authorization service', $path), [ 'scope' => ['api'], @@ -226,7 +230,7 @@ protected function isRelationAccessible(CrudAction $action, string $path): bool $table = $action->getTable(); foreach (explode('.', $path) as $name) { $association = $table->associations()->get($name); - if (!$association instanceof \Cake\ORM\Association) { + if (!$association instanceof Association) { // an unknown association fails later, as before return true; } diff --git a/src/Service/Action/Extension/CursorPaginateExtension.php b/src/Service/Action/Extension/CursorPaginateExtension.php index f465b9d5..ba2f6d31 100644 --- a/src/Service/Action/Extension/CursorPaginateExtension.php +++ b/src/Service/Action/Extension/CursorPaginateExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -36,7 +36,7 @@ class CursorPaginateExtension extends Extension implements EventListenerInterfac 'sinceIdField' => 'since_id', ]; - protected \CakeDC\Api\Service\Utility\ReverseRouting $reverseRouter; + protected ReverseRouting $reverseRouter; /** * CursorPaginateExtension constructor. @@ -142,8 +142,10 @@ protected function count(Action $action): ?int $data = $action->getData(); $countField = $this->getConfig('countField'); $maxCount = $this->getConfig('defaultCount'); - if (!empty($countField) && !empty($data[$countField]) && is_numeric($data[$countField])) { - return min((int)$data[$countField], $maxCount); + // a count below 1 falls back to the default; a negative LIMIT is an SQL error or no limit at all + $requested = empty($countField) ? null : $data[$countField] ?? null; + if (is_numeric($requested) && (int)$requested >= 1) { + return min((int)$requested, $maxCount); } return $maxCount; @@ -176,13 +178,9 @@ public function afterFind(EventInterface $event): ?Entity $sinceId = $this->sinceId($action); $maxId = $this->maxId($action); - if ($newSinceId === null) { - $newSinceId = $sinceId; - } + $newSinceId ??= $sinceId; - if ($newMaxId === null) { - $newMaxId = $maxId; - } + $newMaxId ??= $maxId; $indexRoute = $action->getRoute(); $version = $action->getService()->getVersion(); diff --git a/src/Service/Action/Extension/ExtendedSortExtension.php b/src/Service/Action/Extension/ExtendedSortExtension.php index 8e18dd3e..d4deb874 100644 --- a/src/Service/Action/Extension/ExtendedSortExtension.php +++ b/src/Service/Action/Extension/ExtendedSortExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -24,12 +24,14 @@ class ExtendedSortExtension extends Extension implements EventListenerInterface /** * Default settings * + * - `order`: default order. It is applied after the request sort as a tie-breaker, or alone when the request has no valid sort entry. * - `sortableFields`: allowed sort fields. When empty, only action table columns the entity does not hide are allowed. * * @var array */ protected array $_defaultConfig = [ 'sortField' => 'sort', + 'order' => [], 'sortableFields' => [], ]; @@ -67,20 +69,28 @@ public function findEntities(Event $event): void try { $sort = json_decode($data[$sortField], true, 512, JSON_THROW_ON_ERROR); } catch (JsonException) { + $this->logIgnoredSort([sprintf('invalid sort JSON %s', $this->logValue($data[$sortField]))], false); $sort = []; } } $order = []; + $ignored = []; foreach (is_array($sort) ? $sort : [] as $field => $direction) { - $field = $this->sortField($action, $field); - if ($field !== null && is_string($direction)) { - $order[$field] = $this->sortDirection($direction); + $sortField = $this->sortField($action, $field); + if ($sortField !== null) { + $order[$sortField] = $this->sortDirection($direction); + } elseif (is_int($field)) { + $ignored[] = sprintf( + 'list entry %s (use the object form {"field": "asc"})', + $this->logValue($direction), + ); + } else { + $ignored[] = $this->ignoredSortField($field); } } - if ($order !== []) { - $query->orderBy($order); - } + $this->logIgnoredSort($ignored); + $this->order($query, $order, $action); $event->setResult($query); } diff --git a/src/Service/Action/Extension/Extension.php b/src/Service/Action/Extension/Extension.php index 81df005e..af0fbca6 100644 --- a/src/Service/Action/Extension/Extension.php +++ b/src/Service/Action/Extension/Extension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -16,6 +16,7 @@ use Cake\Core\InstanceConfigTrait; use Cake\Event\EventListenerInterface; use CakeDC\Api\Service\Action\ExtensionRegistry; +use CakeDC\Api\Utility\LegacyMemberGuard; /** * Class Extension @@ -31,7 +32,7 @@ abstract class Extension implements EventListenerInterface /** * ExtensionRegistry instance. */ - protected \CakeDC\Api\Service\Action\ExtensionRegistry $registry; + protected ExtensionRegistry $registry; /** * Extension constructor. @@ -41,6 +42,7 @@ abstract class Extension implements EventListenerInterface */ public function __construct(ExtensionRegistry $registry, array $config = []) { + LegacyMemberGuard::check($this, LegacyMemberGuard::ACTION_EXTENSION); $this->registry = $registry; $this->setConfig($config); } diff --git a/src/Service/Action/Extension/FilterExtension.php b/src/Service/Action/Extension/FilterExtension.php index 407cd172..f3d52c46 100644 --- a/src/Service/Action/Extension/FilterExtension.php +++ b/src/Service/Action/Extension/FilterExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; diff --git a/src/Service/Action/Extension/NestedExtension.php b/src/Service/Action/Extension/NestedExtension.php index 58603bd7..db69f69a 100644 --- a/src/Service/Action/Extension/NestedExtension.php +++ b/src/Service/Action/Extension/NestedExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; diff --git a/src/Service/Action/Extension/PaginateExtension.php b/src/Service/Action/Extension/PaginateExtension.php index 15e915d5..6b3f1c0d 100644 --- a/src/Service/Action/Extension/PaginateExtension.php +++ b/src/Service/Action/Extension/PaginateExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -74,7 +74,8 @@ protected function page(Action $action): int { $data = $action->getData(); $pageField = $this->getConfig('pageField'); - if (!empty($data[$pageField]) && is_numeric($data[$pageField])) { + // Query::page() refuses a page below 1 + if (!empty($data[$pageField]) && is_numeric($data[$pageField]) && (int)$data[$pageField] >= 1) { return (int)$data[$pageField]; } @@ -95,8 +96,10 @@ protected function limit(Action $action): mixed if (empty($maxLimit)) { $maxLimit = $this->getConfig('defaultLimit'); } - if (!empty($limitField) && !empty($data[$limitField]) && is_numeric($data[$limitField])) { - return min((int)$data[$limitField], $maxLimit); + // a limit below 1 falls back to the maximum; a negative LIMIT is an SQL error or no limit at all + $requested = empty($limitField) ? null : $data[$limitField] ?? null; + if (is_numeric($requested) && (int)$requested >= 1) { + return min((int)$requested, $maxLimit); } return $maxLimit; diff --git a/src/Service/Action/Extension/SortExtension.php b/src/Service/Action/Extension/SortExtension.php index f9c77ffa..5c2727e2 100644 --- a/src/Service/Action/Extension/SortExtension.php +++ b/src/Service/Action/Extension/SortExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; @@ -28,6 +28,7 @@ class SortExtension extends Extension implements EventListenerInterface /** * Default settings * + * - `order`: default order. It is applied after the request sort as a tie-breaker, or alone when the request has no valid sort field. * - `sortableFields`: allowed sort fields. When empty, only action table columns the entity does not hide are allowed. * * @var array @@ -35,6 +36,7 @@ class SortExtension extends Extension implements EventListenerInterface protected array $_defaultConfig = [ 'sortField' => 'sort', 'directionField' => 'direction', + 'order' => [], 'sortableFields' => [], ]; @@ -66,11 +68,15 @@ public function findEntities(Event $event): void } $data = $action->getData(); - $sort = $this->sortField($action, $data[$this->getConfig('sortField')] ?? null); + $order = []; + $requested = $data[$this->getConfig('sortField')] ?? null; + $sort = $this->sortField($action, $requested); if ($sort !== null) { - $direction = $this->sortDirection($data[$this->getConfig('directionField')] ?? null); - $query->orderBy([$sort => $direction]); + $order[$sort] = $this->sortDirection($data[$this->getConfig('directionField')] ?? null); + } elseif ($requested !== null && $requested !== '') { + $this->logIgnoredSort([$this->ignoredSortField($requested)]); } + $this->order($query, $order, $action); $event->setResult($query); } diff --git a/src/Service/Action/Extension/SortableTrait.php b/src/Service/Action/Extension/SortableTrait.php index 7d704e45..19f3a412 100644 --- a/src/Service/Action/Extension/SortableTrait.php +++ b/src/Service/Action/Extension/SortableTrait.php @@ -2,29 +2,87 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Extension; +use Cake\Log\Log; +use Cake\ORM\Query\SelectQuery; use Cake\ORM\Table; use CakeDC\Api\Service\Action\Action; use CakeDC\Api\Service\Action\CrudAction; /** - * Shared sort field validation for sort extensions. + * Shared sort field validation and default order handling for sort extensions. * - * Uses the `sortableFields` config key of the extension. + * Uses the `order` and `sortableFields` config keys of the extension. * Actions without a table (not a CrudAction) accept only `sortableFields` entries. + * + * @method mixed getConfig(?string $key = null, mixed $default = null) From `InstanceConfigTrait`. */ trait SortableTrait { + /** + * Describes a rejected sort field for the debug log. + * + * @param mixed $field Requested sort field. + * @return string + */ + protected function ignoredSortField(mixed $field): string + { + return sprintf('sort field %s', $this->logValue($field)); + } + + /** + * Logs what a request asked for but did not get, as one line per request, so a client + * whose sort has no effect can be diagnosed. Logged at debug level with the `api` scope. + * + * @param array $ignored Descriptions of the ignored parts. + * @param bool $fieldHint Whether to point at the `sortableFields` setting. + * @return void + */ + protected function logIgnoredSort(array $ignored, bool $fieldHint = true): void + { + if ($ignored === []) { + return; + } + $count = count($ignored); + if ($count > 10) { + $ignored = array_slice($ignored, 0, 10); + $ignored[] = sprintf('%d more', $count - 10); + } + Log::debug( + sprintf( + '%s ignored %s.%s', + static::class, + implode(', ', $ignored), + $fieldHint ? ' Allowed fields can be listed in sortableFields.' : '', + ), + ['scope' => ['api']], + ); + } + + /** + * Encodes a request value for a log line: JSON keeps control characters out of the log. + * + * @param mixed $value Request value. + * @return string + */ + protected function logValue(mixed $value): string + { + $flags = JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR; + $encoded = (string)json_encode($value, $flags); + + return mb_strlen($encoded) > 200 ? mb_substr($encoded, 0, 200) . '...' : $encoded; + } + /** * Returns a safe sort field, or null if the field is not allowed. * @@ -116,4 +174,32 @@ protected function sortDirection(mixed $direction): string return 'asc'; } + + /** + * Applies the request order to the query, followed by the configured default order. + * + * Default order entries for fields already in the request order are skipped. + * + * @param \Cake\ORM\Query\SelectQuery $query Query instance. + * @param array $order Validated request order. + * @param \CakeDC\Api\Service\Action\Action|null $action Action instance. + * @return void + */ + protected function order(SelectQuery $query, array $order, ?Action $action): void + { + $table = $action instanceof CrudAction ? $action->getTable() : null; + foreach ((array)$this->getConfig('order') as $field => $direction) { + if (!is_string($field)) { + $order[] = $direction; + } else { + $field = $this->qualifyField($table, $field); + if (!array_key_exists($field, $order)) { + $order[$field] = $direction; + } + } + } + if ($order !== []) { + $query->orderBy($order); + } + } } diff --git a/src/Service/Action/ExtensionRegistry.php b/src/Service/Action/ExtensionRegistry.php index 1c0dc707..0e28d30f 100644 --- a/src/Service/Action/ExtensionRegistry.php +++ b/src/Service/Action/ExtensionRegistry.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; @@ -37,7 +37,7 @@ class ExtensionRegistry extends ObjectRegistry implements EventDispatcherInterfa /** * The Action that this collection was initialized with. */ - protected ?\CakeDC\Api\Service\Action\Action $action = null; + protected ?Action $action = null; /** * Constructor. @@ -46,7 +46,7 @@ class ExtensionRegistry extends ObjectRegistry implements EventDispatcherInterfa */ public function __construct(?Action $action = null) { - if ($action instanceof \CakeDC\Api\Service\Action\Action) { + if ($action instanceof Action) { $this->action = $action; } } diff --git a/src/Service/Action/ListAction.php b/src/Service/Action/ListAction.php index 0f2de387..8d677111 100644 --- a/src/Service/Action/ListAction.php +++ b/src/Service/Action/ListAction.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; // use Shim\Filesystem\Folder; use Cake\Utility\Inflector; +use Override; /** * Class ListAction @@ -29,11 +30,10 @@ class ListAction extends Action * @param array $config Configuration options passed to the constructor * @return void */ - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); - $this->Auth->allow($this->getName()); } /** diff --git a/src/Service/Action/Recaptcha/ValidateAction.php b/src/Service/Action/Recaptcha/ValidateAction.php index ca5f6348..6adbdccf 100644 --- a/src/Service/Action/Recaptcha/ValidateAction.php +++ b/src/Service/Action/Recaptcha/ValidateAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Recaptcha; @@ -17,7 +17,7 @@ use CakeDC\Api\Service\Action\Traits\ReCaptchaTrait; /** - * Class SocialLoginAction + * Validates the reCaptcha response of the request. * * @package CakeDC\Api\Service\Action */ diff --git a/src/Service/Action/Result.php b/src/Service/Action/Result.php index 9dff9365..06d1d224 100644 --- a/src/Service/Action/Result.php +++ b/src/Service/Action/Result.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action; @@ -30,7 +30,7 @@ class Result /** * Response data * - * @var array|mixed + * @var mixed|array */ protected $data; @@ -42,7 +42,7 @@ class Result /** * Exception structure */ - protected ?\Exception $exception = null; + protected ?Exception $exception = null; /** * Result constructor. @@ -63,7 +63,7 @@ public function __construct(?array $data = null, ?int $code = null) /** * Gets a result data. * - * @return array|mixed + * @return mixed|array */ public function getData(): mixed { @@ -73,7 +73,7 @@ public function getData(): mixed /** * Sets a result data. * - * @param array|mixed $value data to be delivered for the api + * @param mixed|array $value data to be delivered for the api * @return self */ public function setData($value): self @@ -122,7 +122,7 @@ public function getException(): ?Exception * @param \Exception $value exception to be delivered for the api * @return self */ - public function setException(\Exception $value): self + public function setException(Exception $value): self { $this->exception = $value; @@ -145,7 +145,7 @@ public function appendPayload(string $key, $value): void * Gets a result payload. * * @param string $key Payload key. - * @return array|null|mixed Payload + * @return mixed|array|null Payload */ public function getPayload(?string $key = null): mixed { @@ -185,7 +185,7 @@ public function toArray(): array 'data' => $this->data, 'payload' => $this->payload, ]; - if ($this->exception instanceof \Exception) { + if ($this->exception instanceof Exception) { $info['exception'] = $this->exception->getMessage(); $info['exceptionStack'] = $this->exception->getTraceAsString(); } diff --git a/src/Service/Action/Traits/ReCaptchaTrait.php b/src/Service/Action/Traits/ReCaptchaTrait.php index 54e00801..49a81267 100644 --- a/src/Service/Action/Traits/ReCaptchaTrait.php +++ b/src/Service/Action/Traits/ReCaptchaTrait.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Action\Traits; @@ -16,6 +16,7 @@ use Cake\Core\Configure; use Cake\Log\Log; use CakeDC\Api\Utility\RequestParser; +use ReCaptcha\ReCaptcha; /** * Covers registration features and email token validation @@ -35,13 +36,14 @@ public function validateReCaptcha($recaptchaResponse = null): bool if (Configure::read('Api.reCaptcha.disabled') === true) { return true; } - // turning validation off is a global setting; a domain setting only logs a warning, without a - // scope so that the application's default logs record it + // the domain can come from the client's Referer header, so its settings must not turn the + // check off: a client could name a domain that has it disabled. The warnings carry no scope, + // so the application's default logs record them. $domain = RequestParser::getDomain($this->getService()->getRequest()); if (Configure::read('Api.reCaptcha.' . $domain . '.disabled')) { Log::warning(sprintf( '`Api.reCaptcha.%s.disabled` is ignored; set `Api.reCaptcha.disabled` to true instead', - $domain + $domain, )); } @@ -51,8 +53,9 @@ public function validateReCaptcha($recaptchaResponse = null): bool return false; } - if ($recaptchaResponse === null) { - $recaptchaResponse = $this->getService()->getRequest()->getData('g-recaptcha-response'); + $recaptchaResponse ??= $this->getService()->getRequest()->getData('g-recaptcha-response'); + if (!is_string($recaptchaResponse) || $recaptchaResponse === '') { + return false; } $resp = $recaptcha->verify($recaptchaResponse, $this->getService()->getRequest()->clientIp()); @@ -64,12 +67,12 @@ public function validateReCaptcha($recaptchaResponse = null): bool * * @return \ReCaptcha\ReCaptcha|null */ - protected function getReCaptchaInstance(): ?\ReCaptcha\ReCaptcha + protected function getReCaptchaInstance(): ?ReCaptcha { $domain = RequestParser::getDomain($this->getService()->getRequest()); $reCaptchaSecret = Configure::read('Api.reCaptcha.' . $domain . '.secret'); if (!empty($reCaptchaSecret)) { - return new \ReCaptcha\ReCaptcha($reCaptchaSecret); + return new ReCaptcha($reCaptchaSecret); } return null; diff --git a/src/Service/Attribute/ApiActions.php b/src/Service/Attribute/ApiActions.php index 0150d528..fb9e66e3 100644 --- a/src/Service/Attribute/ApiActions.php +++ b/src/Service/Attribute/ApiActions.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; @@ -26,7 +26,7 @@ readonly class ApiActions { /** - * @param string|array $actions Action class names. + * @param array|string $actions Action class names. */ public function __construct( public string|array $actions, diff --git a/src/Service/Attribute/ApiDelete.php b/src/Service/Attribute/ApiDelete.php index 29142c34..00c16bfe 100644 --- a/src/Service/Attribute/ApiDelete.php +++ b/src/Service/Attribute/ApiDelete.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ApiGet.php b/src/Service/Attribute/ApiGet.php index 30b08a8c..262999ff 100644 --- a/src/Service/Attribute/ApiGet.php +++ b/src/Service/Attribute/ApiGet.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ApiOptions.php b/src/Service/Attribute/ApiOptions.php index 1a97cfbd..1fe03d42 100644 --- a/src/Service/Attribute/ApiOptions.php +++ b/src/Service/Attribute/ApiOptions.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ApiPatch.php b/src/Service/Attribute/ApiPatch.php index 05eb8aaf..21f9f755 100644 --- a/src/Service/Attribute/ApiPatch.php +++ b/src/Service/Attribute/ApiPatch.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ApiPost.php b/src/Service/Attribute/ApiPost.php index 089fd1ab..f6e38a21 100644 --- a/src/Service/Attribute/ApiPost.php +++ b/src/Service/Attribute/ApiPost.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ApiPut.php b/src/Service/Attribute/ApiPut.php index 0dcc9731..9c98952b 100644 --- a/src/Service/Attribute/ApiPut.php +++ b/src/Service/Attribute/ApiPut.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ApiResource.php b/src/Service/Attribute/ApiResource.php index 4c0ea3f7..5ab58dde 100644 --- a/src/Service/Attribute/ApiResource.php +++ b/src/Service/Attribute/ApiResource.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ApiRoute.php b/src/Service/Attribute/ApiRoute.php index e7bcabc5..92f9fcae 100644 --- a/src/Service/Attribute/ApiRoute.php +++ b/src/Service/Attribute/ApiRoute.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; @@ -27,7 +27,7 @@ /** * @param string $action Action name (route key). * @param string $path Route path, relative to the service resource (or `ApiScope` prefix). Supports `{placeholder}` params. - * @param string|array $method HTTP method(s). + * @param array|string $method HTTP method(s). * @param bool $mapCors Register an OPTIONS route for CORS preflight. * @param string|null $name Optional route name. * @param array $patterns Regex patterns for route placeholders. diff --git a/src/Service/Attribute/ApiScope.php b/src/Service/Attribute/ApiScope.php index 364581ce..c6f414cc 100644 --- a/src/Service/Attribute/ApiScope.php +++ b/src/Service/Attribute/ApiScope.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; diff --git a/src/Service/Attribute/ServiceAttributeConnector.php b/src/Service/Attribute/ServiceAttributeConnector.php index 4188dcf8..56605260 100644 --- a/src/Service/Attribute/ServiceAttributeConnector.php +++ b/src/Service/Attribute/ServiceAttributeConnector.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Attribute; @@ -192,15 +192,20 @@ protected function routeAttributes(array $infos): array * @param \CakeDC\Api\Service\Attribute\ApiRoute $route Route attribute. * @return void */ - protected function connectRoute(Service $service, array $state, string $actionClass, string $actionName, ApiRoute $route): void - { + protected function connectRoute( + Service $service, + array $state, + string $actionClass, + string $actionName, + ApiRoute $route, + ): void { $path = trim($state['scopePath'], '/') . '/' . trim($route->path, '/'); $path = trim($path, '/'); $options = [ 'method' => (array)$route->method, 'mapCors' => $route->mapCors, - ] + $route->defaults; + ] + array_merge($state['scopeDefaults'], $route->defaults); if ($path !== '') { $options['path'] = $path; diff --git a/src/Service/Auth/Auth.php b/src/Service/Auth/Auth.php index d27921a5..e840430a 100644 --- a/src/Service/Auth/Auth.php +++ b/src/Service/Auth/Auth.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ /** @@ -22,7 +22,7 @@ * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 0.10.0 - * @license http://www.opensource.org/licenses/mit-license.php MIT License + * @license https://www.opensource.org/licenses/mit-license.php MIT License */ namespace CakeDC\Api\Service\Auth; @@ -37,6 +37,9 @@ /** * Class Auth * + * @deprecated 14.0.0 Not part of the request lifecycle: the allow list is never read. Access is decided by the + * AuthenticationMiddleware and the RBAC rules in api_permissions.php (`bypassAuth` for public endpoints). + * Will be removed in 15.0.0. * @package CakeDC\Api\Service\Auth */ class Auth @@ -85,6 +88,9 @@ class Auth 'identityAttribute' => 'identity', ]; + /** + * @var mixed + */ protected $registry; /** @@ -162,7 +168,7 @@ protected function setDefaults(): void * $this->Auth->allow('view'); * $this->Auth->allow(['edit', 'add']); * - * @param string|array $actions Controller action name or array of actions + * @param array|string $actions Controller action name or array of actions * @return void */ public function allow($actions): void @@ -185,7 +191,7 @@ public function allow($actions): void * ``` * to remove all items from the allowed list * - * @param string|array|null $actions Controller action name or array of actions + * @param array|string|null $actions Controller action name or array of actions * @return void */ public function deny($actions = null): void diff --git a/src/Service/Auth/AuthenticateTrait.php b/src/Service/Auth/AuthenticateTrait.php index 2423dbf6..096898fc 100644 --- a/src/Service/Auth/AuthenticateTrait.php +++ b/src/Service/Auth/AuthenticateTrait.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Auth; @@ -27,6 +27,8 @@ /** * Class AuthenticateTrait * + * @deprecated 14.0.0 Used only by the deprecated Auth class. Use Action::getIdentity() or the request's + * `identity` attribute set by the AuthenticationMiddleware. Will be removed in 15.0.0. * @package CakeDC\Api\Service\Auth */ trait AuthenticateTrait @@ -61,7 +63,7 @@ public function getAuthenticationService(): AuthenticationServiceInterface if ($service === null) { throw new Exception( 'The request object does not contain the required `authentication` attribute. Verify the ' . - 'AuthenticationMiddleware has been added.' + 'AuthenticationMiddleware has been added.', ); } @@ -200,7 +202,7 @@ public function setIdentity(ArrayAccess $identity) $result = $service->persistIdentity( $this->getRequest(), $this->getResponse(), - $identity + $identity, ); $this->setRequest($result['request']); @@ -230,7 +232,7 @@ public function impersonate(ArrayAccess $impersonated) $this->getRequest(), $this->getResponse(), $identity, - $impersonated + $impersonated, ); if (!$service->isImpersonating($this->getRequest())) { @@ -256,7 +258,7 @@ public function stopImpersonating() /** @psalm-var array{request: \Cake\Http\ServerRequest, response: \Cake\Http\Response} $result */ $result = $service->stopImpersonating( $this->getRequest(), - $this->getResponse() + $this->getResponse(), ); if ($service->isImpersonating($this->getRequest())) { @@ -280,7 +282,7 @@ public function isImpersonating(): bool $service = $this->getImpersonationAuthenticationService(); return $service->isImpersonating( - $this->getRequest() + $this->getRequest(), ); } @@ -296,7 +298,7 @@ protected function getImpersonationAuthenticationService(): ImpersonationInterfa if (!($service instanceof ImpersonationInterface)) { $className = $service::class; throw new InvalidArgumentException( - sprintf('The %s must implement ImpersonationInterface in order to use impersonation.', $className) + sprintf('The %s must implement ImpersonationInterface in order to use impersonation.', $className), ); } diff --git a/src/Service/Auth/TwoFactorAuthentication/DefaultOneTimePasswordAuthenticationChecker.php b/src/Service/Auth/TwoFactorAuthentication/DefaultOneTimePasswordAuthenticationChecker.php index c5fe1c45..20c14b4d 100644 --- a/src/Service/Auth/TwoFactorAuthentication/DefaultOneTimePasswordAuthenticationChecker.php +++ b/src/Service/Auth/TwoFactorAuthentication/DefaultOneTimePasswordAuthenticationChecker.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Auth\TwoFactorAuthentication; diff --git a/src/Service/Auth/TwoFactorAuthentication/DefaultWebauthn2fAuthenticationChecker.php b/src/Service/Auth/TwoFactorAuthentication/DefaultWebauthn2fAuthenticationChecker.php index a9bd3397..54453b79 100644 --- a/src/Service/Auth/TwoFactorAuthentication/DefaultWebauthn2fAuthenticationChecker.php +++ b/src/Service/Auth/TwoFactorAuthentication/DefaultWebauthn2fAuthenticationChecker.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Auth\TwoFactorAuthentication; diff --git a/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerFactory.php b/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerFactory.php index 443e40c3..38b5da84 100644 --- a/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerFactory.php +++ b/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerFactory.php @@ -2,17 +2,18 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Auth\TwoFactorAuthentication; use Cake\Core\Configure; +use InvalidArgumentException; /** * Factory for two authentication checker @@ -37,6 +38,6 @@ public function build(): OneTimePasswordAuthenticationCheckerInterface } $message = "Invalid config for 'OneTimePasswordAuthenticator.checker', " . sprintf("'%s' does not implement '%s'", $className, $required); - throw new \InvalidArgumentException($message); + throw new InvalidArgumentException($message); } } diff --git a/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerInterface.php b/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerInterface.php index 3f5cc5c8..8debc4ec 100644 --- a/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerInterface.php +++ b/src/Service/Auth/TwoFactorAuthentication/OneTimePasswordAuthenticationCheckerInterface.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Auth\TwoFactorAuthentication; diff --git a/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerFactory.php b/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerFactory.php index 3f429940..e0c20a2c 100644 --- a/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerFactory.php +++ b/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerFactory.php @@ -2,17 +2,18 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2018, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Auth\TwoFactorAuthentication; use Cake\Core\Configure; +use InvalidArgumentException; /** * Factory for two authentication checker @@ -37,6 +38,6 @@ public function build(): Webauthn2fAuthenticationCheckerInterface } $message = "Invalid config for 'Webauthn2fa.checker', " . sprintf("'%s' does not implement '%s'", $className, $required); - throw new \InvalidArgumentException($message); + throw new InvalidArgumentException($message); } } diff --git a/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerInterface.php b/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerInterface.php index ee86f9f9..821ea791 100644 --- a/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerInterface.php +++ b/src/Service/Auth/TwoFactorAuthentication/Webauthn2fAuthenticationCheckerInterface.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2019, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Auth\TwoFactorAuthentication; diff --git a/src/Service/AuthService.php b/src/Service/AuthService.php index f5d0a4d0..af20be5d 100644 --- a/src/Service/AuthService.php +++ b/src/Service/AuthService.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; @@ -32,6 +32,7 @@ use CakeDC\Api\Service\Action\Auth\Webauthn2faAuthOptionsAction; use CakeDC\Api\Service\Action\Auth\Webauthn2faRegisterAction; use CakeDC\Api\Service\Action\Auth\Webauthn2faRegisterOptionsAction; +use Override; /** * Class AuthService @@ -43,7 +44,7 @@ class AuthService extends Service /** * @inheritDoc */ - #[\Override] + #[Override] public function initialize(): void { parent::initialize(); @@ -81,7 +82,7 @@ public function initialize(): void * @param array $route Action route. * @return array */ - #[\Override] + #[Override] protected function actionOptions(array $route): array { $options = []; diff --git a/src/Service/ConfigReader.php b/src/Service/ConfigReader.php index 7b746d1d..d11976f4 100644 --- a/src/Service/ConfigReader.php +++ b/src/Service/ConfigReader.php @@ -2,19 +2,21 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; +use ArrayAccess; use Cake\Core\Configure; use Cake\Utility\Hash; use Cake\Utility\Inflector; +use CakeDC\Api\Service\Locator\ServiceLocator; class ConfigReader { @@ -32,6 +34,11 @@ public function serviceOptions(string $serviceName, ?string $version = null): ar $versionDefaults = $this->checkServiceOptions($version . '.default.options'); $options = $this->checkServiceOptions(sprintf('%s.%s.options', $version, $serviceName)); $options = $this->mergeWithDefaults($options, $versionDefaults, true); + if ($this->readsUnversionedOptions($serviceName, $version)) { + // the keys under the version override the unversioned ones + $unversioned = $this->checkServiceOptions($serviceName . '.options'); + $options = $this->mergeWithDefaults($options, $unversioned, true); + } } else { $options = $this->checkServiceOptions($serviceName . '.options'); } @@ -57,11 +64,21 @@ public function actionOptions(string $serviceName, string $actionName, ?string $ $versionDefaultsByName = $this->checkServiceOptions(sprintf('%s.default.Action.%s', $version, $actionName)); $byServiceDefault = $this->checkServiceOptions(sprintf('%s.%s.Action.default', $version, $serviceName)); - $byServiceOptions = $this->checkServiceOptions(sprintf('%s.%s.Action.%s', $version, $serviceName, $actionName)); + $byServiceOptions = $this->checkServiceOptions( + sprintf('%s.%s.Action.%s', $version, $serviceName, $actionName), + ); $options = $this->mergeWithDefaults($byServiceOptions, $byServiceDefault); $options = $this->mergeWithDefaults($options, $versionDefaultsByName); $options = $this->mergeWithDefaults($options, $versionDefaults); + if ($this->readsUnversionedOptions($serviceName, $version)) { + // the keys under the version override the unversioned ones + $unversioned = $this->mergeWithDefaults( + $this->checkServiceOptions(sprintf('%s.Action.%s', $serviceName, $actionName)), + $this->checkServiceOptions($serviceName . '.Action.default'), + ); + $options = $this->mergeWithDefaults($unversioned, $options); + } } else { $byServiceDefault = $this->checkServiceOptions($serviceName . '.Action.default'); $byServiceOptions = $this->checkServiceOptions(sprintf('%s.Action.%s', $serviceName, $actionName)); @@ -74,13 +91,49 @@ public function actionOptions(string $serviceName, string $actionName, ?string $ return $this->mergeWithDefaults($defaults, $options); } + /** + * Whether a service of the version also reads the unversioned `Api.Service.` keys. + * + * Two kinds of version do. The default version, which serves URLs without a version, so that + * options an application set before it had versions keep applying to those URLs. And a version + * without a service class of its own: the unversioned class serves it, and its options, such as + * an extension that scopes the query, must not be skipped by asking for another version. + * + * @param string $serviceName Service name. + * @param string $version Version with its prefix, such as `v1`. + * @return bool + */ + protected function readsUnversionedOptions(string $serviceName, string $version): bool + { + if ($this->isDefaultVersion($version)) { + return true; + } + $locator = ServiceRegistry::getServiceLocator(); + + // another locator decides on its own which class serves a version + return $locator instanceof ServiceLocator && !$locator->hasVersionedClass($serviceName, $version); + } + + /** + * Whether the version is `Api.defaultVersion`, the one that serves URLs without a version. + * + * @param string $version Version with its prefix, such as `v1`. + * @return bool + */ + protected function isDefaultVersion(string $version): bool + { + $default = (string)Configure::read('Api.defaultVersion'); + + return $default !== '' && $version === (Configure::read('Api.versionPrefix') ?: 'v') . $default; + } + /** * Check options existence by prefix. * * @param string $prefix Path prefix. * @return \ArrayAccess|array */ - protected function checkServiceOptions(string $prefix): \ArrayAccess|array + protected function checkServiceOptions(string $prefix): ArrayAccess|array { $data = Configure::read('Api.Service'); if (is_array($data) && Hash::check($data, $prefix)) { diff --git a/src/Service/CrudService.php b/src/Service/CrudService.php index d0aa5756..1b71e5b8 100644 --- a/src/Service/CrudService.php +++ b/src/Service/CrudService.php @@ -2,18 +2,25 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; use Cake\Utility\Inflector; +use CakeDC\Api\Service\Action\CrudAddAction; +use CakeDC\Api\Service\Action\CrudDeleteAction; +use CakeDC\Api\Service\Action\CrudDescribeAction; +use CakeDC\Api\Service\Action\CrudEditAction; +use CakeDC\Api\Service\Action\CrudIndexAction; +use CakeDC\Api\Service\Action\CrudViewAction; +use Override; /** * Class CrudService @@ -28,12 +35,12 @@ abstract class CrudService extends Service * @var array */ protected array $actionsClassMap = [ - 'describe' => \CakeDC\Api\Service\Action\CrudDescribeAction::class, - 'index' => \CakeDC\Api\Service\Action\CrudIndexAction::class, - 'view' => \CakeDC\Api\Service\Action\CrudViewAction::class, - 'add' => \CakeDC\Api\Service\Action\CrudAddAction::class, - 'edit' => \CakeDC\Api\Service\Action\CrudEditAction::class, - 'delete' => \CakeDC\Api\Service\Action\CrudDeleteAction::class, + 'describe' => CrudDescribeAction::class, + 'index' => CrudIndexAction::class, + 'view' => CrudViewAction::class, + 'add' => CrudAddAction::class, + 'edit' => CrudEditAction::class, + 'delete' => CrudDeleteAction::class, ]; /** @@ -92,7 +99,7 @@ public function setTable(string $table) * @param array $route Activated route. * @return array */ - #[\Override] + #[Override] protected function actionOptions(array $route): array { $id = null; diff --git a/src/Service/DescribeService.php b/src/Service/DescribeService.php index a2e753f1..f449a911 100644 --- a/src/Service/DescribeService.php +++ b/src/Service/DescribeService.php @@ -2,19 +2,21 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; use Cake\Routing\RouteBuilder; use CakeDC\Api\Routing\ApiRouter; +use CakeDC\Api\Service\Action\DescribeAction; +use Override; class DescribeService extends Service { @@ -22,13 +24,13 @@ class DescribeService extends Service * @var array */ protected array $actionsClassMap = [ - 'describe' => \CakeDC\Api\Service\Action\DescribeAction::class, + 'describe' => DescribeAction::class, ]; /** * @inheritDoc */ - #[\Override] + #[Override] public function loadRoutes(): void { $builder = ApiRouter::createRouteBuilder('/', []); diff --git a/src/Service/Exception/MissingActionException.php b/src/Service/Exception/MissingActionException.php index 3fc182b4..f40dc706 100644 --- a/src/Service/Exception/MissingActionException.php +++ b/src/Service/Exception/MissingActionException.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Exception; -class MissingActionException extends \Cake\Core\Exception\CakeException +use Cake\Core\Exception\CakeException; + +class MissingActionException extends CakeException { protected string $_messageTemplate = 'Action class %s could not be found.'; } diff --git a/src/Service/Exception/MissingExtensionException.php b/src/Service/Exception/MissingExtensionException.php index f296cf67..6764f2e4 100644 --- a/src/Service/Exception/MissingExtensionException.php +++ b/src/Service/Exception/MissingExtensionException.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Exception; -class MissingExtensionException extends \Cake\Core\Exception\CakeException +use Cake\Core\Exception\CakeException; + +class MissingExtensionException extends CakeException { protected string $_messageTemplate = 'Extension class %s could not be found.'; } diff --git a/src/Service/Exception/MissingParserException.php b/src/Service/Exception/MissingParserException.php index 4e927c7e..a0f49efe 100644 --- a/src/Service/Exception/MissingParserException.php +++ b/src/Service/Exception/MissingParserException.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Exception; -class MissingParserException extends \Cake\Core\Exception\CakeException +use Cake\Core\Exception\CakeException; + +class MissingParserException extends CakeException { protected string $_messageTemplate = 'Request Parser class %s could not be found.'; } diff --git a/src/Service/Exception/MissingRendererException.php b/src/Service/Exception/MissingRendererException.php index 08c393d2..e4c43f08 100644 --- a/src/Service/Exception/MissingRendererException.php +++ b/src/Service/Exception/MissingRendererException.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Exception; -class MissingRendererException extends \Cake\Core\Exception\CakeException +use Cake\Core\Exception\CakeException; + +class MissingRendererException extends CakeException { protected string $_messageTemplate = 'Renderer class %s could not be found.'; } diff --git a/src/Service/Extension/CollectionExtension.php b/src/Service/Extension/CollectionExtension.php index 44bcc0dc..1bc934b0 100644 --- a/src/Service/Extension/CollectionExtension.php +++ b/src/Service/Extension/CollectionExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Extension; @@ -17,10 +17,11 @@ use Cake\Event\EventListenerInterface; use CakeDC\Api\Service\Action\Collection\AddEditAction; use CakeDC\Api\Service\Action\Collection\DeleteAction; +use CakeDC\Api\Service\Service; class CollectionExtension extends Extension implements EventListenerInterface { - protected \CakeDC\Api\Service\Service $service; + protected Service $service; /** * Returns a list of events this object is implementing. When the class is registered diff --git a/src/Service/Extension/Extension.php b/src/Service/Extension/Extension.php index 4b52ff86..c5b498d8 100644 --- a/src/Service/Extension/Extension.php +++ b/src/Service/Extension/Extension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Extension; @@ -16,6 +16,7 @@ use Cake\Core\InstanceConfigTrait; use Cake\Event\EventListenerInterface; use CakeDC\Api\Service\ExtensionRegistry; +use CakeDC\Api\Utility\LegacyMemberGuard; /** * Class Extension @@ -31,7 +32,7 @@ abstract class Extension implements EventListenerInterface /** * ExtensionRegistry instance. */ - protected \CakeDC\Api\Service\ExtensionRegistry $registry; + protected ExtensionRegistry $registry; /** * Extension constructor. @@ -41,6 +42,7 @@ abstract class Extension implements EventListenerInterface */ public function __construct(ExtensionRegistry $registry, array $config = []) { + LegacyMemberGuard::check($this, LegacyMemberGuard::SERVICE_EXTENSION); $this->registry = $registry; $this->setConfig($config); } diff --git a/src/Service/Extension/LogExtension.php b/src/Service/Extension/LogExtension.php index aeaf8dfa..e128d30e 100644 --- a/src/Service/Extension/LogExtension.php +++ b/src/Service/Extension/LogExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Extension; @@ -16,6 +16,8 @@ use Cake\Event\EventInterface; use Cake\Event\EventListenerInterface; use Cake\Log\LogTrait; +use CakeDC\Api\Service\Action\Action; +use CakeDC\Api\Service\Service; use JsonSerializable; use Psr\Log\LogLevel; use stdClass; @@ -36,9 +38,9 @@ class LogExtension extends Extension implements EventListenerInterface 'redact' => ['password', 'token', 'secret', 'authorization'], ]; - protected \CakeDC\Api\Service\Service $service; + protected Service $service; - protected \CakeDC\Api\Service\Action\Action $action; + protected Action $action; protected ?float $timer = null; @@ -84,7 +86,7 @@ public function afterProcess(EventInterface $event): void unset($result['exceptionStack']); $log = [ 'url' => $url, - 'method' => env('REQUEST_METHOD'), + 'method' => $this->service->getRequest()?->getMethod(), 'duration' => $duration . 'ms', 'input' => $this->redact($data), 'result' => json_encode($this->redact($result), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), @@ -98,7 +100,7 @@ public function afterProcess(EventInterface $event): void * @param mixed $data Request data or result. * @return mixed */ - protected function redact($data): mixed + protected function redact($data) { // a query serializes to a result set, which serializes to its rows while ($data instanceof JsonSerializable) { diff --git a/src/Service/Extension/OptionsHandlerExtension.php b/src/Service/Extension/OptionsHandlerExtension.php index 2c8e0b5c..38ea249d 100644 --- a/src/Service/Extension/OptionsHandlerExtension.php +++ b/src/Service/Extension/OptionsHandlerExtension.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Extension; @@ -40,6 +40,8 @@ public function implementedEvents(): array /** * Cors process before dispatch. * + * The result is set on the event; the method itself always returns null. + * * @param \Cake\Event\EventInterface $event An Event instance * @return \CakeDC\Api\Service\Action\Result|null * @throws \Exception @@ -61,11 +63,9 @@ public function onDispatch(EventInterface $event): ?Result 'CakeDC/Api.Cors', ], ]); - $action->Auth->allow('options'); $result = $service->getResult(); $result->setData($action->process()); - - return $result; + $event->setResult($result); } return null; diff --git a/src/Service/ExtensionRegistry.php b/src/Service/ExtensionRegistry.php index 13ec30c6..11fce19a 100644 --- a/src/Service/ExtensionRegistry.php +++ b/src/Service/ExtensionRegistry.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; @@ -37,7 +37,7 @@ class ExtensionRegistry extends ObjectRegistry implements EventDispatcherInterfa /** * The Service that this collection was initialized with. */ - protected ?\CakeDC\Api\Service\Service $service = null; + protected ?Service $service = null; /** * Constructor. @@ -46,7 +46,7 @@ class ExtensionRegistry extends ObjectRegistry implements EventDispatcherInterfa */ public function __construct(?Service $service = null) { - if ($service instanceof \CakeDC\Api\Service\Service) { + if ($service instanceof Service) { $this->service = $service; } } diff --git a/src/Service/FallbackService.php b/src/Service/FallbackService.php index a171dcfe..719e24e0 100644 --- a/src/Service/FallbackService.php +++ b/src/Service/FallbackService.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; @@ -17,6 +17,7 @@ use Cake\Routing\RouteBuilder; use Cake\Utility\Inflector; use CakeDC\Api\Routing\ApiRouter; +use Override; /** * Class FallbackService @@ -39,7 +40,7 @@ class FallbackService extends NestedCrudService * * @return void */ - #[\Override] + #[Override] public function initialize(): void { parent::initialize(); @@ -53,7 +54,7 @@ public function initialize(): void * * @return void */ - #[\Override] + #[Override] public function loadRoutes(): void { $table = $this->fetchTable($this->table); diff --git a/src/Service/ListingService.php b/src/Service/ListingService.php index 931ff89f..824ee9cb 100644 --- a/src/Service/ListingService.php +++ b/src/Service/ListingService.php @@ -2,19 +2,21 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; use Cake\Routing\RouteBuilder; use CakeDC\Api\Routing\ApiRouter; +use CakeDC\Api\Service\Action\ListAction; +use Override; /** * Class ListingService @@ -24,7 +26,7 @@ class ListingService extends Service { protected array $actionsClassMap = [ - 'list' => \CakeDC\Api\Service\Action\ListAction::class, + 'list' => ListAction::class, ]; /** @@ -32,7 +34,7 @@ class ListingService extends Service * * @return void */ - #[\Override] + #[Override] public function loadRoutes(): void { $builder = ApiRouter::createRouteBuilder('/', []); diff --git a/src/Service/Locator/LocatorAwareTrait.php b/src/Service/Locator/LocatorAwareTrait.php index 35757caa..4799a002 100644 --- a/src/Service/Locator/LocatorAwareTrait.php +++ b/src/Service/Locator/LocatorAwareTrait.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Locator; @@ -28,7 +28,7 @@ trait LocatorAwareTrait protected $serviceLocator; /** - * Sets the table locator. + * Sets the service locator. * * @param \CakeDC\Api\Service\Locator\LocatorInterface $serviceLocator LocatorInterface instance. * @return self @@ -41,11 +41,11 @@ public function setServiceLocator(LocatorInterface $serviceLocator): self } /** - * Gets the table locator. + * Gets the service locator, by default the one of ServiceRegistry. * * @return \CakeDC\Api\Service\Locator\LocatorInterface */ - public function getServiceLocator(): \CakeDC\Api\Service\Locator\LocatorInterface + public function getServiceLocator(): LocatorInterface { if (!$this->serviceLocator) { $this->serviceLocator = ServiceRegistry::getServiceLocator(); diff --git a/src/Service/Locator/LocatorInterface.php b/src/Service/Locator/LocatorInterface.php index 8e684c75..e8b280f2 100644 --- a/src/Service/Locator/LocatorInterface.php +++ b/src/Service/Locator/LocatorInterface.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Locator; @@ -33,7 +33,7 @@ public function getConfig(?string $alias = null): array; * Stores a list of options to be used when instantiating an object * with a matching alias. * - * @param string|array $alias Name of the alias or array to completely + * @param array|string $alias Name of the alias or array to completely * overwrite current config. * @param array|null $options list of options for the alias * @return $this diff --git a/src/Service/Locator/ServiceLocator.php b/src/Service/Locator/ServiceLocator.php index ecf2cb36..d98b3a56 100644 --- a/src/Service/Locator/ServiceLocator.php +++ b/src/Service/Locator/ServiceLocator.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Locator; @@ -49,7 +49,7 @@ class ServiceLocator implements LocatorInterface * Stores a list of options to be used when instantiating an object * with a matching alias. * - * @param string|array $alias Name of the alias or array to completely overwrite current config. + * @param array|string $alias Name of the alias or array to completely overwrite current config. * @param array|null $options list of options for the alias * @return \CakeDC\Api\Service\Locator\LocatorInterface * @throws \RuntimeException When you attempt to configure an existing table instance. @@ -65,7 +65,7 @@ public function setConfig($alias, ?array $options = null): LocatorInterface if (isset($this->instances[$alias])) { throw new RuntimeException(sprintf( 'You cannot configure "%s", service has already been constructed.', - $alias + $alias, )); } @@ -130,7 +130,7 @@ public function get(string $alias, array $options = []): Service if ($options !== [] && !$this->compareOptions($alias, $options)) { throw new RuntimeException(sprintf( 'You cannot configure "%s", it already exists in the registry.', - $alias + $alias, )); } @@ -149,24 +149,11 @@ public function get(string $alias, array $options = []): Service $options['className'] = Inflector::camelize($alias); } - $className = $this->getClassName($alias, $options); - $lookupPlugins = Configure::read('Api.serviceLookupPlugins'); $lookupMode = Configure::read('Api.lookupMode', 'underscore'); - if ($lookupPlugins === null) { - $lookupPlugins = ['CakeDC/Api']; - } - if (!$className && !str_contains($options['className'], '.')) { - foreach ($lookupPlugins as $candidate) { - if ($lookupMode === 'dasherize') { - $options['className'] = Inflector::camelize(Inflector::underscore($options['className'])); - } - - $options['className'] = $candidate . '.' . $options['className']; - $className = $this->getClassName($alias, $options); - if ($className) { - break; - } - } + $className = $this->lookupClassName($alias, $options); + if (!$className && Configure::read('Api.useVersioning')) { + // a version without its own class is served by the unversioned class, not the fallback + $className = $this->lookupClassName($alias, ['unversioned' => true] + $options); } if ($className) { if ($lookupMode === 'dasherize') { @@ -194,6 +181,58 @@ public function get(string $alias, array $options = []): Service return $this->instances[$alias]; } + /** + * Whether the service has a class of its own for the version, such as `Service/v2/ArticlesService`. + * + * Without one, get() serves the version with the unversioned class, or with the fallback service. + * + * @param string $alias The service name. + * @param string $version The version with its prefix, such as `v2`. + * @return bool + */ + public function hasVersionedClass(string $alias, string $version): bool + { + if (!Configure::read('Api.useVersioning')) { + return false; + } + $alias = Inflector::camelize($alias); + $options = ['version' => $version] + ($this->config[$alias] ?? []); + if (empty($options['className'])) { + $options['className'] = $alias; + } + + return $this->lookupClassName($alias, $options) !== null; + } + + /** + * Finds the service class in the application, then in the lookup plugins. + * + * @param string $alias The alias name you want to get. + * @param array $options Method options array. + * @return string|null + */ + protected function lookupClassName(string $alias, array $options): ?string + { + $className = $this->getClassName($alias, $options); + if ($className || str_contains($options['className'], '.')) { + return $className; + } + $lookupMode = Configure::read('Api.lookupMode', 'underscore'); + foreach (Configure::read('Api.serviceLookupPlugins') ?? ['CakeDC/Api'] as $candidate) { + if ($lookupMode === 'dasherize') { + $options['className'] = Inflector::camelize(Inflector::underscore($options['className'])); + } + + $options['className'] = $candidate . '.' . $options['className']; + $className = $this->getClassName($alias, $options); + if ($className) { + return $className; + } + } + + return null; + } + /** * Gets the method class name. * @@ -203,18 +242,19 @@ public function get(string $alias, array $options = []): Service */ protected function getClassName(string $alias, array $options = []): ?string { - $useVersions = Configure::read('Api.useVersioning'); - if ($useVersions) { + $version = ''; + if (Configure::read('Api.useVersioning') && empty($options['unversioned'])) { $versionPrefix = Configure::read('Api.versionPrefix'); if (empty($versionPrefix)) { $versionPrefix = 'v'; } - if (empty($options['version'])) { - $options['version'] = $versionPrefix . Configure::read('Api.defaultVersion'); + $defaultVersion = (string)Configure::read('Api.defaultVersion'); + if (empty($options['version']) && $defaultVersion !== '') { + $options['version'] = $versionPrefix . $defaultVersion; + } + if (!empty($options['version'])) { + $version = '/' . $options['version']; } - $version = '/' . $options['version']; - } else { - $version = ''; } if (empty($options['className'])) { $options['className'] = Inflector::camelize($alias); @@ -229,7 +269,7 @@ protected function getClassName(string $alias, array $options = []): ?string * @param array $options The alias to check for. * @return \CakeDC\Api\Service\Service */ - protected function create(array $options): \CakeDC\Api\Service\Service + protected function create(array $options): Service { return new $options['className']($options); } @@ -281,7 +321,7 @@ public function remove(string $alias): void unset( $this->instances[$alias], $this->config[$alias], - $this->fallbacked[$alias] + $this->fallbacked[$alias], ); } diff --git a/src/Service/NestedCrudService.php b/src/Service/NestedCrudService.php index ba9a33f4..700c1570 100644 --- a/src/Service/NestedCrudService.php +++ b/src/Service/NestedCrudService.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; use Cake\Utility\Hash; use Cake\Utility\Inflector; +use Override; /** * Class NestedCrudService @@ -44,7 +45,7 @@ public function __construct(array $config = []) * @param array $route Action route, * @return array */ - #[\Override] + #[Override] protected function actionOptions(array $route): array { $parent = $this->getParentService(); diff --git a/src/Service/RecaptchaService.php b/src/Service/RecaptchaService.php index 15f55b8f..545e3471 100644 --- a/src/Service/RecaptchaService.php +++ b/src/Service/RecaptchaService.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2023, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2023, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; use CakeDC\Api\Service\Action\Recaptcha\ValidateAction; +use Override; /** * Class RecaptchaService @@ -25,7 +26,7 @@ class RecaptchaService extends Service /** * @inheritDoc */ - #[\Override] + #[Override] public function initialize(): void { parent::initialize(); diff --git a/src/Service/Renderer/BaseRenderer.php b/src/Service/Renderer/BaseRenderer.php index 86e43af8..ec610ccc 100644 --- a/src/Service/Renderer/BaseRenderer.php +++ b/src/Service/Renderer/BaseRenderer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Renderer; @@ -16,6 +16,7 @@ use Cake\Core\Configure; use CakeDC\Api\Service\Action\Result; use CakeDC\Api\Service\Service; +use CakeDC\Api\Utility\LegacyMemberGuard; use Exception; /** @@ -26,7 +27,7 @@ abstract class BaseRenderer /** * Reference to the Service. */ - protected ?\CakeDC\Api\Service\Service $service = null; + protected ?Service $service = null; /** * Constructor @@ -35,6 +36,7 @@ abstract class BaseRenderer */ public function __construct(Service $service) { + LegacyMemberGuard::check($this, LegacyMemberGuard::RENDERER); $this->service = $service; } diff --git a/src/Service/Renderer/FileRenderer.php b/src/Service/Renderer/FileRenderer.php index dc585089..6a36c4d6 100644 --- a/src/Service/Renderer/FileRenderer.php +++ b/src/Service/Renderer/FileRenderer.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Renderer; use Cake\Core\Configure; +use Cake\Http\Exception\NotFoundException; use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Result; use Exception; @@ -33,10 +34,18 @@ class FileRenderer extends BaseRenderer */ public function response(?Result $result = null): bool { - $response = $this->service - ->getResponse() - ->withFile($result->getData()) - ->withStatus($result->getCode()); + try { + $response = $this->service + ->getResponse() + ->withFile($result->getData()) + ->withStatus($result->getCode()); + } catch (NotFoundException $notFoundException) { + // a missing file is a 404, not the generic 400 of an exception thrown while rendering + $this->error($notFoundException); + $this->service->setResponse($this->service->getResponse()->withStatus(404)); + + return true; + } $this->service->setResponse($response); return true; diff --git a/src/Service/Renderer/FlysystemRenderer.php b/src/Service/Renderer/FlysystemRenderer.php index 59231642..88bbbdab 100644 --- a/src/Service/Renderer/FlysystemRenderer.php +++ b/src/Service/Renderer/FlysystemRenderer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Renderer; @@ -20,10 +20,11 @@ use CakeDC\Api\Service\Action\Result; use Exception; use Laminas\Diactoros\Stream; -use League\Flysystem\File; -use League\Flysystem\FileNotFoundException; -use League\Flysystem\Filesystem; -use League\Flysystem\Handler; +use League\Flysystem\CorruptedPathDetected; +use League\Flysystem\FilesystemOperator; +use League\Flysystem\PathTraversalDetected; +use League\Flysystem\UnableToRetrieveMetadata; +use Override; /** * Class FlysystemRenderer to render file using Flysystem library @@ -38,58 +39,75 @@ class FlysystemRenderer extends FileRenderer * @param \CakeDC\Api\Service\Action\Result $result The result object returned by the Service. * @return bool */ - #[\Override] + #[Override] public function response(?Result $result = null): bool { $data = $result->getData(); + /** @var \League\Flysystem\FilesystemOperator $filesystem */ + $filesystem = Hash::get($data, 'filesystem'); + $path = (string)Hash::get($data, 'path'); try { - /** @var \League\Flysystem\File $file */ - $file = $this->getFile( - Hash::get($data, 'filesystem'), - Hash::get($data, 'path') - ); + if (!$filesystem->fileExists($path)) { + $this->notFound(); + + return true; + } $name = Hash::get($data, 'name'); $this->service->setResponse( - $this->deliverAsset($this->service->getResponse(), $file, $name) + $this->deliverAsset($this->service->getResponse(), $filesystem, $path, $name), ); - } catch (FileNotFoundException) { - $response = $this->service->getResponse() - ->withStatus(404); - - $this->service->setResponse($response); + } catch (PathTraversalDetected | CorruptedPathDetected) { + // an invalid path cannot name an existing file; other storage errors (permissions, + // an unreachable backend) are not a 404 and reach the service's error handling + $this->notFound(); } return true; } /** - * Get flysystem file object + * Sets a 404 response. * - * @param \League\Flysystem\Filesystem $filesystem custom filesystem - * @param string $path of file at filesystem - * @return \League\Flysystem\Handler + * @return void */ - protected function getFile(Filesystem $filesystem, string $path): Handler + protected function notFound(): void { - return $filesystem->get($path); + $response = $this->service->getResponse() + ->withStatus(404); + + $this->service->setResponse($response); } /** * Deliver the asset stream in body * * @param \Cake\Http\Response $response service response - * @param \League\Flysystem\File $file file object + * @param \League\Flysystem\FilesystemOperator $filesystem filesystem with the file + * @param string $path path of file at filesystem * @param string|null $name file name shown to user * @return \Cake\Http\Response + * @throws \League\Flysystem\FilesystemException */ - public function deliverAsset(Response $response, File $file, ?string $name): Response - { - $contentType = $file->getType(); - $modified = $file->getTimestamp() ?: time(); + public function deliverAsset( + Response $response, + FilesystemOperator $filesystem, + string $path, + ?string $name, + ): Response { + try { + $contentType = $filesystem->mimeType($path); + } catch (UnableToRetrieveMetadata) { + $contentType = 'application/octet-stream'; + } + try { + $modified = $filesystem->lastModified($path); + } catch (UnableToRetrieveMetadata) { + $modified = time(); + } $expire = strtotime((string)Configure::read('Api.Flysystem.expire')) ?: time(); $maxAge = $expire - time(); - $stream = new Stream($file->readStream()); + $stream = new Stream($filesystem->readStream($path)); return $response->withBody($stream) // Content @@ -109,7 +127,7 @@ public function deliverAsset(Response $response, File $file, ?string $name): Res * @param \Exception $exception thrown at service or action * @return void */ - #[\Override] + #[Override] public function error(Exception $exception): void { $code = $exception->getCode(); diff --git a/src/Service/Renderer/JSendRenderer.php b/src/Service/Renderer/JSendRenderer.php index f88af457..984eb485 100644 --- a/src/Service/Renderer/JSendRenderer.php +++ b/src/Service/Renderer/JSendRenderer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Renderer; @@ -18,6 +18,7 @@ use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Result; use Exception; +use Override; use stdClass; /** @@ -58,7 +59,7 @@ class JSendRenderer extends BaseRenderer * * @return bool */ - #[\Override] + #[Override] public function accept(): bool { $request = $this->service->getRequest(); diff --git a/src/Service/Renderer/JsonRenderer.php b/src/Service/Renderer/JsonRenderer.php index 466a0a07..c645dd0c 100644 --- a/src/Service/Renderer/JsonRenderer.php +++ b/src/Service/Renderer/JsonRenderer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Renderer; diff --git a/src/Service/Renderer/RawRenderer.php b/src/Service/Renderer/RawRenderer.php index 448e5e8c..ecfe8f36 100644 --- a/src/Service/Renderer/RawRenderer.php +++ b/src/Service/Renderer/RawRenderer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Renderer; diff --git a/src/Service/Renderer/XmlRenderer.php b/src/Service/Renderer/XmlRenderer.php index 2477be1e..1442a0be 100644 --- a/src/Service/Renderer/XmlRenderer.php +++ b/src/Service/Renderer/XmlRenderer.php @@ -2,25 +2,28 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Renderer; +use Cake\Chronos\Chronos; +use Cake\Chronos\ChronosDate; +use Cake\Chronos\ChronosTime; use Cake\Collection\Collection; use Cake\Core\Configure; use Cake\Datasource\EntityInterface; use Cake\Datasource\ResultSetInterface; -use Cake\I18n\DateTime; use Cake\Utility\Xml; use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Result; +use DateTimeInterface; use Exception; /** @@ -81,6 +84,8 @@ protected function format($content = null): array { if (is_array($content) || $content instanceof Collection || $content instanceof ResultSetInterface) { $data = $this->array($content); + } elseif ($this->formatDate($content) !== null) { + $data = ['value' => $this->formatDate($content)]; } elseif (is_object($content)) { $data = $this->object($content); } else { @@ -105,12 +110,10 @@ protected function object(object $data): array $data = $data->toArray(); } foreach ($data as $name => $value) { - if ($value instanceof \DateTime) { + $date = $this->formatDate($value); + if ($date !== null) { $property = []; - $property['@'] = $value->format(\DateTime::ISO8601); - } elseif ($value instanceof DateTime) { - $property = []; - $property['@'] = $value->toIso8601String(); + $property['@'] = $date; } elseif (is_object($value)) { $property = $this->object($value); } elseif (is_array($value)) { @@ -131,7 +134,7 @@ protected function object(object $data): array /** * Formats an array as an XML node. * - * @param array|\Cake\Collection\Collection $data The array to process. + * @param \Cake\Collection\Collection|array $data The array to process. * @return array */ protected function array($data): array @@ -144,7 +147,11 @@ protected function array($data): array foreach ($data as $name => $value) { $item = []; $item['@key'] = $name; - if (is_object($value)) { + $date = $this->formatDate($value); + if ($date !== null) { + $item = []; + $item['@'] = $date; + } elseif (is_object($value)) { $item = $this->object($value); } elseif (is_array($value)) { $item = $this->array($value); @@ -160,10 +167,34 @@ protected function array($data): array return $xml; } + /** + * Formats a date or time value as a string. + * + * @param mixed $value The value to process. + * @return string|null The formatted value, or null when the value is not a date or time. + */ + protected function formatDate(mixed $value): ?string + { + if ($value instanceof Chronos) { + return $value->toIso8601String(); + } + if ($value instanceof DateTimeInterface) { + return $value->format(DateTimeInterface::ATOM); + } + if ($value instanceof ChronosDate) { + return $value->format('Y-m-d'); + } + if ($value instanceof ChronosTime) { + return $value->format('H:i:s'); + } + + return null; + } + /** * Encoded object as xml. * - * @param array|object $data Encoded data. + * @param object|array $data Encoded data. * @return string */ protected function encode(object|array $data): string diff --git a/src/Service/RequestParser/BaseParser.php b/src/Service/RequestParser/BaseParser.php index 069efac8..e80a2a6c 100644 --- a/src/Service/RequestParser/BaseParser.php +++ b/src/Service/RequestParser/BaseParser.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\RequestParser; use CakeDC\Api\Service\Service; +use CakeDC\Api\Utility\LegacyMemberGuard; /** * Base class for a Service content negotiation Adapter. @@ -23,7 +24,7 @@ abstract class BaseParser /** * Reference to the Service. */ - protected ?\CakeDC\Api\Service\Service $service = null; + protected ?Service $service = null; /** * Constructor @@ -32,6 +33,7 @@ abstract class BaseParser */ public function __construct(Service $service) { + LegacyMemberGuard::check($this, LegacyMemberGuard::PARSER); $this->service = $service; } diff --git a/src/Service/RequestParser/FormParser.php b/src/Service/RequestParser/FormParser.php index 8ce48afe..20046adc 100644 --- a/src/Service/RequestParser/FormParser.php +++ b/src/Service/RequestParser/FormParser.php @@ -2,17 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\RequestParser; +use Cake\Http\ServerRequest; +use RuntimeException; + /** * Parse form based data representation. */ @@ -26,8 +29,8 @@ class FormParser extends BaseParser public function getParams(): array { $request = $this->service->getRequest(); - if (!$request instanceof \Cake\Http\ServerRequest) { - throw new \RuntimeException('Request is not available in the parser.'); + if (!$request instanceof ServerRequest) { + throw new RuntimeException('Request is not available in the parser.'); } if ($request->is(['post', 'put'])) { return (array)$request->getData(); diff --git a/src/Service/Service.php b/src/Service/Service.php index 1edb4072..3be85530 100644 --- a/src/Service/Service.php +++ b/src/Service/Service.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; @@ -20,6 +20,7 @@ use Cake\Datasource\Exception\RecordNotFoundException; use Cake\Event\EventDispatcherInterface; use Cake\Event\EventDispatcherTrait; +use Cake\Event\EventInterface; use Cake\Event\EventListenerInterface; use Cake\Event\EventManager; use Cake\Http\Response; @@ -38,6 +39,7 @@ use CakeDC\Api\Service\Exception\MissingRendererException; use CakeDC\Api\Service\Renderer\BaseRenderer; use CakeDC\Api\Service\RequestParser\BaseParser; +use CakeDC\Api\Utility\LegacyMemberGuard; use Exception; use ReflectionClass; use ReflectionNamedType; @@ -102,12 +104,12 @@ abstract class Service implements EventListenerInterface, EventDispatcherInterfa /** * Parser class to process the HTTP request. */ - protected ?\CakeDC\Api\Service\RequestParser\BaseParser $parser = null; + protected ?BaseParser $parser = null; /** * Renderer class to build the HTTP response. */ - protected ?\CakeDC\Api\Service\Renderer\BaseRenderer $renderer = null; + protected ?BaseRenderer $renderer = null; /** * The parser class. @@ -129,12 +131,12 @@ abstract class Service implements EventListenerInterface, EventDispatcherInterfa /** * Parent service instance. */ - protected ?\CakeDC\Api\Service\Service $parentService = null; + protected ?Service $parentService = null; /** * Service Action Result object. */ - protected ?\CakeDC\Api\Service\Action\Result $result = null; + protected ?Result $result = null; /** * Base url for service. @@ -146,24 +148,24 @@ abstract class Service implements EventListenerInterface, EventDispatcherInterfa /** * Request */ - protected ?\Cake\Http\ServerRequest $request = null; + protected ?ServerRequest $request = null; /** * Request */ - protected \Cake\Http\Response $response; + protected Response $response; protected string $corsSuffix = '_cors'; /** * Extension registry. */ - protected ?\CakeDC\Api\Service\ExtensionRegistry $_extensions = null; + protected ?ExtensionRegistry $_extensions = null; /** * Action instance populated on prepare step. */ - protected ?\CakeDC\Api\Service\Action\Action $action = null; + protected ?Action $action = null; /** * Container @@ -180,6 +182,7 @@ abstract class Service implements EventListenerInterface, EventDispatcherInterfa */ public function __construct(array $config = []) { + LegacyMemberGuard::check($this, LegacyMemberGuard::SERVICE); if (isset($config['request'])) { $this->setRequest($config['request']); } @@ -232,7 +235,7 @@ public function __construct(array $config = []) public function initialize(): void { if ($this->name === null) { - $className = (new \ReflectionClass($this))->getShortName(); + $className = (new ReflectionClass($this))->getShortName(); $this->setName(Inflector::underscore(str_replace('Service', '', $className))); } @@ -401,6 +404,8 @@ public function routerDefaultOptions(): array $mapList[$alias] = $map; $mapList[$alias] += ['method' => 'GET', 'path' => '', 'action' => $alias]; if ($mapCors) { + // the route name belongs to the action route only + unset($map['name']); $map['method'] = 'OPTIONS'; $map += ['path' => '', 'action' => $alias . $this->corsSuffix]; $mapList[$alias . $this->corsSuffix] = $map; @@ -417,7 +422,7 @@ public function routerDefaultOptions(): array * * Returns an URL pointing to a combination of controller and action. * - * @param string|array|null $route An array specifying any of the following: + * @param array|string|null $route An array specifying any of the following: * 'controller', 'action', 'plugin' additionally, you can provide routed * elements or query string parameters. If string it can be name any valid url * string. @@ -625,7 +630,7 @@ public function buildAction(): Action $service->setParentService($this); } $action = $route['action']; - [$namespace, $serviceClass] = namespaceSplit($service instanceof \CakeDC\Api\Service\Service ? $service::class : self::class); + [$namespace, $serviceClass] = namespaceSplit($service instanceof Service ? $service::class : self::class); $actionPrefix = substr($serviceClass, 0, -7); $actionClass = $namespace . '\\Action\\' . $actionPrefix . Inflector::camelize($action) . 'Action'; if (class_exists($actionClass)) { @@ -749,10 +754,10 @@ protected function actionOptions(array $route): array */ public function getResult(): Result { - if ($this->parentService instanceof \CakeDC\Api\Service\Service) { + if ($this->parentService instanceof Service) { return $this->parentService->getResult(); } - if (!$this->result instanceof \CakeDC\Api\Service\Action\Result) { + if (!$this->result instanceof Result) { $this->result = new Result(); } @@ -767,7 +772,7 @@ public function getResult(): Result */ public function setResult(Result $result) { - if ($this->parentService instanceof \CakeDC\Api\Service\Service) { + if ($this->parentService instanceof Service) { $this->parentService->setResult($result); return $this; @@ -785,11 +790,11 @@ public function setResult(Result $result) */ public function respond(?Result $result = null): Response { - if (!$result instanceof \CakeDC\Api\Service\Action\Result) { + if (!$result instanceof Result) { $result = $this->getResult(); } $this->setResponse($this->getResponse()->withStatus($result->getCode())); - if ($result->getException() instanceof \Exception) { + if ($result->getException() instanceof Exception) { $this->getRenderer() ->error($result->getException()); } else { @@ -861,9 +866,7 @@ public function mapAction(string $actionName, string $className, array $route): if ($route['mapCors']) { $this->actionsClassMap[$actionName . $this->corsSuffix] = DummyAction::class; } - if (!isset($route['path'])) { - $route['path'] = $actionName; - } + $route['path'] ??= $actionName; $this->actions[$actionName] = $route; } @@ -880,9 +883,10 @@ public function mapAction(string $actionName, string $className, array $route): public function addAction(string $actionName, array $route): void { $route += ['mapCors' => false]; - if (!isset($route['path'])) { - $route['path'] = $actionName; + if ($route['mapCors']) { + $this->actionsClassMap[$actionName . $this->corsSuffix] = DummyAction::class; } + $route['path'] ??= $actionName; $this->actions[$actionName] = $route; } @@ -940,7 +944,7 @@ public function implementedEvents(): array */ public function getExtensions(): ExtensionRegistry { - if (!$this->_extensions instanceof \CakeDC\Api\Service\ExtensionRegistry) { + if (!$this->_extensions instanceof ExtensionRegistry) { $this->_extensions = new ExtensionRegistry($this); } @@ -955,7 +959,7 @@ public function getExtensions(): ExtensionRegistry */ public function setExtensions(?ExtensionRegistry $extensions): self { - if (!$extensions instanceof \CakeDC\Api\Service\ExtensionRegistry) { + if (!$extensions instanceof ExtensionRegistry) { $extensions = new ExtensionRegistry($this); } $this->_extensions = $extensions; @@ -976,8 +980,8 @@ protected function loadExtensions(): void } $registry = $this->getExtensions(); $extensions = $registry->normalizeArray($this->extensions); - foreach ($extensions as $properties) { - $instance = $registry->load($properties['class'], $properties['config']); + foreach ($extensions as $name => $config) { + $instance = $registry->load((string)$name, $config); $this->_eventManager->on($instance); } } @@ -1032,7 +1036,7 @@ protected function initializeRenderer(array $config): void * @param bool $forceCors Force cors. * @return \Cake\Event\EventInterface */ - public function triggerBeforeDispatch($forceCors = false): \Cake\Event\EventInterface + public function triggerBeforeDispatch($forceCors = false): EventInterface { return $this->dispatchEvent('Service.beforeDispatch', ['service' => $this, 'force' => $forceCors]); } diff --git a/src/Service/ServiceRegistry.php b/src/Service/ServiceRegistry.php index 0887c5db..64fcf441 100644 --- a/src/Service/ServiceRegistry.php +++ b/src/Service/ServiceRegistry.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service; @@ -20,7 +20,7 @@ class ServiceRegistry /** * LocatorInterface implementation instance. */ - protected static ?\CakeDC\Api\Service\Locator\LocatorInterface $locator = null; + protected static ?LocatorInterface $locator = null; /** * Default LocatorInterface implementation class. @@ -32,9 +32,9 @@ class ServiceRegistry * * @return \CakeDC\Api\Service\Locator\LocatorInterface */ - public static function getServiceLocator(): \CakeDC\Api\Service\Locator\LocatorInterface + public static function getServiceLocator(): LocatorInterface { - if (!static::$locator instanceof \CakeDC\Api\Service\Locator\LocatorInterface) { + if (!static::$locator instanceof LocatorInterface) { static::$locator = new static::$defaultLocatorClass(); } diff --git a/src/Service/Utility/ReverseRouting.php b/src/Service/Utility/ReverseRouting.php index 226153d2..f062853a 100644 --- a/src/Service/Utility/ReverseRouting.php +++ b/src/Service/Utility/ReverseRouting.php @@ -2,21 +2,23 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Service\Utility; use Cake\Core\Configure; +use Cake\Routing\Route\Route; use Cake\Routing\Router; use Cake\Utility\Inflector; use CakeDC\Api\Service\Action\Action; +use CakeDC\Api\Service\Service; /** * Class ReverseRouting @@ -66,10 +68,10 @@ public function indexPath(Action $action, ?callable $beforeReverse = null): arra $indexRoute = $action->getRoute(); $parent = $action->getService()->getParentService(); $path = null; - if ($parent instanceof \CakeDC\Api\Service\Service) { + if ($parent instanceof Service) { $parentRoutes = $parent->routes(); $currentRoute = $this->findRoute($indexRoute, $parentRoutes); - if ($currentRoute instanceof \Cake\Routing\Route\Route) { + if ($currentRoute instanceof Route) { if (is_callable($beforeReverse)) { $indexRoute = $beforeReverse($indexRoute); } @@ -122,7 +124,7 @@ public function parentViewPath(string $parentName, Action $action, string $type) * @param array $routes List of all routes. * @return \Cake\Routing\Route\Route|null */ - public function findRoute(array $route, array $routes): ?\Cake\Routing\Route\Route + public function findRoute(array $route, array $routes): ?Route { foreach ($routes as $item) { if ($this->compareDefaults($item->defaults, $route)) { diff --git a/src/TestSuite/IntegrationTestCase.php b/src/TestSuite/IntegrationTestCase.php index 7b7154f1..fac2e9a5 100644 --- a/src/TestSuite/IntegrationTestCase.php +++ b/src/TestSuite/IntegrationTestCase.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\TestSuite; @@ -17,6 +17,7 @@ use Cake\Datasource\EntityInterface; use Cake\ORM\TableRegistry; use Cake\TestSuite\IntegrationTestTrait; +use Cake\TestSuite\TestCase; use Cake\Utility\Hash; use Cake\View\Exception\MissingTemplateException; use CakeDC\Api\Service\ServiceRegistry; @@ -26,7 +27,7 @@ * * @package CakeDC\Api\TestSuite */ -class IntegrationTestCase extends \Cake\TestSuite\TestCase +class IntegrationTestCase extends TestCase { use IntegrationTestTrait; @@ -94,9 +95,7 @@ public function getDefaultUser(?string $userId = null): ?string */ protected function userToken(?string $userId = null): mixed { - if ($userId === null) { - $userId = $this->getDefaultUser(); - } + $userId ??= $this->getDefaultUser(); $Users = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); if ($userId) { $user = $Users->find() @@ -126,7 +125,7 @@ public function sendRequest( string $method, $data = [], ?string $userId = null, - array $headers = [] + array $headers = [], ): void { ServiceRegistry::getServiceLocator()->clear(); $userToken = $this->userToken($userId); @@ -225,9 +224,7 @@ public function assertError($result, ?int $code = null): void */ public function assertStatus(int $code, ?string $message = null): void { - if ($message === null) { - $message = sprintf('Status code %d does not match', $code); - } + $message ??= sprintf('Status code %d does not match', $code); $this->assertResponseCode($code, $message); } diff --git a/src/TestSuite/TestCase.php b/src/TestSuite/TestCase.php index c8a5ea18..7cdd524d 100644 --- a/src/TestSuite/TestCase.php +++ b/src/TestSuite/TestCase.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\TestSuite; diff --git a/src/Transformer/AbstractTransformer.php b/src/Transformer/AbstractTransformer.php index 11351bb5..10129eab 100644 --- a/src/Transformer/AbstractTransformer.php +++ b/src/Transformer/AbstractTransformer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2025, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2025, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Transformer; @@ -16,6 +16,8 @@ use Cake\Datasource\EntityInterface; use Cake\I18n\Date; use Cake\I18n\DateTime; +use DateTime as NativeDateTime; +use Exception; /** * Abstract Transformer @@ -89,14 +91,14 @@ protected function timestamp($date): ?string return $date->toIso8601String(); } - if ($date instanceof \DateTime) { + if ($date instanceof NativeDateTime) { return $date->format('c'); } if (is_string($date)) { try { return (new DateTime($date))->toIso8601String(); - } catch (\Exception) { + } catch (Exception) { return null; } } diff --git a/src/Transformer/TransformerInterface.php b/src/Transformer/TransformerInterface.php index eb888918..a51c74b9 100644 --- a/src/Transformer/TransformerInterface.php +++ b/src/Transformer/TransformerInterface.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2025, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2025, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Transformer; diff --git a/src/Utility/LegacyMemberGuard.php b/src/Utility/LegacyMemberGuard.php new file mode 100644 index 00000000..033a32c6 --- /dev/null +++ b/src/Utility/LegacyMemberGuard.php @@ -0,0 +1,223 @@ + [ + '_executeAction', '_loadExtensions', '_initializeAuth', '_authConfig', '_afterIdentifyUser', + '_afterRegister', '_registerOptions', '_changePassword', '_validateMany', '_saveMany', '_newEntities', + '_validateDataIsArray', '_deleteMany', '_newEntity', '_patchEntity', '_getEntities', '_getEntitiesQuery', + '_getEntity', '_getEntityQuery', '_buildViewCondition', '_save', '_describe', '_getReCaptchaInstance', + // SecondFactorTrait, with an underscore only in 12.0.2 and 12.0.3 + '_hasVerifiedOtp', '_hasWebauthnCredential', '_refuseEnrollmentIf', + ], + 'properties' => [ + '_service', '_route', '_name', '_identifiedField', '_passwordField', '_table', '_id', '_idName', + '_parentId', '_parentIdName', '_finder', + ], + ]; + + public const SERVICE = [ + 'methods' => [ + '_actionOptions', '_routesWrapper', '_prepareAction', '_processAction', '_loadExtensions', + '_initializeParser', '_initializeRenderer', + ], + 'properties' => [ + '_actionsClassMap', '_table', '_idName', '_parentIdName', '_actions', '_routeExtensions', '_routePrefix', + '_name', '_version', '_parser', '_renderer', '_parserClass', '_rendererClass', '_innerServices', + '_parentService', '_result', '_baseUrl', '_request', '_response', '_corsSuffix', '_action', + ], + ]; + + public const ACTION_EXTENSION = [ + 'methods' => [ + '_userCleanup', '_autocompleteList', '_buildIndexLinks', '_buildViewLinks', '_includeAssociations', + '_includeDirectAssociations', '_attachAssociations', '_isRelationAccessible', '_relatedServiceName', + '_sinceId', '_maxId', '_count', '_page', '_limit', '_sortField', '_qualifyField', '_sortDirection', + ], + 'properties' => [ + '_reverseRouter', '_registry', + ], + ]; + + public const SERVICE_EXTENSION = [ + 'methods' => [ + '_redact', + ], + 'properties' => [ + '_service', '_registry', '_action', '_timer', + ], + ]; + + public const RENDERER = [ + 'methods' => [ + '_buildMessage', '_stackTrace', '_encode', '_format', '_success', '_fail', '_mapStatus', '_object', + '_array', + ], + 'properties' => [ + '_service', + ], + ]; + + public const PARSER = [ + 'methods' => [], + 'properties' => [ + '_service', + ], + ]; + + /** + * Classes already checked. + * + * @var array + */ + protected static array $checked = []; + + /** + * Throws when a class outside the plugin declares a member with a pre-13.0 name. + * + * @param object $object Instance to check. + * @param array{methods: list, properties: list} $legacy Old member names, with the `_`. + * @return void + * @throws \Cake\Core\Exception\CakeException When an old name is declared. + */ + public static function check(object $object, array $legacy): void + { + $class = $object::class; + if (isset(static::$checked[$class]) || Configure::read('Api.legacyMemberGuard') === false) { + return; + } + // the plugin class the object extends: only a member it renamed can have been overridden + $plugin = new ReflectionClass($object); + while ($plugin && !static::isPluginClass($plugin)) { + $plugin = $plugin->getParentClass(); + } + // the plugin code the object builds on: that class, and the plugin traits its own classes use + $sources = $plugin ? [$plugin] : []; + $reflection = new ReflectionClass($object); + while ($plugin && $reflection && $reflection->getName() !== $plugin->getName()) { + $sources = array_merge($sources, static::pluginTraits($reflection)); + $reflection = $reflection->getParentClass(); + } + $found = []; + $reflection = new ReflectionClass($object); + while ($plugin && $reflection && $reflection->getName() !== $plugin->getName()) { + $name = $reflection->getName(); + foreach ($legacy['methods'] as $method) { + // an old name whose new name the plugin code lacks is a member of the application or + // of another package, such as `_getReCaptchaInstance()` of the cakedc/auth trait + if (!$reflection->hasMethod($method) || !static::has($sources, substr($method, 1), true)) { + continue; + } + $declared = $reflection->getMethod($method); + // a private member cannot have overridden a protected one + if ($declared->class === $name && !$declared->isPrivate()) { + $found[] = sprintf('%s::%s() (now %s())', $name, $method, substr($method, 1)); + } + } + foreach ($legacy['properties'] as $property) { + if (!$reflection->hasProperty($property) || !static::has($sources, substr($property, 1), false)) { + continue; + } + $declared = $reflection->getProperty($property); + if ($declared->class === $name && !$declared->isPrivate()) { + $found[] = sprintf('%s::$%s (now $%s)', $name, $property, substr($property, 1)); + } + } + $reflection = $reflection->getParentClass(); + } + if ($found !== []) { + throw new CakeException(sprintf( + 'These members use names from before CakeDC/Api 13.0, which dropped the leading underscore, ' . + 'so the plugin no longer calls or reads them: %s. Rename them, for example with the Rector set ' . + 'config/rector/cakephp-api-13.php; see docs/Documentation/upgrading.md. ' . + 'To turn this check off, set `Api.legacyMemberGuard` to the boolean false in the application ' . + 'configuration.', + implode(', ', $found), + )); + } + static::$checked[$class] = true; + } + + /** + * The traits of this plugin that a class uses, also through other traits. + * + * @param \ReflectionClass $reflection Class or trait. + * @return list<\ReflectionClass> + */ + protected static function pluginTraits(ReflectionClass $reflection): array + { + $traits = []; + foreach ($reflection->getTraits() as $trait) { + if (static::isPluginClass($trait)) { + $traits[] = $trait; + } + $traits = array_merge($traits, static::pluginTraits($trait)); + } + + return $traits; + } + + /** + * Whether one of the classes or traits has the member. + * + * @param list<\ReflectionClass> $sources Plugin classes and traits. + * @param string $member Member name, without `$`. + * @param bool $method True for a method, false for a property. + * @return bool + */ + protected static function has(array $sources, string $member, bool $method): bool + { + foreach ($sources as $source) { + if ($method ? $source->hasMethod($member) : $source->hasProperty($member)) { + return true; + } + } + + return false; + } + + /** + * Whether the class is a class of this plugin. + * + * An anonymous class is named after its parent, so it is never one. + * + * @param \ReflectionClass $reflection Class. + * @return bool + */ + protected static function isPluginClass(ReflectionClass $reflection): bool + { + $name = $reflection->getName(); + + return !$reflection->isAnonymous() + && str_starts_with($name, 'CakeDC\\Api\\') + && !str_starts_with($name, 'CakeDC\\Api\\Test\\'); + } +} diff --git a/src/Utility/RequestParser.php b/src/Utility/RequestParser.php index a0b02f0a..725bab7d 100644 --- a/src/Utility/RequestParser.php +++ b/src/Utility/RequestParser.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Utility; diff --git a/src/Webauthn/AuthenticateAdapter.php b/src/Webauthn/AuthenticateAdapter.php index 1b78ebb6..f4f34821 100644 --- a/src/Webauthn/AuthenticateAdapter.php +++ b/src/Webauthn/AuthenticateAdapter.php @@ -2,79 +2,113 @@ declare(strict_types=1); /** - * Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Webauthn; use Cake\Http\Exception\BadRequestException; -use Webauthn\AuthenticationExtensions\AuthenticationExtensionsClientInputs; use Webauthn\AuthenticatorAssertionResponse; use Webauthn\AuthenticatorAssertionResponseValidator; +use Webauthn\AuthenticatorSelectionCriteria; +use Webauthn\CredentialRecord; use Webauthn\PublicKeyCredentialRequestOptions; -use Webauthn\PublicKeyCredentialSource; class AuthenticateAdapter extends BaseAdapter { /** + * Store name of the authentication challenge. + */ + protected const CHALLENGE = 'authenticateChallenge'; + + /** + * Creates the authentication options and stores their challenge for verifyResponse(). + * + * Everything else stored for the bearer token, such as a registration challenge, is dropped. + * * @return \Webauthn\PublicKeyCredentialRequestOptions + * @throws \Cake\Http\Exception\BadRequestException Without a bearer token. */ public function getOptions(): PublicKeyCredentialRequestOptions { - $userEntity = $this->getUserEntity(); - $allowedCredentials = array_map(fn(PublicKeyCredentialSource $credential): \Webauthn\PublicKeyCredentialDescriptor => $credential->getPublicKeyCredentialDescriptor(), $this->repository->findAllForUserEntity($userEntity)); - - $options = (new PublicKeyCredentialRequestOptions(random_bytes(32))) - ->setRpId($this->rpEntity->getId()) - ->setUserVerification(PublicKeyCredentialRequestOptions::USER_VERIFICATION_REQUIREMENT_PREFERRED) - ->allowCredentials(...$allowedCredentials) - ->setExtensions(new AuthenticationExtensionsClientInputs()); - - $storeEntity = $this->readStore(); - $storeEntity->store = []; - $storeEntity = $this->patchStore($storeEntity, 'authenticateOptions', base64_encode(serialize($options))); - - $this->store->save($storeEntity); + $challenge = random_bytes(32); + $options = $this->buildOptions($challenge); + $this->storeChallenge(static::CHALLENGE, $challenge, true); return $options; } /** - * Verify the registration response + * Builds the authentication options for a challenge. + * + * Everything but the challenge comes from the settings and the credentials of the user, so + * verifyResponse() builds the same options again from the stored challenge. * - * @return \Webauthn\PublicKeyCredentialSource - * @throws \Throwable + * @param string $challenge Challenge, as binary. + * @return \Webauthn\PublicKeyCredentialRequestOptions */ - public function verifyResponse(): \Webauthn\PublicKeyCredentialSource + protected function buildOptions(string $challenge): PublicKeyCredentialRequestOptions { - $storeEntity = $this->readStore(); - $options = $this->getStore($storeEntity, 'authenticateOptions'); - if ($options) { - $options = unserialize(base64_decode($options)); + $allowedCredentials = []; + foreach ($this->repository->findAllForUserEntity($this->getUserEntity()) as $credential) { + $allowedCredentials[] = $credential->getPublicKeyCredentialDescriptor(); } - $publicKeyCredentialLoader = $this->createPublicKeyCredentialLoader(); - $publicKeyCredential = $publicKeyCredentialLoader->loadArray($this->request->getData()); - $authenticatorAssertionResponse = $publicKeyCredential->getResponse(); - if ($authenticatorAssertionResponse instanceof AuthenticatorAssertionResponse) { - $authenticatorAssertionResponseValidator = $this->createAssertionResponseValidator(); + return PublicKeyCredentialRequestOptions::create( + $challenge, + $this->rpEntity->id, + $allowedCredentials, + AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_PREFERRED, + ); + } + + /** + * Verify the authentication response and store the updated credential, with its new counter. + * + * @return \Webauthn\CredentialRecord + * @throws \Cake\Http\Exception\BadRequestException When no options were requested, the body is not + * an authentication response, or the credential is not one of the user. + * @throws \InvalidArgumentException When the body is not a WebAuthn credential. + * @throws \Webauthn\Exception\WebauthnException When the response does not pass the checks. + */ + public function verifyResponse(): CredentialRecord + { + $challenge = $this->readChallenge(static::CHALLENGE); + // without the challenge there is nothing to verify against + if ($challenge === null) { + throw new BadRequestException(__d('cake_d_c/api', 'Request the authentication options first')); + } + $options = $this->buildOptions($challenge); - return $authenticatorAssertionResponseValidator->check( - $publicKeyCredential->getRawId(), - $authenticatorAssertionResponse, - $options, - $this->request, - $this->getUserEntity()->getId(), + $publicKeyCredential = $this->loadPublicKeyCredential(); + $response = $publicKeyCredential->response; + if (!$response instanceof AuthenticatorAssertionResponse) { + throw new BadRequestException( + __d('cake_d_c/api', 'Could not validate credential response for authentication'), ); } + // the library checks the response against the credential it is given, so find it here + $credential = $this->repository->findOneByCredentialId($publicKeyCredential->rawId); + if (!$credential instanceof CredentialRecord) { + throw new BadRequestException(__d('cake_d_c/api', 'The credential is not registered')); + } + + $credential = $this->createAssertionResponseValidator()->check( + $credential, + $response, + $options, + $this->getHost(), + $this->getUserEntity()->id, + ); + $this->repository->saveCredentialSource($credential); - throw new BadRequestException(__d('cake_d_c/api', 'Could not validate credential response for authentication')); + return $credential; } /** @@ -82,11 +116,8 @@ public function verifyResponse(): \Webauthn\PublicKeyCredentialSource */ protected function createAssertionResponseValidator(): AuthenticatorAssertionResponseValidator { - return new AuthenticatorAssertionResponseValidator( - $this->repository, - null, - $this->createExtensionOutputCheckerHandler(), - $this->getAlgorithmManager() + return AuthenticatorAssertionResponseValidator::create( + $this->getCeremonyStepManagerFactory()->requestCeremony(), ); } } diff --git a/src/Webauthn/Base64Utility.php b/src/Webauthn/Base64Utility.php index 4e90d577..333394e6 100644 --- a/src/Webauthn/Base64Utility.php +++ b/src/Webauthn/Base64Utility.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Webauthn; diff --git a/src/Webauthn/BaseAdapter.php b/src/Webauthn/BaseAdapter.php index a155c94c..197b9045 100644 --- a/src/Webauthn/BaseAdapter.php +++ b/src/Webauthn/BaseAdapter.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Webauthn; use Cake\Core\Configure; +use Cake\Datasource\EntityInterface; +use Cake\Http\Exception\BadRequestException; use Cake\Http\ServerRequest; use Cake\ORM\Table; use Cake\ORM\TableRegistry; @@ -26,18 +28,22 @@ use Cose\Algorithm\Signature\ECDSA\ES256K; use Cose\Algorithm\Signature\ECDSA\ES384; use Cose\Algorithm\Signature\ECDSA\ES512; -use Cose\Algorithm\Signature\EdDSA\Ed256; -use Cose\Algorithm\Signature\EdDSA\Ed512; +use Cose\Algorithm\Signature\EdDSA\EdDSA; use Cose\Algorithm\Signature\RSA\PS256; use Cose\Algorithm\Signature\RSA\PS384; use Cose\Algorithm\Signature\RSA\PS512; use Cose\Algorithm\Signature\RSA\RS256; use Cose\Algorithm\Signature\RSA\RS384; use Cose\Algorithm\Signature\RSA\RS512; -use Webauthn\AttestationStatement\AttestationObjectLoader; +use InvalidArgumentException; +use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; +use Throwable; use Webauthn\AttestationStatement\AttestationStatementSupportManager; -use Webauthn\AttestationStatement\NoneAttestationStatementSupport; use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler; +use Webauthn\CeremonyStep\CeremonyStepManagerFactory; +use Webauthn\PublicKeyCredential; +use Webauthn\PublicKeyCredentialOptions; use Webauthn\PublicKeyCredentialRpEntity; use Webauthn\PublicKeyCredentialUserEntity; @@ -45,17 +51,27 @@ class BaseAdapter { public const STORE_PREFIX = 'api.Webauthn2fa'; - protected \Cake\Http\ServerRequest $request; + protected ServerRequest $request; - protected \CakeDC\Api\Webauthn\Repository\UserCredentialSourceRepository $repository; + protected UserCredentialSourceRepository $repository; - private \Cake\Datasource\EntityInterface $user; + private EntityInterface $user; /** * @var \Webauthn\PublicKeyCredentialRpEntity */ protected PublicKeyCredentialRpEntity $rpEntity; + /** + * The `appName` setting of the domain, sent to the client as the relying party name. + */ + protected string $appName = ''; + + /** + * @var (\Symfony\Component\Serializer\Normalizer\NormalizerInterface&\Symfony\Component\Serializer\Normalizer\DenormalizerInterface)|null + */ + protected (NormalizerInterface&DenormalizerInterface)|null $serializer = null; + /** * @var \CakeDC\Api\Model\Table\AuthStoreTable */ @@ -85,10 +101,15 @@ public function __construct(ServerRequest $request, ?Table $usersTable, $userDat $store = TableRegistry::getTableLocator()->get('CakeDC/Api.AuthStore'); $this->store = $store; $this->readStore(); - $this->rpEntity = new PublicKeyCredentialRpEntity( - Configure::read('Api.Webauthn2fa.' . $this->getDomain() . '.appName'), // The application name - Configure::read('Api.Webauthn2fa.' . $this->getDomain() . '.id') - ); + $rpId = Configure::read('Api.Webauthn2fa.' . $this->getDomain() . '.id'); + // the domain can come from the client's Referer header; without settings for it there is + // no relying party to check a response against + if (!is_string($rpId) || $rpId === '') { + throw new BadRequestException(__d('cake_d_c/api', 'WebAuthn is not configured for this domain')); + } + $this->appName = (string)Configure::read('Api.Webauthn2fa.' . $this->getDomain() . '.appName'); + // web-auth/webauthn-lib deprecates a name on the entity; getOptionsData() sends appName instead + $this->rpEntity = PublicKeyCredentialRpEntity::create('', $rpId); /** * @var \Cake\ORM\Entity $userSession */ @@ -97,7 +118,8 @@ public function __construct(ServerRequest $request, ?Table $usersTable, $userDat $this->repository = new UserCredentialSourceRepository( $request, $this->user, - $usersTable + $usersTable, + $this->getSerializer(), ); } @@ -110,10 +132,10 @@ protected function getUserEntity(): PublicKeyCredentialUserEntity { $user = $this->getUser(); - return new PublicKeyCredentialUserEntity( - $user->webauthn_username ?? $user->username, + return PublicKeyCredentialUserEntity::create( + (string)($user->webauthn_username ?? $user->username), (string)$user->id, - (string)$user->first_name + (string)$user->first_name, ); } @@ -135,7 +157,7 @@ public function getUser(): mixed public function hasCredential(): bool { return (bool)$this->repository->findAllForUserEntity( - $this->getUserEntity() + $this->getUserEntity(), ); } @@ -154,8 +176,15 @@ public function hasCredentialOnAnyDomain(): bool * * @return \CakeDC\Api\Model\Entity\AuthStore */ - public function readStore(): \CakeDC\Api\Model\Entity\AuthStore + public function readStore(): AuthStore { + if ($this->getStoreKey() === '') { + // no bearer token: nothing can have been stored for this request + $entity = $this->store->newEmptyEntity(); + $entity->store = []; + + return $entity; + } /** @var \CakeDC\Api\Model\Entity\AuthStore|null $entity */ $entity = $this->store->find()->where(['id' => $this->getStoreKey()])->first(); if ($entity === null) { @@ -175,11 +204,28 @@ public function readStore(): \CakeDC\Api\Model\Entity\AuthStore * @param array $data The data to save. * @return \CakeDC\Api\Model\Entity\AuthStore|false */ - public function saveStore($data): \CakeDC\Api\Model\Entity\AuthStore|false + public function saveStore($data): AuthStore|false { $entity = $this->readStore(); $entity->store = $data; + return $this->persistStore($entity); + } + + /** + * Save the store entity under the bearer token of the request. + * + * @param \CakeDC\Api\Model\Entity\AuthStore $entity The store entity. + * @return \CakeDC\Api\Model\Entity\AuthStore|false + * @throws \Cake\Http\Exception\BadRequestException Without a bearer token. + */ + protected function persistStore(AuthStore $entity): AuthStore|false + { + // without a token every such request would share one store entry + if ($this->getStoreKey() === '') { + throw new BadRequestException(__d('cake_d_c/api', 'WebAuthn needs a bearer token')); + } + return $this->store->save($entity); } @@ -190,6 +236,9 @@ public function saveStore($data): \CakeDC\Api\Model\Entity\AuthStore|false */ public function deleteStore(): bool { + if ($this->getStoreKey() === '') { + return false; + } $entity = $this->readStore(); return $this->store->delete($entity); @@ -203,7 +252,7 @@ public function deleteStore(): bool public function getStoreKey(): string { $authHeader = $this->request->getHeader('Authorization'); - $authHeader = array_pop($authHeader); + $authHeader = (string)array_pop($authHeader); $options = [ 'tokenPrefix' => 'bearer', @@ -217,12 +266,16 @@ public function getStoreKey(): string * * @param \CakeDC\Api\Model\Entity\AuthStore $entity The entity to patch. * @param string $name The name of the data. - * @param string|array $options The options to patch. + * @param array|string $options The options to patch. * @return \CakeDC\Api\Model\Entity\AuthStore */ - public function patchStore($entity, $name, $options): \CakeDC\Api\Model\Entity\AuthStore + public function patchStore($entity, $name, $options): AuthStore { - $entity->store['api']['Webauthn2fa'][$this->getDomain()][$name] = $options; + $store = (array)$entity->get('store'); + $store['api']['Webauthn2fa'][$this->getDomain()][$name] = $options; + // set the field as a whole: a change inside the array would not mark it dirty, and an + // existing row would keep its old value + $entity->set('store', $store); return $entity; } @@ -257,7 +310,7 @@ public function getDomain($replace = true): string * @return void */ public function setAttestationStatementSupportManager( - AttestationStatementSupportManager $attestationStatementSupportManager + AttestationStatementSupportManager $attestationStatementSupportManager, ): void { $this->attestationStatementSupportManager = $attestationStatementSupportManager; } @@ -267,27 +320,182 @@ public function setAttestationStatementSupportManager( */ protected function getAttestationStatementSupportManager(): AttestationStatementSupportManager { - if (!$this->attestationStatementSupportManager instanceof \Webauthn\AttestationStatement\AttestationStatementSupportManager) { + if (!$this->attestationStatementSupportManager instanceof AttestationStatementSupportManager) { + // the manager supports the `none` attestation format, and no other one unless added $this->attestationStatementSupportManager = new AttestationStatementSupportManager(); - $this->attestationStatementSupportManager - ->add(new NoneAttestationStatementSupport()); } return $this->attestationStatementSupportManager; } /** - * @return \CakeDC\Api\Webauthn\PublicKeyCredentialLoader + * The serializer that reads client responses and stored credentials, and writes options. + * + * @return \Symfony\Component\Serializer\Normalizer\NormalizerInterface&\Symfony\Component\Serializer\Normalizer\DenormalizerInterface + */ + protected function getSerializer(): NormalizerInterface&DenormalizerInterface + { + return $this->serializer ??= WebauthnSerializer::create($this->getAttestationStatementSupportManager()); + } + + /** + * The factory of the checks that a registration or an authentication response must pass. + * + * The origin of the response must be HTTPS and its host the relying party id or a subdomain of it. + * + * @return \Webauthn\CeremonyStep\CeremonyStepManagerFactory */ - protected function createPublicKeyCredentialLoader(): PublicKeyCredentialLoader + protected function getCeremonyStepManagerFactory(): CeremonyStepManagerFactory { - $attestationObjectLoader = new AttestationObjectLoader( - $this->getAttestationStatementSupportManager() - ); + $factory = new CeremonyStepManagerFactory(); + $factory->setAlgorithmManager($this->getAlgorithmManager()); + $factory->setAttestationStatementSupportManager($this->getAttestationStatementSupportManager()); + $factory->setExtensionOutputCheckerHandler($this->createExtensionOutputCheckerHandler()); - return new PublicKeyCredentialLoader( - $attestationObjectLoader - ); + return $factory; + } + + /** + * The host of the request, which the checks use when the relying party has no id. + * + * @return string + */ + protected function getHost(): string + { + return $this->request->getUri()->getHost(); + } + + /** + * Reads the credential the client sent in the request body. + * + * @return \Webauthn\PublicKeyCredential + * @throws \InvalidArgumentException When the body is not a WebAuthn credential. + */ + protected function loadPublicKeyCredential(): PublicKeyCredential + { + $data = $this->normalizeResponseData((array)$this->request->getData()); + try { + return $this->getSerializer()->denormalize($data, PublicKeyCredential::class); + } catch (Throwable $throwable) { + // malformed base64, JSON or CBOR is a client error, whatever the decoder throws; the + // actions log this message and answer with a generic one + throw new InvalidArgumentException('Invalid data provided: ' . $throwable->getMessage(), 0, $throwable); + } + } + + /** + * Rewrites the base64 members of a client response as unpadded base64url. + * + * web-auth/webauthn-lib accepts only that form for these members, and clients written for + * earlier versions may send standard base64 or padding. + * + * @param array $data Request body. + * @return array + * @throws \InvalidArgumentException When a member is not base64. + */ + protected function normalizeResponseData(array $data): array + { + if (isset($data['id']) && is_string($data['id'])) { + $data['id'] = Base64Utility::complyEncodedNoPadding($data['id']); + } + if (!isset($data['response']) || !is_array($data['response'])) { + return $data; + } + foreach (['clientDataJSON', 'authenticatorData', 'signature', 'userHandle'] as $member) { + $value = $data['response'][$member] ?? null; + if (is_string($value) && $value !== '') { + $data['response'][$member] = Base64Utility::complyEncodedNoPadding($value); + } + } + + return $data; + } + + /** + * Turns creation or request options into the array sent to the client. + * + * Binary members are unpadded base64url, members without a value are left out, and the + * relying party name is the `appName` setting of the domain. + * + * @param \Webauthn\PublicKeyCredentialOptions $options Options. + * @return array + */ + public function getOptionsData(PublicKeyCredentialOptions $options): array + { + $data = static::withoutNulls((array)$this->getSerializer()->normalize($options)); + if (isset($data['rp']) && is_array($data['rp']) && $this->appName !== '') { + $data['rp']['name'] = $this->appName; + } + // keep what earlier versions sent, for clients that decode the options strictly: + // `requireResidentKey` is always there, and an empty credential list is left out + if (isset($data['authenticatorSelection']) && is_array($data['authenticatorSelection'])) { + $residentKey = $data['authenticatorSelection']['residentKey'] ?? null; + $data['authenticatorSelection'] += ['requireResidentKey' => $residentKey === 'required']; + } + foreach (['excludeCredentials', 'allowCredentials'] as $list) { + if (($data[$list] ?? null) === []) { + unset($data[$list]); + } + } + + return $data; + } + + /** + * Removes the members that are null, at every level. + * + * @param array $data Data. + * @return array + */ + protected static function withoutNulls(array $data): array + { + foreach ($data as $key => $value) { + if ($value === null) { + unset($data[$key]); + } elseif (is_array($value)) { + $data[$key] = static::withoutNulls($value); + } + } + + return $data; + } + + /** + * Stores the challenge of a ceremony under the bearer token of the request. + * + * @param string $name Store name of the challenge. + * @param string $challenge Challenge, as binary. + * @param bool $reset Whether to drop everything else stored for the token. + * @return void + * @throws \Cake\Http\Exception\BadRequestException Without a bearer token. + */ + protected function storeChallenge(string $name, string $challenge, bool $reset = false): void + { + $storeEntity = $this->readStore(); + if ($reset) { + $storeEntity->store = []; + } + $storeEntity = $this->patchStore($storeEntity, $name, Base64Utility::basicEncode($challenge)); + $this->persistStore($storeEntity); + } + + /** + * Reads a stored challenge. + * + * @param string $name Store name of the challenge. + * @return string|null The challenge as binary, or null when none is stored. + */ + protected function readChallenge(string $name): ?string + { + $encoded = $this->getStore($this->readStore(), $name); + if (!is_string($encoded) || $encoded === '') { + return null; + } + try { + return Base64Utility::basicDecode($encoded); + } catch (InvalidArgumentException) { + return null; + } } /** @@ -295,7 +503,7 @@ protected function createPublicKeyCredentialLoader(): PublicKeyCredentialLoader */ protected function createExtensionOutputCheckerHandler(): ExtensionOutputCheckerHandler { - return new ExtensionOutputCheckerHandler(); + return ExtensionOutputCheckerHandler::create(); } /** @@ -303,7 +511,7 @@ protected function createExtensionOutputCheckerHandler(): ExtensionOutputChecker */ protected function getAlgorithmManager(): Manager { - if (!$this->algorithmManager instanceof \Cose\Algorithm\Manager) { + if (!$this->algorithmManager instanceof Manager) { $this->algorithmManager = Manager::create()->add( ES256::create(), ES256K::create(), @@ -315,8 +523,9 @@ protected function getAlgorithmManager(): Manager PS256::create(), PS384::create(), PS512::create(), - Ed256::create(), - Ed512::create(), + // EdDSA (-8) is the WebAuthn Ed25519 algorithm. Ed256 (-260) and Ed512 (-261) are + // not WebAuthn algorithms, no authenticator uses them, and cose-lib warns about them. + new EdDSA(), ); } diff --git a/src/Webauthn/PublicKeyCredentialLoader.php b/src/Webauthn/PublicKeyCredentialLoader.php deleted file mode 100644 index 25925c5d..00000000 --- a/src/Webauthn/PublicKeyCredentialLoader.php +++ /dev/null @@ -1,38 +0,0 @@ -getUserEntity(); $challenge = random_bytes(16); + $options = $this->buildOptions($challenge); + $this->storeChallenge(static::CHALLENGE, $challenge); + + return $options; + } - $options = PublicKeyCredentialCreationOptions::create( + /** + * Builds the registration options for a challenge. + * + * Everything but the challenge comes from the settings and the user, so verifyResponse() + * builds the same options again from the stored challenge. + * + * @param string $challenge Challenge, as binary. + * @return \Webauthn\PublicKeyCredentialCreationOptions + */ + protected function buildOptions(string $challenge): PublicKeyCredentialCreationOptions + { + return PublicKeyCredentialCreationOptions::create( $this->rpEntity, - $userEntity, + $this->getUserEntity(), $challenge, - $this->getPubKeyCredParams() + $this->getPubKeyCredParams(), + AuthenticatorSelectionCriteria::create(), + PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE, ); - $options = $options - ->setAuthenticatorSelection(new AuthenticatorSelectionCriteria()) - ->setAttestation(PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE) - ->setExtensions(new AuthenticationExtensionsClientInputs()); - - $storeEntity = $this->readStore(); - $storeEntity = $this->patchStore($storeEntity, 'registerOptions', base64_encode(serialize($options))); - - $this->store->save($storeEntity); - - return $options; } /** @@ -59,53 +71,47 @@ protected function getPubKeyCredParams(): array { $list = []; foreach ($this->getAlgorithmManager()->all() as $algorithm) { - $list[] = PublicKeyCredentialParameters::create( - PublicKeyCredentialDescriptor::CREDENTIAL_TYPE_PUBLIC_KEY, - $algorithm::identifier() - ); + $list[] = PublicKeyCredentialParameters::createPk($algorithm::identifier()); } return $list; } /** - * Verify the registration response + * Verify the registration response and store the new credential. * - * @return \Webauthn\PublicKeyCredentialSource + * @return \Webauthn\CredentialRecord + * @throws \Cake\Http\Exception\BadRequestException When no options were requested, the body is not + * a registration response, or the credential is already registered. + * @throws \InvalidArgumentException When the body is not a WebAuthn credential. + * @throws \Webauthn\Exception\WebauthnException When the response does not pass the checks. */ - public function verifyResponse(): PublicKeyCredentialSource + public function verifyResponse(): CredentialRecord { - $storeEntity = $this->readStore(); - $options = $this->getStore($storeEntity, 'registerOptions'); - if ($options) { - $options = unserialize(base64_decode($options)); + $challenge = $this->readChallenge(static::CHALLENGE); + // without the challenge there is nothing to verify against + if ($challenge === null) { + throw new BadRequestException(__d('cake_d_c/api', 'Request the registration options first')); } + $options = $this->buildOptions($challenge); - $attestationStatementSupportManager = $this->getAttestationStatementSupportManager(); - $publicKeyCredentialLoader = $this->createPublicKeyCredentialLoader(); - - $publicKeyCredential = $publicKeyCredentialLoader->loadArray((array)$this->request->getData()); - $authenticatorAttestationResponse = $publicKeyCredential->getResponse(); - if ($authenticatorAttestationResponse instanceof AuthenticatorAttestationResponse) { - $extensionOutputCheckerHandler = $this->createExtensionOutputCheckerHandler(); - - $authenticatorAttestationResponseValidator = new AuthenticatorAttestationResponseValidator( - $attestationStatementSupportManager, - $this->repository, - null, //Token binding is deprecated - $extensionOutputCheckerHandler - ); - - $credential = $authenticatorAttestationResponseValidator->check( - $authenticatorAttestationResponse, - $options, - $this->request + $response = $this->loadPublicKeyCredential()->response; + if (!$response instanceof AuthenticatorAttestationResponse) { + throw new BadRequestException( + __d('cake_d_c/api', 'Could not create credential response for registration'), ); - $this->repository->saveCredentialSource($credential); + } - return $credential; + $validator = AuthenticatorAttestationResponseValidator::create( + $this->getCeremonyStepManagerFactory()->creationCeremony(), + ); + $credential = $validator->check($response, $options, $this->getHost()); + // the library no longer refuses a credential id that is already registered + if ($this->repository->findOneByCredentialId($credential->publicKeyCredentialId) instanceof CredentialRecord) { + throw new BadRequestException(__d('cake_d_c/api', 'The credential is already registered')); } + $this->repository->saveCredentialSource($credential); - throw new BadRequestException(__d('cake_d_c/api', 'Could not create credential response for registration')); + return $credential; } } diff --git a/src/Webauthn/Repository/UserCredentialSourceRepository.php b/src/Webauthn/Repository/UserCredentialSourceRepository.php index 14ab3f1b..23a3edd4 100644 --- a/src/Webauthn/Repository/UserCredentialSourceRepository.php +++ b/src/Webauthn/Repository/UserCredentialSourceRepository.php @@ -1,73 +1,129 @@ .webauthn_credentials`. + * + * An entry is the normalized credential record of web-auth/webauthn-lib. Entries written with + * web-auth/webauthn-lib 4.4 (`PublicKeyCredentialSource::jsonSerialize()`) have the same keys and + * are read as they are. + */ +class UserCredentialSourceRepository { - private \Cake\Http\ServerRequest $request; + private ServerRequest $request; + + private EntityInterface $user; - private \Cake\Datasource\EntityInterface $user; + private ?Table $usersTable; - private ?\Cake\ORM\Table $usersTable; + private (NormalizerInterface&DenormalizerInterface)|null $serializer; /** * @param \Cake\Http\ServerRequest $request The request. * @param \Cake\Datasource\EntityInterface $user The user. * @param \Cake\ORM\Table|null $usersTable The users table. + * @param (\Symfony\Component\Serializer\Normalizer\NormalizerInterface&\Symfony\Component\Serializer\Normalizer\DenormalizerInterface)|null $serializer + * WebAuthn serializer; built on first use when null. */ - public function __construct(ServerRequest $request, EntityInterface $user, ?Table $usersTable = null) - { + public function __construct( + ServerRequest $request, + EntityInterface $user, + ?Table $usersTable = null, + (NormalizerInterface&DenormalizerInterface)|null $serializer = null, + ) { $this->request = $request; $this->user = $user; $this->usersTable = $usersTable; + $this->serializer = $serializer; } /** - * @param string $publicKeyCredentialId Public key credential id - * @return \Webauthn\PublicKeyCredentialSource|null + * @param string $publicKeyCredentialId Public key credential id, as binary. + * @return \Webauthn\CredentialRecord|null */ - public function findOneByCredentialId(string $publicKeyCredentialId): ?PublicKeyCredentialSource + public function findOneByCredentialId(string $publicKeyCredentialId): ?CredentialRecord { $encodedId = Base64Utility::basicEncode($publicKeyCredentialId); $credentials = $this->getUserData($this->user); $credential = $credentials[$encodedId] ?? null; return $credential - ? PublicKeyCredentialSource::createFromArray($credential) + ? $this->toRecord($credential) : null; } /** - * @inheritDoc + * The credentials of the user under the current domain. + * + * @param \Webauthn\PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity User entity. + * @return list<\Webauthn\CredentialRecord> */ public function findAllForUserEntity(PublicKeyCredentialUserEntity $publicKeyCredentialUserEntity): array { - if ($publicKeyCredentialUserEntity->getId() != $this->user->get('id')) { + if ($publicKeyCredentialUserEntity->id != $this->user->get('id')) { return []; } $credentials = $this->getUserData($this->user); $list = []; foreach ($credentials as $credential) { - $list[] = PublicKeyCredentialSource::createFromArray($credential); + $list[] = $this->toRecord($credential); } return $list; } /** - * Whether the user has a credential under any domain, not only the current one. + * Builds the credential record of a stored entry. + * + * @param array $credential Stored entry. + * @return \Webauthn\CredentialRecord + * @throws \Webauthn\Exception\WebauthnException When the entry is not a credential. + */ + protected function toRecord(array $credential): CredentialRecord + { + return $this->getSerializer()->denormalize($credential, CredentialRecord::class); + } + + /** + * @return \Symfony\Component\Serializer\Normalizer\NormalizerInterface&\Symfony\Component\Serializer\Normalizer\DenormalizerInterface + */ + protected function getSerializer(): NormalizerInterface&DenormalizerInterface + { + return $this->serializer ??= WebauthnSerializer::create(); + } + + /** + * Whether the user has a WebAuthn credential stored under any domain. + * + * Credentials are stored per domain, and the domain can come from the client's Referer header, + * so checks that decide whether a user may enroll a second factor must not depend on it. * * @return bool */ @@ -77,7 +133,7 @@ public function hasCredentialOnAnyDomain(): bool } /** - * Whether a user record has a credential under any domain. + * Whether a user record has a WebAuthn credential stored under any domain. * * Needs no WebAuthn settings, so it also works for a domain that has none. * @@ -100,14 +156,20 @@ public static function userHasCredentialOnAnyDomain(EntityInterface|array $user) } /** - * @param \Webauthn\PublicKeyCredentialSource $publicKeyCredentialSource Public key credential source + * Stores a credential, new or updated, in the user record. + * + * @param \Webauthn\CredentialRecord $credentialRecord Credential record. * @return void */ - public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredentialSource): void + public function saveCredentialSource(CredentialRecord $credentialRecord): void { $credentials = $this->getUserData($this->user); - $id = Base64Utility::basicEncode($publicKeyCredentialSource->getPublicKeyCredentialId()); - $credentials[$id] = json_decode(json_encode($publicKeyCredentialSource), true); + $id = Base64Utility::basicEncode($credentialRecord->publicKeyCredentialId); + $entry = (array)$this->getSerializer()->normalize($credentialRecord); + // the trust path is written with its class, as web-auth/webauthn-lib 4.4 did, so an + // application that goes back to that version can still read the entry + $entry['trustPath'] = ['type' => $credentialRecord->trustPath::class] + (array)($entry['trustPath'] ?? []); + $credentials[$id] = $entry; $this->patchUserData($this->user, $credentials); $this->usersTable->saveOrFail($this->user); } @@ -119,7 +181,7 @@ public function saveCredentialSource(PublicKeyCredentialSource $publicKeyCredent * @param array $options The webauthn credentials * @return \Cake\Datasource\EntityInterface */ - public function patchUserData($entity, $options): \Cake\Datasource\EntityInterface + public function patchUserData($entity, $options): EntityInterface { $additionalData = $entity->get('additional_data'); if (!is_array($additionalData)) { @@ -140,7 +202,7 @@ public function patchUserData($entity, $options): \Cake\Datasource\EntityInterfa * @param \Cake\Datasource\EntityInterface $entity The user entity * @return array */ - public function getUserData(\ArrayAccess|array $entity): mixed + public function getUserData(ArrayAccess|array $entity): mixed { $path = 'additional_data.api.' . $this->getDomain() . '.webauthn_credentials'; diff --git a/src/Webauthn/WebauthnSerializer.php b/src/Webauthn/WebauthnSerializer.php new file mode 100644 index 00000000..e5ddc392 --- /dev/null +++ b/src/Webauthn/WebauthnSerializer.php @@ -0,0 +1,45 @@ +create(); + // the factory declares the serialize/deserialize interface only; arrays need these two + if (!$serializer instanceof NormalizerInterface || !$serializer instanceof DenormalizerInterface) { + throw new RuntimeException('The WebAuthn serializer cannot normalize and denormalize'); + } + + return $serializer; + } +} diff --git a/structarmed.php b/structarmed.php index 12a4e871..7a3c71e3 100644 --- a/structarmed.php +++ b/structarmed.php @@ -6,6 +6,8 @@ /** * Intended DAG — NOT as-built. Extract from the as-built IMPORTS matrix (2026-08-14). + * Checked against 14.0.0 on 2026-11-27: the 14 violations listed under "Expected CATCH" + * are the same as in 13.0.1; 14.0.0 adds none. * * Layer model (split by ROLE, not folder nesting): * Service (hub) service classes + registries + ConfigReader @@ -29,23 +31,31 @@ * Direction & classification: * - Hub -> strategy is allowed. Strategy -> Service back-references are BY DESIGN * where the component needs the request/response/parser (no other way) or locates - * Service instances (ServiceLocator, like Cake's TableLocator). Narrow ports live - * in the leaf `Contract` layer (ServiceContextInterface), which renderers/parsers - * depend on instead of the concrete hub. + * Service instances (ServiceLocator, like Cake's TableLocator). Narrow ports are + * planned for the leaf `Contract` layer (ServiceContextInterface, not built yet); + * renderers/parsers should depend on it instead of the concrete hub. * - Action -> Service (and back) is ACCEPTED hub-and-spoke coupling, NOT a * hidden cycle: the Service hub's full public surface IS the contract actions code * against. Thousands of custom actions in real projects call arbitrary Service * methods (getTable, getResult, respond, ...); a narrow port would be a god-interface - * or an incomplete lie. This bidirectional edge is deliberate and documented, so the - * only red left is the true sibling cycle below. + * or an incomplete lie. This bidirectional edge is deliberate and documented, so it + * is not reported. * - * Expected CATCH (red, decisions documented in the ruleset): - * - ServiceAuth -> Action Service\Auth\Auth holds an Action while Action - * holds an Auth — the one true sibling cycle. NOTE: Auth itself is legacy - * (CakePHP 2.x AuthComponent skeleton, allow()/allowedActions never consumed, - * no authenticate() method) — candidate for removal. + * Expected CATCH (red, 14 violations; decisions documented in the ruleset): + * - ServiceAuth -> Action (1) Service\Auth\Auth holds an Action while Action + * holds an Auth — the one true sibling cycle. Auth is the legacy layer + * (CakePHP 2.x AuthComponent skeleton, allow()/allowedActions never consumed): + * deprecated in 14.0.0, removed in 15.0.0, which closes this cycle. + * - ServiceRenderer -> Service (7) and ServiceParser -> Service (2) the renderers + * and parsers hold the concrete hub. Stays red until they take the narrow + * ServiceContextInterface of the `Contract` layer, which is not built yet. + * - ActionExtension -> Service (2) CrudHateoasExtension and CrudRelationsExtension + * reach the hub directly instead of through their action. + * - ActionExtension -> Rbac (1) CrudRelationsExtension checks the permission of the + * related service with ApiRbac. + * - Middleware -> Action (1) ParseApiRequestMiddleware reads Service\Action\Result. * - * External/framework classes (Cake\*, CakeDC\Users, Authentication\*, lcobucci, + * External/framework classes (Cake\*, CakeDC\Users, Authentication\*, Firebase\JWT, * web-auth) are always allowed and are NOT registered as layers. */ return Architecture::define() @@ -72,7 +82,6 @@ // ServiceExtension = service-level extensions (Service\Extension\*) // ServiceAuth = Auth component + 2FA checkers (used BY actions). // ServiceRenderer / ServiceParser / ServiceLocator = strategies of the hub. - // ServiceExtension = legacy Service-level extensions (Service\Extension\*). // The broad 'Service' glob must exclude its sub-namespaces, otherwise // resolveAll() assigns every Service\* class to BOTH its specific layer and // 'Service', collapsing the split into one layer. @@ -99,10 +108,8 @@ ->layerPattern('Command', '/^CakeDC\\\\Api\\\\Command\\\\/') ->layerPattern('TestSuite', '/^CakeDC\\\\Api\\\\TestSuite\\\\/') ->layerPattern('Init', '/^CakeDC\\\\Api\\\\ApiInitializer$/') - ->layerPattern('Plugin', [ - '/^CakeDC\\\\Api\\\\ApiPlugin$/', - '/^CakeDC\\\\Api\\\\Plugin$/', - ]) + // CakeDC\Api\Plugin was removed in 14.0.0; ApiPlugin is the plugin class. + ->layerPattern('Plugin', '/^CakeDC\\\\Api\\\\ApiPlugin$/') ->ruleset([ // Foundation. // 'Exception' => [], diff --git a/tests/App/Application.php b/tests/App/Application.php index 4787492c..07b4c3ea 100644 --- a/tests/App/Application.php +++ b/tests/App/Application.php @@ -12,7 +12,7 @@ * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @since 3.3.0 - * @license http://www.opensource.org/licenses/mit-license.php MIT License + * @license https://www.opensource.org/licenses/mit-license.php MIT License */ namespace CakeDC\Api\Test\App; @@ -24,9 +24,11 @@ use Cake\Http\MiddlewareQueue; use Cake\Routing\Middleware\AssetMiddleware; use Cake\Routing\Middleware\RoutingMiddleware; +use Cake\Routing\RouteBuilder; use CakeDC\Api\Middleware\ContainerInjectorMiddleware; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\App\DI\Service\TestService; +use Override; /** * Application setup class. @@ -36,7 +38,7 @@ */ class Application extends BaseApplication { - #[\Override] + #[Override] public function bootstrap(): void { parent::bootstrap(); @@ -50,7 +52,7 @@ public function bootstrap(): void ]); } - #[\Override] + #[Override] public function pluginBootstrap(): void { parent::pluginBootstrap(); @@ -86,8 +88,8 @@ public function middleware(MiddlewareQueue $middleware): MiddlewareQueue /** * @inheritDoc */ - #[\Override] - public function routes(\Cake\Routing\RouteBuilder $routes): void + #[Override] + public function routes(RouteBuilder $routes): void { $middlewares = Configure::read('Api.Middleware'); foreach ($middlewares as $alias => $middleware) { diff --git a/tests/App/CachedApiInitializer.php b/tests/App/CachedApiInitializer.php new file mode 100644 index 00000000..1ff5a050 --- /dev/null +++ b/tests/App/CachedApiInitializer.php @@ -0,0 +1,56 @@ +map( + ServerRequest::class, + new CollectionPolicy([ + new RbacPolicy([ + 'adapter' => new CachedApiRbac(), + ]), + ]), + ); + + return new AuthorizationService(new ResolverCollection([ + $map, + new OrmResolver(), + ])); + } +} diff --git a/tests/App/Controller/AppController.php b/tests/App/Controller/AppController.php index 00893c97..a42bf54c 100644 --- a/tests/App/Controller/AppController.php +++ b/tests/App/Controller/AppController.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Controller; diff --git a/tests/App/DI/Service/TestService.php b/tests/App/DI/Service/TestService.php index 9aa2b5ea..cc3df231 100644 --- a/tests/App/DI/Service/TestService.php +++ b/tests/App/DI/Service/TestService.php @@ -1,6 +1,16 @@ 'Article N%s', - 'body' => 'Article N%s Body', - ]; - } + $templates ??= [ + 'title' => 'Article N%s', + 'body' => 'Article N%s Body', + ]; foreach (range(1, $count) as $itemId) { $article = $this->newEntity([]); $article['title'] = __($templates['title'], $itemId); diff --git a/tests/App/Model/Table/ArticlesTagsTable.php b/tests/App/Model/Table/ArticlesTagsTable.php index 106c57a3..132f7386 100644 --- a/tests/App/Model/Table/ArticlesTagsTable.php +++ b/tests/App/Model/Table/ArticlesTagsTable.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Model\Table; diff --git a/tests/App/Model/Table/AuthorsTable.php b/tests/App/Model/Table/AuthorsTable.php index fe5a2dce..ead71071 100644 --- a/tests/App/Model/Table/AuthorsTable.php +++ b/tests/App/Model/Table/AuthorsTable.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Model\Table; diff --git a/tests/App/Model/Table/PostsTable.php b/tests/App/Model/Table/PostsTable.php index c379eb36..22ba533b 100644 --- a/tests/App/Model/Table/PostsTable.php +++ b/tests/App/Model/Table/PostsTable.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Model\Table; use Cake\ORM\Table; use Cake\Validation\Validator; +use Override; class PostsTable extends Table { @@ -39,7 +40,7 @@ public function initialize(array $config): void * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ - #[\Override] + #[Override] public function validationDefault(Validator $validator): Validator { $validator diff --git a/tests/App/Model/Table/TagsTable.php b/tests/App/Model/Table/TagsTable.php index 72211455..e93c26ba 100644 --- a/tests/App/Model/Table/TagsTable.php +++ b/tests/App/Model/Table/TagsTable.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Model\Table; diff --git a/tests/App/Service/Action/ArticlesAboutAction.php b/tests/App/Service/Action/ArticlesAboutAction.php new file mode 100644 index 00000000..4e5a74c9 --- /dev/null +++ b/tests/App/Service/Action/ArticlesAboutAction.php @@ -0,0 +1,32 @@ +getService(); + + return [ + 'service' => $service::class, + 'version' => $service->getVersion(), + ]; + } +} diff --git a/tests/App/Service/Action/ArticlesDataAction.php b/tests/App/Service/Action/ArticlesDataAction.php index d5df826d..b181cfbc 100644 --- a/tests/App/Service/Action/ArticlesDataAction.php +++ b/tests/App/Service/Action/ArticlesDataAction.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service\Action; use CakeDC\Api\Service\Action\CrudAction; use CakeDC\Api\Test\App\DI\Service\TestService; +use Override; class ArticlesDataAction extends CrudAction { @@ -26,7 +27,7 @@ public function __construct(TestService $testService, array $config = []) parent::__construct($config); } - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); @@ -38,7 +39,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { return true; @@ -49,7 +50,7 @@ public function execute(): array return $this->testService->data(); } - public function getTestService(): \CakeDC\Api\Test\App\DI\Service\TestService + public function getTestService(): TestService { return $this->testService; } diff --git a/tests/App/Service/Action/ArticlesTagAction.php b/tests/App/Service/Action/ArticlesTagAction.php index c7e4bbe0..3fbd214d 100644 --- a/tests/App/Service/Action/ArticlesTagAction.php +++ b/tests/App/Service/Action/ArticlesTagAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service\Action; @@ -17,10 +17,11 @@ use Cake\Validation\Validator; use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\CrudAction; +use Override; class ArticlesTagAction extends CrudAction { - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); @@ -32,7 +33,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { $validator = new Validator(); @@ -58,7 +59,7 @@ public function execute(): mixed * @param int $tag_id the tag id * @return mixed */ - // @codingStandardsIgnoreStart + // phpcs:disable public function action($tag_id): bool { return true; diff --git a/tests/App/Service/Action/ArticlesUntagAction.php b/tests/App/Service/Action/ArticlesUntagAction.php index cf176c1d..33a69f17 100644 --- a/tests/App/Service/Action/ArticlesUntagAction.php +++ b/tests/App/Service/Action/ArticlesUntagAction.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service\Action; use CakeDC\Api\Service\Action\Action; +use Override; class ArticlesUntagAction extends Action { @@ -22,7 +23,7 @@ class ArticlesUntagAction extends Action * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { return true; diff --git a/tests/App/Service/Action/AttributeEchoAction.php b/tests/App/Service/Action/AttributeEchoAction.php new file mode 100644 index 00000000..1fa79fb3 --- /dev/null +++ b/tests/App/Service/Action/AttributeEchoAction.php @@ -0,0 +1,53 @@ + + */ + protected const array ROUTE_KEYS = ['id', 'code', 'tier', 'origin', 'flag', 'pass', '_name']; + + /** + * @inheritDoc + */ + public function validates(): bool + { + return true; + } + + /** + * @inheritDoc + */ + public function execute(): mixed + { + $route = (array)$this->getRoute(); + + return [ + 'class' => static::class, + 'action' => $this->getName(), + 'method' => $this->getService()->getRequest()->getMethod(), + 'route' => array_intersect_key($route, array_flip(static::ROUTE_KEYS)), + ]; + } +} diff --git a/tests/App/Service/Action/AttributeFeaturedAction.php b/tests/App/Service/Action/AttributeFeaturedAction.php index f97bbe9e..27e52bfe 100644 --- a/tests/App/Service/Action/AttributeFeaturedAction.php +++ b/tests/App/Service/Action/AttributeFeaturedAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service\Action; diff --git a/tests/App/Service/Action/AttributeScopedCodeAction.php b/tests/App/Service/Action/AttributeScopedCodeAction.php new file mode 100644 index 00000000..c3ea9880 --- /dev/null +++ b/tests/App/Service/Action/AttributeScopedCodeAction.php @@ -0,0 +1,24 @@ + '[0-9]+'])] +class AttributeScopedTaggedAction extends AttributeEchoAction +{ +} diff --git a/tests/App/Service/Action/AttributeVerbDeleteAction.php b/tests/App/Service/Action/AttributeVerbDeleteAction.php new file mode 100644 index 00000000..c306333c --- /dev/null +++ b/tests/App/Service/Action/AttributeVerbDeleteAction.php @@ -0,0 +1,24 @@ + '[0-9]+'], + defaults: ['flag' => 'on'], + pass: ['code'], +)] +class AttributeVerbRouteAction extends AttributeEchoAction +{ +} diff --git a/tests/App/Service/Action/AttributesItemAction.php b/tests/App/Service/Action/AttributesItemAction.php index 8433398c..f81ba352 100644 --- a/tests/App/Service/Action/AttributesItemAction.php +++ b/tests/App/Service/Action/AttributesItemAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service\Action; diff --git a/tests/App/Service/Action/Author/IndexAction.php b/tests/App/Service/Action/Author/IndexAction.php index e876e1f9..e115d7b7 100644 --- a/tests/App/Service/Action/Author/IndexAction.php +++ b/tests/App/Service/Action/Author/IndexAction.php @@ -2,22 +2,23 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service\Action\Author; use CakeDC\Api\Service\Action\CrudAction; +use Override; class IndexAction extends CrudAction { - #[\Override] + #[Override] public function initialize(array $config): void { parent::initialize($config); @@ -29,7 +30,7 @@ public function initialize(array $config): void * * @return bool */ - #[\Override] + #[Override] public function validates(): bool { return true; diff --git a/tests/App/Service/Action/FeaturedAction.php b/tests/App/Service/Action/FeaturedAction.php index ce3a47b1..a05b606a 100644 --- a/tests/App/Service/Action/FeaturedAction.php +++ b/tests/App/Service/Action/FeaturedAction.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service\Action; diff --git a/tests/App/Service/Action/FilesDownloadAction.php b/tests/App/Service/Action/FilesDownloadAction.php new file mode 100644 index 00000000..33e8d04a --- /dev/null +++ b/tests/App/Service/Action/FilesDownloadAction.php @@ -0,0 +1,31 @@ +getService()->getRequest()->getQuery('file', 'report.csv'); + + return self::DIRECTORY . basename($file); + } +} diff --git a/tests/App/Service/Action/FilesStampAction.php b/tests/App/Service/Action/FilesStampAction.php new file mode 100644 index 00000000..40659204 --- /dev/null +++ b/tests/App/Service/Action/FilesStampAction.php @@ -0,0 +1,33 @@ + 'Stamp', + 'created' => new DateTime('2026-01-02 03:04:05', 'UTC'), + 'day' => new Date('2026-01-02'), + ]; + } +} diff --git a/tests/App/Service/Action/FilesStoredAction.php b/tests/App/Service/Action/FilesStoredAction.php new file mode 100644 index 00000000..fbb4d7d1 --- /dev/null +++ b/tests/App/Service/Action/FilesStoredAction.php @@ -0,0 +1,40 @@ +write(self::PATH, self::CONTENTS); + + return [ + 'filesystem' => $filesystem, + 'path' => (string)$this->getService()->getRequest()->getQuery('path', self::PATH), + 'name' => 'report.csv', + ]; + } +} diff --git a/tests/App/Service/Action/FilesTextAction.php b/tests/App/Service/Action/FilesTextAction.php new file mode 100644 index 00000000..1a4dc717 --- /dev/null +++ b/tests/App/Service/Action/FilesTextAction.php @@ -0,0 +1,29 @@ + & \"quotes\"\nsecond line"; + + public function execute(): mixed + { + return self::TEXT; + } +} diff --git a/tests/App/Service/Action/UntypedCollectionAction.php b/tests/App/Service/Action/UntypedCollectionAction.php new file mode 100644 index 00000000..62cb2f6f --- /dev/null +++ b/tests/App/Service/Action/UntypedCollectionAction.php @@ -0,0 +1,40 @@ + ['method' => ['GET'], 'path' => 'featured'], ]; - #[\Override] + #[Override] public function initialize(): void { parent::initialize(); @@ -36,7 +38,7 @@ public function initialize(): void 'path' => 'data', ]); - $this->mapAction('featured', \CakeDC\Api\Test\App\Service\Action\FeaturedAction::class, [ + $this->mapAction('featured', FeaturedAction::class, [ 'method' => ['GET'], 'path' => 'featured', ]); diff --git a/tests/App/Service/AttributeScopeBaseService.php b/tests/App/Service/AttributeScopeBaseService.php new file mode 100644 index 00000000..18b93699 --- /dev/null +++ b/tests/App/Service/AttributeScopeBaseService.php @@ -0,0 +1,25 @@ + 'base', 'origin' => 'parent'], patterns: ['code' => '[0-9]+'])] +abstract class AttributeScopeBaseService extends FallbackService +{ +} diff --git a/tests/App/Service/AttributesService.php b/tests/App/Service/AttributesService.php index 815d79f5..19a862e4 100644 --- a/tests/App/Service/AttributesService.php +++ b/tests/App/Service/AttributesService.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service; diff --git a/tests/App/Service/CollectionsService.php b/tests/App/Service/CollectionsService.php index f562df74..b6fd837b 100644 --- a/tests/App/Service/CollectionsService.php +++ b/tests/App/Service/CollectionsService.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service; @@ -16,6 +16,7 @@ use CakeDC\Api\Service\Action\Collection\AddEditAction; use CakeDC\Api\Service\Action\Collection\DeleteAction; use CakeDC\Api\Service\FallbackService; +use Override; /** * Single-word collection service: exercises the bulk AddEdit/Delete @@ -28,7 +29,7 @@ class CollectionsService extends FallbackService * * @return void */ - #[\Override] + #[Override] public function initialize(): void { parent::initialize(); @@ -55,7 +56,7 @@ public function initialize(): void * * @return string */ - #[\Override] + #[Override] public function getTable(): string { return 'Articles'; diff --git a/tests/App/Service/CoreCollisionService.php b/tests/App/Service/CoreCollisionService.php new file mode 100644 index 00000000..d14d1536 --- /dev/null +++ b/tests/App/Service/CoreCollisionService.php @@ -0,0 +1,32 @@ + ['method' => ['GET'], 'path' => ''], + ]; + + protected array $resourceOptions = [ + 'only' => ['index', 'view', 'listing'], + ]; +} diff --git a/tests/App/Service/Extension/CoreProbeExtension.php b/tests/App/Service/Extension/CoreProbeExtension.php new file mode 100644 index 00000000..809e3ef5 --- /dev/null +++ b/tests/App/Service/Extension/CoreProbeExtension.php @@ -0,0 +1,58 @@ + + */ + #[Override] + public function implementedEvents(): array + { + return [ + 'Service.beforeDispatch' => 'beforeDispatch', + ]; + } + + /** + * Counts handled events. + * + * @return void + */ + public function beforeDispatch(): void + { + $this->calls++; + } + + /** + * @return \CakeDC\Api\Service\ExtensionRegistry + */ + public function getRegistry(): ExtensionRegistry + { + return $this->registry; + } +} diff --git a/tests/App/Service/FilesService.php b/tests/App/Service/FilesService.php new file mode 100644 index 00000000..b0fab464 --- /dev/null +++ b/tests/App/Service/FilesService.php @@ -0,0 +1,47 @@ + ['method' => ['GET'], 'path' => 'text'], + 'stamp' => ['method' => ['GET'], 'path' => 'stamp'], + 'download' => ['method' => ['GET'], 'path' => 'download'], + 'stored' => ['method' => ['GET'], 'path' => 'stored'], + ]; + + protected array $actionsClassMap = [ + 'text' => FilesTextAction::class, + 'stamp' => FilesStampAction::class, + 'download' => FilesDownloadAction::class, + 'stored' => FilesStoredAction::class, + ]; + + protected array $resourceOptions = [ + 'only' => ['text', 'stamp', 'download', 'stored'], + ]; +} diff --git a/tests/App/Service/PostsService.php b/tests/App/Service/PostsService.php index b7e830ec..8741c2ca 100644 --- a/tests/App/Service/PostsService.php +++ b/tests/App/Service/PostsService.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service; use CakeDC\Api\Service\Action\CrudIndexAction; use CakeDC\Api\Service\FallbackService; +use Override; /** * Posts service exercising custom route path aliases on top of the @@ -27,7 +28,7 @@ class PostsService extends FallbackService * * @return void */ - #[\Override] + #[Override] public function initialize(): void { parent::initialize(); diff --git a/tests/App/Service/ScopedService.php b/tests/App/Service/ScopedService.php new file mode 100644 index 00000000..67156339 --- /dev/null +++ b/tests/App/Service/ScopedService.php @@ -0,0 +1,35 @@ + 'child'], patterns: ['code' => '[a-z]{3}'])] +#[ApiScope('/extra')] +#[ApiActions([ + AttributeScopedCodeAction::class, + AttributeScopedTaggedAction::class, + AttributeScopedPlainAction::class, +])] +class ScopedService extends AttributeScopeBaseService +{ +} diff --git a/tests/App/Service/VerbsService.php b/tests/App/Service/VerbsService.php new file mode 100644 index 00000000..41939bbb --- /dev/null +++ b/tests/App/Service/VerbsService.php @@ -0,0 +1,53 @@ +mapAction('about', ArticlesAboutAction::class, [ + 'method' => ['GET'], + 'path' => 'about', + ]); + } } diff --git a/tests/App/Transformer/ArticleTransformer.php b/tests/App/Transformer/ArticleTransformer.php index 661dc1b8..203a313f 100644 --- a/tests/App/Transformer/ArticleTransformer.php +++ b/tests/App/Transformer/ArticleTransformer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Transformer; diff --git a/tests/Base/BaseTraitTest.php b/tests/Base/BaseTraitTest.php index ede1c9e8..0f7ef5f0 100644 --- a/tests/Base/BaseTraitTest.php +++ b/tests/Base/BaseTraitTest.php @@ -2,23 +2,22 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Base; use Cake\ORM\TableRegistry; -// @codingStandardsIgnoreStart +// phpcs:disable trait BaseTraitTest { - /** * Sets up the session as a logged in user for an user with id $id * diff --git a/tests/Config/api.php b/tests/Config/api.php index bdfb07ab..03160512 100644 --- a/tests/Config/api.php +++ b/tests/Config/api.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ use Authentication\Middleware\AuthenticationMiddleware; @@ -20,6 +20,9 @@ use CakeDC\Api\ApiInitializer; use CakeDC\Api\Middleware\ParseApiRequestMiddleware; use CakeDC\Api\Middleware\ProcessApiRequestMiddleware; +use CakeDC\Api\Service\Auth\TwoFactorAuthentication\DefaultOneTimePasswordAuthenticationChecker; +use CakeDC\Api\Service\Auth\TwoFactorAuthentication\DefaultWebauthn2fAuthenticationChecker; +use CakeDC\Api\Service\FallbackService; Configure::write('Api', []); $config = Configure::read('Test.Api.Config'); @@ -29,7 +32,7 @@ 'Api' => [ 'renderer' => 'CakeDC/Api.JSend', 'parser' => 'CakeDC/Api.Form', - 'ServiceFallback' => \CakeDC\Api\Service\FallbackService::class, + 'ServiceFallback' => FallbackService::class, '2fa' => [ 'enabled' => false, @@ -37,10 +40,10 @@ 'OneTimePasswordAuthenticator' => [ 'login' => false, - 'checker' => \CakeDC\Api\Service\Auth\TwoFactorAuthentication\DefaultOneTimePasswordAuthenticationChecker::class, + 'checker' => DefaultOneTimePasswordAuthenticationChecker::class, ], 'Webauthn2fa' => [ - 'checker' => \CakeDC\Api\Service\Auth\TwoFactorAuthentication\DefaultWebauthn2fAuthenticationChecker::class, + 'checker' => DefaultWebauthn2fAuthenticationChecker::class, 'localhost' => [ 'enabled' => false, 'appName' => 'apilocal', @@ -55,7 +58,7 @@ ], 'RefreshToken' => [ 'lifetime' => 14 * 86400, - 'secret' => 'this is a long secret, that must be longer than 512 bits if not an exception will be thrown', + 'secret' => 'this is another long secret for refresh tokens, also longer than 512 bits, or an exception is thrown', ], ], @@ -105,6 +108,12 @@ $config['Api']['Auth'] = $auth; } +// tests can replace middleware options, for example the authorization service provider +$middleware = Configure::read('Test.Api.Middleware'); +if (!empty($middleware)) { + $config['Api']['Middleware'] = Hash::merge($config['Api']['Middleware'], $middleware); +} + $serviceOptions = Configure::read('Test.Api.Service'); if (!empty($serviceOptions)) { $config['Api']['Service'] = Hash::merge($config['Api']['Service'], $serviceOptions); diff --git a/tests/Config/api_permissions.php b/tests/Config/api_permissions.php index f54d5036..d39cc18b 100644 --- a/tests/Config/api_permissions.php +++ b/tests/Config/api_permissions.php @@ -1,6 +1,16 @@ [ 'enable' => true, - 'serviceLoader' => \CakeDC\Users\Loader\AuthorizationServiceLoader::class, + 'serviceLoader' => AuthorizationServiceLoader::class, ], 'AuthorizationMiddleware' => [ 'unauthorizedHandler' => [ 'exceptions' => [ - 'MissingIdentityException' => \Authorization\Exception\MissingIdentityException::class, - 'ForbiddenException' => \Authorization\Exception\ForbiddenException::class, + 'MissingIdentityException' => MissingIdentityException::class, + 'ForbiddenException' => ForbiddenException::class, ], 'className' => 'Authorization.CakeRedirect', 'url' => [ @@ -151,8 +155,6 @@ // ], ], 'OAuth' => ['path' => null], - // robthree/twofactorauth 1.x has no Algorithm enum, so the CakeDC/Users default is null - 'OneTimePasswordAuthenticator' => ['algorithm' => 'sha1'], ]; return $config; diff --git a/tests/ConfigTrait.php b/tests/ConfigTrait.php index ea81edb8..b03f3515 100644 --- a/tests/ConfigTrait.php +++ b/tests/ConfigTrait.php @@ -2,17 +2,18 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test; +use Cake\Controller\Controller; use Cake\Core\Configure; use Cake\Http\Response; use Cake\Http\ServerRequest; @@ -164,7 +165,7 @@ protected function _initializeRequest(array $requestOptions = [], $method = 'GET $this->request = new ServerRequest($requestOptions); $this->response = empty($options['response']) ? new Response() : $options['response']; - $this->Controller = $this->createStub(\Cake\Controller\Controller::class); + $this->Controller = $this->createStub(Controller::class); $this->Controller->setRequest($this->request); $this->Controller->setResponse($this->response); } diff --git a/tests/Fixture/ArticlesFixture.php b/tests/Fixture/ArticlesFixture.php index 48f49dbb..382d250d 100644 --- a/tests/Fixture/ArticlesFixture.php +++ b/tests/Fixture/ArticlesFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; @@ -16,6 +16,7 @@ use Cake\Database\Driver\Postgres; use Cake\Datasource\ConnectionInterface; use Cake\TestSuite\Fixture\TestFixture; +use Override; /** * Short description for class. @@ -45,7 +46,7 @@ class ArticlesFixture extends TestFixture ['id' => 15, 'author_id' => 1, 'title' => 'Article N15', 'body' => 'Article N15 Body', 'published' => 'Y'], ]; - #[\Override] + #[Override] public function insert(ConnectionInterface $db): bool { $result = parent::insert($db); diff --git a/tests/Fixture/ArticlesTagsFixture.php b/tests/Fixture/ArticlesTagsFixture.php index 18a775f0..9435c035 100644 --- a/tests/Fixture/ArticlesTagsFixture.php +++ b/tests/Fixture/ArticlesTagsFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; diff --git a/tests/Fixture/AttributesFixture.php b/tests/Fixture/AttributesFixture.php index 236315d7..56625e30 100644 --- a/tests/Fixture/AttributesFixture.php +++ b/tests/Fixture/AttributesFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; diff --git a/tests/Fixture/AuthStoreFixture.php b/tests/Fixture/AuthStoreFixture.php index 44daa093..c677ac4f 100644 --- a/tests/Fixture/AuthStoreFixture.php +++ b/tests/Fixture/AuthStoreFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; diff --git a/tests/Fixture/AuthorsFixture.php b/tests/Fixture/AuthorsFixture.php index 512f9e3e..7e4433d2 100644 --- a/tests/Fixture/AuthorsFixture.php +++ b/tests/Fixture/AuthorsFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; diff --git a/tests/Fixture/JwtRefreshTokensFixture.php b/tests/Fixture/JwtRefreshTokensFixture.php index 8196d2a7..76603abe 100644 --- a/tests/Fixture/JwtRefreshTokensFixture.php +++ b/tests/Fixture/JwtRefreshTokensFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; diff --git a/tests/Fixture/PostsFixture.php b/tests/Fixture/PostsFixture.php index 6fc5a35c..5089e075 100644 --- a/tests/Fixture/PostsFixture.php +++ b/tests/Fixture/PostsFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; @@ -16,6 +16,7 @@ use Cake\Database\Driver\Postgres; use Cake\Datasource\ConnectionInterface; use Cake\TestSuite\Fixture\TestFixture; +use Override; class PostsFixture extends TestFixture { @@ -31,7 +32,7 @@ class PostsFixture extends TestFixture ['id' => 4, 'title' => 'Fourth Post', 'body' => 'Fourth Post Body', 'published' => 'Y'], ]; - #[\Override] + #[Override] public function insert(ConnectionInterface $db): bool { $result = parent::insert($db); diff --git a/tests/Fixture/SocialAccountsFixture.php b/tests/Fixture/SocialAccountsFixture.php index 639e788d..3fd1e3aa 100644 --- a/tests/Fixture/SocialAccountsFixture.php +++ b/tests/Fixture/SocialAccountsFixture.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; diff --git a/tests/Fixture/TagsFixture.php b/tests/Fixture/TagsFixture.php index 6511f194..90aa33a4 100644 --- a/tests/Fixture/TagsFixture.php +++ b/tests/Fixture/TagsFixture.php @@ -2,18 +2,21 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\Fixture; +use Cake\Database\Driver\Postgres; +use Cake\Datasource\ConnectionInterface; use Cake\TestSuite\Fixture\TestFixture; +use Override; /** * Class TagFixture @@ -31,4 +34,18 @@ class TagsFixture extends TestFixture ['id' => 3, 'post_id' => 2, 'name' => 'tag3'], ['id' => 4, 'post_id' => 2, 'name' => 'tag4'], ]; + + #[Override] + public function insert(ConnectionInterface $db): bool + { + $result = parent::insert($db); + + if ($db->getDriver() instanceof Postgres) { + foreach (range(1, count($this->records)) as $i) { + $db->execute("select nextval('tags_id_seq'::regclass)"); + } + } + + return $result; + } } diff --git a/tests/Fixture/UsersFixture.php b/tests/Fixture/UsersFixture.php index d95ab065..af4dbace 100644 --- a/tests/Fixture/UsersFixture.php +++ b/tests/Fixture/UsersFixture.php @@ -1,13 +1,14 @@ + */ + protected const NEEDS_APP = [ + // extends App\Controller\AppController + AppController::class, + ]; + + public function testEverySourceClassLoads(): void + { + $src = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'src'; + $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($src, RecursiveDirectoryIterator::SKIP_DOTS)); + $loaded = 0; + foreach ($files as $file) { + if ($file->getExtension() !== 'php') { + continue; + } + $relative = substr($file->getPathname(), strlen($src) + 1, -4); + $class = 'CakeDC\\Api\\' . str_replace(DIRECTORY_SEPARATOR, '\\', $relative); + if (in_array($class, static::NEEDS_APP, true)) { + continue; + } + $this->assertTrue( + class_exists($class) || interface_exists($class) || trait_exists($class) || enum_exists($class), + $class . ' does not load', + ); + $loaded++; + } + $this->assertGreaterThan(100, $loaded); + } +} diff --git a/tests/TestCase/Command/ServiceRoutesCommandTest.php b/tests/TestCase/Command/ServiceRoutesCommandTest.php index 3752f226..efbfcb67 100644 --- a/tests/TestCase/Command/ServiceRoutesCommandTest.php +++ b/tests/TestCase/Command/ServiceRoutesCommandTest.php @@ -1,12 +1,23 @@ assertOutputNotContains('attributes:add'); } + /** + * Test the command name. + */ + public function testDefaultName(): void + { + $this->assertSame('service routes', ServiceRoutesCommand::defaultName()); + } + + /** + * Test the service argument is required. + */ + public function testServiceArgumentRequired(): void + { + $this->exec('service routes'); + $this->assertExitCode(Command::CODE_ERROR); + $this->assertErrorContains('Missing required argument'); + } + + /** + * Test verbose mode adds a Defaults column with the sorted route defaults as JSON. + */ + public function testServiceRoutesVerbose(): void + { + $this->exec('service routes core_collision -v'); + $this->assertExitCode(Command::CODE_SUCCESS); + $this->assertOutputContainsRow([...$this->getHeaderRow(), 'Defaults']); + $this->assertOutputContainsRow([ + 'core_collision:view', + 'GET', + '/core-collision/{id}', + 'core_collision', + 'view', + '', + '{"_method":"GET","action":"view","controller":"core_collision","map":', + ]); + } + + /** + * Test routes are listed in definition order by default and by name with --sort. + */ + public function testServiceRoutesSort(): void + { + $this->exec('service routes core_collision'); + $this->assertExitCode(Command::CODE_SUCCESS); + $this->assertSame( + ['core_collision:view', 'core_collision:index', 'core_collision:listing'], + $this->routeNames($this->mainTable()), + ); + + $this->exec('service routes core_collision --sort'); + $this->assertExitCode(Command::CODE_SUCCESS); + $this->assertSame( + ['core_collision:index', 'core_collision:listing', 'core_collision:view'], + $this->routeNames($this->mainTable()), + ); + + $this->exec('service routes core_collision -s'); + $this->assertExitCode(Command::CODE_SUCCESS); + $this->assertSame( + ['core_collision:index', 'core_collision:listing', 'core_collision:view'], + $this->routeNames($this->mainTable()), + ); + } + + /** + * Test colliding routes are reported in a second table with the same columns as the route list. + */ + public function testServiceRoutesCollisions(): void + { + $this->exec('service routes core_collision'); + $this->assertExitCode(Command::CODE_SUCCESS); + $this->assertErrorContains('The following possible route collisions were detected.'); + + $collisions = $this->collisionTable(); + $this->assertMatchesRegularExpression($this->rowPattern($this->getHeaderRow()), $collisions); + $this->assertSame(['core_collision:index', 'core_collision:listing'], $this->routeNames($collisions)); + $this->assertMatchesRegularExpression($this->rowPattern([ + 'core_collision:index', + 'GET', + '/core-collision', + 'core_collision', + 'index', + '', + ]), $collisions); + $this->assertMatchesRegularExpression($this->rowPattern([ + 'core_collision:listing', + 'GET', + '/core-collision', + 'core_collision', + 'listing', + '', + ]), $collisions); + } + + /** + * Test the collision table keeps the base columns in verbose mode. + */ + public function testServiceRoutesCollisionsVerbose(): void + { + $this->exec('service routes core_collision -v'); + $this->assertExitCode(Command::CODE_SUCCESS); + + $collisions = $this->collisionTable(); + $this->assertMatchesRegularExpression($this->rowPattern($this->getHeaderRow()), $collisions); + $this->assertStringNotContainsString('Defaults', $collisions); + $this->assertMatchesRegularExpression($this->rowPattern([ + 'core_collision:listing', + 'GET', + '/core-collision', + 'core_collision', + 'listing', + '', + ]), $collisions); + } + + /** + * Test no collision warning is printed for a service without colliding routes. + */ + public function testServiceRoutesWithoutCollisions(): void + { + $this->exec('service routes articles'); + $this->assertExitCode(Command::CODE_SUCCESS); + $this->assertErrorEmpty(); + $this->assertCount(2, explode('Route name', $this->_out->output())); + } + + /** + * Returns the first table of the output: the route list. + */ + private function mainTable(): string + { + $parts = explode('Route name', $this->_out->output()); + + return '| Route name' . $parts[1]; + } + + /** + * Returns the second table of the output: the collision list. + */ + private function collisionTable(): string + { + $this->assertErrorContains('The following possible route collisions were detected.'); + $parts = explode('Route name', $this->_out->output()); + $this->assertCount(3, $parts); + + return '| Route name' . $parts[2]; + } + + /** + * Returns the route names listed in the first column of a table, in order. + */ + private function routeNames(string $table): array + { + preg_match_all('/^\| (core_collision:\w+)\s+\|/m', $table, $matches); + + return $matches[1]; + } + + /** + * Builds a pattern that matches a complete table row with exactly the given cells. + */ + private function rowPattern(array $row): string + { + $cells = array_map(fn(string $cell): string => preg_quote($cell, '/'), $row); + + return '/^\|\s+' . implode('\s+\|\s+', $cells) . '\s+\|$/m'; + } + private function getArticleRoutes(): array { return [ diff --git a/tests/TestCase/Exception/ExceptionTest.php b/tests/TestCase/Exception/ExceptionTest.php index 666d6537..3f3559a3 100644 --- a/tests/TestCase/Exception/ExceptionTest.php +++ b/tests/TestCase/Exception/ExceptionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Exception; @@ -20,6 +20,7 @@ use CakeDC\Api\Exception\UnauthorizedException; use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; /** * Unit tests for the API exception classes. @@ -96,4 +97,37 @@ public function testValidationExceptionCustomCode(): void $e = new ValidationException('Invalid', 400); $this->assertSame(400, $e->getCode()); } + + /** + * @return array + */ + public static function fileLineExceptionProvider(): array + { + return [ + 'service' => [ServiceException::class, 'Service exception', 500], + 'unauthenticated' => [UnauthenticatedException::class, 'Unauthenticated', 401], + 'unauthorized' => [UnauthorizedException::class, 'Unauthorized', 403], + ]; + } + + /** + * The default message is used for an empty message, and file and line can be overridden. + */ + #[DataProvider('fileLineExceptionProvider')] + public function testDefaultMessageAndSetFileLine(string $class, string $message, int $code): void + { + $e = new $class(''); + $this->assertSame($message, $e->getMessage()); + $this->assertSame($code, $e->getCode()); + + $e->setFile('/tmp/service.php'); + $e->setLine(17); + $this->assertSame('/tmp/service.php', $e->getFile()); + $this->assertSame(17, $e->getLine()); + + $e->setFile(); + $e->setLine(); + $this->assertSame('', $e->getFile()); + $this->assertSame(0, $e->getLine()); + } } diff --git a/tests/TestCase/Integration/CachedApiRbacPipelineTest.php b/tests/TestCase/Integration/CachedApiRbacPipelineTest.php new file mode 100644 index 00000000..c64c67f1 --- /dev/null +++ b/tests/TestCase/Integration/CachedApiRbacPipelineTest.php @@ -0,0 +1,265 @@ +_tokenAccess(); + // tests/Config/api.php is loaded again for every request, so the provider is set through its hook + Configure::write('Test.Api.Middleware', [ + 'apiAuthorize' => ['request' => CachedApiInitializer::class], + ]); + Cache::drop(static::CACHE); + Cache::setConfig(static::CACHE, ['className' => 'Array']); + } + + protected function tearDown(): void + { + parent::tearDown(); + Cache::drop(static::CACHE); + Configure::delete('Test.Api.Middleware'); + Configure::delete('Test.Api.Permissions'); + Configure::delete('CakeDC/Auth.api_permissions'); + } + + /** + * Replaces the permission rules for the next requests. + * + * The map is built once and kept in the cache, so the cache is cleared to apply new rules. + * + * @param array $rules Permission rules. + * @return void + */ + protected function setPermissions(array $rules): void + { + Configure::write('Test.Api.Permissions', $rules); + Configure::write('CakeDC/Auth.api_permissions', $rules); + Cache::clear(static::CACHE); + } + + /** + * @param string $url Url. + * @param string|null $userId User to log in as, null for no login. + * @param array $data Query parameters. + * @return array + */ + protected function getAs(string $url, ?string $userId, array $data = []): array + { + $this->defaultUserId = $userId; + $this->sendRequest($url, 'GET', $data); + + return $this->getJsonResponse(); + } + + /** + * @param array $result Response. + * @return void + */ + protected function assertDenied(array $result): void + { + $this->assertSame('error', $result['status'] ?? null); + } + + public function testRequestUsesTheCachedPermissionsMap(): void + { + $rule = ['role' => 'admin', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true]; + $this->setPermissions([$rule]); + $key = CachedApiRbac::cacheKey([$rule]); + $this->assertNull(Cache::read($key, static::CACHE)); + + $this->assertSuccess($this->getAs('/articles', Settings::USER1)); + $this->assertSame(['admin' => ['articles' => [0 => 0]]], Cache::read($key, static::CACHE)); + } + + public function testAllowAndDenyByRole(): void + { + $this->setPermissions([ + ['role' => 'admin', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertSuccess($this->getAs('/articles', Settings::USER1)); + $this->assertDenied($this->getAs('/articles', static::OTHER_ROLE_USER)); + } + + public function testAllowAndDenyByService(): void + { + $this->setPermissions([ + ['role' => '*', 'service' => 'authors', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertSuccess($this->getAs('/authors', Settings::USER1)); + $this->assertDenied($this->getAs('/articles', Settings::USER1)); + } + + public function testDeniedRuleOfTheRoleWins(): void + { + $this->setPermissions([ + ['role' => 'admin', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => false], + ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertDenied($this->getAs('/articles', Settings::USER1)); + $this->assertSuccess($this->getAs('/articles', static::OTHER_ROLE_USER)); + $this->assertSuccess($this->getAs('/authors', Settings::USER1)); + } + + public function testBypassAuthAllowsWithoutLogin(): void + { + $this->setPermissions([ + ['role' => '*', 'service' => 'authors', 'action' => '*', 'method' => '*', 'bypassAuth' => true], + ['role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertSuccess($this->getAs('/authors', null)); + // `allowed` needs a logged in user + $this->assertDenied($this->getAs('/articles', null)); + $this->assertSuccess($this->getAs('/articles', Settings::USER1)); + } + + public function testBypassAuthFirstAppliesOnlyToTheNamedService(): void + { + $this->setPermissions([ + ['bypassAuth' => true, 'role' => '*', 'service' => 'authors', 'action' => '*', 'method' => '*'], + ]); + $this->assertDenied($this->getAs('/articles', null)); + $this->assertSuccess($this->getAs('/authors', null)); + } + + public function testAllowedFirstAppliesOnlyToTheNamedService(): void + { + $this->setPermissions([ + ['allowed' => true, 'role' => '*', 'service' => 'authors', 'action' => '*', 'method' => '*'], + ]); + $this->assertDenied($this->getAs('/articles', Settings::USER1)); + $this->assertSuccess($this->getAs('/authors', Settings::USER1)); + } + + public function testAllowedFirstAppliesOnlyToTheNamedRoleAndMethod(): void + { + $this->setPermissions([ + ['allowed' => true, 'role' => 'admin', 'service' => '*', 'action' => '*', 'method' => 'POST'], + ['allowed' => true, 'service' => 'authors', 'action' => '*', 'role' => 'admin'], + ]); + $this->assertDenied($this->getAs('/articles', Settings::USER1)); + $this->assertDenied($this->getAs('/authors', static::OTHER_ROLE_USER)); + $this->assertSuccess($this->getAs('/authors', Settings::USER1)); + } + + public function testRelationOfAForbiddenServiceIsLeftOut(): void + { + $this->_loadDefaultExtensions('CakeDC/Api.CrudRelations'); + $this->setPermissions([ + ['role' => '*', 'service' => ['articles'], 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $result = $this->getAs('/articles/1', Settings::USER1, ['include_relations' => 'authors']); + $this->assertSuccess($result); + $this->assertSame('First Article', Hash::get($result, 'data.title')); + $this->assertNull(Hash::get($result, 'data.author')); + } + + public function testRelationOfAnAllowedServiceIsEmbedded(): void + { + $this->_loadDefaultExtensions('CakeDC/Api.CrudRelations'); + $this->setPermissions([ + ['role' => '*', 'service' => ['articles', 'authors'], 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $result = $this->getAs('/articles/1', Settings::USER1, ['include_relations' => 'authors']); + $this->assertSuccess($result); + $this->assertSame('Electra', Hash::get($result, 'data.author.first_name')); + } + + public function testRelationIsCheckedForTheRoleOfTheUser(): void + { + $this->_loadDefaultExtensions('CakeDC/Api.CrudRelations'); + $this->setPermissions([ + ['role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true], + ['role' => 'admin', 'service' => 'authors', 'action' => 'index', 'method' => 'GET', 'allowed' => true], + ]); + $result = $this->getAs('/articles/1', Settings::USER1, ['include_relations' => 'authors']); + $this->assertSuccess($result); + $this->assertSame('Electra', Hash::get($result, 'data.author.first_name')); + + $result = $this->getAs('/articles/1', static::OTHER_ROLE_USER, ['include_relations' => 'authors']); + $this->assertSuccess($result); + $this->assertNull(Hash::get($result, 'data.author')); + } + + public function testChangedRulesTakeEffectWithoutClearingTheCache(): void + { + $this->setPermissions([ + ['role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertSuccess($this->getAs('/articles', Settings::USER1)); + + // the cache key depends on the rules, so the new rules build a new map + $rules = [['role' => '*', 'service' => 'authors', 'action' => '*', 'method' => '*', 'allowed' => true]]; + Configure::write('Test.Api.Permissions', $rules); + $this->assertDenied($this->getAs('/articles', Settings::USER1)); + $this->assertSuccess($this->getAs('/authors', Settings::USER1)); + } + + public function testCamelizedServiceNameMatchesAsWithApiRbac(): void + { + $this->setPermissions([ + ['role' => '*', 'service' => 'Articles', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertSuccess($this->getAs('/articles', Settings::USER1)); + } + + public function testFirstMatchingRuleWinsAcrossRoles(): void + { + $this->setPermissions([ + ['role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => false], + ['role' => 'admin', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertDenied($this->getAs('/articles', Settings::USER1)); + } + + public function testFirstMatchingRuleWinsAcrossServices(): void + { + $this->setPermissions([ + ['role' => 'admin', 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => false], + ['role' => 'admin', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true], + ]); + $this->assertDenied($this->getAs('/articles', Settings::USER1)); + } +} diff --git a/tests/TestCase/Integration/LegacyFallbackService.php b/tests/TestCase/Integration/LegacyFallbackService.php new file mode 100644 index 00000000..db03b71a --- /dev/null +++ b/tests/TestCase/Integration/LegacyFallbackService.php @@ -0,0 +1,32 @@ + 'owner']; + } +} diff --git a/tests/TestCase/Integration/LegacyMemberGuardPipelineTest.php b/tests/TestCase/Integration/LegacyMemberGuardPipelineTest.php new file mode 100644 index 00000000..058cb74f --- /dev/null +++ b/tests/TestCase/Integration/LegacyMemberGuardPipelineTest.php @@ -0,0 +1,91 @@ +_tokenAccess(); + $this->getDefaultUser(Settings::USER1); + } + + protected function tearDown(): void + { + Configure::delete('Test.Api'); + parent::tearDown(); + } + + public function testServiceWithALegacyMemberIsReportedWithItsMembers(): void + { + Configure::delete('Test.Api.Config'); + $config = require CONFIG . 'api.php'; + $config['Api']['ServiceFallback'] = LegacyFallbackService::class; + Configure::write('Test.Api.Config', $config); + + // `tags` has no service class, so the fallback service of the application serves it + $this->sendRequest('/tags', 'GET'); + + // the application's error handling answers, not a blank 400 + $this->assertResponseCode(500); + $this->assertNotSame('', (string)$this->_response->getBody()); + + // and what it gets from the plugin is the exception that names the members to rename + ServiceRegistry::getServiceLocator()->clear(); + $handler = new class implements RequestHandlerInterface { + public function handle(ServerRequestInterface $request): ResponseInterface + { + return new Response(); + } + }; + $this->expectException(CakeException::class); + $this->expectExceptionMessage('LegacyFallbackService::_actionOptions() (now actionOptions())'); + (new ParseApiRequestMiddleware())->process(new ServerRequest(['url' => '/api/tags']), $handler); + } + + public function testServiceOfTheApplicationStillAnswers(): void + { + // the same request with the plugin's fallback service is a normal API answer + $this->sendRequest('/articles', 'GET'); + + $this->assertResponseCode(200); + $this->assertSuccess($this->getJsonResponse()); + } +} diff --git a/tests/TestCase/Integration/Service/Action/ArticlesDataActionTest.php b/tests/TestCase/Integration/Service/Action/ArticlesDataActionTest.php index 6ac7ad72..4c9ca816 100644 --- a/tests/TestCase/Integration/Service/Action/ArticlesDataActionTest.php +++ b/tests/TestCase/Integration/Service/Action/ArticlesDataActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/AttributeRoutingTest.php b/tests/TestCase/Integration/Service/Action/AttributeRoutingTest.php index 2778c932..14797921 100644 --- a/tests/TestCase/Integration/Service/Action/AttributeRoutingTest.php +++ b/tests/TestCase/Integration/Service/Action/AttributeRoutingTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/AttributeVerbRoutingTest.php b/tests/TestCase/Integration/Service/Action/AttributeVerbRoutingTest.php new file mode 100644 index 00000000..2536b932 --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/AttributeVerbRoutingTest.php @@ -0,0 +1,255 @@ + ['tests/App/Service/*.php', 'tests/App/Service/**/*.php'], + 'cache' => false, + ]); + $this->_tokenAccess(); + $this->getDefaultUser(Settings::USER1); + } + + protected function tearDown(): void + { + parent::tearDown(); + AttributeResolver::drop('default'); + } + + /** + * Sends a request and returns the echo payload of a successful attribute action. + * + * @param string $url Url below `/api`. + * @param string $method HTTP method. + * @param string $class Expected action class. + * @param string $action Expected action name. + * @return array + */ + protected function assertReaches(string $url, string $method, string $class, string $action): array + { + $this->sendRequest($url, $method, []); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame($class, $result['data']['class']); + $this->assertSame($action, $result['data']['action']); + $this->assertSame($method, $result['data']['method']); + + return $result['data']['route']; + } + + /** + * Sends a request that no attribute route accepts. + * + * JSend reports routing errors with HTTP 200 and the error code in the body, + * and a known path with an unsupported method is "not found" (404), not 405. + * + * @param string $url Url below `/api`. + * @param string $method HTTP method. + * @return void + */ + protected function assertNoRoute(string $url, string $method): void + { + $this->sendRequest($url, $method, []); + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + $this->assertSame(200, $this->_response->getStatusCode()); + $this->assertStringContainsString('could not be found', $result['message']); + } + + public function testApiPostReachesAction(): void + { + $route = $this->assertReaches('/verbs/create', 'POST', AttributeVerbPostAction::class, 'create'); + $this->assertSame([], $route['pass']); + } + + public function testApiPutReachesActionWithPlaceholder(): void + { + $route = $this->assertReaches('/verbs/5/replace', 'PUT', AttributeVerbPutAction::class, 'replace'); + $this->assertSame('5', $route['id']); + $this->assertSame(['5'], $route['pass']); + } + + public function testApiPatchReachesActionWithPlaceholder(): void + { + $route = $this->assertReaches('/verbs/7/touch', 'PATCH', AttributeVerbPatchAction::class, 'touch'); + $this->assertSame('7', $route['id']); + } + + public function testApiDeleteReachesAction(): void + { + $this->assertReaches('/verbs/purge', 'DELETE', AttributeVerbDeleteAction::class, 'purge'); + } + + public function testMapCorsAddsPreflightRoute(): void + { + $this->sendRequest('/verbs/purge', 'OPTIONS', []); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertNull($result['data']); + } + + public function testApiOptionsReachesAction(): void + { + $this->assertReaches('/verbs/probe', 'OPTIONS', AttributeVerbOptionsAction::class, 'probe'); + } + + public function testApiRouteAcceptsEveryListedMethod(): void + { + $this->assertReaches('/verbs/search', 'GET', AttributeVerbRouteAction::class, 'search'); + $this->assertReaches('/verbs/search', 'POST', AttributeVerbRouteAction::class, 'search'); + } + + /** + * @return array + */ + public static function wrongMethodProvider(): array + { + return [ + 'GET on ApiPost' => ['/verbs/create', 'GET'], + 'PUT on ApiPost' => ['/verbs/create', 'PUT'], + 'POST on ApiPut' => ['/verbs/5/replace', 'POST'], + 'PUT on ApiPatch' => ['/verbs/5/touch', 'PUT'], + 'GET on ApiDelete' => ['/verbs/purge', 'GET'], + 'GET on ApiOptions' => ['/verbs/probe', 'GET'], + 'DELETE on ApiRoute GET|POST' => ['/verbs/search', 'DELETE'], + 'POST on repeated ApiGet' => ['/verbs/ping', 'POST'], + 'GET on repeated ApiPost' => ['/verbs/pong', 'GET'], + 'GET on scoped ApiPost' => [self::SCOPED . '/plain', 'GET'], + ]; + } + + #[DataProvider('wrongMethodProvider')] + public function testWrongMethodIsRefused(string $url, string $method): void + { + $this->assertNoRoute($url, $method); + } + + public function testRepeatedAttributesRegisterEveryRoute(): void + { + $this->assertReaches('/verbs/ping', 'GET', AttributeVerbRepeatedAction::class, 'ping'); + $this->assertReaches('/verbs/pong', 'POST', AttributeVerbRepeatedAction::class, 'pong'); + $this->assertReaches('/verbs/stamp', 'PATCH', AttributeVerbRepeatedAction::class, 'stamp'); + } + + public function testEmptyRoutePathFallsBackToActionName(): void + { + // `#[ApiRoute(action: 'stamp', path: '/')]` is served at /verbs/stamp, not /verbs + $this->assertReaches('/verbs/stamp', 'PATCH', AttributeVerbRepeatedAction::class, 'stamp'); + $this->assertNoRoute('/verbs', 'PATCH'); + } + + public function testScopePathPrefixIsApplied(): void + { + $this->assertReaches(self::SCOPED . '/plain', 'POST', AttributeScopedPlainAction::class, 'plain'); + $this->assertNoRoute('/scoped/plain', 'POST'); + $this->assertNoRoute('/scoped/v2/extra/plain', 'POST'); + $this->assertNoRoute('/scoped/base/plain', 'POST'); + } + + public function testScopePatternAcceptsMatchingPlaceholder(): void + { + $route = $this->assertReaches(self::SCOPED . '/code/abc', 'GET', AttributeScopedCodeAction::class, 'code'); + $this->assertSame('abc', $route['code']); + } + + public function testScopePatternRejectsNonMatchingPlaceholder(): void + { + $this->sendRequest(self::SCOPED . '/code/12345', 'GET', []); + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + } + + public function testRoutePatternRejectsNonMatchingPlaceholder(): void + { + $route = $this->assertReaches('/verbs/lookup/12', 'GET', AttributeVerbRouteAction::class, 'lookup'); + $this->assertSame('12', $route['code']); + + $this->sendRequest('/verbs/lookup/abc', 'GET', []); + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + } + + public function testRoutePatternOverridesScopePattern(): void + { + $route = $this->assertReaches(self::SCOPED . '/tagged/12', 'GET', AttributeScopedTaggedAction::class, 'tagged'); + $this->assertSame('12', $route['code']); + + $this->sendRequest(self::SCOPED . '/tagged/abc', 'GET', []); + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + } + + public function testScopeDefaultsReachAction(): void + { + $route = $this->assertReaches(self::SCOPED . '/plain', 'POST', AttributeScopedPlainAction::class, 'plain'); + // child scope overrides the parent value, parent-only keys are kept + $this->assertSame('child', $route['tier']); + $this->assertSame('parent', $route['origin']); + } + + public function testRouteDefaultsReachAction(): void + { + $route = $this->assertReaches('/verbs/lookup/12', 'GET', AttributeVerbRouteAction::class, 'lookup'); + $this->assertSame('on', $route['flag']); + } + + public function testRoutePassReachesAction(): void + { + $route = $this->assertReaches('/verbs/lookup/12', 'GET', AttributeVerbRouteAction::class, 'lookup'); + $this->assertSame(['12'], $route['pass']); + } +} diff --git a/tests/TestCase/Integration/Service/Action/Auth/JwtLoginActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/JwtLoginActionTest.php index bead9086..e86d0468 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/JwtLoginActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/JwtLoginActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; diff --git a/tests/TestCase/Integration/Service/Action/Auth/JwtRefreshActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/JwtRefreshActionTest.php index 10e9659c..5140afa2 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/JwtRefreshActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/JwtRefreshActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2018 - 2020, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; @@ -19,10 +19,7 @@ use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\IntegrationTestCase; -use DateTimeImmutable; -use Lcobucci\JWT\Configuration; -use Lcobucci\JWT\Signer\Hmac\Sha512; -use Lcobucci\JWT\Signer\Key\InMemory; +use Firebase\JWT\JWT; /** * Class RefreshActionTest @@ -90,7 +87,6 @@ public function testSuccessRefresh(): void $this->assertSuccess($result); $this->assertTrue(is_array($result['data'])); $this->assertTrue(array_key_exists('refresh_token', $result['data'])); - sleep(1); ServiceRegistry::getServiceLocator()->clear(); $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, [ @@ -114,7 +110,6 @@ public function testRefreshKeepsTwoFactorAudience(): void $this->assertSuccess($result); $this->assertSame($twoFactorAudience, $this->jwtPayload($result['data']['access_token'])['aud']); $this->assertSame($twoFactorAudience, $this->jwtPayload($result['data']['refresh_token'])['aud']); - sleep(1); ServiceRegistry::getServiceLocator()->clear(); $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, [ @@ -155,7 +150,7 @@ protected function requireTwoFactorPassedForArticles(): void 'role' => '*', 'service' => 'articles', 'action' => 'index', - 'allowed' => new TwoFactorPassedScope(), + 'allowed' => ['className' => TwoFactorPassedScope::class], ], [ 'role' => '*', @@ -170,10 +165,11 @@ protected function requireTwoFactorPassedForArticles(): void /** * Logs user-1 in, then replaces the stored refresh token with one carrying the given audiences. * - * @param string ...$audiences Audiences for the `aud` claim, none for no claim. + * @param array $audiences Audiences for the `aud` claim, none for no claim. + * @param array $claims Extra claims, for example `auth_time`. * @return string The stored refresh token. */ - protected function storeRefreshToken(string ...$audiences): string + protected function storeRefreshToken(array $audiences = [], array $claims = []): string { // Log in first: that loads the api config (so the signing secret is available) and // creates the user's jwt_refresh_tokens row, which we then replace. @@ -185,17 +181,18 @@ protected function storeRefreshToken(string ...$audiences): string $secret = Configure::read('Api.Jwt.RefreshToken.secret'); $this->assertNotEmpty($secret); - $config = Configuration::forSymmetricSigner(new Sha512(), InMemory::plainText((string)$secret)); - $timestamp = new DateTimeImmutable(); - $builder = $config->builder() - ->issuedBy('http://example.com/') - ->issuedAt($timestamp) - ->expiresAt($timestamp->modify('+1 day')) - ->relatedTo((string)$user->get('id')); + $timestamp = time(); + $payload = [ + 'iss' => 'http://example.com/', + 'iat' => $timestamp, + 'exp' => $timestamp + 86400, + 'sub' => (string)$user->get('id'), + ]; if ($audiences !== []) { - $builder = $builder->permittedFor(...$audiences); + // one audience is a string, several are a list + $payload['aud'] = count($audiences) === 1 ? $audiences[0] : $audiences; } - $token = $builder->getToken($config->signer(), $config->signingKey())->toString(); + $token = JWT::encode($claims + $payload, (string)$secret, 'HS512'); $table = TableRegistry::getTableLocator()->get('CakeDC/Api.JwtRefreshTokens'); $entity = $table->find()->where([ @@ -223,7 +220,7 @@ public function testRefreshRejectsTokenWithoutAudience(): void public function testRefreshRejectsTokenWithArrayAudience(): void { // RFC 7519 allows a multi-valued `aud`; it cannot be carried into the new tokens - $token = $this->storeRefreshToken('http://example.com/2fa', 'http://example.com/'); + $token = $this->storeRefreshToken(['http://example.com/2fa', 'http://example.com/']); ServiceRegistry::getServiceLocator()->clear(); $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); @@ -232,7 +229,7 @@ public function testRefreshRejectsTokenWithArrayAudience(): void public function testRefreshRejectsTokenWithEmptyAudience(): void { - $token = $this->storeRefreshToken(''); + $token = $this->storeRefreshToken(['']); ServiceRegistry::getServiceLocator()->clear(); $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); @@ -271,7 +268,6 @@ public function testRefreshedTokenCannotSkipSecondFactor(): void // step 2 (control): the 2FA-pending token is denied on the protected endpoint $pending = $this->articlesWithToken($login['data']['access_token']); $this->assertSame('200 error', $pending, 'Control failed: the 2FA-pending token was not denied, so the permission setup is wrong'); - sleep(1); // step 3: refresh with the 2FA-pending refresh token ServiceRegistry::getServiceLocator()->clear(); @@ -289,4 +285,151 @@ public function testRefreshedTokenCannotSkipSecondFactor(): void sprintf('2FA bypass: pending token got "%s", refreshed token got "%s"', $pending, $refreshed), ); } + + /** + * Limits the session lifetime through the api config the test app loads. + * + * @param mixed $seconds Maximum session age. + * @return void + */ + protected function limitSessionLifetime(mixed $seconds): void + { + $config = include dirname(__DIR__, 5) . DS . 'Config' . DS . 'api.php'; + $config['Api']['Jwt']['RefreshToken']['maxSessionLifetime'] = $seconds; + Configure::write('Test.Api.Config', $config); + } + + public function testRefreshKeepsAuthTime(): void + { + $this->sendRequest('/auth/jwt_login', 'POST', ['username' => 'user-1', 'password' => '12345']); + $login = $this->getJsonResponse(); + $this->assertSuccess($login); + $authTime = $this->jwtPayload($login['data']['refresh_token'])['auth_time']; + $this->assertIsInt($authTime); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $login['data']['refresh_token']]); + $refresh = $this->getJsonResponse(); + $this->assertSuccess($refresh); + $this->assertSame($authTime, $this->jwtPayload($refresh['data']['refresh_token'])['auth_time']); + } + + public function testRefreshWithinMaxSessionLifetime(): void + { + $this->limitSessionLifetime(3600); + $token = $this->storeRefreshToken(['http://example.com/'], ['auth_time' => time() - 60]); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $this->assertSuccess($this->getJsonResponse()); + } + + public function testRefreshRejectedAfterMaxSessionLifetime(): void + { + $this->limitSessionLifetime(3600); + $token = $this->storeRefreshToken(['http://example.com/'], ['auth_time' => time() - 7200]); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $this->assertError($this->getJsonResponse(), 401); + } + + public function testRefreshWithoutAuthTimeRejectedWhenSessionLifetimeIsLimited(): void + { + // a refresh token issued before `auth_time` existed cannot prove the session age + $this->limitSessionLifetime(3600); + $token = $this->storeRefreshToken(['http://example.com/']); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $this->assertError($this->getJsonResponse(), 401); + } + + public function testOldSessionRefreshesWhenLifetimeIsUnlimited(): void + { + $token = $this->storeRefreshToken(['http://example.com/'], ['auth_time' => time() - 365 * 86400]); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $this->assertSuccess($this->getJsonResponse()); + } + + public function testLegacySessionEndsWhenLifetimeIsLimitedLater(): void + { + // refreshing without the setting must not give a pre-upgrade session a fresh auth_time + $token = $this->storeRefreshToken(['http://example.com/']); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $refresh = $this->getJsonResponse(); + $this->assertSuccess($refresh); + $this->assertArrayNotHasKey('auth_time', $this->jwtPayload($refresh['data']['refresh_token'])); + + $this->limitSessionLifetime(3600); + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $refresh['data']['refresh_token']]); + $this->assertError($this->getJsonResponse(), 401); + } + + public function testFalseSessionLifetimeIsUnlimited(): void + { + $this->limitSessionLifetime(false); + $token = $this->storeRefreshToken(['http://example.com/'], ['auth_time' => time() - 365 * 86400]); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $this->assertSuccess($this->getJsonResponse()); + } + + public function testDigitStringSessionLifetimeIsAccepted(): void + { + // a value read from an environment variable is a string + $this->limitSessionLifetime('3600'); + $token = $this->storeRefreshToken(['http://example.com/'], ['auth_time' => time() - 60]); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $this->assertSuccess($this->getJsonResponse()); + + $this->limitSessionLifetime('30'); + $token = $this->storeRefreshToken(['http://example.com/'], ['auth_time' => time() - 60]); + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $this->assertSame('error', $this->getJsonResponse()['status']); + } + + public function testInvalidSessionLifetimeIsRejected(): void + { + $this->limitSessionLifetime('1h'); + $token = $this->storeRefreshToken(['http://example.com/'], ['auth_time' => time()]); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => $token]); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertStringContainsString('maxSessionLifetime must be null or a positive number of seconds', (string)($result['message'] ?? '')); + } + + public function testRefreshWithBearerHeader(): void + { + // clients send `Authorization: Bearer `; the stored token is compared without the prefix + $this->sendRequest('/auth/jwt_login', 'POST', ['username' => 'user-1', 'password' => '12345']); + $login = $this->getJsonResponse(); + $this->assertSuccess($login); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh', 'POST', [], null, ['Authorization' => 'Bearer ' . $login['data']['refresh_token']]); + $this->assertSuccess($this->getJsonResponse()); + } + + public function testRefreshWithQueryTokenIsRejected(): void + { + $this->sendRequest('/auth/jwt_login', 'POST', ['username' => 'user-1', 'password' => '12345']); + $login = $this->getJsonResponse(); + $this->assertSuccess($login); + + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_refresh?token=' . urlencode($login['data']['refresh_token']), 'POST'); + $this->assertError($this->getJsonResponse(), 401); + } } diff --git a/tests/TestCase/Integration/Service/Action/Auth/LoginActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/LoginActionTest.php index cde11283..bc7009ea 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/LoginActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/LoginActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; diff --git a/tests/TestCase/Integration/Service/Action/Auth/OtpVerifyFlowTest.php b/tests/TestCase/Integration/Service/Action/Auth/OtpVerifyFlowTest.php new file mode 100644 index 00000000..e1b11cb0 --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/OtpVerifyFlowTest.php @@ -0,0 +1,255 @@ +clear(); + $this->_authAccess(); + Configure::write('App.fullBaseUrl', 'http://example.com'); + + $config = include dirname(__DIR__, 5) . DS . 'Config' . DS . 'api.php'; + $config['Api']['2fa']['enabled'] = true; + $config['Api']['OneTimePasswordAuthenticator']['login'] = true; + Configure::write('Test.Api.Config', $config); + // the documented setup: the OTP endpoints need a `/2fa` token, protected data a `/` token + Configure::write('Test.Api.Permissions', [ + [ + 'role' => '*', + 'service' => 'auth', + 'action' => ['otp_verify', 'otp_verify_check'], + 'allowed' => ['className' => TwoFactorScope::class], + ], + [ + 'role' => '*', + 'service' => 'articles', + 'action' => 'index', + 'allowed' => ['className' => TwoFactorPassedScope::class], + ], + [ + 'role' => '*', + 'service' => '*', + 'action' => '*', + 'method' => '*', + 'bypassAuth' => true, + ], + ]); + + // start without an enrolled OTP secret + TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->updateQuery() + ->set(['secret' => null, 'secret_verified' => false]) + ->where(['username' => 'user-1']) + ->execute(); + } + + protected function tearDown(): void + { + parent::tearDown(); + Configure::delete('Test.Api.Config'); + Configure::delete('Test.Api.Permissions'); + } + + /** + * Decodes the claims of a JWT without verifying it. + * + * @param string $token JWT. + * @return array + */ + protected function jwtPayload(string $token): array + { + $parts = explode('.', $token); + + return json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true, 512, JSON_THROW_ON_ERROR); + } + + /** + * Sends a request with a JWT and returns the decoded JSend body. + * + * @param string $url Url. + * @param string $method HTTP method. + * @param array $data Request data. + * @param string $token JWT. + * @return array + */ + protected function withToken(string $url, string $method, array $data, string $token): array + { + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest($url, $method, $data, null, ['Authorization' => $token]); + + return (array)json_decode((string)$this->_response->getBody(), true); + } + + /** + * Logs user-1 in with the password. + * + * @return array Token response data. + */ + protected function login(): array + { + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest('/auth/jwt_login', 'POST', ['username' => 'user-1', 'password' => '12345']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + + return $result['data']; + } + + /** + * Returns the current TOTP code for a secret, with the same settings as the OTP actions. + * + * @param string $secret Base32 shared secret. + * @return string + */ + protected function currentCode(string $secret): string + { + $tfa = new TwoFactorAuth(qrcodeprovider: Configure::read('OneTimePasswordAuthenticator.qrcodeprovider')); + + return $tfa->getCode($secret); + } + + public function testOtpFlowReachesFullAccessAndRefreshKeepsIt(): void + { + // step 1: the password alone gives a `/2fa` token, which protected data refuses + $login = $this->login(); + $this->assertSame(self::PENDING, $this->jwtPayload($login['access_token'])['aud']); + $this->assertSame('error', $this->withToken('/articles', 'GET', [], $login['access_token'])['status']); + + // step 2: the `/2fa` token gets the shared secret and its QR code + $verify = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + $this->assertSame('success', $verify['status']); + $this->assertFalse($verify['data']['verified']); + $this->assertNotEmpty($verify['data']['secret']); + $this->assertStringStartsWith('data:image/', $verify['data']['secretDataUri']); + $secret = $verify['data']['secret']; + + // step 3: a valid code issues `/` tokens and marks the secret verified + $check = $this->withToken('/auth/otp_verify_check', 'POST', ['code' => $this->currentCode($secret)], $login['access_token']); + $this->assertSame('success', $check['status']); + $this->assertSame(self::PASSED, $this->jwtPayload($check['data']['access_token'])['aud']); + $this->assertSame(self::PASSED, $this->jwtPayload($check['data']['refresh_token'])['aud']); + $this->assertArrayNotHasKey('secret', $check['data']); + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->find()->where(['username' => 'user-1'])->firstOrFail(); + $this->assertTrue((bool)$user->get('secret_verified')); + + // step 4: the `/` token reaches protected data + $this->assertSame('success', $this->withToken('/articles', 'GET', [], $check['data']['access_token'])['status']); + + // step 5: refreshing the `/` session keeps `/` + $refresh = $this->withToken('/auth/jwt_refresh', 'POST', [], $check['data']['refresh_token']); + $this->assertSame('success', $refresh['status']); + $this->assertSame(self::PASSED, $this->jwtPayload($refresh['data']['access_token'])['aud']); + $this->assertSame('success', $this->withToken('/articles', 'GET', [], $refresh['data']['access_token'])['status']); + } + + public function testInvalidCodeIsRejected(): void + { + $login = $this->login(); + $verify = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + $this->assertSame('success', $verify['status']); + $valid = $this->currentCode($verify['data']['secret']); + $wrong = str_pad((string)(((int)$valid + 1) % 1000000), 6, '0', STR_PAD_LEFT); + + $check = $this->withToken('/auth/otp_verify_check', 'POST', ['code' => $wrong], $login['access_token']); + $this->assertSame('error', $check['status']); + $this->assertStringContainsString('Verification code is invalid', (string)($check['message'] ?? '')); + $this->assertArrayNotHasKey('access_token', (array)($check['data'] ?? [])); + + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->find()->where(['username' => 'user-1'])->firstOrFail(); + $this->assertFalse((bool)$user->get('secret_verified')); + } + + public function testNumericCodeFromJsonIsAccepted(): void + { + // a JSON body gives an int; robthree's verifyCode() requires a string + $login = $this->login(); + $verify = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + do { + $code = $this->currentCode($verify['data']['secret']); + } while ($code[0] === '0' && sleep(1) === 0); + + $check = $this->withToken('/auth/otp_verify_check', 'POST', ['code' => (int)$code], $login['access_token']); + $this->assertSame('success', $check['status'] ?? null, (string)$this->_response->getBody()); + $this->assertSame(self::PASSED, $this->jwtPayload($check['data']['access_token'])['aud']); + } + + public function testMissingOrNonScalarCodeIsRejected(): void + { + $login = $this->login(); + $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + foreach (['missing' => [], 'array' => ['code' => ['123456']]] as $case => $data) { + $check = $this->withToken('/auth/otp_verify_check', 'POST', $data, $login['access_token']); + $this->assertSame('error', $check['status'] ?? null, $case . ': ' . $this->_response->getBody()); + $this->assertStringContainsString('Verification code is invalid', (string)($check['message'] ?? ''), $case); + $this->assertArrayNotHasKey('access_token', (array)($check['data'] ?? []), $case); + } + } + + public function testFullAccessTokenCannotUseTheOtpEndpoints(): void + { + // TwoFactorScope limits the OTP endpoints to `/2fa` tokens; this also proves the + // permission rules above match, so the flow test does not pass through bypassAuth + $login = $this->login(); + $verify = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + $check = $this->withToken('/auth/otp_verify_check', 'POST', ['code' => $this->currentCode($verify['data']['secret'])], $login['access_token']); + $this->assertSame('success', $check['status']); + + $this->assertSame('error', $this->withToken('/auth/otp_verify', 'GET', [], $check['data']['access_token'])['status']); + } + + public function testSecretIsNotDisclosedAfterVerification(): void + { + $login = $this->login(); + $verify = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + $check = $this->withToken('/auth/otp_verify_check', 'POST', ['code' => $this->currentCode($verify['data']['secret'])], $login['access_token']); + $this->assertSame('success', $check['status']); + + // a later password login is `/2fa` again, but the enrolled secret is not handed out + $second = $this->login(); + $this->assertSame(self::PENDING, $this->jwtPayload($second['access_token'])['aud']); + $again = $this->withToken('/auth/otp_verify', 'GET', [], $second['access_token']); + $this->assertSame('success', $again['status']); + $this->assertSame(['verified' => true], $again['data']); + } +} diff --git a/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php index 3ebedbd1..dfa2f33b 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/RegisterActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; diff --git a/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordActionTest.php index abe7d9e2..fc441e5d 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; @@ -81,4 +81,79 @@ public function testSuccessPasswordReset(): void $result = $this->getJsonResponse(); $this->assertSuccess($result); } + + public function testMissingTokenFailsValidation(): void + { + $this->sendRequest('/auth/reset_password', 'POST', ['password' => 'new-password', 'password_confirm' => 'new-password']); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Validation failed'); + } + + public function testPasswordMismatchFailsValidation(): void + { + $this->sendRequest('/auth/reset_password', 'POST', [ + 'token' => 'ae93ddbe32664ce7927cf0c5c5a5e59d', + 'password' => 'new-password', + 'password_confirm' => 'other-password', + ]); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Validation failed'); + $this->assertPasswordUnchanged(); + } + + public function testUnknownTokenIsRejected(): void + { + $this->sendRequest('/auth/reset_password', 'POST', [ + 'token' => 'no-such-token', + 'password' => 'new-password', + 'password_confirm' => 'new-password', + ]); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Invalid token or user account already validated'); + $this->assertPasswordUnchanged(); + } + + public function testExpiredTokenIsRejected(): void + { + // user-2's token expired in 2015 + $this->sendRequest('/auth/reset_password', 'POST', [ + 'token' => '6614f65816754310a5f0553436dd89e9', + 'password' => 'new-password', + 'password_confirm' => 'new-password', + ]); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Token already expired'); + + $this->sendRequest('/auth/login', 'POST', ['username' => 'user-2', 'password' => 'new-password']); + $this->assertSame('error', $this->getJsonResponse()['status']); + } + + public function testTokenCannotBeReusedAfterReset(): void + { + $token = 'ae93ddbe32664ce7927cf0c5c5a5e59d'; + $this->sendRequest('/auth/reset_password', 'POST', ['token' => $token, 'password' => 'new-password', 'password_confirm' => 'new-password']); + $this->assertSuccess($this->getJsonResponse()); + + // a reset token is single use: replaying it must not change the password again + $this->sendRequest('/auth/reset_password', 'POST', ['token' => $token, 'password' => 'second-password', 'password_confirm' => 'second-password']); + $this->assertSame('error', $this->getJsonResponse()['status']); + + $this->sendRequest('/auth/login', 'POST', ['username' => 'user-1', 'password' => 'new-password']); + $this->assertSuccess($this->getJsonResponse()); + } + + /** + * Asserts user-1 can still log in with the fixture password. + * + * @return void + */ + protected function assertPasswordUnchanged(): void + { + $this->sendRequest('/auth/login', 'POST', ['username' => 'user-1', 'password' => '12345']); + $this->assertSuccess($this->getJsonResponse()); + } } diff --git a/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordRequestActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordRequestActionTest.php index c64c3043..2dba5c77 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordRequestActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/ResetPasswordRequestActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; @@ -69,4 +69,20 @@ public function testSuccessResetPasswordRequest(): void $user = $Users->find()->where(['id' => Settings::USER1])->enableHydration(false)->first(); $this->assertNotEmpty($user['token']); } + + public function testMissingReferenceFailsValidation(): void + { + $this->sendRequest('/auth/reset_password_request', 'POST', []); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Validation failed'); + } + + public function testUnknownUserIsRejected(): void + { + $this->sendRequest('/auth/reset_password_request', 'POST', ['reference' => 'nobody']); + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + $this->assertErrorMessage($result, 'User nobody was not found'); + } } diff --git a/tests/TestCase/Integration/Service/Action/Auth/SecondFactorEnrollmentTest.php b/tests/TestCase/Integration/Service/Action/Auth/SecondFactorEnrollmentTest.php index c98e86e6..a5c49896 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/SecondFactorEnrollmentTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/SecondFactorEnrollmentTest.php @@ -122,7 +122,7 @@ public function testOtpCannotBeEnrolledWhenWebauthnIsRegistered(): void // a secret provisioned before the key was registered cannot be verified either $this->setOtp(self::SECRET, false); - $tfa = new TwoFactorAuth(); + $tfa = new TwoFactorAuth(qrcodeprovider: Configure::read('OneTimePasswordAuthenticator.qrcodeprovider')); $this->assertRefused($this->withToken( '/auth/otp_verify_check', 'POST', @@ -136,7 +136,7 @@ public function testVerifiedOtpStillWorksWhenWebauthnIsAlsoRegistered(): void // a user who registered both factors earlier can still pass the second step with OTP [$login] = $this->loginAndRegister(); $this->setOtp(self::SECRET, true); - $tfa = new TwoFactorAuth(); + $tfa = new TwoFactorAuth(qrcodeprovider: Configure::read('OneTimePasswordAuthenticator.qrcodeprovider')); $check = $this->withToken('/auth/otp_verify_check', 'POST', ['code' => $tfa->getCode(self::SECRET)], $login['access_token']); $this->assertSame('success', $check['status'] ?? null, (string)$this->_response->getBody()); diff --git a/tests/TestCase/Integration/Service/Action/Auth/SocialLoginActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/SocialLoginActionTest.php new file mode 100644 index 00000000..11b6b53f --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/SocialLoginActionTest.php @@ -0,0 +1,196 @@ +clear(); + $this->_authAccess(); + Configure::write('App.fullBaseUrl', 'http://example.com'); + } + + /** + * Posts a social profile as a JSON body, so numeric values keep their type. + * + * @param array $body Request body. + * @return array Decoded JSend response. + */ + protected function socialLogin(array $body): array + { + $this->sendRequest( + '/auth/social_login', + 'POST', + json_encode($body, JSON_THROW_ON_ERROR), + null, + ['Content-Type' => 'application/json', 'Accept' => 'application/json'], + ); + + return $this->getJsonResponse(); + } + + public function testExistingSocialAccountLogsInItsUser(): void + { + $result = $this->socialLogin([ + 'data' => [ + 'provider' => 'Facebook', + 'id' => 'reference-1-1234', + 'link' => 'https://facebook.example/user-1', + 'credentials' => ['token' => 'fresh-token', 'secret' => 'fresh-secret', 'expires' => 2000000000], + ], + 'options' => [], + ]); + + $this->assertSuccess($result); + $this->assertSame('00000000-0000-0000-0000-000000000001', $result['data']['id']); + $this->assertSame('user-1', $result['data']['username']); + foreach (['password', 'api_token', 'secret', 'token', 'token_expires'] as $hidden) { + $this->assertArrayNotHasKey($hidden, $result['data']); + } + + // the stored account is refreshed with the provider credentials + $account = TableRegistry::getTableLocator()->get('CakeDC/Users.SocialAccounts') + ->get('00000000-0000-0000-0000-000000000001'); + $this->assertSame('fresh-token', $account->get('token')); + $this->assertSame('fresh-secret', $account->get('token_secret')); + $this->assertSame(2000000000, $account->get('token_expires')->getTimestamp()); + } + + public function testNewProfileCreatesUserAndSocialAccount(): void + { + $result = $this->socialLogin([ + 'data' => [ + 'provider' => 'Google', + 'id' => 'google-ref-1', + 'link' => 'https://google.example/new-user', + 'email' => 'new.user@example.com', + 'validated' => true, + 'first_name' => 'New', + 'last_name' => 'User', + 'credentials' => ['token' => 'google-token'], + ], + 'options' => ['use_email' => true], + ]); + + $this->assertSuccess($result); + $this->assertSame('new.user', $result['data']['username']); + $this->assertSame('new.user@example.com', $result['data']['email']); + $this->assertTrue($result['data']['active']); + $this->assertSame('user', $result['data']['role']); + $this->assertArrayNotHasKey('password', $result['data']); + $this->assertSame('google-ref-1', $result['data']['social_accounts'][0]['reference']); + $this->assertArrayNotHasKey('token', $result['data']['social_accounts'][0]); + + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users') + ->find() + ->where(['email' => 'new.user@example.com']) + ->contain(['SocialAccounts']) + ->firstOrFail(); + $this->assertSame($result['data']['id'], $user->get('id')); + $this->assertTrue($user->get('active')); + $this->assertCount(1, $user->get('social_accounts')); + $this->assertSame('Google', $user->get('social_accounts')[0]->get('provider')); + $this->assertTrue($user->get('social_accounts')[0]->get('active')); + $this->assertSame('google-token', $user->get('social_accounts')[0]->get('token')); + } + + /** + * @return array + */ + public static function missingInputProvider(): array + { + return [ + 'no data' => [['options' => []], 'data'], + 'no options' => [['data' => ['provider' => 'Facebook', 'id' => 'reference-1-1234']], 'options'], + ]; + } + + #[DataProvider('missingInputProvider')] + public function testMissingInputFailsValidation(array $body, string $field): void + { + $result = $this->socialLogin($body); + + $this->assertSame('error', $result['status']); + $this->assertSame(422, $result['code']); + $this->assertStringStartsWith('Validation failed', $result['message']); + $this->assertSame(['_required' => 'This field is required'], $result['data'][$field]); + } + + public function testInactiveSocialAccountIsRejected(): void + { + // the Twitter account `reference-2-2` is not active in the fixture + $result = $this->socialLogin([ + 'data' => ['provider' => 'Twitter', 'id' => 'reference-2-2', 'link' => 'https://twitter.example/2'], + 'options' => [], + ]); + + $this->assertSame('error', $result['status']); + $this->assertSame(500, $result['code']); + $this->assertNull($result['data']); + } + + public function testInactiveUserIsRejected(): void + { + TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->updateQuery() + ->set(['active' => false]) + ->where(['id' => '00000000-0000-0000-0000-000000000002']) + ->execute(); + + $result = $this->socialLogin([ + 'data' => ['provider' => 'Facebook', 'id' => 'reference-2-1', 'link' => 'https://facebook.example/2'], + 'options' => [], + ]); + + $this->assertSame('error', $result['status']); + $this->assertSame(501, $result['code']); + $this->assertStringStartsWith('User account has not validated yet', $result['message']); + $this->assertNull($result['data']); + } + + public function testMissingEmailIsRejectedWhenEmailIsRequired(): void + { + $result = $this->socialLogin([ + 'data' => ['provider' => 'Google', 'id' => 'google-ref-2', 'link' => 'https://google.example/2'], + 'options' => ['use_email' => true], + ]); + + $this->assertSame('error', $result['status']); + $this->assertSame(505, $result['code']); + $this->assertStringStartsWith('Email not present', $result['message']); + $this->assertSame( + 0, + TableRegistry::getTableLocator()->get('CakeDC/Users.SocialAccounts')->find()->where(['reference' => 'google-ref-2'])->count(), + ); + } +} diff --git a/tests/TestCase/Integration/Service/Action/Auth/SocialLoginJwtActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/SocialLoginJwtActionTest.php new file mode 100644 index 00000000..c962fa2d --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/SocialLoginJwtActionTest.php @@ -0,0 +1,247 @@ +clear(); + $this->_authAccess(); + Configure::write('App.fullBaseUrl', 'http://example.com'); + } + + protected function tearDown(): void + { + parent::tearDown(); + Configure::delete('Test.Api.Config'); + Configure::delete('Test.Api.Permissions'); + } + + /** + * Decodes the claims of a JWT without verifying it. + * + * @param string $token JWT. + * @return array + */ + protected function jwtPayload(string $token): array + { + $parts = explode('.', $token); + + return json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true, 512, JSON_THROW_ON_ERROR); + } + + /** + * Posts a social profile to jwt_social_login. + * + * @param array $profile Social profile. + * @param array $options Social login options. + * @return array Decoded JSend response. + */ + protected function socialLogin(array $profile, array $options = []): array + { + $this->sendRequest( + '/auth/jwt_social_login', + 'POST', + json_encode(['data' => $profile, 'options' => $options], JSON_THROW_ON_ERROR), + null, + ['Content-Type' => 'application/json', 'Accept' => 'application/json'], + ); + + return $this->getJsonResponse(); + } + + /** + * Sends a request with a JWT and returns the decoded JSend body. + * + * @param string $url Url. + * @param string $method HTTP method. + * @param string $token JWT. + * @return array + */ + protected function withToken(string $url, string $method, string $token): array + { + ServiceRegistry::getServiceLocator()->clear(); + $this->sendRequest($url, $method, [], null, ['Authorization' => $token]); + + return (array)json_decode((string)$this->_response->getBody(), true); + } + + /** + * Number of refresh tokens stored for a user. + * + * @param string $userId User id. + * @return int + */ + protected function storedRefreshTokens(string $userId): int + { + return TableRegistry::getTableLocator()->get('CakeDC/Api.JwtRefreshTokens') + ->find() + ->where(['foreign_key' => $userId]) + ->count(); + } + + /** + * Limits the articles index to tokens that passed the second factor. + * + * @return void + */ + protected function protectArticles(): void + { + Configure::write('Test.Api.Permissions', [ + [ + 'role' => '*', + 'service' => 'articles', + 'action' => 'index', + 'allowed' => ['className' => TwoFactorPassedScope::class], + ], + [ + 'role' => '*', + 'service' => '*', + 'action' => '*', + 'method' => '*', + 'bypassAuth' => true, + ], + ]); + } + + public function testLoginIssuesFullAccessTokens(): void + { + $this->protectArticles(); + $result = $this->socialLogin(['provider' => 'Facebook', 'id' => 'reference-1-1234']); + + $this->assertSuccess($result); + $data = $result['data']; + $this->assertSame(self::USER_1, $data['id']); + $this->assertFalse($data['enabled2FA']); + $this->assertFalse($data['enabledOtp']); + $this->assertFalse($data['enabledWebauthn']); + $this->assertArrayNotHasKey('secret', $data); + $this->assertArrayNotHasKey('secret_verified', $data); + + $access = $this->jwtPayload($data['access_token']); + $refresh = $this->jwtPayload($data['refresh_token']); + $this->assertSame(self::PASSED, $access['aud']); + $this->assertSame(self::PASSED, $refresh['aud']); + $this->assertSame(self::USER_1, $access['sub']); + $this->assertSame(self::USER_1, $refresh['sub']); + $this->assertSame('http://example.com/', $access['iss']); + $this->assertIsInt($refresh['auth_time']); + $this->assertSame('success', $this->withToken('/articles', 'GET', $data['access_token'])['status']); + + // the refresh token is stored and can be used + $this->assertSame(1, $this->storedRefreshTokens(self::USER_1)); + $refreshed = $this->withToken('/auth/jwt_refresh', 'POST', $data['refresh_token']); + $this->assertSame('success', $refreshed['status']); + $this->assertSame(self::PASSED, $this->jwtPayload($refreshed['data']['access_token'])['aud']); + } + + public function testLoginWithTwoFactorEnabledIssuesPendingTokens(): void + { + $config = include dirname(__DIR__, 5) . DS . 'Config' . DS . 'api.php'; + $config['Api']['2fa']['enabled'] = true; + $config['Api']['OneTimePasswordAuthenticator']['login'] = true; + Configure::write('Test.Api.Config', $config); + $this->protectArticles(); + + $result = $this->socialLogin(['provider' => 'Facebook', 'id' => 'reference-1-1234']); + + $this->assertSuccess($result); + $data = $result['data']; + $this->assertTrue($data['enabled2FA']); + $this->assertTrue($data['enabledOtp']); + $this->assertSame(self::PENDING, $this->jwtPayload($data['access_token'])['aud']); + $this->assertSame(self::PENDING, $this->jwtPayload($data['refresh_token'])['aud']); + + // a social login does not skip the second factor + $this->assertSame('error', $this->withToken('/articles', 'GET', $data['access_token'])['status']); + $refreshed = $this->withToken('/auth/jwt_refresh', 'POST', $data['refresh_token']); + $this->assertSame('success', $refreshed['status']); + $this->assertSame(self::PENDING, $this->jwtPayload($refreshed['data']['access_token'])['aud']); + } + + public function testNewProfileGetsTokensForTheCreatedUser(): void + { + $result = $this->socialLogin([ + 'provider' => 'Google', + 'id' => 'google-ref-jwt', + 'link' => 'https://google.example/jwt', + 'email' => 'jwt.user@example.com', + 'validated' => true, + 'full_name' => 'Jwt User', + 'credentials' => ['token' => 'google-token'], + ], ['use_email' => true]); + + $this->assertSuccess($result); + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users') + ->find() + ->where(['email' => 'jwt.user@example.com']) + ->firstOrFail(); + $this->assertSame($user->get('id'), $result['data']['id']); + $this->assertSame($user->get('id'), $this->jwtPayload($result['data']['access_token'])['sub']); + $this->assertSame(self::PASSED, $this->jwtPayload($result['data']['access_token'])['aud']); + $this->assertSame(1, $this->storedRefreshTokens($user->get('id'))); + } + + public function testRejectedLoginIssuesNoToken(): void + { + // the Twitter account `reference-2-2` is not active in the fixture + $result = $this->socialLogin(['provider' => 'Twitter', 'id' => 'reference-2-2']); + + $this->assertSame('error', $result['status']); + $this->assertNull($result['data']); + $this->assertStringNotContainsString('access_token', (string)$this->_response->getBody()); + $this->assertSame(0, $this->storedRefreshTokens('00000000-0000-0000-0000-000000000003')); + $this->assertSame(0, $this->storedRefreshTokens('00000000-0000-0000-0000-000000000004')); + } + + public function testMissingOptionsFailsValidation(): void + { + $this->sendRequest('/auth/jwt_social_login', 'POST', ['data' => ['provider' => 'Facebook', 'id' => 'reference-1-1234']]); + $result = $this->getJsonResponse(); + + $this->assertSame('error', $result['status']); + $this->assertSame(422, $result['code']); + $this->assertArrayHasKey('options', $result['data']); + $this->assertSame(0, $this->storedRefreshTokens(self::USER_1)); + } +} diff --git a/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php b/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php index defdf47c..71ad1f73 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php +++ b/tests/TestCase/Integration/Service/Action/Auth/SoftwareAuthenticatorTrait.php @@ -152,12 +152,21 @@ protected function attestation(OpenSSLAsymmetricKey $key, string $credentialId, * @param string $credentialId Credential id. * @param string $challenge Base64url challenge from the request options. * @param int $signCount Signature counter. + * @param array $clientData Members of the client data to add or replace, such as `origin`. * @return array */ - protected function assertion(OpenSSLAsymmetricKey $key, string $credentialId, string $challenge, int $signCount = 1): array - { + protected function assertion( + OpenSSLAsymmetricKey $key, + string $credentialId, + string $challenge, + int $signCount = 1, + array $clientData = [], + ): array { $authData = hash('sha256', self::RP_ID, true) . chr(0x05) . pack('N', $signCount); // user present, user verified - $clientData = json_encode(['type' => 'webauthn.get', 'challenge' => $challenge, 'origin' => self::ORIGIN], JSON_THROW_ON_ERROR); + $clientData = json_encode( + $clientData + ['type' => 'webauthn.get', 'challenge' => $challenge, 'origin' => self::ORIGIN], + JSON_THROW_ON_ERROR, + ); $this->assertTrue(openssl_sign($authData . hash('sha256', $clientData, true), $signature, $key, OPENSSL_ALGO_SHA256)); return [ @@ -167,7 +176,7 @@ protected function assertion(OpenSSLAsymmetricKey $key, string $credentialId, st 'response' => [ 'clientDataJSON' => static::b64url($clientData), 'authenticatorData' => static::b64url($authData), - 'signature' => base64_encode((string)$signature), + 'signature' => base64_encode($signature), ], ]; } diff --git a/tests/TestCase/Integration/Service/Action/Auth/TwoFactorAuthActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/TwoFactorAuthActionTest.php new file mode 100644 index 00000000..211a776b --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/TwoFactorAuthActionTest.php @@ -0,0 +1,143 @@ +clear(); + $this->_authAccess(); + Configure::write('App.fullBaseUrl', 'http://example.com'); + $this->enableTwoFactor(true); + // start without any second factor + $this->setOtp(null, false); + } + + protected function tearDown(): void + { + parent::tearDown(); + Configure::delete('Test.Api.Config'); + } + + /** + * @param bool $enabled Whether 2FA and OTP login are enabled. + * @return void + */ + protected function enableTwoFactor(bool $enabled): void + { + $config = include dirname(__DIR__, 5) . DS . 'Config' . DS . 'api.php'; + $config['Api']['2fa']['enabled'] = $enabled; + $config['Api']['OneTimePasswordAuthenticator']['login'] = $enabled; + Configure::write('Test.Api.Config', $config); + } + + /** + * @param string|null $secret OTP secret of user-1. + * @param bool $verified Whether the secret is verified. + * @return void + */ + protected function setOtp(?string $secret, bool $verified): void + { + TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->updateQuery() + ->set(['secret' => $secret, 'secret_verified' => $verified]) + ->where(['username' => 'user-1']) + ->execute(); + } + + /** + * Calls two_factor_auth with a fresh login token. + * + * @return array The action data. + */ + protected function twoFactorStatus(): array + { + $result = $this->withToken('/auth/two_factor_auth', 'GET', [], $this->login()['access_token']); + $this->assertSame('success', $result['status']); + + return $result['data']; + } + + public function testNothingRegistered(): void + { + $this->assertSame([ + 'hasRegistered2fa' => false, + 'hasOtp' => false, + 'hasWebauthn' => false, + 'enabledWebauthn' => true, + 'enabledOtp' => true, + ], $this->twoFactorStatus()); + } + + public function testVerifiedOtpSecretCountsAsOtp(): void + { + $this->setOtp('JBSWY3DPEHPK3PXP', true); + $status = $this->twoFactorStatus(); + $this->assertTrue($status['hasOtp']); + $this->assertFalse($status['hasWebauthn']); + } + + public function testUnverifiedOtpSecretDoesNotCount(): void + { + // otp_verify stores the secret before the first code is checked + $this->setOtp('JBSWY3DPEHPK3PXP', false); + $this->assertFalse($this->twoFactorStatus()['hasOtp']); + } + + public function testRegisteredWebauthnCredentialCounts(): void + { + $this->loginAndRegister(); + $status = $this->twoFactorStatus(); + $this->assertTrue($status['hasWebauthn']); + $this->assertFalse($status['hasOtp']); + } + + public function testBothFactorsRegistered(): void + { + $this->loginAndRegister(); + $this->setOtp('JBSWY3DPEHPK3PXP', true); + $status = $this->twoFactorStatus(); + $this->assertTrue($status['hasWebauthn']); + $this->assertTrue($status['hasOtp']); + $this->assertTrue($status['hasRegistered2fa']); + } + + public function testDisabledTwoFactorIsReported(): void + { + $this->enableTwoFactor(false); + $status = $this->twoFactorStatus(); + $this->assertFalse($status['enabledWebauthn']); + $this->assertFalse($status['enabledOtp']); + } +} diff --git a/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountActionTest.php index a4223f0e..5d7dbfc9 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; @@ -65,4 +65,50 @@ public function testSuccessValidateAccount(): void $result = $this->getJsonResponse(); $this->assertSuccess($result); } + + public function testMissingTokenFailsValidation(): void + { + $this->sendRequest('/auth/validate_account', 'POST', []); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Validation failed'); + } + + public function testUnknownTokenIsRejected(): void + { + $this->sendRequest('/auth/validate_account', 'POST', ['token' => 'no-such-token']); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Invalid token or user account already validated'); + } + + public function testExpiredTokenIsRejected(): void + { + // user-5's token expired in 2015 + $this->sendRequest('/auth/validate_account', 'POST', ['token' => 'token-5']); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Token already expired'); + } + + public function testAlreadyActiveUserIsRejected(): void + { + // user-4 is active and has a valid token + $this->sendRequest('/auth/validate_account', 'POST', ['token' => 'token-4']); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'User already active'); + } + + public function testTokenCannotBeReusedAfterValidation(): void + { + $this->sendRequest('/auth/validate_account', 'POST', ['token' => 'token-6']); + $this->assertSuccess($this->getJsonResponse()); + + // validating clears the token + $this->sendRequest('/auth/validate_account', 'POST', ['token' => 'token-6']); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Invalid token or user account already validated'); + } } diff --git a/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountRequestActionTest.php b/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountRequestActionTest.php index c52486a3..75edd101 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountRequestActionTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/ValidateAccountRequestActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Auth; @@ -61,4 +61,31 @@ public function testSuccessValidateAccountRequest(): void $user = $Users->find()->where(['id' => Settings::USER6])->enableHydration(false)->first(); $this->assertNotEmpty($user['token']); } + + public function testMissingReferenceFailsValidation(): void + { + $this->sendRequest('/auth/validate_account_request', 'POST', []); + $result = $this->getJsonResponse(); + $this->assertSame('error', $result['status']); + $this->assertErrorMessage($result, 'Validation failed'); + } + + public function testUnknownUserIsRejected(): void + { + $this->sendRequest('/auth/validate_account_request', 'POST', ['reference' => 'nobody']); + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + $this->assertErrorMessage($result, 'User nobody was not found'); + } + + public function testActiveUserIsRejected(): void + { + $this->sendRequest('/auth/validate_account_request', 'POST', ['reference' => 'user-1']); + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + $this->assertErrorMessage($result, 'User user-1 is already active'); + + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->find()->where(['id' => Settings::USER1])->enableHydration(false)->first(); + $this->assertSame('ae93ddbe32664ce7927cf0c5c5a5e59d', $user['token'], 'the active user keeps its token'); + } } diff --git a/tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php b/tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php new file mode 100644 index 00000000..9c991b34 --- /dev/null +++ b/tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php @@ -0,0 +1,588 @@ +clear(); + $this->_authAccess(); + Configure::write('App.fullBaseUrl', 'http://example.com'); + + $config = include dirname(__DIR__, 5) . DS . 'Config' . DS . 'api.php'; + $config['Api']['2fa']['enabled'] = true; + Configure::write('Test.Api.Config', $config); + // the WebAuthn endpoints need a `/2fa` token, protected data a `/` token + Configure::write('Test.Api.Permissions', [ + [ + 'role' => '*', + 'service' => 'auth', + 'action' => [ + 'webauthn2fa', + 'webauthn2fa_register_options', + 'webauthn2fa_register', + 'webauthn2fa_auth_options', + 'webauthn2fa_auth', + ], + 'allowed' => ['className' => TwoFactorScope::class], + ], + [ + 'role' => '*', + 'service' => 'articles', + 'action' => 'index', + 'allowed' => ['className' => TwoFactorPassedScope::class], + ], + [ + 'role' => '*', + 'service' => '*', + 'action' => '*', + 'method' => '*', + 'bypassAuth' => true, + ], + ]); + } + + protected function tearDown(): void + { + parent::tearDown(); + Configure::delete('Test.Api.Config'); + Configure::delete('Test.Api.Permissions'); + } + + /** + * Asserts a WebAuthn verification failure is a client error with a generic message and no tokens. + * + * @param array $result JSend body. + * @param int $code Expected JSend error code. + * @param string $message Expected message. + * @return void + */ + protected function assertRejected(array $result, int $code, string $message): void + { + $this->assertSame('error', $result['status'] ?? null, (string)$this->_response->getBody()); + $this->assertSame($code, $result['code'] ?? null); + // debug mode appends the file and line to every error message + $this->assertStringStartsWith($message, (string)($result['message'] ?? '')); + $this->assertArrayNotHasKey('access_token', (array)($result['data'] ?? [])); + } + + public function testAssertionWithoutRequestedOptionsIsRejected(): void + { + [$login, $key, $credentialId] = $this->loginAndRegister(); + + // no webauthn2fa_auth_options call, so there is no stored challenge to check against + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, static::b64url(random_bytes(32))), + $login['access_token'], + ); + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + + public function testMalformedRegistrationIsRejected(): void + { + $login = $this->login(); + $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $register = $this->withToken('/auth/webauthn2fa_register', 'POST', ['id' => 'x', 'type' => 'public-key'], $login['access_token']); + $this->assertRejected($register, 400, 'WebAuthn registration failed'); + } + + public function testRegisterThenAuthenticateReachesFullAccessAndRefreshKeepsIt(): void + { + // step 1: the password alone gives a `/2fa` token, which protected data refuses + $login = $this->login(); + $this->assertSame(self::PENDING, $this->jwtPayload($login['access_token'])['aud']); + $this->assertSame('error', $this->withToken('/articles', 'GET', [], $login['access_token'])['status']); + + // step 2: no credential yet, so the client is told to register + $status = $this->withToken('/auth/webauthn2fa', 'GET', [], $login['access_token']); + $this->assertSame('success', $status['status']); + $this->assertTrue($status['data']['isRegister']); + + // step 3: register an ES256 credential + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $this->assertSame('success', $options['status']); + $this->assertSame(self::RP_ID, $options['data']['rp']['id']); + $key = $this->newKey(); + $credentialId = random_bytes(16); + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($key, $credentialId, $options['data']['challenge']), + $login['access_token'], + ); + $this->assertSame('success', $register['status']); + $this->assertFalse($this->withToken('/auth/webauthn2fa', 'GET', [], $login['access_token'])['data']['isRegister']); + + // step 4: authenticate with that credential, which issues `/` tokens + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $this->assertSame('success', $authOptions['status']); + $this->assertSame(static::b64url($credentialId), $authOptions['data']['allowCredentials'][0]['id']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge']), + $login['access_token'], + ); + $this->assertSame('success', $auth['status']); + $this->assertSame(self::PASSED, $this->jwtPayload($auth['data']['access_token'])['aud']); + $this->assertSame(self::PASSED, $this->jwtPayload($auth['data']['refresh_token'])['aud']); + + // step 5: the `/` token reaches protected data, and refreshing keeps `/` + $this->assertSame('success', $this->withToken('/articles', 'GET', [], $auth['data']['access_token'])['status']); + $refresh = $this->withToken('/auth/jwt_refresh', 'POST', [], $auth['data']['refresh_token']); + $this->assertSame('success', $refresh['status']); + $this->assertSame(self::PASSED, $this->jwtPayload($refresh['data']['access_token'])['aud']); + } + + public function testAssertionSignedByAnotherKeyIsRejected(): void + { + [$login, , $credentialId] = $this->loginAndRegister(); + + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($this->newKey(), $credentialId, $authOptions['data']['challenge']), + $login['access_token'], + ); + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + + public function testAssertionForAnotherChallengeIsRejected(): void + { + [$login, $key, $credentialId] = $this->loginAndRegister(); + + $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, static::b64url(random_bytes(32))), + $login['access_token'], + ); + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + + public function testAssertionForACredentialOfNobodyIsRejected(): void + { + // the credential is looked up in the record of the token's user only + [$login, $key] = $this->loginAndRegister(); + + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, random_bytes(16), $authOptions['data']['challenge']), + $login['access_token'], + ); + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + + public function testAssertionFromAnotherOriginIsRejected(): void + { + [$login, $key, $credentialId] = $this->loginAndRegister(); + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + + $origins = [ + 'another site' => 'https://evil.example', + 'the relying party over http' => 'http://localhost', + 'a site that only ends with the relying party id' => 'https://evillocalhost', + ]; + foreach ($origins as $case => $origin) { + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge'], 1, ['origin' => $origin]), + $login['access_token'], + ); + $this->assertSame(401, $auth['code'] ?? null, $case . ': ' . $this->_response->getBody()); + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + } + + public function testAssertionFromACrossOriginFrameIsRejected(): void + { + // a response that carries `topOrigin` was made inside a frame of another site + [$login, $key, $credentialId] = $this->loginAndRegister(); + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $clientData = ['crossOrigin' => true, 'topOrigin' => 'https://evil.example']; + + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge'], 1, $clientData), + $login['access_token'], + ); + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + + public function testRegistrationFromAnotherOriginIsRejected(): void + { + $login = $this->login(); + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($this->newKey(), random_bytes(16), $options['data']['challenge'], 'https://evil.example'), + $login['access_token'], + ); + $this->assertRejected($register, 400, 'WebAuthn registration failed'); + $this->assertTrue($this->withToken('/auth/webauthn2fa', 'GET', [], $login['access_token'])['data']['isRegister']); + } + + public function testSecondRegistrationIsRejected(): void + { + [$login] = $this->loginAndRegister(); + + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $this->assertSame('error', $options['status']); + $this->assertStringContainsString('already has configured webauthn2fa', (string)($options['message'] ?? '')); + } + + /** + * WebAuthn credentials are stored per domain, and the domain comes from the client's Referer. + * A password alone must not enroll another key by naming another configured domain. + */ + public function testRegistrationUnderAnotherDomainIsRejected(): void + { + [$login] = $this->loginAndRegister(); + $config = Configure::read('Test.Api.Config'); + $config['Api']['Webauthn2fa']['other$test'] = ['appName' => 'other', 'id' => self::RP_ID]; + Configure::write('Test.Api.Config', $config); + $_SERVER['HTTP_REFERER'] = 'https://other.test/'; + try { + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $this->assertSame('error', $options['status'], (string)$this->_response->getBody()); + $this->assertStringContainsString('already has configured webauthn2fa', (string)($options['message'] ?? '')); + + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($this->newKey(), random_bytes(16), static::b64url(random_bytes(32))), + $login['access_token'], + ); + $this->assertRejected($register, 400, 'User already has configured webauthn2fa'); + + // nor set up OTP as a second factor while a WebAuthn key exists under another domain + $otp = $this->withToken('/auth/otp_verify', 'GET', [], $login['access_token']); + $this->assertSame('error', $otp['status'], (string)$this->_response->getBody()); + } finally { + unset($_SERVER['HTTP_REFERER']); + } + } + + public function testSecondRegistrationPostIsRejected(): void + { + // posting a new attestation without asking for options again still cannot add a second credential + [$login] = $this->loginAndRegister(); + + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($this->newKey(), random_bytes(16), static::b64url(random_bytes(32))), + $login['access_token'], + ); + $this->assertRejected($register, 400, 'User already has configured webauthn2fa'); + + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->find()->where(['username' => 'user-1'])->firstOrFail(); + $credentials = Hash::extract((array)$user->get('additional_data'), 'api.{s}.webauthn_credentials'); + $this->assertCount(1, $credentials); + $this->assertCount(1, $credentials[0]); + } + + /** + * Asserts that no member of the data is null, at any level. + * + * @param array $data Data. + * @param string $path Path of the data, for the failure message. + * @return void + */ + protected function assertNoNulls(array $data, string $path = 'data'): void + { + foreach ($data as $key => $value) { + $this->assertNotNull($value, $path . '.' . $key); + if (is_array($value)) { + $this->assertNoNulls($value, $path . '.' . $key); + } + } + } + + public function testOptionsAreSentInTheShapeClientsExpect(): void + { + $login = $this->login(); + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $this->assertSame('success', $options['status'], (string)$this->_response->getBody()); + $data = $options['data']; + + // the relying party name is the appName setting of the domain + $this->assertEquals(['name' => 'apilocal', 'id' => self::RP_ID], $data['rp']); + $this->assertSame('user-1', $data['user']['name']); + $this->assertSame(static::b64url(Settings::USER1), $data['user']['id']); + // binary members are unpadded base64url: 16 bytes give 22 characters + $this->assertMatchesRegularExpression('/^[A-Za-z0-9_-]{22}$/', $data['challenge']); + $this->assertSame('none', $data['attestation']); + // the members earlier versions sent, for clients that decode the options strictly + $this->assertEquals( + ['requireResidentKey' => false, 'userVerification' => 'preferred'], + $data['authenticatorSelection'], + ); + $this->assertContains(['type' => 'public-key', 'alg' => -7], $data['pubKeyCredParams']); + $this->assertArrayNotHasKey('excludeCredentials', $data); + $this->assertNoNulls($data); + + // without a registered key there is no list of allowed credentials + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $this->assertSame('success', $authOptions['status'], (string)$this->_response->getBody()); + $this->assertArrayNotHasKey('allowCredentials', $authOptions['data']); + + [$login, , $credentialId] = $this->loginAndRegister(); + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $this->assertSame('success', $authOptions['status'], (string)$this->_response->getBody()); + $data = $authOptions['data']; + $this->assertSame(self::RP_ID, $data['rpId']); + $this->assertSame('preferred', $data['userVerification']); + // 32 bytes give 43 characters + $this->assertMatchesRegularExpression('/^[A-Za-z0-9_-]{43}$/', $data['challenge']); + $this->assertCount(1, $data['allowCredentials']); + $this->assertSame('public-key', $data['allowCredentials'][0]['type']); + $this->assertSame(static::b64url($credentialId), $data['allowCredentials'][0]['id']); + $this->assertNoNulls($data); + } + + public function testCredentialStoredByEarlierVersionsStillAuthenticates(): void + { + [$login, $key, $credentialId] = $this->loginAndRegister(); + + // rewrite the entry as web-auth/webauthn-lib 4.4 stored it + $users = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $user = $users->find()->where(['username' => 'user-1'])->firstOrFail(); + $additionalData = (array)$user->get('additional_data'); + $id = static::b64url($credentialId); + $entry = $additionalData['api']['localhost']['webauthn_credentials'][$id]; + unset($entry['backupEligible'], $entry['backupStatus'], $entry['uvInitialized']); + $entry['otherUI'] = null; + $entry['transports'] = []; + $this->assertSame(['type' => EmptyTrustPath::class], $entry['trustPath']); + $additionalData['api']['localhost']['webauthn_credentials'][$id] = $entry; + $user->set('additional_data', $additionalData); + $users->saveOrFail($user); + + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $this->assertSame($id, $authOptions['data']['allowCredentials'][0]['id']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge']), + $login['access_token'], + ); + $this->assertSame('success', $auth['status'], (string)$this->_response->getBody()); + $this->assertSame(self::PASSED, $this->jwtPayload($auth['data']['access_token'])['aud']); + } + + public function testCeremonyStartedBeforeTheUpgradeIsRejected(): void + { + // earlier versions stored the serialized options, not the challenge + $legacy = base64_encode(serialize(['challenge' => 'x'])); + $store = TableRegistry::getTableLocator()->get('CakeDC/Api.AuthStore'); + + $login = $this->login(); + $entity = $store->newEmptyEntity(); + $entity->set('id', $login['access_token']); + $entity->set('store', ['api' => ['Webauthn2fa' => ['localhost' => ['registerOptions' => $legacy]]]]); + + $store->saveOrFail($entity); + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($this->newKey(), random_bytes(16), static::b64url(random_bytes(16))), + $login['access_token'], + ); + $this->assertRejected($register, 400, 'WebAuthn registration failed'); + + [$login, $key, $credentialId] = $this->loginAndRegister(); + $entity = $store->get($login['access_token']); + $entity->set('store', ['api' => ['Webauthn2fa' => ['localhost' => ['authenticateOptions' => $legacy]]]]); + + $store->saveOrFail($entity); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, static::b64url(random_bytes(32))), + $login['access_token'], + ); + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + + public function testCounterIsStoredAndAReplayedAssertionIsRejected(): void + { + [$login, $key, $credentialId] = $this->loginAndRegister(); + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge'], 5), + $login['access_token'], + ); + $this->assertSame('success', $auth['status'], (string)$this->_response->getBody()); + + $users = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $user = $users->find()->where(['username' => 'user-1'])->firstOrFail(); + $path = 'api.localhost.webauthn_credentials.' . static::b64url($credentialId) . '.counter'; + $this->assertSame(5, Hash::get((array)$user->get('additional_data'), $path)); + + // a later login: an assertion that does not advance the counter is a replay or a cloned key + $login = $this->login(); + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $replay = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge'], 5), + $login['access_token'], + ); + $this->assertRejected($replay, 401, 'WebAuthn authentication failed'); + + $next = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge'], 6), + $login['access_token'], + ); + $this->assertSame('success', $next['status'], (string)$this->_response->getBody()); + $user = $users->find()->where(['username' => 'user-1'])->firstOrFail(); + $this->assertSame(6, Hash::get((array)$user->get('additional_data'), $path)); + } + + public function testRegistrationOptionsCanBeRequestedAgain(): void + { + // a client that asks for the options twice registers with the second challenge + $login = $this->login(); + $first = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $second = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $this->assertNotSame($first['data']['challenge'], $second['data']['challenge']); + + $key = $this->newKey(); + $stale = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($key, random_bytes(16), $first['data']['challenge']), + $login['access_token'], + ); + $this->assertRejected($stale, 400, 'WebAuthn registration failed'); + + $register = $this->withToken( + '/auth/webauthn2fa_register', + 'POST', + $this->attestation($key, random_bytes(16), $second['data']['challenge']), + $login['access_token'], + ); + $this->assertSame('success', $register['status'], (string)$this->_response->getBody()); + } + + public function testResponsesThatCannotBeDecodedAreRejected(): void + { + $login = $this->login(); + $options = $this->withToken('/auth/webauthn2fa_register_options', 'GET', [], $login['access_token']); + $valid = $this->attestation($this->newKey(), random_bytes(16), $options['data']['challenge']); + + $broken = [ + 'attestation object that is not CBOR' => ['attestationObject', static::b64url('not cbor')], + 'client data that is not JSON' => ['clientDataJSON', static::b64url('{not json')], + 'client data that is not base64' => ['clientDataJSON', '***'], + ]; + foreach ($broken as $case => [$member, $value]) { + $payload = $valid; + $payload['response'][$member] = $value; + $register = $this->withToken('/auth/webauthn2fa_register', 'POST', $payload, $login['access_token']); + $this->assertSame(400, $register['code'] ?? null, $case . ': ' . $this->_response->getBody()); + $this->assertRejected($register, 400, 'WebAuthn registration failed'); + } + $this->assertTrue($this->withToken('/auth/webauthn2fa', 'GET', [], $login['access_token'])['data']['isRegister']); + } + + public function testStandardBase64ResponseMembersAreAccepted(): void + { + // clients written for earlier versions may send standard base64 with padding + [$login, $key, $credentialId] = $this->loginAndRegister(); + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $payload = $this->assertion($key, $credentialId, $authOptions['data']['challenge']); + foreach (['clientDataJSON', 'authenticatorData', 'signature'] as $member) { + $binary = base64_decode(strtr($payload['response'][$member], '-_', '+/')); + $payload['response'][$member] = base64_encode($binary); + } + + $auth = $this->withToken('/auth/webauthn2fa_auth', 'POST', $payload, $login['access_token']); + $this->assertSame('success', $auth['status'], (string)$this->_response->getBody()); + } + + public function testDomainWithoutWebauthnSettingsIsRefused(): void + { + // the domain comes from the Referer header when there is one + $login = $this->login(); + foreach (['/auth/webauthn2fa', '/auth/webauthn2fa_register_options', '/auth/webauthn2fa_auth_options'] as $url) { + $result = $this->withToken($url, 'GET', [], $login['access_token'], 'https://unconfigured.test/'); + $this->assertRejected($result, 400, 'WebAuthn is not configured for this domain'); + } + } + + public function testFullAccessTokenCannotUseTheWebauthnEndpoints(): void + { + // TwoFactorScope limits the WebAuthn endpoints to `/2fa` tokens; this also proves the + // permission rules above match, so the flow test does not pass through bypassAuth + [$login, $key, $credentialId] = $this->loginAndRegister(); + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge']), + $login['access_token'], + ); + $this->assertSame('success', $auth['status']); + + $this->assertSame('error', $this->withToken('/auth/webauthn2fa', 'GET', [], $auth['data']['access_token'])['status']); + } +} diff --git a/tests/TestCase/Integration/Service/Action/CollectionActionsTest.php b/tests/TestCase/Integration/Service/Action/CollectionActionsTest.php index 80ced5bf..14b7ad91 100644 --- a/tests/TestCase/Integration/Service/Action/CollectionActionsTest.php +++ b/tests/TestCase/Integration/Service/Action/CollectionActionsTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/DescribeEndpointTest.php b/tests/TestCase/Integration/Service/Action/DescribeEndpointTest.php index a7aa3abf..c5c8b321 100644 --- a/tests/TestCase/Integration/Service/Action/DescribeEndpointTest.php +++ b/tests/TestCase/Integration/Service/Action/DescribeEndpointTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/Extension/CorsExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/CorsExtensionTest.php index 2272534d..d1551f71 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CorsExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CorsExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/CorsPreflightTest.php b/tests/TestCase/Integration/Service/Action/Extension/CorsPreflightTest.php index 5fb77fd7..cb8fbdba 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CorsPreflightTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CorsPreflightTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/CrudAuthorizeExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/CrudAuthorizeExtensionTest.php index 340f99e7..698758b7 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CrudAuthorizeExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CrudAuthorizeExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/CrudAutocompleteListExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/CrudAutocompleteListExtensionTest.php index 4976dbf4..e5ae49f1 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CrudAutocompleteListExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CrudAutocompleteListExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/CrudExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/CrudExtensionTest.php index 062d1900..afe9879a 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CrudExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CrudExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/CrudHateoasExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/CrudHateoasExtensionTest.php index 518a8253..7dcc8cb3 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CrudHateoasExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CrudHateoasExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; @@ -177,4 +177,58 @@ public function testIndexNested(): void ]; $this->assertEquals($links, Hash::get($result, 'links')); } + + /** + * A view on a table with HasMany associations also links to the nested index of each association. + */ + public function testViewWithHasManyAddsNestedIndexLinks(): void + { + $this->sendRequest('/authors/1', 'GET', []); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $links = [ + [ + 'name' => 'self', + 'href' => 'http://example.com/api/authors/1', + 'rel' => '/api/authors/1', + 'method' => 'GET', + ], + [ + 'name' => 'authors:edit', + 'href' => 'http://example.com/api/authors/1', + 'rel' => '/api/authors/1', + 'method' => 'PUT', + ], + [ + 'name' => 'authors:delete', + 'href' => 'http://example.com/api/authors/1', + 'rel' => '/api/authors/1', + 'method' => 'DELETE', + ], + [ + 'name' => 'authors:index', + 'href' => 'http://example.com/api/authors', + 'rel' => '/api/authors', + 'method' => 'GET', + ], + [ + 'name' => 'articles:index', + 'href' => 'http://example.com/api/authors/1/articles', + 'rel' => '/api/authors/1/articles', + 'method' => 'GET', + ], + ]; + $this->assertEquals($links, Hash::get($result, 'links')); + } + + /** + * Actions other than view and index get an empty links list. + */ + public function testOtherActionsGetEmptyLinks(): void + { + $this->sendRequest('/articles/1', 'DELETE', []); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame([], Hash::get($result, 'links')); + } } diff --git a/tests/TestCase/Integration/Service/Action/Extension/CrudRelationsExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/CrudRelationsExtensionTest.php index 4c6e5166..5db5d386 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CrudRelationsExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CrudRelationsExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/CursorPaginationExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/CursorPaginationExtensionTest.php index f9b636a1..c9f17058 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/CursorPaginationExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/CursorPaginationExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; @@ -60,6 +60,16 @@ public function testListDefault(): void $this->assertEquals('http://example.com/api/articles?max_id=1', Hash::get($result, 'pagination.links.next')); } + public function testNegativeCountFallsBackToTheDefaultCount(): void + { + // a negative count used to reach the query: an SQL error on mysql and pgsql, no limit on sqlite + $this->sendRequest('/articles', 'GET', ['count' => -1]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals(20, Hash::get($result, 'pagination.count')); + $this->assertCount(15, $result['data']); + } + public function testListWithConfigCount(): void { $this->_loadDefaultExtensions([ diff --git a/tests/TestCase/Integration/Service/Action/Extension/ExtendedSortExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/ExtendedSortExtensionTest.php index d9997e4f..5f39499b 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/ExtendedSortExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/ExtendedSortExtensionTest.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; use Cake\Core\Configure; +use Cake\Log\Log; use Cake\Utility\Hash; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\Test\Settings; @@ -101,6 +102,22 @@ public function testSortByFirstNameDesc(): void $this->assertEquals([4, 9, 14, 10], Hash::extract($result, 'data.{n}.id')); } + public function testDefaultOrder(): void + { + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.ExtendedSort' => ['order' => ['Authors.last_name' => 'desc']], + ]); + $this->sendRequest('/authors', 'GET', ['limit' => 4]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([2, 11, 8, 15], Hash::extract($result, 'data.{n}.id')); + + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => json_encode(['first_name' => 'asc'], JSON_THROW_ON_ERROR)]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([7, 5, 11, 15], Hash::extract($result, 'data.{n}.id')); + } + public function testInvalidJsonIsIgnored(): void { $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => '{not json']); @@ -117,9 +134,9 @@ public function testInvalidEntriesAreIgnored(): void 'Authors.last_name' => 'foo', 'id' => ['desc'], ]; - // only Authors.last_name survives: the SQL expression and the unknown field are - // rejected, its own invalid direction is normalized to asc, and the non-string - // direction of `id` drops that entry + // the SQL expression and the unknown field are rejected; Authors.last_name and id + // survive with their invalid directions normalized to asc, and all last names are + // unique, so id never changes the order $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => json_encode($sort, JSON_THROW_ON_ERROR)]); $result = $this->getJsonResponse(); $this->assertSuccess($result); @@ -138,6 +155,17 @@ public function testSortableFields(): void $this->assertEquals([9, 3, 7, 1], Hash::extract($result, 'data.{n}.id')); } + public function testDefaultOrderIsTieBreaker(): void + { + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.ExtendedSort' => ['order' => ['id' => 'desc']], + ]); + $this->sendRequest('/authors', 'GET', ['limit' => 9, 'sort' => json_encode(['first_name' => 'asc'], JSON_THROW_ON_ERROR)]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([7, 5, 11, 15, 1, 2, 3, 12, 8], Hash::extract($result, 'data.{n}.id')); + } + public function testListAndNumericKeyEntriesAreIgnored(): void { // a numeric key makes CakePHP emit the value verbatim, so list elements and numeric @@ -164,4 +192,63 @@ public function testUnlistedAssociationFieldIsIgnored(): void $this->assertSuccess($result); $this->assertEquals([1, 2], Hash::extract($result, 'data.{n}.id')); } + + public function testNonStringDirectionFallsBackToAsc(): void + { + $sort = json_encode(['last_name' => ['desc']], JSON_THROW_ON_ERROR); + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => $sort]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([9, 3, 7, 1], Hash::extract($result, 'data.{n}.id')); + } + + public function testInvalidJsonIsLogged(): void + { + Log::setConfig('ext_sort_test', ['className' => 'Array', 'scopes' => ['api'], 'levels' => ['debug']]); + try { + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => '{not json']); + $this->assertSuccess($this->getJsonResponse()); + $logs = implode("\n", Log::engine('ext_sort_test')->read()); + } finally { + Log::drop('ext_sort_test'); + } + $this->assertStringContainsString('ignored invalid sort JSON "{not json".', $logs); + $this->assertStringNotContainsString('sortableFields', $logs); + } + + public function testSortByAliasedField(): void + { + $sort = json_encode(['Authors.id' => 'desc'], JSON_THROW_ON_ERROR); + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => $sort]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals(array_reverse(range(12, 15)), Hash::extract($result, 'data.{n}.id')); + } + + public function testOtherTableAliasSortIsIgnored(): void + { + $sort = json_encode(['Articles.id' => 'desc'], JSON_THROW_ON_ERROR); + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => $sort]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals(range(1, 4), Hash::extract($result, 'data.{n}.id')); + } + + public function testIgnoredEntriesAreLoggedOnce(): void + { + Log::setConfig('ext_sort_test', ['className' => 'Array', 'scopes' => ['api'], 'levels' => ['debug']]); + try { + $sort = '{"bogus": "asc", "Articles.id": "desc", "last_name": "asc"}'; + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => $sort]); + $this->assertSuccess($this->getJsonResponse()); + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => '["first_name"]']); + $this->assertSuccess($this->getJsonResponse()); + $logs = Log::engine('ext_sort_test')->read(); + } finally { + Log::drop('ext_sort_test'); + } + $this->assertCount(2, $logs); + $this->assertStringContainsString('ignored sort field "bogus", sort field "Articles.id". Allowed fields', $logs[0]); + $this->assertStringContainsString('ignored list entry "first_name" (use the object form {"field": "asc"})', $logs[1]); + } } diff --git a/tests/TestCase/Integration/Service/Action/Extension/FallbackExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/FallbackExtensionTest.php index db9341ff..e2ce0056 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/FallbackExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/FallbackExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/FilterExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/FilterExtensionTest.php index 50361f50..eba7768c 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/FilterExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/FilterExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/NestedCrudExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/NestedCrudExtensionTest.php index 6ce03cdc..641e3ad1 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/NestedCrudExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/NestedCrudExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; diff --git a/tests/TestCase/Integration/Service/Action/Extension/PaginationExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/PaginationExtensionTest.php index cdf62a81..a22f4c4c 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/PaginationExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/PaginationExtensionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; @@ -99,4 +99,34 @@ public function testCustomLimitAndPage(): void $this->assertEquals($expected, $result['pagination']); $this->assertEquals(range(5, 8), Hash::extract($result, 'data.{n}.id')); } + + public function testNegativeLimitFallsBackToTheDefaultLimit(): void + { + // a negative limit used to reach the query: an SQL error on mysql and pgsql, no limit on sqlite + $this->sendRequest('/articles', 'GET', ['limit' => -1]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(20, $result['pagination']['limit']); + $this->assertCount(15, $result['data']); + } + + public function testLimitAboveTheMaximumIsCapped(): void + { + $this->sendRequest('/articles', 'GET', ['limit' => 1000]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(20, $result['pagination']['limit']); + } + + public function testPageBelowOneFallsBackToTheFirstPage(): void + { + // Query::page() throws for a page below 1, which became an HTTP 500 + foreach ([-2, '0'] as $page) { + $this->sendRequest('/articles', 'GET', ['limit' => 4, 'page' => $page]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(1, $result['pagination']['page'], (string)$page); + $this->assertEquals(range(1, 4), Hash::extract($result, 'data.{n}.id'), (string)$page); + } + } } diff --git a/tests/TestCase/Integration/Service/Action/Extension/SortExtensionTest.php b/tests/TestCase/Integration/Service/Action/Extension/SortExtensionTest.php index 11f0afa3..d68fe88e 100644 --- a/tests/TestCase/Integration/Service/Action/Extension/SortExtensionTest.php +++ b/tests/TestCase/Integration/Service/Action/Extension/SortExtensionTest.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action\Extension; use Cake\Core\Configure; +use Cake\Log\Log; use Cake\Utility\Hash; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\Test\Settings; @@ -108,12 +109,37 @@ public function testSortByAliasedField(): void $this->assertEquals(array_reverse(range(12, 15)), Hash::extract($result, 'data.{n}.id')); } - public function testUnknownSortFieldIsIgnored(): void + public function testDefaultOrder(): void { + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => ['order' => ['Authors.last_name' => 'desc']], + ]); + $this->sendRequest('/authors', 'GET', ['limit' => 4]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([2, 11, 8, 15], Hash::extract($result, 'data.{n}.id')); + } + + public function testRequestSortOverridesDefaultOrder(): void + { + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => ['order' => ['Authors.last_name' => 'desc']], + ]); + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'first_name']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([7, 5, 11, 15], Hash::extract($result, 'data.{n}.id')); + } + + public function testUnknownSortFieldFallsBackToDefaultOrder(): void + { + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => ['order' => ['Authors.last_name' => 'desc']], + ]); $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'unknown_field']); $result = $this->getJsonResponse(); $this->assertSuccess($result); - $this->assertEquals(range(1, 4), Hash::extract($result, 'data.{n}.id')); + $this->assertEquals([2, 11, 8, 15], Hash::extract($result, 'data.{n}.id')); } public function testSqlExpressionSortIsIgnored(): void @@ -132,43 +158,75 @@ public function testInvalidDirectionFallsBackToAsc(): void $this->assertEquals([9, 3, 7, 1], Hash::extract($result, 'data.{n}.id')); } - public function testUppercaseDirection(): void + public function testSortableFields(): void { - $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'id', 'direction' => 'DESC']); + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => ['sortableFields' => ['Authors.last_name']], + ]); + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'last_name']); $result = $this->getJsonResponse(); $this->assertSuccess($result); - $this->assertEquals(array_reverse(range(12, 15)), Hash::extract($result, 'data.{n}.id')); - } + $this->assertEquals([9, 3, 7, 1], Hash::extract($result, 'data.{n}.id')); - public function testArraySortParamIsIgnored(): void - { - // sent as a raw query string, because sendRequest() drops array values from $data - $this->sendRequest('/authors?sort[]=first_name&direction[]=desc', 'GET', ['limit' => 4]); + // first_name is not whitelisted, so it is ignored + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'first_name']); $result = $this->getJsonResponse(); $this->assertSuccess($result); $this->assertEquals(range(1, 4), Hash::extract($result, 'data.{n}.id')); } - public function testOtherTableAliasSortIsIgnored(): void + public function testDefaultOrderIsTieBreaker(): void { - $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'Articles.id', 'direction' => 'desc']); + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => ['order' => ['Authors.id' => 'desc']], + ]); + $this->sendRequest('/authors', 'GET', ['limit' => 9, 'sort' => 'first_name']); $result = $this->getJsonResponse(); $this->assertSuccess($result); - $this->assertEquals(range(1, 4), Hash::extract($result, 'data.{n}.id')); + $this->assertEquals([7, 5, 11, 15, 1, 2, 3, 12, 8], Hash::extract($result, 'data.{n}.id')); } - public function testSortableFields(): void + public function testRequestSortReplacesSameDefaultOrderField(): void { $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ - 'CakeDC/Api.Sort' => ['sortableFields' => ['Authors.last_name']], + 'CakeDC/Api.Sort' => ['order' => ['first_name' => 'desc']], ]); - $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'last_name']); + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'Authors.first_name']); $result = $this->getJsonResponse(); $this->assertSuccess($result); - $this->assertEquals([9, 3, 7, 1], Hash::extract($result, 'data.{n}.id')); + $this->assertEquals([7, 5, 11, 15], Hash::extract($result, 'data.{n}.id')); + } - // first_name is not whitelisted, so it is ignored - $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'first_name']); + public function testSortableOwnFieldIsQualifiedWithJoinedAssociation(): void + { + $this->_loadDefaultExtensions('CakeDC/Api.CrudRelations'); + $this->_addSettingByPath('Service.articles.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => ['sortableFields' => ['id']], + ]); + $this->sendRequest('/articles', 'GET', ['limit' => 4, 'sort' => 'id', 'direction' => 'desc', 'include_relations' => 'authors']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([15, 14, 13, 12], Hash::extract($result, 'data.{n}.id')); + } + + public function testSortableAssociationField(): void + { + $this->_loadDefaultExtensions('CakeDC/Api.CrudRelations'); + $this->_addSettingByPath('Service.articles.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => [ + 'sortableFields' => ['Authors.first_name'], + 'order' => ['Articles.id' => 'asc'], + ], + ]); + $this->sendRequest('/articles', 'GET', ['limit' => 4, 'sort' => 'Authors.first_name', 'include_relations' => 'authors']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([5, 12, 1, 10], Hash::extract($result, 'data.{n}.id')); + } + + public function testOtherTableAliasSortIsIgnored(): void + { + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'Articles.id', 'direction' => 'desc']); $result = $this->getJsonResponse(); $this->assertSuccess($result); $this->assertEquals(range(1, 4), Hash::extract($result, 'data.{n}.id')); @@ -185,29 +243,61 @@ public function testSortableFieldsMatchAliasedRequestField(): void $this->assertEquals([9, 3, 7, 1], Hash::extract($result, 'data.{n}.id')); } - public function testSortableOwnFieldIsQualifiedWithJoinedAssociation(): void + public function testDefaultOrderWithNumericKey(): void { - $this->_loadDefaultExtensions('CakeDC/Api.CrudRelations'); - $this->_addSettingByPath('Service.articles.Action.Index.Extension', [ - 'CakeDC/Api.Sort' => ['sortableFields' => ['id']], + $this->_addSettingByPath('Service.authors.Action.Index.Extension', [ + 'CakeDC/Api.Sort' => ['order' => ['Authors.id DESC']], ]); - $this->sendRequest('/articles', 'GET', ['limit' => 4, 'sort' => 'id', 'direction' => 'desc', 'include_relations' => 'authors']); + $this->sendRequest('/authors', 'GET', ['limit' => 4]); $result = $this->getJsonResponse(); $this->assertSuccess($result); - $this->assertEquals([15, 14, 13, 12], Hash::extract($result, 'data.{n}.id')); + $this->assertEquals(array_reverse(range(12, 15)), Hash::extract($result, 'data.{n}.id')); } - public function testSortableAssociationField(): void + public function testUppercaseDirection(): void { + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'id', 'direction' => 'DESC']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals(array_reverse(range(12, 15)), Hash::extract($result, 'data.{n}.id')); + } + + public function testArraySortParamIsIgnored(): void + { + // sent as a raw query string, because sendRequest() drops array values from $data + $this->sendRequest('/authors?sort[]=first_name&direction[]=desc', 'GET', ['limit' => 4]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals(range(1, 4), Hash::extract($result, 'data.{n}.id')); + } + + public function testUnqualifiedDefaultOrderWithJoinedAssociation(): void + { + // `id` exists on both articles and authors; the default order must be qualified $this->_loadDefaultExtensions('CakeDC/Api.CrudRelations'); $this->_addSettingByPath('Service.articles.Action.Index.Extension', [ - 'CakeDC/Api.Sort' => ['sortableFields' => ['Authors.first_name']], + 'CakeDC/Api.Sort' => ['order' => ['id' => 'desc']], ]); - // limited to 2: only Alex (article 5) and Alien (article 12) are unambiguous - // without a tie-breaker, the next four articles all belong to "Electra" - $this->sendRequest('/articles', 'GET', ['limit' => 2, 'sort' => 'Authors.first_name', 'include_relations' => 'authors']); + $this->sendRequest('/articles', 'GET', ['limit' => 2, 'include_relations' => 'authors']); $result = $this->getJsonResponse(); $this->assertSuccess($result); - $this->assertEquals([5, 12], Hash::extract($result, 'data.{n}.id')); + $this->assertEquals([15, 14], Hash::extract($result, 'data.{n}.id')); + } + + public function testIgnoredSortFieldIsLogged(): void + { + Log::setConfig('sort_test', ['className' => 'Array', 'scopes' => ['api'], 'levels' => ['debug']]); + try { + $this->sendRequest('/authors', 'GET', ['limit' => 4, 'sort' => 'bogus']); + $this->assertSuccess($this->getJsonResponse()); + $this->sendRequest('/authors', 'GET', ['limit' => 4]); + $this->assertSuccess($this->getJsonResponse()); + $logs = Log::engine('sort_test')->read(); + } finally { + Log::drop('sort_test'); + } + // one line for the ignored field, nothing for the request without a sort + $this->assertCount(1, $logs); + $this->assertStringContainsString('ignored sort field "bogus". Allowed fields can be listed in sortableFields.', $logs[0]); } } diff --git a/tests/TestCase/Integration/Service/Action/HttpErrorBodiesTest.php b/tests/TestCase/Integration/Service/Action/HttpErrorBodiesTest.php index 85440e15..3965c445 100644 --- a/tests/TestCase/Integration/Service/Action/HttpErrorBodiesTest.php +++ b/tests/TestCase/Integration/Service/Action/HttpErrorBodiesTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/PostsCrudTest.php b/tests/TestCase/Integration/Service/Action/PostsCrudTest.php index 42e539b1..d0c012f2 100644 --- a/tests/TestCase/Integration/Service/Action/PostsCrudTest.php +++ b/tests/TestCase/Integration/Service/Action/PostsCrudTest.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; use Cake\Core\Configure; +use Cake\Utility\Hash; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\Test\Settings; use CakeDC\Api\TestSuite\IntegrationTestCase; @@ -62,7 +63,7 @@ public function testIndex(): void $result = $this->getJsonResponse(); $this->assertSuccess($result); $this->assertCount(4, $result['data']); - $this->assertSame([1, 2, 3, 4], \Cake\Utility\Hash::extract($result['data'], '{n}.id')); + $this->assertSame([1, 2, 3, 4], Hash::extract($result['data'], '{n}.id')); } public function testView(): void diff --git a/tests/TestCase/Integration/Service/Action/PostsExtensionsTest.php b/tests/TestCase/Integration/Service/Action/PostsExtensionsTest.php index a7b86846..636c2212 100644 --- a/tests/TestCase/Integration/Service/Action/PostsExtensionsTest.php +++ b/tests/TestCase/Integration/Service/Action/PostsExtensionsTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/PostsNestedTagsTest.php b/tests/TestCase/Integration/Service/Action/PostsNestedTagsTest.php index 9fe125d1..51b83f88 100644 --- a/tests/TestCase/Integration/Service/Action/PostsNestedTagsTest.php +++ b/tests/TestCase/Integration/Service/Action/PostsNestedTagsTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/PostsRouteAliasTest.php b/tests/TestCase/Integration/Service/Action/PostsRouteAliasTest.php index 8da7ae7c..f0902c48 100644 --- a/tests/TestCase/Integration/Service/Action/PostsRouteAliasTest.php +++ b/tests/TestCase/Integration/Service/Action/PostsRouteAliasTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Action/RecaptchaValidateTest.php b/tests/TestCase/Integration/Service/Action/RecaptchaValidateTest.php index 170b0a6a..4cb5eeef 100644 --- a/tests/TestCase/Integration/Service/Action/RecaptchaValidateTest.php +++ b/tests/TestCase/Integration/Service/Action/RecaptchaValidateTest.php @@ -14,57 +14,131 @@ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; use Cake\Core\Configure; -use CakeDC\Api\Test\ConfigTrait; +use CakeDC\Api\Service\RecaptchaService; +use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\TestSuite\IntegrationTestCase; /** - * The reCaptcha validate endpoint. + * `recaptcha/validate` is served by the plugin's RecaptchaService (the test app has none) and + * answers whether the posted `g-recaptcha-response` passes the reCaptcha check configured for + * the request domain. No test here configures a secret together with a token, so Google is + * never contacted. */ class RecaptchaValidateTest extends IntegrationTestCase { - use ConfigTrait; - - protected function setUp(): void - { - parent::setUp(); - $this->_authAccess(); - Configure::write('App.fullBaseUrl', 'http://localhost'); - } + protected array $fixtures = []; protected function tearDown(): void { - Configure::delete('Test.Api.Config'); parent::tearDown(); + Configure::delete('Test.Api.Config'); } /** - * @param array $reCaptcha `Api.reCaptcha` settings. + * Configure `Api.reCaptcha` for the integration request host (`localhost`). + * + * @param array $settings reCaptcha settings for the domain. + * @param array $global Settings for every domain, such as `disabled`. * @return void */ - protected function configureReCaptcha(array $reCaptcha): void + protected function configureReCaptcha(array $settings, array $global = []): void { $config = include dirname(__DIR__, 4) . DS . 'Config' . DS . 'api.php'; - $config['Api']['reCaptcha'] = $reCaptcha; + $config['Api']['reCaptcha'] = $global + ['localhost' => $settings]; Configure::write('Test.Api.Config', $config); } - public function testGlobalDisabledPasses(): void + public function testValidateIsServedByPluginRecaptchaService(): void + { + $this->configureReCaptcha([], ['disabled' => true]); + $this->sendRequest('/recaptcha/validate', 'POST', []); + $this->assertSuccess($this->getJsonResponse()); + + $service = ServiceRegistry::getServiceLocator()->get('recaptcha'); + $this->assertInstanceOf(RecaptchaService::class, $service); + } + + public function testDisabledReturnsTrue(): void + { + $this->configureReCaptcha(['secret' => 'never-used'], ['disabled' => true]); + $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => 'token']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertTrue($result['data']); + } + + public function testDisabledForTheDomainIsIgnored(): void { $this->configureReCaptcha(['disabled' => true]); $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => 'token']); $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertFalse($result['data']); + } + public function testRefererCannotPickADisabledDomain(): void + { + // the domain comes from the Referer header when there is one + $config = include dirname(__DIR__, 4) . DS . 'Config' . DS . 'api.php'; + $config['Api']['reCaptcha'] = ['localhost' => ['secret' => 'secret'], 'dev$test' => ['disabled' => true]]; + Configure::write('Test.Api.Config', $config); + $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => ''], null, ['Referer' => 'https://dev.test/']); + $result = $this->getJsonResponse(); $this->assertSuccess($result); - $this->assertTrue($result['data']); + $this->assertFalse($result['data']); } - public function testDomainDisabledWithoutSecretFails(): void + public function testNoSecretReturnsFalse(): void { - $this->configureReCaptcha(['localhost' => ['disabled' => true]]); + $this->configureReCaptcha(['disabled' => false]); $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => 'token']); $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertFalse($result['data']); + } + + public function testNoReCaptchaConfigReturnsFalse(): void + { + $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => 'token']); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertFalse($result['data']); + } + + public function testMissingTokenReturnsFalse(): void + { + $this->configureReCaptcha(['secret' => 'secret']); + $this->sendRequest('/recaptcha/validate', 'POST', []); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertFalse($result['data']); + } + public function testEmptyTokenReturnsFalse(): void + { + $this->configureReCaptcha(['secret' => 'secret']); + $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => '']); + $result = $this->getJsonResponse(); $this->assertSuccess($result); $this->assertFalse($result['data']); } + + public function testNonStringTokenReturnsFalse(): void + { + $this->configureReCaptcha(['secret' => 'secret']); + $this->sendRequest('/recaptcha/validate', 'POST', ['g-recaptcha-response' => ['token']]); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertFalse($result['data']); + } + + public function testGetIsRefused(): void + { + $this->configureReCaptcha([], ['disabled' => true]); + $this->sendRequest('/recaptcha/validate', 'GET', []); + $result = $this->getJsonResponse(); + // validate is mapped for POST only: GET finds no route; JSend errors keep HTTP 200 + $this->assertError($result, 404); + $this->assertErrorMessage($result, 'A route matching `/recaptcha/validate` could not be found.'); + } } diff --git a/tests/TestCase/Integration/Service/Action/TransformerActionTest.php b/tests/TestCase/Integration/Service/Action/TransformerActionTest.php index 2f19d4c2..38cb1f2d 100644 --- a/tests/TestCase/Integration/Service/Action/TransformerActionTest.php +++ b/tests/TestCase/Integration/Service/Action/TransformerActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service\Action; diff --git a/tests/TestCase/Integration/Service/Extension/CollectionExtensionTest.php b/tests/TestCase/Integration/Service/Extension/CollectionExtensionTest.php new file mode 100644 index 00000000..7604d564 --- /dev/null +++ b/tests/TestCase/Integration/Service/Extension/CollectionExtensionTest.php @@ -0,0 +1,195 @@ +_tokenAccess(); + $this->getDefaultUser(Settings::USER1); + $this->_addSettingByPath('Service.articles.options.Extension', ['CakeDC/Api.Collection']); + } + + /** + * Sends a bulk delete request. + * + * FormParser reads DELETE parameters from the query string, not the body, and every + * query parameter is taken as an item, so the request is sent without the auth token + * (the test permissions bypass auth). + * + * @param array $items Items to delete. + * @return void + */ + protected function sendBulkDelete(array $items): void + { + $this->defaultUserId = null; + $this->sendRequest('/articles/bulk?' . http_build_query($items), 'DELETE'); + } + + public function testBeforeDispatchMapsBulkActions(): void + { + Configure::load('api'); + $service = new FallbackService([ + 'service' => 'articles', + 'request' => new ServerRequest(['environment' => ['REQUEST_METHOD' => 'GET']]), + 'Extension' => ['CakeDC/Api.Collection'], + ]); + $this->assertArrayNotHasKey('bulkAdd', $service->getActionsClassMap()); + + $service->triggerBeforeDispatch(); + + $map = $service->getActionsClassMap(); + $this->assertSame(AddEditAction::class, $map['bulkAdd']); + $this->assertSame(AddEditAction::class, $map['bulkEdit']); + $this->assertSame(DeleteAction::class, $map['bulkDelete']); + $this->assertSame(DummyAction::class, $map['bulkAdd_cors']); + $this->assertSame(DummyAction::class, $map['bulkEdit_cors']); + $this->assertSame(DummyAction::class, $map['bulkDelete_cors']); + } + + public function testBulkAdd(): void + { + $articles = TableRegistry::getTableLocator()->get('Articles'); + $before = $articles->find()->count(); + + $this->sendRequest('/articles/bulk', 'POST', [ + ['title' => 'Bulk 1'], + ['title' => 'Bulk 2'], + ]); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(['Bulk 1', 'Bulk 2'], Hash::extract($result['data'], '{n}.title')); + $this->assertCount(2, Hash::extract($result['data'], '{n}.id')); + $this->assertSame($before + 2, $articles->find()->count()); + } + + public function testBulkAddValidationError(): void + { + $articles = TableRegistry::getTableLocator()->get('Articles'); + $before = $articles->find()->count(); + + $this->sendRequest('/articles/bulk', 'POST', [ + ['title' => 'Bulk 1'], + ['body' => 'no title'], + ]); + + $result = $this->getJsonResponse(); + $this->assertError($result, 422); + $this->assertArrayHasKey('title', $result['data'][1]); + $this->assertSame($before, $articles->find()->count()); + } + + public function testBulkAddRejectsSingleItem(): void + { + $this->sendRequest('/articles/bulk', 'POST', ['title' => 'Not a list']); + + $result = $this->getJsonResponse(); + $this->assertError($result, 422); + $this->assertErrorMessage($result, 'Validation failed, POST data is not an array of items'); + } + + public function testBulkEdit(): void + { + $articles = TableRegistry::getTableLocator()->get('Articles'); + $before = $articles->find()->count(); + + $this->sendRequest('/articles/bulk', 'PUT', [ + ['id' => 1, 'title' => 'Edited 1'], + ['id' => 2, 'title' => 'Edited 2'], + ]); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame('Edited 1', $articles->get(1)->title); + $this->assertSame('Edited 2', $articles->get(2)->title); + $this->assertSame($before, $articles->find()->count()); + } + + public function testBulkDelete(): void + { + $articles = TableRegistry::getTableLocator()->get('Articles'); + $before = $articles->find()->count(); + + $this->sendBulkDelete([['id' => 1], ['id' => 2]]); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertEquals([1, 2], $result['data']); + $this->assertSame($before - 2, $articles->find()->count()); + $this->assertFalse($articles->exists(['id' => 1])); + $this->assertFalse($articles->exists(['id' => 2])); + } + + public function testBulkDeleteMissingId(): void + { + $this->sendBulkDelete([['id' => 1], ['title' => 'no id']]); + + $result = $this->getJsonResponse(); + $this->assertError($result, 422); + $this->assertSame(['id' => ['_empty' => 'Missing id']], $result['data'][1]); + $this->assertTrue(TableRegistry::getTableLocator()->get('Articles')->exists(['id' => 1])); + } + + public function testBulkOptionsRoute(): void + { + $this->sendRequest('/articles/bulk', 'OPTIONS'); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertNull($result['data']); + } + + public function testBulkRouteHasNoGet(): void + { + $this->sendRequest('/articles/bulk', 'GET'); + + $this->assertError($this->getJsonResponse(), 404); + } + + public function testCrudRoutesStillWork(): void + { + $this->sendRequest('/articles/1', 'GET'); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(1, $result['data']['id']); + } + + public function testBulkRoutesNeedTheExtension(): void + { + Configure::delete('Test.Api.Service.articles'); + + $this->sendRequest('/articles/bulk', 'POST', [['title' => 'Bulk 1']]); + + $this->assertError($this->getJsonResponse(), 404); + } +} diff --git a/tests/TestCase/Integration/Service/Extension/LogExtensionTest.php b/tests/TestCase/Integration/Service/Extension/LogExtensionTest.php new file mode 100644 index 00000000..a42d019e --- /dev/null +++ b/tests/TestCase/Integration/Service/Extension/LogExtensionTest.php @@ -0,0 +1,135 @@ +_tokenAccess(); + $this->getDefaultUser(Settings::USER1); + + // swap the plugin's File logger for an Array one under the same name, so the + // plugin bootstrap run by each request does not register the File logger again + $this->apiLogConfig = Log::getConfig('api'); + Log::drop('api'); + Log::setConfig('api', [ + 'className' => 'Array', + 'scopes' => ['api'], + 'levels' => ['info'], + ]); + } + + protected function tearDown(): void + { + Log::drop('api'); + if ($this->apiLogConfig !== null) { + Log::setConfig('api', $this->apiLogConfig); + } + parent::tearDown(); + } + + /** + * Enables the Log service extension for the articles service. + * + * @return void + */ + protected function enableLog(): void + { + $this->_addSettingByPath('Service.articles.options.Extension', ['CakeDC/Api.Log']); + } + + /** + * Returns the entries written to the test logger. + * + * @return array + */ + protected function logEntries(): array + { + $engine = Log::engine('api'); + $this->assertInstanceOf(ArrayLog::class, $engine); + + return $engine->read(); + } + + public function testLogsSuccessfulRequest(): void + { + $this->enableLog(); + $this->sendRequest('/articles/1', 'GET'); + $this->assertSuccess($this->getJsonResponse()); + + $entries = $this->logEntries(); + $this->assertCount(1, $entries); + $entry = $entries[0]; + $this->assertStringStartsWith('info: Array', $entry); + $this->assertStringContainsString('[url] => /articles/1', $entry); + $this->assertStringContainsString('[method] => GET', $entry); + $this->assertMatchesRegularExpression('/\[duration\] => \d+ms/', $entry); + $this->assertStringContainsString('[token] => ***', $entry); + $this->assertStringNotContainsString('yyy', $entry); + $this->assertStringContainsString('"code": 200', $entry); + $this->assertStringContainsString('"title": "First Article"', $entry); + } + + public function testLogsPostInput(): void + { + $this->enableLog(); + $this->sendRequest('/articles', 'POST', ['title' => 'Logged title']); + $this->assertSuccess($this->getJsonResponse()); + + $entries = $this->logEntries(); + $this->assertCount(1, $entries); + $this->assertStringContainsString('[url] => /articles', $entries[0]); + $this->assertStringContainsString('[method] => POST', $entries[0]); + $this->assertStringContainsString('[title] => Logged title', $entries[0]); + } + + public function testLogsActionError(): void + { + $this->enableLog(); + $this->sendRequest('/articles/9999', 'GET'); + $this->assertError($this->getJsonResponse(), 404); + + $entries = $this->logEntries(); + $this->assertCount(1, $entries); + $this->assertStringContainsString('"code": 404', $entries[0]); + $this->assertStringContainsString('"exception": "Record not found in table `articles`.', $entries[0]); + } + + public function testNothingLoggedWithoutExtension(): void + { + $this->sendRequest('/articles/1', 'GET'); + $this->assertSuccess($this->getJsonResponse()); + + $this->assertSame([], $this->logEntries()); + } +} diff --git a/tests/TestCase/Integration/Service/Extension/OptionsHandlerExtensionTest.php b/tests/TestCase/Integration/Service/Extension/OptionsHandlerExtensionTest.php new file mode 100644 index 00000000..541f64a9 --- /dev/null +++ b/tests/TestCase/Integration/Service/Extension/OptionsHandlerExtensionTest.php @@ -0,0 +1,177 @@ +_tokenAccess(); + $this->getDefaultUser(Settings::USER1); + } + + /** + * Enables the OptionsHandler service extension for the articles service. + * + * @return void + */ + protected function enableOptionsHandler(): void + { + $this->_addSettingByPath('Service.articles.options.Extension', ['CakeDC/Api.OptionsHandler']); + } + + /** + * Only the auth service is allowed, so any articles request is forbidden. + * + * @return void + */ + protected function forbidArticles(): void + { + Configure::write('Test.Api.Permissions', [ + ['role' => '*', 'service' => 'auth', 'action' => '*', 'bypassAuth' => true], + ]); + } + + /** + * Asserts the response carries the default CorsExtension headers. + * + * @return void + */ + protected function assertCorsHeaders(): void + { + $this->assertHeader('Access-Control-Allow-Origin', '*'); + $this->assertHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH'); + $this->assertHeader( + 'Access-Control-Allow-Headers', + 'X-CSRF-Token, Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, ' + . 'Authorization, X-Requested-With', + ); + $this->assertHeader('Access-Control-Allow-Credentials', 'true'); + $this->assertHeader('Access-Control-Max-Age', '300'); + } + + public function testPreflightIsAnsweredWithCorsHeaders(): void + { + $this->enableOptionsHandler(); + $this->_request['headers']['Origin'] = 'http://foobar.com'; + $this->_request['headers']['Access-Control-Request-Method'] = 'POST'; + $this->sendRequest('/articles', 'OPTIONS', []); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + // the describe action mapped to OPTIONS /articles is not executed + $this->assertNull($result['data']); + $this->assertCorsHeaders(); + } + + public function testOptionsOnRecordRouteIsAnsweredWithoutAction(): void + { + $this->enableOptionsHandler(); + $this->_request['headers']['Origin'] = 'http://foobar.com'; + $this->sendRequest('/articles/1', 'OPTIONS', []); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertNull($result['data']); + $this->assertCorsHeaders(); + } + + public function testOptionsWithoutOriginHasNoCorsHeaders(): void + { + $this->enableOptionsHandler(); + $this->sendRequest('/articles', 'OPTIONS', []); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertNull($result['data']); + $this->assertFalse($this->_response->hasHeader('Access-Control-Allow-Origin')); + } + + public function testWithoutExtensionOptionsRunsDescribeAction(): void + { + $this->_request['headers']['Origin'] = 'http://foobar.com'; + $this->sendRequest('/articles', 'OPTIONS', []); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertArrayHasKey('schema', $result['data']); + $this->assertFalse($this->_response->hasHeader('Access-Control-Allow-Origin')); + } + + public function testNonOptionsRequestIsDispatchedToAction(): void + { + $this->enableOptionsHandler(); + $this->_request['headers']['Origin'] = 'http://foobar.com'; + $this->sendRequest('/articles/1', 'GET', []); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(1, $result['data']['id']); + $this->assertFalse($this->_response->hasHeader('Access-Control-Allow-Origin')); + } + + public function testPreflightSkipsAuthorization(): void + { + $this->enableOptionsHandler(); + $this->forbidArticles(); + $this->_request['headers']['Origin'] = 'http://foobar.com'; + $this->sendRequest('/articles', 'OPTIONS', []); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertNull($result['data']); + $this->assertCorsHeaders(); + } + + public function testForbiddenResponseGetsForcedCorsHeaders(): void + { + $this->enableOptionsHandler(); + $this->forbidArticles(); + $this->_request['headers']['Origin'] = 'http://foobar.com'; + $this->sendRequest('/articles', 'GET', []); + + $result = $this->getJsonResponse(); + $this->assertError($result, 403); + $this->assertNull($result['data']); + $this->assertCorsHeaders(); + } + + public function testForbiddenResponseWithoutExtensionHasNoCorsHeaders(): void + { + $this->forbidArticles(); + $this->_request['headers']['Origin'] = 'http://foobar.com'; + $this->sendRequest('/articles', 'GET', []); + + $result = $this->getJsonResponse(); + $this->assertError($result, 403); + $this->assertFalse($this->_response->hasHeader('Access-Control-Allow-Origin')); + } +} diff --git a/tests/TestCase/Integration/Service/FallbackServiceTest.php b/tests/TestCase/Integration/Service/FallbackServiceTest.php index ef7fcfb8..a0a37c41 100644 --- a/tests/TestCase/Integration/Service/FallbackServiceTest.php +++ b/tests/TestCase/Integration/Service/FallbackServiceTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Integration\Service; diff --git a/tests/TestCase/Integration/Service/RendererTest.php b/tests/TestCase/Integration/Service/RendererTest.php new file mode 100644 index 00000000..c474e934 --- /dev/null +++ b/tests/TestCase/Integration/Service/RendererTest.php @@ -0,0 +1,304 @@ +.options.rendererClass`) or the global `Api.renderer`. + */ +class RendererTest extends IntegrationTestCase +{ + use ConfigTrait; + + protected array $fixtures = [ + 'plugin.CakeDC/Api.Users', + 'plugin.CakeDC/Api.Articles', + ]; + + protected function setUp(): void + { + parent::setUp(); + Configure::write('App.fullBaseUrl', 'http://example.com'); + $this->_tokenAccess(); + $this->getDefaultUser(Settings::USER1); + } + + protected function tearDown(): void + { + Configure::delete('Test.Api'); + parent::tearDown(); + } + + /** + * Selects the renderer of one service through its `rendererClass` option. + * + * @param string $service Service name. + * @param string $renderer Renderer name. + * @return void + */ + protected function useServiceRenderer(string $service, string $renderer): void + { + $this->_addSettingByPath('Service.' . $service . '.options.rendererClass', $renderer); + } + + /** + * Replaces the global `Api.renderer` of the test app config. + * + * @param string $renderer Renderer name. + * @return void + */ + protected function useGlobalRenderer(string $renderer): void + { + Configure::delete('Test.Api.Config'); + $config = require CONFIG . 'api.php'; + Configure::write('Test.Api.Config', Hash::insert($config, 'Api.renderer', $renderer)); + } + + public function testJsonIndex(): void + { + $this->useServiceRenderer('articles', 'CakeDC/Api.Json'); + $this->sendRequest('/articles', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('application/json'); + $result = $this->getJsonResponse(); + $this->assertTrue(array_is_list($result)); + $this->assertCount(15, $result); + $this->assertSame(range(1, 15), Hash::extract($result, '{n}.id')); + $this->assertArrayNotHasKey('status', $result); + } + + public function testJsonView(): void + { + $this->useServiceRenderer('articles', 'CakeDC/Api.Json'); + $this->sendRequest('/articles/1', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('application/json'); + $this->assertSame([ + 'id' => 1, + 'author_id' => 1, + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + ], $this->getJsonResponse()); + } + + public function testJsonMissingRecord(): void + { + $this->useServiceRenderer('articles', 'CakeDC/Api.Json'); + $this->sendRequest('/articles/999', 'GET'); + + $this->assertResponseCode(404); + $this->assertContentType('application/json'); + $result = $this->getJsonResponse(); + $this->assertSame(['error'], array_keys($result)); + $this->assertSame(404, $result['error']['code']); + $this->assertStringStartsWith('Record not found in table `articles`', $result['error']['message']); + // debug is on in the test app, so the trace is included + $this->assertIsArray($result['error']['trace']); + } + + public function testJsonDatesAndGlobalRenderer(): void + { + $this->useGlobalRenderer('CakeDC/Api.Json'); + $this->sendRequest('/files/stamp', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('application/json'); + $this->assertSame([ + 'title' => 'Stamp', + 'created' => '2026-01-02T03:04:05+00:00', + 'day' => '2026-01-02', + ], $this->getJsonResponse()); + } + + public function testServiceRendererOverridesGlobalRenderer(): void + { + $this->useGlobalRenderer('CakeDC/Api.Json'); + $this->useServiceRenderer('files', 'CakeDC/Api.Raw'); + $this->sendRequest('/files/text', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('text/plain'); + $this->assertSame(FilesTextAction::TEXT, (string)$this->_response->getBody()); + + // other services keep the global renderer + $this->sendRequest('/articles/1', 'GET'); + $this->assertContentType('application/json'); + $this->assertSame('First Article', $this->getJsonResponse()['title']); + } + + public function testXmlIndex(): void + { + $this->useServiceRenderer('articles', 'CakeDC/Api.Xml'); + $this->sendRequest('/articles', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('application/xml'); + $xml = Xml::build((string)$this->_response->getBody()); + $this->assertSame('data', $xml->getName()); + $rows = $xml->xpath('/data/array/row'); + $this->assertCount(15, $rows); + $this->assertSame('0', (string)$rows[0]['key']); + $this->assertSame( + ['First Article'], + array_map(strval(...), $rows[0]->xpath('object/property[@name="title"]')), + ); + } + + public function testXmlView(): void + { + $this->useServiceRenderer('articles', 'CakeDC/Api.Xml'); + $this->sendRequest('/articles/1', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('application/xml'); + $xml = Xml::build((string)$this->_response->getBody()); + $properties = []; + foreach ($xml->xpath('/data/object/property') as $property) { + $properties[(string)$property['name']] = (string)$property; + } + $this->assertSame([ + 'id' => '1', + 'author_id' => '1', + 'title' => 'First Article', + 'body' => 'First Article Body', + 'published' => 'Y', + ], $properties); + } + + public function testXmlDates(): void + { + $this->useServiceRenderer('files', 'CakeDC/Api.Xml'); + $this->sendRequest('/files/stamp', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('application/xml'); + $xml = Xml::build((string)$this->_response->getBody()); + $values = []; + foreach ($xml->xpath('/data/array/row') as $row) { + $values[(string)$row['key']] = (string)$row; + } + // DateTime is a Chronos: ISO 8601; Date is a ChronosDate: Y-m-d + $this->assertSame([ + 'title' => 'Stamp', + 'created' => '2026-01-02T03:04:05+00:00', + 'day' => '2026-01-02', + ], $values); + } + + public function testXmlMissingRecord(): void + { + $this->useServiceRenderer('articles', 'CakeDC/Api.Xml'); + $this->sendRequest('/articles/999', 'GET'); + + $this->assertResponseCode(404); + $this->assertContentType('application/xml'); + $xml = Xml::build((string)$this->_response->getBody()); + $this->assertSame('error', $xml->getName()); + $this->assertSame('404', (string)$xml->code); + $this->assertStringStartsWith('Record not found in table `articles`', (string)$xml->message); + } + + public function testRawString(): void + { + $this->useServiceRenderer('files', 'CakeDC/Api.Raw'); + $this->sendRequest('/files/text', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('text/plain'); + $this->assertSame(FilesTextAction::TEXT, (string)$this->_response->getBody()); + } + + public function testRawMissingRecord(): void + { + $this->useServiceRenderer('articles', 'CakeDC/Api.Raw'); + $this->sendRequest('/articles/999', 'GET'); + + $this->assertResponseCode(404); + $this->assertContentType('text/plain'); + $this->assertResponseContains('Record not found in table `articles`'); + } + + public function testFileDownload(): void + { + $this->useServiceRenderer('files', 'CakeDC/Api.File'); + $this->sendRequest('/files/download', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('text/csv'); + $this->assertSame( + file_get_contents(ROOT . DS . 'tests' . DS . 'Fixture' . DS . 'files' . DS . 'report.csv'), + (string)$this->_response->getBody(), + ); + } + + public function testFileMissing(): void + { + $this->useServiceRenderer('files', 'CakeDC/Api.File'); + Configure::write('debug', false); + $this->sendRequest('/files/download', 'GET', ['file' => 'missing.csv']); + + // with debug off the message does not name the path + $this->assertResponseCode(404); + $this->assertContentType('application/json'); + $this->assertSame([ + 'error' => [ + 'code' => 404, + 'message' => 'The requested file was not found', + ], + ], $this->getJsonResponse()); + } + + public function testFlysystemDownload(): void + { + $this->useServiceRenderer('files', 'CakeDC/Api.Flysystem'); + $this->sendRequest('/files/stored', 'GET'); + + $this->assertResponseCode(200); + $this->assertContentType('text/csv'); + $this->assertSame(FilesStoredAction::CONTENTS, (string)$this->_response->getBody()); + $this->assertHeader('Content-Disposition', 'attachment; filename="report.csv"'); + } + + public function testFlysystemMissingPath(): void + { + $this->useServiceRenderer('files', 'CakeDC/Api.Flysystem'); + $this->sendRequest('/files/stored', 'GET', ['path' => 'docs/missing.csv']); + + $this->assertResponseCode(404); + $this->assertSame('', (string)$this->_response->getBody()); + } + + public function testFlysystemPathTraversal(): void + { + $this->useServiceRenderer('files', 'CakeDC/Api.Flysystem'); + $this->sendRequest('/files/stored', 'GET', ['path' => '../../etc/passwd']); + + $this->assertResponseCode(404); + $this->assertSame('', (string)$this->_response->getBody()); + } +} diff --git a/tests/TestCase/Integration/Service/VersioningTest.php b/tests/TestCase/Integration/Service/VersioningTest.php new file mode 100644 index 00000000..7e46c47a --- /dev/null +++ b/tests/TestCase/Integration/Service/VersioningTest.php @@ -0,0 +1,263 @@ +_tokenAccess(); + $this->getDefaultUser(Settings::USER1); + } + + protected function tearDown(): void + { + Configure::delete('Test.Api'); + parent::tearDown(); + } + + /** + * Writes `Api.*` settings over the test app config (`tests/Config/api.php`). + * + * The config file resets `Api` on every load, so changes go through `Test.Api.Config`. + * + * @param array $settings Settings keyed by path below `Api`. + * @return void + */ + protected function apiConfig(array $settings): void + { + Configure::delete('Test.Api.Config'); + $config = require CONFIG . 'api.php'; + foreach ($settings as $path => $value) { + $config = Hash::insert($config, 'Api.' . $path, $value); + } + Configure::write('Test.Api.Config', $config); + } + + public function testVersionedUrlIsServedByVersionedServiceClass(): void + { + $this->apiConfig(['useVersioning' => true]); + $this->sendRequest('/v1/articles/about', 'GET'); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame([ + 'service' => V1ArticlesService::class, + 'version' => 'v1', + ], $result['data']); + } + + public function testVersionedUrlServesInheritedCrudAndCustomRoutes(): void + { + $this->apiConfig(['useVersioning' => true]); + + $this->sendRequest('/v1/articles', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(range(1, 15), Hash::extract($result['data'], '{n}.id')); + + $this->sendRequest('/v1/articles/1', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame('First Article', $result['data']['title']); + + // `featured` is declared by the unversioned parent class + $this->sendRequest('/v1/articles/featured', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame(['id', 'title', 'published'], array_keys($result['data'][0])); + } + + public function testVersionRouteIsNotExposedWithoutVersioning(): void + { + $this->sendRequest('/v1/articles/about', 'GET'); + + // without versioning `v1` is taken as the service name (a table that does not exist) + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + $this->assertErrorMessage($result, 'A route matching `/v1/articles/about` could not be found.'); + } + + public function testUnknownVersionIsServedByTheUnversionedService(): void + { + $this->apiConfig(['useVersioning' => true]); + + // there is no Service/v2 namespace: the app's unversioned ArticlesService serves it, + // not the generic FallbackService, so its own routes stay available + $this->sendRequest('/v2/articles', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertCount(15, $result['data']); + + $this->sendRequest('/v2/articles/featured', 'GET'); + $this->assertSuccess($this->getJsonResponse()); + } + + public function testVersionSegmentMustBePrefixAndDigits(): void + { + $this->apiConfig(['useVersioning' => true]); + $this->sendRequest('/v1x/articles', 'GET'); + + // `v1x` is not a version: it is taken as the service name + $result = $this->getJsonResponse(); + $this->assertError($result, 404); + $this->assertErrorMessage($result, 'A route matching `/v1x/articles` could not be found.'); + } + + public function testUnversionedUrlUsesDefaultVersionClass(): void + { + $this->apiConfig(['useVersioning' => true, 'defaultVersion' => '1']); + $this->sendRequest('/articles/about', 'GET'); + + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + // a URL without a version is served as the default version + $this->assertSame([ + 'service' => V1ArticlesService::class, + 'version' => 'v1', + ], $result['data']); + } + + public function testUnversionedUrlWithoutDefaultVersion(): void + { + $this->apiConfig(['useVersioning' => true]); + + // without a default version the app's unversioned ArticlesService serves the URL + $this->sendRequest('/articles', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertCount(15, $result['data']); + + $this->sendRequest('/articles/featured', 'GET'); + $this->assertSuccess($this->getJsonResponse()); + } + + public function testVersionedServiceOptionsOverride(): void + { + $this->apiConfig(['useVersioning' => true, 'defaultVersion' => '1']); + $this->_addSettingByPath('Service.v1.articles.options.rendererClass', 'CakeDC/Api.Json'); + + $this->sendRequest('/v1/articles/1', 'GET'); + $this->assertResponseCode(200); + $this->assertContentType('application/json'); + // the JSON renderer has no JSend envelope + $this->assertSame('First Article', $this->getJsonResponse()['title']); + + // a URL without a version is served as the default version, with its options + $this->sendRequest('/articles/1', 'GET'); + $this->assertContentType('application/json'); + $this->assertSame('First Article', $this->getJsonResponse()['title']); + + // a version without options of its own does not get them + $this->sendRequest('/v2/articles/1', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame('First Article', $result['data']['title']); + } + + public function testVersionedActionOptionsOverride(): void + { + $this->apiConfig(['useVersioning' => true]); + $this->_addSettingByPath('Service.v1.articles.Action.View.Extension', ['CakeDC/Api.CrudHateoas']); + + $this->sendRequest('/v1/articles/1', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $self = Hash::extract($result, 'links.{n}[name=self]'); + $this->assertSame([[ + 'name' => 'self', + 'href' => 'http://example.com/api/v1/articles/1', + 'rel' => '/api/v1/articles/1', + 'method' => 'GET', + ]], $self); + + // another version does not get the v1 action options + $this->sendRequest('/v2/articles/1', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertArrayNotHasKey('links', $result); + } + + public function testUnversionedOptionsStillApplyToTheDefaultVersion(): void + { + $this->apiConfig(['useVersioning' => true, 'defaultVersion' => '1']); + $this->_addSettingByPath('Service.articles.options.rendererClass', 'CakeDC/Api.Json'); + + // options an application set before it had versions keep applying to URLs without a version + $this->sendRequest('/articles/1', 'GET'); + $this->assertContentType('application/json'); + $this->assertSame('First Article', $this->getJsonResponse()['title']); + + // the same service under its version in the URL + $this->sendRequest('/v1/articles/1', 'GET'); + $this->assertSame('First Article', $this->getJsonResponse()['title']); + + // a version without a class of its own is served by the same unversioned class, with its options + $this->sendRequest('/v2/articles/1', 'GET'); + $this->assertContentType('application/json'); + $this->assertSame('First Article', $this->getJsonResponse()['title']); + } + + public function testUnversionedActionOptionsStillApplyToTheDefaultVersion(): void + { + $this->apiConfig(['useVersioning' => true, 'defaultVersion' => '1']); + $this->_addSettingByPath('Service.articles.Action.View.Extension', ['CakeDC/Api.CrudHateoas']); + + // an extension the application set for the service keeps running on a URL without a version + $this->sendRequest('/articles/1', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertNotEmpty(Hash::extract($result, 'links.{n}[name=self]')); + + // nor can a client skip it by asking for a version that has no class of its own + $this->sendRequest('/v2/articles/1', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertNotEmpty(Hash::extract($result, 'links.{n}[name=self]')); + } + + public function testUnversionedOptionsDoNotApplyToVersionedUrls(): void + { + $this->apiConfig(['useVersioning' => true]); + $this->_addSettingByPath('Service.articles.options.rendererClass', 'CakeDC/Api.Json'); + + $this->sendRequest('/v1/articles/1', 'GET'); + $result = $this->getJsonResponse(); + $this->assertSuccess($result); + $this->assertSame('First Article', $result['data']['title']); + } +} diff --git a/tests/TestCase/Middleware/ParseApiRequestMiddlewareTest.php b/tests/TestCase/Middleware/ParseApiRequestMiddlewareTest.php index 96ecec9a..cb6eb689 100644 --- a/tests/TestCase/Middleware/ParseApiRequestMiddlewareTest.php +++ b/tests/TestCase/Middleware/ParseApiRequestMiddlewareTest.php @@ -2,27 +2,33 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Middleware; +use Authentication\Authenticator\UnauthenticatedException; use Cake\Core\Configure; use Cake\Http\Response; +use Cake\Http\ServerRequest; use CakeDC\Api\Middleware\ParseApiRequestMiddleware; +use CakeDC\Api\Service\FallbackService; +use CakeDC\Api\Service\Locator\LocatorInterface; use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; +use CakeDC\Api\Test\App\Service\v1\ArticlesService; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; +use RuntimeException; /** * Unit tests for the API request parsing middleware. @@ -31,6 +37,11 @@ class ParseApiRequestMiddlewareTest extends TestCase { use ConfigTrait; + /** + * Locator replaced by a test, restored in tearDown. + */ + protected ?LocatorInterface $originalLocator = null; + protected function setUp(): void { parent::setUp(); @@ -40,6 +51,10 @@ protected function setUp(): void protected function tearDown(): void { + if ($this->originalLocator instanceof LocatorInterface) { + ServiceRegistry::setServiceLocator($this->originalLocator); + $this->originalLocator = null; + } ServiceRegistry::getServiceLocator()->clear(); Configure::delete('Api.prefix'); Configure::delete('Api.useVersioning'); @@ -73,7 +88,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface return new Response(); } }; - $request = new \Cake\Http\ServerRequest(['url' => '/non-api/path']); + $request = new ServerRequest(['url' => '/non-api/path']); $response = $middleware->process($request, $handler); $this->assertInstanceOf(Response::class, $response); } @@ -83,7 +98,7 @@ public function testApiPathAttachesServiceToHandler(): void $captured = null; $handler = $this->captureHandler($captured); $middleware = new ParseApiRequestMiddleware(); - $request = new \Cake\Http\ServerRequest(['url' => '/api/articles']); + $request = new ServerRequest(['url' => '/api/articles']); $response = $middleware->process($request, $handler); $this->assertInstanceOf(Service::class, $captured); $this->assertSame('articles', $captured->getName()); @@ -96,7 +111,7 @@ public function testCustomPrefix(): void $captured = null; $handler = $this->captureHandler($captured); $middleware = new ParseApiRequestMiddleware(); - $request = new \Cake\Http\ServerRequest(['url' => '/rest/articles']); + $request = new ServerRequest(['url' => '/rest/articles']); $response = $middleware->process($request, $handler); $this->assertInstanceOf(Service::class, $captured); $this->assertSame('HANDLER', (string)$response->getBody()); @@ -107,11 +122,11 @@ public function testUnknownServiceReturnsResponse(): void $handler = new class implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { - throw new \RuntimeException('handler should not be called'); + throw new RuntimeException('handler should not be called'); } }; $middleware = new ParseApiRequestMiddleware(); - $request = new \Cake\Http\ServerRequest(['url' => '/api/nonexistent']); + $request = new ServerRequest(['url' => '/api/nonexistent']); $response = $middleware->process($request, $handler); $this->assertInstanceOf(Response::class, $response); } @@ -124,11 +139,11 @@ public function testActionBuildErrorRespondsDirectly(): void $handler = new class implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { - throw new \RuntimeException('handler should not be called'); + throw new RuntimeException('handler should not be called'); } }; $middleware = new ParseApiRequestMiddleware(); - $request = new \Cake\Http\ServerRequest([ + $request = new ServerRequest([ 'url' => '/api/articles', 'environment' => ['REQUEST_METHOD' => 'DELETE'], ]); @@ -145,10 +160,107 @@ public function testVersionedServiceResolved(): void $captured = null; $handler = $this->captureHandler($captured); $middleware = new ParseApiRequestMiddleware(); - $request = new \Cake\Http\ServerRequest(['url' => '/api/v1/articles']); + $request = new ServerRequest(['url' => '/api/v1/articles']); $response = $middleware->process($request, $handler); - $this->assertInstanceOf(\CakeDC\Api\Test\App\Service\v1\ArticlesService::class, $captured); + $this->assertInstanceOf(ArticlesService::class, $captured); $this->assertSame('articles', $captured->getName()); $this->assertSame('HANDLER', (string)$response->getBody()); } + + /** + * Handler that fails the test when the middleware delegates to it. + */ + protected function failingHandler(): RequestHandlerInterface + { + return new class implements RequestHandlerInterface { + public function handle(ServerRequestInterface $request): ResponseInterface + { + throw new RuntimeException('handler should not be called'); + } + }; + } + + /** + * Replaces the service locator with a stub whose get() is the given callback. + * + * @param callable $get Callback receiving the service alias and options. + * @return void + */ + protected function stubLocator(callable $get): void + { + $this->originalLocator = ServiceRegistry::getServiceLocator(); + $locator = $this->createStub(LocatorInterface::class); + $locator->method('get')->willReturnCallback($get); + ServiceRegistry::setServiceLocator($locator); + } + + public function testUnversionedPathResolvedWhenVersioningIsEnabled(): void + { + Configure::write('Api.useVersioning', true); + $captured = null; + $handler = $this->captureHandler($captured); + $middleware = new ParseApiRequestMiddleware(); + $request = new ServerRequest(['url' => '/api/articles']); + $response = $middleware->process($request, $handler); + $this->assertInstanceOf(Service::class, $captured); + $this->assertNotInstanceOf(ArticlesService::class, $captured); + $this->assertSame('articles', $captured->getName()); + $this->assertNull($captured->getVersion()); + $this->assertSame('HANDLER', (string)$response->getBody()); + } + + public function testUnauthenticatedExceptionWhilePreparingIsRenderedAs401(): void + { + $request = new ServerRequest(['url' => '/api/articles']); + $exception = new UnauthenticatedException('Token expired'); + $service = $this->getMockBuilder(FallbackService::class) + ->setConstructorArgs([['service' => 'articles', 'request' => $request]]) + ->onlyMethods(['dispatchPrepareAction']) + ->getMock(); + $service->expects($this->once())->method('dispatchPrepareAction')->willThrowException($exception); + $this->stubLocator(fn(): Service => $service); + + $response = (new ParseApiRequestMiddleware())->process($request, $this->failingHandler()); + + $this->assertSame(401, $service->getResult()->getCode()); + $this->assertSame($exception, $service->getResult()->getException()); + $decoded = json_decode((string)$response->getBody(), true); + $this->assertSame('error', $decoded['status']); + $this->assertSame(401, $decoded['code']); + $this->assertStringStartsWith('Token expired', $decoded['message']); + } + + /** + * An authentication failure before a service exists cannot be rendered by a service, so an + * empty 400 is returned. + */ + public function testUnauthenticatedBeforeServiceIsBuiltReturnsEmpty400(): void + { + $this->stubLocator(function (): never { + throw new UnauthenticatedException(); + }); + + $request = new ServerRequest(['url' => '/api/articles']); + $response = (new ParseApiRequestMiddleware())->process($request, $this->failingHandler()); + + $this->assertInstanceOf(Response::class, $response); + $this->assertSame(400, $response->getStatusCode()); + $this->assertSame('', (string)$response->getBody()); + } + + /** + * Any other failure before a service exists is passed on with its message, so that the + * application logs it: a service that cannot be built is a fault of the code, not of the request. + */ + public function testFailureBeforeServiceIsBuiltIsPassedOn(): void + { + $exception = new RuntimeException('Cannot build service'); + $this->stubLocator(function () use ($exception): never { + throw $exception; + }); + $request = new ServerRequest(['url' => '/api/articles']); + + $this->expectExceptionObject($exception); + (new ParseApiRequestMiddleware())->process($request, $this->failingHandler()); + } } diff --git a/tests/TestCase/Middleware/ProcessApiRequestMiddlewareTest.php b/tests/TestCase/Middleware/ProcessApiRequestMiddlewareTest.php index b1b33496..e4caeb25 100644 --- a/tests/TestCase/Middleware/ProcessApiRequestMiddlewareTest.php +++ b/tests/TestCase/Middleware/ProcessApiRequestMiddlewareTest.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Middleware; use Cake\Http\Response; +use Cake\Http\ServerRequest; use CakeDC\Api\Middleware\ProcessApiRequestMiddleware; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; @@ -21,6 +22,7 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; +use RuntimeException; /** * Unit tests for the API request processing middleware. @@ -35,7 +37,7 @@ protected function tearDown(): void parent::tearDown(); } - protected function buildServiceRequest(): \Cake\Http\ServerRequest + protected function buildServiceRequest(): ServerRequest { ServiceRegistry::getServiceLocator()->clear(); $this->_initializeRequest([ @@ -65,7 +67,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface } }; $middleware = new ProcessApiRequestMiddleware(); - $request = new \Cake\Http\ServerRequest(['url' => '/articles']); + $request = new ServerRequest(['url' => '/articles']); $response = $middleware->process($request, $handler); $this->assertSame('HANDLER', (string)$response->getBody()); } @@ -76,7 +78,7 @@ public function testWithServiceProcessesAction(): void $handler = new class implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { - throw new \RuntimeException('handler should not be called'); + throw new RuntimeException('handler should not be called'); } }; $middleware = new ProcessApiRequestMiddleware(); @@ -90,12 +92,12 @@ public function testServiceDispatchExceptionReturns400(): void $request = $this->buildServiceRequest(); $service = $request->getAttribute('service'); $service->getEventManager()->on('Service.afterDispatch', function (): void { - throw new \RuntimeException('after-dispatch boom'); + throw new RuntimeException('after-dispatch boom'); }); $handler = new class implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { - throw new \RuntimeException('handler should not be called'); + throw new RuntimeException('handler should not be called'); } }; $middleware = new ProcessApiRequestMiddleware(); diff --git a/tests/TestCase/Middleware/UnauthorizedHandler/ApiExceptionHandlerTest.php b/tests/TestCase/Middleware/UnauthorizedHandler/ApiExceptionHandlerTest.php new file mode 100644 index 00000000..e1fbc4bb --- /dev/null +++ b/tests/TestCase/Middleware/UnauthorizedHandler/ApiExceptionHandlerTest.php @@ -0,0 +1,105 @@ + '/api/articles', + 'environment' => ['REQUEST_METHOD' => 'GET'], + ]); + $service = new FallbackService(['service' => 'articles', 'request' => $request]); + + return $request->withAttribute('service', $service); + } + + /** + * An authorization failure other than "forbidden" is rendered by the service as a 401 with its message. + */ + public function testNotForbiddenExceptionIsRenderedAsUnauthenticated(): void + { + $request = $this->requestWithService(); + $exception = new MissingIdentityException(['identity']); + + $response = (new ApiExceptionHandler())->handle($exception, $request); + + $service = $request->getAttribute('service'); + $this->assertSame(401, $service->getResult()->getCode()); + $this->assertSame($exception, $service->getResult()->getException()); + $body = json_decode((string)$response->getBody(), true); + $this->assertSame('error', $body['status']); + $this->assertSame('Identity is not present in `identity` request attribute.', $body['message']); + $this->assertSame(403, $body['code']); + } + + /** + * A forbidden exception is replaced by a generic 403 message. + */ + public function testForbiddenExceptionIsRenderedWithGenericMessage(): void + { + $request = $this->requestWithService(); + + $response = (new ApiExceptionHandler())->handle(new ForbiddenException(), $request); + + $service = $request->getAttribute('service'); + $this->assertSame(403, $service->getResult()->getCode()); + $body = json_decode((string)$response->getBody(), true); + $this->assertSame('Forbidden authorization request', $body['message']); + $this->assertSame(403, $body['code']); + } + + /** + * Without a service on the request the exception is rethrown unchanged. + */ + public function testExceptionIsRethrownWithoutService(): void + { + $exception = new ForbiddenException(); + $request = new ServerRequest(['url' => '/not-api']); + + try { + (new ApiExceptionHandler())->handle($exception, $request); + $this->fail('The exception was expected to be rethrown'); + } catch (ForbiddenException $forbiddenException) { + $this->assertSame($exception, $forbiddenException); + } + } +} diff --git a/tests/TestCase/Model/AuthStoreTest.php b/tests/TestCase/Model/AuthStoreTest.php index bf71b515..0486326e 100644 --- a/tests/TestCase/Model/AuthStoreTest.php +++ b/tests/TestCase/Model/AuthStoreTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Model; @@ -71,10 +71,16 @@ public function testStoreColumnIsJson(): void public function testSaveAndFindRoundtrip(): void { $table = TableRegistry::getTableLocator()->get('CakeDC/Api.AuthStore'); - $entity = $table->newEntity(['store' => 'store-data']); + // the WebAuthn adapter keys the store by the bearer token, which is longer than a uuid + $id = str_repeat('a', 400); + + $entity = $table->newEmptyEntity(); + $entity->set('id', $id); + $entity->set('store', 'store-data'); + $saved = $table->save($entity); $this->assertNotFalse($saved); - $found = $table->get($saved->get('id')); + $found = $table->get($id); $this->assertSame('store-data', $found->get('store')); } } diff --git a/tests/TestCase/Model/EntityDescriptionStub.php b/tests/TestCase/Model/EntityDescriptionStub.php index 4d47ef0c..5e129af4 100644 --- a/tests/TestCase/Model/EntityDescriptionStub.php +++ b/tests/TestCase/Model/EntityDescriptionStub.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Model; diff --git a/tests/TestCase/Model/EntityInterfacesTest.php b/tests/TestCase/Model/EntityInterfacesTest.php index 7fa4b46e..a5da4be2 100644 --- a/tests/TestCase/Model/EntityInterfacesTest.php +++ b/tests/TestCase/Model/EntityInterfacesTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Model; diff --git a/tests/TestCase/Model/JwtRefreshTokensTest.php b/tests/TestCase/Model/JwtRefreshTokensTest.php index c5bb3326..ea5f91fc 100644 --- a/tests/TestCase/Model/JwtRefreshTokensTest.php +++ b/tests/TestCase/Model/JwtRefreshTokensTest.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Model; use Cake\ORM\TableRegistry; use CakeDC\Api\Model\Entity\JwtRefreshToken; +use CakeDC\Api\Test\Settings; use CakeDC\Api\TestSuite\TestCase; /** @@ -62,14 +63,14 @@ public function testSaveAndFind(): void $table = TableRegistry::getTableLocator()->get('CakeDC/Api.JwtRefreshTokens'); $entity = $table->newEntity([ 'model' => 'Users', - 'foreign_key' => '1', + 'foreign_key' => Settings::USER1, 'token' => 'token-value', 'expired' => 123456, ]); $saved = $table->save($entity); $this->assertNotFalse($saved); $found = $table->find() - ->where(['model' => 'Users', 'foreign_key' => '1']) + ->where(['model' => 'Users', 'foreign_key' => Settings::USER1]) ->first(); $this->assertNotNull($found); $this->assertSame('token-value', $found->get('token')); diff --git a/tests/TestCase/Model/MigrationsSchemaTest.php b/tests/TestCase/Model/MigrationsSchemaTest.php new file mode 100644 index 00000000..6b51bba0 --- /dev/null +++ b/tests/TestCase/Model/MigrationsSchemaTest.php @@ -0,0 +1,90 @@ + Connection::class, + 'driver' => Sqlite::class, + 'database' => ':memory:', + ]); + } + + protected function tearDown(): void + { + ConnectionManager::drop(self::CONNECTION); + parent::tearDown(); + } + + /** + * Returns the tables of tests/schema.php, keyed by table name. + * + * @return array> + */ + protected function testSchema(): array + { + $tables = []; + foreach (include dirname(__DIR__, 2) . DS . 'schema.php' as $table) { + $tables[$table['table']] = $table; + } + + return $tables; + } + + public function testMigrationsMatchTheTestSchema(): void + { + $migrations = new Migrations(['connection' => self::CONNECTION, 'plugin' => 'CakeDC/Api']); + $this->assertTrue($migrations->migrate()); + + $collection = ConnectionManager::get(self::CONNECTION)->getSchemaCollection(); + $expected = $this->testSchema(); + foreach (['jwt_refresh_tokens', 'auth_store'] as $tableName) { + $this->assertArrayHasKey($tableName, $expected, $tableName . ' is missing from tests/schema.php'); + $migrated = $collection->describe($tableName); + $columns = $expected[$tableName]['columns']; + + $this->assertEqualsCanonicalizing(array_keys($columns), $migrated->columns(), $tableName . ' columns'); + $this->assertSame( + $expected[$tableName]['constraints']['primary']['columns'], + $migrated->getPrimaryKey(), + $tableName . ' primary key', + ); + foreach ($columns as $name => $column) { + $actual = $migrated->getColumn($name); + $this->assertNotNull($actual, $tableName . '.' . $name); + $this->assertSame($column['type'], $actual['type'], $tableName . '.' . $name . ' type'); + $this->assertSame($column['null'], $actual['null'], $tableName . '.' . $name . ' null'); + if ($column['type'] === 'string') { + $this->assertSame($column['length'], $actual['length'], $tableName . '.' . $name . ' length'); + } + } + } + } +} diff --git a/tests/TestCase/Rbac/AlwaysFalseRule.php b/tests/TestCase/Rbac/AlwaysFalseRule.php index 08849447..e1b7d822 100644 --- a/tests/TestCase/Rbac/AlwaysFalseRule.php +++ b/tests/TestCase/Rbac/AlwaysFalseRule.php @@ -2,23 +2,24 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Rbac; +use ArrayAccess; use CakeDC\Auth\Rbac\Rules\Rule; use Psr\Http\Message\ServerRequestInterface; class AlwaysFalseRule implements Rule { - public function allowed(array|\ArrayAccess $user, string $role, ServerRequestInterface $request): bool + public function allowed(array|ArrayAccess $user, string $role, ServerRequestInterface $request): bool { return false; } diff --git a/tests/TestCase/Rbac/AlwaysTrueRule.php b/tests/TestCase/Rbac/AlwaysTrueRule.php index 9a0795d1..b650f392 100644 --- a/tests/TestCase/Rbac/AlwaysTrueRule.php +++ b/tests/TestCase/Rbac/AlwaysTrueRule.php @@ -2,23 +2,24 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Rbac; +use ArrayAccess; use CakeDC\Auth\Rbac\Rules\Rule; use Psr\Http\Message\ServerRequestInterface; class AlwaysTrueRule implements Rule { - public function allowed(array|\ArrayAccess $user, string $role, ServerRequestInterface $request): bool + public function allowed(array|ArrayAccess $user, string $role, ServerRequestInterface $request): bool { return true; } diff --git a/tests/TestCase/Rbac/ApiConfigProviderTest.php b/tests/TestCase/Rbac/ApiConfigProviderTest.php index cd00f61f..45ad264e 100644 --- a/tests/TestCase/Rbac/ApiConfigProviderTest.php +++ b/tests/TestCase/Rbac/ApiConfigProviderTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Rbac; diff --git a/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php b/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php index 91c393bd..bfddc2ef 100644 --- a/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php +++ b/tests/TestCase/Rbac/ApiRbacKeyOrderTest.php @@ -22,6 +22,7 @@ use CakeDC\Api\Service\CrudService; use CakeDC\Api\TestSuite\TestCase; use PHPUnit\Framework\Attributes\DataProvider; +use stdClass; /** * The `allowed` and `bypassAuth` keys end the check of a rule; the other keys must still apply. @@ -131,6 +132,69 @@ public function testCachedRbacChecksTheTarget(): void $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'view'))); } + public function testCallableWithANumericKeyIsChecked(): void + { + $rule = fn(bool $result): array => [ + 'role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*', + fn(): bool => $result, + 'allowed' => true, + ]; + $this->assertTrue($this->check([$rule(true)], $this->request('articles', 'index'))); + $this->assertFalse($this->check([$rule(false)], $this->request('articles', 'index'))); + } + + public function testIntegerRoleIsMatchedAsAString(): void + { + // roles stored in an integer column reach the adapter as integers + $rules = [['role' => '2', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true]]; + if (!Cache::getConfig('_cakedc_api_auth_')) { + Cache::setConfig('_cakedc_api_auth_', ['className' => 'Array']); + } + Cache::clear('_cakedc_api_auth_'); + $rbacs = [new ApiRbac(['api_permissions' => $rules]), new CachedApiRbac(['api_permissions' => $rules])]; + Cache::clear('_cakedc_api_auth_'); + foreach ($rbacs as $rbac) { + $request = $this->request('articles', 'index'); + $this->assertTrue($rbac->checkPermissions(['id' => 1, 'role' => 2], $request), $rbac::class); + $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 3], $request), $rbac::class); + } + } + + public function testEnumRoleIsMatchedByItsValue(): void + { + // a role column mapped to a backed enum reaches the adapter as the enum case + $rules = [['role' => 'admin', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true]]; + foreach ([new ApiRbac(['api_permissions' => $rules]), $this->cached($rules)] as $rbac) { + $request = $this->request('articles', 'index'); + $this->assertTrue($rbac->checkPermissions(['id' => 1, 'role' => RoleEnum::Admin], $request), $rbac::class); + $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => RoleEnum::Guest], $request), $rbac::class); + } + } + + public function testRoleThatCannotBeMatchedIsDeniedAndLogged(): void + { + // a rule for the default role must not apply to a user whose role cannot be read as a name + $rules = [['role' => 'user', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => true]]; + Log::setConfig('rbac_role_test', ['className' => 'Array', 'levels' => ['warning']]); + try { + foreach ([new ApiRbac(['api_permissions' => $rules]), $this->cached($rules)] as $rbac) { + $request = $this->request('articles', 'index'); + $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => ['admin', 'user']], $request), $rbac::class); + $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => new stdClass()], $request), $rbac::class); + // a user without a role is still the default role + $this->assertTrue($rbac->checkPermissions(['id' => 1], $request), $rbac::class); + $this->assertTrue($rbac->checkPermissions(['id' => 1, 'role' => null], $request), $rbac::class); + } + $logs = Log::engine('rbac_role_test')->read(); + $this->assertCount(4, $logs); + $this->assertStringContainsString('role', $logs[0]); + $this->assertStringContainsString('array', $logs[0]); + $this->assertStringContainsString('stdClass', $logs[1]); + } finally { + Log::drop('rbac_role_test'); + } + } + /** * Rule lists where the order of rules for different roles or services decides the result. * @@ -208,7 +272,7 @@ public static function orderedRulesProvider(): array ['role' => '*', 'service' => '*'] + $allow, ], false], 'callable role is checked' => [[ - ['role' => fn(): true => true, 'service' => 'articles'] + $deny, + ['role' => fn(): bool => true, 'service' => 'articles'] + $deny, ['role' => '*', 'service' => '*'] + $allow, ], false], ]; @@ -369,120 +433,6 @@ public function testCachedRbacIgnoresMapsOfEarlierVersions(): void $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index'))); } - /** - * A changed option of a Rule object takes effect without clearing a cache that serializes. - * - * @return void - */ - public function testCachedRbacUsesChangedRuleOptions(): void - { - $rule = ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*']; - $this->withFileCache(function () use ($rule): void { - new CachedApiRbac(['api_permissions' => [$rule + ['allowed' => new OptionRule(['allow' => true])]]]); - $rbac = new CachedApiRbac(['api_permissions' => [$rule + ['allowed' => new OptionRule(['allow' => false])]]]); - - $this->assertFalse( - $rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index')) - ); - }); - } - - /** - * Rules with closures work with a cache that serializes, because the map holds rule positions only. - * - * @return void - */ - public function testCachedRbacWorksWithClosuresAndAFileCache(): void - { - $rules = [ - ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*', 'allowed' => fn(): true => true], - ]; - $this->withFileCache(function () use ($rules): void { - new CachedApiRbac(['api_permissions' => $rules]); - $rbac = new CachedApiRbac(['api_permissions' => $rules]); - - $this->assertTrue( - $rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index')) - ); - }); - } - - /** - * Rule lists with names that are not valid UTF-8 get their own cache keys. - * - * @return void - */ - public function testCachedRbacCacheKeyOfNamesThatAreNotUtf8(): void - { - $rbac = new class extends CachedApiRbac { - /** - * Without the parent constructor, no map is built. - */ - public function __construct() - { - } - - /** - * @param array $permissions Permission rules. - * @return string - */ - public static function key(array $permissions): string - { - return static::cacheKey($permissions); - } - }; - $rule = ['service' => '*', 'action' => '*', 'allowed' => true]; - - $keys = [ - $rbac::key([['role' => "\xff"] + $rule]), - $rbac::key([['role' => "\xfe"] + $rule]), - $rbac::key([]), - ]; - $this->assertCount(3, array_unique($keys)); - } - - /** - * Rules set with setPermissions() are checked instead of the rules of the constructor. - * - * @return void - */ - public function testCachedRbacUsesSetPermissions(): void - { - $rule = ['role' => '*', 'service' => '*', 'action' => '*', 'method' => '*']; - $rbac = $this->cached([$rule + ['allowed' => true]]); - $rbac->setPermissions([$rule + ['allowed' => false]]); - Cache::clear('_cakedc_api_auth_'); - - $this->assertFalse($rbac->checkPermissions(['id' => 1, 'role' => 'user'], $this->request('articles', 'index'))); - } - - /** - * Runs a test with a File cache that serializes as the `_cakedc_api_auth_` engine. - * - * @param callable $test Test. - * @return void - */ - protected function withFileCache(callable $test): void - { - $previous = Cache::getConfig('_cakedc_api_auth_'); - Cache::drop('_cakedc_api_auth_'); - Cache::setConfig('_cakedc_api_auth_', [ - 'className' => 'File', - 'path' => TMP . 'cache' . DS . 'cached_rbac_test' . DS, - 'serialize' => true, - ]); - try { - Cache::clear('_cakedc_api_auth_'); - $test(); - } finally { - Cache::clear('_cakedc_api_auth_'); - Cache::drop('_cakedc_api_auth_'); - if ($previous) { - Cache::setConfig('_cakedc_api_auth_', $previous); - } - } - } - /** * Builds and caches the map of the rules, and leaves it in the cache. * diff --git a/tests/TestCase/Rbac/ApiRbacTest.php b/tests/TestCase/Rbac/ApiRbacTest.php index 4146e904..6016ac18 100644 --- a/tests/TestCase/Rbac/ApiRbacTest.php +++ b/tests/TestCase/Rbac/ApiRbacTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Rbac; diff --git a/tests/TestCase/Rbac/CachedApiRbacTest.php b/tests/TestCase/Rbac/CachedApiRbacTest.php index 2cbe4d5e..4206bcad 100644 --- a/tests/TestCase/Rbac/CachedApiRbacTest.php +++ b/tests/TestCase/Rbac/CachedApiRbacTest.php @@ -2,22 +2,24 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Rbac; use Cake\Cache\Cache; +use CakeDC\Api\Rbac\ApiRbac; use CakeDC\Api\Rbac\CachedApiRbac; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; /** * Unit tests for the cached permissions-map based RBAC. @@ -170,7 +172,7 @@ public function testCheckPermissionsWithoutServiceAttributeDenies(): void public function testCheckPermissionsUsesCachedMap(): void { - [$rbac, $request] = $this->buildRbac([ + [, $request] = $this->buildRbac([ ['role' => 'user', 'service' => 'articles', 'action' => 'index'], ]); // second instance reads the permissions map from the cache engine @@ -211,4 +213,136 @@ public function testFileCacheEnginePersistsMap(): void Cache::setConfig('_cakedc_api_auth_', ['engine' => 'Array']); Cache::clear('_cakedc_api_auth_'); } + + /** + * Rule lists where the order of rules for different roles or services decides the result. + * + * @return array + */ + public static function orderedRulesProvider(): array + { + $deny = ['action' => '*', 'method' => '*', 'allowed' => false]; + $allow = ['action' => '*', 'method' => '*', 'allowed' => true]; + + return [ + 'any role denied before own role allowed' => [[ + ['role' => '*', 'service' => 'articles'] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ]], + 'own role allowed before any role denied' => [[ + ['role' => 'user', 'service' => 'articles'] + $allow, + ['role' => '*', 'service' => 'articles'] + $deny, + ]], + 'any service denied before own service allowed' => [[ + ['role' => 'user', 'service' => '*'] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ]], + 'rule without a service denied before own service allowed' => [[ + ['role' => 'user'] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ]], + 'role list denied before own role allowed' => [[ + ['role' => ['admin', 'user'], 'service' => ['authors', 'articles']] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ]], + 'camelized service name allowed' => [[ + ['role' => 'user', 'service' => 'Articles'] + $allow, + ]], + 'camelized service name denied before own service allowed' => [[ + ['role' => 'user', 'service' => 'Articles'] + $deny, + ['role' => 'user', 'service' => 'articles'] + $allow, + ]], + ]; + } + + /** + * The cached map gives the same result as ApiRbac, which checks the rules in order. + */ + #[DataProvider('orderedRulesProvider')] + public function testSameResultAsApiRbac(array $permissions): void + { + [$cached, $request] = $this->buildRbac($permissions); + $plain = new ApiRbac(['api_permissions' => $permissions, 'role_field' => 'role', 'default_role' => 'user']); + $user = ['role' => 'user', 'id' => 1]; + + $this->assertSame($plain->checkPermissions($user, $request), $cached->checkPermissions($user, $request)); + } + + public function testChangedRuleOptionsTakeEffectWithAFileCache(): void + { + $rule = ['role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*']; + $this->withFileCache(function () use ($rule): void { + $this->buildRbac([$rule + ['allowed' => new OptionRule(['allow' => true])]]); + [$rbac, $request] = $this->buildRbac([$rule + ['allowed' => new OptionRule(['allow' => false])]]); + + $this->assertFalse($rbac->checkPermissions(['role' => 'user', 'id' => 1], $request)); + }); + } + + public function testClosuresWorkWithAFileCache(): void + { + $rules = [ + ['role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*', 'allowed' => fn(): bool => true], + ]; + $this->withFileCache(function () use ($rules): void { + $this->buildRbac($rules); + [$rbac, $request] = $this->buildRbac($rules); + + $this->assertTrue($rbac->checkPermissions(['role' => 'user', 'id' => 1], $request)); + }); + } + + public function testCacheKeyOfNamesThatAreNotUtf8(): void + { + $rule = ['service' => '*', 'action' => '*', 'allowed' => true]; + $keys = [ + CachedApiRbac::cacheKey([['role' => "\xff"] + $rule]), + CachedApiRbac::cacheKey([['role' => "\xfe"] + $rule]), + CachedApiRbac::cacheKey([]), + ]; + + $this->assertCount(3, array_unique($keys)); + } + + public function testSetPermissionsReplacesTheRules(): void + { + $rule = ['role' => '*', 'service' => 'articles', 'action' => '*', 'method' => '*']; + [$rbac, $request] = $this->buildRbac([$rule + ['allowed' => true]]); + $rbac->setPermissions([$rule + ['allowed' => false]]); + + $this->assertFalse($rbac->checkPermissions(['role' => 'user', 'id' => 1], $request)); + } + + /** + * Runs a test with a File cache that serializes as the `_cakedc_api_auth_` engine. + */ + protected function withFileCache(callable $test): void + { + Cache::drop('_cakedc_api_auth_'); + Cache::setConfig('_cakedc_api_auth_', [ + 'engine' => 'File', + 'path' => TMP . 'cache' . DS . 'rbac_file', + 'serialize' => true, + ]); + try { + Cache::clear('_cakedc_api_auth_'); + $test(); + } finally { + Cache::clear('_cakedc_api_auth_'); + Cache::drop('_cakedc_api_auth_'); + Cache::setConfig('_cakedc_api_auth_', ['engine' => 'Array']); + } + } + + public function testRulesKeepTheirPositionInTheMap(): void + { + [$rbac] = $this->buildRbac([ + ['role' => '*', 'service' => 'articles', 'action' => '*', 'allowed' => false], + ['role' => 'user', 'service' => 'articles', 'action' => '*', 'allowed' => true], + ]); + $map = $rbac->buildPermissionsMap(); + + $this->assertSame([0], array_keys($map['*']['articles'])); + $this->assertSame([1], array_keys($map['user']['articles'])); + } } diff --git a/tests/TestCase/Rbac/RoleEnum.php b/tests/TestCase/Rbac/RoleEnum.php new file mode 100644 index 00000000..f871ef07 --- /dev/null +++ b/tests/TestCase/Rbac/RoleEnum.php @@ -0,0 +1,23 @@ +aud = $aud; $authenticator = new class () extends JwtAuthenticator { @@ -78,7 +79,7 @@ public function testNoProviderDenies(): void public function testNonJwtProviderDenies(): void { $scope = new TwoFactorPassedScope(); - $this->assertFalse($scope->allowed(['id' => 1], 'user', $this->buildRequest(new \stdClass()))); + $this->assertFalse($scope->allowed(['id' => 1], 'user', $this->buildRequest(new stdClass()))); } public function testAudMatchAllows(): void diff --git a/tests/TestCase/Rbac/TwoFactorScopeTest.php b/tests/TestCase/Rbac/TwoFactorScopeTest.php index 924b0b1f..8568695c 100644 --- a/tests/TestCase/Rbac/TwoFactorScopeTest.php +++ b/tests/TestCase/Rbac/TwoFactorScopeTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Rbac; @@ -18,6 +18,7 @@ use Cake\Routing\Router; use CakeDC\Api\Rbac\Rules\TwoFactorScope; use CakeDC\Api\TestSuite\TestCase; +use stdClass; /** * Unit tests for the 2FA RBAC scope rule (JWT aud claim == /2fa). @@ -44,7 +45,7 @@ public function getAuthenticationProvider(): ?object protected function buildJwtAuthenticator(string $aud): JwtAuthenticator { - $payload = new \stdClass(); + $payload = new stdClass(); $payload->aud = $aud; $authenticator = new class () extends JwtAuthenticator { @@ -78,7 +79,7 @@ public function testNoProviderDenies(): void public function testNonJwtProviderDenies(): void { $scope = new TwoFactorScope(); - $this->assertFalse($scope->allowed(['id' => 1], 'user', $this->buildRequest(new \stdClass()))); + $this->assertFalse($scope->allowed(['id' => 1], 'user', $this->buildRequest(new stdClass()))); } public function testAudMatchAllows(): void diff --git a/tests/TestCase/Rector/Fixture/crud_action_override.php.inc b/tests/TestCase/Rector/Fixture/crud_action_override.php.inc new file mode 100644 index 00000000..4c1295ad --- /dev/null +++ b/tests/TestCase/Rector/Fixture/crud_action_override.php.inc @@ -0,0 +1,47 @@ +where([$this->_table->aliasField('published') => true]); + } + + public function execute() + { + return parent::execute(); + } +} + +?> +----- +where([$this->table->aliasField('published') => true]); + } + + public function execute(): \Cake\Datasource\ResultSetInterface + { + return parent::execute(); + } +} + +?> diff --git a/tests/TestCase/Rector/Fixture/extension_own_call.php.inc b/tests/TestCase/Rector/Fixture/extension_own_call.php.inc new file mode 100644 index 00000000..afaad344 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/extension_own_call.php.inc @@ -0,0 +1,43 @@ +_limit($action) . ', page ' . static::_page($action); + } +} + +?> +----- +limit($action) . ', page ' . static::page($action); + } +} + +?> diff --git a/tests/TestCase/Rector/Fixture/property_type.php.inc b/tests/TestCase/Rector/Fixture/property_type.php.inc new file mode 100644 index 00000000..e6711565 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/property_type.php.inc @@ -0,0 +1,25 @@ + +----- + diff --git a/tests/TestCase/Rector/Fixture/removed_classes.php.inc b/tests/TestCase/Rector/Fixture/removed_classes.php.inc new file mode 100644 index 00000000..55958cb1 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/removed_classes.php.inc @@ -0,0 +1,27 @@ + +----- + diff --git a/tests/TestCase/Rector/Fixture/second_factor_override.php.inc b/tests/TestCase/Rector/Fixture/second_factor_override.php.inc new file mode 100644 index 00000000..6dfc71e5 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/second_factor_override.php.inc @@ -0,0 +1,41 @@ +_hasVerifiedOtp($identity); + } + + protected function _refuseEnrollmentIf(bool $otherFactorRegistered): void + { + parent::_refuseEnrollmentIf($otherFactorRegistered); + } +} + +?> +----- +hasVerifiedOtp($identity); + } + + protected function refuseEnrollmentIf(bool $otherFactorRegistered): void + { + parent::refuseEnrollmentIf($otherFactorRegistered); + } +} + +?> diff --git a/tests/TestCase/Rector/Fixture/service_properties.php.inc b/tests/TestCase/Rector/Fixture/service_properties.php.inc new file mode 100644 index 00000000..1c5f2617 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/service_properties.php.inc @@ -0,0 +1,37 @@ +_actionsClassMap['index'] = PublishedIndexAction::class; + } +} + +?> +----- +actionsClassMap['index'] = PublishedIndexAction::class; + } +} + +?> diff --git a/tests/TestCase/Rector/Fixture/skip_unrelated_class.php.inc b/tests/TestCase/Rector/Fixture/skip_unrelated_class.php.inc new file mode 100644 index 00000000..62dd7db3 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/skip_unrelated_class.php.inc @@ -0,0 +1,20 @@ +_table; + } + + public function run() + { + return $this->_save(); + } +} + +?> diff --git a/tests/TestCase/Rector/Fixture/sort_extension_override.php.inc b/tests/TestCase/Rector/Fixture/sort_extension_override.php.inc new file mode 100644 index 00000000..5ab4630c --- /dev/null +++ b/tests/TestCase/Rector/Fixture/sort_extension_override.php.inc @@ -0,0 +1,43 @@ +_sortDirection($direction); + } +} + +?> +----- +sortDirection($direction); + } +} + +?> diff --git a/tests/TestCase/Rector/Fixture/typed_action_properties.php.inc b/tests/TestCase/Rector/Fixture/typed_action_properties.php.inc new file mode 100644 index 00000000..b36423a8 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/typed_action_properties.php.inc @@ -0,0 +1,37 @@ + +----- + diff --git a/tests/TestCase/Rector/Fixture/typed_properties_without_default.php.inc b/tests/TestCase/Rector/Fixture/typed_properties_without_default.php.inc new file mode 100644 index 00000000..986de515 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/typed_properties_without_default.php.inc @@ -0,0 +1,33 @@ + +----- + diff --git a/tests/TestCase/Rector/Fixture/typed_service_properties.php.inc b/tests/TestCase/Rector/Fixture/typed_service_properties.php.inc new file mode 100644 index 00000000..888e6040 --- /dev/null +++ b/tests/TestCase/Rector/Fixture/typed_service_properties.php.inc @@ -0,0 +1,41 @@ + CommentsIndexAction::class, + ]; + + protected $_idName = 'uuid'; + + protected $_parentIdName = 'article_id'; + + protected $_routePrefix = 'comments'; +} + +?> +----- + CommentsIndexAction::class, + ]; + + protected string $idName = 'uuid'; + + protected ?string $parentIdName = 'article_id'; + + protected string $routePrefix = 'comments'; +} + +?> diff --git a/tests/TestCase/Rector/UpgradeChangesTest.php b/tests/TestCase/Rector/UpgradeChangesTest.php new file mode 100644 index 00000000..4f76a51b --- /dev/null +++ b/tests/TestCase/Rector/UpgradeChangesTest.php @@ -0,0 +1,123 @@ +changes()['classes'] as $old => $new) { + $this->assertFalse(class_exists($old), $old); + $this->assertTrue(class_exists($new), $new); + } + } + + public function testRenamedMethodsExistOnlyWithTheNewName(): void + { + $src = dirname(__DIR__, 3) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR; + foreach ($this->changes()['methods'] as $class => $names) { + foreach ($names as $name) { + // RegisterAction still has the `_afterRegister()` of the cakedc/users RegisterTrait + $old = method_exists($class, $name) ? (string)(new ReflectionMethod($class, $name))->getFileName() : ''; + $this->assertStringStartsNotWith($src, $old, "$class::$name()"); + $this->assertTrue(method_exists($class, substr($name, 1)), "$class::" . substr($name, 1) . '()'); + } + } + } + + public function testRenamedPropertiesExistOnlyWithTheNewName(): void + { + foreach ($this->changes()['properties'] as $class => $names) { + foreach ($names as $name) { + $this->assertFalse(property_exists($class, $name), "$class::\$$name"); + $this->assertTrue(property_exists($class, substr($name, 1)), "$class::\$" . substr($name, 1)); + } + } + } + + public function testTypesOfRenamedPropertiesCanBeWrittenByTheSet(): void + { + // AddInheritedPropertyTypeRector repeats named and union types; it leaves an intersection type out, + // and a subclass that redeclares such a property would then stop PHP with a fatal error + $typed = 0; + foreach ($this->changes()['properties'] as $class => $names) { + foreach ($names as $name) { + $declared = (new ReflectionProperty($class, substr($name, 1)))->getType(); + if (!$declared instanceof ReflectionType) { + continue; + } + $typed++; + $this->assertTrue( + $declared instanceof ReflectionNamedType || $declared instanceof ReflectionUnionType, + "$class::\$" . substr($name, 1), + ); + } + } + // the renamed properties do have native types, so the set must add them + $this->assertGreaterThan(20, $typed); + } + + public function testRenamesMatchTheLegacyMemberGuard(): void + { + $groups = [ + Action::class => LegacyMemberGuard::ACTION, + Service::class => LegacyMemberGuard::SERVICE, + ActionExtension::class => LegacyMemberGuard::ACTION_EXTENSION, + ServiceExtension::class => LegacyMemberGuard::SERVICE_EXTENSION, + BaseRenderer::class => LegacyMemberGuard::RENDERER, + BaseParser::class => LegacyMemberGuard::PARSER, + ]; + $changes = $this->changes(); + foreach ($groups as $root => $legacy) { + foreach (['methods', 'properties'] as $kind) { + $renamed = []; + foreach ($changes[$kind] as $class => $names) { + if (is_a($class, $root, true)) { + $renamed = array_merge($renamed, $names); + } + } + $renamed = array_values(array_unique($renamed)); + sort($renamed); + $guarded = $legacy[$kind]; + sort($guarded); + $this->assertSame($guarded, $renamed, "$root $kind"); + } + } + } +} diff --git a/tests/TestCase/Rector/UpgradeSetTest.php b/tests/TestCase/Rector/UpgradeSetTest.php new file mode 100644 index 00000000..834f99fb --- /dev/null +++ b/tests/TestCase/Rector/UpgradeSetTest.php @@ -0,0 +1,40 @@ +doTestFile($filePath); + } + + public static function provideData(): Iterator + { + return self::yieldFilesFromDirectory(__DIR__ . '/Fixture'); + } + + public function provideConfigFilePath(): string + { + return dirname(__DIR__, 3) . '/config/rector/cakephp-api-13.php'; + } +} diff --git a/tests/TestCase/Routing/ApiRouteBuilderTest.php b/tests/TestCase/Routing/ApiRouteBuilderTest.php new file mode 100644 index 00000000..759da7c0 --- /dev/null +++ b/tests/TestCase/Routing/ApiRouteBuilderTest.php @@ -0,0 +1,145 @@ + $className Route builder class. + * @param array $options Resource options. + * @param bool $nested Whether to connect a nested resource. + * @return list + */ + protected function connect(string $className, array $options, bool $nested = false): array + { + $collection = new RouteCollection(); + $builder = new $className($collection, '/', ['scoped' => 'yes']); + $callback = $nested ? function (RouteBuilder $routes): void { + $routes->resources('Comments'); + } : null; + $builder->resources('Articles', $options, $callback); + + $routes = []; + foreach ($collection->routes() as $route) { + $routes[] = [$route->template, $route->defaults, $route->options]; + } + + return $routes; + } + + public function testApiRouterCreatesApiRouteBuilder(): void + { + ApiRouter::reload(); + + $this->assertInstanceOf(ApiRouteBuilder::class, ApiRouter::createRouteBuilder('/')); + } + + public function testMapWithoutRouteOptionsConnectsLikeRouteBuilder(): void + { + $options = [ + 'map' => [ + 'featured' => ['method' => 'GET', 'path' => 'featured', 'action' => 'featured'], + 'view' => ['method' => 'GET', 'path' => '{id}', 'action' => 'show'], + ], + 'connectOptions' => ['id' => '[0-9]+'], + ]; + + $this->assertSame( + $this->connect(RouteBuilder::class, $options, true), + $this->connect(ApiRouteBuilder::class, $options, true), + ); + } + + public function testRouteOptionsAreApplied(): void + { + $routes = $this->connect(ApiRouteBuilder::class, [ + 'only' => ['lookup'], + 'map' => [ + 'lookup' => [ + 'method' => ['GET'], + 'path' => 'lookup/{code}', + 'action' => 'lookup', + 'flag' => 'on', + 'patterns' => ['code' => '[0-9]+'], + 'pass' => ['code'], + 'name' => 'articlesLookup', + ], + ], + 'connectOptions' => ['code' => '[a-z]+', 'other' => '[a-z]+'], + ]); + + $this->assertCount(1, $routes); + [$template, $defaults, $options] = $routes[0]; + $this->assertSame('/articles/lookup/{code}', $template); + $this->assertSame('lookup', $defaults['action']); + $this->assertSame('on', $defaults['flag']); + $this->assertSame('yes', $defaults['scoped']); + $this->assertSame('[0-9]+', $options['code']); + $this->assertSame('[a-z]+', $options['other']); + $this->assertSame(['code'], $options['pass']); + $this->assertSame('articlesLookup', $options['_name']); + } + + public function testRouteOrderOnlyAndNestingAreKept(): void + { + $plain = [ + 'only' => ['index', 'view', 'first', 'second', 'third'], + 'map' => [ + 'first' => ['method' => 'GET', 'path' => 'first/{code}', 'action' => 'first'], + 'view' => ['method' => 'GET', 'path' => '{id}', 'action' => 'view'], + 'second' => ['method' => 'GET', 'path' => 'second', 'action' => 'second'], + 'third' => ['method' => 'GET', 'path' => '{code}/third', 'action' => 'third'], + 'skipped' => ['method' => 'GET', 'path' => 'skipped', 'action' => 'skipped'], + ], + ]; + $custom = $plain; + $custom['map']['first']['patterns'] = ['code' => '[0-9]+']; + $custom['map']['view']['pass'] = []; + + $expected = array_map( + fn(array $route): string => $route[0], + $this->connect(RouteBuilder::class, $plain, true), + ); + $routes = $this->connect(ApiRouteBuilder::class, $custom, true); + + $this->assertSame($expected, array_map(fn(array $route): string => $route[0], $routes)); + // in parse order: longest static path first, then connection order + $this->assertSame([ + '/articles/second', + '/articles/first/{code}', + '/articles/{id}', + '/articles/{code}/third', + '/articles/{article_id}/comments', + '/articles/{article_id}/comments', + '/articles/{article_id}/comments/{id}', + '/articles/{article_id}/comments/{id}', + '/articles/{article_id}/comments/{id}', + '/articles', + ], $expected); + $this->assertSame('[0-9]+', $routes[1][2]['code']); + $this->assertSame([], $routes[2][2]['pass']); + $this->assertSame(['id'], $routes[3][2]['pass']); + } +} diff --git a/tests/TestCase/Service/Action/ActionTest.php b/tests/TestCase/Service/Action/ActionTest.php index f5c2f9f4..9ba8f2ef 100644 --- a/tests/TestCase/Service/Action/ActionTest.php +++ b/tests/TestCase/Service/Action/ActionTest.php @@ -2,20 +2,39 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; +use ArrayIterator; +use Cake\Event\EventInterface; +use Cake\Event\EventManager; +use Cake\Http\ServerRequest; +use Cake\ORM\Entity; +use Cake\ORM\ResultSet; +use CakeDC\Api\Exception\ValidationException; +use CakeDC\Api\Service\Action\Action; +use CakeDC\Api\Service\Action\DummyAction; +use CakeDC\Api\Service\Action\Extension\CorsExtension; +use CakeDC\Api\Service\Action\ExtensionRegistry; +use CakeDC\Api\Service\FallbackService; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; +use CakeDC\Api\Test\TestCase\Transformer\TestTransformer; use CakeDC\Api\TestSuite\TestCase; +use CakeDC\Api\Transformer\TransformerInterface; +use Exception; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\DataProvider; +use ReflectionMethod; +use stdClass; class ActionTest extends TestCase { @@ -86,4 +105,375 @@ public function testActionCallOnProcess(): void $result = $action->process(); $this->assertEquals(true, $result); } + + /** + * Calls the protected Action::transform() on a plain action. + */ + private function callTransform(mixed $data, string $transformerClass): array + { + $service = new FallbackService([ + 'service' => 'articles', + 'request' => new ServerRequest(), + ]); + $action = new DummyAction(['service' => $service, 'name' => 'dummy']); + + return (new ReflectionMethod($action, 'transform'))->invoke($action, $data, $transformerClass); + } + + /** + * An unknown transformer class is rejected. + */ + public function testTransformMissingClass(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Transformer class App\\Transformer\\MissingTransformer does not exist'); + $this->callTransform(['id' => 1], 'App\\Transformer\\MissingTransformer'); + } + + /** + * A class that does not implement TransformerInterface is rejected. + */ + public function testTransformClassNotImplementingInterface(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf( + 'Transformer class %s must implement %s', + stdClass::class, + TransformerInterface::class, + )); + $this->callTransform(['id' => 1], stdClass::class); + } + + /** + * A single entity is transformed as one item. + */ + public function testTransformEntity(): void + { + $result = $this->callTransform(new Entity(['id' => 3, 'title' => 'x']), TestTransformer::class); + $this->assertSame(['id' => 3], $result); + } + + /** + * An associative array (e.g. a JOIN row) is transformed as one item. + */ + public function testTransformAssociativeArray(): void + { + $result = $this->callTransform(['id' => 4, 'title' => 'x'], TestTransformer::class); + $this->assertSame(['id' => 4], $result); + } + + /** + * A list array is transformed item by item. + */ + public function testTransformListArray(): void + { + $result = $this->callTransform([['id' => 1], new Entity(['id' => 2])], TestTransformer::class); + $this->assertSame([['id' => 1], ['id' => 2]], $result); + } + + /** + * An empty list is an empty collection, not a single empty item. + */ + public function testTransformEmptyArray(): void + { + $this->assertSame([], $this->callTransform([], TestTransformer::class)); + } + + /** + * A ResultSet is transformed item by item. + */ + public function testTransformResultSet(): void + { + $resultSet = new ResultSet([new Entity(['id' => 5]), new Entity(['id' => 6])]); + $result = $this->callTransform($resultSet, TestTransformer::class); + $this->assertSame([['id' => 5], ['id' => 6]], $result); + } + + /** + * Any other iterable is transformed item by item. + */ + public function testTransformIterable(): void + { + $iterator = new ArrayIterator([new Entity(['id' => 7]), ['id' => 8]]); + $result = $this->callTransform($iterator, TestTransformer::class); + $this->assertSame([['id' => 7], ['id' => 8]], $result); + } + + /** + * Paginated results keep the pagination metadata and only the data items are transformed. + */ + public function testTransformPaginatedResult(): void + { + $pagination = ['page' => 1, 'limit' => 2, 'count' => 10]; + $data = [ + 'data' => [new Entity(['id' => 1, 'title' => 'a']), new Entity(['id' => 2, 'title' => 'b'])], + 'pagination' => $pagination, + ]; + $result = $this->callTransform($data, TestTransformer::class); + $this->assertSame([ + 'data' => [['id' => 1], ['id' => 2]], + 'pagination' => $pagination, + ], $result); + } + + /** + * Builds a service for a GET request with the given query. + */ + private function getService(array $query = []): FallbackService + { + return new FallbackService([ + 'service' => 'articles', + 'request' => new ServerRequest(['query' => $query, 'environment' => ['REQUEST_METHOD' => 'GET']]), + ]); + } + + /** + * Records the names of the events the action dispatches. + * + * @param \CakeDC\Api\Service\Action\Action $action Action. + * @param array $names Event names. + * @param array $dispatched Receives the dispatched names. + * @return void + */ + private function recordEvents(Action $action, array $names, array &$dispatched): void + { + foreach ($names as $name) { + $action->getEventManager()->on($name, function () use ($name, &$dispatched): void { + $dispatched[] = $name; + }); + } + } + + /** + * An event manager given in the config is used by the action. + */ + public function testEventManagerFromConfig(): void + { + $eventManager = new EventManager(); + $action = new DummyAction(['service' => $this->getService(), 'eventManager' => $eventManager]); + $this->assertSame($eventManager, $action->getEventManager()); + } + + /** + * @return array}> + */ + public static function stoppedEventProvider(): array + { + return [ + 'beforeProcess' => ['Action.beforeProcess', []], + 'onAuth' => ['Action.onAuth', []], + 'beforeValidate' => ['Action.beforeValidate', ['Action.beforeValidateStopped']], + 'beforeExecute' => ['Action.beforeExecute', ['Action.beforeExecuteStopped']], + ]; + } + + /** + * A listener that stops a life cycle event ends the processing with the event result. + */ + #[DataProvider('stoppedEventProvider')] + public function testProcessStoppedByEvent(string $eventName, array $expectedStoppedEvents): void + { + $action = new class (['service' => $this->getService(), 'name' => 'stopped']) extends Action { + public bool $executed = false; + + public function execute(): mixed + { + $this->executed = true; + + return 'executed'; + } + }; + $action->getEventManager()->on($eventName, ['priority' => 1], function (EventInterface $event): void { + $event->stopPropagation(); + $event->setResult('stopped'); + }); + $dispatched = []; + $this->recordEvents( + $action, + ['Action.beforeValidateStopped', 'Action.beforeExecuteStopped', 'Action.afterProcess'], + $dispatched, + ); + + $this->assertSame('stopped', $action->process()); + $this->assertFalse($action->executed); + $this->assertSame($expectedStoppedEvents, $dispatched); + } + + /** + * A failed validation dispatches validationFailed and throws. + */ + public function testProcessValidationFailed(): void + { + $action = new class (['service' => $this->getService(), 'name' => 'invalid']) extends Action { + public function validates(): bool + { + return false; + } + + public function execute(): mixed + { + throw new Exception('execute should not be called'); + } + }; + $dispatched = []; + $this->recordEvents($action, ['Action.validationFailed'], $dispatched); + + try { + $action->process(); + $this->fail('ValidationException was expected'); + } catch (ValidationException $validationException) { + $this->assertSame('Validation failed', $validationException->getMessage()); + $this->assertSame([], $validationException->getValidationErrors()); + } + $this->assertSame(['Action.validationFailed'], $dispatched); + } + + /** + * Builds an action whose action() method receives the request params as arguments. + */ + private function paramsAction(array $query): Action + { + return new class (['service' => $this->getService($query), 'name' => 'params']) extends Action { + public function execute(): mixed + { + throw new Exception('execute should not be called'); + } + + public function action(int $id, string $mode = 'full', ?string $tag = null): array + { + return ['id' => $id, 'mode' => $mode, 'tag' => $tag]; + } + }; + } + + /** + * Numeric params are cast, and missing or empty optional params use the default value. + */ + public function testProcessPassesParamsToActionMethod(): void + { + $action = $this->paramsAction(['id' => '5', 'mode' => '']); + $this->assertSame(['id' => 5, 'mode' => 'full', 'tag' => null], $action->process()); + + $action = $this->paramsAction(['id' => '6', 'mode' => 'short', 'tag' => 'news']); + $this->assertSame(['id' => 6, 'mode' => 'short', 'tag' => 'news'], $action->process()); + } + + /** + * A missing required param of the action() method is a 409 error. + */ + public function testProcessMissingRequiredActionParam(): void + { + $this->expectException(Exception::class); + $this->expectExceptionMessage('Missing required param: id'); + $this->expectExceptionCode(409); + $this->paramsAction(['mode' => 'short'])->process(); + } + + /** + * Life cycle callbacks defined on the action are registered as listeners. + */ + public function testLifeCycleCallbacksAreImplementedEvents(): void + { + $action = new class (['service' => $this->getService(), 'name' => 'callbacks']) extends Action { + public array $calls = []; + + public function beforeProcess(EventInterface $event): void + { + $this->calls[] = 'beforeProcess'; + } + + public function afterProcess(EventInterface $event): void + { + $this->calls[] = 'afterProcess:' . $event->getData('result'); + } + + public function execute(): mixed + { + $this->calls[] = 'execute'; + + return 'done'; + } + }; + $this->assertSame( + ['Action.beforeProcess' => 'beforeProcess', 'Action.afterProcess' => 'afterProcess'], + $action->implementedEvents(), + ); + $this->assertSame('done', $action->process()); + $this->assertSame(['beforeProcess', 'execute', 'afterProcess:done'], $action->calls); + } + + /** + * An extension registry can replace the one built by the constructor. + */ + public function testSetExtensionsReplacesRegistry(): void + { + $action = new DummyAction(['service' => $this->getService()]); + $this->assertInstanceOf(ExtensionRegistry::class, $action->getExtensions()); + $registry = new ExtensionRegistry($action); + $this->assertSame($action, $action->setExtensions($registry)); + $this->assertSame($registry, $action->getExtensions()); + } + + /** + * Setting no registry keeps the registry the action already has. + */ + public function testSetExtensionsWithoutRegistryKeepsTheCurrentOne(): void + { + $action = new DummyAction(['service' => $this->getService()]); + $registry = $action->getExtensions(); + $this->assertSame($action, $action->setExtensions()); + $this->assertSame($registry, $action->getExtensions()); + } + + /** + * An extension configured as false is not loaded. + */ + public function testDisabledExtensionIsNotLoaded(): void + { + $action = new DummyAction([ + 'service' => $this->getService(), + 'Extension' => ['CakeDC/Api.Cors' => false], + ]); + $this->assertSame([], $action->extensions); + $this->assertSame([], $action->getExtensions()->loaded()); + } + + /** + * An attachable extension is also set as an action property named after it. + */ + public function testAttachableExtensionIsSetOnAction(): void + { + $action = new class ([ + 'service' => $this->getService(), + 'Extension' => ['CakeDC/Api.Cors' => ['attachable' => true]], + ]) extends DummyAction { + public ?CorsExtension $Cors = null; + }; + $this->assertInstanceOf(CorsExtension::class, $action->Cors); + $this->assertSame($action->getExtensions()->get('Cors'), $action->Cors); + } + + /** + * A stock action takes an attachable extension without a dynamic property deprecation. + */ + public function testAttachableExtensionOnAStockAction(): void + { + $deprecations = []; + set_error_handler(function (int $level, string $message) use (&$deprecations): bool { + $deprecations[] = $message; + + return true; + }, E_DEPRECATED); + try { + $action = new DummyAction([ + 'service' => $this->getService(), + 'Extension' => ['CakeDC/Api.Cors' => ['attachable' => true]], + ]); + } finally { + restore_error_handler(); + } + + $this->assertSame([], $deprecations); + $this->assertSame($action->getExtensions()->get('Cors'), $action->Cors); + } } diff --git a/tests/TestCase/Service/Action/Auth/AuthActionTrait.php b/tests/TestCase/Service/Action/Auth/AuthActionTrait.php new file mode 100644 index 00000000..c2a4d26d --- /dev/null +++ b/tests/TestCase/Service/Action/Auth/AuthActionTrait.php @@ -0,0 +1,66 @@ + $headers Request headers. + * @return \CakeDC\Api\Service\Action\Action + */ + protected function authAction( + string $name, + array $data = [], + string $method = 'POST', + mixed $identity = null, + array $headers = [], + ): Action { + $request = new ServerRequest([ + 'url' => '/api/auth/' . $name, + 'params' => ['service' => 'auth', 'pass' => [$name]], + 'environment' => ['REQUEST_METHOD' => $method, 'HTTP_HOST' => 'localhost'], + $method === 'GET' ? 'query' : 'post' => $data, + ]); + foreach ($headers as $header => $value) { + $request = $request->withHeader($header, $value); + } + if ($identity !== null) { + $request = $request->withAttribute('identity', $identity); + } + $service = ServiceRegistry::getServiceLocator()->get('auth', [ + 'version' => null, + 'service' => 'auth', + 'request' => $request, + 'response' => new Response(), + 'baseUrl' => '/auth/' . $name, + 'refresh' => true, + ]); + + return $service->buildAction(); + } +} diff --git a/tests/TestCase/Service/Action/Auth/LoginActionTest.php b/tests/TestCase/Service/Action/Auth/LoginActionTest.php new file mode 100644 index 00000000..31b68673 --- /dev/null +++ b/tests/TestCase/Service/Action/Auth/LoginActionTest.php @@ -0,0 +1,83 @@ + ['REQUEST_METHOD' => 'POST'], + 'post' => ['username' => 'user-1', 'password' => '12345'], + ]); + $action = new LoginAction([ + 'service' => new FallbackService(['service' => 'auth', 'request' => $request]), + 'name' => 'login', + 'identifiedField' => 'email', + 'passwordField' => 'secret_password', + ]); + + try { + $action->validates(); + $this->fail('ValidationException was expected'); + } catch (ValidationException $validationException) { + $this->assertSame('Validation failed', $validationException->getMessage()); + $this->assertSame(['email', 'secret_password'], array_keys($validationException->getValidationErrors())); + } + } + + /** + * Blank credentials fail the validation. + */ + public function testBlankCredentialsFailValidation(): void + { + $action = $this->authAction('login', ['username' => '', 'password' => '']); + $this->assertInstanceOf(LoginAction::class, $action); + + $this->expectException(ValidationException::class); + $action->validates(); + } + + /** + * An identity whose data is an ArrayAccess object (e.g. a JWT payload) is returned as an array. + */ + public function testArrayAccessIdentityIsReturnedAsArray(): void + { + $payload = ['id' => '00000000-0000-0000-0000-000000000001', 'username' => 'user-1']; + $request = (new ServerRequest(['environment' => ['REQUEST_METHOD' => 'POST']])) + ->withAttribute('identity', new Identity(new ArrayObject($payload))); + $action = new LoginAction([ + 'service' => new FallbackService(['service' => 'auth', 'request' => $request]), + 'name' => 'login', + ]); + + $this->assertSame($payload, $action->execute()); + } +} diff --git a/tests/TestCase/Service/Action/Auth/OtpVerifyActionTest.php b/tests/TestCase/Service/Action/Auth/OtpVerifyActionTest.php new file mode 100644 index 00000000..6b812157 --- /dev/null +++ b/tests/TestCase/Service/Action/Auth/OtpVerifyActionTest.php @@ -0,0 +1,187 @@ +clear(); + Configure::delete('OneTimePasswordAuthenticator'); + unset($this->request, $this->response); + parent::tearDown(); + } + + /** + * Builds the otp_verify action of the auth service. + * + * @return \CakeDC\Api\Service\Action\Auth\OtpVerifyGetAction + */ + protected function getAction(): OtpVerifyGetAction + { + $this->_initializeRequest([ + 'params' => [ + 'service' => 'auth', + 'pass' => ['otp_verify'], + ], + ], 'GET'); + $service = ServiceRegistry::getServiceLocator()->get('auth', [ + 'version' => null, + 'service' => 'auth', + 'request' => $this->request, + 'response' => $this->response, + 'baseUrl' => '/auth/otp_verify', + ]); + $action = $service->buildAction(); + $this->assertInstanceOf(OtpVerifyGetAction::class, $action); + + return $action; + } + + public function testDefaultUsersConfig(): void + { + $action = $this->getAction(); + + $secret = $action->createSecret(); + $this->assertNotEmpty($secret); + $this->assertStringStartsWith('data:image/', $action->getQRCodeImageAsDataUri('user@example.com', $secret)); + $this->assertTrue($action->verifyCode($secret, $action->tfa->getCode($secret))); + } + + public function testStringAlgorithm(): void + { + Configure::write('OneTimePasswordAuthenticator.algorithm', 'SHA256'); + $action = $this->getAction(); + + $secret = $action->createSecret(); + $sha256 = new TwoFactorAuth( + qrcodeprovider: Configure::read('OneTimePasswordAuthenticator.qrcodeprovider'), + algorithm: Algorithm::Sha256, + ); + $this->assertSame($sha256->getCode($secret, 1000000), $action->tfa->getCode($secret, 1000000)); + $this->assertTrue($action->verifyCode($secret, $action->tfa->getCode($secret))); + } + + public function testMissingQrCodeProvider(): void + { + Configure::write('OneTimePasswordAuthenticator.qrcodeprovider'); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('An error has occurred configuring OneTimePasswordAuthenticator'); + try { + $this->getAction(); + } catch (RuntimeException $runtimeException) { + // the inner TypeError text (types, file paths) is logged, not returned to the client + $this->assertStringNotContainsString('must be of type', $runtimeException->getMessage()); + $this->assertStringContainsString('qrcodeprovider is set', $runtimeException->getMessage()); + throw $runtimeException; + } + } + + /** + * Builds the otp_verify action for user-1, whose fixture secret is not verified yet. + * + * @param array $fields Fields to set on the identity. + * @return \CakeDC\Api\Service\Action\Auth\OtpVerifyGetAction + */ + protected function getActionFor(array $fields = []): OtpVerifyGetAction + { + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->get(self::USER_ID); + $user->patch($fields); + // the WebAuthn store used to check for another factor is keyed by the bearer token + $action = $this->authAction('otp_verify', [], 'GET', $user, ['Authorization' => 'Bearer otp-test-token']); + $this->assertInstanceOf(OtpVerifyGetAction::class, $action); + + return $action; + } + + public function testUnverifiedSecretIsReused(): void + { + $result = $this->getActionFor(['secret' => 'JBSWY3DPEHPK3PXP'])->execute(); + + $this->assertFalse($result['verified']); + $this->assertSame('JBSWY3DPEHPK3PXP', $result['secret']); + $this->assertStringStartsWith('data:image/', $result['secretDataUri']); + $stored = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->get(self::USER_ID); + $this->assertSame('yyy', $stored->get('secret'), 'the existing secret is not replaced'); + } + + public function testSecretStoreFailureIsReportedGenerically(): void + { + $action = $this->getActionFor(['secret' => null]); + $action->setUsersTable(new class (['alias' => 'Users', 'table' => 'users']) extends UsersTable { + public function updateQuery(): UpdateQuery + { + throw new DatabaseException('SQLSTATE[HY000]: database is locked'); + } + }); + + try { + $action->execute(); + $this->fail('An exception was expected'); + } catch (Exception $exception) { + $this->assertSame('Could not verify, please try again', $exception->getMessage()); + $this->assertStringNotContainsString('SQLSTATE', $exception->getMessage()); + } + } +} diff --git a/tests/TestCase/Service/Action/Auth/RegisterActionTest.php b/tests/TestCase/Service/Action/Auth/RegisterActionTest.php new file mode 100644 index 00000000..57b8b8ee --- /dev/null +++ b/tests/TestCase/Service/Action/Auth/RegisterActionTest.php @@ -0,0 +1,148 @@ +connect('/users/validate-email/*', [ + 'plugin' => 'CakeDC/Users', + 'controller' => 'Users', + 'action' => 'validateEmail', + ]); + } + + /** + * Registration data that passes the register validation. + * + * @param string $username Username. + * @return array + */ + protected function registration(string $username): array + { + return [ + 'username' => $username, + 'email' => $username . '@example.com', + 'password' => '12345678', + 'password_confirm' => '12345678', + 'first_name' => 'First', + 'last_name' => 'Last', + 'tos' => true, + ]; + } + + /** + * Counts the users with the given username. + */ + protected function countUsers(string $username): int + { + return TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->find()->where(['username' => $username])->count(); + } + + /** + * A beforeRegister listener can provide the data of the user to register. + */ + public function testBeforeRegisterEntityIsRegistered(): void + { + $action = $this->authAction('register', $this->registration('request-user')); + $this->assertInstanceOf(RegisterAction::class, $action); + $action->getEventManager()->on(Plugin::EVENT_BEFORE_REGISTER, function (EventInterface $event): void { + if ($event->getData('userEntity') !== null) { + $event->setResult(new Entity($this->registration('event-user'))); + } + }); + + $user = $action->execute(); + + $this->assertSame('event-user', $user['username']); + $this->assertSame('You have registered successfully, please log in', $user['message']); + $this->assertSame(1, $this->countUsers('event-user')); + $this->assertSame(0, $this->countUsers('request-user')); + } + + /** + * The saved user goes to afterRegister listeners, not to beforeRegister listeners again. + */ + public function testAfterRegisterReceivesTheSavedUser(): void + { + $action = $this->authAction('register', $this->registration('after-user')); + $calls = ['before' => 0, 'after' => []]; + $action->getEventManager()->on(Plugin::EVENT_BEFORE_REGISTER, function () use (&$calls): void { + $calls['before']++; + }); + $action->getEventManager()->on(Plugin::EVENT_AFTER_REGISTER, function (EventInterface $event) use (&$calls): void { + $calls['after'][] = $event->getData('user')->get('username'); + }); + + $user = $action->execute(); + + $this->assertSame('after-user', $user['username']); + $this->assertSame(1, $calls['before']); + $this->assertSame(['after-user'], $calls['after']); + } + + /** + * A beforeRegister listener that stops the event cancels the registration. + */ + public function testStoppedBeforeRegisterCancelsRegistration(): void + { + $action = $this->authAction('register', $this->registration('stopped-user')); + $action->getEventManager()->on(Plugin::EVENT_BEFORE_REGISTER, function (EventInterface $event): void { + $event->stopPropagation(); + }); + + $this->assertFalse($action->execute()); + $this->assertSame(0, $this->countUsers('stopped-user')); + } + + /** + * Data the users table cannot save is reported with the entity errors. + */ + public function testUnsavedUserThrowsValidationException(): void + { + $data = $this->registration('invalid-user'); + $data['password_confirm'] = 'different'; + $action = $this->authAction('register', $data); + + try { + $action->execute(); + $this->fail('ValidationException was expected'); + } catch (ValidationException $validationException) { + $this->assertSame('The user could not be saved', $validationException->getMessage()); + $errors = $validationException->getValidationErrors(); + $this->assertArrayHasKey('password_confirm_check', $errors['password'] ?? []); + } + $this->assertSame(0, $this->countUsers('invalid-user')); + } +} diff --git a/tests/TestCase/Service/Action/Auth/ResetPasswordActionTest.php b/tests/TestCase/Service/Action/Auth/ResetPasswordActionTest.php new file mode 100644 index 00000000..bc306868 --- /dev/null +++ b/tests/TestCase/Service/Action/Auth/ResetPasswordActionTest.php @@ -0,0 +1,120 @@ +authAction('reset_password', [ + 'token' => self::TOKEN, + 'password' => 'new-password', + 'password_confirm' => 'new-password', + ]); + $this->assertInstanceOf(ResetPasswordAction::class, $action); + $this->assertTrue($action->validates()); + + return $action; + } + + /** + * Replaces the Password behavior of the users table with a mock. + */ + protected function mockChangePassword(): PasswordBehavior + { + $behavior = $this->createMock(PasswordBehavior::class); + TableRegistry::getTableLocator()->get(Configure::read('Users.table'))->behaviors()->set('Password', $behavior); + + return $behavior; + } + + /** + * Runs the action and returns the exception it throws. + */ + protected function failure(ResetPasswordAction $action): Exception + { + try { + $action->execute(); + } catch (Exception $exception) { + return $exception; + } + $this->fail('An exception was expected'); + } + + /** + * A password the users table does not save is a 500. + */ + public function testUnsavedPasswordIsAServerError(): void + { + $this->mockChangePassword() + ->expects($this->once()) + ->method('changePassword') + ->with($this->callback(fn(EntityInterface $user): bool => $user->get('id') === self::USER_ID)) + ->willReturn(false); + + $exception = $this->failure($this->action()); + + $this->assertSame('Password could not be changed', $exception->getMessage()); + $this->assertSame(500, $exception->getCode()); + $this->assertSame('Password could not be changed', $exception->getPrevious()->getMessage()); + } + + /** + * A user removed after the token was validated is a 404. + */ + public function testUserNotFoundOnPasswordChangeIsA404(): void + { + $cause = new UserNotFoundException('User not found'); + $this->mockChangePassword() + ->expects($this->once()) + ->method('changePassword') + ->willThrowException($cause); + + $exception = $this->failure($this->action()); + + $this->assertSame('User was not found', $exception->getMessage()); + $this->assertSame(404, $exception->getCode()); + $this->assertSame($cause, $exception->getPrevious()); + } +} diff --git a/tests/TestCase/Service/Action/Auth/ResetPasswordRequestActionTest.php b/tests/TestCase/Service/Action/Auth/ResetPasswordRequestActionTest.php new file mode 100644 index 00000000..fe4a3cad --- /dev/null +++ b/tests/TestCase/Service/Action/Auth/ResetPasswordRequestActionTest.php @@ -0,0 +1,126 @@ +authAction('reset_password_request', ['reference' => $reference]); + $this->assertInstanceOf(ResetPasswordRequestAction::class, $action); + + return $action; + } + + /** + * Replaces the Password behavior of the users table with a mock. + */ + protected function mockPasswordBehavior(): PasswordBehavior + { + $behavior = $this->createMock(PasswordBehavior::class); + TableRegistry::getTableLocator()->get(Configure::read('Users.table'))->behaviors()->set('Password', $behavior); + + return $behavior; + } + + /** + * Runs the action and returns the exception it throws. + */ + protected function failure(ResetPasswordRequestAction $action): Exception + { + try { + $action->execute(); + } catch (Exception $exception) { + return $exception; + } + $this->fail('An exception was expected'); + } + + /** + * An inactive user gets a 404 when the configuration requires an active account. + */ + public function testInactiveUserIsRejectedWhenActiveAccountIsRequired(): void + { + Configure::write('Users.Registration.ensureActive', true); + $users = TableRegistry::getTableLocator()->get(Configure::read('Users.table')); + $token = $users->find()->where(['username' => 'user-3'])->firstOrFail()->get('token'); + + $exception = $this->failure($this->action('user-3')); + + $this->assertSame('The user is not active', $exception->getMessage()); + $this->assertSame(404, $exception->getCode()); + $this->assertSame($token, $users->find()->where(['username' => 'user-3'])->firstOrFail()->get('token')); + } + + /** + * When no token is generated the client gets a generic 500. + */ + public function testNoTokenGeneratedIsAServerError(): void + { + $this->mockPasswordBehavior() + ->expects($this->once()) + ->method('resetToken') + ->with('user-1', $this->callback(fn(array $options): bool => $options['type'] === 'password')) + ->willReturn(null); + + $exception = $this->failure($this->action('user-1')); + + $this->assertSame('Token could not be reset', $exception->getMessage()); + $this->assertSame(500, $exception->getCode()); + $this->assertSame( + 'The password token could not be generated. Please try again', + $exception->getPrevious()->getMessage(), + ); + } + + /** + * Any other failure is a generic 500 that keeps the cause as the previous exception. + */ + public function testOtherFailureIsAServerError(): void + { + $cause = new RuntimeException('Mail transport is down'); + $this->mockPasswordBehavior() + ->expects($this->once()) + ->method('resetToken') + ->willThrowException($cause); + + $exception = $this->failure($this->action('user-1')); + + $this->assertSame('Token could not be reset', $exception->getMessage()); + $this->assertSame(500, $exception->getCode()); + $this->assertSame($cause, $exception->getPrevious()); + } +} diff --git a/tests/TestCase/Service/Action/Auth/SecondFactorTraitTest.php b/tests/TestCase/Service/Action/Auth/SecondFactorTraitTest.php new file mode 100644 index 00000000..08432b94 --- /dev/null +++ b/tests/TestCase/Service/Action/Auth/SecondFactorTraitTest.php @@ -0,0 +1,119 @@ +hasVerifiedOtp($identity); + } + + public function webauthn(mixed $identity): bool + { + return $this->hasWebauthnCredential($identity); + } + + public function refuse(bool $registered): void + { + $this->refuseEnrollmentIf($registered); + } + }; + } + + /** + * @return array + */ + public static function otpIdentityProvider(): array + { + return [ + 'array verified' => [['secret' => 'ABC', 'secret_verified' => true], true], + 'array not verified' => [['secret' => 'ABC', 'secret_verified' => false], false], + 'array without secret' => [['secret' => null, 'secret_verified' => true], false], + 'array without fields' => [['id' => 1], false], + 'entity verified' => [new Entity(['secret' => 'ABC', 'secret_verified' => true]), true], + 'entity not verified' => [new Entity(['secret' => 'ABC', 'secret_verified' => false]), false], + 'no identity' => [null, false], + ]; + } + + /** + * Only an identity with a secret that is also verified counts as an OTP factor. + */ + #[DataProvider('otpIdentityProvider')] + public function testHasVerifiedOtp(mixed $identity, bool $expected): void + { + $this->assertSame($expected, $this->subject()->otp($identity)); + } + + /** + * An identity with hidden secret fields is still read field by field. + */ + public function testHasVerifiedOtpReadsHiddenEntityFields(): void + { + $entity = new Entity(['secret' => 'ABC', 'secret_verified' => true]); + $entity->setHidden(['secret', 'secret_verified']); + $this->assertSame([], $entity->toArray()); + $this->assertTrue($this->subject()->otp($entity)); + } + + /** + * Without an identity there is no WebAuthn credential and no lookup is made. + */ + public function testNoWebauthnCredentialWithoutIdentity(): void + { + $this->assertFalse($this->subject()->webauthn(null)); + } + + /** + * Enrollment is refused only while another factor is registered. + */ + public function testRefuseEnrollmentIf(): void + { + $subject = $this->subject(); + $subject->refuse(false); + + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('Another second factor is already registered; verify with it instead'); + $subject->refuse(true); + } +} diff --git a/tests/TestCase/Service/Action/Collection/AddEditActionTest.php b/tests/TestCase/Service/Action/Collection/AddEditActionTest.php index 741d6758..da156862 100644 --- a/tests/TestCase/Service/Action/Collection/AddEditActionTest.php +++ b/tests/TestCase/Service/Action/Collection/AddEditActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action\Collection; @@ -18,6 +18,7 @@ use CakeDC\Api\Service\Action\Collection\AddEditAction; use CakeDC\Api\Service\FallbackService; use CakeDC\Api\Service\ServiceRegistry; +use CakeDC\Api\Test\App\Model\Table\ArticlesTable; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; @@ -34,7 +35,7 @@ class AddEditActionTest extends TestCase public $response; - public ?\CakeDC\Api\Service\Action\Collection\AddEditAction $Action = null; + public ?AddEditAction $Action = null; /** * setUp method @@ -82,7 +83,7 @@ public function testValidationPostNotArray(): void { $this->expectException(ValidationException::class); $this->_initializeAction( - ['title' => 'Article1'] + ['title' => 'Article1'], ); $this->Action->execute(); } @@ -200,6 +201,29 @@ public function testIntegrationArticlesCollection(): void $this->assertEquals(2, $finalCount - $initialCount, 'We should have added 3 new articles'); } + /** + * With a primary key given as a list every key field is accessible, so existing records are edited. + * + * @return void + */ + public function testExecuteWithPrimaryKeyList(): void + { + $table = TableRegistry::getTableLocator()->get('ArticlesKeyList', ['className' => ArticlesTable::class]); + $table->setPrimaryKey(['id']); + $this->assertSame(['id'], $table->getPrimaryKey()); + $initialCount = $table->find()->count(); + $this->_initializeAction([ + ['id' => 1, 'title' => 'First Article edited'], + ['title' => 'Article3'], + ]); + $this->Action->setTable($table); + + $this->Action->execute(); + + $this->assertSame(1, $table->find()->count() - $initialCount); + $this->assertSame('First Article edited', $table->get(1)->get('title')); + } + protected function _initializeAction($post = []): void { $this->_initializeRequest([ diff --git a/tests/TestCase/Service/Action/Collection/DeleteActionTest.php b/tests/TestCase/Service/Action/Collection/DeleteActionTest.php index fa450e16..8cb8926f 100644 --- a/tests/TestCase/Service/Action/Collection/DeleteActionTest.php +++ b/tests/TestCase/Service/Action/Collection/DeleteActionTest.php @@ -2,17 +2,18 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action\Collection; +use ArrayObject; use Cake\ORM\TableRegistry; use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Collection\DeleteAction; @@ -33,7 +34,7 @@ class DeleteActionTest extends TestCase public $response; - public ?\CakeDC\Api\Service\Action\Collection\DeleteAction $Action = null; + public ?DeleteAction $Action = null; /** * setUp method @@ -81,7 +82,7 @@ public function testValidationPostNotArray(): void { $this->expectException(ValidationException::class); $this->_initializeAction( - ['id' => 1] + ['id' => 1], ); $this->Action->execute(); } @@ -115,7 +116,7 @@ public function testExecuteValidationEntityNotValid(): void $this->expectExceptionMessage('Validation failed'); $this->_initializeAction([ ['not-id' => 'something'], - ['blank' => new \ArrayObject()], + ['blank' => new ArrayObject()], ]); $this->Action->execute(); diff --git a/tests/TestCase/Service/Action/Collection/SubclassCompatibilityTest.php b/tests/TestCase/Service/Action/Collection/SubclassCompatibilityTest.php new file mode 100644 index 00000000..8cc2a0eb --- /dev/null +++ b/tests/TestCase/Service/Action/Collection/SubclassCompatibilityTest.php @@ -0,0 +1,30 @@ +assertTrue(class_exists(UntypedCollectionAction::class)); + } +} diff --git a/tests/TestCase/Service/Action/CrudActionTest.php b/tests/TestCase/Service/Action/CrudActionTest.php new file mode 100644 index 00000000..1203b465 --- /dev/null +++ b/tests/TestCase/Service/Action/CrudActionTest.php @@ -0,0 +1,256 @@ +clear(); + parent::tearDown(); + } + + private function service(string $name = 'articles'): FallbackService + { + return new FallbackService([ + 'service' => $name, + 'request' => new ServerRequest(['environment' => ['REQUEST_METHOD' => 'GET']]), + ]); + } + + /** + * The id and its field name default to null and "id", and the table comes from the service. + */ + public function testDefaults(): void + { + $action = new CrudViewAction(['service' => $this->service()]); + $this->assertNull($action->getId()); + $this->assertSame('id', $action->getIdName()); + $this->assertSame('articles', $action->getTable()->getTable()); + } + + /** + * The id and its field name can be configured. + */ + public function testConfiguredIdAndIdName(): void + { + $action = new CrudViewAction([ + 'service' => $this->service(), + 'id' => '7', + 'idName' => 'article_id', + ]); + $this->assertSame('7', $action->getId()); + $this->assertSame('article_id', $action->getIdName()); + } + + /** + * The id is read from the routed request. + */ + public function testIdFromRoute(): void + { + $this->_initializeRequest(['params' => ['service' => 'articles']]); + $service = ServiceRegistry::getServiceLocator()->get('articles', [ + 'service' => 'articles', + 'request' => $this->request, + 'response' => $this->response, + 'baseUrl' => '/articles/3', + ]); + $action = $service->buildAction(); + $this->assertInstanceOf(CrudViewAction::class, $action); + $this->assertSame('3', $action->getId()); + $this->assertSame('id', $action->getIdName()); + } + + /** + * A table instance can be given in the config instead of the service table. + */ + public function testTableInstanceConfig(): void + { + $table = TableRegistry::getTableLocator()->get('Authors'); + $action = new CrudViewAction(['service' => $this->service(), 'table' => $table]); + $this->assertSame($table, $action->getTable()); + } + + /** + * A table name can be given in the config and is loaded from the table locator. + */ + public function testTableNameConfig(): void + { + $action = new CrudViewAction(['service' => $this->service(), 'table' => 'Authors']); + $this->assertSame(TableRegistry::getTableLocator()->get('Authors'), $action->getTable()); + } + + /** + * Calls a protected method of the action. + */ + private function invoke(CrudAction $action, string $method, mixed ...$args): mixed + { + return (new ReflectionMethod($action, $method))->invoke($action, ...$args); + } + + /** + * Builds a view action on an articles table with a custom finder, configured as the action finder. + */ + private function actionWithFinder(): CrudViewAction + { + $table = new class (['alias' => 'Articles', 'table' => 'articles']) extends ArticlesTable { + public function findFirstTwo(SelectQuery $query): SelectQuery + { + return $query->where(['Articles.id IN' => [1, 2]]); + } + }; + + return new CrudViewAction(['service' => $this->service(), 'table' => $table, 'finder' => 'firstTwo']); + } + + /** + * The configured finder is applied to the list query. + */ + public function testFinderAppliedToEntities(): void + { + $records = $this->invoke($this->actionWithFinder(), 'getEntities'); + $this->assertSame([1, 2], $records->extract('id')->toList()); + } + + /** + * The configured finder is applied to the single record query. + */ + public function testFinderAppliedToEntity(): void + { + $action = $this->actionWithFinder(); + $this->assertSame(2, $this->invoke($action, 'getEntity', 2)->get('id')); + + $this->expectException(RecordNotFoundException::class); + $this->invoke($action, 'getEntity', 3); + } + + /** + * An afterFindEntities listener can replace the found records. + */ + public function testAfterFindEntitiesResultReplacesRecords(): void + { + $action = new CrudViewAction(['service' => $this->service()]); + $replacement = new ResultSet([]); + $action->getEventManager()->on( + 'Action.Crud.afterFindEntities', + function (EventInterface $event) use ($replacement): void { + $this->assertGreaterThan(0, $event->getData('records')->count()); + $event->setResult($replacement); + }, + ); + $this->assertSame($replacement, $this->invoke($action, 'getEntities')); + } + + /** + * An afterFindEntity listener can replace the found record. + */ + public function testAfterFindEntityResultReplacesRecord(): void + { + $action = new CrudViewAction(['service' => $this->service()]); + $action->getEventManager()->on('Action.Crud.afterFindEntity', function (EventInterface $event): void { + $event->setResult(['id' => $event->getData('record')->get('id'), 'replaced' => true]); + }); + $this->assertSame(['id' => 1, 'replaced' => true], $this->invoke($action, 'getEntity', 1)); + } + + /** + * @return array + */ + public static function invalidPrimaryKeyProvider(): array + { + return [ + 'too many values' => [[1, 2], '[1, 2]'], + 'no value' => [null, '[NULL]'], + 'empty list' => [[], '[NULL]'], + ]; + } + + /** + * A primary key value that does not match the number of key columns is rejected. + */ + #[DataProvider('invalidPrimaryKeyProvider')] + public function testInvalidPrimaryKey(mixed $primaryKey, string $expected): void + { + $action = new CrudViewAction(['service' => $this->service()]); + $this->expectException(InvalidPrimaryKeyException::class); + $this->expectExceptionMessage('Record not found in table "articles" with primary key ' . $expected); + $this->invoke($action, 'getEntity', $primaryKey); + } + + /** + * Callable validation rules are left out of the description and callable params are nulled. + */ + public function testDescribeSkipsCallableValidationParts(): void + { + $table = TableRegistry::getTableLocator()->get('DescribeArticles', ['className' => ArticlesTable::class]); + $validator = new Validator(); + $validator + ->add('title', 'closureRule', ['rule' => fn($value): bool => true]) + // a pass list that happens to form a callable [class, method] pair + ->add('title', 'callablePass', ['rule' => ['inList', Validation::class, 'notBlank']]) + ->add('body', 'callableParam', [ + 'rule' => ['lengthBetween', fn(): int => 1, 10], + 'message' => 'Between 1 and 10', + ]); + $table->setValidator('default', $validator); + + $action = new CrudDescribeAction([ + 'service' => $this->service(), + 'table' => $table, + 'route' => [ + 'plugin' => null, + 'controller' => 'articles', + 'action' => 'describe', + '_method' => 'OPTIONS', + 'pass' => [], + 'map' => [], + '_matchedRoute' => '/articles', + ], + ]); + $result = $action->execute(); + + $this->assertSame(['callablePass'], array_keys($result['validators']['title']['rules'])); + $this->assertSame('inList', $result['validators']['title']['rules']['callablePass']['rule']); + $this->assertNull($result['validators']['title']['rules']['callablePass']['params']); + $this->assertSame([ + 'message' => 'Between 1 and 10', + 'on' => null, + 'rule' => 'lengthBetween', + 'params' => [null, 10], + 'last' => false, + ], $result['validators']['body']['rules']['callableParam']); + } +} diff --git a/tests/TestCase/Service/Action/CrudAddActionTest.php b/tests/TestCase/Service/Action/CrudAddActionTest.php index 399d8b4c..5710a003 100644 --- a/tests/TestCase/Service/Action/CrudAddActionTest.php +++ b/tests/TestCase/Service/Action/CrudAddActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; @@ -33,7 +33,7 @@ class CrudAddActionTest extends TestCase */ public $Service; - public ?\CakeDC\Api\Service\Action\CrudAddAction $Action = null; + public ?CrudAddAction $Action = null; /** * setUp method diff --git a/tests/TestCase/Service/Action/CrudDeleteActionTest.php b/tests/TestCase/Service/Action/CrudDeleteActionTest.php index 3ebd0c5d..4c5dcb08 100644 --- a/tests/TestCase/Service/Action/CrudDeleteActionTest.php +++ b/tests/TestCase/Service/Action/CrudDeleteActionTest.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; use Cake\Datasource\Exception\RecordNotFoundException; use CakeDC\Api\Service\Action\CrudDeleteAction; +use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; @@ -27,9 +28,9 @@ class CrudDeleteActionTest extends TestCase public $response; - public ?\CakeDC\Api\Service\Action\CrudDeleteAction $Action = null; + public ?CrudDeleteAction $Action = null; - protected ?\CakeDC\Api\Service\Service $Service = null; + protected ?Service $Service = null; /** * setUp method diff --git a/tests/TestCase/Service/Action/CrudEditActionTest.php b/tests/TestCase/Service/Action/CrudEditActionTest.php index eb03125a..2016439d 100644 --- a/tests/TestCase/Service/Action/CrudEditActionTest.php +++ b/tests/TestCase/Service/Action/CrudEditActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; @@ -34,7 +34,7 @@ class CrudEditActionTest extends TestCase public $response; - public ?\CakeDC\Api\Service\Action\CrudEditAction $Action = null; + public ?CrudEditAction $Action = null; /** * setUp method @@ -109,6 +109,43 @@ public function testExecuteNotFound(): void $this->Action->execute(); } + /** + * validates() rejects data that breaks the update validation rules. + * + * @return void + */ + public function testValidatesFailure(): void + { + $this->_initializeAction(1, [ + 'title' => '', + ]); + + try { + $this->Action->validates(); + $this->fail('ValidationException was expected'); + } catch (ValidationException $validationException) { + $this->assertSame('Validation failed', $validationException->getMessage()); + $this->assertSame( + ['title' => ['_empty' => 'This field cannot be left empty']], + $validationException->getValidationErrors(), + ); + } + } + + /** + * validates() accepts a partial update. + * + * @return void + */ + public function testValidatesSuccess(): void + { + $this->_initializeAction(1, [ + 'body' => 'Changed body', + ]); + + $this->assertTrue($this->Action->validates()); + } + protected function _initializeAction($id, $post = []): void { $this->_initializeRequest([ diff --git a/tests/TestCase/Service/Action/CrudIndexActionTest.php b/tests/TestCase/Service/Action/CrudIndexActionTest.php index 745820bf..ab0213e7 100644 --- a/tests/TestCase/Service/Action/CrudIndexActionTest.php +++ b/tests/TestCase/Service/Action/CrudIndexActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; @@ -25,7 +25,7 @@ class CrudIndexActionTest extends TestCase { use ConfigTrait; - public \CakeDC\Api\Service\Action\CrudIndexAction $Action; + public CrudIndexAction $Action; /** * setUp method diff --git a/tests/TestCase/Service/Action/CrudViewActionTest.php b/tests/TestCase/Service/Action/CrudViewActionTest.php index 264b539e..7262b00d 100644 --- a/tests/TestCase/Service/Action/CrudViewActionTest.php +++ b/tests/TestCase/Service/Action/CrudViewActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; @@ -33,7 +33,7 @@ class CrudViewActionTest extends TestCase */ public $Service; - public ?\CakeDC\Api\Service\Action\CrudViewAction $Action = null; + public ?CrudViewAction $Action = null; /** * setUp method diff --git a/tests/TestCase/Service/Action/DescribeActionTest.php b/tests/TestCase/Service/Action/DescribeActionTest.php index b83819ef..e07d2c5d 100644 --- a/tests/TestCase/Service/Action/DescribeActionTest.php +++ b/tests/TestCase/Service/Action/DescribeActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; @@ -36,7 +36,7 @@ class DescribeActionTest extends TestCase */ public $Service; - public ?\CakeDC\Api\Service\Action\DescribeAction $Action = null; + public ?DescribeAction $Action = null; /** * setUp method diff --git a/tests/TestCase/Service/Action/Extension/SortableHarness.php b/tests/TestCase/Service/Action/Extension/SortableHarness.php index 32b482c1..57aa9acf 100644 --- a/tests/TestCase/Service/Action/Extension/SortableHarness.php +++ b/tests/TestCase/Service/Action/Extension/SortableHarness.php @@ -2,19 +2,18 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action\Extension; use Cake\Core\InstanceConfigTrait; -use CakeDC\Api\Service\Action\Action; use CakeDC\Api\Service\Action\Extension\SortableTrait; /** @@ -24,7 +23,11 @@ class SortableHarness { use InstanceConfigTrait; use SortableTrait { - sortField as protected traitSortField; + sortField as public; + ignoredSortField as public; + logIgnoredSort as public; + logValue as public; + order as public; } /** @@ -41,14 +44,4 @@ public function __construct(array $config = []) { $this->setConfig($config); } - - /** - * @param \CakeDC\Api\Service\Action\Action|null $action Action instance. - * @param mixed $field Requested sort field. - * @return string|null - */ - public function sortField(?Action $action, mixed $field): ?string - { - return $this->traitSortField($action, $field); - } } diff --git a/tests/TestCase/Service/Action/Extension/SortableTraitTest.php b/tests/TestCase/Service/Action/Extension/SortableTraitTest.php index 7a5ac3ef..c7ec7ee7 100644 --- a/tests/TestCase/Service/Action/Extension/SortableTraitTest.php +++ b/tests/TestCase/Service/Action/Extension/SortableTraitTest.php @@ -2,20 +2,24 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action\Extension; +use Cake\Log\Log; +use Cake\ORM\Query\SelectQuery; use Cake\ORM\TableRegistry; use CakeDC\Api\Service\Action\CrudAction; +use CakeDC\Api\Service\Action\Extension\SortExtension; use CakeDC\Api\TestSuite\TestCase; +use ErrorException; class SortableTraitTest extends TestCase { @@ -23,6 +27,18 @@ class SortableTraitTest extends TestCase 'plugin.CakeDC/Api.Users', ]; + protected function setUp(): void + { + parent::setUp(); + Log::setConfig('sortable_test', ['className' => 'Array', 'scopes' => ['api'], 'levels' => ['debug']]); + } + + protected function tearDown(): void + { + Log::drop('sortable_test'); + parent::tearDown(); + } + public function testWithoutTableEmptySortableFieldsRejectsEverything(): void { // an action that is not a CrudAction has no table columns to fall back to @@ -49,6 +65,120 @@ public function testNonStringFieldIsRejected(): void $this->assertNull($harness->sortField(null, null)); } + public function testIgnoredSortIsLoggedAsOneJsonLine(): void + { + $harness = new SortableHarness(); + $harness->logIgnoredSort([$harness->ignoredSortField("last_name\ninjected"), $harness->ignoredSortField('bogus')]); + + $logs = Log::engine('sortable_test')->read(); + $this->assertCount(1, $logs); + // JSON keeps the request's newline out of the log line + $this->assertStringContainsString('ignored sort field "last_name\\ninjected", sort field "bogus".', $logs[0]); + $this->assertStringNotContainsString("\ninjected", $logs[0]); + $this->assertStringContainsString('sortableFields', $logs[0]); + } + + public function testLongIgnoredListIsCapped(): void + { + $harness = new SortableHarness(); + $harness->logIgnoredSort(array_map(fn(int $i): string => $harness->ignoredSortField('f' . $i), range(1, 15))); + + $logs = Log::engine('sortable_test')->read(); + $this->assertCount(1, $logs); + $this->assertStringContainsString('sort field "f10", 5 more.', $logs[0]); + $this->assertStringNotContainsString('"f11"', $logs[0]); + } + + public function testTenIgnoredEntriesAreAllListed(): void + { + // the list is cut only when it has more than ten entries + $harness = new SortableHarness(); + $harness->logIgnoredSort(array_map(fn(int $i): string => $harness->ignoredSortField('f' . $i), range(1, 10))); + + $logs = Log::engine('sortable_test')->read(); + $this->assertCount(1, $logs); + $this->assertStringContainsString('sort field "f9", sort field "f10".', $logs[0]); + $this->assertStringNotContainsString(' more', $logs[0]); + } + + public function testLogValueKeepsSlashesAndReplacesBytesThatAreNotUtf8(): void + { + $harness = new SortableHarness(); + $this->assertSame('"Authors/last_name"', $harness->logValue('Authors/last_name')); + // a value that is not UTF-8 is still logged, with the bad byte replaced + $this->assertSame('"a\\ufffdb"', $harness->logValue("a\xffb")); + $this->assertSame('["title"]', $harness->logValue(['title'])); + } + + public function testLogValueIsCutAfterTwoHundredCharacters(): void + { + $harness = new SortableHarness(); + // 198 letters and the two quotes of the JSON string are exactly 200 characters: not cut + $this->assertSame('"' . str_repeat('a', 198) . '"', $harness->logValue(str_repeat('a', 198))); + // one character more: the first 200 characters and three dots + $this->assertSame('"' . str_repeat('a', 199) . '...', $harness->logValue(str_repeat('a', 199))); + $this->assertSame('"' . str_repeat('a', 199) . '...', $harness->logValue(str_repeat('a', 250))); + } + + public function testOrderWithoutAnOrderSettingLeavesTheQueryAlone(): void + { + // the harness has no `order` setting at all, as an extension of an application may not + $harness = new SortableHarness(); + $query = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->find(); + + // a PHP warning, such as a loop over a missing setting, fails the test + set_error_handler(static function (int $code, string $message): never { + throw new ErrorException($message, 0, $code); + }); + try { + $harness->order($query, [], null); + } finally { + restore_error_handler(); + } + $this->assertNull($query->clause('order')); + + $harness->order($query, ['Users.username' => 'desc'], null); + $this->assertNotNull($query->clause('order')); + } + + public function testHelpersCanBeUsedByASubclassOfAnExtension(): void + { + // the helpers are protected: an extension of an application that extends Sort builds on them + $extension = new class extends SortExtension { + /** + * No registry is needed for this check. + */ + public function __construct() + { + } + + public function describe(SelectQuery $query): string + { + $this->order($query, ['Users.username' => 'asc'], null); + $this->logIgnoredSort([$this->ignoredSortField('bogus')]); + + return $this->logValue('bogus'); + } + }; + $query = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->find(); + + $this->assertSame('"bogus"', $extension->describe($query)); + $this->assertNotNull($query->clause('order')); + $logs = Log::engine('sortable_test')->read(); + $this->assertCount(1, $logs); + $this->assertStringContainsString('ignored sort field "bogus".', $logs[0]); + } + + public function testNothingIgnoredIsNotLogged(): void + { + $harness = new SortableHarness(['sortableFields' => ['first_name']]); + $harness->logIgnoredSort([]); + // resolving a field never logs; the extensions log once per request + $harness->sortField(null, 'bogus'); + + $this->assertSame([], Log::engine('sortable_test')->read()); + } + /** * A CrudAction whose table is the users plugin table, whose entity hides * the password and token columns. diff --git a/tests/TestCase/Service/Action/ExtensionRegistryTest.php b/tests/TestCase/Service/Action/ExtensionRegistryTest.php index ad850ac1..8c85a3a8 100644 --- a/tests/TestCase/Service/Action/ExtensionRegistryTest.php +++ b/tests/TestCase/Service/Action/ExtensionRegistryTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; diff --git a/tests/TestCase/Service/Action/ListActionTest.php b/tests/TestCase/Service/Action/ListActionTest.php index 9bd22b6e..467c997d 100644 --- a/tests/TestCase/Service/Action/ListActionTest.php +++ b/tests/TestCase/Service/Action/ListActionTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; @@ -36,7 +36,7 @@ class ListActionTest extends TestCase */ public $Service; - public ?\CakeDC\Api\Service\Action\ListAction $Action = null; + public ?ListAction $Action = null; /** * setUp method diff --git a/tests/TestCase/Service/Action/Recaptcha/ValidateActionTest.php b/tests/TestCase/Service/Action/Recaptcha/ValidateActionTest.php new file mode 100644 index 00000000..50ee296d --- /dev/null +++ b/tests/TestCase/Service/Action/Recaptcha/ValidateActionTest.php @@ -0,0 +1,90 @@ + '/recaptcha/validate', + 'environment' => [ + 'HTTP_HOST' => 'example.com', + 'REQUEST_METHOD' => 'POST', + ], + ]); + $service = new RecaptchaService([ + 'request' => $request, + 'response' => new Response(), + 'service' => 'recaptcha', + 'baseUrl' => '/recaptcha/validate', + ]); + + return new ValidateAction(['service' => $service, 'name' => 'validate']); + } + + protected function getReCaptchaInstance(ValidateAction $action): ?ReCaptcha + { + return (new ReflectionMethod($action, 'getReCaptchaInstance'))->invoke($action); + } + + public function testInstanceCreatedWhenSecretConfigured(): void + { + Configure::write('Api.reCaptcha.example$com', ['secret' => 'secret']); + $this->assertInstanceOf(ReCaptcha::class, $this->getReCaptchaInstance($this->buildAction())); + } + + public function testNoInstanceWithoutSecret(): void + { + Configure::write('Api.reCaptcha.example$com', ['disabled' => false]); + $this->assertNull($this->getReCaptchaInstance($this->buildAction())); + } + + public function testNoInstanceWithEmptySecret(): void + { + Configure::write('Api.reCaptcha.example$com', ['secret' => '']); + $this->assertNull($this->getReCaptchaInstance($this->buildAction())); + } + + public function testNoInstanceForOtherDomain(): void + { + Configure::write('Api.reCaptcha.other$com', ['secret' => 'secret']); + $this->assertNull($this->getReCaptchaInstance($this->buildAction())); + } + + public function testExecuteReturnsTrueWhenDisabled(): void + { + Configure::write('Api.reCaptcha.disabled', true); + $this->assertTrue($this->buildAction()->execute()); + } +} diff --git a/tests/TestCase/Service/Action/ResultTest.php b/tests/TestCase/Service/Action/ResultTest.php new file mode 100644 index 00000000..853e65f3 --- /dev/null +++ b/tests/TestCase/Service/Action/ResultTest.php @@ -0,0 +1,94 @@ +assertSame(200, $result->getCode()); + $this->assertNull($result->getData()); + $this->assertSame([], $result->getPayload()); + $this->assertNull($result->getException()); + } + + /** + * Constructor arguments set data and code. + */ + public function testConstructorSetsDataAndCode(): void + { + $result = new Result(['id' => 1], 201); + $this->assertSame(['id' => 1], $result->getData()); + $this->assertSame(201, $result->getCode()); + } + + /** + * setPayload replaces the whole payload, appendPayload adds a key, getPayload reads one key. + */ + public function testPayload(): void + { + $result = new Result(); + $result->appendPayload('links', ['self']); + $this->assertSame($result, $result->setPayload(['pagination' => ['page' => 1]])); + $this->assertSame(['pagination' => ['page' => 1]], $result->getPayload()); + $this->assertNull($result->getPayload('links')); + + $result->appendPayload('links', ['self']); + $this->assertSame(['self'], $result->getPayload('links')); + $this->assertSame(['page' => 1], $result->getPayload('pagination')); + $this->assertNull($result->getPayload('missing')); + } + + /** + * toArray and __debugInfo expose code, data and payload, without exception keys when none is set. + */ + public function testToArrayWithoutException(): void + { + $result = new Result(['id' => 1], 202); + $result->setPayload(['meta' => true]); + + $expected = [ + 'code' => 202, + 'data' => ['id' => 1], + 'payload' => ['meta' => true], + ]; + $this->assertSame($expected, $result->toArray()); + $this->assertSame($expected, $result->__debugInfo()); + } + + /** + * toArray adds the exception message and stack trace when an exception is set. + */ + public function testToArrayWithException(): void + { + $exception = new RuntimeException('Something failed'); + $result = new Result(); + $this->assertSame($result, $result->setException($exception)); + $this->assertSame($exception, $result->getException()); + + $info = $result->toArray(); + $this->assertSame(['code', 'data', 'payload', 'exception', 'exceptionStack'], array_keys($info)); + $this->assertSame('Something failed', $info['exception']); + $this->assertSame($exception->getTraceAsString(), $info['exceptionStack']); + $this->assertSame($info, $result->__debugInfo()); + } +} diff --git a/tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php b/tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php deleted file mode 100644 index d282ecce..00000000 --- a/tests/TestCase/Service/Action/Traits/ReCaptchaTraitTest.php +++ /dev/null @@ -1,217 +0,0 @@ - 'example.com']; - if ($referer !== '') { - $environment['HTTP_REFERER'] = $referer; - } - $request = new ServerRequest(['environment' => $environment]); - - return new class ($request, $success) { - use ReCaptchaTrait; - - public $request; - - public $success; - - public function __construct($request, $success) - { - $this->request = $request; - $this->success = $success; - } - - public function getService(): object - { - $request = $this->request; - - return new class ($request) { - private $request; - - public function __construct($request) - { - $this->request = $request; - } - - public function getRequest() - { - return $this->request; - } - }; - } - - protected function getReCaptchaInstance(): ?object - { - if ($this->success === null) { - return null; - } - $success = $this->success; - - return new class ($success) { - private $success; - - public function __construct($success) - { - $this->success = $success; - } - - public function verify($response, $ip): object - { - $success = $this->success && $response === 'valid'; - - return new class ($success) { - private $success; - - public function __construct($success) - { - $this->success = $success; - } - - public function isSuccess() - { - return $this->success; - } - }; - } - }; - } - }; - } - - public function testGlobalDisabledSkipsValidation(): void - { - Configure::write('Api.reCaptcha.disabled', true); - $this->assertTrue($this->subject(false)->validateReCaptcha('any')); - } - - public function testValidTokenPasses(): void - { - $this->assertTrue($this->subject(true)->validateReCaptcha('valid')); - $this->assertFalse($this->subject(true)->validateReCaptcha('invalid')); - } - - public function testDisabledForTheDomainStillValidates(): void - { - Configure::write('Api.reCaptcha.example$com', ['disabled' => true, 'secret' => 'secret']); - $this->assertFalse($this->subject(true)->validateReCaptcha('invalid')); - } - - public function testDisabledForAnotherDomainStillValidates(): void - { - Configure::write('Api.reCaptcha.dev$test', ['disabled' => true]); - $this->assertFalse($this->subject(true, 'https://dev.test/')->validateReCaptcha('invalid')); - } - - public function testNoReCaptchaInstanceFails(): void - { - $this->assertFalse($this->subject(null)->validateReCaptcha('valid')); - } - - public function testGlobalDisabledMustBeTrue(): void - { - // a string, as read from an environment variable, does not turn validation off - Configure::write('Api.reCaptcha.disabled', 'true'); - $this->assertFalse($this->subject(true)->validateReCaptcha('invalid')); - } - - public function testNoSecretFails(): void - { - // the real lookup: no secret for the domain means no reCaptcha instance - $request = new ServerRequest(['environment' => ['HTTP_HOST' => 'example.com']]); - $subject = new class ($request) { - use ReCaptchaTrait; - - public $request; - - public function __construct($request) - { - $this->request = $request; - } - - public function getService(): object - { - $request = $this->request; - - return new class ($request) { - private $request; - - public function __construct($request) - { - $this->request = $request; - } - - public function getRequest() - { - return $this->request; - } - }; - } - }; - - $this->assertFalse($subject->validateReCaptcha('valid')); - } - - public function testDisabledForTheDomainIsLogged(): void - { - // like the loggers of the application skeleton, which take messages without a scope - Log::setConfig('recaptcha_test', ['className' => 'Array', 'levels' => ['warning'], 'scopes' => null]); - Configure::write('Api.reCaptcha.example$com', ['disabled' => true]); - try { - $this->subject(true)->validateReCaptcha('invalid'); - $logged = implode("\n", Log::engine('recaptcha_test')->read()); - } finally { - Log::drop('recaptcha_test'); - } - - $this->assertStringContainsString('`Api.reCaptcha.example$com.disabled` is ignored', $logged); - } - - public function testNoSecretIsLogged(): void - { - // like the loggers of the application skeleton, which take messages without a scope - Log::setConfig('recaptcha_test', ['className' => 'Array', 'levels' => ['warning'], 'scopes' => null]); - try { - $this->subject(null)->validateReCaptcha('valid'); - $logged = implode("\n", Log::engine('recaptcha_test')->read()); - } finally { - Log::drop('recaptcha_test'); - } - - $this->assertStringContainsString('No reCaptcha secret is configured for `example$com`', $logged); - } -} diff --git a/tests/TestCase/Service/ApiRouterTest.php b/tests/TestCase/Service/ApiRouterTest.php index 3a0e3eea..58f18a8d 100644 --- a/tests/TestCase/Service/ApiRouterTest.php +++ b/tests/TestCase/Service/ApiRouterTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; diff --git a/tests/TestCase/Service/Attribute/ServiceAttributeConnectorTest.php b/tests/TestCase/Service/Attribute/ServiceAttributeConnectorTest.php new file mode 100644 index 00000000..802e87a6 --- /dev/null +++ b/tests/TestCase/Service/Attribute/ServiceAttributeConnectorTest.php @@ -0,0 +1,259 @@ +configureResolver(); + } + + protected function tearDown(): void + { + ServiceRegistry::getServiceLocator()->clear(); + if (AttributeResolver::getConfig('default') !== null) { + AttributeResolver::drop('default'); + } + parent::tearDown(); + } + + protected function configureResolver(): void + { + if (AttributeResolver::getConfig('default') !== null) { + AttributeResolver::clear('default'); + AttributeResolver::drop('default'); + } + AttributeResolver::setConfig('default', [ + 'paths' => ['tests/App/Service/*.php', 'tests/App/Service/**/*.php'], + 'cache' => false, + ]); + } + + protected function buildService(string $serviceName): Service + { + ServiceRegistry::getServiceLocator()->clear(); + $this->_initializeRequest(['params' => ['service' => $serviceName]], 'GET'); + + return ServiceRegistry::getServiceLocator()->get($serviceName, [ + 'version' => null, + 'service' => $serviceName, + 'request' => $this->request, + 'response' => $this->response, + 'baseUrl' => '/' . $serviceName, + ]); + } + + /** + * Returns the resource map entries built from the service actions map. + */ + protected function actionMap(Service $service): array + { + return $service->routerDefaultOptions()['map']; + } + + public function testNoOpWithoutResolverConfig(): void + { + AttributeResolver::drop('default'); + + $service = $this->buildService('verbs'); + + $this->assertArrayNotHasKey('create', $service->getActionsClassMap()); + $this->assertArrayNotHasKey('create', $this->actionMap($service)); + } + + public function testHttpShortcutsRegisterMethodPathAndClass(): void + { + $service = $this->buildService('verbs'); + $map = $this->actionMap($service); + $classMap = $service->getActionsClassMap(); + + $expected = [ + 'create' => ['POST', 'create', AttributeVerbPostAction::class], + 'replace' => ['PUT', '{id}/replace', AttributeVerbPutAction::class], + 'touch' => ['PATCH', '{id}/touch', AttributeVerbPatchAction::class], + 'probe' => ['OPTIONS', 'probe', AttributeVerbOptionsAction::class], + ]; + foreach ($expected as $action => [$method, $path, $class]) { + $this->assertSame( + ['method' => [$method], 'mapCors' => false, 'path' => $path, 'action' => $action], + $map[$action], + $action, + ); + $this->assertSame($class, $classMap[$action], $action); + } + + // `mapCors: true` is consumed when the map is built + $this->assertSame(['method' => ['DELETE'], 'path' => 'purge', 'action' => 'purge'], $map['purge']); + $this->assertSame(AttributeVerbDeleteAction::class, $classMap['purge']); + } + + public function testApiRouteKeepsMethodList(): void + { + $map = $this->actionMap($this->buildService('verbs')); + + $this->assertSame(['GET', 'POST'], $map['search']['method']); + $this->assertSame('search', $map['search']['path']); + } + + public function testApiRouteWithStringMethodAndEmptyPath(): void + { + $map = $this->actionMap($this->buildService('verbs')); + + // `method: 'PATCH'` becomes a list; an empty path falls back to the action name + $this->assertSame(['method' => ['PATCH'], 'mapCors' => false, 'path' => 'stamp', 'action' => 'stamp'], $map['stamp']); + } + + public function testRepeatedAttributesMapOneClassToEveryAction(): void + { + $classMap = $this->buildService('verbs')->getActionsClassMap(); + + $this->assertSame(AttributeVerbRepeatedAction::class, $classMap['ping']); + $this->assertSame(AttributeVerbRepeatedAction::class, $classMap['pong']); + $this->assertSame(AttributeVerbRepeatedAction::class, $classMap['stamp']); + $this->assertSame(AttributeVerbRouteAction::class, $classMap['search']); + $this->assertSame(AttributeVerbRouteAction::class, $classMap['lookup']); + } + + public function testMethodLevelAttributesAreIgnored(): void + { + $service = $this->buildService('verbs'); + $classMap = $service->getActionsClassMap(); + + // ApiGet on AttributeVerbPostAction::execute() and ApiActions on VerbsService::initialize() + $this->assertArrayNotHasKey('methodLevel', $classMap); + $this->assertArrayNotHasKey('plain', $classMap); + $this->assertArrayNotHasKey('methodLevel', $this->actionMap($service)); + } + + public function testApiScopeOnActionClassIsIgnored(): void + { + $map = $this->actionMap($this->buildService('verbs')); + + $this->assertSame('create', $map['create']['path']); + $this->assertArrayNotHasKey('patterns', $map['create']); + } + + public function testMapCorsRegistersPreflightEntry(): void + { + $service = $this->buildService('verbs'); + $map = $this->actionMap($service); + $classMap = $service->getActionsClassMap(); + + $this->assertSame(['method' => 'OPTIONS', 'path' => 'purge', 'action' => 'purge_cors'], $map['purge_cors']); + $this->assertSame(DummyAction::class, $classMap['purge_cors']); + $this->assertArrayNotHasKey('create_cors', $map); + } + + public function testOptionalRouteParametersArePassedToActionsMap(): void + { + $map = $this->actionMap($this->buildService('verbs')); + + $this->assertSame([ + 'method' => ['GET'], + 'mapCors' => false, + 'flag' => 'on', + 'path' => 'lookup/{code}', + 'patterns' => ['code' => '[0-9]+'], + 'pass' => ['code'], + 'name' => 'verbsLookupNamed', + 'action' => 'lookup', + ], $map['lookup']); + } + + public function testRouteNameIsConnected(): void + { + $service = $this->buildService('verbs'); + $names = []; + foreach ($service->routes() as $route) { + $names[] = $route->options['_name'] ?? $route->getName(); + } + $this->assertContains('verbsLookupNamed', $names); + $this->assertSame( + '/verbs/lookup/12', + $service->routeUrl(['_name' => 'verbsLookupNamed', 'code' => '12']), + ); + } + + public function testServiceWithoutApiResourceKeepsResourceOptions(): void + { + $this->assertSame([], $this->buildService('verbs')->getResourceOptions()); + $this->assertSame( + ['index', 'view', 'featured', 'item'], + $this->buildService('attributes')->getResourceOptions()['only'], + ); + } + + public function testScopesStackAcrossRepeatedAttributesAndInheritance(): void + { + $service = $this->buildService('scoped'); + $map = $this->actionMap($service); + + // parent `/base`, then the child's `/v2` and `/extra`; child pattern and default win over the parent's + $this->assertSame([ + 'method' => ['GET'], + 'mapCors' => false, + 'tier' => 'child', + 'origin' => 'parent', + 'path' => 'base/v2/extra/code/{code}', + 'patterns' => ['code' => '[a-z]{3}'], + 'action' => 'code', + ], $map['code']); + $this->assertSame(AttributeScopedCodeAction::class, $service->getActionsClassMap()['code']); + $this->assertSame('base/v2/extra/plain', $map['plain']['path']); + + $templates = []; + foreach ($service->routes() as $route) { + $templates[] = $route->template; + } + $this->assertContains('/scoped/base/v2/extra/code/{code}', $templates); + $this->assertContains('/scoped/base/v2/extra/plain', $templates); + } + + public function testRoutePatternsMergeOverScopePatterns(): void + { + $map = $this->actionMap($this->buildService('scoped')); + + $this->assertSame(['code' => '[0-9]+'], $map['tagged']['patterns']); + } + + public function testScopeDefaultsAreMergedIntoRoutes(): void + { + $map = $this->actionMap($this->buildService('scoped')); + $this->assertSame('child', $map['plain']['tier']); + $this->assertSame('parent', $map['plain']['origin']); + } +} diff --git a/tests/TestCase/Service/AuthTest.php b/tests/TestCase/Service/AuthTest.php index 25f3ef05..79797504 100644 --- a/tests/TestCase/Service/AuthTest.php +++ b/tests/TestCase/Service/AuthTest.php @@ -2,18 +2,20 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; +use CakeDC\Api\Service\Action\Action; use CakeDC\Api\Service\Auth\Auth; +use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; @@ -141,7 +143,7 @@ public function testMagicGetSet(): void public function testServiceActionProperties(): void { $auth = $this->buildAuth(); - $this->assertInstanceOf(\CakeDC\Api\Service\Service::class, $auth->service); - $this->assertInstanceOf(\CakeDC\Api\Service\Action\Action::class, $auth->action); + $this->assertInstanceOf(Service::class, $auth->service); + $this->assertInstanceOf(Action::class, $auth->action); } } diff --git a/tests/TestCase/Service/ConfigReaderTest.php b/tests/TestCase/Service/ConfigReaderTest.php index d05cb9d6..0ef8888b 100644 --- a/tests/TestCase/Service/ConfigReaderTest.php +++ b/tests/TestCase/Service/ConfigReaderTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; @@ -33,6 +33,8 @@ protected function tearDown(): void { Configure::delete('Api.Service'); Configure::delete('Api.useVersioning'); + Configure::delete('Api.versionPrefix'); + Configure::delete('Api.defaultVersion'); parent::tearDown(); } @@ -166,6 +168,151 @@ public function testActionOptionsVersioned(): void $this->assertFalse($options['auth']); } + public function testDefaultVersionKeepsTheUnversionedServiceOptions(): void + { + Configure::write('Api.useVersioning', true); + Configure::write('Api.versionPrefix', 'v'); + Configure::write('Api.defaultVersion', '1'); + $this->writeService([ + 'default' => ['options' => ['adapter' => 'Db', 'limit' => 10]], + 'articles' => ['options' => ['limit' => 25, 'rendererClass' => 'CakeDC/Api.Json']], + 'v1' => ['articles' => ['options' => ['limit' => 100]]], + ]); + $reader = new ConfigReader(); + + // the unversioned keys are the options of the default version; its own keys override them + $options = $reader->serviceOptions('articles', 'v1'); + $this->assertSame('CakeDC/Api.Json', $options['rendererClass']); + $this->assertSame(100, $options['limit']); + $this->assertSame('Db', $options['adapter']); + + // `v2` has no ArticlesService of its own: the unversioned class serves it, with its options + $options = $reader->serviceOptions('articles', 'v2'); + $this->assertSame('CakeDC/Api.Json', $options['rendererClass']); + $this->assertSame(25, $options['limit']); + } + + public function testVersionWithItsOwnClassDoesNotReadTheUnversionedOptions(): void + { + // the test application has Service/v1/ArticlesService, and no Service/v2 + Configure::write('Api.useVersioning', true); + Configure::write('Api.versionPrefix', 'v'); + $this->writeService([ + 'default' => ['options' => ['limit' => 10]], + 'articles' => [ + 'options' => ['limit' => 25, 'rendererClass' => 'CakeDC/Api.Json'], + 'Action' => ['Index' => ['Extension' => ['App.OwnerScope']]], + ], + ]); + $reader = new ConfigReader(); + + $options = $reader->serviceOptions('articles', 'v1'); + $this->assertArrayNotHasKey('rendererClass', $options); + $this->assertSame(10, $options['limit']); + $this->assertSame([], $reader->actionOptions('articles', 'index', 'v1')); + + // a version without its own class is served by the unversioned class, so it reads its options + $options = $reader->serviceOptions('articles', 'v2'); + $this->assertSame('CakeDC/Api.Json', $options['rendererClass']); + $this->assertSame(25, $options['limit']); + $this->assertSame(['App.OwnerScope'], $reader->actionOptions('articles', 'index', 'v2')['Extension']); + + // the keys under the version win there too + $this->writeService([ + 'articles' => ['options' => ['limit' => 25, 'rendererClass' => 'CakeDC/Api.Json']], + 'v2' => ['articles' => ['options' => ['limit' => 100]]], + ]); + $options = $reader->serviceOptions('articles', 'v2'); + $this->assertSame(100, $options['limit']); + $this->assertSame('CakeDC/Api.Json', $options['rendererClass']); + } + + public function testDefaultVersionKeepsTheUnversionedActionOptions(): void + { + Configure::write('Api.useVersioning', true); + Configure::write('Api.versionPrefix', 'v'); + Configure::write('Api.defaultVersion', '1'); + $this->writeService([ + 'articles' => [ + 'Action' => [ + 'default' => ['marker' => 'unversioned'], + 'Index' => ['limit' => 5, 'Extension' => ['App.OwnerScope']], + ], + ], + 'v1' => ['articles' => ['Action' => ['Index' => ['limit' => 50]]]], + ]); + $reader = new ConfigReader(); + + $options = $reader->actionOptions('articles', 'index', 'v1'); + $this->assertSame('unversioned', $options['marker']); + $this->assertSame(['App.OwnerScope'], $options['Extension']); + $this->assertSame(50, $options['limit']); + + // `v2` has no ArticlesService of its own, so it reads the unversioned keys and no `v1` key + $options = $reader->actionOptions('articles', 'index', 'v2'); + $this->assertSame('unversioned', $options['marker']); + $this->assertSame(['App.OwnerScope'], $options['Extension']); + $this->assertSame(5, $options['limit']); + } + + public function testDefaultVersionJoinsListsAndPrefersItsOwnDefaults(): void + { + Configure::write('Api.useVersioning', true); + Configure::write('Api.versionPrefix', 'v'); + Configure::write('Api.defaultVersion', '1'); + $sort = 'CakeDC/Api.Sort'; + $this->writeService([ + 'articles' => [ + 'options' => ['rendererClass' => 'CakeDC/Api.Json'], + 'Action' => ['Index' => [ + 'limit' => 5, + 'Extension' => [$sort => ['sortableFields' => ['id', 'title']]], + ]], + ], + 'v1' => [ + 'default' => [ + 'options' => ['rendererClass' => 'CakeDC/Api.Xml'], + 'Action' => ['default' => ['limit' => 100]], + ], + 'articles' => ['Action' => ['Index' => [ + 'Extension' => [$sort => ['sortableFields' => ['created']]], + ]]], + ], + ]); + $reader = new ConfigReader(); + + // the keys under the version win, also its defaults over an unversioned key of the service + $this->assertSame('CakeDC/Api.Xml', $reader->serviceOptions('articles', 'v1')['rendererClass']); + $options = $reader->actionOptions('articles', 'index', 'v1'); + $this->assertSame(100, $options['limit']); + // list values are joined, not replaced + $this->assertSame(['id', 'title', 'created'], $options['Extension'][$sort]['sortableFields']); + } + + public function testDefaultVersionReplacesAServiceOptionListWhole(): void + { + Configure::write('Api.useVersioning', true); + Configure::write('Api.versionPrefix', 'v'); + Configure::write('Api.defaultVersion', '1'); + $this->writeService([ + 'articles' => ['options' => ['Extension' => ['App.OwnerScope'], 'limit' => 25]], + 'v1' => ['default' => ['options' => ['Extension' => ['CakeDC/Api.Log']]]], + ]); + $reader = new ConfigReader(); + + // in service options a key under the version replaces the unversioned key, a list included + $options = $reader->serviceOptions('articles', 'v1'); + $this->assertSame(['CakeDC/Api.Log'], $options['Extension']); + // keys the version does not set still come from the unversioned service options + $this->assertSame(25, $options['limit']); + + $this->writeService([ + 'articles' => ['options' => ['Extension' => ['App.OwnerScope']]], + 'v1' => ['articles' => ['options' => ['Extension' => ['CakeDC/Api.Log']]]], + ]); + $this->assertSame(['CakeDC/Api.Log'], $reader->serviceOptions('articles', 'v1')['Extension']); + } + public function testActionNameIsCamelized(): void { $this->writeService([ diff --git a/tests/TestCase/Service/Extension/OptionsHandlerExtensionTest.php b/tests/TestCase/Service/Extension/OptionsHandlerExtensionTest.php new file mode 100644 index 00000000..d937f5d0 --- /dev/null +++ b/tests/TestCase/Service/Extension/OptionsHandlerExtensionTest.php @@ -0,0 +1,101 @@ + '/articles', + 'environment' => [ + 'REQUEST_METHOD' => $method, + 'HTTP_ORIGIN' => 'http://foobar.com', + ], + ]); + + return new FallbackService(['service' => 'articles', 'request' => $request]); + } + + /** + * Calls the listener directly, outside the event manager. + * + * @param \CakeDC\Api\Service\FallbackService $service Service. + * @param bool $force Force flag of the event. + * @return \Cake\Event\Event + */ + protected function dispatch(FallbackService $service, bool $force = false): Event + { + $extension = new OptionsHandlerExtension(new ExtensionRegistry($service)); + $event = new Event('Service.beforeDispatch', $service, ['service' => $service, 'force' => $force]); + $extension->onDispatch($event); + + return $event; + } + + public function testImplementedEvents(): void + { + $extension = new OptionsHandlerExtension(new ExtensionRegistry()); + + $this->assertSame(['Service.beforeDispatch' => 'onDispatch'], $extension->implementedEvents()); + } + + public function testOptionsRequestSetsEventResult(): void + { + $service = $this->service('OPTIONS'); + + $event = $this->dispatch($service); + + // the result is set on the event, as returning it from a listener is deprecated since CakePHP 5.2 + $this->assertInstanceOf(Result::class, $event->getResult()); + $this->assertSame($service->getResult(), $event->getResult()); + $this->assertNull($event->getResult()->getData()); + $this->assertSame(200, $event->getResult()->getCode()); + $this->assertSame('*', $service->getResponse()->getHeaderLine('Access-Control-Allow-Origin')); + } + + public function testOtherRequestIsIgnored(): void + { + $service = $this->service('GET'); + + $event = $this->dispatch($service); + + $this->assertNull($event->getResult()); + $this->assertFalse($service->getResponse()->hasHeader('Access-Control-Allow-Origin')); + } + + public function testForceAddsCorsHeadersToOtherRequest(): void + { + $service = $this->service('GET'); + + $event = $this->dispatch($service, true); + + $this->assertInstanceOf(Result::class, $event->getResult()); + $this->assertSame('*', $service->getResponse()->getHeaderLine('Access-Control-Allow-Origin')); + } +} diff --git a/tests/TestCase/Service/ExtensionLoadingTest.php b/tests/TestCase/Service/ExtensionLoadingTest.php new file mode 100644 index 00000000..69f21bfb --- /dev/null +++ b/tests/TestCase/Service/ExtensionLoadingTest.php @@ -0,0 +1,72 @@ + config` map (the + * old CakePHP 4 `class`/`config` shape is gone), so extensions must be loaded by + * their normalized name. A plugin-prefixed extension (e.g. `CakeDC/Api.Log`) only + * carries a `className` key, and an app extension without a plugin prefix carries + * neither `class` nor `className`. + */ +class ExtensionLoadingTest extends TestCase +{ + /** + * A service configured with extensions must load them without a TypeError. + * + * @return void + */ + public function testServiceLoadsConfiguredExtension(): void + { + $service = new FallbackService([ + 'request' => new ServerRequest(), + 'response' => new Response(), + 'Extension' => ['CakeDC/Api.Log'], + ]); + + $this->assertTrue($service->getExtensions()->has('Log')); + } + + /** + * An action configured with an app extension (no plugin prefix) must load it. + * + * @return void + */ + public function testActionLoadsAppExtensionWithoutPluginPrefix(): void + { + $request = new ServerRequest(); + $response = new Response(); + $service = new FallbackService([ + 'request' => $request, + 'response' => $response, + ]); + $action = new CrudIndexAction([ + 'service' => $service, + 'request' => $request, + 'response' => $response, + 'Extension' => ['Sort'], + ]); + + $this->assertNotNull($action->getExtensions()); + $this->assertTrue($action->getExtensions()->has('Sort')); + } +} diff --git a/tests/TestCase/Service/ExtensionRegistryTest.php b/tests/TestCase/Service/ExtensionRegistryTest.php new file mode 100644 index 00000000..2166ecec --- /dev/null +++ b/tests/TestCase/Service/ExtensionRegistryTest.php @@ -0,0 +1,154 @@ +service = new FallbackService([ + 'service' => 'articles', + 'request' => new ServerRequest(), + ]); + $this->registry = new ExtensionRegistry($this->service); + } + + protected function tearDown(): void + { + unset($this->registry, $this->service); + parent::tearDown(); + } + + /** + * A plugin qualified name resolves to the plugin extension. + */ + public function testLoadPluginExtension(): void + { + $extension = $this->registry->load('CakeDC/Api.OptionsHandler'); + $this->assertInstanceOf(OptionsHandlerExtension::class, $extension); + $this->assertTrue($this->registry->has('OptionsHandler')); + $this->assertSame($extension, $this->registry->get('OptionsHandler')); + } + + /** + * A short name falls back to the plugin namespace when the application has no such extension. + */ + public function testLoadShortNameFallsBackToPlugin(): void + { + $this->assertInstanceOf(LogExtension::class, $this->registry->load('Log')); + } + + /** + * A short name resolves to the application extension first. + */ + public function testLoadApplicationExtension(): void + { + $extension = $this->registry->load('CoreProbe'); + $this->assertInstanceOf(CoreProbeExtension::class, $extension); + $this->assertSame($this->registry, $extension->getRegistry()); + } + + /** + * The registry service is injected into the extension config unless one is given. + */ + public function testCreateInjectsService(): void + { + $extension = $this->registry->load('CoreProbe', ['option' => 'value']); + $this->assertSame($this->service, $extension->getConfig('service')); + $this->assertSame('value', $extension->getConfig('option')); + + $other = new FallbackService(['service' => 'authors', 'request' => new ServerRequest()]); + $extension = $this->registry->load('Custom', ['className' => 'CoreProbe', 'service' => $other]); + $this->assertInstanceOf(CoreProbeExtension::class, $extension); + $this->assertSame($other, $extension->getConfig('service')); + } + + /** + * A registry without a service leaves the service config empty. + */ + public function testCreateWithoutService(): void + { + $extension = (new ExtensionRegistry())->load('CoreProbe'); + $this->assertNull($extension->getConfig('service')); + } + + /** + * Created extensions are attached to the registry event manager. + */ + public function testCreateAttachesListener(): void + { + $extension = $this->registry->load('CoreProbe'); + $this->registry->getEventManager()->dispatch(new Event('Service.beforeDispatch', $this->service)); + $this->assertSame(1, $extension->calls); + } + + /** + * An unknown short name is reported with the Extension suffix and no plugin. + */ + public function testLoadUnknownExtension(): void + { + try { + $this->registry->load('Unknown'); + $this->fail('MissingExtensionException was not thrown'); + } catch (MissingExtensionException $missingExtensionException) { + $this->assertSame( + 'Extension class UnknownExtension could not be found.', + $missingExtensionException->getMessage(), + ); + $this->assertSame( + ['class' => 'UnknownExtension', 'plugin' => null], + $missingExtensionException->getAttributes(), + ); + } + } + + /** + * A misspelled plugin qualified name is reported with its plugin and is not retried elsewhere. + */ + public function testLoadMisspelledPluginExtension(): void + { + try { + $this->registry->load('CakeDC/Api.OptionHandler'); + $this->fail('MissingExtensionException was not thrown'); + } catch (MissingExtensionException $missingExtensionException) { + $this->assertSame( + 'Extension class OptionHandlerExtension could not be found.', + $missingExtensionException->getMessage(), + ); + $this->assertSame( + ['class' => 'OptionHandlerExtension', 'plugin' => 'CakeDC/Api'], + $missingExtensionException->getAttributes(), + ); + } + } +} diff --git a/tests/TestCase/Service/JwtTokenHarness.php b/tests/TestCase/Service/JwtTokenHarness.php index db5d566d..869b8b03 100644 --- a/tests/TestCase/Service/JwtTokenHarness.php +++ b/tests/TestCase/Service/JwtTokenHarness.php @@ -2,19 +2,22 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; use CakeDC\Api\Service\Action\Auth\JwtTokenTrait; +/** + * Exposes JwtTokenTrait for unit tests. + */ class JwtTokenHarness { use JwtTokenTrait; diff --git a/tests/TestCase/Service/JwtTokenTraitTest.php b/tests/TestCase/Service/JwtTokenTraitTest.php index 71596dca..97cdcd10 100644 --- a/tests/TestCase/Service/JwtTokenTraitTest.php +++ b/tests/TestCase/Service/JwtTokenTraitTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; @@ -19,9 +19,9 @@ use CakeDC\Api\Test\Settings; use CakeDC\Api\TestSuite\TestCase; use DateTimeImmutable; -use Lcobucci\JWT\Configuration; -use Lcobucci\JWT\Signer\Hmac\Sha512; -use Lcobucci\JWT\Signer\Key\InMemory; +use Firebase\JWT\JWT; +use Firebase\JWT\Key; +use InvalidArgumentException; /** * Unit tests for the JWT token generation trait. @@ -53,14 +53,17 @@ protected function tearDown(): void parent::tearDown(); } - protected function decode(string $token): \Lcobucci\JWT\Token\Plain + /** + * Verifies an access token as the request pipeline does and returns its claims. + * + * @param string $token Access token. + * @return array + */ + protected function decode(string $token): array { - $config = Configuration::forSymmetricSigner( - new Sha512(), - InMemory::plainText('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') - ); + $key = new Key('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'HS512'); - return $config->parser()->parse($token); + return (array)JWT::decode($token, $key); } public function testGenerateAccessTokenHasClaims(): void @@ -69,90 +72,143 @@ public function testGenerateAccessTokenHasClaims(): void $timestamp = new DateTimeImmutable('-1 second'); $tokenString = $harness->generateAccessToken(['id' => 1], $timestamp, 'login'); $this->assertIsString($tokenString); - $token = $this->decode($tokenString); - $this->assertSame('1', $token->claims()->get('sub')); - $this->assertSame(Router::url('/', true), $token->claims()->get('iss')); - $exp = $token->claims()->get('exp'); - $this->assertInstanceOf(DateTimeImmutable::class, $exp); - $this->assertGreaterThan($timestamp, $exp); + $claims = $this->decode($tokenString); + $this->assertSame('1', $claims['sub']); + $this->assertSame(Router::url('/', true), $claims['iss']); + $this->assertEqualsWithDelta($timestamp->getTimestamp() + 600, $claims['exp'], 1.0); } - public function testGenerateAccessTokenEmptyUserReturnsFalse(): void + /** + * Builds the token the plugin must issue, with nothing but PHP's own functions. + * + * @param string $payload The claims as the JSON text of the token. + * @param string $secret Signing secret. + * @return string + */ + protected function expectedToken(string $payload, string $secret): string { - $harness = new JwtTokenHarness(); - $this->assertFalse($harness->generateAccessToken([], new DateTimeImmutable(), 'login')); + $encode = static fn(string $raw): string => rtrim(strtr(base64_encode($raw), '+/', '-_'), '='); + $message = $encode('{"typ":"JWT","alg":"HS512"}') . '.' . $encode($payload); + + return $message . '.' . $encode(hash_hmac('sha512', $message, $secret, true)); } - public function testGetAudienceLoginWithout2fa(): void + public function testAccessTokenIsTheSameTokenAsBefore14(): void { - $harness = new JwtTokenHarness(); - $this->assertSame(Router::url('/', true), $harness->getAudience(['id' => 1], 'login', null)); + // the exact bytes that 13.x issued: header order, claim order, and dates with microseconds as floats + $timestamp = new DateTimeImmutable('2026-11-27 12:00:00.123456 UTC'); + $url = Router::url('/', true); + $expected = $this->expectedToken( + '{"iss":"' . $url . '","iat":1795780800.123456,"aud":"' . $url . '","exp":1795781400.123456,"sub":"42"}', + (string)Configure::read('Api.Jwt.AccessToken.secret'), + ); + + $this->assertSame($expected, (new JwtTokenHarness())->generateAccessToken(['id' => 42], $timestamp, 'login')); } - public function testGetAudienceLoginWith2fa(): void + public function testRefreshTokenIsTheSameTokenAsBefore14(): void { - Configure::write('Api.2fa.enabled', true); - Configure::write('Api.OneTimePasswordAuthenticator.login', true); - $harness = new JwtTokenHarness(); - $this->assertSame(Router::url('/2fa', true), $harness->getAudience(['id' => 1], 'login', null)); + $timestamp = new DateTimeImmutable('2026-11-27 12:00:00.123456 UTC'); + $url = Router::url('/', true); + $expected = $this->expectedToken( + '{"iss":"' . $url . '","iat":1795780800.123456,"aud":"' . $url . '","exp":1796990400.123456,"sub":"' + . Settings::USER1 . '","auth_time":1795780800}', + (string)Configure::read('Api.Jwt.RefreshToken.secret'), + ); + + $token = (new JwtTokenHarness())->generateRefreshToken(['id' => Settings::USER1], $timestamp, 'login'); + $this->assertSame($expected, $token); } - public function testGetAudienceFromPayload(): void + public function testTokenDatesWithoutMicrosecondsAreIntegers(): void { - $harness = new JwtTokenHarness(); - $this->assertSame('custom-audience', $harness->getAudience(['id' => 1], null, ['aud' => 'custom-audience'])); + $timestamp = new DateTimeImmutable('2026-11-27 12:00:00 UTC'); + $url = Router::url('/', true); + $expected = $this->expectedToken( + '{"iss":"' . $url . '","iat":1795780800,"aud":"' . $url . '","exp":1795781400,"sub":"42"}', + (string)Configure::read('Api.Jwt.AccessToken.secret'), + ); + + $this->assertSame($expected, (new JwtTokenHarness())->generateAccessToken(['id' => 42], $timestamp, 'login')); } - public function testGenerateTokenResponseShape(): void + public function testTokenKeepsCharactersOutsideAsciiUnescaped(): void { - $harness = new JwtTokenHarness(); - $result = $harness->generateTokenResponse(['id' => 1, 'email' => 'a@b.c'], 'login'); - $this->assertArrayHasKey('access_token', $result); - $this->assertArrayHasKey('refresh_token', $result); - $this->assertArrayHasKey('expired', $result); - $this->assertArrayHasKey('enabled2FA', $result); - $this->assertArrayHasKey('enabledWebauthn', $result); - $this->assertArrayHasKey('enabledOtp', $result); - $this->assertFalse($result['enabled2FA']); - $this->assertFalse($result['enabledOtp']); + $base = Router::fullBaseUrl(); + Router::fullBaseUrl('http://żółw.example'); + try { + $timestamp = new DateTimeImmutable('2026-11-27 12:00:00 UTC'); + $expected = $this->expectedToken( + '{"iss":"http://żółw.example/","iat":1795780800,"aud":"http://żółw.example/","exp":1795781400,' + . '"sub":"użytkownik"}', + (string)Configure::read('Api.Jwt.AccessToken.secret'), + ); + + $token = (new JwtTokenHarness())->generateAccessToken(['id' => 'użytkownik'], $timestamp, 'login'); + $this->assertSame($expected, $token); + } finally { + Router::fullBaseUrl($base); + } } - public function testGenerateTokenResponse2faFlagsEnabled(): void + public function testIssuedTokenIsAcceptedByTheVerifierOfTheRequestPipeline(): void { - Configure::write('Api.2fa.enabled', true); - Configure::write('Api.OneTimePasswordAuthenticator.login', true); - $harness = new JwtTokenHarness(); - $result = $harness->generateTokenResponse(['id' => 1], 'login'); - $this->assertTrue($result['enabled2FA']); - $this->assertTrue($result['enabledOtp']); + // cakephp/authentication verifies bearer tokens with firebase/php-jwt + $token = (new JwtTokenHarness())->generateAccessToken(['id' => 42], new DateTimeImmutable('-1 second'), 'login'); + $key = new Key((string)Configure::read('Api.Jwt.AccessToken.secret'), 'HS512'); + + $this->assertSame('42', JWT::decode((string)$token, $key)->sub); } - public function testGenerateTokenResponseRemovesSensitiveUserFields(): void + public function testSecretShorterThan64BytesIsRefused(): void + { + // HS512 needs a key of 512 bits; a shorter one must never sign a token + Configure::write('Api.Jwt.AccessToken.secret', str_repeat('k', 63)); + + $this->expectException(InvalidArgumentException::class); + (new JwtTokenHarness())->generateAccessToken(['id' => 42], new DateTimeImmutable(), 'login'); + } + + public function testSecretOfExactly64BytesSigns(): void + { + // 64 bytes is the documented minimum, and what `openssl rand -hex 32` gives + $secret = str_repeat('k', 64); + Configure::write('Api.Jwt.AccessToken.secret', $secret); + + $token = (new JwtTokenHarness())->generateAccessToken(['id' => 42], new DateTimeImmutable('-1 second'), 'login'); + + $this->assertSame('42', JWT::decode((string)$token, new Key($secret, 'HS512'))->sub); + } + + public function testEmptySecretIsRefused(): void + { + Configure::write('Api.Jwt.RefreshToken.secret', ''); + + $this->expectException(InvalidArgumentException::class); + (new JwtTokenHarness())->generateRefreshToken(['id' => Settings::USER1], new DateTimeImmutable(), 'login'); + } + + public function testGenerateAccessTokenEmptyUserReturnsFalse(): void { $harness = new JwtTokenHarness(); - $result = $harness->generateTokenResponse([ - 'id' => 1, - 'secret' => 'should-be-removed', - 'secret_verified' => true, - ], 'login'); - $this->assertArrayNotHasKey('secret', $result); - $this->assertArrayNotHasKey('secret_verified', $result); + $this->assertFalse($harness->generateAccessToken([], new DateTimeImmutable(), 'login')); } - /** - * Returns the claims of a JWT without verifying it. - * - * @param string $token JWT. - * @return array - */ - protected function claims(string $token): array + public function testGetAudienceLoginWithout2fa(): void { - $parts = explode('.', $token); + $harness = new JwtTokenHarness(); + $this->assertSame(Router::url('/', true), $harness->getAudience(['id' => 1], 'login', null)); + } - return json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true); + public function testGetAudienceLoginWith2fa(): void + { + Configure::write('Api.2fa.enabled', true); + Configure::write('Api.OneTimePasswordAuthenticator.login', true); + $harness = new JwtTokenHarness(); + $this->assertSame(Router::url('/2fa', true), $harness->getAudience(['id' => 1], 'login', null)); } - public function testGetAudienceFromArrayPayload(): void + public function testGetAudienceFromPayload(): void { $harness = new JwtTokenHarness(); $this->assertSame('custom-audience', $harness->getAudience(['id' => 1], null, ['aud' => 'custom-audience'])); @@ -224,7 +280,101 @@ public function testGenerateRefreshTokenResponseKeepsObjectPayloadAudience(): vo $payload = (object)['aud' => Router::url('/2fa', true)]; $result = $harness->generateRefreshTokenResponse(['id' => Settings::USER1], $payload); - $this->assertSame(Router::url('/2fa', true), $this->claims($result['access_token'])['aud']); - $this->assertSame(Router::url('/2fa', true), $this->claims($result['refresh_token'])['aud']); + $this->assertSame(Router::url('/2fa', true), $this->decode($result['access_token'])['aud']); + $refreshParts = explode('.', $result['refresh_token']); + $refreshClaims = json_decode(base64_decode(strtr($refreshParts[1], '-_', '+/')), true); + $this->assertSame(Router::url('/2fa', true), $refreshClaims['aud']); + } + + public function testGenerateTokenResponseShape(): void + { + $harness = new JwtTokenHarness(); + $result = $harness->generateTokenResponse(['id' => Settings::USER1, 'email' => 'a@b.c'], 'login'); + $this->assertArrayHasKey('access_token', $result); + $this->assertArrayHasKey('refresh_token', $result); + $this->assertArrayHasKey('expired', $result); + $this->assertArrayHasKey('enabled2FA', $result); + $this->assertArrayHasKey('enabledWebauthn', $result); + $this->assertArrayHasKey('enabledOtp', $result); + $this->assertFalse($result['enabled2FA']); + $this->assertFalse($result['enabledOtp']); + } + + public function testGenerateTokenResponse2faFlagsEnabled(): void + { + Configure::write('Api.2fa.enabled', true); + Configure::write('Api.OneTimePasswordAuthenticator.login', true); + $harness = new JwtTokenHarness(); + $result = $harness->generateTokenResponse(['id' => Settings::USER1], 'login'); + $this->assertTrue($result['enabled2FA']); + $this->assertTrue($result['enabledOtp']); + } + + public function testGenerateTokenResponseRemovesSensitiveUserFields(): void + { + $harness = new JwtTokenHarness(); + $result = $harness->generateTokenResponse([ + 'id' => Settings::USER1, + 'secret' => 'should-be-removed', + 'secret_verified' => true, + ], 'login'); + $this->assertArrayNotHasKey('secret', $result); + $this->assertArrayNotHasKey('secret_verified', $result); + } + + /** + * Decodes the claims of a token without verifying it. + * + * @param string $token JWT. + * @return array + */ + protected function refreshClaims(string $token): array + { + $parts = explode('.', $token); + + return json_decode(base64_decode(strtr($parts[1], '-_', '+/')), true); + } + + public function testLoginStartsAuthTime(): void + { + $harness = new JwtTokenHarness(); + $before = time(); + $result = $harness->generateTokenResponse(['id' => Settings::USER1], 'login'); + $authTime = $this->refreshClaims($result['refresh_token'])['auth_time']; + + // login tokens are issued one second in the past + $this->assertGreaterThanOrEqual($before - 1, $authTime); + $this->assertLessThanOrEqual(time(), $authTime); + } + + public function testRefreshKeepsPayloadAuthTime(): void + { + $harness = new JwtTokenHarness(); + $payload = (object)['aud' => Router::url('/', true), 'auth_time' => 1000]; + $result = $harness->generateRefreshTokenResponse(['id' => Settings::USER1], $payload); + + $this->assertSame(1000, $this->refreshClaims($result['refresh_token'])['auth_time']); + } + + public function testRefreshWithoutPayloadAuthTimeKeepsItMissing(): void + { + // a session from before auth_time existed must not get a fresh one, or enabling + // maxSessionLifetime later would never end it + $harness = new JwtTokenHarness(); + $payload = (object)['aud' => Router::url('/', true)]; + $result = $harness->generateRefreshTokenResponse(['id' => Settings::USER1], $payload); + + $this->assertArrayNotHasKey('auth_time', $this->refreshClaims($result['refresh_token'])); + } + + public function testSecondFactorStartsAuthTime(): void + { + $harness = new JwtTokenHarness(); + $before = time(); + $result = $harness->generateTokenResponse(['id' => Settings::USER1], '2fa'); + $authTime = $this->refreshClaims($result['refresh_token'])['auth_time']; + + $this->assertGreaterThanOrEqual($before - 1, $authTime); + $this->assertLessThanOrEqual(time(), $authTime); } } diff --git a/tests/TestCase/Service/ListingServiceTest.php b/tests/TestCase/Service/ListingServiceTest.php index d411c734..6bbef478 100644 --- a/tests/TestCase/Service/ListingServiceTest.php +++ b/tests/TestCase/Service/ListingServiceTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; diff --git a/tests/TestCase/Service/LocatorAwareTraitTest.php b/tests/TestCase/Service/LocatorAwareTraitTest.php new file mode 100644 index 00000000..49b59d52 --- /dev/null +++ b/tests/TestCase/Service/LocatorAwareTraitTest.php @@ -0,0 +1,51 @@ +assertSame(ServiceRegistry::getServiceLocator(), $this->locatorAware()->getServiceLocator()); + } + + public function testSetServiceLocatorReplacesItForThatObjectOnly(): void + { + $locator = $this->createStub(LocatorInterface::class); + $object = $this->locatorAware(); + $other = $this->locatorAware(); + + $this->assertSame($object, $object->setServiceLocator($locator)); + $this->assertSame($locator, $object->getServiceLocator()); + $this->assertSame(ServiceRegistry::getServiceLocator(), $other->getServiceLocator()); + } +} diff --git a/tests/TestCase/Service/RecaptchaTraitHarness.php b/tests/TestCase/Service/RecaptchaTraitHarness.php index ebe63840..70062320 100644 --- a/tests/TestCase/Service/RecaptchaTraitHarness.php +++ b/tests/TestCase/Service/RecaptchaTraitHarness.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; @@ -20,9 +20,9 @@ class RecaptchaTraitHarness { use ReCaptchaTrait; - private ?object $recaptchaInstance = null; + private ?object $recaptchaInstance; - private ?Service $service = null; + private ?Service $service; public function __construct(?Service $service = null, ?object $recaptchaInstance = null) { diff --git a/tests/TestCase/Service/RecaptchaTraitTest.php b/tests/TestCase/Service/RecaptchaTraitTest.php index b5c412bd..267aa7be 100644 --- a/tests/TestCase/Service/RecaptchaTraitTest.php +++ b/tests/TestCase/Service/RecaptchaTraitTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; @@ -16,8 +16,10 @@ use Cake\Core\Configure; use Cake\Http\Response; use Cake\Http\ServerRequest; +use Cake\Log\Log; use CakeDC\Api\Service\FallbackService; use CakeDC\Api\TestSuite\TestCase; +use ReCaptcha\ReCaptcha; /** * Unit tests for the reCaptcha validation trait. @@ -40,7 +42,8 @@ protected function buildHarness(?object $recaptchaInstance = null, array $data = 'HTTP_HOST' => 'example.com', 'REQUEST_METHOD' => 'POST', ], - 'data' => $data, + // ServerRequest reads the parsed body from `post`; `data` would be silently ignored + 'post' => $data, ]); $service = new FallbackService([ 'request' => $request, @@ -82,6 +85,15 @@ public function testDisabledReturnsTrue(): void $this->assertTrue($harness->exposedValidateReCaptcha('any-token')); } + public function testDisabledMustBeTheBooleanTrue(): void + { + // a string, as read from an environment variable, does not turn validation off + Configure::write('Api.reCaptcha.disabled', 'true'); + Configure::write($this->domainKey, ['secret' => 'secret']); + $harness = $this->buildHarness($this->buildVerifyStub(false)); + $this->assertFalse($harness->exposedValidateReCaptcha('token')); + } + public function testDisabledForTheDomainStillVerifies(): void { // the domain can come from the client's Referer, so its settings cannot turn the check off @@ -119,4 +131,59 @@ public function testNoSecretReturnsNullInstance(): void $harness = $this->buildHarness(); $this->assertNull($harness->getReCaptchaInstance()); } + + public function testMissingTokenFailsWithRealClient(): void + { + // google/recaptcha 2.x declares verify(string ...): a missing token must not reach it + Configure::write($this->domainKey, ['secret' => 'secret']); + $harness = $this->buildHarness(new ReCaptcha('secret')); + $this->assertFalse($harness->exposedValidateReCaptcha()); + } + + public function testNonStringTokenFails(): void + { + Configure::write($this->domainKey, ['secret' => 'secret']); + $harness = $this->buildHarness(new ReCaptcha('secret'), ['g-recaptcha-response' => ['x']]); + $this->assertFalse($harness->exposedValidateReCaptcha()); + } + + public function testNoSecretFails(): void + { + Configure::write($this->domainKey, ['disabled' => false]); + $harness = $this->buildHarness(null, ['g-recaptcha-response' => 'token']); + $this->assertFalse($harness->exposedValidateReCaptcha()); + } + + /** + * Reads what a logger like the application skeleton's, which takes messages without a scope, records. + * + * @param callable $run Code that logs. + * @return string + */ + protected function logged(callable $run): string + { + Log::setConfig('recaptcha_test', ['className' => 'Array', 'levels' => ['warning'], 'scopes' => null]); + try { + $run(); + + return implode("\n", Log::engine('recaptcha_test')->read()); + } finally { + Log::drop('recaptcha_test'); + } + } + + public function testDisabledForTheDomainIsLogged(): void + { + Configure::write($this->domainKey, ['disabled' => true, 'secret' => 'secret']); + $logged = $this->logged(fn() => $this->buildHarness($this->buildVerifyStub(false))->exposedValidateReCaptcha('token')); + + $this->assertStringContainsString('`Api.reCaptcha.example$com.disabled` is ignored', $logged); + } + + public function testNoSecretIsLogged(): void + { + $logged = $this->logged(fn() => $this->buildHarness()->exposedValidateReCaptcha('token')); + + $this->assertStringContainsString('No reCaptcha secret is configured for `example$com`', $logged); + } } diff --git a/tests/TestCase/Service/Renderer/FileRendererTest.php b/tests/TestCase/Service/Renderer/FileRendererTest.php new file mode 100644 index 00000000..9f1d114f --- /dev/null +++ b/tests/TestCase/Service/Renderer/FileRendererTest.php @@ -0,0 +1,239 @@ + + */ + protected array $files = []; + + protected function setUp(): void + { + parent::setUp(); + $this->_initializeRequest(); + $this->Service = new FallbackService([ + 'request' => $this->request, + 'rendererClass' => 'CakeDC/Api.File', + ]); + } + + protected function tearDown(): void + { + foreach ($this->files as $file) { + if (is_file($file)) { + unlink($file); + } + } + unset($this->Service); + parent::tearDown(); + } + + /** + * Creates a file in TMP and returns its path. + * + * @param string $name File name. + * @param string $content File content. + * @return string + */ + protected function createFile(string $name, string $content): string + { + $path = TMP . 'ext_file_renderer_' . $name; + file_put_contents($path, $content); + $this->files[] = $path; + + return $path; + } + + /** + * Builds a result for the given data and code. + * + * @param mixed $data Result data. + * @param int $code Result code. + * @return \CakeDC\Api\Service\Action\Result + */ + protected function fileResult(mixed $data, int $code = 200): Result + { + $result = new Result(); + $result->setCode($code); + $result->setData($data); + + return $result; + } + + public function testRendererInitializeByClassName(): void + { + $this->assertInstanceOf(FileRenderer::class, $this->Service->getRenderer()); + } + + public function testResponseStreamsFile(): void + { + $path = $this->createFile('report.csv', "a,b\n1,2\n"); + + $this->assertTrue($this->Service->getRenderer()->response($this->fileResult($path))); + + $response = $this->Service->getResponse(); + $this->assertSame(200, $response->getStatusCode()); + $this->assertSame('text/csv', $response->getType()); + $this->assertSame('8', $response->getHeaderLine('Content-Length')); + $this->assertSame('bytes', $response->getHeaderLine('Accept-Ranges')); + $this->assertFalse($response->hasHeader('Content-Disposition')); + $this->assertSame("a,b\n1,2\n", (string)$response->getBody()); + $this->assertSame(realpath($path), $response->getFile()?->getRealPath()); + } + + public function testResponseUsesResultCode(): void + { + $path = $this->createFile('partial.txt', 'partial'); + + $this->Service->getRenderer()->response($this->fileResult($path, 202)); + + $response = $this->Service->getResponse(); + $this->assertSame(202, $response->getStatusCode()); + $this->assertSame('text/plain', $response->getType()); + $this->assertSame('partial', (string)$response->getBody()); + } + + public function testResponseFileWithoutExtensionIsDownload(): void + { + $path = $this->createFile('noext', 'raw'); + + $this->Service->getRenderer()->response($this->fileResult($path)); + + $response = $this->Service->getResponse(); + $this->assertSame( + 'attachment; filename="' . basename($path) . '"', + $response->getHeaderLine('Content-Disposition'), + ); + $this->assertSame('binary', $response->getHeaderLine('Content-Transfer-Encoding')); + $this->assertSame('raw', (string)$response->getBody()); + } + + public function testResponseMissingFile(): void + { + Configure::write('debug', false); + $this->assertTrue($this->Service->getRenderer()->response($this->fileResult(TMP . 'ext_file_renderer_missing.txt'))); + + $response = $this->Service->getResponse(); + $this->assertSame(404, $response->getStatusCode()); + $this->assertSame( + '{"error":{"code":404,"message":"The requested file was not found"}}', + (string)$response->getBody(), + ); + } + + public function testResponseRejectsPathTraversal(): void + { + $this->assertTrue($this->Service->getRenderer()->response($this->fileResult(TMP . '../composer.json'))); + + $response = $this->Service->getResponse(); + $this->assertSame(404, $response->getStatusCode()); + $this->assertStringContainsString('The requested file contains `..` and will not be read.', (string)$response->getBody()); + $this->assertStringNotContainsString('"name"', (string)$response->getBody()); + } + + public function testError(): void + { + Configure::write('debug', false); + $response = $this->Service->getResponse()->withStatus(401); + $this->Service->setResponse($response); + + $this->Service->getRenderer()->error(new UnauthenticatedException()); + + $response = $this->Service->getResponse(); + // the status is set by Service::respond(), the renderer keeps it + $this->assertSame(401, $response->getStatusCode()); + $this->assertSame('application/json', $response->getType()); + $this->assertSame( + '{"error":{"code":401,"message":"Unauthenticated"}}', + (string)$response->getBody(), + ); + } + + public function testErrorValidation(): void + { + Configure::write('debug', false); + $errors = ['title' => ['_empty' => 'Required']]; + + $this->Service->getRenderer()->error(new ValidationException('Validation failed', 0, null, $errors)); + + $this->assertSame( + ['error' => ['code' => 422, 'message' => 'Validation failed', 'validation' => $errors]], + json_decode((string)$this->Service->getResponse()->getBody(), true), + ); + } + + public function testErrorDebug(): void + { + Configure::write('debug', true); + $exception = new Exception('Boom', 500); + + $this->Service->getRenderer()->error($exception); + + $body = (string)$this->Service->getResponse()->getBody(); + // pretty printed in debug mode + $this->assertStringContainsString("\n", $body); + $data = json_decode($body, true); + $this->assertSame(500, $data['error']['code']); + $this->assertSame( + 'Boom on line ' . $exception->getLine() . ' in ' . __FILE__, + $data['error']['message'], + ); + $this->assertSame(__FUNCTION__, $data['error']['trace'][0]['function']); + $this->assertArrayNotHasKey('args', $data['error']['trace'][0]); + } + + public function testRespondStreamsFileThroughService(): void + { + $path = $this->createFile('service.txt', 'via service'); + + $response = $this->Service->respond($this->fileResult($path)); + + $this->assertSame(200, $response->getStatusCode()); + $this->assertSame('via service', (string)$response->getBody()); + } + + public function testRespondRendersExceptionAsJson(): void + { + Configure::write('debug', false); + $result = $this->fileResult(null, 404); + $result->setException(new NotFoundException('Missing')); + + $response = $this->Service->respond($result); + + $this->assertSame(404, $response->getStatusCode()); + $this->assertSame('application/json', $response->getType()); + $this->assertSame('{"error":{"code":404,"message":"Missing"}}', (string)$response->getBody()); + } +} diff --git a/tests/TestCase/Service/Renderer/FlysystemRendererTest.php b/tests/TestCase/Service/Renderer/FlysystemRendererTest.php index 19d750a0..a5dd34a8 100644 --- a/tests/TestCase/Service/Renderer/FlysystemRendererTest.php +++ b/tests/TestCase/Service/Renderer/FlysystemRendererTest.php @@ -2,27 +2,30 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Renderer; use Cake\Core\Configure; +use Cake\Http\Response; use CakeDC\Api\Exception\UnauthenticatedException; use CakeDC\Api\Service\Action\Result; use CakeDC\Api\Service\FallbackService; use CakeDC\Api\Service\Renderer\FlysystemRenderer; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use Exception; use League\Flysystem\Filesystem; -use League\Flysystem\Vfs\VfsAdapter; -use VirtualFileSystem\FileSystem as Vfs; +use League\Flysystem\FilesystemOperator; +use League\Flysystem\InMemory\InMemoryFilesystemAdapter; +use League\Flysystem\UnableToCheckFileExistence; class FlysystemRendererTest extends TestCase { @@ -32,7 +35,7 @@ class FlysystemRendererTest extends TestCase public $request; - public ?\CakeDC\Api\Service\FallbackService $Service = null; + public ?FallbackService $Service = null; /** * setUp method @@ -64,7 +67,7 @@ protected function tearDown(): void */ public function testRendererInitializeByClassName(): void { - $response = $this->createStub(\Cake\Http\Response::class); + $response = $this->createStub(Response::class); $this->_initializeRequest([], 'GET', ['response' => $response]); $serviceOptions = [ @@ -88,7 +91,7 @@ public function testRendererSuccess(): void Configure::write('debug', false); Configure::write('Api.Flysystem.expire', '+1 day'); - $response = new \Cake\Http\Response(); + $response = new Response(); $this->_initializeRequest([], 'GET', ['response' => $response]); $serviceOptions = [ @@ -103,22 +106,26 @@ public function testRendererSuccess(): void $statusCode = 200; $result->setCode($statusCode); - $vfs = new Vfs(); $path = '/my-file.zip'; - $vfs->createFile($path, 'content-for-download'); + $filesystem = new Filesystem(new InMemoryFilesystemAdapter()); + $filesystem->write($path, 'content-for-download'); - $filesystem = new Filesystem(new VfsAdapter($vfs)); - $data = ['filesystem' => $filesystem, 'path' => $path]; + $data = ['filesystem' => $filesystem, 'path' => $path, 'name' => 'download.zip']; $result->setData($data); $renderer = $this->Service->getRenderer(); $renderer->response($result); - $headers = $this->Service->getResponse()->getHeaders(); + $response = $this->Service->getResponse(); + $headers = $response->getHeaders(); + // older league/mime-type-detection versions report application/x-zip $this->assertEquals( - ['file'], - $headers['Content-Type'] + [$filesystem->mimeType($path)], + $headers['Content-Type'], ); + $this->assertStringContainsString('zip', $headers['Content-Type'][0]); + $this->assertSame('content-for-download', (string)$response->getBody()); + $this->assertStringContainsString('download.zip', $response->getHeaderLine('Content-Disposition')); $this->assertArrayHasKey('Cache-Control', $headers); $this->assertArrayHasKey('Date', $headers); $this->assertArrayHasKey('Last-Modified', $headers); @@ -134,7 +141,7 @@ public function testRendereFileNotFound(): void { Configure::write('debug', false); $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -151,10 +158,9 @@ public function testRendereFileNotFound(): void $statusCode = 200; $result->setCode($statusCode); - $vfs = new Vfs(); $path = '/my-file-not-found.zip'; - $filesystem = new Filesystem(new VfsAdapter($vfs)); + $filesystem = new Filesystem(new InMemoryFilesystemAdapter()); $data = ['filesystem' => $filesystem, 'path' => $path]; $result->setData($data); $renderer = $this->Service->getRenderer(); @@ -172,11 +178,45 @@ public function testRendereFileNotFound(): void $headers = $this->Service->getResponse()->getHeaders(); $this->assertEquals( ['text/html; charset=UTF-8'], - $headers['Content-Type'] + $headers['Content-Type'], ); $this->assertEmpty((string)$this->Service->getResponse()->getBody()); } + /** + * Test unknown mime type falls back to application/octet-stream + * + * @return void + */ + public function testRendererUnknownMimeType(): void + { + Configure::write('debug', false); + + $response = new Response(); + + $this->_initializeRequest([], 'GET', ['response' => $response]); + $serviceOptions = [ + 'version' => null, + 'request' => $this->request, + 'response' => $response, + 'rendererClass' => 'CakeDC/Api.Flysystem', + ]; + $this->Service = new FallbackService($serviceOptions); + + $result = new Result(); + $result->setCode(200); + + $path = '/no-extension'; + $filesystem = new Filesystem(new InMemoryFilesystemAdapter()); + $filesystem->write($path, ''); + + $result->setData(['filesystem' => $filesystem, 'path' => $path]); + + $this->Service->getRenderer()->response($result); + + $this->assertSame('application/octet-stream', $this->Service->getResponse()->getHeaderLine('Content-Type')); + } + /** * Test render error * @@ -185,7 +225,7 @@ public function testRendereFileNotFound(): void public function testRendererError(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -222,7 +262,7 @@ public function testRendererError(): void public function testRendererErrorEmptyExceptionCode(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -236,7 +276,7 @@ public function testRendererErrorEmptyExceptionCode(): void $this->Service = new FallbackService($serviceOptions); Configure::write('debug', false); - $error = new \Exception(); + $error = new Exception(); $renderer = $this->Service->getRenderer(); $response->expects($this->once()) @@ -250,4 +290,38 @@ public function testRendererErrorEmptyExceptionCode(): void $renderer->error($error); } + + public function testPathTraversalIsNotFound(): void + { + $this->_initializeRequest([], 'GET'); + $this->Service = new FallbackService([ + 'version' => null, + 'request' => $this->request, + 'rendererClass' => 'CakeDC/Api.Flysystem', + ]); + $result = new Result(); + $result->setData(['filesystem' => new Filesystem(new InMemoryFilesystemAdapter()), 'path' => '../outside.zip']); + + $this->Service->getRenderer()->response($result); + + $this->assertSame(404, $this->Service->getResponse()->getStatusCode()); + } + + public function testStorageErrorIsNotNotFound(): void + { + $this->_initializeRequest([], 'GET'); + $this->Service = new FallbackService([ + 'version' => null, + 'request' => $this->request, + 'rendererClass' => 'CakeDC/Api.Flysystem', + ]); + $filesystem = $this->createStub(FilesystemOperator::class); + $filesystem->method('fileExists')->willThrowException(UnableToCheckFileExistence::forLocation('file.zip')); + $result = new Result(); + $result->setData(['filesystem' => $filesystem, 'path' => 'file.zip']); + + // an unreachable backend must not look like a missing file + $this->expectException(UnableToCheckFileExistence::class); + $this->Service->getRenderer()->response($result); + } } diff --git a/tests/TestCase/Service/Renderer/JSendRendererTest.php b/tests/TestCase/Service/Renderer/JSendRendererTest.php index 84a49529..7258ac47 100644 --- a/tests/TestCase/Service/Renderer/JSendRendererTest.php +++ b/tests/TestCase/Service/Renderer/JSendRendererTest.php @@ -2,24 +2,27 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Renderer; use Cake\Core\Configure; +use Cake\Http\Response; +use Cake\Http\ServerRequest; use CakeDC\Api\Exception\UnauthenticatedException; use CakeDC\Api\Service\Action\Result; use CakeDC\Api\Service\FallbackService; use CakeDC\Api\Service\Renderer\JSendRenderer; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; class JSendRendererTest extends TestCase { @@ -29,7 +32,7 @@ class JSendRendererTest extends TestCase public $request; - public ?\CakeDC\Api\Service\FallbackService $Service = null; + public ?FallbackService $Service = null; /** * setUp method @@ -61,7 +64,7 @@ protected function tearDown(): void */ public function testRendererInitializeByClassName(): void { - $response = $this->createStub(\Cake\Http\Response::class); + $response = $this->createStub(Response::class); $this->_initializeRequest([], 'GET', ['response' => $response]); $serviceOptions = [ @@ -84,7 +87,7 @@ public function testRendererSuccess(): void { Configure::write('debug', false); $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); $this->_initializeRequest([], 'GET', ['response' => $response]); @@ -127,7 +130,7 @@ public function testRendererSuccess(): void public function testRendererError(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -158,4 +161,35 @@ public function testRendererError(): void $renderer->error($error); } + + /** + * @return array + */ + public static function acceptProvider(): array + { + return [ + 'application/json' => ['application/json', true], + 'text/json' => ['text/json', true], + 'text/javascript' => ['text/javascript', true], + 'html only' => ['text/html', false], + 'xml only' => ['application/xml', false], + ]; + } + + /** + * The renderer accepts requests asking for JSON or JavaScript. + */ + #[DataProvider('acceptProvider')] + public function testAccept(string $accept, bool $expected): void + { + $request = new ServerRequest(['environment' => ['HTTP_ACCEPT' => $accept, 'REQUEST_METHOD' => 'GET']]); + $service = new FallbackService([ + 'service' => 'articles', + 'request' => $request, + 'rendererClass' => 'CakeDC/Api.JSend', + ]); + $renderer = $service->getRenderer(); + $this->assertInstanceOf(JSendRenderer::class, $renderer); + $this->assertSame($expected, $renderer->accept()); + } } diff --git a/tests/TestCase/Service/Renderer/JsonRendererTest.php b/tests/TestCase/Service/Renderer/JsonRendererTest.php index 92161c73..ba8489f3 100644 --- a/tests/TestCase/Service/Renderer/JsonRendererTest.php +++ b/tests/TestCase/Service/Renderer/JsonRendererTest.php @@ -2,24 +2,28 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Renderer; use Cake\Core\Configure; +use Cake\Http\Response; use CakeDC\Api\Exception\UnauthenticatedException; +use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Result; use CakeDC\Api\Service\FallbackService; use CakeDC\Api\Service\Renderer\JsonRenderer; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use Exception; +use RuntimeException; class JsonRendererTest extends TestCase { @@ -29,7 +33,7 @@ class JsonRendererTest extends TestCase public $request; - public ?\CakeDC\Api\Service\FallbackService $Service = null; + public ?FallbackService $Service = null; /** * setUp method @@ -61,7 +65,7 @@ protected function tearDown(): void */ public function testRendererInitializeByClassName(): void { - $response = $this->createStub(\Cake\Http\Response::class); + $response = $this->createStub(Response::class); $this->_initializeRequest([], 'GET', ['response' => $response]); $serviceOptions = [ @@ -84,7 +88,7 @@ public function testRendererSuccess(): void { Configure::write('debug', false); $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -128,7 +132,7 @@ public function testRendererSuccess(): void public function testRendererError(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -156,4 +160,81 @@ public function testRendererError(): void $renderer->error($error); } + + /** + * Renders an exception with a real response and returns the decoded body. + * + * @param \Exception $exception Exception to render. + * @param bool $debug Debug mode. + * @param int $status Response status before rendering. + * @return array + */ + protected function renderError(Exception $exception, bool $debug, int $status = 200): array + { + $debugBefore = Configure::read('debug'); + Configure::write('debug', $debug); + try { + $this->_initializeRequest([], 'GET', ['response' => (new Response())->withStatus($status)]); + $this->Service = new FallbackService([ + 'request' => $this->request, + 'response' => $this->response, + 'rendererClass' => 'CakeDC/Api.Json', + ]); + $this->Service->getRenderer()->error($exception); + $response = $this->Service->getResponse(); + $this->assertSame('application/json', $response->getType()); + + return json_decode((string)$response->getBody(), true); + } finally { + Configure::write('debug', $debugBefore); + } + } + + /** + * An exception without a code reports the current response status. + * + * @return void + */ + public function testRendererErrorWithoutCodeUsesResponseStatus(): void + { + $body = $this->renderError(new RuntimeException('Teapot'), false, 418); + $this->assertSame(['error' => ['code' => 418, 'message' => 'Teapot']], $body); + } + + /** + * In debug mode the message names the location and a trace is added. + * + * @return void + */ + public function testRendererErrorDebugAddsTrace(): void + { + $exception = new RuntimeException('Broken', 500); + $body = $this->renderError($exception, true); + $this->assertSame(500, $body['error']['code']); + $this->assertSame( + 'Broken on line ' . $exception->getLine() . ' in ' . $exception->getFile(), + $body['error']['message'], + ); + $this->assertIsArray($body['error']['trace']); + $this->assertNotEmpty($body['error']['trace']); + $this->assertArrayNotHasKey('args', $body['error']['trace'][0]); + } + + /** + * Validation errors are listed under the "validation" key. + * + * @return void + */ + public function testRendererErrorValidationErrors(): void + { + $errors = ['title' => ['_empty' => 'This field cannot be left empty']]; + $body = $this->renderError(new ValidationException('Validation failed', 422, null, $errors), false); + $this->assertSame([ + 'error' => [ + 'code' => 422, + 'message' => 'Validation failed', + 'validation' => $errors, + ], + ], $body); + } } diff --git a/tests/TestCase/Service/Renderer/RawRendererTest.php b/tests/TestCase/Service/Renderer/RawRendererTest.php index 51f91970..6dbb6ec3 100644 --- a/tests/TestCase/Service/Renderer/RawRendererTest.php +++ b/tests/TestCase/Service/Renderer/RawRendererTest.php @@ -2,18 +2,19 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Renderer; use Cake\Core\Configure; +use Cake\Http\Response; use CakeDC\Api\Exception\UnauthenticatedException; use CakeDC\Api\Service\Action\Result; use CakeDC\Api\Service\FallbackService; @@ -29,7 +30,7 @@ class RawRendererTest extends TestCase public $request; - public ?\CakeDC\Api\Service\FallbackService $Service = null; + public ?FallbackService $Service = null; /** * setUp method @@ -61,7 +62,7 @@ protected function tearDown(): void */ public function testRendererInitializeByClassName(): void { - $response = $this->createStub(\Cake\Http\Response::class); + $response = $this->createStub(Response::class); $this->_initializeRequest([], 'GET', ['response' => $response]); $serviceOptions = [ @@ -83,7 +84,7 @@ public function testRendererInitializeByClassName(): void public function testRendererSuccess(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -127,7 +128,7 @@ public function testRendererSuccess(): void public function testRendererError(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); diff --git a/tests/TestCase/Service/Renderer/XmlRendererTest.php b/tests/TestCase/Service/Renderer/XmlRendererTest.php index 46771a7e..528f305c 100644 --- a/tests/TestCase/Service/Renderer/XmlRendererTest.php +++ b/tests/TestCase/Service/Renderer/XmlRendererTest.php @@ -2,24 +2,35 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Renderer; +use Cake\Collection\Collection; use Cake\Core\Configure; +use Cake\Http\Response; +use Cake\I18n\Date; +use Cake\I18n\DateTime; +use Cake\I18n\Time; +use Cake\ORM\Entity; use CakeDC\Api\Exception\UnauthenticatedException; +use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Result; use CakeDC\Api\Service\FallbackService; use CakeDC\Api\Service\Renderer\XmlRenderer; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use DateTime as NativeDateTime; +use DateTimeImmutable; +use Exception; +use stdClass; class XmlRendererTest extends TestCase { @@ -29,7 +40,11 @@ class XmlRendererTest extends TestCase public $request; - public ?\CakeDC\Api\Service\FallbackService $Service = null; + public ?FallbackService $Service = null; + + protected array $fixtures = [ + 'plugin.CakeDC/Api.Articles', + ]; /** * setUp method @@ -61,7 +76,7 @@ protected function tearDown(): void */ public function testRendererInitializeByClassName(): void { - $response = $this->createStub(\Cake\Http\Response::class); + $response = $this->createStub(Response::class); $this->_initializeRequest([], 'GET', ['response' => $response]); $serviceOptions = [ @@ -83,7 +98,7 @@ public function testRendererInitializeByClassName(): void public function testRendererSuccess(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -127,7 +142,7 @@ public function testRendererSuccess(): void public function testRendererError(): void { $response = $this - ->getMockBuilder(\Cake\Http\Response::class) + ->getMockBuilder(Response::class) ->onlyMethods(['withStatus', 'withType', 'withStringBody']) ->getMock(); @@ -156,6 +171,256 @@ public function testRendererError(): void $renderer->error($error); } + /** + * Renders data through a real response and returns the body without the XML declaration. + * + * @param mixed $data Result data. + * @param int $code Result code. + * @return string + */ + protected function render(mixed $data, int $code = 200): string + { + $this->Service = new FallbackService([ + 'request' => $this->request, + 'rendererClass' => 'CakeDC/Api.Xml', + ]); + $result = new Result(); + $result->setCode($code); + $result->setData($data); + + $this->assertTrue($this->Service->getRenderer()->response($result)); + + $response = $this->Service->getResponse(); + $this->assertSame($code, $response->getStatusCode()); + $this->assertSame('application/xml', $response->getType()); + $body = (string)$response->getBody(); + $this->assertStringStartsWith('' . "\n", $body); + + return trim(substr($body, strlen(''))); + } + + /** + * Renders an exception and returns the body without the XML declaration. + * + * @param \Exception $exception Exception. + * @return string + */ + protected function renderError(Exception $exception): string + { + $this->Service = new FallbackService([ + 'request' => $this->request, + 'rendererClass' => 'CakeDC/Api.Xml', + ]); + $this->Service->getRenderer()->error($exception); + + $response = $this->Service->getResponse(); + $this->assertSame('application/xml', $response->getType()); + + return trim(substr((string)$response->getBody(), strlen(''))); + } + + public function testResponseScalarAndNull(): void + { + $this->assertSame('5', $this->render(5)); + $this->assertSame('', $this->render(null)); + } + + public function testResponseStatusCode(): void + { + $this->assertSame('created', $this->render('created', 201)); + } + + public function testResponseList(): void + { + // booleans are cast to string, so false renders like null + $this->assertSame( + '1two' + . '1', + $this->render([1, 'two', null, true, false]), + ); + } + + public function testResponseNestedArray(): void + { + $this->assertSame( + '12' + . '34' + . '', + $this->render(['a' => 1, 'b' => ['c' => 2, 'd' => [3, 4]]]), + ); + } + + public function testResponseEmptyArray(): void + { + // an empty array still renders one row element, without a key + $this->assertSame('', $this->render([])); + $this->assertSame( + '', + $this->render(['a' => []]), + ); + } + + public function testResponseEscapesValuesAndKeys(): void + { + $this->assertSame( + '<&>ü', + $this->render(['a "b"' => '<&>', 'é' => 'ü']), + ); + } + + public function testResponseObject(): void + { + $object = new stdClass(); + $object->a = 1; + $object->b = null; + $object->c = ['x' => 1]; + $object->d = new stdClass(); + $object->d->e = 'f'; + + $this->assertSame( + '1' + . '1' + . 'f' + . '', + $this->render($object), + ); + } + + public function testResponseEntity(): void + { + $entity = new Entity([ + 'id' => 1, + 'title' => 'T', + 'tags' => [new Entity(['id' => 2])], + 'author' => new Entity(['name' => 'N']), + ]); + + // nested entities are converted by Entity::toArray(), so they render as arrays + $this->assertSame( + '1T' + . '2' + . 'N' + . '', + $this->render($entity), + ); + } + + public function testResponseEntityHiddenFields(): void + { + $entity = new Entity(['id' => 1, 'password' => 'secret']); + $entity->setHidden(['password']); + + $this->assertSame( + '1', + $this->render($entity), + ); + } + + public function testResponseListOfEntities(): void + { + $this->assertSame( + '1' + . '2', + $this->render([new Entity(['id' => 1]), new Entity(['id' => 2])]), + ); + } + + public function testResponseCollection(): void + { + $this->assertSame( + '12', + $this->render(new Collection(['a' => 1, 'b' => 2])), + ); + } + + public function testResponseResultSet(): void + { + $articles = $this->fetchTable('Articles') + ->find() + ->select(['id', 'title']) + ->orderBy(['id' => 'ASC']) + ->limit(2) + ->all(); + + $this->assertSame( + '1' + . 'First Article' + . '2' + . 'Second Article', + $this->render($articles), + ); + } + + public function testResponseDatesInObject(): void + { + $entity = new Entity([ + 'cake' => new DateTime('2026-01-02 03:04:05'), + 'native' => new NativeDateTime('2026-01-02 03:04:05'), + 'immutable' => new DateTimeImmutable('2026-01-02 03:04:05'), + 'date' => new Date('2026-01-02'), + 'time' => new Time('03:04:05'), + ]); + + $this->assertSame( + '2026-01-02T03:04:05+00:00' + . '2026-01-02T03:04:05+00:00' + . '2026-01-02T03:04:05+00:00' + . '2026-01-02' + . '03:04:05', + $this->render($entity), + ); + } + + public function testResponseDatesInArray(): void + { + $this->assertSame( + '2026-01-02T03:04:05+00:00' + . '2026-01-02T03:04:05+00:00' + . '2026-01-02', + $this->render([ + 'cake' => new DateTime('2026-01-02 03:04:05'), + 'native' => new NativeDateTime('2026-01-02 03:04:05'), + 'date' => new Date('2026-01-02'), + ]), + ); + } + + public function testResponseDate(): void + { + $this->assertSame( + '2026-01-02T03:04:05+00:00', + $this->render(new DateTime('2026-01-02 03:04:05')), + ); + } + + public function testErrorValidation(): void + { + Configure::write('debug', false); + $exception = new ValidationException('Validation failed', 0, null, ['title' => ['_empty' => 'Required']]); + + $this->assertSame( + '422Validation failed' + . '<_empty>Required</_empty>', + $this->renderError($exception), + ); + } + + public function testErrorDebugIncludesLocationAndTrace(): void + { + Configure::write('debug', true); + $exception = new Exception('Boom', 500); + + $body = $this->renderError($exception); + + $this->assertStringStartsWith( + '500Boom on line ' . $exception->getLine() . ' in ' . __FILE__ . '', + $body, + ); + $this->assertStringContainsString('' . __FUNCTION__ . '', $body); + // arguments are stripped from the trace + $this->assertStringNotContainsString('', $body); + } + protected function _xmlMessage($text): string { return '' . "\n" . $text . "\n"; diff --git a/tests/TestCase/Service/RequestParserTest.php b/tests/TestCase/Service/RequestParserTest.php index ec24806c..e59f29b6 100644 --- a/tests/TestCase/Service/RequestParserTest.php +++ b/tests/TestCase/Service/RequestParserTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; diff --git a/tests/TestCase/Service/ReverseRoutingTest.php b/tests/TestCase/Service/ReverseRoutingTest.php index 7b267510..17b0bc52 100644 --- a/tests/TestCase/Service/ReverseRoutingTest.php +++ b/tests/TestCase/Service/ReverseRoutingTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; diff --git a/tests/TestCase/Service/ServiceEventsTest.php b/tests/TestCase/Service/ServiceEventsTest.php index aa89ae02..11d30913 100644 --- a/tests/TestCase/Service/ServiceEventsTest.php +++ b/tests/TestCase/Service/ServiceEventsTest.php @@ -2,21 +2,25 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; +use Cake\Datasource\Exception\RecordNotFoundException; +use CakeDC\Api\Exception\ValidationException; use CakeDC\Api\Service\Action\Result; +use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use RuntimeException; /** * Unit tests for the service event dispatch and error-code mapping. @@ -31,7 +35,7 @@ protected function tearDown(): void parent::tearDown(); } - protected function buildService(string $serviceName = 'articles', string $baseUrl = '/articles', array $params = [], string $method = 'GET'): \CakeDC\Api\Service\Service + protected function buildService(string $serviceName = 'articles', string $baseUrl = '/articles', array $params = [], string $method = 'GET'): Service { ServiceRegistry::getServiceLocator()->clear(); $this->_initializeRequest([ @@ -61,12 +65,12 @@ public function testBeforeDispatchListenerStopsWithResult(): void public function testAfterDispatchListenerExceptionPropagates(): void { - $this->expectException(\RuntimeException::class); + $this->expectException(RuntimeException::class); $this->expectExceptionMessage('after-dispatch boom'); $service = $this->buildService(); $service->dispatchPrepareAction(); $service->getEventManager()->on('Service.afterDispatch', function (): void { - throw new \RuntimeException('after-dispatch boom'); + throw new RuntimeException('after-dispatch boom'); }); $service->dispatchProcessAction($this->request); } @@ -77,7 +81,7 @@ public function testDispatchRecordNotFoundSets404(): void $result = $service->dispatch(); $this->assertInstanceOf(Result::class, $result); $this->assertSame(404, $result->getCode()); - $this->assertInstanceOf(\Cake\Datasource\Exception\RecordNotFoundException::class, $result->getException()); + $this->assertInstanceOf(RecordNotFoundException::class, $result->getException()); } public function testDispatchValidationSets422(): void @@ -88,6 +92,6 @@ public function testDispatchValidationSets422(): void $result = $service->dispatch(); $this->assertInstanceOf(Result::class, $result); $this->assertSame(422, $result->getCode()); - $this->assertInstanceOf(\CakeDC\Api\Exception\ValidationException::class, $result->getException()); + $this->assertInstanceOf(ValidationException::class, $result->getException()); } } diff --git a/tests/TestCase/Service/ServiceLocatorTest.php b/tests/TestCase/Service/ServiceLocatorTest.php index 8a2fc104..eb025d29 100644 --- a/tests/TestCase/Service/ServiceLocatorTest.php +++ b/tests/TestCase/Service/ServiceLocatorTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; @@ -18,6 +18,8 @@ use CakeDC\Api\Service\Locator\ServiceLocator; use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; +use CakeDC\Api\Test\App\Service\ArticlesService; +use CakeDC\Api\Test\App\Service\v1\ArticlesService as V1ArticlesService; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; use RuntimeException; @@ -32,7 +34,7 @@ class ServiceLocatorTest extends TestCase protected function setUp(): void { parent::setUp(); - Configure::write('Api.ServiceFallback', \CakeDC\Api\Service\FallbackService::class); + Configure::write('Api.ServiceFallback', FallbackService::class); Configure::write('Api.useVersioning', false); Configure::write('Api.versionPrefix', 'v'); Configure::delete('Api.defaultVersion'); @@ -68,7 +70,7 @@ public function testVersioningDisabledResolvesBaseService(): void { $locator = new ServiceLocator(); $service = $locator->get('articles', $this->buildOptions()); - $this->assertInstanceOf(\CakeDC\Api\Test\App\Service\ArticlesService::class, $service); + $this->assertInstanceOf(ArticlesService::class, $service); } public function testVersioningResolvesVersionedService(): void @@ -76,7 +78,7 @@ public function testVersioningResolvesVersionedService(): void Configure::write('Api.useVersioning', true); $locator = new ServiceLocator(); $service = $locator->get('articles', $this->buildOptions(version: 'v1')); - $this->assertInstanceOf(\CakeDC\Api\Test\App\Service\v1\ArticlesService::class, $service); + $this->assertInstanceOf(V1ArticlesService::class, $service); $this->assertSame('articles', $service->getName()); } @@ -86,7 +88,7 @@ public function testVersioningUsesDefaultVersion(): void Configure::write('Api.defaultVersion', '1'); $locator = new ServiceLocator(); $service = $locator->get('articles', $this->buildOptions()); - $this->assertInstanceOf(\CakeDC\Api\Test\App\Service\v1\ArticlesService::class, $service); + $this->assertInstanceOf(V1ArticlesService::class, $service); } public function testVersioningUnresolvedVersionFallsBack(): void @@ -95,7 +97,7 @@ public function testVersioningUnresolvedVersionFallsBack(): void Configure::write('Api.useVersioning', true); $locator = new ServiceLocator(); $service = $locator->get('articles', $this->buildOptions(version: 'ver1')); - $this->assertInstanceOf(\CakeDC\Api\Service\FallbackService::class, $service); + $this->assertInstanceOf(FallbackService::class, $service); } public function testGetResolvesExistingService(): void @@ -144,8 +146,8 @@ public function testGetUnknownServiceFallsBack(): void public function testSetConfigAliasOptions(): void { $locator = new ServiceLocator(); - $locator->setConfig('custom', ['className' => \CakeDC\Api\Test\App\Service\ArticlesService::class]); - $this->assertSame(['className' => \CakeDC\Api\Test\App\Service\ArticlesService::class], $locator->getConfig('custom')); + $locator->setConfig('custom', ['className' => ArticlesService::class]); + $this->assertSame(['className' => ArticlesService::class], $locator->getConfig('custom')); } public function testSetConfigArrayOverwrites(): void diff --git a/tests/TestCase/Service/ServiceRegistryTest.php b/tests/TestCase/Service/ServiceRegistryTest.php index 1acb61fe..9ed46486 100644 --- a/tests/TestCase/Service/ServiceRegistryTest.php +++ b/tests/TestCase/Service/ServiceRegistryTest.php @@ -2,21 +2,23 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service\Action; +use CakeDC\Api\Service\Locator\ServiceLocator; use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use ReflectionProperty; class ServiceRegistryTest extends TestCase { @@ -100,4 +102,42 @@ public function testLoadNested(): void $this->assertTrue($Service instanceof Service); $this->assertTextEquals('/authors/1/articles', $Service->getBaseUrl()); } + + /** + * A locator set on the registry is returned until another one is set. + * + * @return void + */ + public function testSetServiceLocator(): void + { + $original = ServiceRegistry::getServiceLocator(); + $locator = new ServiceLocator(); + try { + ServiceRegistry::setServiceLocator($locator); + $this->assertSame($locator, ServiceRegistry::getServiceLocator()); + } finally { + ServiceRegistry::setServiceLocator($original); + } + $this->assertSame($original, ServiceRegistry::getServiceLocator()); + } + + /** + * Without a locator, the default locator class is created once and then reused. + * + * @return void + */ + public function testDefaultLocatorIsCreatedLazily(): void + { + $original = ServiceRegistry::getServiceLocator(); + $property = new ReflectionProperty(ServiceRegistry::class, 'locator'); + try { + $property->setValue(null, null); + $locator = ServiceRegistry::getServiceLocator(); + $this->assertInstanceOf(ServiceLocator::class, $locator); + $this->assertNotSame($original, $locator); + $this->assertSame($locator, ServiceRegistry::getServiceLocator()); + } finally { + ServiceRegistry::setServiceLocator($original); + } + } } diff --git a/tests/TestCase/Service/ServiceRoutingTest.php b/tests/TestCase/Service/ServiceRoutingTest.php index 6fa86e85..7cd7bc80 100644 --- a/tests/TestCase/Service/ServiceRoutingTest.php +++ b/tests/TestCase/Service/ServiceRoutingTest.php @@ -2,19 +2,21 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; use Cake\Routing\Exception\MissingRouteException; use Cake\Routing\Route\Route; +use CakeDC\Api\Service\Action\DummyAction; +use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; @@ -32,7 +34,7 @@ protected function tearDown(): void parent::tearDown(); } - protected function buildService(string $serviceName = 'articles', string $baseUrl = '/articles', array $params = []): \CakeDC\Api\Service\Service + protected function buildService(string $serviceName = 'articles', string $baseUrl = '/articles', array $params = []): Service { ServiceRegistry::getServiceLocator()->clear(); $this->_initializeRequest([ @@ -105,6 +107,34 @@ public function testInnerServiceResolvedWithParent(): void $this->assertSame($service, $inner->getParentService()); } + public function testMappedRouteOptionsAreConnected(): void + { + $service = $this->buildService(); + $service->mapAction('named', DummyAction::class, [ + 'method' => ['GET'], + 'mapCors' => true, + 'path' => 'named/{code}', + 'patterns' => ['code' => '[0-9]+'], + 'pass' => ['code'], + 'name' => 'articlesNamed', + 'flag' => 'on', + ]); + + // the CORS route keeps the patterns, but not the name of the action route + $map = $service->routerDefaultOptions()['map']; + $this->assertArrayNotHasKey('name', $map['named_cors']); + $this->assertSame(['code' => '[0-9]+'], $map['named_cors']['patterns']); + + $route = $service->parseRoute('/articles/named/12'); + $this->assertSame('named', $route['action']); + $this->assertSame(['12'], $route['pass']); + $this->assertSame('on', $route['flag']); + $this->assertSame('/articles/named/12', $service->routeUrl(['_name' => 'articlesNamed', 'code' => '12'])); + + $this->expectException(MissingRouteException::class); + $service->parseRoute('/articles/named/abc'); + } + public function testGetParentServiceNullForRoot(): void { $service = $this->buildService(); diff --git a/tests/TestCase/Service/ServiceTest.php b/tests/TestCase/Service/ServiceTest.php index d4b14fef..d1b9e800 100644 --- a/tests/TestCase/Service/ServiceTest.php +++ b/tests/TestCase/Service/ServiceTest.php @@ -2,28 +2,41 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\App\Service; +use Cake\Controller\Exception\InvalidParameterException; use Cake\Core\Configure; use Cake\Core\Container; use Cake\Http\ServerRequest; use Cake\Routing\Exception\MissingRouteException; +use CakeDC\Api\Service\Action\DummyAction; use CakeDC\Api\Service\ConfigReader; +use CakeDC\Api\Service\Exception\MissingActionException; +use CakeDC\Api\Service\ExtensionRegistry; use CakeDC\Api\Service\FallbackService; +use CakeDC\Api\Service\RequestParser\FormParser; use CakeDC\Api\Service\Service; use CakeDC\Api\Service\ServiceRegistry; use CakeDC\Api\Test\App\DI\Service\TestService; +use CakeDC\Api\Test\App\Service\Action\ArticlesTagAction; +use CakeDC\Api\Test\App\Service\Action\ArticlesUntagAction; +use CakeDC\Api\Test\App\Service\Action\Author\IndexAction; use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\TestSuite\TestCase; +use ReflectionClass; +use ReflectionFunction; +use ReflectionMethod; +use ReflectionNamedType; +use ReflectionProperty; class ServiceTest extends TestCase { @@ -224,7 +237,7 @@ public function testInitializeActionStoredAsExistsClass(): void $this->assertTrue($Service instanceof Service); $this->assertTextEquals('/articles/tag/1', $Service->getBaseUrl()); $action = $Service->buildAction(); - $this->assertEquals(\CakeDC\Api\Test\App\Service\Action\ArticlesTagAction::class, $action::class); + $this->assertEquals(ArticlesTagAction::class, $action::class); } /** @@ -234,7 +247,7 @@ public function testInitializeActionStoredAsExistsClass(): void */ public function testInitializeActionByServiceConfigMap(): void { - $actionClass = \CakeDC\Api\Test\App\Service\Action\Author\IndexAction::class; + $actionClass = IndexAction::class; $this->_addSettingByPath('Service.authors.options', [ 'classMap' => [ 'index' => $actionClass, @@ -291,7 +304,7 @@ public function testActionInitializeContainer(): void 'request' => $this->request, 'response' => $this->response, 'baseUrl' => '/articles/data', - 'className' => \CakeDC\Api\Test\App\Service\ArticlesService::class, + 'className' => ArticlesService::class, 'container' => $this->container, ]; @@ -306,4 +319,323 @@ public function testActionInitializeContainer(): void $this->assertSame($action->getTestService(), $testService); $this->assertSame($action->getTestService(), $this->container->get(TestService::class)); } + + /** + * Builds a fallback service for the given url and method. + */ + private function buildService(string $baseUrl = '/articles', string $method = 'GET', array $options = []): Service + { + $this->_initializeRequest(['params' => ['service' => 'articles']], $method); + // the test ArticlesService reads this dependency when a container is set + $this->container->add(TestService::class, new TestService()); + + return ServiceRegistry::getServiceLocator()->get('articles', $options + [ + 'version' => null, + 'service' => 'articles', + 'request' => $this->request, + 'response' => $this->response, + 'baseUrl' => $baseUrl, + ]); + } + + /** + * Returns the [method, template] pairs of the service routes. + */ + private function routeMap(Service $service): array + { + $map = []; + foreach ($service->routes() as $route) { + $map[$route->getName()] = [(array)($route->defaults['_method'] ?? []), $route->template]; + } + + return $map; + } + + /** + * Test setParser replaces the parser and returns the service. + */ + public function testSetParser(): void + { + $service = $this->buildService(); + $parser = new FormParser($service); + $this->assertNotSame($parser, $service->getParser()); + $this->assertSame($service, $service->setParser($parser)); + $this->assertSame($parser, $service->getParser()); + } + + /** + * Test addAction defines a route whose action class is resolved by convention. + */ + public function testAddAction(): void + { + $service = $this->buildService('/articles/remove-tag/1'); + $classMap = $service->getActionsClassMap(); + $service->addAction('untag', ['method' => ['GET'], 'path' => 'remove-tag/{id}']); + + $this->assertSame($classMap, $service->getActionsClassMap()); + $routes = $this->routeMap($service); + $this->assertSame([['GET'], '/articles/remove-tag/{id}'], $routes['articles:untag']); + $this->assertArrayNotHasKey('articles:untag_cors', $routes); + + $action = $service->buildAction(); + $this->assertInstanceOf(ArticlesUntagAction::class, $action); + $this->assertSame('untag', $action->getName()); + } + + /** + * Test addAction defaults the path to the action name. + */ + public function testAddActionDefaultsPathToActionName(): void + { + $service = $this->buildService(); + $service->addAction('untag', ['method' => ['POST']]); + $this->assertSame([['POST'], '/articles/untag'], $this->routeMap($service)['articles:untag']); + } + + /** + * Test addAction with mapCors registers an OPTIONS route that is served by DummyAction, like mapAction does. + */ + public function testAddActionWithMapCors(): void + { + $service = $this->buildService('/articles/remove-tag/1', 'OPTIONS'); + $service->addAction('untag', ['method' => ['GET'], 'path' => 'remove-tag/{id}', 'mapCors' => true]); + + $routes = $this->routeMap($service); + $this->assertSame([['GET'], '/articles/remove-tag/{id}'], $routes['articles:untag']); + $this->assertSame([['OPTIONS'], '/articles/remove-tag/{id}'], $routes['articles:untag_cors']); + + $action = $service->buildAction(); + $this->assertInstanceOf(DummyAction::class, $action); + $this->assertSame('untag_cors', $action->getName()); + } + + /** + * Test an action route defined without a class and without a convention class is reported as missing. + */ + public function testAddActionWithoutConventionClass(): void + { + $service = $this->buildService('/articles/stats'); + $service->addAction('stats', ['method' => ['GET']]); + $this->expectException(MissingActionException::class); + $this->expectExceptionMessage('CakeDC\Api\Test\App\Service\Action\ArticlesStatsAction'); + $service->buildAction(); + } + + /** + * Test resource options are stored and merged into the router default options. + */ + public function testResourceOptions(): void + { + $service = $this->buildService(); + $this->assertSame([], $service->getResourceOptions()); + $this->assertSame($service, $service->setResourceOptions(['only' => ['index', 'view']])); + $this->assertSame(['only' => ['index', 'view']], $service->getResourceOptions()); + + $options = $service->routerDefaultOptions(); + $this->assertSame(['index', 'view'], $options['only']); + $this->assertArrayHasKey('map', $options); + + $routes = $this->routeMap($service); + $this->assertArrayHasKey('articles:index', $routes); + $this->assertArrayHasKey('articles:view', $routes); + $this->assertArrayNotHasKey('articles:add', $routes); + $this->assertArrayNotHasKey('articles:delete', $routes); + } + + /** + * Test the extension registry accessors. + */ + public function testGetExtensions(): void + { + $service = $this->buildService(); + $registry = $service->getExtensions(); + $this->assertInstanceOf(ExtensionRegistry::class, $registry); + $this->assertSame($registry, $service->getExtensions()); + + $custom = new ExtensionRegistry($service); + $this->assertSame($service, $service->setExtensions($custom)); + $this->assertSame($custom, $service->getExtensions()); + + // passing null builds a fresh registry + $service->setExtensions(null); + $this->assertNotSame($custom, $service->getExtensions()); + + // the registry is created lazily when none is set + (new ReflectionProperty($service, '_extensions'))->setValue($service, null); + $lazy = $service->getExtensions(); + $this->assertInstanceOf(ExtensionRegistry::class, $lazy); + $this->assertSame($lazy, $service->getExtensions()); + } + + /** + * Test the container accessor, and that the request is registered in the container. + */ + public function testGetContainer(): void + { + $this->assertNull($this->buildService()->getContainer()); + ServiceRegistry::getServiceLocator()->clear(); + + $service = $this->buildService('/articles', 'GET', ['container' => $this->container]); + $this->assertSame($this->container, $service->getContainer()); + $this->assertSame($this->request, $this->container->get(ServerRequest::class)); + } + + /** + * Calls the protected coerceStringToType() for a parameter declared with the given type. + */ + private function coerce(Service $service, string $argument, callable $signature): mixed + { + $type = (new ReflectionFunction($signature(...)))->getParameters()[0]->getType(); + $this->assertInstanceOf(ReflectionNamedType::class, $type); + + return (new ReflectionMethod($service, 'coerceStringToType'))->invoke($service, $argument, $type); + } + + /** + * Test coercion of string route arguments to each supported type, and null for invalid input. + */ + public function testCoerceStringToType(): void + { + $service = $this->buildService(); + $string = fn(string $value): null => null; + $float = fn(float $value): null => null; + $int = fn(int $value): null => null; + $bool = fn(bool $value): null => null; + $array = fn(array $value): null => null; + $object = fn(object $value): null => null; + + $this->assertSame('abc', $this->coerce($service, 'abc', $string)); + $this->assertSame('', $this->coerce($service, '', $string)); + + $this->assertSame(1.5, $this->coerce($service, '1.5', $float)); + $this->assertSame(2.0, $this->coerce($service, '2', $float)); + $this->assertSame(100.0, $this->coerce($service, '1e2', $float)); + $this->assertNull($this->coerce($service, 'abc', $float)); + $this->assertNull($this->coerce($service, '', $float)); + + $this->assertSame(42, $this->coerce($service, '42', $int)); + $this->assertSame(-7, $this->coerce($service, '-7', $int)); + $this->assertNull($this->coerce($service, '1.5', $int)); + $this->assertNull($this->coerce($service, 'abc', $int)); + $this->assertNull($this->coerce($service, '', $int)); + + $this->assertTrue($this->coerce($service, '1', $bool)); + $this->assertFalse($this->coerce($service, '0', $bool)); + $this->assertNull($this->coerce($service, 'true', $bool)); + $this->assertNull($this->coerce($service, '', $bool)); + + $this->assertSame([], $this->coerce($service, '', $array)); + $this->assertSame(['a'], $this->coerce($service, 'a', $array)); + $this->assertSame(['a', 'b', 'c'], $this->coerce($service, 'a,b,c', $array)); + + // unsupported types cannot be coerced + $this->assertNull($this->coerce($service, 'abc', $object)); + } + + /** + * Calls the protected getActionArgs() for the constructor of the given object. + */ + private function actionArgs(Service $service, object $action, array $passed): array + { + return (new ReflectionMethod($service, 'getActionArgs')) + ->invoke($service, new ReflectionClass($action), $passed, 'view'); + } + + /** + * Test constructor arguments are resolved from the container, passed params (coerced) and defaults. + */ + public function testGetActionArgs(): void + { + $service = $this->buildService('/articles', 'GET', ['container' => $this->container]); + $testService = $this->container->get(TestService::class); + $action = new class ($testService, 1, true) { + public function __construct( + public TestService $testService, + public int $id, + public bool $flag, + public string $label = 'none', + public ?Container $container = null, + ) { + } + }; + + $args = $this->actionArgs($service, $action, ['5', '1']); + $this->assertSame([$testService, 5, true, 'none', null], $args); + + // extra passed params are appended + $args = $this->actionArgs($service, $action, ['5', '0', 'label', 'extra']); + $this->assertSame([$testService, 5, false, 'label', null, 'extra'], $args); + } + + /** + * Test a passed string that cannot be coerced is rejected. + */ + public function testGetActionArgsFailedCoercion(): void + { + $service = $this->buildService('/articles', 'GET', ['container' => $this->container]); + $action = new class (1) { + public function __construct(public int $id) + { + } + }; + + $this->expectException(InvalidParameterException::class); + $this->expectExceptionMessage('Unable to coerce `abc` to `int` for `id` in action `articles::view()`.'); + $this->actionArgs($service, $action, ['abc']); + } + + /** + * Test a required scalar parameter without a passed value is rejected. + */ + public function testGetActionArgsMissingParameter(): void + { + $service = $this->buildService('/articles', 'GET', ['container' => $this->container]); + $action = new class (1) { + public function __construct(public int $id) + { + } + }; + + $this->expectException(InvalidParameterException::class); + $this->expectExceptionMessage('Missing passed parameter for `id` in action `articles::view()`.'); + $this->actionArgs($service, $action, []); + } + + /** + * Test a required class dependency missing from the container is rejected. + */ + public function testGetActionArgsMissingDependency(): void + { + $service = $this->buildService('/articles', 'GET', ['container' => $this->container]); + $action = new class (new ConfigReader()) { + public function __construct(public ConfigReader $reader) + { + } + }; + + $this->expectException(InvalidParameterException::class); + $this->expectExceptionMessage(sprintf( + 'Failed to inject dependency from service container for parameter `reader` ' . + 'with type `%s` in action `articles::view()`.', + ConfigReader::class, + )); + $this->actionArgs($service, $action, []); + } + + /** + * Test union type declarations are rejected. + */ + public function testGetActionArgsUnsupportedType(): void + { + $service = $this->buildService('/articles', 'GET', ['container' => $this->container]); + $action = new class (1) { + public function __construct(public int|string $id) + { + } + }; + + $this->expectException(InvalidParameterException::class); + $this->expectExceptionMessage('Type declaration for `id` in action `articles::view()` is unsupported.'); + $this->actionArgs($service, $action, ['1']); + } } diff --git a/tests/TestCase/Service/TwoFactorAuthenticationTest.php b/tests/TestCase/Service/TwoFactorAuthenticationTest.php index 9100f2b2..92ed39eb 100644 --- a/tests/TestCase/Service/TwoFactorAuthenticationTest.php +++ b/tests/TestCase/Service/TwoFactorAuthenticationTest.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Service; @@ -19,6 +19,8 @@ use CakeDC\Api\Service\Auth\TwoFactorAuthentication\OneTimePasswordAuthenticationCheckerFactory; use CakeDC\Api\Service\Auth\TwoFactorAuthentication\Webauthn2fAuthenticationCheckerFactory; use CakeDC\Api\TestSuite\TestCase; +use InvalidArgumentException; +use stdClass; /** * Unit tests for the 2FA authentication checkers and their factories. @@ -105,8 +107,8 @@ public function testOtpFactoryBuildsDefaultChecker(): void public function testOtpFactoryRejectsInvalidChecker(): void { - $this->expectException(\InvalidArgumentException::class); - Configure::write('Api.OneTimePasswordAuthenticator.checker', \stdClass::class); + $this->expectException(InvalidArgumentException::class); + Configure::write('Api.OneTimePasswordAuthenticator.checker', stdClass::class); (new OneTimePasswordAuthenticationCheckerFactory())->build(); } @@ -120,8 +122,8 @@ public function testWebauthnFactoryBuildsDefaultChecker(): void public function testWebauthnFactoryRejectsInvalidChecker(): void { - $this->expectException(\InvalidArgumentException::class); - Configure::write('Api.Webauthn2fa.checker', \stdClass::class); + $this->expectException(InvalidArgumentException::class); + Configure::write('Api.Webauthn2fa.checker', stdClass::class); (new Webauthn2fAuthenticationCheckerFactory())->build(); } } diff --git a/tests/TestCase/Transformer/AbstractTransformerTest.php b/tests/TestCase/Transformer/AbstractTransformerTest.php index 33705611..c50512c6 100644 --- a/tests/TestCase/Transformer/AbstractTransformerTest.php +++ b/tests/TestCase/Transformer/AbstractTransformerTest.php @@ -2,20 +2,23 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Transformer; +use Cake\I18n\Date; use Cake\I18n\DateTime; use Cake\ORM\Entity; use CakeDC\Api\TestSuite\TestCase; +use DateTime as NativeDateTime; +use stdClass; /** * Unit tests for the transformer helper methods. @@ -50,7 +53,7 @@ public function testGetFromArray(): void public function testGetFromObjectProperty(): void { - $obj = new \stdClass(); + $obj = new stdClass(); $obj->title = 'Hello'; $this->assertSame('Hello', $this->transformer->exposedGet($obj, 'title')); } @@ -90,7 +93,7 @@ public function testTimestampCakeDateTime(): void public function testTimestampPhpDateTime(): void { - $date = new \DateTime('2024-02-20 08:30:00'); + $date = new NativeDateTime('2024-02-20 08:30:00'); $result = $this->transformer->exposedTimestamp($date); $this->assertIsString($result); $this->assertStringStartsWith('2024-02-20T08:30:00', $result); @@ -103,6 +106,21 @@ public function testTimestampStringDate(): void $this->assertStringStartsWith('2024-03-01', $result); } + public function testTimestampCakeDate(): void + { + $result = $this->transformer->exposedTimestamp(new Date('2024-05-06')); + $this->assertIsString($result); + $this->assertStringStartsWith('2024-05-06T00:00:00', $result); + } + + public function testTimestampUnsupportedTypeReturnsNull(): void + { + // integers (e.g. unix timestamps), arrays and other objects are not formatted + $this->assertNull($this->transformer->exposedTimestamp(1700000000)); + $this->assertNull($this->transformer->exposedTimestamp(['2024-01-01'])); + $this->assertNull($this->transformer->exposedTimestamp(new stdClass())); + } + public function testTimestampInvalidStringReturnsNull(): void { $this->assertNull($this->transformer->exposedTimestamp('not-a-date')); diff --git a/tests/TestCase/Transformer/TestTransformer.php b/tests/TestCase/Transformer/TestTransformer.php index 10132a7b..b5b6be6b 100644 --- a/tests/TestCase/Transformer/TestTransformer.php +++ b/tests/TestCase/Transformer/TestTransformer.php @@ -2,13 +2,13 @@ declare(strict_types=1); /** - * Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2026, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Transformer; diff --git a/tests/TestCase/Utility/LegacyMemberGuardTest.php b/tests/TestCase/Utility/LegacyMemberGuardTest.php new file mode 100644 index 00000000..acaf551c --- /dev/null +++ b/tests/TestCase/Utility/LegacyMemberGuardTest.php @@ -0,0 +1,265 @@ +expectException(CakeException::class); + $this->expectExceptionMessage('::_getEntitiesQuery() (now getEntitiesQuery())'); + + // an app action that scoped the index query through the old hook + new class extends CrudIndexAction { + protected function _getEntitiesQuery(): SelectQuery + { + return $this->getTable()->find()->where(['owner_id' => 1]); + } + }; + } + + public function testServiceDeclaringAnOldPropertyIsRefused(): void + { + $this->expectException(CakeException::class); + $this->expectExceptionMessage('::$_table (now $table)'); + + new class extends FallbackService { + protected $_table = 'Articles'; + }; + } + + public function testOldNameOfAnotherPackageTraitPasses(): void + { + // the cakedc/auth trait still names its method `_getReCaptchaInstance()`, and an application + // cannot rename it; Action has no `getReCaptchaInstance()`, so nothing is overridden + $object = new class extends Action { + use AuthReCaptchaTrait; + + /** + * No service is needed for this check. + */ + public function __construct() + { + } + + public function execute(): mixed + { + return null; + } + }; + + LegacyMemberGuard::check($object, LegacyMemberGuard::ACTION); + $this->assertTrue(method_exists($object, '_getReCaptchaInstance')); + } + + public function testPrivateHelperWithAnOldNamePasses(): void + { + // a private method cannot have overridden a protected one, so it is the application's own helper + $object = new class extends CursorPaginateExtension { + /** + * No registry is needed for this check. + */ + public function __construct() + { + } + + private function _count(): int + { + return 0; + } + + public function helper(): int + { + return $this->_count(); + } + }; + + LegacyMemberGuard::check($object, LegacyMemberGuard::ACTION_EXTENSION); + $this->assertSame(0, $object->helper()); + } + + public function testOldNameInATraitOfTheApplicationIsRefused(): void + { + $this->expectException(CakeException::class); + $this->expectExceptionMessage('::_getEntitiesQuery() (now getEntitiesQuery())'); + + new class extends CrudIndexAction { + use LegacyScopeTrait; + }; + } + + public function testOldNameOfAPluginTraitIsRefused(): void + { + $this->expectException(CakeException::class); + $this->expectExceptionMessage('::_getReCaptchaInstance() (now getReCaptchaInstance())'); + + // the new name comes from the plugin trait, not from Action, and the override is never called + new class extends Action { + use ReCaptchaTrait; + + protected function _getReCaptchaInstance(): ?object + { + return null; + } + + public function execute(): mixed + { + return null; + } + }; + } + + public function testOldSortHelperWithThePluginTraitIsRefused(): void + { + $object = new class extends ActionExtension { + use SortableTrait; + + /** + * No registry is needed for this check. + */ + public function __construct() + { + } + + public function implementedEvents(): array + { + return []; + } + + protected function _sortField(?Action $action, mixed $field): ?string + { + return $field === 'title' ? 'title' : null; + } + }; + + $this->expectException(CakeException::class); + $this->expectExceptionMessage('::_sortField() (now sortField())'); + LegacyMemberGuard::check($object, LegacyMemberGuard::ACTION_EXTENSION); + } + + public function testOldSecondFactorCheckIsRefused(): void + { + $this->expectException(CakeException::class); + $this->expectExceptionMessage('::_hasWebauthnCredential() (now hasWebauthnCredential())'); + + // 12.0.2 and 12.0.3 named the enrollment checks with an underscore; an override that keeps the + // old name is never asked, so the plugin's own check would decide who may enroll a second factor + new class extends Action { + use SecondFactorTrait; + + protected function _hasWebauthnCredential(mixed $identity): bool + { + return true; + } + + public function execute(): mixed + { + return null; + } + }; + } + + public function testOffSwitchSetBeforeThePluginConfigLoadsIsKept(): void + { + $api = Configure::read('Api'); + Configure::write('Api.legacyMemberGuard', false); + try { + // the plugin bootstrap loads this file after the application has set its configuration + Configure::load('CakeDC/Api.api'); + $this->assertFalse(Configure::read('Api.legacyMemberGuard')); + } finally { + Configure::delete('Api'); + if ($api !== null) { + Configure::write('Api', $api); + } + } + } + + public function testOnlyTheBooleanFalseTurnsTheGuardOff(): void + { + // a string, as read from an environment variable, leaves the check on + Configure::write('Api.legacyMemberGuard', 'false'); + try { + $this->expectException(CakeException::class); + new class extends CrudIndexAction { + protected function _getEntitiesQuery(): SelectQuery + { + return $this->getTable()->find(); + } + }; + } finally { + Configure::delete('Api.legacyMemberGuard'); + } + } + + public function testGuardCanBeTurnedOff(): void + { + Configure::write('Api.legacyMemberGuard', false); + try { + $object = new class extends CrudIndexAction { + /** + * No service is needed for this check. + */ + public function __construct() + { + } + + protected function _getEntitiesQuery(): SelectQuery + { + return $this->getTable()->find(); + } + }; + LegacyMemberGuard::check($object, LegacyMemberGuard::ACTION); + } finally { + Configure::delete('Api.legacyMemberGuard'); + } + + // turning the guard off does not mark the class as checked + $this->expectException(CakeException::class); + LegacyMemberGuard::check($object, LegacyMemberGuard::ACTION); + } + + public function testCurrentNamesPass(): void + { + $object = new class { + protected ?string $table = 'Articles'; + + protected function getEntitiesQuery(): string + { + return 'a member with its current name'; + } + }; + LegacyMemberGuard::check($object, LegacyMemberGuard::ACTION); + LegacyMemberGuard::check($object, LegacyMemberGuard::SERVICE); + $this->assertTrue(true); + } +} diff --git a/tests/TestCase/Utility/LegacyScopeTrait.php b/tests/TestCase/Utility/LegacyScopeTrait.php new file mode 100644 index 00000000..5fc68ac5 --- /dev/null +++ b/tests/TestCase/Utility/LegacyScopeTrait.php @@ -0,0 +1,30 @@ +getTable()->find()->where(['owner_id' => 1]); + } +} diff --git a/tests/TestCase/Webauthn/Base64UtilityTest.php b/tests/TestCase/Webauthn/Base64UtilityTest.php index ef7ff836..1092ba7a 100644 --- a/tests/TestCase/Webauthn/Base64UtilityTest.php +++ b/tests/TestCase/Webauthn/Base64UtilityTest.php @@ -2,19 +2,20 @@ declare(strict_types=1); /** - * Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2010 - 2023, Cake Development Corporation (https://www.cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ namespace CakeDC\Api\Test\TestCase\Webauthn; use Cake\TestSuite\TestCase; -use CakeDC\Users\Webauthn\Base64Utility; +use CakeDC\Api\Webauthn\Base64Utility; +use InvalidArgumentException; use ParagonIE\ConstantTime\Base64UrlSafe; use PHPUnit\Framework\Attributes\DataProvider; @@ -79,4 +80,40 @@ public static function dataProviderComplyEncodedNoPadding(): array ['Rmlyc3QgTmFtZQ==', 'First Name'], ]; } + + /** + * basicEncode keeps the padding on request and uses the URL safe alphabet. + * + * @return void + */ + public function testBasicEncodeWithPadding(): void + { + $this->assertSame('Rmlyc3QgTmFtZQ==', Base64Utility::basicEncode('First Name', true)); + $this->assertSame('Rmlyc3QgTmFtZQ', Base64Utility::basicEncode('First Name')); + $this->assertSame('-_8', Base64Utility::basicEncode("\xfb\xff")); + $this->assertSame("\xfb\xff", Base64Utility::basicDecode('-_8')); + } + + /** + * basicDecode rejects data outside the base64 alphabet. + * + * @return void + */ + public function testBasicDecodeInvalidData(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid data provided'); + Base64Utility::basicDecode('not base64!'); + } + + /** + * complyEncodedNoPadding rejects invalid input as well. + * + * @return void + */ + public function testComplyEncodedNoPaddingInvalidData(): void + { + $this->expectException(InvalidArgumentException::class); + Base64Utility::complyEncodedNoPadding('*invalid*'); + } } diff --git a/tests/TestCase/Webauthn/RegisterAdapterTest.php b/tests/TestCase/Webauthn/RegisterAdapterTest.php new file mode 100644 index 00000000..c91245f9 --- /dev/null +++ b/tests/TestCase/Webauthn/RegisterAdapterTest.php @@ -0,0 +1,142 @@ + 'example', 'id' => 'example.com']); + } + + protected function tearDown(): void + { + Configure::delete('Api.Webauthn2fa.example$com'); + parent::tearDown(); + } + + /** + * @param array $headers Request headers. + * @return \CakeDC\Api\Webauthn\RegisterAdapter + */ + protected function adapter(array $headers = []): RegisterAdapter + { + $environment = ['HTTP_HOST' => 'example.com']; + foreach ($headers as $name => $value) { + $environment['HTTP_' . strtoupper($name)] = $value; + } + $users = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + + return new RegisterAdapter(new ServerRequest(['environment' => $environment]), $users, $users->get(Settings::USER1)); + } + + public function testStoreKeyIsTheBearerToken(): void + { + $this->assertSame('a.jwt.token', $this->adapter(['Authorization' => 'Bearer a.jwt.token'])->getStoreKey()); + } + + public function testAdapterWorksWithoutAnAuthorizationHeader(): void + { + // a session login has no bearer token; checking for credentials must not fail + $adapter = $this->adapter(); + + $this->assertSame('', $adapter->getStoreKey()); + $this->assertFalse($adapter->hasCredential()); + $this->assertFalse($adapter->hasCredentialOnAnyDomain()); + } + + public function testOptionsNeedABearerToken(): void + { + // without a token the ceremony data would be shared by every such request + $this->expectException(BadRequestException::class); + $this->adapter()->getOptions(); + } + + /** + * An adapter for the `localhost` domain, which the software authenticator signs for. + * + * @param array $data Request body. + * @return \CakeDC\Api\Webauthn\RegisterAdapter + */ + protected function localAdapter(array $data = []): RegisterAdapter + { + $users = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $request = new ServerRequest([ + 'environment' => ['HTTP_HOST' => 'localhost', 'HTTP_AUTHORIZATION' => 'Bearer a.jwt.token'], + 'post' => $data, + ]); + + return new RegisterAdapter($request, $users, $users->get(Settings::USER1)); + } + + public function testCredentialIdThatIsAlreadyRegisteredIsRefused(): void + { + Configure::write('Api.Webauthn2fa.localhost', ['appName' => 'local', 'id' => 'localhost']); + try { + $credentialId = random_bytes(16); + $adapter = $this->localAdapter(); + $challenge = $adapter->getOptionsData($adapter->getOptions())['challenge']; + $credential = $this->localAdapter($this->attestation($this->newKey(), $credentialId, $challenge)) + ->verifyResponse(); + $this->assertSame($credentialId, $credential->publicKeyCredentialId); + $this->assertTrue($this->localAdapter()->hasCredential()); + + // the same credential id again, with a valid response for new options + $adapter = $this->localAdapter(); + $challenge = $adapter->getOptionsData($adapter->getOptions())['challenge']; + $adapter = $this->localAdapter($this->attestation($this->newKey(), $credentialId, $challenge)); + + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('The credential is already registered'); + $adapter->verifyResponse(); + } finally { + Configure::delete('Api.Webauthn2fa.localhost'); + } + } + + public function testDomainWithoutSettingsIsRefused(): void + { + Configure::delete('Api.Webauthn2fa.example$com'); + + $this->expectException(BadRequestException::class); + $this->expectExceptionMessage('WebAuthn is not configured for this domain'); + $this->adapter(); + } + + public function testStoreIsNotSavedWithoutABearerToken(): void + { + $this->expectException(BadRequestException::class); + $this->adapter()->saveStore(['api' => []]); + } +} diff --git a/tests/TestCase/Webauthn/Repository/UserCredentialSourceRepositoryTest.php b/tests/TestCase/Webauthn/Repository/UserCredentialSourceRepositoryTest.php new file mode 100644 index 00000000..e37c024e --- /dev/null +++ b/tests/TestCase/Webauthn/Repository/UserCredentialSourceRepositoryTest.php @@ -0,0 +1,190 @@ + ['HTTP_HOST' => 'example.com']]); + + return new UserCredentialSourceRepository($request, $user, TableRegistry::getTableLocator()->get('CakeDC/Users.Users')); + } + + /** + * Builds a credential record. + * + * @param string $credentialId Credential id. + * @return \Webauthn\CredentialRecord + */ + protected function getCredential(string $credentialId): CredentialRecord + { + return CredentialRecord::create( + $credentialId, + 'public-key', + ['usb'], + 'none', + EmptyTrustPath::create(), + Uuid::fromString('00000000-0000-0000-0000-000000000000'), + 'public-key-data', + Settings::USER1, + 7, + ); + } + + public function testSavedCredentialCanBeFound(): void + { + $usersTable = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $user = $usersTable->get(Settings::USER1); + $user->set('additional_data', ['other' => 'kept']); + + $usersTable->saveOrFail($user); + + $this->getRepository($user)->saveCredentialSource($this->getCredential('credential-1')); + + $user = $usersTable->get(Settings::USER1); + $repository = $this->getRepository($user); + $found = $repository->findOneByCredentialId('credential-1'); + $this->assertInstanceOf(CredentialRecord::class, $found); + $this->assertSame('credential-1', $found->publicKeyCredentialId); + $this->assertSame('public-key-data', $found->credentialPublicKey); + $this->assertSame(Settings::USER1, $found->userHandle); + $this->assertSame(['usb'], $found->transports); + $this->assertSame(7, $found->counter); + $this->assertNull($repository->findOneByCredentialId('credential-2')); + + $additionalData = $user->get('additional_data'); + $this->assertSame('kept', $additionalData['other']); + $this->assertArrayHasKey('webauthn_credentials', $additionalData['api'][$repository->getDomain()]); + } + + public function testSavedCredentialKeepsTheShapeOfEarlierVersions(): void + { + $usersTable = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $user = $usersTable->get(Settings::USER1); + $repository = $this->getRepository($user); + $repository->saveCredentialSource($this->getCredential('credential-1')); + + $key = Base64Utility::basicEncode('credential-1'); + $stored = $repository->getUserData($usersTable->get(Settings::USER1)); + $this->assertSame([$key], array_keys($stored)); + // unpadded base64url values, a 36 character AAGUID, and a trust path named by its class: + // the entry 13.x wrote, which its PublicKeyCredentialSource::createFromArray() can read back + $this->assertSame($key, $stored[$key]['publicKeyCredentialId']); + $this->assertSame(Base64Utility::basicEncode('public-key-data'), $stored[$key]['credentialPublicKey']); + $this->assertSame(Base64Utility::basicEncode(Settings::USER1), $stored[$key]['userHandle']); + $this->assertSame('public-key', $stored[$key]['type']); + $this->assertSame(['usb'], $stored[$key]['transports']); + $this->assertSame('none', $stored[$key]['attestationType']); + $this->assertSame(['type' => EmptyTrustPath::class], $stored[$key]['trustPath']); + $this->assertSame('00000000-0000-0000-0000-000000000000', $stored[$key]['aaguid']); + $this->assertSame(7, $stored[$key]['counter']); + } + + public function testCertificateTrustPathIsStoredWithItsClass(): void + { + // an application that adds attestation formats gets certificate trust paths + $usersTable = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $user = $usersTable->get(Settings::USER1); + $repository = $this->getRepository($user); + $record = $this->getCredential('credential-1'); + $record->trustPath = CertificateTrustPath::create(['certificate-1', 'certificate-2']); + + $repository->saveCredentialSource($record); + + $stored = $repository->getUserData($usersTable->get(Settings::USER1)); + $this->assertSame( + ['type' => CertificateTrustPath::class, 'x5c' => ['certificate-1', 'certificate-2']], + $stored[Base64Utility::basicEncode('credential-1')]['trustPath'], + ); + + $found = $this->getRepository($usersTable->get(Settings::USER1))->findOneByCredentialId('credential-1'); + $this->assertInstanceOf(CertificateTrustPath::class, $found->trustPath); + $this->assertSame(['certificate-1', 'certificate-2'], $found->trustPath->certificates); + } + + public function testCredentialStoredByEarlierVersionsIsRead(): void + { + // the entry web-auth/webauthn-lib 4.4 wrote through PublicKeyCredentialSource::jsonSerialize() + $key = Base64Utility::basicEncode('credential-1'); + $usersTable = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $user = $usersTable->get(Settings::USER1); + $user->set('additional_data', ['api' => ['example$com' => ['webauthn_credentials' => [$key => [ + 'publicKeyCredentialId' => $key, + 'type' => 'public-key', + 'transports' => [], + 'attestationType' => 'none', + 'trustPath' => ['type' => EmptyTrustPath::class], + 'aaguid' => '00000000-0000-0000-0000-000000000000', + 'credentialPublicKey' => Base64Utility::basicEncode('public-key-data'), + 'userHandle' => Base64Utility::basicEncode(Settings::USER1), + 'counter' => 3, + 'otherUI' => null, + ]]]]]); + $repository = $this->getRepository($user); + + $found = $repository->findOneByCredentialId('credential-1'); + $this->assertInstanceOf(CredentialRecord::class, $found); + $this->assertSame('credential-1', $found->publicKeyCredentialId); + $this->assertSame('public-key-data', $found->credentialPublicKey); + $this->assertSame(Settings::USER1, $found->userHandle); + $this->assertSame(3, $found->counter); + $this->assertInstanceOf(EmptyTrustPath::class, $found->trustPath); + + $all = $repository->findAllForUserEntity(PublicKeyCredentialUserEntity::create('user-1', Settings::USER1, 'User')); + $this->assertCount(1, $all); + $this->assertSame('credential-1', $all[0]->publicKeyCredentialId); + // another user's entity gets none of them + $this->assertSame([], $repository->findAllForUserEntity(PublicKeyCredentialUserEntity::create('x', 'other-id', 'X'))); + } + + public function testPatchUserDataKeepsOtherDomains(): void + { + $user = TableRegistry::getTableLocator()->get('CakeDC/Users.Users')->newEmptyEntity(); + $user->set('additional_data', ['api' => ['other.com' => ['webauthn_credentials' => ['a' => []]]]]); + + $repository = $this->getRepository($user); + $repository->patchUserData($user, ['b' => []]); + + $this->assertSame(['b' => []], $repository->getUserData($user)); + $this->assertSame(['a' => []], $user->get('additional_data')['api']['other.com']['webauthn_credentials']); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 8cfdbe5b..cddb74e5 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -2,20 +2,27 @@ declare(strict_types=1); /** - * Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) + * Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * - * @copyright Copyright 2016 - 2019, Cake Development Corporation (http://cakedc.com) - * @license MIT License (http://www.opensource.org/licenses/mit-license.php) + * @copyright Copyright 2016 - 2026, Cake Development Corporation (https://cakedc.com) + * @license MIT License (https://www.opensource.org/licenses/mit-license.php) */ +use Cake\Cache\Cache; use Cake\Core\Configure; +use Cake\Datasource\ConnectionManager; use Cake\Error\ErrorTrap; use Cake\Error\ExceptionTrap; use Cake\Mailer\Mailer; +use Cake\Mailer\TransportFactory; +use Cake\Routing\Router; +use Cake\TestSuite\Fixture\SchemaLoader; use Cake\Utility\Security; +use CakeDC\Api\Test\App\Application; +use CakeDC\Api\Test\App\Controller\AppController; $findRoot = function (): ?string { $root = dirname(__DIR__); @@ -81,7 +88,7 @@ function def($name, $value): void // Cake\Core\Configure::write('App.namespace', 'CakeDC\Api\Test\App'); // Cake\Core\Configure::write('App.encoding', 'UTF-8'); -Cake\Core\Configure::write('debug', true); +Configure::write('debug', true); if (!file_exists(TMP . 'cache/models')) { mkdir(TMP . 'cache/models', 0777, true); @@ -113,8 +120,8 @@ function def($name, $value): void ], ]; -Cake\Cache\Cache::setConfig($cache); -Cake\Core\Configure::write('EmailTransport', [ +Cache::setConfig($cache); +Configure::write('EmailTransport', [ 'default' => [ 'className' => 'Debug', 'host' => 'localhost', @@ -127,24 +134,24 @@ function def($name, $value): void 'log' => true, ], ]); -Cake\Core\Configure::write('Email', [ +Configure::write('Email', [ 'default' => [ 'transport' => 'default', 'from' => 'test@localhost', 'log' => true, ], ]); -Cake\Core\Configure::write('Session', [ +Configure::write('Session', [ 'defaults' => 'php', ]); session_id('cli'); date_default_timezone_set('UTC'); -Cake\Core\Configure::write('Security.salt', 'bc8b5b70eb0e18bac40204dc3a5b9fbc8b5b70eb0e18bac40204dc3a5b9f'); +Configure::write('Security.salt', 'bc8b5b70eb0e18bac40204dc3a5b9fbc8b5b70eb0e18bac40204dc3a5b9f'); mb_internal_encoding(Configure::read('App.encoding')); Security::setSalt(Configure::read('Security.salt')); -\Cake\Mailer\TransportFactory::setConfig(Configure::consume('EmailTransport')); +TransportFactory::setConfig(Configure::consume('EmailTransport')); Mailer::setConfig(Configure::consume('Email')); // Ensure default test connection is defined @@ -152,23 +159,22 @@ function def($name, $value): void putenv('db_dsn=sqlite:///:memory:'); } -Cake\Datasource\ConnectionManager::setConfig('test', [ +ConnectionManager::setConfig('test', [ 'url' => getenv('db_dsn'), 'timezone' => 'UTC', ]); if (env('FIXTURE_SCHEMA_METADATA')) { - $loader = new \Cake\TestSuite\Fixture\SchemaLoader(); + $loader = new SchemaLoader(); $loader->loadInternalFile(env('FIXTURE_SCHEMA_METADATA')); } -class_alias(\CakeDC\Api\Test\App\Controller\AppController::class, 'App\Controller\AppController'); +class_alias(AppController::class, 'App\Controller\AppController'); -$isCli = PHP_SAPI === 'cli'; -$conf = (array)Cake\Core\Configure::read('Error'); +$conf = (array)Configure::read('Error'); (new ErrorTrap($conf))->register(); (new ExceptionTrap($conf))->register(); -\Cake\Routing\Router::reload(); -$application = new \CakeDC\Api\Test\App\Application(CONFIG); +Router::reload(); +$application = new Application(CONFIG); $application->bootstrap(); $application->pluginBootstrap(); diff --git a/tests/schema.php b/tests/schema.php index b3c67ae8..e538af4b 100644 --- a/tests/schema.php +++ b/tests/schema.php @@ -1,6 +1,16 @@ 'auth_store', 'columns' => [ - 'id' => ['type' => 'uuid', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], + 'id' => ['type' => 'string', 'length' => 500, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], 'store' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null], 'created' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], 'modified' => ['type' => 'datetime', 'length' => null, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null], diff --git a/webroot/empty b/webroot/empty deleted file mode 100644 index e69de29b..00000000 From 0b91cc0756b20348a4ea76e23bd1409ab7dbfe2a Mon Sep 17 00:00:00 2001 From: Adam Rusinowski Date: Tue, 1 Dec 2026 14:51:31 +0100 Subject: [PATCH 2/2] Offer EdDSA only with ext-sodium and document Ed256 and Ed512 keys that no longer log in --- CHANGELOG.md | 3 +- composer.json | 3 +- docs/Documentation/upgrading.md | 3 +- src/Webauthn/BaseAdapter.php | 20 +++++++++-- .../Action/Auth/Webauthn2faFlowTest.php | 35 ++++++++++++++++++ .../TestCase/Webauthn/RegisterAdapterTest.php | 36 +++++++++++++++++++ 6 files changed, 94 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cf825f0..9b1df607 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ Releases for CakePHP 5.4 * Breaking: FlysystemRenderer uses Flysystem v3 (`league/flysystem` ^3.35.3, which includes the fix for CVE-2026-102601). The result `filesystem` must be a `League\Flysystem\FilesystemOperator`, `deliverAsset()` now takes the filesystem and path instead of a v1 `File`, and `getFile()` is removed. A missing file or an invalid path gives a 404; other storage errors, such as an unreachable backend, now reach the error renderer instead. Flysystem v1 and the composer patches for it are dropped. * Breaking: the OTP 2FA actions need `robthree/twofactorauth` ^3.0.1 and `endroid/qr-code` ^5.0 || ^6.0; versions 1 and 2 of `robthree/twofactorauth` no longer work. A string `algorithm` setting (for example `'sha1'`) is still accepted. `robthree/twofactorauth` 3 requires a QR code provider, so when `OneTimePasswordAuthenticator.qrcodeprovider` is null every OTP action fails in `initialize()`, including `otp_verify_check`, which does not use a QR code. The `cakedc/users` default config sets an `EndroidQrCodeProvider`; an app that overrides `OneTimePasswordAuthenticator` must keep a provider. * Breaking: the members that lost their leading underscore in 13.0.0, for example `_getEntitiesQuery()` and `$_table`, are now checked. An override that keeps an old name is silently never called, so the constructors of actions, services, extensions, renderers and parsers now throw a `CakeException` listing such members. A member is reported only when the plugin class that the class extends, or a plugin trait that the class uses, has the new name; private members and the old names of traits from other packages, such as `_getReCaptchaInstance()` of cakedc/auth, are not. `Api.legacyMemberGuard` set to the boolean `false` in the application configuration turns the check off. See the full list in [Upgrading to 14.x](docs/Documentation/upgrading.md#renamed-protected-members). - * Breaking: `OtpVerifyGetAction::onVerifyGetSecret()` no longer types its `$user` parameter as `array`, because the identity is an entity; an override must drop the `array` type. A subclass of `JwtRefreshAction` that reads `$this->payload` gets an array instead of an object; this changed in 13.0.1 and was not listed there. `SecondFactorTrait::hasVerifiedOtp()` and `hasWebauthnCredential()` type their parameter as `EntityInterface|array|null`, so a call with an identity of another type fails with a `TypeError`. WebAuthn no longer offers the non-standard `Ed256` and `Ed512` algorithms; `EdDSA` (Ed25519) is offered instead. + * Breaking: `OtpVerifyGetAction::onVerifyGetSecret()` no longer types its `$user` parameter as `array`, because the identity is an entity; an override must drop the `array` type. A subclass of `JwtRefreshAction` that reads `$this->payload` gets an array instead of an object; this changed in 13.0.1 and was not listed there. `SecondFactorTrait::hasVerifiedOtp()` and `hasWebauthnCredential()` type their parameter as `EntityInterface|array|null`, so a call with an identity of another type fails with a `TypeError`. WebAuthn no longer offers or verifies the non-standard `Ed256` and `Ed512` algorithms; `EdDSA` (Ed25519) is offered instead. A key registered with one of them can no longer log in, and its entry must be removed before the user can register again; see the upgrade guide. * Breaking: WebAuthn two-factor authentication needs `web-auth/webauthn-lib` ^5.3.13, the first release without open security advisories; 4.x is no longer supported. Registered keys keep working: stored credentials are read as they are, and are still written in a form that 13.x can read. A registration or login that was started before the upgrade must be started again, because only the challenge is stored between the two requests now, not a serialized options object. The JSON that clients receive and send keeps its shape, and standard base64 is still accepted in responses. A response sent from a cross-origin frame (one that carries `topOrigin`) is refused. For code that extends the plugin: `CakeDC\Api\Webauthn\PublicKeyCredentialLoader` is removed; `UserCredentialSourceRepository` no longer implements the library's removed repository interface and works with `Webauthn\CredentialRecord`; `verifyResponse()` of both adapters returns a `CredentialRecord`; and the `webauthn2fa_register_options` and `webauthn2fa_auth_options` actions return the options as an array, built by the new `BaseAdapter::getOptionsData()`. `cakedc/users` ^17.1 is now required: 17.1 uses the same `web-auth/webauthn-lib` version, so the WebAuthn pages of that plugin and the WebAuthn endpoints of this one work in the same application. See [Upgrading to 14.x](docs/Documentation/upgrading.md#webauthn-with-web-authwebauthn-lib-5). * WebAuthn: a domain without an `Api.Webauthn2fa.` entry is answered with code 400 and "WebAuthn is not configured for this domain" instead of failing with a `TypeError`; a credential id that is already registered is refused; and registration options requested a second time with the same token are now stored, so the retry no longer fails with an invalid challenge. * Require `firebase/php-jwt` ^7.0 (used by the `Authentication.Jwt` authenticator), which includes the fix for CVE-2025-45769. @@ -30,6 +30,7 @@ Releases for CakePHP 5.4 * Fixes: services now load the extensions listed in their `$extensions` property; `Service::addAction()` maps the CORS action when `mapCors` is set; `OptionsHandlerExtension` sets its result on the event (its listener now always returns null); `LogExtension` logs the method of the service request instead of `REQUEST_METHOD`; `XmlRenderer` outputs Chronos dates and times instead of dropping them, and formats native dates as RFC 3339 (`+00:00` instead of `+0000`); `SocialLoginAction` calls `socialLogin()` through the Social behavior, as CakePHP 5.3 requires; `bin/cake service routes` gains a `--sort` option and lists the right columns for route collisions. * Fix `RegisterAction`: after saving the user it dispatched `Users.Global.beforeRegister` again instead of `Users.Global.afterRegister`, so afterRegister listeners never ran and beforeRegister listeners ran twice. * Upgrade note (fix): listeners that used the second `Users.Global.beforeRegister` call to change the saved user must listen to `Users.Global.afterRegister` instead. + * Fix WebAuthn failing with an HTTP 500 on a PHP build without the `sodium` extension: `EdDSA` needs it, so it is now offered and verified only when the extension is loaded, and the other algorithms keep working. `ext-sodium` is listed in the `suggest` section of `composer.json`. * Fix the WebAuthn adapters failing with a `TypeError` (HTTP 500) when the request has no `Authorization` header, for example OTP enrollment with a session login. WebAuthn registration and authentication options now need a bearer token and are answered with code 400 without one, instead of storing the challenge where other such requests share it. For code that extends the adapters: without a bearer token `BaseAdapter::saveStore()` throws a `BadRequestException`, `readStore()` returns a new, empty entity and `deleteStore()` returns `false`. `UserCredentialSourceRepository::__construct()` takes the WebAuthn serializer as an optional fourth argument. * Fix `FileRenderer` answering HTTP 400 for a missing file; it now answers 404 with the error body. * Fix a service that cannot be built being answered with an empty HTTP 400 and nothing in the logs. `ParseApiRequestMiddleware` now passes the exception on to the application's error handling. This is also where the check for pre-13.0 member names reports a service, a service extension, a renderer or a parser. An `UnauthenticatedException` thrown before the service is built is still answered with an empty HTTP 400. diff --git a/composer.json b/composer.json index c3cd4376..328d9b08 100644 --- a/composer.json +++ b/composer.json @@ -58,7 +58,8 @@ "league/flysystem": "Required for the Flysystem renderer (^3.35.3)", "robthree/twofactorauth": "Required for OTP two-factor authentication (^3.0.1), together with endroid/qr-code", "endroid/qr-code": "Required by the default OTP QR code provider, robthree's EndroidQrCodeProvider (^5.0 || ^6.0)", - "web-auth/webauthn-lib": "Required for WebAuthn two-factor authentication (^5.3.13)" + "web-auth/webauthn-lib": "Required for WebAuthn two-factor authentication (^5.3.13)", + "ext-sodium": "Lets WebAuthn offer and verify EdDSA (Ed25519) keys; without it the other algorithms are used" }, "conflict": { "cakephp/migrations": "<4.5 || >=6.0", diff --git a/docs/Documentation/upgrading.md b/docs/Documentation/upgrading.md index 276f35a1..8f49fe83 100644 --- a/docs/Documentation/upgrading.md +++ b/docs/Documentation/upgrading.md @@ -86,7 +86,8 @@ The plugin's `config/api.php` changed in the same area. None of these settings w - `Api.Jwt.RefreshToken.maxSessionLifetime` (seconds, default `null` = unlimited) is new. It ends a session that long after login or after completing the second factor, however often it is refreshed. Refresh tokens issued by 13.x or older carry no `auth_time` claim, so they are refused once that setting is on. Set it to `null`, a positive integer or a string of digits. Any other value except `false`, such as `0` or a negative number, does not mean unlimited: every refresh then fails with an `InvalidArgumentException`. - A failed WebAuthn verification now returns code 401 (`webauthn2fa_auth`) or 400 (`webauthn2fa_register`) with a generic message, instead of code 500 with the library's reason. Clients that matched messages such as `Invalid signature` should check the code instead. - WebAuthn registration and authentication options need a bearer token and are answered with code 400 without one. -- WebAuthn no longer offers the non-standard `Ed256` and `Ed512` algorithms; `EdDSA` (Ed25519) is offered instead. +- WebAuthn no longer offers or verifies the non-standard `Ed256` (-260) and `Ed512` (-261) algorithms; `EdDSA` (Ed25519, -8) is offered instead. No known authenticator uses them, so few or no keys are affected. A key registered with one of them on 13.x can no longer log in: the login is refused with code 401. Its user cannot register a new key either, because registration is refused while the user has a credential. To let such a user register again, remove the credential from `additional_data.api..webauthn_credentials` of the user; its `credentialPublicKey` names algorithm -260 or -261. +- `EdDSA` needs the PHP `sodium` extension, which PHP builds include by default. Without it, WebAuthn offers and verifies the other algorithms (ES256, RS256 and the rest) and leaves `EdDSA` out. - A missing or non-scalar `code` in `otp_verify_check` is an invalid code, not an HTTP 500. ### WebAuthn with web-auth/webauthn-lib 5 diff --git a/src/Webauthn/BaseAdapter.php b/src/Webauthn/BaseAdapter.php index 197b9045..eca69bc3 100644 --- a/src/Webauthn/BaseAdapter.php +++ b/src/Webauthn/BaseAdapter.php @@ -523,12 +523,26 @@ protected function getAlgorithmManager(): Manager PS256::create(), PS384::create(), PS512::create(), - // EdDSA (-8) is the WebAuthn Ed25519 algorithm. Ed256 (-260) and Ed512 (-261) are - // not WebAuthn algorithms, no authenticator uses them, and cose-lib warns about them. - new EdDSA(), ); + // EdDSA (-8) is the WebAuthn Ed25519 algorithm. It needs ext-sodium, and creating it without the + // extension throws, so a PHP build without sodium offers the other algorithms only. Ed256 (-260) + // and Ed512 (-261) are not WebAuthn algorithms, no authenticator uses them, and cose-lib warns + // about them. + if ($this->isEdDsaSupported()) { + $this->algorithmManager->add(new EdDSA()); + } } return $this->algorithmManager; } + + /** + * Whether EdDSA can be used, which needs the sodium extension. + * + * @return bool + */ + protected function isEdDsaSupported(): bool + { + return EdDSA::isSupported(); + } } diff --git a/tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php b/tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php index 9c991b34..fe33d9d9 100644 --- a/tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php +++ b/tests/TestCase/Integration/Service/Action/Auth/Webauthn2faFlowTest.php @@ -21,6 +21,10 @@ use CakeDC\Api\Test\ConfigTrait; use CakeDC\Api\Test\Settings; use CakeDC\Api\TestSuite\IntegrationTestCase; +use CBOR\ByteStringObject; +use CBOR\MapObject; +use CBOR\NegativeIntegerObject; +use CBOR\UnsignedIntegerObject; use Webauthn\TrustPath\EmptyTrustPath; /** @@ -424,6 +428,37 @@ public function testCredentialStoredByEarlierVersionsStillAuthenticates(): void $this->assertSame(self::PASSED, $this->jwtPayload($auth['data']['access_token'])['aud']); } + public function testCredentialWithTheRemovedEd256AlgorithmIsRejected(): void + { + [$login, $key, $credentialId] = $this->loginAndRegister(); + + // 13.x offered Ed256 (-260); 14.x no longer verifies it. -260 is WalnutDSA for IANA. + $users = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $user = $users->find()->where(['username' => 'user-1'])->firstOrFail(); + $additionalData = (array)$user->get('additional_data'); + $id = static::b64url($credentialId); + $ec = openssl_pkey_get_details($key)['ec']; + $coseKey = MapObject::create() + ->add(UnsignedIntegerObject::create(1), UnsignedIntegerObject::create(2)) + ->add(UnsignedIntegerObject::create(3), NegativeIntegerObject::create(-260)) + ->add(NegativeIntegerObject::create(-1), UnsignedIntegerObject::create(1)) + ->add(NegativeIntegerObject::create(-2), ByteStringObject::create(str_pad($ec['x'], 32, "\0", STR_PAD_LEFT))) + ->add(NegativeIntegerObject::create(-3), ByteStringObject::create(str_pad($ec['y'], 32, "\0", STR_PAD_LEFT))); + $additionalData['api']['localhost']['webauthn_credentials'][$id]['credentialPublicKey'] = static::b64url((string)$coseKey); + $user->set('additional_data', $additionalData); + $users->saveOrFail($user); + + $authOptions = $this->withToken('/auth/webauthn2fa_auth_options', 'GET', [], $login['access_token']); + $auth = $this->withToken( + '/auth/webauthn2fa_auth', + 'POST', + $this->assertion($key, $credentialId, $authOptions['data']['challenge']), + $login['access_token'], + ); + // a clear refusal, not a 500 + $this->assertRejected($auth, 401, 'WebAuthn authentication failed'); + } + public function testCeremonyStartedBeforeTheUpgradeIsRejected(): void { // earlier versions stored the serialized options, not the challenge diff --git a/tests/TestCase/Webauthn/RegisterAdapterTest.php b/tests/TestCase/Webauthn/RegisterAdapterTest.php index c91245f9..04da3ce9 100644 --- a/tests/TestCase/Webauthn/RegisterAdapterTest.php +++ b/tests/TestCase/Webauthn/RegisterAdapterTest.php @@ -76,6 +76,42 @@ public function testAdapterWorksWithoutAnAuthorizationHeader(): void $this->assertFalse($adapter->hasCredentialOnAnyDomain()); } + /** + * @param \CakeDC\Api\Webauthn\RegisterAdapter $adapter Adapter. + * @return list The algorithm identifiers the registration options offer. + */ + protected function offeredAlgorithms(RegisterAdapter $adapter): array + { + return array_column($adapter->getOptionsData($adapter->getOptions())['pubKeyCredParams'], 'alg'); + } + + public function testOptionsOfferEdDsaWhenSodiumIsLoaded(): void + { + $algorithms = $this->offeredAlgorithms($this->adapter(['Authorization' => 'Bearer a.jwt.token'])); + + $this->assertContains(-7, $algorithms); // ES256 + $this->assertContains(-257, $algorithms); // RS256 + $this->assertContains(-8, $algorithms); // EdDSA + } + + public function testOptionsWithoutSodiumOfferTheOtherAlgorithms(): void + { + // a PHP build without ext-sodium cannot create EdDSA; WebAuthn must keep working with the others + $users = TableRegistry::getTableLocator()->get('CakeDC/Users.Users'); + $request = new ServerRequest(['environment' => ['HTTP_HOST' => 'example.com', 'HTTP_AUTHORIZATION' => 'Bearer a.jwt.token']]); + $adapter = new class ($request, $users, $users->get(Settings::USER1)) extends RegisterAdapter { + protected function isEdDsaSupported(): bool + { + return false; + } + }; + + $algorithms = $this->offeredAlgorithms($adapter); + $this->assertContains(-7, $algorithms); + $this->assertContains(-257, $algorithms); + $this->assertNotContains(-8, $algorithms); + } + public function testOptionsNeedABearerToken(): void { // without a token the ceremony data would be shared by every such request