diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 5324ef95..c36afd59 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -4,6 +4,9 @@ on: push: branches: - main + pull_request: + branches: + - main jobs: check-compatibility: diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 17b73c04..7b0f5b8c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -32,3 +32,9 @@ jobs: - name: Run Tests run: poetry run pytest + env: + BASE_URL: ${{ secrets.BASE_URL }} + AUTH_TOKEN: ${{ secrets.AUTH_TOKEN }} + JWT_KEY: ${{ secrets.JWT_KEY }} + CLIENT_ID: ${{ secrets.CLIENT_ID }} + CLIENT_SECRET: ${{ secrets.CLIENT_SECRET }} diff --git a/.openapi-generator-ignore b/.openapi-generator-ignore index 98fafa65..0062019e 100644 --- a/.openapi-generator-ignore +++ b/.openapi-generator-ignore @@ -17,3 +17,4 @@ poetry.lock requirements.txt test-requirements.txt tox.ini +test/*.py diff --git a/README.md b/README.md index a036487f..dee20c92 100644 --- a/README.md +++ b/README.md @@ -37,45 +37,133 @@ install dependencies. Install the SDK by running one of the following commands: ```bash -composer require zitadel/client +pip install zitadel_client ``` -### Authentication +## Authentication Methods -The SDK supports three authentication methods: +Your SDK offers three ways to authenticate with Zitadel. Each method has its +own benefits—choose the one that fits your situation best. -1. Private Key JWT Authentication -2. Client Credentials Grant -3. Personal Access Tokens (PATs) +#### 1. Private Key JWT Authentication -For most service user scenarios in Zitadel, private key JWT authentication -is the recommended choice due to its benefits in security, performance, and control. -However, client credentials authentication might be considered in specific -situations where simplicity and trust between servers are priorities. +**What is it?** +You use a JSON Web Token (JWT) that you sign with a private key stored in a +JSON file. This process creates a secure token. -For more details on these authentication methods, please refer -to the [Zitadel documentation on authenticating service users](https://zitadel.com/docs/guides/integrate/service-users/authenticate-service-users). +**When should you use it?** +- **Best for production:** It offers strong security. +- **Advanced control:** You can adjust token settings like expiration. +**How do you use it?** +1. Save your private key in a JSON file. +2. Use the provided method to load this key and create a JWT-based + authenticator. -### Example +**Example:** ```python import zitadel_client as zitadel +from zitadel_client.auth.web_token_authenticator import WebTokenAuthenticator + +base_url = "https://example.zitadel.com" +key_file = "/path/to/jwt-key.json" + +authenticator = WebTokenAuthenticator.from_json(base_url, key_file) +zitadel = zitadel.Zitadel(authenticator) + +try: + response = zitadel.users.add_human_user({ + "username": "john.doe", + "profile": {"givenName": "John", "familyName": "Doe"}, + "email": {"email": "john@doe.com"} + }) + print("User created:", response) +except Exception as e: + print("Error:", e) +``` + +#### 2. Client Credentials Grant + +**What is it?** +This method uses a client ID and client secret to get a secure access token, +which is then used to authenticate. + +**When should you use it?** +- **Simple and straightforward:** Good for server-to-server communication. +- **Trusted environments:** Use it when both servers are owned or trusted. + +**How do you use it?** +1. Provide your client ID and client secret. +2. Build the authenticator -with zitadel.Zitadel("your-zitadel-base-url", 'your-valid-token') as client: - try: - response = client.users.add_human_user( - body=zitadel.V2AddHumanUserRequest( - username="john.doe", - profile=zitadel.V2SetHumanProfile(given_name="John", family_name="Doe"), - email=zitadel.V2SetHumanEmail(email="johndoe@doe.com") - ) - ) - print("User created:", response) - except Exception as e: - raise e +**Example:** + +```python +import zitadel_client as zitadel +from zitadel_client.auth.client_credentials_authenticator import ClientCredentialsAuthenticator + +base_url = "https://example.zitadel.com" +client_id = "your-client-id" +client_secret = "your-client-secret" + +authenticator = ClientCredentialsAuthenticator.builder(base_url, client_id, client_secret).build() +zitadel = zitadel.Zitadel(authenticator) + +try: + response = zitadel.users.add_human_user({ + "username": "john.doe", + "profile": {"givenName": "John", "familyName": "Doe"}, + "email": {"email": "john@doe.com"} + }) + print("User created:", response) +except Exception as e: + print("Error:", e) ``` +#### 3. Personal Access Tokens (PATs) + +**What is it?** +A Personal Access Token (PAT) is a pre-generated token that you can use to +authenticate without exchanging credentials every time. + +**When should you use it?** +- **Easy to use:** Great for development or testing scenarios. +- **Quick setup:** No need for dynamic token generation. + +**How do you use it?** +1. Obtain a valid personal access token from your account. +2. Create the authenticator with: `PersonalAccessTokenAuthenticator` + +**Example:** + +```python +import zitadel_client as zitadel +from zitadel_client.auth.personal_access_token_authenticator import PersonalAccessTokenAuthenticator + +base_url = "https://example.zitadel.com" +valid_token = "your-valid-token" + +authenticator = PersonalAccessTokenAuthenticator(base_url, valid_token) +zitadel = zitadel.Zitadel(authenticator) + +try: + response = zitadel.users.add_human_user({ + "username": "john.doe", + "profile": {"givenName": "John", "familyName": "Doe"}, + "email": {"email": "john@doe.com"} + }) + print("User created:", response) +except Exception as e: + print("Error:", e) +``` + +--- + +Choose the authentication method that best suits your needs based on your +environment and security requirements. For more details, please refer to the +[Zitadel documentation on authenticating service users](https://zitadel.com/docs/guides/integrate/service-users/authenticate-service-users). + ### Debugging The SDK supports debug logging, which can be enabled for troubleshooting and debugging purposes. You can enable debug logging by setting the `debug` diff --git a/poetry.lock b/poetry.lock index 5d29b2cb..80a5812d 100644 --- a/poetry.lock +++ b/poetry.lock @@ -15,6 +15,21 @@ files = [ [package.dependencies] typing-extensions = {version = ">=4.0.0", markers = "python_version < \"3.9\""} +[[package]] +name = "authlib" +version = "1.3.2" +description = "The ultimate Python library in building OAuth and OpenID Connect servers and clients." +optional = false +python-versions = ">=3.8" +groups = ["main"] +files = [ + {file = "Authlib-1.3.2-py2.py3-none-any.whl", hash = "sha256:ede026a95e9f5cdc2d4364a52103f5405e75aa156357e831ef2bfd0bc5094dfc"}, + {file = "authlib-1.3.2.tar.gz", hash = "sha256:4b16130117f9eb82aa6eec97f6dd4673c3f960ac0283ccdae2897ee4bc030ba2"}, +] + +[package.dependencies] +cryptography = "*" + [[package]] name = "cachetools" version = "5.5.2" @@ -27,6 +42,99 @@ files = [ {file = "cachetools-5.5.2.tar.gz", hash = "sha256:1a661caa9175d26759571b2e19580f9d6393969e5dfca11fdb1f947a23e640d4"}, ] +[[package]] +name = "certifi" +version = "2025.1.31" +description = "Python package for providing Mozilla's CA Bundle." +optional = false +python-versions = ">=3.6" +groups = ["dev"] +files = [ + {file = "certifi-2025.1.31-py3-none-any.whl", hash = "sha256:ca78db4565a652026a4db2bcdf68f2fb589ea80d0be70e03929ed730746b84fe"}, + {file = "certifi-2025.1.31.tar.gz", hash = "sha256:3d5da6925056f6f18f119200434a4780a94263f10d1c21d032a6f6b2baa20651"}, +] + +[[package]] +name = "cffi" +version = "1.17.1" +description = "Foreign Function Interface for Python calling C code." +optional = false +python-versions = ">=3.8" +groups = ["main"] +markers = "platform_python_implementation != \"PyPy\"" +files = [ + {file = "cffi-1.17.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:df8b1c11f177bc2313ec4b2d46baec87a5f3e71fc8b45dab2ee7cae86d9aba14"}, + {file = "cffi-1.17.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f2cdc858323644ab277e9bb925ad72ae0e67f69e804f4898c070998d50b1a67"}, + {file = "cffi-1.17.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:edae79245293e15384b51f88b00613ba9f7198016a5948b5dddf4917d4d26382"}, + {file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:45398b671ac6d70e67da8e4224a065cec6a93541bb7aebe1b198a61b58c7b702"}, + {file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ad9413ccdeda48c5afdae7e4fa2192157e991ff761e7ab8fdd8926f40b160cc3"}, + {file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5da5719280082ac6bd9aa7becb3938dc9f9cbd57fac7d2871717b1feb0902ab6"}, + {file = "cffi-1.17.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bb1a08b8008b281856e5971307cc386a8e9c5b625ac297e853d36da6efe9c17"}, + {file = "cffi-1.17.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:045d61c734659cc045141be4bae381a41d89b741f795af1dd018bfb532fd0df8"}, + {file = "cffi-1.17.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:6883e737d7d9e4899a8a695e00ec36bd4e5e4f18fabe0aca0efe0a4b44cdb13e"}, + {file = "cffi-1.17.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:6b8b4a92e1c65048ff98cfe1f735ef8f1ceb72e3d5f0c25fdb12087a23da22be"}, + {file = "cffi-1.17.1-cp310-cp310-win32.whl", hash = "sha256:c9c3d058ebabb74db66e431095118094d06abf53284d9c81f27300d0e0d8bc7c"}, + {file = "cffi-1.17.1-cp310-cp310-win_amd64.whl", hash = "sha256:0f048dcf80db46f0098ccac01132761580d28e28bc0f78ae0d58048063317e15"}, + {file = "cffi-1.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a45e3c6913c5b87b3ff120dcdc03f6131fa0065027d0ed7ee6190736a74cd401"}, + {file = "cffi-1.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30c5e0cb5ae493c04c8b42916e52ca38079f1b235c2f8ae5f4527b963c401caf"}, + {file = "cffi-1.17.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f75c7ab1f9e4aca5414ed4d8e5c0e303a34f4421f8a0d47a4d019ceff0ab6af4"}, + {file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41"}, + {file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1"}, + {file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6"}, + {file = "cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d"}, + {file = "cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6"}, + {file = "cffi-1.17.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:de2ea4b5833625383e464549fec1bc395c1bdeeb5f25c4a3a82b5a8c756ec22f"}, + {file = "cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b"}, + {file = "cffi-1.17.1-cp311-cp311-win32.whl", hash = "sha256:85a950a4ac9c359340d5963966e3e0a94a676bd6245a4b55bc43949eee26a655"}, + {file = "cffi-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:caaf0640ef5f5517f49bc275eca1406b0ffa6aa184892812030f04c2abf589a0"}, + {file = "cffi-1.17.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:805b4371bf7197c329fcb3ead37e710d1bca9da5d583f5073b799d5c5bd1eee4"}, + {file = "cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:733e99bc2df47476e3848417c5a4540522f234dfd4ef3ab7fafdf555b082ec0c"}, + {file = "cffi-1.17.1-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1257bdabf294dceb59f5e70c64a3e2f462c30c7ad68092d01bbbfb1c16b1ba36"}, + {file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da95af8214998d77a98cc14e3a3bd00aa191526343078b530ceb0bd710fb48a5"}, + {file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d63afe322132c194cf832bfec0dc69a99fb9bb6bbd550f161a49e9e855cc78ff"}, + {file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f79fc4fc25f1c8698ff97788206bb3c2598949bfe0fef03d299eb1b5356ada99"}, + {file = "cffi-1.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b62ce867176a75d03a665bad002af8e6d54644fad99a3c70905c543130e39d93"}, + {file = "cffi-1.17.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:386c8bf53c502fff58903061338ce4f4950cbdcb23e2902d86c0f722b786bbe3"}, + {file = "cffi-1.17.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ceb10419a9adf4460ea14cfd6bc43d08701f0835e979bf821052f1805850fe8"}, + {file = "cffi-1.17.1-cp312-cp312-win32.whl", hash = "sha256:a08d7e755f8ed21095a310a693525137cfe756ce62d066e53f502a83dc550f65"}, + {file = "cffi-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903"}, + {file = "cffi-1.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f3a2b4222ce6b60e2e8b337bb9596923045681d71e5a082783484d845390938e"}, + {file = "cffi-1.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0984a4925a435b1da406122d4d7968dd861c1385afe3b45ba82b750f229811e2"}, + {file = "cffi-1.17.1-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d01b12eeeb4427d3110de311e1774046ad344f5b1a7403101878976ecd7a10f3"}, + {file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:706510fe141c86a69c8ddc029c7910003a17353970cff3b904ff0686a5927683"}, + {file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de55b766c7aa2e2a3092c51e0483d700341182f08e67c63630d5b6f200bb28e5"}, + {file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c59d6e989d07460165cc5ad3c61f9fd8f1b4796eacbd81cee78957842b834af4"}, + {file = "cffi-1.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd398dbc6773384a17fe0d3e7eeb8d1a21c2200473ee6806bb5e6a8e62bb73dd"}, + {file = "cffi-1.17.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3edc8d958eb099c634dace3c7e16560ae474aa3803a5df240542b305d14e14ed"}, + {file = "cffi-1.17.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:72e72408cad3d5419375fc87d289076ee319835bdfa2caad331e377589aebba9"}, + {file = "cffi-1.17.1-cp313-cp313-win32.whl", hash = "sha256:e03eab0a8677fa80d646b5ddece1cbeaf556c313dcfac435ba11f107ba117b5d"}, + {file = "cffi-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6a16c31041f09ead72d69f583767292f750d24913dadacf5756b966aacb3f1a"}, + {file = "cffi-1.17.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:636062ea65bd0195bc012fea9321aca499c0504409f413dc88af450b57ffd03b"}, + {file = "cffi-1.17.1-cp38-cp38-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c7eac2ef9b63c79431bc4b25f1cd649d7f061a28808cbc6c47b534bd789ef964"}, + {file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e221cf152cff04059d011ee126477f0d9588303eb57e88923578ace7baad17f9"}, + {file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:31000ec67d4221a71bd3f67df918b1f88f676f1c3b535a7eb473255fdc0b83fc"}, + {file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6f17be4345073b0a7b8ea599688f692ac3ef23ce28e5df79c04de519dbc4912c"}, + {file = "cffi-1.17.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0e2b1fac190ae3ebfe37b979cc1ce69c81f4e4fe5746bb401dca63a9062cdaf1"}, + {file = "cffi-1.17.1-cp38-cp38-win32.whl", hash = "sha256:7596d6620d3fa590f677e9ee430df2958d2d6d6de2feeae5b20e82c00b76fbf8"}, + {file = "cffi-1.17.1-cp38-cp38-win_amd64.whl", hash = "sha256:78122be759c3f8a014ce010908ae03364d00a1f81ab5c7f4a7a5120607ea56e1"}, + {file = "cffi-1.17.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b2ab587605f4ba0bf81dc0cb08a41bd1c0a5906bd59243d56bad7668a6fc6c16"}, + {file = "cffi-1.17.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:28b16024becceed8c6dfbc75629e27788d8a3f9030691a1dbf9821a128b22c36"}, + {file = "cffi-1.17.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1d599671f396c4723d016dbddb72fe8e0397082b0a77a4fab8028923bec050e8"}, + {file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca74b8dbe6e8e8263c0ffd60277de77dcee6c837a3d0881d8c1ead7268c9e576"}, + {file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f7f5baafcc48261359e14bcd6d9bff6d4b28d9103847c9e136694cb0501aef87"}, + {file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98e3969bcff97cae1b2def8ba499ea3d6f31ddfdb7635374834cf89a1a08ecf0"}, + {file = "cffi-1.17.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdf5ce3acdfd1661132f2a9c19cac174758dc2352bfe37d98aa7512c6b7178b3"}, + {file = "cffi-1.17.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:9755e4345d1ec879e3849e62222a18c7174d65a6a92d5b346b1863912168b595"}, + {file = "cffi-1.17.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:f1e22e8c4419538cb197e4dd60acc919d7696e5ef98ee4da4e01d3f8cfa4cc5a"}, + {file = "cffi-1.17.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:c03e868a0b3bc35839ba98e74211ed2b05d2119be4e8a0f224fba9384f1fe02e"}, + {file = "cffi-1.17.1-cp39-cp39-win32.whl", hash = "sha256:e31ae45bc2e29f6b2abd0de1cc3b9d5205aa847cafaecb8af1476a609a2f6eb7"}, + {file = "cffi-1.17.1-cp39-cp39-win_amd64.whl", hash = "sha256:d016c76bdd850f3c626af19b0542c9677ba156e4ee4fccfdd7848803533ef662"}, + {file = "cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824"}, +] + +[package.dependencies] +pycparser = "*" + [[package]] name = "chardet" version = "5.2.0" @@ -39,6 +147,108 @@ files = [ {file = "chardet-5.2.0.tar.gz", hash = "sha256:1b3b6ff479a8c414bc3fa2c0852995695c4a026dcd6d0633b2dd092ca39c1cf7"}, ] +[[package]] +name = "charset-normalizer" +version = "3.4.1" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "charset_normalizer-3.4.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:91b36a978b5ae0ee86c394f5a54d6ef44db1de0815eb43de826d41d21e4af3de"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7461baadb4dc00fd9e0acbe254e3d7d2112e7f92ced2adc96e54ef6501c5f176"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e218488cd232553829be0664c2292d3af2eeeb94b32bea483cf79ac6a694e037"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:80ed5e856eb7f30115aaf94e4a08114ccc8813e6ed1b5efa74f9f82e8509858f"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b010a7a4fd316c3c484d482922d13044979e78d1861f0e0650423144c616a46a"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4532bff1b8421fd0a320463030c7520f56a79c9024a4e88f01c537316019005a"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:d973f03c0cb71c5ed99037b870f2be986c3c05e63622c017ea9816881d2dd247"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3a3bd0dcd373514dcec91c411ddb9632c0d7d92aed7093b8c3bbb6d69ca74408"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:d9c3cdf5390dcd29aa8056d13e8e99526cda0305acc038b96b30352aff5ff2bb"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:2bdfe3ac2e1bbe5b59a1a63721eb3b95fc9b6817ae4a46debbb4e11f6232428d"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:eab677309cdb30d047996b36d34caeda1dc91149e4fdca0b1a039b3f79d9a807"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-win32.whl", hash = "sha256:c0429126cf75e16c4f0ad00ee0eae4242dc652290f940152ca8c75c3a4b6ee8f"}, + {file = "charset_normalizer-3.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:9f0b8b1c6d84c8034a44893aba5e767bf9c7a211e313a9605d9c617d7083829f"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:8bfa33f4f2672964266e940dd22a195989ba31669bd84629f05fab3ef4e2d125"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:28bf57629c75e810b6ae989f03c0828d64d6b26a5e205535585f96093e405ed1"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f08ff5e948271dc7e18a35641d2f11a4cd8dfd5634f55228b691e62b37125eb3"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:234ac59ea147c59ee4da87a0c0f098e9c8d169f4dc2a159ef720f1a61bbe27cd"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd4ec41f914fa74ad1b8304bbc634b3de73d2a0889bd32076342a573e0779e00"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eea6ee1db730b3483adf394ea72f808b6e18cf3cb6454b4d86e04fa8c4327a12"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c96836c97b1238e9c9e3fe90844c947d5afbf4f4c92762679acfe19927d81d77"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:4d86f7aff21ee58f26dcf5ae81a9addbd914115cdebcbb2217e4f0ed8982e146"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:09b5e6733cbd160dcc09589227187e242a30a49ca5cefa5a7edd3f9d19ed53fd"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:5777ee0881f9499ed0f71cc82cf873d9a0ca8af166dfa0af8ec4e675b7df48e6"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:237bdbe6159cff53b4f24f397d43c6336c6b0b42affbe857970cefbb620911c8"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-win32.whl", hash = "sha256:8417cb1f36cc0bc7eaba8ccb0e04d55f0ee52df06df3ad55259b9a323555fc8b"}, + {file = "charset_normalizer-3.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:d7f50a1f8c450f3925cb367d011448c39239bb3eb4117c36a6d354794de4ce76"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:73d94b58ec7fecbc7366247d3b0b10a21681004153238750bb67bd9012414545"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dad3e487649f498dd991eeb901125411559b22e8d7ab25d3aeb1af367df5efd7"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c30197aa96e8eed02200a83fba2657b4c3acd0f0aa4bdc9f6c1af8e8962e0757"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2369eea1ee4a7610a860d88f268eb39b95cb588acd7235e02fd5a5601773d4fa"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc2722592d8998c870fa4e290c2eec2c1569b87fe58618e67d38b4665dfa680d"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ffc9202a29ab3920fa812879e95a9e78b2465fd10be7fcbd042899695d75e616"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:804a4d582ba6e5b747c625bf1255e6b1507465494a40a2130978bda7b932c90b"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:0f55e69f030f7163dffe9fd0752b32f070566451afe180f99dbeeb81f511ad8d"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:c4c3e6da02df6fa1410a7680bd3f63d4f710232d3139089536310d027950696a"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:5df196eb874dae23dcfb968c83d4f8fdccb333330fe1fc278ac5ceeb101003a9"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e358e64305fe12299a08e08978f51fc21fac060dcfcddd95453eabe5b93ed0e1"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-win32.whl", hash = "sha256:9b23ca7ef998bc739bf6ffc077c2116917eabcc901f88da1b9856b210ef63f35"}, + {file = "charset_normalizer-3.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:6ff8a4a60c227ad87030d76e99cd1698345d4491638dfa6673027c48b3cd395f"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:aabfa34badd18f1da5ec1bc2715cadc8dca465868a4e73a0173466b688f29dda"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:22e14b5d70560b8dd51ec22863f370d1e595ac3d024cb8ad7d308b4cd95f8313"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8436c508b408b82d87dc5f62496973a1805cd46727c34440b0d29d8a2f50a6c9"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2d074908e1aecee37a7635990b2c6d504cd4766c7bc9fc86d63f9c09af3fa11b"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:955f8851919303c92343d2f66165294848d57e9bba6cf6e3625485a70a038d11"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:44ecbf16649486d4aebafeaa7ec4c9fed8b88101f4dd612dcaf65d5e815f837f"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0924e81d3d5e70f8126529951dac65c1010cdf117bb75eb02dd12339b57749dd"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:2967f74ad52c3b98de4c3b32e1a44e32975e008a9cd2a8cc8966d6a5218c5cb2"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c75cb2a3e389853835e84a2d8fb2b81a10645b503eca9bcb98df6b5a43eb8886"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:09b26ae6b1abf0d27570633b2b078a2a20419c99d66fb2823173d73f188ce601"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fa88b843d6e211393a37219e6a1c1df99d35e8fd90446f1118f4216e307e48cd"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-win32.whl", hash = "sha256:eb8178fe3dba6450a3e024e95ac49ed3400e506fd4e9e5c32d30adda88cbd407"}, + {file = "charset_normalizer-3.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:b1ac5992a838106edb89654e0aebfc24f5848ae2547d22c2c3f66454daa11971"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f30bf9fd9be89ecb2360c7d94a711f00c09b976258846efe40db3d05828e8089"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:97f68b8d6831127e4787ad15e6757232e14e12060bec17091b85eb1486b91d8d"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7974a0b5ecd505609e3b19742b60cee7aa2aa2fb3151bc917e6e2646d7667dcf"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc54db6c8593ef7d4b2a331b58653356cf04f67c960f584edb7c3d8c97e8f39e"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:311f30128d7d333eebd7896965bfcfbd0065f1716ec92bd5638d7748eb6f936a"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-musllinux_1_2_aarch64.whl", hash = "sha256:7d053096f67cd1241601111b698f5cad775f97ab25d81567d3f59219b5f1adbd"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-musllinux_1_2_i686.whl", hash = "sha256:807f52c1f798eef6cf26beb819eeb8819b1622ddfeef9d0977a8502d4db6d534"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-musllinux_1_2_ppc64le.whl", hash = "sha256:dccbe65bd2f7f7ec22c4ff99ed56faa1e9f785482b9bbd7c717e26fd723a1d1e"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-musllinux_1_2_s390x.whl", hash = "sha256:2fb9bd477fdea8684f78791a6de97a953c51831ee2981f8e4f583ff3b9d9687e"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-musllinux_1_2_x86_64.whl", hash = "sha256:01732659ba9b5b873fc117534143e4feefecf3b2078b0a6a2e925271bb6f4cfa"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-win32.whl", hash = "sha256:7a4f97a081603d2050bfaffdefa5b02a9ec823f8348a572e39032caa8404a487"}, + {file = "charset_normalizer-3.4.1-cp37-cp37m-win_amd64.whl", hash = "sha256:7b1bef6280950ee6c177b326508f86cad7ad4dff12454483b51d8b7d673a2c5d"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:ecddf25bee22fe4fe3737a399d0d177d72bc22be6913acfab364b40bce1ba83c"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8c60ca7339acd497a55b0ea5d506b2a2612afb2826560416f6894e8b5770d4a9"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b7b2d86dd06bfc2ade3312a83a5c364c7ec2e3498f8734282c6c3d4b07b346b8"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dd78cfcda14a1ef52584dbb008f7ac81c1328c0f58184bf9a84c49c605002da6"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6e27f48bcd0957c6d4cb9d6fa6b61d192d0b13d5ef563e5f2ae35feafc0d179c"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:01ad647cdd609225c5350561d084b42ddf732f4eeefe6e678765636791e78b9a"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:619a609aa74ae43d90ed2e89bdd784765de0a25ca761b93e196d938b8fd1dbbd"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-musllinux_1_2_i686.whl", hash = "sha256:89149166622f4db9b4b6a449256291dc87a99ee53151c74cbd82a53c8c2f6ccd"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-musllinux_1_2_ppc64le.whl", hash = "sha256:7709f51f5f7c853f0fb938bcd3bc59cdfdc5203635ffd18bf354f6967ea0f824"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-musllinux_1_2_s390x.whl", hash = "sha256:345b0426edd4e18138d6528aed636de7a9ed169b4aaf9d61a8c19e39d26838ca"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:0907f11d019260cdc3f94fbdb23ff9125f6b5d1039b76003b5b0ac9d6a6c9d5b"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-win32.whl", hash = "sha256:ea0d8d539afa5eb2728aa1932a988a9a7af94f18582ffae4bc10b3fbdad0626e"}, + {file = "charset_normalizer-3.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:329ce159e82018d646c7ac45b01a430369d526569ec08516081727a20e9e4af4"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:b97e690a2118911e39b4042088092771b4ae3fc3aa86518f84b8cf6888dbdb41"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:78baa6d91634dfb69ec52a463534bc0df05dbd546209b79a3880a34487f4b84f"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1a2bc9f351a75ef49d664206d51f8e5ede9da246602dc2d2726837620ea034b2"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:75832c08354f595c760a804588b9357d34ec00ba1c940c15e31e96d902093770"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0af291f4fe114be0280cdd29d533696a77b5b49cfde5467176ecab32353395c4"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0167ddc8ab6508fe81860a57dd472b2ef4060e8d378f0cc555707126830f2537"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:2a75d49014d118e4198bcee5ee0a6f25856b29b12dbf7cd012791f8a6cc5c496"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:363e2f92b0f0174b2f8238240a1a30142e3db7b957a5dd5689b0e75fb717cc78"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:ab36c8eb7e454e34e60eb55ca5d241a5d18b2c6244f6827a30e451c42410b5f7"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:4c0907b1928a36d5a998d72d64d8eaa7244989f7aaaf947500d3a800c83a3fd6"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:04432ad9479fa40ec0f387795ddad4437a2b50417c69fa275e212933519ff294"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-win32.whl", hash = "sha256:3bed14e9c89dcb10e8f3a29f9ccac4955aebe93c71ae803af79265c9ca5644c5"}, + {file = "charset_normalizer-3.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:49402233c892a461407c512a19435d1ce275543138294f7ef013f0b63d5d3765"}, + {file = "charset_normalizer-3.4.1-py3-none-any.whl", hash = "sha256:d98b1668f06378c6dbefec3b92299716b931cd4e6061f3c875a71ced1780ab85"}, + {file = "charset_normalizer-3.4.1.tar.gz", hash = "sha256:44251f18cd68a75b56585dd00dae26183e102cd5e0f9f1466e6df5da2ed64ea3"}, +] + [[package]] name = "colorama" version = "0.4.6" @@ -139,6 +349,71 @@ tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.1 [package.extras] toml = ["tomli ; python_full_version <= \"3.11.0a6\""] +[[package]] +name = "cryptography" +version = "43.0.3" +description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." +optional = false +python-versions = ">=3.7" +groups = ["main"] +files = [ + {file = "cryptography-43.0.3-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:bf7a1932ac4176486eab36a19ed4c0492da5d97123f1406cf15e41b05e787d2e"}, + {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:63efa177ff54aec6e1c0aefaa1a241232dcd37413835a9b674b6e3f0ae2bfd3e"}, + {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e1ce50266f4f70bf41a2c6dc4358afadae90e2a1e5342d3c08883df1675374f"}, + {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:443c4a81bb10daed9a8f334365fe52542771f25aedaf889fd323a853ce7377d6"}, + {file = "cryptography-43.0.3-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:74f57f24754fe349223792466a709f8e0c093205ff0dca557af51072ff47ab18"}, + {file = "cryptography-43.0.3-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:9762ea51a8fc2a88b70cf2995e5675b38d93bf36bd67d91721c309df184f49bd"}, + {file = "cryptography-43.0.3-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:81ef806b1fef6b06dcebad789f988d3b37ccaee225695cf3e07648eee0fc6b73"}, + {file = "cryptography-43.0.3-cp37-abi3-win32.whl", hash = "sha256:cbeb489927bd7af4aa98d4b261af9a5bc025bd87f0e3547e11584be9e9427be2"}, + {file = "cryptography-43.0.3-cp37-abi3-win_amd64.whl", hash = "sha256:f46304d6f0c6ab8e52770addfa2fc41e6629495548862279641972b6215451cd"}, + {file = "cryptography-43.0.3-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:8ac43ae87929a5982f5948ceda07001ee5e83227fd69cf55b109144938d96984"}, + {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:846da004a5804145a5f441b8530b4bf35afbf7da70f82409f151695b127213d5"}, + {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0f996e7268af62598f2fc1204afa98a3b5712313a55c4c9d434aef49cadc91d4"}, + {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f7b178f11ed3664fd0e995a47ed2b5ff0a12d893e41dd0494f406d1cf555cab7"}, + {file = "cryptography-43.0.3-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c2e6fc39c4ab499049df3bdf567f768a723a5e8464816e8f009f121a5a9f4405"}, + {file = "cryptography-43.0.3-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:e1be4655c7ef6e1bbe6b5d0403526601323420bcf414598955968c9ef3eb7d16"}, + {file = "cryptography-43.0.3-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:df6b6c6d742395dd77a23ea3728ab62f98379eff8fb61be2744d4679ab678f73"}, + {file = "cryptography-43.0.3-cp39-abi3-win32.whl", hash = "sha256:d56e96520b1020449bbace2b78b603442e7e378a9b3bd68de65c782db1507995"}, + {file = "cryptography-43.0.3-cp39-abi3-win_amd64.whl", hash = "sha256:0c580952eef9bf68c4747774cde7ec1d85a6e61de97281f2dba83c7d2c806362"}, + {file = "cryptography-43.0.3-pp310-pypy310_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d03b5621a135bffecad2c73e9f4deb1a0f977b9a8ffe6f8e002bf6c9d07b918c"}, + {file = "cryptography-43.0.3-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:a2a431ee15799d6db9fe80c82b055bae5a752bef645bba795e8e52687c69efe3"}, + {file = "cryptography-43.0.3-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:281c945d0e28c92ca5e5930664c1cefd85efe80e5c0d2bc58dd63383fda29f83"}, + {file = "cryptography-43.0.3-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:f18c716be16bc1fea8e95def49edf46b82fccaa88587a45f8dc0ff6ab5d8e0a7"}, + {file = "cryptography-43.0.3-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:4a02ded6cd4f0a5562a8887df8b3bd14e822a90f97ac5e544c162899bc467664"}, + {file = "cryptography-43.0.3-pp39-pypy39_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:53a583b6637ab4c4e3591a15bc9db855b8d9dee9a669b550f311480acab6eb08"}, + {file = "cryptography-43.0.3-pp39-pypy39_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:1ec0bcf7e17c0c5669d881b1cd38c4972fade441b27bda1051665faaa89bdcaa"}, + {file = "cryptography-43.0.3-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:2ce6fae5bdad59577b44e4dfed356944fbf1d925269114c28be377692643b4ff"}, + {file = "cryptography-43.0.3.tar.gz", hash = "sha256:315b9001266a492a6ff443b61238f956b214dbec9910a081ba5b6646a055a805"}, +] + +[package.dependencies] +cffi = {version = ">=1.12", markers = "platform_python_implementation != \"PyPy\""} + +[package.extras] +docs = ["sphinx (>=5.3.0)", "sphinx-rtd-theme (>=1.1.1)"] +docstest = ["pyenchant (>=1.6.11)", "readme-renderer", "sphinxcontrib-spelling (>=4.0.1)"] +nox = ["nox"] +pep8test = ["check-sdist", "click", "mypy", "ruff"] +sdist = ["build"] +ssh = ["bcrypt (>=3.1.5)"] +test = ["certifi", "cryptography-vectors (==43.0.3)", "pretend", "pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-xdist"] +test-randomorder = ["pytest-randomly"] + +[[package]] +name = "deprecation" +version = "2.1.0" +description = "A library to handle automated deprecations" +optional = false +python-versions = "*" +groups = ["dev"] +files = [ + {file = "deprecation-2.1.0-py2.py3-none-any.whl", hash = "sha256:a10811591210e1fb0e768a8c25517cabeabcba6f0bf96564f8ff45189f90b14a"}, + {file = "deprecation-2.1.0.tar.gz", hash = "sha256:72b3bde64e5d778694b0cf68178aed03d15e15477116add3fb773e581f9518ff"}, +] + +[package.dependencies] +packaging = "*" + [[package]] name = "distlib" version = "0.3.9" @@ -151,6 +426,29 @@ files = [ {file = "distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403"}, ] +[[package]] +name = "docker" +version = "7.1.0" +description = "A Python library for the Docker Engine API." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "docker-7.1.0-py3-none-any.whl", hash = "sha256:c96b93b7f0a746f9e77d325bcfb87422a3d8bd4f03136ae8a85b37f1898d5fc0"}, + {file = "docker-7.1.0.tar.gz", hash = "sha256:ad8c70e6e3f8926cb8a92619b832b4ea5299e2831c14284663184e200546fa6c"}, +] + +[package.dependencies] +pywin32 = {version = ">=304", markers = "sys_platform == \"win32\""} +requests = ">=2.26.0" +urllib3 = ">=1.26.0" + +[package.extras] +dev = ["coverage (==7.2.7)", "pytest (==7.4.2)", "pytest-cov (==4.1.0)", "pytest-timeout (==2.1.0)", "ruff (==0.1.8)"] +docs = ["myst-parser (==0.18.0)", "sphinx (==5.1.1)"] +ssh = ["paramiko (>=2.4.3)"] +websockets = ["websocket-client (>=1.3.0)"] + [[package]] name = "exceptiongroup" version = "1.2.2" @@ -201,6 +499,21 @@ mccabe = ">=0.7.0,<0.8.0" pycodestyle = ">=2.9.0,<2.10.0" pyflakes = ">=2.5.0,<2.6.0" +[[package]] +name = "idna" +version = "3.10" +description = "Internationalized Domain Names in Applications (IDNA)" +optional = false +python-versions = ">=3.6" +groups = ["dev"] +files = [ + {file = "idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3"}, + {file = "idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9"}, +] + +[package.extras] +all = ["flake8 (>=7.1.1)", "mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.6.2)"] + [[package]] name = "iniconfig" version = "2.1.0" @@ -354,6 +667,19 @@ files = [ {file = "pycodestyle-2.9.1.tar.gz", hash = "sha256:2c9607871d58c76354b697b42f5d57e1ada7d261c261efac224b664affdc5785"}, ] +[[package]] +name = "pycparser" +version = "2.22" +description = "C parser in Python" +optional = false +python-versions = ">=3.8" +groups = ["main"] +markers = "platform_python_implementation != \"PyPy\"" +files = [ + {file = "pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc"}, + {file = "pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6"}, +] + [[package]] name = "pydantic" version = "2.10.6" @@ -577,6 +903,70 @@ files = [ [package.dependencies] six = ">=1.5" +[[package]] +name = "python-dotenv" +version = "1.0.1" +description = "Read key-value pairs from a .env file and set them as environment variables" +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "python-dotenv-1.0.1.tar.gz", hash = "sha256:e324ee90a023d808f1959c46bcbc04446a10ced277783dc6ee09987c37ec10ca"}, + {file = "python_dotenv-1.0.1-py3-none-any.whl", hash = "sha256:f7b63ef50f1b690dddf550d03497b66d609393b40b564ed0d674909a68ebf16a"}, +] + +[package.extras] +cli = ["click (>=5.0)"] + +[[package]] +name = "pywin32" +version = "310" +description = "Python for Window Extensions" +optional = false +python-versions = "*" +groups = ["dev"] +markers = "sys_platform == \"win32\"" +files = [ + {file = "pywin32-310-cp310-cp310-win32.whl", hash = "sha256:6dd97011efc8bf51d6793a82292419eba2c71cf8e7250cfac03bba284454abc1"}, + {file = "pywin32-310-cp310-cp310-win_amd64.whl", hash = "sha256:c3e78706e4229b915a0821941a84e7ef420bf2b77e08c9dae3c76fd03fd2ae3d"}, + {file = "pywin32-310-cp310-cp310-win_arm64.whl", hash = "sha256:33babed0cf0c92a6f94cc6cc13546ab24ee13e3e800e61ed87609ab91e4c8213"}, + {file = "pywin32-310-cp311-cp311-win32.whl", hash = "sha256:1e765f9564e83011a63321bb9d27ec456a0ed90d3732c4b2e312b855365ed8bd"}, + {file = "pywin32-310-cp311-cp311-win_amd64.whl", hash = "sha256:126298077a9d7c95c53823934f000599f66ec9296b09167810eb24875f32689c"}, + {file = "pywin32-310-cp311-cp311-win_arm64.whl", hash = "sha256:19ec5fc9b1d51c4350be7bb00760ffce46e6c95eaf2f0b2f1150657b1a43c582"}, + {file = "pywin32-310-cp312-cp312-win32.whl", hash = "sha256:8a75a5cc3893e83a108c05d82198880704c44bbaee4d06e442e471d3c9ea4f3d"}, + {file = "pywin32-310-cp312-cp312-win_amd64.whl", hash = "sha256:bf5c397c9a9a19a6f62f3fb821fbf36cac08f03770056711f765ec1503972060"}, + {file = "pywin32-310-cp312-cp312-win_arm64.whl", hash = "sha256:2349cc906eae872d0663d4d6290d13b90621eaf78964bb1578632ff20e152966"}, + {file = "pywin32-310-cp313-cp313-win32.whl", hash = "sha256:5d241a659c496ada3253cd01cfaa779b048e90ce4b2b38cd44168ad555ce74ab"}, + {file = "pywin32-310-cp313-cp313-win_amd64.whl", hash = "sha256:667827eb3a90208ddbdcc9e860c81bde63a135710e21e4cb3348968e4bd5249e"}, + {file = "pywin32-310-cp313-cp313-win_arm64.whl", hash = "sha256:e308f831de771482b7cf692a1f308f8fca701b2d8f9dde6cc440c7da17e47b33"}, + {file = "pywin32-310-cp38-cp38-win32.whl", hash = "sha256:0867beb8addefa2e3979d4084352e4ac6e991ca45373390775f7084cc0209b9c"}, + {file = "pywin32-310-cp38-cp38-win_amd64.whl", hash = "sha256:30f0a9b3138fb5e07eb4973b7077e1883f558e40c578c6925acc7a94c34eaa36"}, + {file = "pywin32-310-cp39-cp39-win32.whl", hash = "sha256:851c8d927af0d879221e616ae1f66145253537bbdd321a77e8ef701b443a9a1a"}, + {file = "pywin32-310-cp39-cp39-win_amd64.whl", hash = "sha256:96867217335559ac619f00ad70e513c0fcf84b8a3af9fc2bba3b59b97da70475"}, +] + +[[package]] +name = "requests" +version = "2.32.3" +description = "Python HTTP for Humans." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "requests-2.32.3-py3-none-any.whl", hash = "sha256:70761cfe03c773ceb22aa2f671b4757976145175cdfca038c02654d061d6dcc6"}, + {file = "requests-2.32.3.tar.gz", hash = "sha256:55365417734eb18255590a9ff9eb97e9e1da868d4ccd6402399eaf68af20a760"}, +] + +[package.dependencies] +certifi = ">=2017.4.17" +charset-normalizer = ">=2,<4" +idna = ">=2.5,<4" +urllib3 = ">=1.21.1,<3" + +[package.extras] +socks = ["PySocks (>=1.5.6,!=1.5.7)"] +use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"] + [[package]] name = "six" version = "1.17.0" @@ -589,6 +979,40 @@ files = [ {file = "six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81"}, ] +[[package]] +name = "testcontainers" +version = "3.7.1" +description = "Library provides lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container" +optional = false +python-versions = ">=3.7" +groups = ["dev"] +files = [ + {file = "testcontainers-3.7.1-py2.py3-none-any.whl", hash = "sha256:7f48cef4bf0ccd78f1a4534d4b701a003a3bace851f24eae58a32f9e3f0aeba0"}, +] + +[package.dependencies] +deprecation = "*" +docker = ">=4.0.0" +wrapt = "*" + +[package.extras] +arangodb = ["python-arango"] +azurite = ["azure-storage-blob"] +clickhouse = ["clickhouse-driver"] +docker-compose = ["docker-compose"] +google-cloud-pubsub = ["google-cloud-pubsub (<2)"] +kafka = ["kafka-python"] +keycloak = ["python-keycloak"] +mongo = ["pymongo"] +mssqlserver = ["pymssql"] +mysql = ["pymysql", "sqlalchemy"] +neo4j = ["neo4j"] +oracle = ["cx-Oracle", "sqlalchemy"] +postgresql = ["psycopg2-binary", "sqlalchemy"] +rabbitmq = ["pika"] +redis = ["redis"] +selenium = ["selenium"] + [[package]] name = "tomli" version = "2.2.1" @@ -690,7 +1114,7 @@ version = "2.2.3" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false python-versions = ">=3.8" -groups = ["main"] +groups = ["main", "dev"] files = [ {file = "urllib3-2.2.3-py3-none-any.whl", hash = "sha256:ca899ca043dcb1bafa3e262d73aa25c465bfb49e0bd9dd5d59f1d0acba2f8fac"}, {file = "urllib3-2.2.3.tar.gz", hash = "sha256:e7d814a81dad81e6caf2ec9fdedb284ecc9c73076b62654547cc64ccdcae26e9"}, @@ -723,7 +1147,96 @@ platformdirs = ">=3.9.1,<5" docs = ["furo (>=2023.7.26)", "proselint (>=0.13)", "sphinx (>=7.1.2,!=7.3)", "sphinx-argparse (>=0.4)", "sphinxcontrib-towncrier (>=0.2.1a0)", "towncrier (>=23.6)"] test = ["covdefaults (>=2.3)", "coverage (>=7.2.7)", "coverage-enable-subprocess (>=1)", "flaky (>=3.7)", "packaging (>=23.1)", "pytest (>=7.4)", "pytest-env (>=0.8.2)", "pytest-freezer (>=0.4.8) ; platform_python_implementation == \"PyPy\" or platform_python_implementation == \"CPython\" and sys_platform == \"win32\" and python_version >= \"3.13\"", "pytest-mock (>=3.11.1)", "pytest-randomly (>=3.12)", "pytest-timeout (>=2.1)", "setuptools (>=68)", "time-machine (>=2.10) ; platform_python_implementation == \"CPython\""] +[[package]] +name = "wrapt" +version = "1.17.2" +description = "Module for decorators, wrappers and monkey patching." +optional = false +python-versions = ">=3.8" +groups = ["dev"] +files = [ + {file = "wrapt-1.17.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:3d57c572081fed831ad2d26fd430d565b76aa277ed1d30ff4d40670b1c0dd984"}, + {file = "wrapt-1.17.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b5e251054542ae57ac7f3fba5d10bfff615b6c2fb09abeb37d2f1463f841ae22"}, + {file = "wrapt-1.17.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:80dd7db6a7cb57ffbc279c4394246414ec99537ae81ffd702443335a61dbf3a7"}, + {file = "wrapt-1.17.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a6e821770cf99cc586d33833b2ff32faebdbe886bd6322395606cf55153246c"}, + {file = "wrapt-1.17.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b60fb58b90c6d63779cb0c0c54eeb38941bae3ecf7a73c764c52c88c2dcb9d72"}, + {file = "wrapt-1.17.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b870b5df5b71d8c3359d21be8f0d6c485fa0ebdb6477dda51a1ea54a9b558061"}, + {file = "wrapt-1.17.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4011d137b9955791f9084749cba9a367c68d50ab8d11d64c50ba1688c9b457f2"}, + {file = "wrapt-1.17.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:1473400e5b2733e58b396a04eb7f35f541e1fb976d0c0724d0223dd607e0f74c"}, + {file = "wrapt-1.17.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:3cedbfa9c940fdad3e6e941db7138e26ce8aad38ab5fe9dcfadfed9db7a54e62"}, + {file = "wrapt-1.17.2-cp310-cp310-win32.whl", hash = "sha256:582530701bff1dec6779efa00c516496968edd851fba224fbd86e46cc6b73563"}, + {file = "wrapt-1.17.2-cp310-cp310-win_amd64.whl", hash = "sha256:58705da316756681ad3c9c73fd15499aa4d8c69f9fd38dc8a35e06c12468582f"}, + {file = "wrapt-1.17.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ff04ef6eec3eee8a5efef2401495967a916feaa353643defcc03fc74fe213b58"}, + {file = "wrapt-1.17.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4db983e7bca53819efdbd64590ee96c9213894272c776966ca6306b73e4affda"}, + {file = "wrapt-1.17.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9abc77a4ce4c6f2a3168ff34b1da9b0f311a8f1cfd694ec96b0603dff1c79438"}, + {file = "wrapt-1.17.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0b929ac182f5ace000d459c59c2c9c33047e20e935f8e39371fa6e3b85d56f4a"}, + {file = "wrapt-1.17.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f09b286faeff3c750a879d336fb6d8713206fc97af3adc14def0cdd349df6000"}, + {file = "wrapt-1.17.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1a7ed2d9d039bd41e889f6fb9364554052ca21ce823580f6a07c4ec245c1f5d6"}, + {file = "wrapt-1.17.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:129a150f5c445165ff941fc02ee27df65940fcb8a22a61828b1853c98763a64b"}, + {file = "wrapt-1.17.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1fb5699e4464afe5c7e65fa51d4f99e0b2eadcc176e4aa33600a3df7801d6662"}, + {file = "wrapt-1.17.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9a2bce789a5ea90e51a02dfcc39e31b7f1e662bc3317979aa7e5538e3a034f72"}, + {file = "wrapt-1.17.2-cp311-cp311-win32.whl", hash = "sha256:4afd5814270fdf6380616b321fd31435a462019d834f83c8611a0ce7484c7317"}, + {file = "wrapt-1.17.2-cp311-cp311-win_amd64.whl", hash = "sha256:acc130bc0375999da18e3d19e5a86403667ac0c4042a094fefb7eec8ebac7cf3"}, + {file = "wrapt-1.17.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d5e2439eecc762cd85e7bd37161d4714aa03a33c5ba884e26c81559817ca0925"}, + {file = "wrapt-1.17.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fc7cb4c1c744f8c05cd5f9438a3caa6ab94ce8344e952d7c45a8ed59dd88392"}, + {file = "wrapt-1.17.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8fdbdb757d5390f7c675e558fd3186d590973244fab0c5fe63d373ade3e99d40"}, + {file = "wrapt-1.17.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5bb1d0dbf99411f3d871deb6faa9aabb9d4e744d67dcaaa05399af89d847a91d"}, + {file = "wrapt-1.17.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d18a4865f46b8579d44e4fe1e2bcbc6472ad83d98e22a26c963d46e4c125ef0b"}, + {file = "wrapt-1.17.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc570b5f14a79734437cb7b0500376b6b791153314986074486e0b0fa8d71d98"}, + {file = "wrapt-1.17.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6d9187b01bebc3875bac9b087948a2bccefe464a7d8f627cf6e48b1bbae30f82"}, + {file = "wrapt-1.17.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9e8659775f1adf02eb1e6f109751268e493c73716ca5761f8acb695e52a756ae"}, + {file = "wrapt-1.17.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e8b2816ebef96d83657b56306152a93909a83f23994f4b30ad4573b00bd11bb9"}, + {file = "wrapt-1.17.2-cp312-cp312-win32.whl", hash = "sha256:468090021f391fe0056ad3e807e3d9034e0fd01adcd3bdfba977b6fdf4213ea9"}, + {file = "wrapt-1.17.2-cp312-cp312-win_amd64.whl", hash = "sha256:ec89ed91f2fa8e3f52ae53cd3cf640d6feff92ba90d62236a81e4e563ac0e991"}, + {file = "wrapt-1.17.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6ed6ffac43aecfe6d86ec5b74b06a5be33d5bb9243d055141e8cabb12aa08125"}, + {file = "wrapt-1.17.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:35621ae4c00e056adb0009f8e86e28eb4a41a4bfa8f9bfa9fca7d343fe94f998"}, + {file = "wrapt-1.17.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a604bf7a053f8362d27eb9fefd2097f82600b856d5abe996d623babd067b1ab5"}, + {file = "wrapt-1.17.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5cbabee4f083b6b4cd282f5b817a867cf0b1028c54d445b7ec7cfe6505057cf8"}, + {file = "wrapt-1.17.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:49703ce2ddc220df165bd2962f8e03b84c89fee2d65e1c24a7defff6f988f4d6"}, + {file = "wrapt-1.17.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8112e52c5822fc4253f3901b676c55ddf288614dc7011634e2719718eaa187dc"}, + {file = "wrapt-1.17.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9fee687dce376205d9a494e9c121e27183b2a3df18037f89d69bd7b35bcf59e2"}, + {file = "wrapt-1.17.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:18983c537e04d11cf027fbb60a1e8dfd5190e2b60cc27bc0808e653e7b218d1b"}, + {file = "wrapt-1.17.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:703919b1633412ab54bcf920ab388735832fdcb9f9a00ae49387f0fe67dad504"}, + {file = "wrapt-1.17.2-cp313-cp313-win32.whl", hash = "sha256:abbb9e76177c35d4e8568e58650aa6926040d6a9f6f03435b7a522bf1c487f9a"}, + {file = "wrapt-1.17.2-cp313-cp313-win_amd64.whl", hash = "sha256:69606d7bb691b50a4240ce6b22ebb319c1cfb164e5f6569835058196e0f3a845"}, + {file = "wrapt-1.17.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:4a721d3c943dae44f8e243b380cb645a709ba5bd35d3ad27bc2ed947e9c68192"}, + {file = "wrapt-1.17.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:766d8bbefcb9e00c3ac3b000d9acc51f1b399513f44d77dfe0eb026ad7c9a19b"}, + {file = "wrapt-1.17.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e496a8ce2c256da1eb98bd15803a79bee00fc351f5dfb9ea82594a3f058309e0"}, + {file = "wrapt-1.17.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40d615e4fe22f4ad3528448c193b218e077656ca9ccb22ce2cb20db730f8d306"}, + {file = "wrapt-1.17.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a5aaeff38654462bc4b09023918b7f21790efb807f54c000a39d41d69cf552cb"}, + {file = "wrapt-1.17.2-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9a7d15bbd2bc99e92e39f49a04653062ee6085c0e18b3b7512a4f2fe91f2d681"}, + {file = "wrapt-1.17.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e3890b508a23299083e065f435a492b5435eba6e304a7114d2f919d400888cc6"}, + {file = "wrapt-1.17.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:8c8b293cd65ad716d13d8dd3624e42e5a19cc2a2f1acc74b30c2c13f15cb61a6"}, + {file = "wrapt-1.17.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4c82b8785d98cdd9fed4cac84d765d234ed3251bd6afe34cb7ac523cb93e8b4f"}, + {file = "wrapt-1.17.2-cp313-cp313t-win32.whl", hash = "sha256:13e6afb7fe71fe7485a4550a8844cc9ffbe263c0f1a1eea569bc7091d4898555"}, + {file = "wrapt-1.17.2-cp313-cp313t-win_amd64.whl", hash = "sha256:eaf675418ed6b3b31c7a989fd007fa7c3be66ce14e5c3b27336383604c9da85c"}, + {file = "wrapt-1.17.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:5c803c401ea1c1c18de70a06a6f79fcc9c5acfc79133e9869e730ad7f8ad8ef9"}, + {file = "wrapt-1.17.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:f917c1180fdb8623c2b75a99192f4025e412597c50b2ac870f156de8fb101119"}, + {file = "wrapt-1.17.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:ecc840861360ba9d176d413a5489b9a0aff6d6303d7e733e2c4623cfa26904a6"}, + {file = "wrapt-1.17.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb87745b2e6dc56361bfde481d5a378dc314b252a98d7dd19a651a3fa58f24a9"}, + {file = "wrapt-1.17.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:58455b79ec2661c3600e65c0a716955adc2410f7383755d537584b0de41b1d8a"}, + {file = "wrapt-1.17.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b4e42a40a5e164cbfdb7b386c966a588b1047558a990981ace551ed7e12ca9c2"}, + {file = "wrapt-1.17.2-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:91bd7d1773e64019f9288b7a5101f3ae50d3d8e6b1de7edee9c2ccc1d32f0c0a"}, + {file = "wrapt-1.17.2-cp38-cp38-musllinux_1_2_i686.whl", hash = "sha256:bb90fb8bda722a1b9d48ac1e6c38f923ea757b3baf8ebd0c82e09c5c1a0e7a04"}, + {file = "wrapt-1.17.2-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:08e7ce672e35efa54c5024936e559469436f8b8096253404faeb54d2a878416f"}, + {file = "wrapt-1.17.2-cp38-cp38-win32.whl", hash = "sha256:410a92fefd2e0e10d26210e1dfb4a876ddaf8439ef60d6434f21ef8d87efc5b7"}, + {file = "wrapt-1.17.2-cp38-cp38-win_amd64.whl", hash = "sha256:95c658736ec15602da0ed73f312d410117723914a5c91a14ee4cdd72f1d790b3"}, + {file = "wrapt-1.17.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:99039fa9e6306880572915728d7f6c24a86ec57b0a83f6b2491e1d8ab0235b9a"}, + {file = "wrapt-1.17.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2696993ee1eebd20b8e4ee4356483c4cb696066ddc24bd70bcbb80fa56ff9061"}, + {file = "wrapt-1.17.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:612dff5db80beef9e649c6d803a8d50c409082f1fedc9dbcdfde2983b2025b82"}, + {file = "wrapt-1.17.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62c2caa1585c82b3f7a7ab56afef7b3602021d6da34fbc1cf234ff139fed3cd9"}, + {file = "wrapt-1.17.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c958bcfd59bacc2d0249dcfe575e71da54f9dcf4a8bdf89c4cb9a68a1170d73f"}, + {file = "wrapt-1.17.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc78a84e2dfbc27afe4b2bd7c80c8db9bca75cc5b85df52bfe634596a1da846b"}, + {file = "wrapt-1.17.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:ba0f0eb61ef00ea10e00eb53a9129501f52385c44853dbd6c4ad3f403603083f"}, + {file = "wrapt-1.17.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:1e1fe0e6ab7775fd842bc39e86f6dcfc4507ab0ffe206093e76d61cde37225c8"}, + {file = "wrapt-1.17.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:c86563182421896d73858e08e1db93afdd2b947a70064b813d515d66549e15f9"}, + {file = "wrapt-1.17.2-cp39-cp39-win32.whl", hash = "sha256:f393cda562f79828f38a819f4788641ac7c4085f30f1ce1a68672baa686482bb"}, + {file = "wrapt-1.17.2-cp39-cp39-win_amd64.whl", hash = "sha256:36ccae62f64235cf8ddb682073a60519426fdd4725524ae38874adf72b5f2aeb"}, + {file = "wrapt-1.17.2-py3-none-any.whl", hash = "sha256:b18f2d1533a71f069c7f82d524a52599053d4c7166e9dd374ae2136b7f40f7c8"}, + {file = "wrapt-1.17.2.tar.gz", hash = "sha256:41388e9d4d1522446fe79d3213196bd9e3b301a336965b9e27ca2788ebd122f3"}, +] + [metadata] lock-version = "2.1" python-versions = ">=3.8" -content-hash = "6ffedc3b18270f40c666d987288ce74cbefad771ccc663eedc530ae08e4309c5" +content-hash = "d66d79be5c31db83ad345b5fe1bb384e9410902aaee7258f4719d69d7451d000" diff --git a/pyproject.toml b/pyproject.toml index af63386c..5c5ea57e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,7 +16,8 @@ dependencies = [ "urllib3>=1.25.3,<3.0.0", "python-dateutil>=2.8.2", "pydantic>=2", - "typing-extensions>=4.7.1" + "typing-extensions>=4.7.1", + "authlib (==1.3.2)" ] [project.urls] @@ -35,6 +36,8 @@ tox = ">= 3.9.0" flake8 = ">= 4.0.0" types-python-dateutil = ">= 2.8.19.14" mypy = ">= 1.5" +testcontainers = "3.7.1" +python-dotenv = "1.0.1" [build-system] requires = ["poetry-core>=1.0.0"] @@ -43,13 +46,21 @@ build-backend = "poetry.core.masonry.api" [tool.tox] envlist = ["py3"] -[testenv] -deps = [ - "pytest", - "pytest-cov" +[tool.pytest.ini_options] +testpaths = ["test", "spec"] +python_files = "test_*.py *_spec.py" +addopts = [ + "--cov=zitadel_client", + "--cov-report=html:build/coverage/html", + "--cov-report=lcov:build/coverage/lcov.info", + "--cov-report=term" ] -commands = [ - "pytest --cov=zitadel_client" + +[tool.coverage.run] +data_file = "build/coverage/.coverage" +omit = [ + "zitadel_client/api/*", + "zitadel_client/models/*" ] [tool.pylint.'MESSAGES CONTROL'] @@ -60,8 +71,6 @@ files = [ "zitadel_client", "tests", ] -# TODO: enable "strict" once all these individual checks are passing -# strict = true # List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options warn_unused_configs = true diff --git a/spec/__init__.py b/spec/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/spec/conftest.py b/spec/conftest.py new file mode 100644 index 00000000..ac145e8d --- /dev/null +++ b/spec/conftest.py @@ -0,0 +1,8 @@ +import pytest +from dotenv import load_dotenv + + +@pytest.fixture(scope="session", autouse=True) +def load_env(): + """Load the .env file for the entire test session.""" + load_dotenv() diff --git a/spec/sdk_test_using_client_credentials_authentication_spec.py b/spec/sdk_test_using_client_credentials_authentication_spec.py new file mode 100644 index 00000000..8982234e --- /dev/null +++ b/spec/sdk_test_using_client_credentials_authentication_spec.py @@ -0,0 +1,74 @@ +import os +import uuid + +import pytest + +import zitadel_client as zitadel +from zitadel_client.auth.client_credentials_authenticator import ClientCredentialsAuthenticator + + +@pytest.fixture +def client_id(): + """Fixture to return a valid personal access token.""" + return os.getenv("CLIENT_ID") + + +@pytest.fixture +def client_secret(): + """Fixture to return a valid personal access token.""" + return os.getenv("CLIENT_SECRET") + + +@pytest.fixture +def base_url(): + """Fixture to return the base URL.""" + return os.getenv("BASE_URL") + + +@pytest.fixture +def user_id(client_id, client_secret, base_url): + """Fixture to create a user and return their ID.""" + with zitadel.Zitadel(ClientCredentialsAuthenticator.builder(base_url, client_id, client_secret).build()) as client: + try: + response = client.users.add_human_user( + body=zitadel.models.V2AddHumanUserRequest( + username=uuid.uuid4().hex, + profile=zitadel.models.V2SetHumanProfile(given_name="John", family_name="Doe"), + email=zitadel.models.V2SetHumanEmail(email=f"johndoe{uuid.uuid4().hex}@caos.ag") + ) + ) + print("User created:", response) + return response.user_id + except Exception as e: + pytest.fail(f"Exception while creating user: {e}") + + +def test_should_deactivate_and_reactivate_user_with_valid_token(user_id, client_id, client_secret, base_url): + """Test to (de)activate the user with a valid token.""" + with zitadel.Zitadel(ClientCredentialsAuthenticator.builder(base_url, client_id, client_secret).build()) as client: + try: + deactivate_response = client.users.deactivate_user(user_id=user_id) + print("User deactivated:", deactivate_response) + + reactivate_response = client.users.reactivate_user(user_id=user_id) + print("User reactivated:", reactivate_response) + # Adjust based on actual response format + # assert reactivate_response["status"] == "success" + except Exception as e: + pytest.fail(f"Exception when calling deactivate_user or reactivate_user with valid token: {e}") + + +def test_should_not_deactivate_or_reactivate_user_with_invalid_token(user_id, base_url): + """Test to attempt (de)activating the user with an invalid token.""" + with zitadel.Zitadel(ClientCredentialsAuthenticator.builder(base_url, "id", "secret").build()) as client: + try: + client.users.deactivate_user(user_id=user_id) + pytest.fail("Expected exception when deactivating user with invalid token, but got response.") + except Exception as e: + print("Caught expected UnauthorizedException:", e) + + try: + client.users.reactivate_user(user_id=user_id) + pytest.fail("Expected exception when reactivating user with invalid token, but got response.") + except Exception as e: + print("Caught expected UnauthorizedException:", e) diff --git a/spec/sdk_test_using_personal_access_token_authentication_spec.py b/spec/sdk_test_using_personal_access_token_authentication_spec.py new file mode 100644 index 00000000..177d3b71 --- /dev/null +++ b/spec/sdk_test_using_personal_access_token_authentication_spec.py @@ -0,0 +1,79 @@ +import os +import uuid + +import pytest + +import zitadel_client as zitadel +from zitadel_client.auth.personal_access_token_authenticator import PersonalAccessTokenAuthenticator +from zitadel_client.exceptions import UnauthorizedException + + +@pytest.fixture +def valid_token(): + """Fixture to return a valid personal access token.""" + return os.getenv("AUTH_TOKEN") + + +@pytest.fixture +def invalid_token(): + """Fixture to return an invalid token.""" + return "whoops" + + +@pytest.fixture +def base_url(): + """Fixture to return the base URL.""" + return os.getenv("BASE_URL") + + +@pytest.fixture +def user_id(valid_token, base_url): + """Fixture to create a user and return their ID.""" + with zitadel.Zitadel(PersonalAccessTokenAuthenticator(base_url, valid_token)) as client: + try: + response = client.users.add_human_user( + body=zitadel.models.V2AddHumanUserRequest( + username=uuid.uuid4().hex, + profile=zitadel.models.V2SetHumanProfile(given_name="John", family_name="Doe"), + email=zitadel.models.V2SetHumanEmail(email=f"johndoe{uuid.uuid4().hex}@caos.ag") + ) + ) + print("User created:", response) + return response.user_id + except Exception as e: + pytest.fail(f"Exception while creating user: {e}") + + +def test_should_deactivate_and_reactivate_user_with_valid_token(user_id, valid_token, base_url): + """Test to (de)activate the user with a valid token.""" + with zitadel.Zitadel(PersonalAccessTokenAuthenticator(base_url, valid_token)) as client: + try: + deactivate_response = client.users.deactivate_user(user_id=user_id) + print("User deactivated:", deactivate_response) + + reactivate_response = client.users.reactivate_user(user_id=user_id) + print("User reactivated:", reactivate_response) + # Adjust based on actual response format + # assert reactivate_response["status"] == "success" + except Exception as e: + pytest.fail(f"Exception when calling deactivate_user or reactivate_user with valid token: {e}") + + +def test_should_not_deactivate_or_reactivate_user_with_invalid_token(user_id, invalid_token, base_url): + """Test to attempt (de)activating the user with an invalid token.""" + with zitadel.Zitadel(PersonalAccessTokenAuthenticator(base_url, invalid_token)) as client: + try: + client.users.deactivate_user(user_id=user_id) + pytest.fail("Expected exception when deactivating user with invalid token, but got response.") + except UnauthorizedException as e: + print("Caught expected UnauthorizedException:", e) + except Exception as e: + pytest.fail(f"Invalid exception when calling the function: {e}") + + try: + client.users.reactivate_user(user_id=user_id) + pytest.fail("Expected exception when reactivating user with invalid token, but got response.") + except UnauthorizedException as e: + print("Caught expected UnauthorizedException:", e) + except Exception as e: + pytest.fail(f"Invalid exception when calling the function: {e}") diff --git a/spec/sdk_test_using_web_token_authentication_spec.py b/spec/sdk_test_using_web_token_authentication_spec.py new file mode 100644 index 00000000..3a5e3eec --- /dev/null +++ b/spec/sdk_test_using_web_token_authentication_spec.py @@ -0,0 +1,57 @@ +import os +import tempfile +import uuid + +import pytest + +import zitadel_client as zitadel +from zitadel_client.auth.web_token_authenticator import WebTokenAuthenticator + + +@pytest.fixture +def key_file(): + jwt_key = os.getenv("JWT_KEY") + if jwt_key is None: + pytest.fail("JWT_KEY is not set in the environment") + with tempfile.NamedTemporaryFile(delete=False, mode="w") as tf: + tf.write(jwt_key) + return tf.name + + +@pytest.fixture +def base_url(): + """Fixture to return the base URL.""" + return os.getenv("BASE_URL") + + +@pytest.fixture +def user_id(key_file, base_url): + """Fixture to create a user and return their ID.""" + with zitadel.Zitadel(WebTokenAuthenticator.from_json(base_url, key_file)) as client: + try: + response = client.users.add_human_user( + body=zitadel.models.V2AddHumanUserRequest( + username=uuid.uuid4().hex, + profile=zitadel.models.V2SetHumanProfile(given_name="John", family_name="Doe"), + email=zitadel.models.V2SetHumanEmail(email=f"johndoe{uuid.uuid4().hex}@caos.ag") + ) + ) + print("User created:", response) + return response.user_id + except Exception as e: + pytest.fail(f"Exception while creating user: {e}") + + +def test_should_deactivate_and_reactivate_user_with_valid_token(user_id, key_file, base_url): + """Test to (de)activate the user with a valid token.""" + with zitadel.Zitadel(WebTokenAuthenticator.from_json(base_url, key_file)) as client: + try: + deactivate_response = client.users.deactivate_user(user_id=user_id) + print("User deactivated:", deactivate_response) + + reactivate_response = client.users.reactivate_user(user_id=user_id) + print("User reactivated:", reactivate_response) + # Adjust based on actual response format + # assert reactivate_response["status"] == "success" + except Exception as e: + pytest.fail(f"Exception when calling deactivate_user or reactivate_user with valid token: {e}") diff --git a/test/auth/__init__.py b/test/auth/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/test/auth/test_client_credentials_authenticator.py b/test/auth/test_client_credentials_authenticator.py new file mode 100644 index 00000000..affdd329 --- /dev/null +++ b/test/auth/test_client_credentials_authenticator.py @@ -0,0 +1,29 @@ +import time +from datetime import datetime, timezone + +from test.auth.test_oauth_authenticator import OAuthAuthenticatorTest +from zitadel_client.auth.client_credentials_authenticator import ClientCredentialsAuthenticator + + +class ClientCredentialsAuthenticatorTest(OAuthAuthenticatorTest): + """ + Test for ClientCredentialsAuthenticator to verify token refresh functionality. + Extends the base OAuthAuthenticatorTest class. + """ + + def test_refresh_token(self): + time.sleep(20) + + authenticator = ClientCredentialsAuthenticator.builder(self.oauth_host, "dummy-client", "dummy-secret") \ + .scopes("openid", "foo") \ + .build() + + self.assertTrue(authenticator.get_auth_token(), "Access token should not be empty") + token = authenticator.refresh_token() + self.assertEqual({"Authorization": "Bearer " + token.access_token}, authenticator.get_auth_headers()) + self.assertTrue(token.access_token, "Access token should not be null") + self.assertTrue(token.expires_at > datetime.now(timezone.utc), "Token expiry should be in the future") + self.assertEqual(token.access_token, authenticator.get_auth_token()) + self.assertEqual(self.oauth_host, authenticator.get_host()) + self.assertNotEqual(authenticator.refresh_token().access_token, authenticator.refresh_token().access_token, + "Two refreshToken calls should produce different tokens") diff --git a/test/auth/test_no_auth_authenticator.py b/test/auth/test_no_auth_authenticator.py new file mode 100644 index 00000000..d42fc403 --- /dev/null +++ b/test/auth/test_no_auth_authenticator.py @@ -0,0 +1,15 @@ +import unittest + +from zitadel_client.auth.no_auth_authenticator import NoAuthAuthenticator + + +class NoAuthAuthenticatorTest(unittest.TestCase): + def test_returns_empty_headers_and_default_host(self): + auth = NoAuthAuthenticator() + self.assertEqual({}, auth.get_auth_headers()) + self.assertEqual("http://localhost", auth.get_host()) + + def test_returns_empty_headers_and_custom_host(self): + auth = NoAuthAuthenticator("https://custom-host") + self.assertEqual({}, auth.get_auth_headers()) + self.assertEqual("https://custom-host", auth.get_host()) diff --git a/test/auth/test_oauth_authenticator.py b/test/auth/test_oauth_authenticator.py new file mode 100644 index 00000000..45e37a35 --- /dev/null +++ b/test/auth/test_oauth_authenticator.py @@ -0,0 +1,32 @@ +import unittest + +from testcontainers.core.container import DockerContainer + + +class OAuthAuthenticatorTest(unittest.TestCase): + """ + Base test class for OAuth authenticators. + + This class starts a Docker container running the mock OAuth2 server + (ghcr.io/navikt/mock-oauth2-server:2.1.10) before any tests run and stops it after all tests. + It sets the class variable `oauth_host` to the container’s accessible URL. + + The container is configured to wait for an HTTP response from the "/" endpoint + with a status code of 405, using HttpWaitStrategy. + """ + oauth_host: str = None + mock_oauth2_server: DockerContainer = None + + @classmethod + def setUpClass(cls): + cls.mock_oauth2_server = DockerContainer("ghcr.io/navikt/mock-oauth2-server:2.1.10") \ + .with_exposed_ports(8080) + cls.mock_oauth2_server.start() + host = cls.mock_oauth2_server.get_container_host_ip() + port = cls.mock_oauth2_server.get_exposed_port(8080) + cls.oauth_host = f"http://{host}:{port}" + + @classmethod + def tearDownClass(cls): + if cls.mock_oauth2_server is not None: + cls.mock_oauth2_server.stop() diff --git a/test/auth/test_personal_access_authenticator.py b/test/auth/test_personal_access_authenticator.py new file mode 100644 index 00000000..2b143ed3 --- /dev/null +++ b/test/auth/test_personal_access_authenticator.py @@ -0,0 +1,10 @@ +import unittest + +from zitadel_client.auth.personal_access_token_authenticator import PersonalAccessTokenAuthenticator + + +class PersonalAccessTokenAuthenticatorTest(unittest.TestCase): + def test_returns_expected_headers_and_host(self): + auth = PersonalAccessTokenAuthenticator("https://api.example.com", "my-secret-token") + self.assertEqual({"Authorization": "Bearer my-secret-token"}, auth.get_auth_headers()) + self.assertEqual("https://api.example.com", auth.get_host()) diff --git a/test/auth/test_web_token_authenticator.py b/test/auth/test_web_token_authenticator.py new file mode 100644 index 00000000..1ab33999 --- /dev/null +++ b/test/auth/test_web_token_authenticator.py @@ -0,0 +1,38 @@ +import time +from datetime import datetime, timezone + +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption + +from test.auth.test_oauth_authenticator import OAuthAuthenticatorTest +from zitadel_client.auth.web_token_authenticator import WebTokenAuthenticator + + +class WebTokenAuthenticatorTest(OAuthAuthenticatorTest): + """ + Test for WebTokenAuthenticator to verify JWT token refresh functionality using the builder. + """ + + def test_refresh_token_using_builder(self): + time.sleep(20) + + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + private_key_pem = key.private_bytes( + encoding=Encoding.PEM, + format=PrivateFormat.PKCS8, + encryption_algorithm=NoEncryption() + ).decode('utf-8') + + authenticator = WebTokenAuthenticator.builder(self.oauth_host, "dummy-client", private_key_pem) \ + .token_lifetime_seconds(3600) \ + .build() + + self.assertTrue(authenticator.get_auth_token(), "Access token should not be empty") + token = authenticator.refresh_token() + self.assertEqual({"Authorization": "Bearer " + token.access_token}, authenticator.get_auth_headers()) + self.assertTrue(token.access_token, "Access token should not be null") + self.assertTrue(token.expires_at > datetime.now(timezone.utc), "Token expiry should be in the future") + self.assertEqual(token.access_token, authenticator.get_auth_token()) + self.assertEqual(self.oauth_host, authenticator.get_host()) + self.assertNotEqual(authenticator.refresh_token().access_token, authenticator.refresh_token().access_token, + "Two refreshToken calls should produce different tokens") diff --git a/test/test_api_client.py b/test/test_api_client.py new file mode 100644 index 00000000..598bcf46 --- /dev/null +++ b/test/test_api_client.py @@ -0,0 +1,87 @@ +import json +import time +import unittest +import urllib + +from testcontainers.core.container import DockerContainer + +from zitadel_client import ApiClient, Configuration +from zitadel_client.auth.personal_access_token_authenticator import PersonalAccessTokenAuthenticator + + +class TestApiClient(unittest.TestCase): + """ + Test case for interacting with the WireMock mock OAuth2 server. + """ + + @classmethod + def setUpClass(cls): + """ + Starts the WireMock Docker container and exposes the required port. + Sets up the OAuth server URL. + """ + cls.mock_oauth2_server = DockerContainer("wiremock/wiremock") \ + .with_exposed_ports(8080) + cls.mock_oauth2_server.start() + + host = cls.mock_oauth2_server.get_container_host_ip() + port = cls.mock_oauth2_server.get_exposed_port(8080) + cls.oauth_host = f"http://{host}:{port}" + + @classmethod + def tearDownClass(cls): + """ + Stops the WireMock Docker container. + """ + if cls.mock_oauth2_server is not None: + cls.mock_oauth2_server.stop() + + def test_assert_headers_and_content_type(self): + """ + Test the behavior of API client when sending requests to the mock OAuth2 server, + asserting headers and content type. + """ + time.sleep(20) + + with urllib.request.urlopen( + urllib.request.Request( + self.oauth_host + "/__admin/mappings", + data=json.dumps({ + "request": { + "method": "GET", + "url": "/your/endpoint", + "headers": { + "Authorization": { + "equalTo": "Bearer mm" + } + } + }, + "response": { + "status": 200, + "body": "{\"key\": \"value\"}", + "headers": { + "Content-Type": "application/json" + } + } + }).encode('utf-8'), + headers={'Content-Type': 'application/json'}, + method='POST' + ) + ) as response: + response.read().decode() + + api_client = ApiClient( + Configuration(authenticator=PersonalAccessTokenAuthenticator(self.oauth_host, "mm")) + ) + + api_response = api_client.call_api(*(api_client.param_serialize( + method='GET', + resource_path='/your/endpoint', + ))) + + if api_response.status != 200: + self.fail(f"Expected status 200, but got {api_response.status}") + + +if __name__ == '__main__': + unittest.main() diff --git a/test/test_zitadel.py b/test/test_zitadel.py new file mode 100644 index 00000000..065e6eef --- /dev/null +++ b/test/test_zitadel.py @@ -0,0 +1,29 @@ +import importlib +import inspect +import pkgutil +import unittest + +from zitadel_client.auth.no_auth_authenticator import NoAuthAuthenticator +from zitadel_client.zitadel import Zitadel + + +class ZitadelServicesTest(unittest.TestCase): + """ + Test to verify that all API service classes defined in the "zitadel_client.api" namespace + are registered as attributes in the Zitadel class. + """ + + def test_services_dynamic(self): + expected = set() + package = importlib.import_module("zitadel_client.api") + for _, modname, _ in pkgutil.walk_packages(package.__path__, package.__name__ + "."): + module = importlib.import_module(modname) + for name, obj in inspect.getmembers(module, inspect.isclass): + if obj.__module__ == modname and obj.__name__.endswith("ServiceApi"): + expected.add(obj) + zitadel = Zitadel(NoAuthAuthenticator("http://dummy")) + actual = {type(getattr(zitadel, attr)) + for attr in dir(zitadel) + if not attr.startswith("_") and hasattr(getattr(zitadel, attr), "__class__") + and getattr(zitadel, attr).__class__.__module__.startswith("zitadel_client.api")} + self.assertEqual(expected, actual) diff --git a/zitadel_client/__init__.py b/zitadel_client/__init__.py index 9de50ceb..642b1644 100644 --- a/zitadel_client/__init__.py +++ b/zitadel_client/__init__.py @@ -1,32 +1,5 @@ -# coding: utf-8 - -# flake8: noqa - -""" - Zitadel SDK - - The Zitadel SDK is a convenience wrapper around the Zitadel APIs to assist you in integrating with your Zitadel environment. This SDK enables you to handle resources, settings, and configurations within the Zitadel platform. - - The version of the OpenAPI document: 1.0.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - __version__ = "0.0.1" -# import apis into sdk package -from zitadel_client.api.feature_service_api import FeatureServiceApi -from zitadel_client.api.identity_provider_service_api import IdentityProviderServiceApi -from zitadel_client.api.oidc_service_api import OIDCServiceApi -from zitadel_client.api.organization_service_api import OrganizationServiceApi -from zitadel_client.api.session_service_api import SessionServiceApi -from zitadel_client.api.settings_api import SettingsApi -from zitadel_client.api.settings_service_api import SettingsServiceApi -from zitadel_client.api.user_service_api import UserServiceApi - -# import ApiClient from zitadel_client.api_response import ApiResponse from zitadel_client.api_client import ApiClient from zitadel_client.configuration import Configuration @@ -37,282 +10,4 @@ from zitadel_client.exceptions import ApiAttributeError from zitadel_client.exceptions import ApiException -# import models into sdk package -from zitadel_client.models.add_organization_request_admin import AddOrganizationRequestAdmin -from zitadel_client.models.add_organization_response_created_admin import AddOrganizationResponseCreatedAdmin -from zitadel_client.models.oidc_service_create_callback_body import OIDCServiceCreateCallbackBody -from zitadel_client.models.otp_email_send_code import OTPEmailSendCode -from zitadel_client.models.objectv2_list_details import Objectv2ListDetails -from zitadel_client.models.objectv2_list_query import Objectv2ListQuery -from zitadel_client.models.protobuf_any import ProtobufAny -from zitadel_client.models.request_challenges_otp_email import RequestChallengesOTPEmail -from zitadel_client.models.request_challenges_otpsms import RequestChallengesOTPSMS -from zitadel_client.models.rpc_status import RpcStatus -from zitadel_client.models.session_service_delete_session_body import SessionServiceDeleteSessionBody -from zitadel_client.models.session_service_set_session_body import SessionServiceSetSessionBody -from zitadel_client.models.user_agent_header_values import UserAgentHeaderValues -from zitadel_client.models.user_service_add_idp_link_body import UserServiceAddIDPLinkBody -from zitadel_client.models.user_service_create_invite_code_body import UserServiceCreateInviteCodeBody -from zitadel_client.models.user_service_create_passkey_registration_link_body import UserServiceCreatePasskeyRegistrationLinkBody -from zitadel_client.models.user_service_list_idp_links_body import UserServiceListIDPLinksBody -from zitadel_client.models.user_service_password_reset_body import UserServicePasswordResetBody -from zitadel_client.models.user_service_register_passkey_body import UserServiceRegisterPasskeyBody -from zitadel_client.models.user_service_register_u2_f_body import UserServiceRegisterU2FBody -from zitadel_client.models.user_service_resend_email_code_body import UserServiceResendEmailCodeBody -from zitadel_client.models.user_service_resend_phone_code_body import UserServiceResendPhoneCodeBody -from zitadel_client.models.user_service_retrieve_identity_provider_intent_body import UserServiceRetrieveIdentityProviderIntentBody -from zitadel_client.models.user_service_send_email_code_body import UserServiceSendEmailCodeBody -from zitadel_client.models.user_service_set_email_body import UserServiceSetEmailBody -from zitadel_client.models.user_service_set_phone_body import UserServiceSetPhoneBody -from zitadel_client.models.user_service_update_human_user_body import UserServiceUpdateHumanUserBody -from zitadel_client.models.user_service_verify_email_body import UserServiceVerifyEmailBody -from zitadel_client.models.user_service_verify_invite_code_body import UserServiceVerifyInviteCodeBody -from zitadel_client.models.user_service_verify_passkey_registration_body import UserServiceVerifyPasskeyRegistrationBody -from zitadel_client.models.user_service_verify_phone_body import UserServiceVerifyPhoneBody -from zitadel_client.models.user_service_verify_totp_registration_body import UserServiceVerifyTOTPRegistrationBody -from zitadel_client.models.user_service_verify_u2_f_registration_body import UserServiceVerifyU2FRegistrationBody -from zitadel_client.models.userv2_set_password import Userv2SetPassword -from zitadel_client.models.userv2_type import Userv2Type -from zitadel_client.models.v2_access_token_type import V2AccessTokenType -from zitadel_client.models.v2_add_human_user_request import V2AddHumanUserRequest -from zitadel_client.models.v2_add_human_user_request1 import V2AddHumanUserRequest1 -from zitadel_client.models.v2_add_human_user_response import V2AddHumanUserResponse -from zitadel_client.models.v2_add_idp_link_response import V2AddIDPLinkResponse -from zitadel_client.models.v2_add_otp_email_response import V2AddOTPEmailResponse -from zitadel_client.models.v2_add_otpsms_response import V2AddOTPSMSResponse -from zitadel_client.models.v2_add_organization_request import V2AddOrganizationRequest -from zitadel_client.models.v2_add_organization_response import V2AddOrganizationResponse -from zitadel_client.models.v2_and_query import V2AndQuery -from zitadel_client.models.v2_apple_config import V2AppleConfig -from zitadel_client.models.v2_auth_factor import V2AuthFactor -from zitadel_client.models.v2_auth_factor_state import V2AuthFactorState -from zitadel_client.models.v2_auth_factor_u2_f import V2AuthFactorU2F -from zitadel_client.models.v2_auth_request import V2AuthRequest -from zitadel_client.models.v2_authentication_method_type import V2AuthenticationMethodType -from zitadel_client.models.v2_authorization_error import V2AuthorizationError -from zitadel_client.models.v2_auto_linking_option import V2AutoLinkingOption -from zitadel_client.models.v2_azure_ad_config import V2AzureADConfig -from zitadel_client.models.v2_azure_ad_tenant import V2AzureADTenant -from zitadel_client.models.v2_azure_ad_tenant_type import V2AzureADTenantType -from zitadel_client.models.v2_branding_settings import V2BrandingSettings -from zitadel_client.models.v2_challenges import V2Challenges -from zitadel_client.models.v2_challenges_web_auth_n import V2ChallengesWebAuthN -from zitadel_client.models.v2_check_idp_intent import V2CheckIDPIntent -from zitadel_client.models.v2_check_otp import V2CheckOTP -from zitadel_client.models.v2_check_password import V2CheckPassword -from zitadel_client.models.v2_check_totp import V2CheckTOTP -from zitadel_client.models.v2_check_user import V2CheckUser -from zitadel_client.models.v2_check_web_auth_n import V2CheckWebAuthN -from zitadel_client.models.v2_checks import V2Checks -from zitadel_client.models.v2_create_callback_response import V2CreateCallbackResponse -from zitadel_client.models.v2_create_invite_code_response import V2CreateInviteCodeResponse -from zitadel_client.models.v2_create_passkey_registration_link_response import V2CreatePasskeyRegistrationLinkResponse -from zitadel_client.models.v2_create_session_request import V2CreateSessionRequest -from zitadel_client.models.v2_create_session_response import V2CreateSessionResponse -from zitadel_client.models.v2_creation_date_query import V2CreationDateQuery -from zitadel_client.models.v2_creator_query import V2CreatorQuery -from zitadel_client.models.v2_deactivate_user_response import V2DeactivateUserResponse -from zitadel_client.models.v2_delete_session_response import V2DeleteSessionResponse -from zitadel_client.models.v2_delete_user_response import V2DeleteUserResponse -from zitadel_client.models.v2_details import V2Details -from zitadel_client.models.v2_display_name_query import V2DisplayNameQuery -from zitadel_client.models.v2_domain_settings import V2DomainSettings -from zitadel_client.models.v2_email_query import V2EmailQuery -from zitadel_client.models.v2_embedded_iframe_settings import V2EmbeddedIframeSettings -from zitadel_client.models.v2_error_reason import V2ErrorReason -from zitadel_client.models.v2_factors import V2Factors -from zitadel_client.models.v2_feature_flag import V2FeatureFlag -from zitadel_client.models.v2_first_name_query import V2FirstNameQuery -from zitadel_client.models.v2_gender import V2Gender -from zitadel_client.models.v2_generic_oidc_config import V2GenericOIDCConfig -from zitadel_client.models.v2_get_active_identity_providers_response import V2GetActiveIdentityProvidersResponse -from zitadel_client.models.v2_get_auth_request_response import V2GetAuthRequestResponse -from zitadel_client.models.v2_get_branding_settings_response import V2GetBrandingSettingsResponse -from zitadel_client.models.v2_get_domain_settings_response import V2GetDomainSettingsResponse -from zitadel_client.models.v2_get_general_settings_response import V2GetGeneralSettingsResponse -from zitadel_client.models.v2_get_idpby_id_response import V2GetIDPByIDResponse -from zitadel_client.models.v2_get_instance_features_response import V2GetInstanceFeaturesResponse -from zitadel_client.models.v2_get_legal_and_support_settings_response import V2GetLegalAndSupportSettingsResponse -from zitadel_client.models.v2_get_lockout_settings_response import V2GetLockoutSettingsResponse -from zitadel_client.models.v2_get_login_settings_response import V2GetLoginSettingsResponse -from zitadel_client.models.v2_get_organization_features_response import V2GetOrganizationFeaturesResponse -from zitadel_client.models.v2_get_password_complexity_settings_response import V2GetPasswordComplexitySettingsResponse -from zitadel_client.models.v2_get_password_expiry_settings_response import V2GetPasswordExpirySettingsResponse -from zitadel_client.models.v2_get_security_settings_response import V2GetSecuritySettingsResponse -from zitadel_client.models.v2_get_session_response import V2GetSessionResponse -from zitadel_client.models.v2_get_system_features_response import V2GetSystemFeaturesResponse -from zitadel_client.models.v2_get_user_by_id_response import V2GetUserByIDResponse -from zitadel_client.models.v2_get_user_features_response import V2GetUserFeaturesResponse -from zitadel_client.models.v2_git_hub_config import V2GitHubConfig -from zitadel_client.models.v2_git_hub_enterprise_server_config import V2GitHubEnterpriseServerConfig -from zitadel_client.models.v2_git_lab_config import V2GitLabConfig -from zitadel_client.models.v2_git_lab_self_hosted_config import V2GitLabSelfHostedConfig -from zitadel_client.models.v2_google_config import V2GoogleConfig -from zitadel_client.models.v2_hashed_password import V2HashedPassword -from zitadel_client.models.v2_human_email import V2HumanEmail -from zitadel_client.models.v2_human_mfa_init_skipped_response import V2HumanMFAInitSkippedResponse -from zitadel_client.models.v2_human_phone import V2HumanPhone -from zitadel_client.models.v2_human_profile import V2HumanProfile -from zitadel_client.models.v2_human_user import V2HumanUser -from zitadel_client.models.v2_idp import V2IDP -from zitadel_client.models.v2_idp_config import V2IDPConfig -from zitadel_client.models.v2_idp_information import V2IDPInformation -from zitadel_client.models.v2_idp_intent import V2IDPIntent -from zitadel_client.models.v2_idpldap_access_information import V2IDPLDAPAccessInformation -from zitadel_client.models.v2_idp_link import V2IDPLink -from zitadel_client.models.v2_idpo_auth_access_information import V2IDPOAuthAccessInformation -from zitadel_client.models.v2_idpsaml_access_information import V2IDPSAMLAccessInformation -from zitadel_client.models.v2_idp_state import V2IDPState -from zitadel_client.models.v2_idp_type import V2IDPType -from zitadel_client.models.v2_ids_query import V2IDsQuery -from zitadel_client.models.v2_identity_provider import V2IdentityProvider -from zitadel_client.models.v2_identity_provider_type import V2IdentityProviderType -from zitadel_client.models.v2_improved_performance import V2ImprovedPerformance -from zitadel_client.models.v2_improved_performance_feature_flag import V2ImprovedPerformanceFeatureFlag -from zitadel_client.models.v2_in_user_emails_query import V2InUserEmailsQuery -from zitadel_client.models.v2_in_user_id_query import V2InUserIDQuery -from zitadel_client.models.v2_intent_factor import V2IntentFactor -from zitadel_client.models.v2_jwt_config import V2JWTConfig -from zitadel_client.models.v2_ldap_attributes import V2LDAPAttributes -from zitadel_client.models.v2_ldap_config import V2LDAPConfig -from zitadel_client.models.v2_ldap_credentials import V2LDAPCredentials -from zitadel_client.models.v2_last_name_query import V2LastNameQuery -from zitadel_client.models.v2_legal_and_support_settings import V2LegalAndSupportSettings -from zitadel_client.models.v2_list_authentication_factors_response import V2ListAuthenticationFactorsResponse -from zitadel_client.models.v2_list_authentication_method_types_response import V2ListAuthenticationMethodTypesResponse -from zitadel_client.models.v2_list_details import V2ListDetails -from zitadel_client.models.v2_list_idp_links_response import V2ListIDPLinksResponse -from zitadel_client.models.v2_list_organizations_request import V2ListOrganizationsRequest -from zitadel_client.models.v2_list_organizations_response import V2ListOrganizationsResponse -from zitadel_client.models.v2_list_passkeys_response import V2ListPasskeysResponse -from zitadel_client.models.v2_list_query import V2ListQuery -from zitadel_client.models.v2_list_sessions_request import V2ListSessionsRequest -from zitadel_client.models.v2_list_sessions_response import V2ListSessionsResponse -from zitadel_client.models.v2_list_users_request import V2ListUsersRequest -from zitadel_client.models.v2_list_users_response import V2ListUsersResponse -from zitadel_client.models.v2_lock_user_response import V2LockUserResponse -from zitadel_client.models.v2_lockout_settings import V2LockoutSettings -from zitadel_client.models.v2_login_name_query import V2LoginNameQuery -from zitadel_client.models.v2_login_settings import V2LoginSettings -from zitadel_client.models.v2_login_v2 import V2LoginV2 -from zitadel_client.models.v2_login_v2_feature_flag import V2LoginV2FeatureFlag -from zitadel_client.models.v2_machine_user import V2MachineUser -from zitadel_client.models.v2_multi_factor_type import V2MultiFactorType -from zitadel_client.models.v2_nick_name_query import V2NickNameQuery -from zitadel_client.models.v2_not_query import V2NotQuery -from zitadel_client.models.v2_notification_type import V2NotificationType -from zitadel_client.models.v2_o_auth_config import V2OAuthConfig -from zitadel_client.models.v2_otp_factor import V2OTPFactor -from zitadel_client.models.v2_or_query import V2OrQuery -from zitadel_client.models.v2_organization import V2Organization -from zitadel_client.models.v2_organization_domain_query import V2OrganizationDomainQuery -from zitadel_client.models.v2_organization_field_name import V2OrganizationFieldName -from zitadel_client.models.v2_organization_id_query import V2OrganizationIDQuery -from zitadel_client.models.v2_organization_name_query import V2OrganizationNameQuery -from zitadel_client.models.v2_organization_state import V2OrganizationState -from zitadel_client.models.v2_organization_state_query import V2OrganizationStateQuery -from zitadel_client.models.v2_passkey import V2Passkey -from zitadel_client.models.v2_passkey_authenticator import V2PasskeyAuthenticator -from zitadel_client.models.v2_passkey_registration_code import V2PasskeyRegistrationCode -from zitadel_client.models.v2_passkeys_type import V2PasskeysType -from zitadel_client.models.v2_password import V2Password -from zitadel_client.models.v2_password_complexity_settings import V2PasswordComplexitySettings -from zitadel_client.models.v2_password_expiry_settings import V2PasswordExpirySettings -from zitadel_client.models.v2_password_factor import V2PasswordFactor -from zitadel_client.models.v2_password_reset_response import V2PasswordResetResponse -from zitadel_client.models.v2_phone_query import V2PhoneQuery -from zitadel_client.models.v2_prompt import V2Prompt -from zitadel_client.models.v2_reactivate_user_response import V2ReactivateUserResponse -from zitadel_client.models.v2_redirect_urls import V2RedirectURLs -from zitadel_client.models.v2_register_passkey_response import V2RegisterPasskeyResponse -from zitadel_client.models.v2_register_totp_response import V2RegisterTOTPResponse -from zitadel_client.models.v2_register_u2_f_response import V2RegisterU2FResponse -from zitadel_client.models.v2_remove_idp_link_response import V2RemoveIDPLinkResponse -from zitadel_client.models.v2_remove_otp_email_response import V2RemoveOTPEmailResponse -from zitadel_client.models.v2_remove_otpsms_response import V2RemoveOTPSMSResponse -from zitadel_client.models.v2_remove_passkey_response import V2RemovePasskeyResponse -from zitadel_client.models.v2_remove_phone_response import V2RemovePhoneResponse -from zitadel_client.models.v2_remove_totp_response import V2RemoveTOTPResponse -from zitadel_client.models.v2_remove_u2_f_response import V2RemoveU2FResponse -from zitadel_client.models.v2_request_challenges import V2RequestChallenges -from zitadel_client.models.v2_request_challenges_web_auth_n import V2RequestChallengesWebAuthN -from zitadel_client.models.v2_resend_email_code_response import V2ResendEmailCodeResponse -from zitadel_client.models.v2_resend_invite_code_response import V2ResendInviteCodeResponse -from zitadel_client.models.v2_resend_phone_code_response import V2ResendPhoneCodeResponse -from zitadel_client.models.v2_reset_instance_features_response import V2ResetInstanceFeaturesResponse -from zitadel_client.models.v2_reset_organization_features_response import V2ResetOrganizationFeaturesResponse -from zitadel_client.models.v2_reset_system_features_response import V2ResetSystemFeaturesResponse -from zitadel_client.models.v2_reset_user_features_response import V2ResetUserFeaturesResponse -from zitadel_client.models.v2_resource_owner_type import V2ResourceOwnerType -from zitadel_client.models.v2_retrieve_identity_provider_intent_response import V2RetrieveIdentityProviderIntentResponse -from zitadel_client.models.v2_saml_binding import V2SAMLBinding -from zitadel_client.models.v2_saml_config import V2SAMLConfig -from zitadel_client.models.v2_saml_name_id_format import V2SAMLNameIDFormat -from zitadel_client.models.v2_search_query import V2SearchQuery -from zitadel_client.models.v2_search_query1 import V2SearchQuery1 -from zitadel_client.models.v2_second_factor_type import V2SecondFactorType -from zitadel_client.models.v2_security_settings import V2SecuritySettings -from zitadel_client.models.v2_send_email_code_response import V2SendEmailCodeResponse -from zitadel_client.models.v2_send_email_verification_code import V2SendEmailVerificationCode -from zitadel_client.models.v2_send_invite_code import V2SendInviteCode -from zitadel_client.models.v2_send_passkey_registration_link import V2SendPasskeyRegistrationLink -from zitadel_client.models.v2_send_password_reset_link import V2SendPasswordResetLink -from zitadel_client.models.v2_session import V2Session -from zitadel_client.models.v2_session1 import V2Session1 -from zitadel_client.models.v2_session_field_name import V2SessionFieldName -from zitadel_client.models.v2_set_email_response import V2SetEmailResponse -from zitadel_client.models.v2_set_human_email import V2SetHumanEmail -from zitadel_client.models.v2_set_human_email1 import V2SetHumanEmail1 -from zitadel_client.models.v2_set_human_phone import V2SetHumanPhone -from zitadel_client.models.v2_set_human_phone1 import V2SetHumanPhone1 -from zitadel_client.models.v2_set_human_profile import V2SetHumanProfile -from zitadel_client.models.v2_set_human_profile1 import V2SetHumanProfile1 -from zitadel_client.models.v2_set_instance_features_request import V2SetInstanceFeaturesRequest -from zitadel_client.models.v2_set_instance_features_response import V2SetInstanceFeaturesResponse -from zitadel_client.models.v2_set_metadata_entry import V2SetMetadataEntry -from zitadel_client.models.v2_set_metadata_entry1 import V2SetMetadataEntry1 -from zitadel_client.models.v2_set_organization_features_response import V2SetOrganizationFeaturesResponse -from zitadel_client.models.v2_set_password_response import V2SetPasswordResponse -from zitadel_client.models.v2_set_phone_response import V2SetPhoneResponse -from zitadel_client.models.v2_set_security_settings_request import V2SetSecuritySettingsRequest -from zitadel_client.models.v2_set_security_settings_response import V2SetSecuritySettingsResponse -from zitadel_client.models.v2_set_session_response import V2SetSessionResponse -from zitadel_client.models.v2_set_system_features_request import V2SetSystemFeaturesRequest -from zitadel_client.models.v2_set_system_features_response import V2SetSystemFeaturesResponse -from zitadel_client.models.v2_set_user_features_response import V2SetUserFeaturesResponse -from zitadel_client.models.v2_source import V2Source -from zitadel_client.models.v2_start_identity_provider_intent_request import V2StartIdentityProviderIntentRequest -from zitadel_client.models.v2_start_identity_provider_intent_response import V2StartIdentityProviderIntentResponse -from zitadel_client.models.v2_state_query import V2StateQuery -from zitadel_client.models.v2_totp_factor import V2TOTPFactor -from zitadel_client.models.v2_text_query_method import V2TextQueryMethod -from zitadel_client.models.v2_theme import V2Theme -from zitadel_client.models.v2_theme_mode import V2ThemeMode -from zitadel_client.models.v2_type_query import V2TypeQuery -from zitadel_client.models.v2_unlock_user_response import V2UnlockUserResponse -from zitadel_client.models.v2_update_human_user_response import V2UpdateHumanUserResponse -from zitadel_client.models.v2_user import V2User -from zitadel_client.models.v2_user_agent import V2UserAgent -from zitadel_client.models.v2_user_agent_query import V2UserAgentQuery -from zitadel_client.models.v2_user_factor import V2UserFactor -from zitadel_client.models.v2_user_field_name import V2UserFieldName -from zitadel_client.models.v2_user_id_query import V2UserIDQuery -from zitadel_client.models.v2_user_name_query import V2UserNameQuery -from zitadel_client.models.v2_user_service_set_password_body import V2UserServiceSetPasswordBody -from zitadel_client.models.v2_user_state import V2UserState -from zitadel_client.models.v2_user_verification_requirement import V2UserVerificationRequirement -from zitadel_client.models.v2_verify_email_response import V2VerifyEmailResponse -from zitadel_client.models.v2_verify_invite_code_response import V2VerifyInviteCodeResponse -from zitadel_client.models.v2_verify_passkey_registration_response import V2VerifyPasskeyRegistrationResponse -from zitadel_client.models.v2_verify_phone_response import V2VerifyPhoneResponse -from zitadel_client.models.v2_verify_totp_registration_response import V2VerifyTOTPRegistrationResponse -from zitadel_client.models.v2_verify_u2_f_registration_response import V2VerifyU2FRegistrationResponse -from zitadel_client.models.v2_web_auth_n_factor import V2WebAuthNFactor -from zitadel_client.models.zitadelidpv2_options import Zitadelidpv2Options -from zitadel_client.models.zitadelidpv2_options1 import Zitadelidpv2Options1 -from zitadel_client.models.zitadelobjectv2_organization import Zitadelobjectv2Organization -from zitadel_client.models.zitadelorgv2_organization import Zitadelorgv2Organization -from zitadel_client.models.zitadelorgv2_search_query import Zitadelorgv2SearchQuery -from zitadel_client.models.zitadelv1_timestamp_query_method import Zitadelv1TimestampQueryMethod - from zitadel_client.zitadel import Zitadel diff --git a/zitadel_client/api_client.py b/zitadel_client/api_client.py index 276a7b3b..a93cdcfa 100644 --- a/zitadel_client/api_client.py +++ b/zitadel_client/api_client.py @@ -1,67 +1,47 @@ -# coding: utf-8 - -""" - Zitadel SDK - - The Zitadel SDK is a convenience wrapper around the Zitadel APIs to assist you in integrating with your Zitadel environment. This SDK enables you to handle resources, settings, and configurations within the Zitadel platform. - - The version of the OpenAPI document: 1.0.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - import datetime -from dateutil.parser import parse -from enum import Enum import decimal import json import mimetypes import os import re import tempfile - +from enum import Enum +from typing import Tuple, Optional, List, Dict, Union, Any from urllib.parse import quote -from typing import Tuple, Optional, List, Dict, Union + +from dateutil.parser import parse from pydantic import SecretStr -from zitadel_client.configuration import Configuration -from zitadel_client.api_response import ApiResponse, T as ApiResponseT import zitadel_client.models from zitadel_client import rest +from zitadel_client.api_response import ApiResponse, T as ApiResponseT +from zitadel_client.auth.no_auth_authenticator import NoAuthAuthenticator +from zitadel_client.configuration import Configuration from zitadel_client.exceptions import ( - ApiValueError, - ApiException, - BadRequestException, - UnauthorizedException, - ForbiddenException, - NotFoundException, - ServiceException + ApiException ) RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] + class ApiClient: """Generic API client for OpenAPI client library builds. - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI + OpenAPI generic API client. This client handles the client-server communication, + and is invariant across implementations. Specifics of the methods and models + for each application are generated from the OpenAPI templates. :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to the API. - :param cookie: a cookie to include in the header when making calls - to the API """ PRIMITIVE_TYPES = (float, bool, bytes, str, int) NATIVE_TYPES_MAPPING = { 'int': int, - 'long': int, # TODO remove as only py3 is supported? + 'long': int, 'float': float, 'str': str, 'bool': bool, @@ -73,23 +53,17 @@ class ApiClient: _pool = None def __init__( - self, - configuration=None, - header_name=None, - header_value=None, - cookie=None + self, + configuration: Configuration, + header_name=None, + header_value=None, ) -> None: - # use default configuration if none is provided - if configuration is None: - configuration = Configuration.get_default() self.configuration = configuration self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. self.user_agent = 'OpenAPI-Generator/0.0.1/python' self.client_side_validation = configuration.client_side_validation @@ -111,49 +85,27 @@ def user_agent(self, value): def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value - _default = None - @classmethod - def get_default(cls): - """Return new instance of ApiClient. - - This method returns newly created, based on default constructor, - object of ApiClient class or returns a copy of default - ApiClient. - - :return: The ApiClient object. - """ - if cls._default is None: - cls._default = ApiClient() - return cls._default - - @classmethod - def set_default(cls, default): - """Set default instance of ApiClient. - - It stores default ApiClient. - - :param default: object of ApiClient. - """ - cls._default = default - def param_serialize( - self, - method, - resource_path, - path_params=None, - query_params=None, - header_params=None, - body=None, - post_params=None, - files=None, auth_settings=None, - collection_formats=None, - _host=None, - _request_auth=None + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, + auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None ) -> RequestSerialized: """Builds the HTTP request params needed by the request. + :param _host: + :param auth_settings: :param method: Method to call. :param resource_path: Path to method endpoint. :param path_params: Path parameters in the url. @@ -161,14 +113,12 @@ def param_serialize( :param header_params: Header parameters to be placed in the request header. :param body: Request body. - :param post_params dict: Request post form parameters, + :param post_params: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. + :param auth_settings: Auth Settings names for the request. :param collection_formats: dict of collection formats for path, query, header, and post parameters. - :param _request_auth: set to override the auth_settings for an a single + :param _request_auth: set to override the auth_settings for an single request; this effectively ignores the authentication in the spec for a single request. :return: tuple of form (path, http_method, query_params, header_params, @@ -180,12 +130,10 @@ def param_serialize( # header parameters header_params = header_params or {} header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) header_params = dict( - self.parameters_to_tuples(header_params,collection_formats) + self.parameters_to_tuples(header_params, collection_formats) ) # path parameters @@ -213,29 +161,16 @@ def param_serialize( if files: post_params.extend(self.files_parameters(files)) - # auth setting - self.update_params_for_auth( - header_params, - query_params, - auth_settings, - resource_path, - method, - body, - request_auth=_request_auth - ) + header_params.update(self.configuration.authenticator.get_auth_headers()) - # body if body: body = self.sanitize_for_serialization(body) - # request url - if _host is None or self.configuration.ignore_operation_servers: - url = self.configuration.host + resource_path + if _host is None: + url = self.configuration.host + resource_path else: - # use server/host defined in path or operation instead - url = _host + resource_path + url = _host + resource_path - # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) url_query = self.parameters_to_url_query( @@ -246,23 +181,23 @@ def param_serialize( return method, url, header_params, body, post_params - def call_api( - self, - method, - url, - header_params=None, - body=None, - post_params=None, - _request_timeout=None + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None ) -> rest.RESTResponse: """Makes the HTTP request (synchronous) + :param post_params: :param method: Method to call. :param url: Path to method endpoint. :param header_params: Header parameters to be placed in the request header. :param body: Request body. - :param post_params dict: Request post form parameters, + :param post_params: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param _request_timeout: timeout setting for this request. :return: RESTResponse @@ -283,9 +218,9 @@ def call_api( return response_data def response_deserialize( - self, - response_data: rest.RESTResponse, - response_types_map: Optional[Dict[str, ApiResponseT]]=None + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]] = None ) -> ApiResponse[ApiResponseT]: """Deserializes response into an object. :param response_data: RESTResponse object to be deserialized. @@ -324,13 +259,13 @@ def response_deserialize( body=response_text, data=return_data, ) - - return ApiResponse( - status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data - ) + else: + return ApiResponse( + status_code=response_data.status, + data=return_data, + headers=response_data.getheaders(), + raw_data=response_data.data + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -343,7 +278,7 @@ def sanitize_for_serialization(self, obj): If obj is decimal.Decimal return string representation. If obj is list, sanitize each element in the list. If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. + If obj is OpenAPI model, return the properties' dict. :param obj: The data to serialize. :return: The serialized form of data. @@ -390,7 +325,7 @@ def sanitize_for_serialization(self, obj): def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]): """Deserializes response into an object. - :param response: RESTResponse object to be deserialized. + :param response_text: RESTResponse object to be deserialized. :param response_type: class literal for deserialized object, or string of class name. :param content_type: content type of response. @@ -419,7 +354,8 @@ def deserialize(self, response_text: str, response_type: str, content_type: Opti return self.__deserialize(data, response_type) - def __deserialize(self, data, klass): + @staticmethod + def __deserialize(data, klass): """Deserializes dict, list, str into an object. :param data: dict, list or str. @@ -435,38 +371,39 @@ def __deserialize(self, data, klass): m = re.match(r'List\[(.*)]', klass) assert m is not None, "Malformed List type definition" sub_kls = m.group(1) - return [self.__deserialize(sub_data, sub_kls) + return [ApiClient.__deserialize(sub_data) for sub_data in data] if klass.startswith('Dict['): m = re.match(r'Dict\[([^,]*), (.*)]', klass) assert m is not None, "Malformed Dict type definition" sub_kls = m.group(2) - return {k: self.__deserialize(v, sub_kls) + return {k: ApiClient.__deserialize(sub_kls) for k, v in data.items()} # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] + if klass in ApiClient.NATIVE_TYPES_MAPPING: + klass = ApiClient.NATIVE_TYPES_MAPPING[klass] else: klass = getattr(zitadel_client.models, klass) - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) + if klass in ApiClient.PRIMITIVE_TYPES: + return ApiClient.__deserialize_primitive(data, klass) elif klass == object: - return self.__deserialize_object(data) + return ApiClient.__deserialize_object(data) elif klass == datetime.date: - return self.__deserialize_date(data) + return ApiClient.__deserialize_date(data) elif klass == datetime.datetime: - return self.__deserialize_datetime(data) + return ApiClient.__deserialize_datetime(data) elif klass == decimal.Decimal: return decimal.Decimal(data) elif issubclass(klass, Enum): - return self.__deserialize_enum(data, klass) + return ApiClient.__deserialize_enum(data, klass) else: - return self.__deserialize_model(data, klass) + return ApiClient.__deserialize_model(data, klass) - def parameters_to_tuples(self, params, collection_formats): + @staticmethod + def parameters_to_tuples(params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples @@ -496,7 +433,8 @@ def parameters_to_tuples(self, params, collection_formats): new_params.append((k, v)) return new_params - def parameters_to_url_query(self, params, collection_formats): + @staticmethod + def parameters_to_url_query(params, collection_formats): """Get parameters as list of tuples, formatting collections. :param params: Parameters as dict or list of two-tuples @@ -536,8 +474,8 @@ def parameters_to_url_query(self, params, collection_formats): return "&".join(["=".join(map(str, item)) for item in new_params]) def files_parameters( - self, - files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], + self, + files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]], ): """Builds form parameters. @@ -562,15 +500,16 @@ def files_parameters( else: raise ValueError("Unsupported file value") mimetype = ( - mimetypes.guess_type(filename)[0] - or 'application/octet-stream' + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' ) params.append( tuple([k, tuple([filename, filedata, mimetype])]) ) return params - def select_header_accept(self, accepts: List[str]) -> Optional[str]: + @staticmethod + def select_header_accept(accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. @@ -585,7 +524,8 @@ def select_header_accept(self, accepts: List[str]) -> Optional[str]: return accepts[0] - def select_header_content_type(self, content_types): + @staticmethod + def select_header_content_type(content_types): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. @@ -600,85 +540,8 @@ def select_header_content_type(self, content_types): return content_types[0] - def update_params_for_auth( - self, - headers, - queries, - auth_settings, - resource_path, - method, - body, - request_auth=None - ) -> None: - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param request_auth: if set, the provided settings will - override the token in the configuration. - """ - if not auth_settings: - return - - if request_auth: - self._apply_auth_params( - headers, - queries, - resource_path, - method, - body, - request_auth - ) - else: - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params( - headers, - queries, - resource_path, - method, - body, - auth_setting - ) - - def _apply_auth_params( - self, - headers, - queries, - resource_path, - method, - body, - auth_setting - ) -> None: - """Updates the request parameters based on a single auth_setting - - :param headers: Header parameters dict to be updated. - :param queries: Query parameters tuple list to be updated. - :resource_path: A string representation of the HTTP request resource path. - :method: A string representation of the HTTP request method. - :body: A object representing the body of the HTTP request. - The object type is the return value of sanitize_for_serialization(). - :param auth_setting: auth settings for the endpoint - """ - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['value'] - elif auth_setting['in'] == 'header': - if auth_setting['type'] != 'http-signature': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - queries.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - def __deserialize_file(self, response): + @staticmethod + def __deserialize_file(response): """Deserializes body to file Saves response body into a file in a temporary folder, @@ -690,7 +553,7 @@ def __deserialize_file(self, response): :param response: RESTResponse. :return: file path. """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) + fd, path = tempfile.mkstemp() os.close(fd) os.remove(path) @@ -709,7 +572,8 @@ def __deserialize_file(self, response): return path - def __deserialize_primitive(self, data, klass): + @staticmethod + def __deserialize_primitive(data, klass): """Deserializes string to primitive type. :param data: str. @@ -724,14 +588,16 @@ def __deserialize_primitive(self, data, klass): except TypeError: return data - def __deserialize_object(self, value): + @staticmethod + def __deserialize_object(value): """Return an original value. :return: object. """ return value - def __deserialize_date(self, string): + @staticmethod + def __deserialize_date(string): """Deserializes string to date. :param string: str. @@ -747,7 +613,8 @@ def __deserialize_date(self, string): reason="Failed to parse `{0}` as date object".format(string) ) - def __deserialize_datetime(self, string): + @staticmethod + def __deserialize_datetime(string): """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -768,7 +635,8 @@ def __deserialize_datetime(self, string): ) ) - def __deserialize_enum(self, data, klass): + @staticmethod + def __deserialize_enum(data, klass): """Deserializes primitive type to enum. :param data: primitive type. @@ -786,7 +654,8 @@ def __deserialize_enum(self, data, klass): ) ) - def __deserialize_model(self, data, klass): + @staticmethod + def __deserialize_model(data, klass: Any): """Deserializes list or dict to model. :param data: dict, list. @@ -795,3 +664,7 @@ def __deserialize_model(self, data, klass): """ return klass.from_dict(data) + + @classmethod + def get_default(cls): + return ApiClient(configuration=Configuration(authenticator=NoAuthAuthenticator())) diff --git a/zitadel_client/api_response.py b/zitadel_client/api_response.py index 9bc7c11f..271ae162 100644 --- a/zitadel_client/api_response.py +++ b/zitadel_client/api_response.py @@ -1,21 +1,22 @@ -"""API response object.""" - from __future__ import annotations + from typing import Optional, Generic, Mapping, TypeVar + from pydantic import Field, StrictInt, StrictBytes, BaseModel T = TypeVar("T") + class ApiResponse(BaseModel, Generic[T]): - """ - API response object - """ + """ + API response object + """ - status_code: StrictInt = Field(description="HTTP status code") - headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") - data: T = Field(description="Deserialized data given the data type") - raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - model_config = { - "arbitrary_types_allowed": True - } + model_config = { + "arbitrary_types_allowed": True + } diff --git a/zitadel_client/auth/__init__.py b/zitadel_client/auth/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/zitadel_client/auth/authenticator.py b/zitadel_client/auth/authenticator.py new file mode 100644 index 00000000..ea0a37bc --- /dev/null +++ b/zitadel_client/auth/authenticator.py @@ -0,0 +1,100 @@ +from abc import ABC, abstractmethod +from datetime import datetime, timezone +from typing import Dict, Generic, TypeVar + +from zitadel_client.auth.open_id import OpenId + + +class Authenticator(ABC): + """ + Abstract base class for authenticators. + + This class defines the basic structure for any authenticator by requiring the implementation + of a method to retrieve authentication headers, and provides a way to store and retrieve the host. + """ + + def __init__(self, host: str): + """ + Initializes the Authenticator with the specified host. + + :param host: The base URL or endpoint for the service. + """ + self.host = host + + @abstractmethod + def get_auth_headers(self) -> Dict[str, str]: + """ + Retrieves the authentication headers to be sent with requests. + + Subclasses must override this method to return the appropriate headers. + + :return: A dictionary mapping header names to their values. + """ + pass + + def get_host(self) -> str: + """ + Returns the stored host. + + :return: The host as a string. + """ + return self.host + + +class Token: + def __init__(self, access_token: str, expires_at: datetime): + """ + Initializes a new Token instance. + + Parameters: + - access_token (str): The JWT or OAuth token. + - expires_at (datetime): The expiration time of the token. It should be timezone-aware. + If a naive datetime is provided, it will be converted to an aware datetime in UTC. + """ + self.access_token = access_token + + # Ensure expires_at is timezone-aware. If naive, assume UTC. + if expires_at.tzinfo is None: + self.expires_at = expires_at.replace(tzinfo=timezone.utc) + else: + self.expires_at = expires_at + + def is_expired(self) -> bool: + """ + Checks if the token is expired by comparing the current UTC time + with the token's expiration time. + + Returns: + - bool: True if expired, False otherwise. + """ + return datetime.now(timezone.utc) >= self.expires_at + + +T = TypeVar("T", bound="OAuthAuthenticatorBuilder") + + +class OAuthAuthenticatorBuilder(ABC, Generic[T]): + """ + Abstract builder class for constructing OAuth authenticator instances. + + This builder provides common configuration options such as the OpenId instance and authentication scopes. + """ + + def __init__(self, host: str): + """ + Initializes the OAuthAuthenticatorBuilder with a given host. + + :param host: The base URL for the OAuth provider. + """ + self.open_id = OpenId(host) + self.auth_scopes = {"openid", "urn:zitadel:iam:org:project:id:zitadel:aud"} + + def scopes(self: T, *auth_scopes: str) -> T: + """ + Sets the authentication scopes for the OAuth authenticator. + + :param auth_scopes: A variable number of scope strings. + :return: The builder instance to allow for method chaining. + """ + self.auth_scopes = set(auth_scopes) + return self diff --git a/zitadel_client/auth/client_credentials_authenticator.py b/zitadel_client/auth/client_credentials_authenticator.py new file mode 100644 index 00000000..2e54209e --- /dev/null +++ b/zitadel_client/auth/client_credentials_authenticator.py @@ -0,0 +1,77 @@ +from typing import override, Set + +from authlib.integrations.requests_client import OAuth2Session + +from zitadel_client.auth.authenticator import OAuthAuthenticatorBuilder +from zitadel_client.auth.oauth_authenticator import OAuthAuthenticator +from zitadel_client.auth.open_id import OpenId + + +class ClientCredentialsAuthenticator(OAuthAuthenticator): + """ + OAuth authenticator implementing the client credentials flow. + + Uses client_id and client_secret to obtain an access token from the OAuth2 token endpoint. + """ + + def __init__(self, open_id: OpenId, client_id: str, client_secret: str, auth_scopes: Set[str]): + """ + Constructs a ClientCredentialsAuthenticator. + + :param open_id: The base URL for the OAuth provider. + :param client_id: The OAuth client identifier. + :param client_secret: The OAuth client secret. + :param auth_scopes: The scope(s) for the token request. + """ + super().__init__(open_id, + OAuth2Session(client_id=client_id, client_secret=client_secret, scope=" ".join(auth_scopes))) + + @override + def get_grant(self) -> dict: + """ + Returns the grant parameters for the client credentials flow. + + :return: A dictionary with the grant type for client credentials. + """ + return {"grant_type": "client_credentials"} + + @staticmethod + def builder(host: str, client_id: str, client_secret: str) -> "ClientCredentialsAuthenticatorBuilder": + """ + Returns a builder for constructing a ClientCredentialsAuthenticator. + + :param host: The base URL for the OAuth provider. + :param client_id: The OAuth client identifier. + :param client_secret: The OAuth client secret. + :return: A ClientCredentialsAuthenticatorBuilder instance. + """ + return ClientCredentialsAuthenticatorBuilder(host, client_id, client_secret) + + +class ClientCredentialsAuthenticatorBuilder(OAuthAuthenticatorBuilder): + """ + Builder class for constructing ClientCredentialsAuthenticator instances. + + This builder extends the OAuthAuthenticatorBuilder with client credentials (client_id and client_secret) + required for the client credentials flow. + """ + + def __init__(self, host: str, client_id: str, client_secret: str): + """ + Initializes the ClientCredentialsAuthenticatorBuilder with host, client ID, and client secret. + + :param host: The base URL for the OAuth provider. + :param client_id: The OAuth client identifier. + :param client_secret: The OAuth client secret. + """ + super().__init__(host) + self.client_id = client_id + self.client_secret = client_secret + + def build(self) -> ClientCredentialsAuthenticator: + """ + Constructs and returns a ClientCredentialsAuthenticator instance using the configured parameters. + + :return: A configured ClientCredentialsAuthenticator. + """ + return ClientCredentialsAuthenticator(self.open_id, self.client_id, self.client_secret, self.auth_scopes) diff --git a/zitadel_client/auth/no_auth_authenticator.py b/zitadel_client/auth/no_auth_authenticator.py new file mode 100644 index 00000000..c6df71f3 --- /dev/null +++ b/zitadel_client/auth/no_auth_authenticator.py @@ -0,0 +1,28 @@ +from typing import Dict + +from zitadel_client.auth.authenticator import Authenticator + + +class NoAuthAuthenticator(Authenticator): + """ + A simple authenticator that performs no authentication. + + This authenticator is useful for cases where no token or credentials are required. + It simply returns an empty dictionary for authentication headers. + """ + + def __init__(self, host: str = "http://localhost"): + """ + Initializes the NoAuthAuthenticator with a default host. + + :param host: The base URL for the service. Defaults to "http://localhost". + """ + super().__init__(host) + + def get_auth_headers(self) -> Dict[str, str]: + """ + Returns an empty dictionary since no authentication is performed. + + :return: An empty dictionary. + """ + return {} diff --git a/zitadel_client/auth/oauth_authenticator.py b/zitadel_client/auth/oauth_authenticator.py new file mode 100644 index 00000000..eb595c1a --- /dev/null +++ b/zitadel_client/auth/oauth_authenticator.py @@ -0,0 +1,73 @@ +from abc import ABC, abstractmethod +from datetime import datetime, timedelta, timezone +from typing import Dict, Optional + +from authlib.integrations.requests_client import OAuth2Session + +from zitadel_client.auth.authenticator import Token, Authenticator +from zitadel_client.auth.open_id import OpenId + + +class OAuthAuthenticator(Authenticator, ABC): + """ + Base class for OAuth-based authentication using Authlib. + + Attributes: + open_id: An object providing OAuth endpoint information. + oauth_session: An OAuth2Session instance used for fetching tokens. + """ + + def __init__(self, open_id: OpenId, oauth_session: OAuth2Session): + """ + Constructs an OAuthAuthenticator. + + :param open_id: An object that must implement get_host_endpoint() and get_token_endpoint(). + :param oauth_session: The scope for the token request. + """ + super().__init__(open_id.get_host_endpoint()) + self.open_id = open_id + self.token: Optional[Token] = None + self.oauth_session = oauth_session + + def get_auth_token(self) -> str: + """ + Returns the current access token, refreshing it if necessary. + """ + if self.token is None or self.token.is_expired(): + self.refresh_token() + return self.token.access_token + + def get_auth_headers(self) -> Dict[str, str]: + """ + Retrieves authentication headers. + + :return: A dictionary containing the 'Authorization' header. + """ + return {"Authorization": "Bearer " + self.get_auth_token()} + + @abstractmethod + def get_grant(self) -> dict: + """ + Builds and returns a dictionary of grant parameters required for the token request. + + For example, this might include parameters like grant_type, client_assertion, etc. + """ + pass + + def refresh_token(self) -> Token: + """ + Refreshes the access token using the OAuth flow. + It uses get_grant() to obtain all necessary parameters, such as the grant type and any assertions. + + :return: A new Token. + """ + try: + token_response = self.oauth_session.fetch_token(url=(self.open_id.get_token_endpoint()), + **(self.get_grant())) + access_token = token_response["access_token"] + expires_in = token_response.get("expires_in", 3600) + expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in) + self.token = Token(access_token, expires_at) + return self.token + except Exception as e: + raise Exception("Failed to refresh token: " + str(e)) from e diff --git a/zitadel_client/auth/open_id.py b/zitadel_client/auth/open_id.py new file mode 100644 index 00000000..e036abf1 --- /dev/null +++ b/zitadel_client/auth/open_id.py @@ -0,0 +1,54 @@ +import json +import urllib +from urllib.parse import urljoin + + +class OpenId: + """ + OpenId retrieves OpenID Connect configuration from a given host. + + It builds the well-known configuration URL from the provided hostname, + fetches the configuration, and extracts the token endpoint. + """ + + def __init__(self, hostname: str): + if not (hostname.startswith("http://") or hostname.startswith("https://")): + hostname = "https://" + hostname + + self.host_endpoint = hostname + well_known_url = self.build_well_known_url(hostname) + + try: + with urllib.request.urlopen(well_known_url) as response: + if response.status != 200: + raise Exception(f"Failed to fetch OpenID configuration: HTTP {response.status}") + config = json.loads(response.read().decode('utf-8')) + except urllib.error.URLError as e: + raise Exception(f"URL error occurred: {e}") + except json.JSONDecodeError: + raise Exception("Failed to decode JSON response") + + token_endpoint = config.get("token_endpoint") + if not token_endpoint: + raise Exception("token_endpoint not found in OpenID configuration") + + self.token_endpoint = token_endpoint + + @staticmethod + def build_well_known_url(hostname: str) -> str: + """ + Builds the well-known OpenID configuration URL for the given hostname. + """ + return urljoin(hostname, "/.well-known/openid-configuration") + + def get_host_endpoint(self) -> str: + """ + Returns the host endpoint URL. + """ + return self.host_endpoint + + def get_token_endpoint(self) -> str: + """ + Returns the token endpoint URL extracted from the OpenID configuration. + """ + return self.token_endpoint diff --git a/zitadel_client/auth/personal_access_token_authenticator.py b/zitadel_client/auth/personal_access_token_authenticator.py new file mode 100644 index 00000000..000c06d6 --- /dev/null +++ b/zitadel_client/auth/personal_access_token_authenticator.py @@ -0,0 +1,24 @@ +from typing import Dict + +from zitadel_client.auth.authenticator import Authenticator +from zitadel_client.utils.url_util import URLUtil + + +class PersonalAccessTokenAuthenticator(Authenticator): + """ + Personal Access Token Authenticator. + + Uses a static personal access token for API authentication. + """ + + def __init__(self, host: str, token: str): + super().__init__(URLUtil.build_hostname(host)) + self.token = token + + def get_auth_headers(self) -> Dict[str, str]: + """ + Returns the authentication headers using the personal access token. + + :return: A dictionary containing the 'Authorization' header. + """ + return {"Authorization": "Bearer " + self.token} diff --git a/zitadel_client/auth/web_token_authenticator.py b/zitadel_client/auth/web_token_authenticator.py new file mode 100644 index 00000000..2d53dc54 --- /dev/null +++ b/zitadel_client/auth/web_token_authenticator.py @@ -0,0 +1,172 @@ +import json +from datetime import datetime, timedelta, timezone +from typing import Set + +from authlib.integrations.requests_client import OAuth2Session +from authlib.jose import jwt, JoseError + +from zitadel_client.auth.authenticator import OAuthAuthenticatorBuilder +from zitadel_client.auth.oauth_authenticator import OAuthAuthenticator +from zitadel_client.auth.open_id import OpenId + + +class WebTokenAuthenticator(OAuthAuthenticator): + """ + OAuth authenticator implementing the JWT bearer flow. + + This implementation builds a JWT assertion dynamically in get_grant(). + """ + + def __init__(self, open_id: OpenId, auth_scopes: Set[str], + jwt_issuer: str, jwt_subject: str, jwt_audience: str, + private_key: str, jwt_lifetime: timedelta = timedelta(hours=1), jwt_algorithm: str = "RS256", + key_id: str = None): + """ + Constructs a JWTAuthenticator. + + :param open_id: The base URL for the OAuth provider. + :param auth_scopes: The scope(s) for the token request. + :param jwt_issuer: The JWT issuer. + :param jwt_subject: The JWT subject. + :param jwt_audience: The JWT audience. + :param private_key: The private key used to sign the JWT. + :param jwt_lifetime: Lifetime of the JWT in seconds. + :param jwt_algorithm: The JWT signing algorithm (default "RS256"). + """ + super().__init__(open_id, OAuth2Session(scope=" ".join(auth_scopes))) + self.jwt_issuer = jwt_issuer + self.jwt_subject = jwt_subject + self.jwt_audience = jwt_audience + self.private_key = private_key + self.jwt_lifetime = jwt_lifetime + self.jwt_algorithm = jwt_algorithm + self.key_id = key_id + + def get_grant(self) -> dict: + """ + Builds and returns the grant parameters for the JWT bearer flow. + + Dynamically generates a JWT assertion that includes time-sensitive claims. + + :return: A dictionary with the JWT bearer grant parameters. + :raises Exception: If JWT generation fails. + """ + now = datetime.now(timezone.utc) + try: + return { + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "assertion": (jwt.encode({"alg": self.jwt_algorithm, "typ": "JWT", "kid": self.key_id, }, { + "iss": self.jwt_issuer, + "sub": self.jwt_subject, + "aud": self.jwt_audience, + "iat": int(now.timestamp()), + "exp": int((now + self.jwt_lifetime).timestamp()) + }, self.private_key)) + } + except JoseError as e: + raise Exception("Failed to generate JWT assertion: " + str(e)) from e + + @classmethod + def from_json(cls, host: str, json_path: str) -> "WebTokenAuthenticator": + """ + Create a WebTokenAuthenticatorBuilder instance from a JSON configuration file. + + Expected JSON format: + { + "type": "serviceaccount", + "keyId": "", + "key": "", + "userId": "" + } + + :param host: Base URL for the API endpoints. + :param json_path: File path to the JSON configuration file. + :return: A new instance of WebTokenAuthenticator. + :raises Exception: If the file cannot be read, the JSON is invalid, + or required keys are missing. + """ + try: + with open(json_path, "r") as file: + config = json.load(file) + except Exception as e: + raise Exception(f"Unable to read JSON file: {json_path}") from e + + user_id = config.get("userId") + private_key = config.get("key") + key_id = config.get("keyId") + if not user_id or not key_id or not private_key: + raise Exception("Missing required keys 'userId', 'key_id' or 'key' in JSON file.") + + return (WebTokenAuthenticator.builder(host, user_id, private_key)).key_identifier(key_id).build() + + @staticmethod + def builder(host: str, user_id: str, private_key: str) -> "WebTokenAuthenticatorBuilder": + """ + Returns a builder for constructing a JWTAuthenticator. + + :param host: The base URL for the OAuth provider. + :param user_id: The user identifier, used as both the issuer and subject. + :param private_key: The private key used to sign the JWT. + :return: A JWTAuthenticatorBuilder instance. + """ + return WebTokenAuthenticatorBuilder(host, user_id, user_id, host, private_key) + + +class WebTokenAuthenticatorBuilder(OAuthAuthenticatorBuilder): + """ + Builder for JWTAuthenticator. + + Provides a fluent API for configuring and constructing a JWTAuthenticator instance. + """ + + def __init__(self, host: str, jwt_issuer: str, jwt_subject: str, jwt_audience: str, private_key: str): + """ + Initializes the JWTAuthenticatorBuilder with required parameters. + + :param host: The base URL for API endpoints. + :param jwt_issuer: The issuer claim for the JWT. + :param jwt_subject: The subject claim for the JWT. + :param jwt_audience: The audience claim for the JWT. + :param private_key: The PEM-formatted private key used for signing the JWT. + """ + super().__init__(host) + self.jwt_issuer = jwt_issuer + self.jwt_subject = jwt_subject + self.jwt_audience = jwt_audience + self.private_key = private_key + self.jwt_lifetime = timedelta(hours=1) + self.key_id = None + + def token_lifetime_seconds(self, seconds: int) -> "WebTokenAuthenticatorBuilder": + """ + Sets the JWT token lifetime in seconds. + + :param seconds: Lifetime of the JWT in seconds. + :return: The builder instance. + """ + self.jwt_lifetime = timedelta(seconds=seconds) + return self + + def build(self) -> WebTokenAuthenticator: + """ + Builds and returns a new JWTAuthenticator instance using the configured parameters. + + This method inlines the JWT assertion generation logic and passes all required + configuration to the JWTAuthenticator constructor. + + :return: A new JWTAuthenticator instance. + """ + return WebTokenAuthenticator( + open_id=self.open_id, + auth_scopes=self.auth_scopes, + jwt_issuer=self.jwt_issuer, + jwt_subject=self.jwt_subject, + jwt_audience=self.jwt_audience, + private_key=self.private_key, + jwt_lifetime=self.jwt_lifetime, + key_id=self.key_id + ) + + def key_identifier(self, key_id): + self.key_id = key_id + return self diff --git a/zitadel_client/configuration.py b/zitadel_client/configuration.py index dc8abb1f..ba532dd5 100644 --- a/zitadel_client/configuration.py +++ b/zitadel_client/configuration.py @@ -1,581 +1,197 @@ -# coding: utf-8 - -""" - Zitadel SDK - - The Zitadel SDK is a convenience wrapper around the Zitadel APIs to assist you in integrating with your Zitadel environment. This SDK enables you to handle resources, settings, and configurations within the Zitadel platform. - - The version of the OpenAPI document: 1.0.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - import copy import http.client as httplib import logging -from logging import FileHandler import multiprocessing import sys -from typing import Any, ClassVar, Dict, List, Literal, Optional, TypedDict, Union -from typing_extensions import NotRequired, Self - -import urllib3 - - -JSON_SCHEMA_VALIDATION_KEYWORDS = { - 'multipleOf', 'maximum', 'exclusiveMaximum', - 'minimum', 'exclusiveMinimum', 'maxLength', - 'minLength', 'pattern', 'maxItems', 'minItems' -} - -ServerVariablesT = Dict[str, str] - -GenericAuthSetting = TypedDict( - "GenericAuthSetting", - { - "type": str, - "in": str, - "key": str, - "value": str, - }, -) - - -OAuth2AuthSetting = TypedDict( - "OAuth2AuthSetting", - { - "type": Literal["oauth2"], - "in": Literal["header"], - "key": Literal["Authorization"], - "value": str, - }, -) - - -APIKeyAuthSetting = TypedDict( - "APIKeyAuthSetting", - { - "type": Literal["api_key"], - "in": str, - "key": str, - "value": Optional[str], - }, -) - - -BasicAuthSetting = TypedDict( - "BasicAuthSetting", - { - "type": Literal["basic"], - "in": Literal["header"], - "key": Literal["Authorization"], - "value": Optional[str], - }, -) - - -BearerFormatAuthSetting = TypedDict( - "BearerFormatAuthSetting", - { - "type": Literal["bearer"], - "in": Literal["header"], - "format": Literal["JWT"], - "key": Literal["Authorization"], - "value": str, - }, -) - - -BearerAuthSetting = TypedDict( - "BearerAuthSetting", - { - "type": Literal["bearer"], - "in": Literal["header"], - "key": Literal["Authorization"], - "value": str, - }, -) - - -HTTPSignatureAuthSetting = TypedDict( - "HTTPSignatureAuthSetting", - { - "type": Literal["http-signature"], - "in": Literal["header"], - "key": Literal["Authorization"], - "value": None, - }, -) - - -AuthSettings = TypedDict( - "AuthSettings", - { - "zitadelAccessToken": BearerAuthSetting, - }, - total=False, -) - - -class HostSettingVariable(TypedDict): - description: str - default_value: str - enum_values: List[str] +from logging import FileHandler +from typing import Any, Dict, Optional, Union +from typing_extensions import Self -class HostSetting(TypedDict): - url: str - description: str - variables: NotRequired[Dict[str, HostSettingVariable]] +from zitadel_client.auth.authenticator import Authenticator class Configuration: - """This class contains various settings of the API client. - - :param host: Base url. - :param ignore_operation_servers - Boolean to ignore operation servers for the API client. - Config will use `host` as the base url regardless of the operation servers. - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer). - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication. - :param password: Password for HTTP basic authentication. - :param access_token: Access token. - :param server_index: Index to servers configuration. - :param server_variables: Mapping with string values to replace variables in - templated server configuration. The validation of enums is performed for - variables with defined enum values before. - :param server_operation_index: Mapping from operation ID to an index to server - configuration. - :param server_operation_variables: Mapping from operation ID to a mapping with - string values to replace variables in templated server configuration. - The validation of enums is performed for variables with defined enum - values before. - :param ssl_ca_cert: str - the path to a file of concatenated CA certificates - in PEM format. - :param retries: Number of retries for API requests. - :param ca_cert_data: verify the peer using concatenated CA certificate data - in PEM (str) or DER (bytes) format. - - :Example: + """This class contains various settings of the API client. + """ + + def __init__( + self, + authenticator: Authenticator, + ssl_ca_cert: Optional[str] = None, + retries: Optional[int] = None, + ca_cert_data: Optional[Union[str, bytes]] = None, + *, + debug: Optional[bool] = None, + ) -> None: + """Constructor + """ + self.authenticator = authenticator + self.api_key_prefix = {} + self.refresh_api_key_hook = None + self.logger = {"package_logger": logging.getLogger("zitadel_client"), + "urllib3_logger": logging.getLogger("urllib3")} + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + self.logger_stream_handler = None + self.logger_file_handler: Optional[FileHandler] = None + self.logger_file = None + if debug is not None: + self.debug = debug + else: + self.__debug = False + self.verify_ssl = True + self.ssl_ca_cert = ssl_ca_cert + self.ca_cert_data = ca_cert_data + self.cert_file = None + self.key_file = None + self.assert_hostname = None + self.tls_server_name = None + + self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. """ - _default: ClassVar[Optional[Self]] = None - - def __init__( - self, - host: Optional[str]=None, - api_key: Optional[Dict[str, str]]=None, - api_key_prefix: Optional[Dict[str, str]]=None, - username: Optional[str]=None, - password: Optional[str]=None, - access_token: Optional[str]=None, - server_index: Optional[int]=None, - server_variables: Optional[ServerVariablesT]=None, - server_operation_index: Optional[Dict[int, int]]=None, - server_operation_variables: Optional[Dict[int, ServerVariablesT]]=None, - ignore_operation_servers: bool=False, - ssl_ca_cert: Optional[str]=None, - retries: Optional[int] = None, - ca_cert_data: Optional[Union[str, bytes]] = None, - *, - debug: Optional[bool] = None, - ) -> None: - """Constructor - """ - self._base_path = "http://localhost:8080" if host is None else host - """Default Base url - """ - self.server_index = 0 if server_index is None and host is None else server_index - self.server_operation_index = server_operation_index or {} - """Default server index - """ - self.server_variables = server_variables or {} - self.server_operation_variables = server_operation_variables or {} - """Default server variables - """ - self.ignore_operation_servers = ignore_operation_servers - """Ignore operation servers - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - self.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.access_token = access_token - """Access token - """ - self.logger = {} - """Logging Settings - """ - self.logger["package_logger"] = logging.getLogger("zitadel_client") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - """Log format - """ - self.logger_stream_handler = None - """Log stream handler - """ - self.logger_file_handler: Optional[FileHandler] = None - """Log file handler - """ - self.logger_file = None - """Debug file location - """ - if debug is not None: - self.debug = debug - else: - self.__debug = False - """Debug switch - """ - - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = ssl_ca_cert - """Set this to customize the certificate file to verify the peer. - """ - self.ca_cert_data = ca_cert_data - """Set this to verify the peer using PEM (str) or DER (bytes) - certificate data. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - self.tls_server_name = None - """SSL/TLS Server Name Indication (SNI) - Set this to the SNI value expected by the server. - """ - - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - """urllib3 connection pool's maximum number of connections saved - per pool. urllib3 uses 1 connection as default value, but this is - not the best value when you are making a lot of possibly parallel - requests to the same host, which is often the case here. - cpu_count * 5 is used as default value to increase performance. - """ - - self.proxy: Optional[str] = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = '' - """Safe chars for path_param - """ - self.retries = retries - """Adding retries to override urllib3 default value 3 - """ - # Enable client side validation - self.client_side_validation = True - - self.socket_options = None - """Options to pass down to the underlying urllib3 socket - """ - - self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" - """datetime format - """ - - self.date_format = "%Y-%m-%d" - """date format - """ - - def __deepcopy__(self, memo: Dict[int, Any]) -> Self: - cls = self.__class__ - result = cls.__new__(cls) - memo[id(self)] = result - for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler'): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result - - def __setattr__(self, name: str, value: Any) -> None: - object.__setattr__(self, name, value) - - @classmethod - def set_default(cls, default: Optional[Self]) -> None: - """Set default instance of configuration. - - It stores default configuration, which can be - returned by get_default_copy method. - - :param default: object of Configuration - """ - cls._default = default - - @classmethod - def get_default_copy(cls) -> Self: - """Deprecated. Please use `get_default` instead. - - Deprecated. Please use `get_default` instead. - - :return: The configuration object. - """ - return cls.get_default() - - @classmethod - def get_default(cls) -> Self: - """Return the default configuration. - - This method returns newly created, based on default constructor, - object of Configuration class or returns a copy of default - configuration. - - :return: The configuration object. - """ - if cls._default is None: - cls._default = cls() - return cls._default - - @property - def logger_file(self) -> Optional[str]: - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value: Optional[str]) -> None: - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in self.logger.items(): - logger.addHandler(self.logger_file_handler) - - @property - def debug(self) -> bool: - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value: bool) -> None: - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in self.logger.items(): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in self.logger.items(): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self) -> str: - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value: str) -> None: - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier: str, alias: Optional[str]=None) -> Optional[str]: - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :param alias: The alternative identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - return None - - def get_basic_auth_token(self) -> Optional[str]: - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') - - def auth_settings(self)-> AuthSettings: - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - auth: AuthSettings = {} - if self.access_token is not None: - auth['zitadelAccessToken'] = { - 'type': 'bearer', - 'in': 'header', - 'key': 'Authorization', - 'value': 'Bearer ' + self.access_token - } - return auth - - def to_debug_report(self) -> str: - """Gets the essential information for debugging. + self.proxy: Optional[str] = None + self.proxy_headers = None + self.safe_chars_for_path_param = '' + self.retries = retries + # Enable client side validation + self.client_side_validation = True + self.socket_options = None + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + self.date_format = "%Y-%m-%d" + + def __deepcopy__(self, memo: Dict[int, Any]) -> Self: + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name: str, value: Any) -> None: + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default: Optional[Self]) -> None: + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default - :return: The report for debugging. - """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: 1.0.0\n"\ - "SDK Package Version: 0.0.1".\ - format(env=sys.platform, pyversion=sys.version) + @property + def logger_file(self) -> Optional[str]: + """The logger file. - def get_host_settings(self) -> List[HostSetting]: - """Gets an array of host settings + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. - :return: An array of host settings - """ - return [ - { - 'url': "http://localhost:8080", - 'description': "No description provided", - } - ] + :param value: The logger_file path. + :type: str + """ + return self.__logger_file - def get_host_from_settings( - self, - index: Optional[int], - variables: Optional[ServerVariablesT]=None, - servers: Optional[List[HostSetting]]=None, - ) -> str: - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :param servers: an array of host settings or None - :return: URL based on host settings - """ - if index is None: - return self._base_path + @logger_file.setter + def logger_file(self, value: Optional[str]) -> None: + """The logger file. - variables = {} if variables is None else variables - servers = self.get_host_settings() if servers is None else servers + If the logger_file is None, then add stream handler and remove file + handler. Otherwise, add file handler and remove stream handler. - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: + # If set logging file, + # then add file handler and remove stream handler. + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) + for _, logger in self.logger.items(): + logger.addHandler(self.logger_file_handler) + + @property + def debug(self) -> bool: + """Debug status + + :param value: The debug status, True or False. + :type: bool + """ + return self.__debug - url = server['url'] + @debug.setter + def debug(self, value: bool) -> None: + """Debug status - # go through variables and replace placeholders - for variable_name, variable in server.get('variables', {}).items(): - used_value = variables.get( - variable_name, variable['default_value']) + :param value: The debug status, True or False. + :type: bool + """ + self.__debug = value + if self.__debug: + # if debug status is True, turn on debug logging + for _, logger in self.logger.items(): + logger.setLevel(logging.DEBUG) + # turn on httplib debug + httplib.HTTPConnection.debuglevel = 1 + else: + # if debug status is False, turn off debug logging, + # setting log level to default `logging.WARNING` + for _, logger in self.logger.items(): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logger_format(self) -> str: + """The logger format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + return self.__logger_format - if 'enum_values' in variable \ - and used_value not in variable['enum_values']: - raise ValueError( - "The variable `{0}` in the host URL has invalid value " - "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) + @logger_format.setter + def logger_format(self, value: str) -> None: + """The logger format. - url = url.replace("{" + variable_name + "}", used_value) + The logger_formatter will be updated when sets logger_format. - return url + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) - @property - def host(self) -> str: - """Return generated host.""" - return self.get_host_from_settings(self.server_index, variables=self.server_variables) + @staticmethod + def to_debug_report() -> str: + """Gets the essential information for debugging. - @host.setter - def host(self, value: str) -> None: - """Fix base path.""" - self._base_path = value - self.server_index = None + :return: The report for debugging. + """ + return "Python SDK Debug Report:\n" \ + "OS: {env}\n" \ + "Python Version: {pyversion}\n" \ + "Version of the API: 1.0.0\n" \ + "SDK Package Version: 0.0.1". \ + format(env=sys.platform, pyversion=sys.version) + + @property + def host(self) -> str: + """Return generated host.""" + return self.authenticator.get_host() diff --git a/zitadel_client/exceptions.py b/zitadel_client/exceptions.py index 3b49b898..9e517e33 100644 --- a/zitadel_client/exceptions.py +++ b/zitadel_client/exceptions.py @@ -1,216 +1,205 @@ -# coding: utf-8 - -""" - Zitadel SDK - - The Zitadel SDK is a convenience wrapper around the Zitadel APIs to assist you in integrating with your Zitadel environment. This SDK enables you to handle resources, settings, and configurations within the Zitadel platform. - - The version of the OpenAPI document: 1.0.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - from typing import Any, Optional + from typing_extensions import Self + class OpenApiException(Exception): - """The base exception class for all OpenAPIExceptions""" + """The base exception class for all OpenAPIExceptions""" class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, - key_type=None) -> None: - """ Raises an exception for TypeErrors - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list): a list of keys an indices to get to the - current_item - None if unset - valid_classes (tuple): the primitive classes that current item - should be an instance of - None if unset - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item None if unset - """ - self.path_to_item = path_to_item - self.valid_classes = valid_classes - self.key_type = key_type - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiTypeError, self).__init__(full_msg) + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) class ApiValueError(OpenApiException, ValueError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Args: - msg (str): the exception message + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message - Keyword Args: - path_to_item (list) the path to the exception in the - received_data dict. None if unset - """ + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiValueError, self).__init__(full_msg) + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) class ApiAttributeError(OpenApiException, AttributeError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Raised when an attribute reference or assignment fails. + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. - Args: - msg (str): the exception message + Args: + msg (str): the exception message - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiAttributeError, self).__init__(full_msg) + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) class ApiKeyError(OpenApiException, KeyError): - def __init__(self, msg, path_to_item=None) -> None: - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiKeyError, self).__init__(full_msg) + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) class ApiException(OpenApiException): - def __init__( - self, - status=None, - reason=None, - http_resp=None, - *, - body: Optional[str] = None, - data: Optional[Any] = None, - ) -> None: - self.status = status - self.reason = reason - self.body = body - self.data = data - self.headers = None - - if http_resp: - if self.status is None: - self.status = http_resp.status - if self.reason is None: - self.reason = http_resp.reason - if self.body is None: - try: - self.body = http_resp.data.decode('utf-8') - except Exception: - pass - self.headers = http_resp.getheaders() - - @classmethod - def from_response( - cls, - *, - http_resp, - body: Optional[str], - data: Optional[Any], - ) -> Self: - if http_resp.status == 400: - raise BadRequestException(http_resp=http_resp, body=body, data=data) - - if http_resp.status == 401: - raise UnauthorizedException(http_resp=http_resp, body=body, data=data) - - if http_resp.status == 403: - raise ForbiddenException(http_resp=http_resp, body=body, data=data) - - if http_resp.status == 404: - raise NotFoundException(http_resp=http_resp, body=body, data=data) - - # Added new conditions for 409 and 422 - if http_resp.status == 409: - raise ConflictException(http_resp=http_resp, body=body, data=data) - - if http_resp.status == 422: - raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data) - - if 500 <= http_resp.status <= 599: - raise ServiceException(http_resp=http_resp, body=body, data=data) - raise ApiException(http_resp=http_resp, body=body, data=data) - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) - - if self.data or self.body: - error_message += "HTTP response body: {0}\n".format(self.data or self.body) - - return error_message + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + + if http_resp: + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass + self.headers = http_resp.getheaders() + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + # Added new conditions for 409 and 422 + if http_resp.status == 409: + raise ConflictException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 422: + raise UnprocessableEntityException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n" \ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) + + return error_message class BadRequestException(ApiException): - pass + pass class NotFoundException(ApiException): - pass + pass class UnauthorizedException(ApiException): - pass + pass class ForbiddenException(ApiException): - pass + pass class ServiceException(ApiException): - pass + pass class ConflictException(ApiException): - """Exception for HTTP 409 Conflict.""" - pass + """Exception for HTTP 409 Conflict.""" + pass class UnprocessableEntityException(ApiException): - """Exception for HTTP 422 Unprocessable Entity.""" - pass + """Exception for HTTP 422 Unprocessable Entity.""" + pass def render_path(path_to_item): - """Returns a string representation of a path""" - result = "" - for pth in path_to_item: - if isinstance(pth, int): - result += "[{0}]".format(pth) - else: - result += "['{0}']".format(pth) - return result + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/zitadel_client/rest.py b/zitadel_client/rest.py index f73b85d8..0522f9bd 100644 --- a/zitadel_client/rest.py +++ b/zitadel_client/rest.py @@ -1,17 +1,3 @@ -# coding: utf-8 - -""" - Zitadel SDK - - The Zitadel SDK is a convenience wrapper around the Zitadel APIs to assist you in integrating with your Zitadel environment. This SDK enables you to handle resources, settings, and configurations within the Zitadel platform. - - The version of the OpenAPI document: 1.0.0 - Generated by OpenAPI Generator (https://openapi-generator.tech) - - Do not edit the class manually. -""" # noqa: E501 - - import io import json import re @@ -26,233 +12,232 @@ def is_socks_proxy_url(url): - if url is None: - return False - split_section = url.split("://") - if len(split_section) < 2: - return False - else: - return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES class RESTResponse(io.IOBase): - def __init__(self, resp) -> None: - self.response = resp - self.status = resp.status - self.reason = resp.reason - self.data = None + def __init__(self, resp) -> None: + self.response = resp + self.status = resp.status + self.reason = resp.reason + self.data = None - def read(self): - if self.data is None: - self.data = self.response.data - return self.data + def read(self): + if self.data is None: + self.data = self.response.data + return self.data - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.response.headers + def getheaders(self): + """Returns a dictionary of the response headers.""" + return self.response.headers - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.response.headers.get(name, default) + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration) -> None: - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - pool_args = { - "cert_reqs": cert_reqs, - "ca_certs": configuration.ssl_ca_cert, - "cert_file": configuration.cert_file, - "key_file": configuration.key_file, - "ca_cert_data": configuration.ca_cert_data, - } - if configuration.assert_hostname is not None: - pool_args['assert_hostname'] = ( - configuration.assert_hostname - ) - - if configuration.retries is not None: - pool_args['retries'] = configuration.retries - - if configuration.tls_server_name: - pool_args['server_hostname'] = configuration.tls_server_name - + def __init__(self, configuration) -> None: + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 + # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - if configuration.socket_options is not None: - pool_args['socket_options'] = configuration.socket_options - - if configuration.connection_pool_maxsize is not None: - pool_args['maxsize'] = configuration.connection_pool_maxsize - - # https pool manager - self.pool_manager: urllib3.PoolManager - - if configuration.proxy: - if is_socks_proxy_url(configuration.proxy): - from urllib3.contrib.socks import SOCKSProxyManager - pool_args["proxy_url"] = configuration.proxy - pool_args["headers"] = configuration.proxy_headers - self.pool_manager = SOCKSProxyManager(**pool_args) - else: - pool_args["proxy_url"] = configuration.proxy - pool_args["proxy_headers"] = configuration.proxy_headers - self.pool_manager = urllib3.ProxyManager(**pool_args) + # cert_reqs + if configuration.verify_ssl: + cert_reqs = ssl.CERT_REQUIRED + else: + cert_reqs = ssl.CERT_NONE + + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + "ca_cert_data": configuration.ca_cert_data, + } + if configuration.assert_hostname is not None: + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) + + if configuration.retries is not None: + pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + pool_args['server_hostname'] = configuration.tls_server_name + + if configuration.socket_options is not None: + pool_args['socket_options'] = configuration.socket_options + + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize + + # https pool manager + self.pool_manager: urllib3.PoolManager + + if configuration.proxy: + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) + else: + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): + """Perform requests. + + :param method: http request method + :param url: http request url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, float)): + timeout = urllib3.Timeout(total=_request_timeout) + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): + timeout = urllib3.Timeout( + connect=_request_timeout[0], + read=_request_timeout[1] + ) + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None + if body is not None: + request_body = json.dumps(body) + r = self.pool_manager.request( + method, + url, + body=request_body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=False, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by urllib3 will be + # overwritten. + del headers['Content-Type'] + # Ensures that dict objects are serialized + post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a, b) for a, b in post_params] + r = self.pool_manager.request( + method, + url, + fields=post_params, + encode_multipart=True, + timeout=timeout, + headers=headers, + preload_content=False + ) + # Pass a `string` parameter directly in the body to support + # other content types than JSON when `body` argument is + # provided in serialized form. + elif isinstance(body, str) or isinstance(body, bytes): + r = self.pool_manager.request( + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, + body=request_body, + preload_content=False, + timeout=timeout, + headers=headers) else: - self.pool_manager = urllib3.PoolManager(**pool_args) - - def request( - self, - method, - url, - headers=None, - body=None, - post_params=None, - _request_timeout=None - ): - """Perform requests. - - :param method: http request method - :param url: http request url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in [ - 'GET', - 'HEAD', - 'DELETE', - 'POST', - 'PUT', - 'PATCH', - 'OPTIONS' - ] - - if post_params and body: - raise ApiValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int, float)): - timeout = urllib3.Timeout(total=_request_timeout) - elif ( - isinstance(_request_timeout, tuple) - and len(_request_timeout) == 2 - ): - timeout = urllib3.Timeout( - connect=_request_timeout[0], - read=_request_timeout[1] - ) - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - - # no content type provided or payload is json - content_type = headers.get('Content-Type') - if ( - not content_type - or re.search('json', content_type, re.IGNORECASE) - ): - request_body = None - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, - url, - body=request_body, - timeout=timeout, - headers=headers, - preload_content=False - ) - elif content_type == 'application/x-www-form-urlencoded': - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=False, - timeout=timeout, - headers=headers, - preload_content=False - ) - elif content_type == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers['Content-Type'] - # Ensures that dict objects are serialized - post_params = [(a, json.dumps(b)) if isinstance(b, dict) else (a,b) for a, b in post_params] - r = self.pool_manager.request( - method, - url, - fields=post_params, - encode_multipart=True, - timeout=timeout, - headers=headers, - preload_content=False - ) - # Pass a `string` parameter directly in the body to support - # other content types than JSON when `body` argument is - # provided in serialized form. - elif isinstance(body, str) or isinstance(body, bytes): - r = self.pool_manager.request( - method, - url, - body=body, - timeout=timeout, - headers=headers, - preload_content=False - ) - elif headers['Content-Type'].startswith('text/') and isinstance(body, bool): - request_body = "true" if body else "false" - r = self.pool_manager.request( - method, - url, - body=request_body, - preload_content=False, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided arguments. Please check that your arguments match declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request( - method, - url, - fields={}, - timeout=timeout, - headers=headers, - preload_content=False - ) - except urllib3.exceptions.SSLError as e: - msg = "\n".join([type(e).__name__, str(e)]) - raise ApiException(status=0, reason=msg) - - return RESTResponse(r) + raise ApiException(status=0, reason=msg) + # For `GET`, `HEAD` + else: + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) + except urllib3.exceptions.SSLError as e: + msg = "\n".join([type(e).__name__, str(e)]) + raise ApiException(status=0, reason=msg) + + return RESTResponse(r) diff --git a/zitadel_client/utils/__init__.py b/zitadel_client/utils/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/zitadel_client/utils/url_util.py b/zitadel_client/utils/url_util.py new file mode 100644 index 00000000..df4b63d6 --- /dev/null +++ b/zitadel_client/utils/url_util.py @@ -0,0 +1,12 @@ +class URLUtil: + @staticmethod + def build_hostname(host: str) -> str: + """ + Processes the host string. This might include cleaning up the input, + adding a protocol, or other logic similar to your Java URLUtil.buildHostname method. + """ + # For example, trim whitespace and ensure the host starts with 'https://' + host = host.strip() + if not host.startswith("http://") and not host.startswith("https://"): + host = "https://" + host + return host diff --git a/zitadel_client/zitadel.py b/zitadel_client/zitadel.py index 5c429992..1d11b055 100644 --- a/zitadel_client/zitadel.py +++ b/zitadel_client/zitadel.py @@ -3,40 +3,79 @@ from zitadel_client.api.oidc_service_api import OIDCServiceApi from zitadel_client.api.organization_service_api import OrganizationServiceApi from zitadel_client.api.session_service_api import SessionServiceApi -from zitadel_client.api.settings_api import SettingsApi from zitadel_client.api.settings_service_api import SettingsServiceApi from zitadel_client.api.user_service_api import UserServiceApi -from zitadel_client.configuration import Configuration from zitadel_client.api_client import ApiClient +from zitadel_client.auth.authenticator import Authenticator +from zitadel_client.configuration import Configuration + class Zitadel: - def __init__(self, host: str, access_token: str, mutate_config: callable = None): - """ - Initialize the Zitadel SDK with the provided host and access token. - - Parameters: - - host: The base URL of the Zitadel API. - - access_token: The access token for authenticating API requests. - """ - self.configuration = Configuration( - host = host, - access_token = access_token - ) - - if mutate_config: - mutate_config(self.configuration) - - self.client = ApiClient(configuration = self.configuration) - self.features = FeatureServiceApi(self.client) - self.idps = IdentityProviderServiceApi(self.client) - self.oidc = OIDCServiceApi(self.client) - self.organizations = OrganizationServiceApi(self.client) - self.sessions = SessionServiceApi(self.client) - self.settings = SettingsServiceApi(self.client) - self.users = UserServiceApi(self.client) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - pass + """ + Main entry point for the Zitadel SDK. + + This class initializes and configures the SDK with the provided authentication strategy. + It sets up service APIs for interacting with various Zitadel features such as identity providers, + organizations, sessions, settings, users, and more. + + Attributes: + configuration (Configuration): The configuration instance containing authentication and endpoint details. + client (ApiClient): The API client used for making HTTP requests to the Zitadel API. + features (FeatureServiceApi): Service API for feature management. + idps (IdentityProviderServiceApi): Service API for identity provider operations. + oidc (OIDCServiceApi): Service API for OIDC-related operations. + organizations (OrganizationServiceApi): Service API for organization-related operations. + sessions (SessionServiceApi): Service API for session management. + settings (SettingsServiceApi): Service API for settings management. + users (UserServiceApi): Service API for user management. + """ + + def __init__(self, authenticator: Authenticator, mutate_config: callable = None): + """ + Initialize the Zitadel SDK. + + This constructor creates a configuration instance using the provided authenticator. + Optionally, the configuration can be modified via the `mutate_config` callback function. + It then instantiates the underlying API client and initializes various service APIs. + + Args: + authenticator (Authenticator): The authentication strategy to be used. + mutate_config (callable, optional): A callback function that receives the configuration + instance for any additional modifications before the API client is created. + Defaults to None. + """ + self.configuration = Configuration(authenticator) + + if mutate_config: + mutate_config(self.configuration) + + client = ApiClient(configuration=self.configuration) + self.features = FeatureServiceApi(client) + self.idps = IdentityProviderServiceApi(client) + self.oidc = OIDCServiceApi(client) + self.organizations = OrganizationServiceApi(client) + self.sessions = SessionServiceApi(client) + self.settings = SettingsServiceApi(client) + self.users = UserServiceApi(client) + + def __enter__(self): + """ + Enter the runtime context related to the Zitadel instance. + + Returns: + Zitadel: The current instance. + """ + return self + + def __exit__(self, exc_type, exc_value, traceback): + """ + Exit the runtime context. + + This method can be used to perform cleanup actions. Currently, it does nothing. + + Args: + exc_type: The exception type, if an exception occurred. + exc_value: The exception value, if an exception occurred. + traceback: The traceback of the exception, if an exception occurred. + """ + pass