diff --git a/src/workos/authorization.py b/src/workos/authorization.py index 6e12f035..e1712ff3 100644 --- a/src/workos/authorization.py +++ b/src/workos/authorization.py @@ -1,6 +1,7 @@ -from typing import Any, Dict, Optional, Protocol, Sequence +from typing import Any, Dict, Mapping, Optional, Protocol, Sequence, Union from pydantic import TypeAdapter +from typing_extensions import TypedDict from workos.types.authorization.environment_role import ( EnvironmentRole, @@ -8,7 +9,9 @@ ) from workos.types.authorization.organization_role import OrganizationRole from workos.types.authorization.permission import Permission +from workos.types.authorization.resource import Resource from workos.types.authorization.role import Role, RoleList +from workos.types.fga import AuthorizationResource from workos.types.list_resource import ( ListArgs, ListMetadata, @@ -28,6 +31,19 @@ ) AUTHORIZATION_PERMISSIONS_PATH = "authorization/permissions" +AUTHORIZATION_RESOURCES_PATH = "authorization/resources" + + +class ParentResourceById(TypedDict): + parent_resource_id: str + + +class ParentResourceByExternalId(TypedDict): + parent_resource_external_id: str + parent_resource_type_slug: str + + +ParentResource = Union[ParentResourceById, ParentResourceByExternalId] _role_adapter: TypeAdapter[Role] = TypeAdapter(Role) @@ -41,6 +57,15 @@ class PermissionListFilters(ListArgs, total=False): ] +class ResourceByExternalIdListFilters(ListArgs, total=False): + resource_type_slug: Optional[str] + + +ResourceByExternalIdListResource = WorkOSListResource[ + AuthorizationResource, ResourceByExternalIdListFilters, ListMetadata +] + + class AuthorizationModule(Protocol): """Offers methods through the WorkOS Authorization service.""" @@ -161,6 +186,74 @@ def add_environment_role_permission( permission_slug: str, ) -> SyncOrAsync[EnvironmentRole]: ... + # Resources + + def get_resource(self, resource_id: str) -> SyncOrAsync[Resource]: ... + + def create_resource( + self, + *, + resource_type_slug: str, + organization_id: str, + external_id: str, + name: str, + parent: ParentResource, + description: Optional[str] = None, + ) -> SyncOrAsync[Resource]: ... + + def update_resource( + self, + resource_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + ) -> SyncOrAsync[Resource]: ... + + def delete_resource( + self, + resource_id: str, + *, + cascade_delete: Optional[bool] = None, + ) -> SyncOrAsync[None]: ... + + # Resources by External ID + + def get_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + ) -> SyncOrAsync[AuthorizationResource]: ... + + def update_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + *, + meta: Optional[Mapping[str, Any]] = None, + ) -> SyncOrAsync[AuthorizationResource]: ... + + def delete_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + *, + cascade_delete: Optional[bool] = None, + ) -> SyncOrAsync[None]: ... + + def list_resources( + self, + organization_id: str, + *, + resource_type_slug: Optional[str] = None, + limit: int = DEFAULT_LIST_RESPONSE_LIMIT, + before: Optional[str] = None, + after: Optional[str] = None, + order: PaginationOrder = "desc", + ) -> SyncOrAsync[ResourceByExternalIdListResource]: ... + class Authorization(AuthorizationModule): _http_client: SyncHTTPClient @@ -437,6 +530,168 @@ def add_environment_role_permission( return EnvironmentRole.model_validate(response) + # Resources + + def get_resource(self, resource_id: str) -> Resource: + response = self._http_client.request( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + method=REQUEST_METHOD_GET, + ) + + return Resource.model_validate(response) + + def create_resource( + self, + *, + resource_type_slug: str, + organization_id: str, + external_id: str, + name: str, + parent: ParentResource, + description: Optional[str] = None, + ) -> Resource: + json: Dict[str, Any] = { + "resource_type_slug": resource_type_slug, + "organization_id": organization_id, + "external_id": external_id, + "name": name, + **parent, + } + if description is not None: + json["description"] = description + + response = self._http_client.request( + AUTHORIZATION_RESOURCES_PATH, + method=REQUEST_METHOD_POST, + json=json, + ) + + return Resource.model_validate(response) + + def update_resource( + self, + resource_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + ) -> Resource: + json: Dict[str, Any] = {} + if name is not None: + json["name"] = name + if description is not None: + json["description"] = description + + response = self._http_client.request( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + method=REQUEST_METHOD_PATCH, + json=json, + ) + + return Resource.model_validate(response) + + def delete_resource( + self, + resource_id: str, + *, + cascade_delete: Optional[bool] = None, + ) -> None: + if cascade_delete is not None: + self._http_client.delete_with_body( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + json={"cascade_delete": cascade_delete}, + ) + else: + self._http_client.request( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + method=REQUEST_METHOD_DELETE, + ) + + # Resources by External ID + + def get_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + ) -> AuthorizationResource: + response = self._http_client.request( + f"authorization/organizations/{organization_id}/resources/{resource_type}/{external_id}", + method=REQUEST_METHOD_GET, + ) + + return AuthorizationResource.model_validate(response) + + def update_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + *, + meta: Optional[Mapping[str, Any]] = None, + ) -> AuthorizationResource: + json: Dict[str, Any] = {} + if meta is not None: + json["meta"] = meta + + response = self._http_client.request( + f"authorization/organizations/{organization_id}/resources/{resource_type}/{external_id}", + method=REQUEST_METHOD_PATCH, + json=json, + ) + + return AuthorizationResource.model_validate(response) + + def delete_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + *, + cascade_delete: Optional[bool] = None, + ) -> None: + path = f"authorization/organizations/{organization_id}/resources/{resource_type}/{external_id}" + if cascade_delete is not None: + self._http_client.delete_with_body( + path, + json={"cascade_delete": cascade_delete}, + ) + else: + self._http_client.request( + path, + method=REQUEST_METHOD_DELETE, + ) + + def list_resources( + self, + organization_id: str, + *, + resource_type_slug: Optional[str] = None, + limit: int = DEFAULT_LIST_RESPONSE_LIMIT, + before: Optional[str] = None, + after: Optional[str] = None, + order: PaginationOrder = "desc", + ) -> ResourceByExternalIdListResource: + list_params: ResourceByExternalIdListFilters = { + "limit": limit, + "before": before, + "after": after, + "order": order, + } + if resource_type_slug is not None: + list_params["resource_type_slug"] = resource_type_slug + + response = self._http_client.request( + f"authorization/organizations/{organization_id}/resources", + method=REQUEST_METHOD_GET, + params=list_params, + ) + + return ResourceByExternalIdListResource( + list_method=self.list_resources, + list_args=list_params, + **ListPage[AuthorizationResource](**response).model_dump(), + ) + class AsyncAuthorization(AuthorizationModule): _http_client: AsyncHTTPClient @@ -712,3 +967,165 @@ async def add_environment_role_permission( ) return EnvironmentRole.model_validate(response) + + # Resources + + async def get_resource(self, resource_id: str) -> Resource: + response = await self._http_client.request( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + method=REQUEST_METHOD_GET, + ) + + return Resource.model_validate(response) + + async def create_resource( + self, + *, + resource_type_slug: str, + organization_id: str, + external_id: str, + name: str, + parent: ParentResource, + description: Optional[str] = None, + ) -> Resource: + json: Dict[str, Any] = { + "resource_type_slug": resource_type_slug, + "organization_id": organization_id, + "external_id": external_id, + "name": name, + **parent, + } + if description is not None: + json["description"] = description + + response = await self._http_client.request( + AUTHORIZATION_RESOURCES_PATH, + method=REQUEST_METHOD_POST, + json=json, + ) + + return Resource.model_validate(response) + + async def update_resource( + self, + resource_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + ) -> Resource: + json: Dict[str, Any] = {} + if name is not None: + json["name"] = name + if description is not None: + json["description"] = description + + response = await self._http_client.request( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + method=REQUEST_METHOD_PATCH, + json=json, + ) + + return Resource.model_validate(response) + + async def delete_resource( + self, + resource_id: str, + *, + cascade_delete: Optional[bool] = None, + ) -> None: + if cascade_delete is not None: + await self._http_client.delete_with_body( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + json={"cascade_delete": cascade_delete}, + ) + else: + await self._http_client.request( + f"{AUTHORIZATION_RESOURCES_PATH}/{resource_id}", + method=REQUEST_METHOD_DELETE, + ) + + # Resources by External ID + + async def get_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + ) -> AuthorizationResource: + response = await self._http_client.request( + f"authorization/organizations/{organization_id}/resources/{resource_type}/{external_id}", + method=REQUEST_METHOD_GET, + ) + + return AuthorizationResource.model_validate(response) + + async def update_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + *, + meta: Optional[Mapping[str, Any]] = None, + ) -> AuthorizationResource: + json: Dict[str, Any] = {} + if meta is not None: + json["meta"] = meta + + response = await self._http_client.request( + f"authorization/organizations/{organization_id}/resources/{resource_type}/{external_id}", + method=REQUEST_METHOD_PATCH, + json=json, + ) + + return AuthorizationResource.model_validate(response) + + async def delete_resource_by_external_id( + self, + organization_id: str, + resource_type: str, + external_id: str, + *, + cascade_delete: Optional[bool] = None, + ) -> None: + path = f"authorization/organizations/{organization_id}/resources/{resource_type}/{external_id}" + if cascade_delete is not None: + await self._http_client.delete_with_body( + path, + json={"cascade_delete": cascade_delete}, + ) + else: + await self._http_client.request( + path, + method=REQUEST_METHOD_DELETE, + ) + + async def list_resources( + self, + organization_id: str, + *, + resource_type_slug: Optional[str] = None, + limit: int = DEFAULT_LIST_RESPONSE_LIMIT, + before: Optional[str] = None, + after: Optional[str] = None, + order: PaginationOrder = "desc", + ) -> ResourceByExternalIdListResource: + list_params: ResourceByExternalIdListFilters = { + "limit": limit, + "before": before, + "after": after, + "order": order, + } + if resource_type_slug is not None: + list_params["resource_type_slug"] = resource_type_slug + + response = await self._http_client.request( + f"authorization/organizations/{organization_id}/resources", + method=REQUEST_METHOD_GET, + params=list_params, + ) + + return ResourceByExternalIdListResource( + list_method=self.list_resources, + list_args=list_params, + **ListPage[AuthorizationResource](**response).model_dump(), + ) diff --git a/tests/test_authorization_resource_crud.py b/tests/test_authorization_resource_crud.py new file mode 100644 index 00000000..4942e29a --- /dev/null +++ b/tests/test_authorization_resource_crud.py @@ -0,0 +1,190 @@ +from typing import Union + +import pytest +from tests.utils.fixtures.mock_resource import MockResource +from tests.utils.syncify import syncify +from workos.authorization import AsyncAuthorization, Authorization + + +@pytest.mark.sync_and_async(Authorization, AsyncAuthorization) +class TestAuthorizationResourceCRUD: + @pytest.fixture(autouse=True) + def setup(self, module_instance: Union[Authorization, AsyncAuthorization]): + self.http_client = module_instance._http_client + self.authorization = module_instance + + @pytest.fixture + def mock_resource(self): + return MockResource(id="res_01ABC").dict() + + # --- get_resource --- + + def test_get_resource(self, mock_resource, capture_and_mock_http_client_request): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_resource, 200 + ) + + resource = syncify(self.authorization.get_resource("res_01ABC")) + + assert resource.id == "res_01ABC" + assert resource.object == "authorization_resource" + assert request_kwargs["method"] == "get" + assert request_kwargs["url"].endswith("/authorization/resources/res_01ABC") + + # --- create_resource --- + + def test_create_resource_required_fields_only( + self, mock_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_resource, 201 + ) + + resource = syncify( + self.authorization.create_resource( + resource_type_slug="document", + organization_id="org_01EHT88Z8J8795GZNQ4ZP1J81T", + external_id="ext_123", + name="Test Document", + parent={"parent_resource_id": "res_01PARENT"}, + ) + ) + + assert resource.id == "res_01ABC" + assert request_kwargs["method"] == "post" + assert request_kwargs["url"].endswith("/authorization/resources") + assert request_kwargs["json"] == { + "resource_type_slug": "document", + "organization_id": "org_01EHT88Z8J8795GZNQ4ZP1J81T", + "external_id": "ext_123", + "name": "Test Document", + "parent_resource_id": "res_01PARENT", + } + + def test_create_resource_with_description( + self, mock_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_resource, 201 + ) + + syncify( + self.authorization.create_resource( + resource_type_slug="document", + organization_id="org_01EHT88Z8J8795GZNQ4ZP1J81T", + external_id="ext_123", + name="Test Document", + parent={"parent_resource_id": "res_01PARENT"}, + description="A test document", + ) + ) + + assert request_kwargs["json"]["description"] == "A test document" + + def test_create_resource_with_parent_by_id( + self, mock_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_resource, 201 + ) + + syncify( + self.authorization.create_resource( + resource_type_slug="document", + organization_id="org_01EHT88Z8J8795GZNQ4ZP1J81T", + external_id="ext_123", + name="Test Document", + parent={"parent_resource_id": "res_01PARENT"}, + ) + ) + + assert request_kwargs["json"]["parent_resource_id"] == "res_01PARENT" + + def test_create_resource_with_parent_by_external_id( + self, mock_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_resource, 201 + ) + + syncify( + self.authorization.create_resource( + resource_type_slug="document", + organization_id="org_01EHT88Z8J8795GZNQ4ZP1J81T", + external_id="ext_123", + name="Test Document", + parent={ + "parent_resource_external_id": "ext_parent_456", + "parent_resource_type_slug": "folder", + }, + ) + ) + + assert request_kwargs["json"]["parent_resource_external_id"] == "ext_parent_456" + assert request_kwargs["json"]["parent_resource_type_slug"] == "folder" + + # --- update_resource --- + + def test_update_resource_with_name( + self, mock_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_resource, 200 + ) + + resource = syncify( + self.authorization.update_resource( + "res_01ABC", + name="Updated Name", + ) + ) + + assert resource.id == "res_01ABC" + assert request_kwargs["method"] == "patch" + assert request_kwargs["url"].endswith("/authorization/resources/res_01ABC") + assert request_kwargs["json"] == {"name": "Updated Name"} + + def test_update_resource_without_changes( + self, mock_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_resource, 200 + ) + + syncify(self.authorization.update_resource("res_01ABC")) + + assert request_kwargs["method"] == "patch" + assert request_kwargs["json"] == {} + + # --- delete_resource --- + + def test_delete_resource_without_cascade( + self, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, + status_code=202, + headers={"content-type": "text/plain; charset=utf-8"}, + ) + + response = syncify(self.authorization.delete_resource("res_01ABC")) + + assert response is None + assert request_kwargs["method"] == "delete" + assert request_kwargs["url"].endswith("/authorization/resources/res_01ABC") + + def test_delete_resource_with_cascade(self, capture_and_mock_http_client_request): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, + status_code=202, + headers={"content-type": "text/plain; charset=utf-8"}, + ) + + response = syncify( + self.authorization.delete_resource("res_01ABC", cascade_delete=True) + ) + + assert response is None + assert request_kwargs["method"] == "delete" + assert request_kwargs["url"].endswith("/authorization/resources/res_01ABC") + assert request_kwargs["json"] == {"cascade_delete": True} diff --git a/tests/test_authorization_resource_external_id.py b/tests/test_authorization_resource_external_id.py new file mode 100644 index 00000000..a82866f2 --- /dev/null +++ b/tests/test_authorization_resource_external_id.py @@ -0,0 +1,244 @@ +from typing import Union + +import pytest +from tests.utils.list_resource import list_response_of +from tests.utils.syncify import syncify +from workos.authorization import AsyncAuthorization, Authorization + + +@pytest.mark.sync_and_async(Authorization, AsyncAuthorization) +class TestAuthorizationResourceByExternalId: + @pytest.fixture(autouse=True) + def setup(self, module_instance: Union[Authorization, AsyncAuthorization]): + self.http_client = module_instance._http_client + self.authorization = module_instance + + @pytest.fixture + def mock_authorization_resource(self): + return { + "resource_type": "document", + "resource_id": "doc_123", + "meta": {"title": "Test Document"}, + "created_at": "2024-01-01T00:00:00Z", + } + + # --- get_resource_by_external_id --- + + def test_get_resource_by_external_id( + self, mock_authorization_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_authorization_resource, 200 + ) + + resource = syncify( + self.authorization.get_resource_by_external_id( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + "document", + "ext_123", + ) + ) + + assert resource.resource_type == "document" + assert resource.resource_id == "doc_123" + assert resource.meta == {"title": "Test Document"} + assert request_kwargs["method"] == "get" + assert request_kwargs["url"].endswith( + "/authorization/organizations/org_01EHT88Z8J8795GZNQ4ZP1J81T" + "/resources/document/ext_123" + ) + + # --- update_resource_by_external_id --- + + def test_update_resource_by_external_id_with_meta( + self, mock_authorization_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_authorization_resource, 200 + ) + + resource = syncify( + self.authorization.update_resource_by_external_id( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + "document", + "ext_123", + meta={"title": "Updated Document"}, + ) + ) + + assert resource.resource_type == "document" + assert resource.resource_id == "doc_123" + assert request_kwargs["method"] == "patch" + assert request_kwargs["url"].endswith( + "/authorization/organizations/org_01EHT88Z8J8795GZNQ4ZP1J81T" + "/resources/document/ext_123" + ) + assert request_kwargs["json"] == {"meta": {"title": "Updated Document"}} + + def test_update_resource_by_external_id_without_meta( + self, mock_authorization_resource, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_authorization_resource, 200 + ) + + syncify( + self.authorization.update_resource_by_external_id( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + "document", + "ext_123", + ) + ) + + assert request_kwargs["method"] == "patch" + assert request_kwargs["json"] == {} + + # --- delete_resource_by_external_id --- + + def test_delete_resource_by_external_id_without_cascade( + self, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, + status_code=202, + headers={"content-type": "text/plain; charset=utf-8"}, + ) + + response = syncify( + self.authorization.delete_resource_by_external_id( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + "document", + "ext_123", + ) + ) + + assert response is None + assert request_kwargs["method"] == "delete" + assert request_kwargs["url"].endswith( + "/authorization/organizations/org_01EHT88Z8J8795GZNQ4ZP1J81T" + "/resources/document/ext_123" + ) + + def test_delete_resource_by_external_id_with_cascade( + self, capture_and_mock_http_client_request + ): + request_kwargs = capture_and_mock_http_client_request( + self.http_client, + status_code=202, + headers={"content-type": "text/plain; charset=utf-8"}, + ) + + response = syncify( + self.authorization.delete_resource_by_external_id( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + "document", + "ext_123", + cascade_delete=True, + ) + ) + + assert response is None + assert request_kwargs["method"] == "delete" + assert request_kwargs["url"].endswith( + "/authorization/organizations/org_01EHT88Z8J8795GZNQ4ZP1J81T" + "/resources/document/ext_123" + ) + assert request_kwargs["json"] == {"cascade_delete": True} + + # --- list_resources --- + + def test_list_resources_with_results(self, capture_and_mock_http_client_request): + mock_resources = [ + { + "resource_type": "document", + "resource_id": "doc_1", + "meta": {"title": "Doc 1"}, + "created_at": "2024-01-01T00:00:00Z", + }, + { + "resource_type": "document", + "resource_id": "doc_2", + "meta": None, + "created_at": "2024-01-02T00:00:00Z", + }, + ] + mock_response = list_response_of(data=mock_resources) + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_response, 200 + ) + + result = syncify( + self.authorization.list_resources( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + ) + ) + + assert len(result.data) == 2 + assert result.data[0].resource_type == "document" + assert result.data[0].resource_id == "doc_1" + assert result.data[1].resource_id == "doc_2" + assert request_kwargs["method"] == "get" + assert request_kwargs["url"].endswith( + "/authorization/organizations/org_01EHT88Z8J8795GZNQ4ZP1J81T/resources" + ) + + def test_list_resources_empty(self, capture_and_mock_http_client_request): + mock_response = list_response_of(data=[]) + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_response, 200 + ) + + result = syncify( + self.authorization.list_resources( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + ) + ) + + assert len(result.data) == 0 + assert request_kwargs["method"] == "get" + + def test_list_resources_with_resource_type_slug_filter( + self, capture_and_mock_http_client_request + ): + mock_response = list_response_of( + data=[ + { + "resource_type": "document", + "resource_id": "doc_1", + "created_at": "2024-01-01T00:00:00Z", + } + ] + ) + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_response, 200 + ) + + syncify( + self.authorization.list_resources( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + resource_type_slug="document", + ) + ) + + assert request_kwargs["params"]["resource_type_slug"] == "document" + + def test_list_resources_with_pagination_params( + self, capture_and_mock_http_client_request + ): + mock_response = list_response_of(data=[]) + request_kwargs = capture_and_mock_http_client_request( + self.http_client, mock_response, 200 + ) + + syncify( + self.authorization.list_resources( + "org_01EHT88Z8J8795GZNQ4ZP1J81T", + limit=5, + after="cursor_abc", + order="asc", + ) + ) + + assert request_kwargs["params"]["limit"] == 5 + assert request_kwargs["params"]["after"] == "cursor_abc" + assert request_kwargs["params"]["order"] == "asc"