anaplan-sdk 0.4.3a1__tar.gz → 0.4.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/PKG-INFO +5 -2
  2. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/README.md +2 -1
  3. anaplan_sdk-0.4.4/anaplan_sdk/__init__.py +15 -0
  4. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_async_clients/_bulk.py +35 -79
  5. anaplan_sdk-0.4.4/anaplan_sdk/_auth.py +363 -0
  6. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_clients/_bulk.py +36 -70
  7. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_oauth.py +91 -32
  8. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/models/_bulk.py +2 -2
  9. anaplan_sdk-0.4.4/docs/guides/authentication.md +366 -0
  10. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/transactional.md +2 -2
  11. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/pyproject.toml +103 -101
  12. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/uv.lock +1294 -1162
  13. anaplan_sdk-0.4.3a1/anaplan_sdk/__init__.py +0 -5
  14. anaplan_sdk-0.4.3a1/anaplan_sdk/_auth.py +0 -324
  15. anaplan_sdk-0.4.3a1/docs/guides/authentication.md +0 -327
  16. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/.github/dependabot.yml +0 -0
  17. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/.github/workflows/docs.yml +0 -0
  18. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/.github/workflows/lint.yml +0 -0
  19. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/.github/workflows/tests.yml +0 -0
  20. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/.gitignore +0 -0
  21. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/.pre-commit-config.yaml +0 -0
  22. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/LICENSE +0 -0
  23. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_async_clients/__init__.py +0 -0
  24. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_async_clients/_alm.py +0 -0
  25. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_async_clients/_audit.py +0 -0
  26. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_async_clients/_cloud_works.py +0 -0
  27. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_async_clients/_cw_flow.py +0 -0
  28. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_async_clients/_transactional.py +0 -0
  29. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_base.py +0 -0
  30. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_clients/__init__.py +0 -0
  31. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_clients/_alm.py +0 -0
  32. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_clients/_audit.py +0 -0
  33. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_clients/_cloud_works.py +0 -0
  34. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_clients/_cw_flow.py +0 -0
  35. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/_clients/_transactional.py +0 -0
  36. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/exceptions.py +0 -0
  37. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/models/__init__.py +0 -0
  38. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/models/_alm.py +0 -0
  39. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/models/_base.py +0 -0
  40. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/models/_transactional.py +0 -0
  41. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/models/cloud_works.py +0 -0
  42. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/anaplan_sdk/models/flows.py +0 -0
  43. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/anaplan_explained.md +0 -0
  44. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/async/async_alm_client.md +0 -0
  45. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/async/async_audit_client.md +0 -0
  46. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/async/async_client.md +0 -0
  47. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/async/async_cw_client.md +0 -0
  48. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/async/async_flows_client.md +0 -0
  49. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/async/async_oauth_client.md +0 -0
  50. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/async/async_transactional_client.md +0 -0
  51. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/exceptions.md +0 -0
  52. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/models/alm.md +0 -0
  53. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/models/bulk.md +0 -0
  54. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/models/cloud_works.md +0 -0
  55. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/models/flows.md +0 -0
  56. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/models/transactional.md +0 -0
  57. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/sync/sync_alm_client.md +0 -0
  58. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/sync/sync_audit_client.md +0 -0
  59. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/sync/sync_client.md +0 -0
  60. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/sync/sync_cw_client.md +0 -0
  61. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/sync/sync_flows_client.md +0 -0
  62. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/sync/sync_oauth_client.md +0 -0
  63. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/api/sync/sync_transactional_client.md +0 -0
  64. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/assets/overview.html +0 -0
  65. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/css/styles.css +0 -0
  66. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/alm.md +0 -0
  67. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/audit.md +0 -0
  68. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/bulk.md +0 -0
  69. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/bulk_vs_transactional.md +0 -0
  70. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/cloud_works.md +0 -0
  71. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/index.md +0 -0
  72. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/logging.md +0 -0
  73. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/guides/multiple_models.md +0 -0
  74. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/img/anaplan-sdk.webp +0 -0
  75. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/index.md +0 -0
  76. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/installation.md +0 -0
  77. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/js/assets/hljs.js +0 -0
  78. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/js/assets/hljs.min.js +0 -0
  79. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/js/assets/python.js +0 -0
  80. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/js/assets/python.min.js +0 -0
  81. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/js/highlight.js +0 -0
  82. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/js/highlight.min.js +0 -0
  83. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/docs/quickstart.md +0 -0
  84. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/mkdocs.yml +0 -0
  85. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/async/conftest.py +0 -0
  86. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/async/test_async_alm_client.py +0 -0
  87. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/async/test_async_audit_client.py +0 -0
  88. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/async/test_async_client.py +0 -0
  89. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/async/test_async_cloud_works_client.py +0 -0
  90. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/async/test_async_flows_client.py +0 -0
  91. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/async/test_async_transactional_client.py +0 -0
  92. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/conftest.py +0 -0
  93. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/sync/conftest.py +0 -0
  94. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/sync/test_alm_client.py +0 -0
  95. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/sync/test_audit_client.py +0 -0
  96. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/sync/test_client.py +0 -0
  97. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/sync/test_cloud_works_client.py +0 -0
  98. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/sync/test_flows_client.py +0 -0
  99. {anaplan_sdk-0.4.3a1 → anaplan_sdk-0.4.4}/tests/sync/test_transactional_client.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: anaplan-sdk
3
- Version: 0.4.3a1
3
+ Version: 0.4.4
4
4
  Summary: Streamlined Python Interface for Anaplan
5
5
  Project-URL: Homepage, https://vinzenzklass.github.io/anaplan-sdk/
6
6
  Project-URL: Repository, https://github.com/VinzenzKlass/anaplan-sdk
@@ -14,6 +14,8 @@ Requires-Dist: httpx<1.0.0,>=0.27.0
14
14
  Requires-Dist: pydantic<3.0.0,>=2.7.2
15
15
  Provides-Extra: cert
16
16
  Requires-Dist: cryptography<46.0.0,>=42.0.7; extra == 'cert'
17
+ Provides-Extra: keyring
18
+ Requires-Dist: keyring<26.0.0,>=25.6.0; extra == 'keyring'
17
19
  Provides-Extra: oauth
18
20
  Requires-Dist: oauthlib<4.0.0,>=3.0.0; extra == 'oauth'
19
21
  Description-Content-Type: text/markdown
@@ -58,7 +60,8 @@ abstractions over all Anaplan APIs, allowing you to focus on business requiremen
58
60
 
59
61
  ## Getting Started
60
62
 
61
- Head over to the [Quick Start](quickstart.md) for basic usage instructions and examples.
63
+ Head over to the [Quick Start](https://vinzenzklass.github.io/anaplan-sdk/quickstart/) for basic usage instructions and
64
+ examples.
62
65
 
63
66
  ## Contributing
64
67
 
@@ -38,7 +38,8 @@ abstractions over all Anaplan APIs, allowing you to focus on business requiremen
38
38
 
39
39
  ## Getting Started
40
40
 
41
- Head over to the [Quick Start](quickstart.md) for basic usage instructions and examples.
41
+ Head over to the [Quick Start](https://vinzenzklass.github.io/anaplan-sdk/quickstart/) for basic usage instructions and
42
+ examples.
42
43
 
43
44
  ## Contributing
44
45
 
@@ -0,0 +1,15 @@
1
+ from ._async_clients import AsyncClient
2
+ from ._auth import AnaplanLocalOAuth, AnaplanRefreshTokenAuth
3
+ from ._clients import Client
4
+ from ._oauth import AsyncOauth, Oauth
5
+
6
+ __all__ = [
7
+ "AsyncClient",
8
+ "Client",
9
+ "AnaplanLocalOAuth",
10
+ "AnaplanRefreshTokenAuth",
11
+ "AsyncOauth",
12
+ "Oauth",
13
+ "models",
14
+ "exceptions",
15
+ ]
@@ -6,7 +6,7 @@ from typing import AsyncIterator, Iterator
6
6
  import httpx
7
7
  from typing_extensions import Self
8
8
 
9
- from anaplan_sdk._auth import AuthCodeCallback, AuthTokenRefreshCallback, _create_auth
9
+ from anaplan_sdk._auth import _create_auth
10
10
  from anaplan_sdk._base import _AsyncBaseClient, action_url
11
11
  from anaplan_sdk.exceptions import AnaplanActionError, InvalidIdentifierException
12
12
  from anaplan_sdk.models import (
@@ -32,14 +32,8 @@ logger = logging.getLogger("anaplan_sdk")
32
32
 
33
33
  class AsyncClient(_AsyncBaseClient):
34
34
  """
35
- An asynchronous Client for pythonic access to the
36
- [Anaplan Integration API v2](https://anaplan.docs.apiary.io/). This Client provides high-level
37
- abstractions over the API, so you can deal with python objects and simple functions rather than
38
- implementation details like http, json, compression, chunking etc.
39
-
40
-
41
- For more information, quick start guides and detailed instructions refer to:
42
- [Anaplan SDK](https://vinzenzklass.github.io/anaplan-sdk).
35
+ Asynchronous Anaplan Client. For guides and examples
36
+ refer to https://vinzenzklass.github.io/anaplan-sdk.
43
37
  """
44
38
 
45
39
  def __init__(
@@ -51,15 +45,8 @@ class AsyncClient(_AsyncBaseClient):
51
45
  certificate: str | bytes | None = None,
52
46
  private_key: str | bytes | None = None,
53
47
  private_key_password: str | bytes | None = None,
54
- client_id: str | None = None,
55
- client_secret: str | None = None,
56
- redirect_uri: str | None = None,
57
- refresh_token: str | None = None,
58
- oauth2_scope: str = "openid profile email offline_access",
59
- on_auth_code: AuthCodeCallback = None,
60
- on_token_refresh: AuthTokenRefreshCallback = None,
61
- oauth_token: dict[str, str] | None = None,
62
48
  token: str | None = None,
49
+ auth: httpx.Auth | None = None,
63
50
  timeout: float | httpx.Timeout = 30,
64
51
  retry_count: int = 2,
65
52
  status_poll_delay: int = 1,
@@ -67,86 +54,55 @@ class AsyncClient(_AsyncBaseClient):
67
54
  allow_file_creation: bool = False,
68
55
  ) -> None:
69
56
  """
70
- An asynchronous Client for pythonic access to the Anaplan Integration API v2:
71
- https://anaplan.docs.apiary.io/. This Client provides high-level abstractions over the API,
72
- so you can deal with python objects and simple functions rather than implementation details
73
- like http, json, compression, chunking etc.
74
-
75
-
76
- For more information, quick start guides and detailed instructions refer to:
77
- https://vinzenzklass.github.io/anaplan-sdk.
57
+ Asynchronous Anaplan Client. For guides and examples
58
+ refer to https://vinzenzklass.github.io/anaplan-sdk.
78
59
 
79
60
  :param workspace_id: The Anaplan workspace Id. You can copy this from the browser URL or
80
- find them using an HTTP Client like Postman, Paw, Insomnia etc.
61
+ find them using an HTTP Client like Postman, Paw, Insomnia etc.
81
62
  :param model_id: The identifier of the model.
82
63
  :param user_email: A valid email registered with the Anaplan Workspace you are attempting
83
- to access. **The associated user must have Workspace Admin privileges**
84
- :param password: Password for the given `user_email`. This is not suitable for production
85
- setups. If you intend to use this in production, acquire a client
86
- certificate as described under: https://help.anaplan.com/procure-ca-certificates-47842267-2cb3-4e38-90bf-13b1632bcd44
87
- :param certificate: The absolute path to the client certificate file or the certificate
88
- itself.
89
- :param private_key: The absolute path to the private key file or the private key itself.
90
- :param private_key_password: The password to access the private key if there is one.
91
- :param client_id: The client Id of the Oauth2 Anaplan Client.
92
- :param client_secret: The client secret for your Oauth2 Anaplan Client.
93
- :param redirect_uri: The redirect URI for your Oauth2 Anaplan Client.
94
- :param refresh_token: If you have a valid refresh token, you can pass it to skip the
95
- interactive authentication code step.
96
- :param oauth2_scope: The scope of the Oauth2 token, if you want to narrow it.
97
- :param on_auth_code: A callback that takes the redirect URI as a single argument and must
98
- return the entire response URI. This will substitute the interactive
99
- authentication code step in the terminal. The callback can be either
100
- a synchronous function or an async coroutine function - both will be
101
- handled appropriately regardless of the execution context (in a thread,
102
- with or without an event loop, etc.).
103
- **Note**: When using asynchronous callbacks in complex applications
104
- with multiple event loops, be aware that callbacks may execute in a
105
- separate event loop context from where they were defined, which can
106
- make debugging challenging.
107
- :param on_token_refresh: A callback function that is called whenever the token is refreshed.
108
- This includes the initial token retrieval and any subsequent calls.
109
- With this you can for example securely store the token in your
110
- application or on your server for later reuse. The function
111
- must accept a single argument, which is the token dictionary
112
- returned by the Oauth2 token endpoint and does not return anything.
113
- This can be either a synchronous function or an async coroutine
114
- function. **Note**: When using asynchronous callbacks in complex
115
- applications with multiple event loops, be aware that callbacks
116
- may execute in a separate event loop context from where they were
117
- defined, which can make debugging challenging.
64
+ to access.
65
+ :param password: Password for the given `user_email` for basic Authentication.
66
+ :param certificate: The certificate content or the absolute path to the certificate file.
67
+ :param private_key: The private key content or the absolute path to the private key file.
68
+ :param private_key_password: The password to access the private key file. This is only
69
+ considered if you provided a private key file and it password-protected.
70
+ :param token: An Anaplan API Token. This will be used to authenticate the client. If
71
+ sufficient other authentication parameters are provided, the token will be used
72
+ until it expires, after which a new one will be created. If you provide only this
73
+ parameter, the client will raise an error upon first authentication failure. For
74
+ short-lived instances, such as in web applications where user specific clients are
75
+ created, this is the recommended way to authenticate, since this has the least
76
+ overhead.
77
+ :param auth: You can provide a subclass of `httpx.Auth` to use for authentication. You can
78
+ provide an instance of one of the classes provided by the SDK, or an instance of
79
+ your own subclass of `httpx.Auth`. This will give you full control over the
80
+ authentication process, but you will need to implement the entire authentication
81
+ logic yourself.
118
82
  :param timeout: The timeout in seconds for the HTTP requests. Alternatively, you can pass
119
- an instance of `httpx.Timeout` to set the timeout for the HTTP requests.
83
+ an instance of `httpx.Timeout` to set the timeout for the HTTP requests.
120
84
  :param retry_count: The number of times to retry an HTTP request if it fails. Set this to 0
121
- to never retry. Defaults to 2, meaning each HTTP Operation will be
122
- tried a total number of 2 times.
85
+ to never retry. Defaults to 2, meaning each HTTP Operation will be tried a total
86
+ number of 2 times.
123
87
  :param status_poll_delay: The delay between polling the status of a task.
124
88
  :param upload_chunk_size: The size of the chunks to upload. This is the maximum size of
125
- each chunk. Defaults to 25MB.
89
+ each chunk. Defaults to 25MB.
126
90
  :param allow_file_creation: Whether to allow the creation of new files. Defaults to False
127
- since this is typically unintentional and may well be unwanted
128
- behaviour in the API altogether. A file that is created this
129
- way will not be referenced by any action in anaplan until
130
- manually assigned so there is typically no value in dynamically
131
- creating new files and uploading content to them.
91
+ since this is typically unintentional and may well be unwanted behaviour in the API
92
+ altogether. A file that is created this way will not be referenced by any action in
93
+ anaplan until manually assigned so there is typically no value in dynamically
94
+ creating new files and uploading content to them.
132
95
  """
133
96
  _client = httpx.AsyncClient(
134
97
  auth=(
135
- _create_auth(
98
+ auth
99
+ or _create_auth(
136
100
  token=token,
137
- oauth_token=oauth_token,
138
101
  user_email=user_email,
139
102
  password=password,
140
103
  certificate=certificate,
141
104
  private_key=private_key,
142
105
  private_key_password=private_key_password,
143
- client_id=client_id,
144
- client_secret=client_secret,
145
- redirect_uri=redirect_uri,
146
- refresh_token=refresh_token,
147
- oauth2_scope=oauth2_scope,
148
- on_auth_code=on_auth_code,
149
- on_token_refresh=on_token_refresh,
150
106
  )
151
107
  ),
152
108
  timeout=timeout,
@@ -0,0 +1,363 @@
1
+ import logging
2
+ import os
3
+ from base64 import b64encode
4
+ from typing import Callable
5
+
6
+ import httpx
7
+
8
+ from ._oauth import _OAuthRequestFactory
9
+ from .exceptions import AnaplanException, InvalidCredentialsException, InvalidPrivateKeyException
10
+
11
+ logger = logging.getLogger("anaplan_sdk")
12
+
13
+
14
+ class _AnaplanAuth(httpx.Auth):
15
+ requires_response_body = True
16
+
17
+ def __init__(self, token: str | None = None):
18
+ self._token: str = token or ""
19
+ if not token:
20
+ logger.info("Creating Authentication Token.")
21
+ with httpx.Client(timeout=15.0) as client:
22
+ self._parse_auth_response(client.send(self._build_auth_request()))
23
+
24
+ def _build_auth_request(self) -> httpx.Request:
25
+ raise NotImplementedError("Must be implemented in subclass.")
26
+
27
+ def auth_flow(self, request):
28
+ request.headers["Authorization"] = f"AnaplanAuthToken {self._token}"
29
+ response = yield request
30
+ if response.status_code == 401:
31
+ logger.info("Token expired, refreshing.")
32
+ auth_res = yield self._build_auth_request()
33
+ self._parse_auth_response(auth_res)
34
+ request.headers["Authorization"] = f"AnaplanAuthToken {self._token}"
35
+ yield request
36
+
37
+ def _parse_auth_response(self, response: httpx.Response) -> None:
38
+ if response.status_code == 401:
39
+ raise InvalidCredentialsException
40
+ if not response.is_success:
41
+ raise AnaplanException(f"Authentication failed: {response.status_code} {response.text}")
42
+ self._token = response.json()["tokenInfo"]["tokenValue"]
43
+
44
+
45
+ class _StaticTokenAuth(httpx.Auth):
46
+ def __init__(self, token: str):
47
+ self._token = token
48
+
49
+ def auth_flow(self, request):
50
+ request.headers["Authorization"] = f"AnaplanAuthToken {self._token}"
51
+ response = yield request
52
+ if response.status_code == 401:
53
+ raise InvalidCredentialsException("Token is invalid or expired.")
54
+
55
+
56
+ class _AnaplanBasicAuth(_AnaplanAuth):
57
+ def __init__(self, user_email: str, password: str, token: str | None = None):
58
+ self.user_email = user_email
59
+ self.password = password
60
+ super().__init__(token)
61
+
62
+ def _build_auth_request(self) -> httpx.Request:
63
+ cred = b64encode(f"{self.user_email}:{self.password}".encode()).decode()
64
+ return httpx.Request(
65
+ method="post",
66
+ url="https://auth.anaplan.com/token/authenticate",
67
+ headers={"Authorization": f"Basic {cred}"},
68
+ )
69
+
70
+
71
+ class _AnaplanCertAuth(_AnaplanAuth):
72
+ requires_request_body = True
73
+
74
+ def __init__(
75
+ self,
76
+ certificate: str | bytes,
77
+ private_key: str | bytes,
78
+ private_key_password: str | bytes | None = None,
79
+ token: str | None = None,
80
+ ):
81
+ self.__set_certificate(certificate)
82
+ self.__set_private_key(private_key, private_key_password)
83
+ super().__init__(token)
84
+
85
+ def _build_auth_request(self) -> httpx.Request:
86
+ encoded_cert, encoded_string, encoded_signed_string = self._prep_credentials()
87
+ return httpx.Request(
88
+ method="post",
89
+ url="https://auth.anaplan.com/token/authenticate",
90
+ headers={
91
+ "Authorization": f"CACertificate {encoded_cert}",
92
+ "Content-Type": "application/json",
93
+ },
94
+ json={"encodedData": encoded_string, "encodedSignedData": encoded_signed_string},
95
+ )
96
+
97
+ def _prep_credentials(self) -> tuple[str, str, str]:
98
+ from cryptography.hazmat.primitives import hashes
99
+ from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
100
+
101
+ message = os.urandom(150)
102
+ return (
103
+ b64encode(self._certificate).decode(),
104
+ b64encode(message).decode(),
105
+ b64encode(self._private_key.sign(message, PKCS1v15(), hashes.SHA512())).decode(),
106
+ )
107
+
108
+ def __set_certificate(self, certificate: str | bytes) -> None:
109
+ if isinstance(certificate, str):
110
+ if os.path.isfile(certificate):
111
+ with open(certificate, "rb") as f:
112
+ self._certificate = f.read()
113
+ else:
114
+ self._certificate = certificate.encode()
115
+ else:
116
+ self._certificate = certificate
117
+
118
+ def __set_private_key(
119
+ self, private_key: str | bytes, private_key_password: str | bytes
120
+ ) -> None:
121
+ try:
122
+ from cryptography.exceptions import InvalidKey, UnsupportedAlgorithm
123
+ from cryptography.hazmat.backends import default_backend
124
+ from cryptography.hazmat.primitives import serialization
125
+ from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
126
+ except ImportError as e:
127
+ raise AnaplanException(
128
+ "cryptography is not available. Please install anaplan-sdk with the cert extra "
129
+ "`pip install anaplan-sdk[cert]` or install cryptography separately."
130
+ ) from e
131
+ try:
132
+ if isinstance(private_key, str):
133
+ if os.path.isfile(private_key):
134
+ with open(private_key, "rb") as f:
135
+ data = f.read()
136
+ else:
137
+ data = private_key.encode()
138
+ else:
139
+ data = private_key
140
+ password = (
141
+ private_key_password.encode()
142
+ if isinstance(private_key_password, str)
143
+ else private_key_password
144
+ )
145
+ self._private_key: RSAPrivateKey = serialization.load_pem_private_key(
146
+ data, password, backend=default_backend()
147
+ )
148
+ except (IOError, InvalidKey, UnsupportedAlgorithm) as error:
149
+ raise InvalidPrivateKeyException from error
150
+
151
+
152
+ class AnaplanLocalOAuth(_AnaplanAuth):
153
+ def __init__(
154
+ self,
155
+ client_id: str,
156
+ client_secret: str,
157
+ redirect_uri: str,
158
+ token: dict[str, str] | None = None,
159
+ persist_token: bool = False,
160
+ authorization_url: str = "https://us1a.app.anaplan.com/auth/prelogin",
161
+ token_url: str = "https://us1a.app.anaplan.com/oauth/token",
162
+ validation_url: str = "https://auth.anaplan.com/token/validate",
163
+ scope: str = "openid profile email offline_access",
164
+ state_generator: Callable[[], str] | None = None,
165
+ ):
166
+ """
167
+ Initializes the AnaplanLocalOAuth class for OAuth2 authentication using the
168
+ Authorization Code Flow. This is a utility class for local development and requires user
169
+ interaction. For Web Applications and other scenarios, refer to `Oauth` or `AsyncOauth`.
170
+ This class will refresh the access token automatically when it expires.
171
+ :param client_id: The client ID of your Anaplan Oauth 2.0 application. This Application
172
+ must be an Authorization Code Grant application.
173
+ :param client_secret: The client secret of your Anaplan Oauth 2.0 application.
174
+ :param redirect_uri: The URL to which the user will be redirected after authorizing the
175
+ application.
176
+ :param token: The OAuth token dictionary containing at least the `access_token` and
177
+ `refresh_token`. If not provided, the user will be prompted to interactive
178
+ authorize the application, if `persist_token` is set to False or no valid refresh
179
+ token is found in the keyring.
180
+ :param persist_token: If set to True, the refresh token will be stored in the system's
181
+ keyring, allowing the application to use the same refresh token across multiple
182
+ runs. If set to False, the user will be prompted to authorize the application each
183
+ time. This requires the `keyring` extra to be installed. If a valid refresh token
184
+ is found in the keyring, it will be used instead of the given `token` parameter.
185
+ :param authorization_url: The URL to which the user will be redirected to authorize the
186
+ application. Defaults to the Anaplan Prelogin Page, where the user can select the
187
+ login method.
188
+ :param token_url: The URL to post the authorization code to in order to fetch the access
189
+ token.
190
+ :param validation_url: The URL to validate the access token.
191
+ :param scope: The scope of the access request.
192
+ :param state_generator: A callable that generates a random state string. You can optionally
193
+ pass this if you need to customize the state generation logic. If not provided,
194
+ the state will be generated by `oauthlib`.
195
+ """
196
+ self._oauth_token = token or {}
197
+ self._service_name = "anaplan_sdk"
198
+
199
+ if persist_token:
200
+ try:
201
+ import keyring
202
+
203
+ stored = keyring.get_password(self._service_name, self._service_name)
204
+ if stored:
205
+ logger.info("Using persisted OAuth refresh token.")
206
+ self._oauth_token = {"refresh_token": stored}
207
+ self._token = "" # Set to blank to trigger the super().__init__ auth request.
208
+ except ImportError as e:
209
+ raise AnaplanException(
210
+ "keyring is not available. Please install anaplan-sdk with the keyring extra "
211
+ "`pip install anaplan-sdk[keyring]` or install keyring separately."
212
+ ) from e
213
+ self._persist_token = persist_token
214
+ self._oauth = _OAuthRequestFactory(
215
+ client_id=client_id,
216
+ client_secret=client_secret,
217
+ redirect_uri=redirect_uri,
218
+ scope=scope,
219
+ authorization_url=authorization_url,
220
+ token_url=token_url,
221
+ validation_url=validation_url,
222
+ state_generator=state_generator,
223
+ )
224
+ if not self._oauth_token:
225
+ self.__auth_code_flow()
226
+ super().__init__(self._token)
227
+
228
+ @property
229
+ def token(self) -> dict[str, str]:
230
+ """
231
+ Returns the current token dictionary. You can safely use the `access_token`, but if you
232
+ must not use the `refresh_token` outside of this class, if you expect to use this instance
233
+ further. If you do use the `refresh_token` outside of this class, this will error on the
234
+ next attempt to refresh the token, as the `refresh_token` can only be used once.
235
+ """
236
+ return self._oauth_token
237
+
238
+ def _build_auth_request(self) -> httpx.Request:
239
+ return self._oauth.refresh_token_request(self._oauth_token["refresh_token"])
240
+
241
+ def _parse_auth_response(self, response: httpx.Response) -> None:
242
+ if response.status_code == 401:
243
+ raise InvalidCredentialsException
244
+ if not response.is_success:
245
+ raise AnaplanException(f"Authentication failed: {response.status_code} {response.text}")
246
+ self._oauth_token = response.json()
247
+ if self._persist_token:
248
+ import keyring
249
+
250
+ keyring.set_password(
251
+ self._service_name, self._service_name, self._oauth_token["refresh_token"]
252
+ )
253
+ self._token: str = self._oauth_token["access_token"]
254
+
255
+ def __auth_code_flow(self):
256
+ from oauthlib.oauth2 import OAuth2Error
257
+
258
+ try:
259
+ logger.info("Creating Authentication Token with OAuth2 Authorization Code Flow.")
260
+ url, _ = self._oauth.authorization_url()
261
+ authorization_response = input(
262
+ f"Please go to {url} and authorize the app.\n"
263
+ "Then paste the entire redirect URL here: "
264
+ )
265
+ with httpx.Client() as client:
266
+ res = client.send(self._oauth.token_request(authorization_response))
267
+ self._parse_auth_response(res)
268
+ except (httpx.HTTPError, ValueError, TypeError, OAuth2Error) as error:
269
+ raise InvalidCredentialsException("Error during OAuth2 authorization flow.") from error
270
+
271
+
272
+ class AnaplanRefreshTokenAuth(_AnaplanAuth):
273
+ def __init__(
274
+ self,
275
+ client_id: str,
276
+ client_secret: str,
277
+ redirect_uri: str,
278
+ token: dict[str, str],
279
+ token_url: str = "https://us1a.app.anaplan.com/oauth/token",
280
+ ):
281
+ """
282
+ This class is a utility class for long-lived `Client` or `AsyncClient` instances that use
283
+ OAuth. This class will use the `access_token` until the first request fails with a 401
284
+ Unauthorized error, at which point it will attempt to refresh the `access_token` using the
285
+ `refresh_token`. If the refresh fails, it will raise an `InvalidCredentialsException`. The
286
+ `expires_in` field in the token dictionary is not considered. Manipulating any of the
287
+ fields in the token dictionary is not recommended and will likely have no effect.
288
+
289
+ **For its entire lifetime, you are ceding control of the token to this class.**
290
+ You must not use the same token simultaneously in multiple instances of this class or
291
+ outside of it, as this may lead to unexpected behavior when e.g. the refresh token is
292
+ used, which can only happen once and will lead to errors when attempting to use the same
293
+ refresh token again elsewhere.
294
+
295
+ If you need the token back before this instance is destroyed, you can use the `token`
296
+ method.
297
+
298
+ :param client_id: The client ID of your Anaplan Oauth 2.0 application. This Application
299
+ must be an Authorization Code Grant application.
300
+ :param client_secret: The client secret of your Anaplan Oauth 2.0 application.
301
+ :param redirect_uri: The URL to which the user will be redirected after authorizing the
302
+ application.
303
+ :param token: The OAuth token dictionary containing at least the `access_token` and
304
+ `refresh_token`.
305
+ :param token_url: The URL to post the refresh token request to in order to fetch the access
306
+ token.
307
+ """
308
+ if not isinstance(token, dict) or not all(
309
+ key in token for key in ("access_token", "refresh_token")
310
+ ):
311
+ raise ValueError(
312
+ "The token must at least contain 'access_token' and 'refresh_token' keys."
313
+ )
314
+ self._oauth_token = token
315
+ self._oauth = _OAuthRequestFactory(
316
+ client_id=client_id,
317
+ client_secret=client_secret,
318
+ redirect_uri=redirect_uri,
319
+ token_url=token_url,
320
+ )
321
+ super().__init__(self._oauth_token["access_token"])
322
+
323
+ @property
324
+ def token(self) -> dict[str, str]:
325
+ """
326
+ Returns the current OAuth token. You can safely use the `access_token`, but you
327
+ must not use the `refresh_token` outside of this class, if you expect to use this instance
328
+ further. If you do use the `refresh_token` outside of this class, this will error on the
329
+ next attempt to refresh the token, as the `refresh_token` can only be used once.
330
+ """
331
+ return self._oauth_token
332
+
333
+ def _build_auth_request(self) -> httpx.Request:
334
+ return self._oauth.refresh_token_request(self._oauth_token["refresh_token"])
335
+
336
+ def _parse_auth_response(self, response: httpx.Response) -> None:
337
+ if response.status_code == 401:
338
+ raise InvalidCredentialsException
339
+ if not response.is_success:
340
+ raise AnaplanException(f"Authentication failed: {response.status_code} {response.text}")
341
+ self._oauth_token = response.json()
342
+ self._token: str = self._oauth_token["access_token"]
343
+
344
+
345
+ def _create_auth(
346
+ user_email: str | None = None,
347
+ password: str | None = None,
348
+ certificate: str | bytes | None = None,
349
+ private_key: str | bytes | None = None,
350
+ private_key_password: str | bytes | None = None,
351
+ token: str | None = None,
352
+ ) -> httpx.Auth:
353
+ if certificate and private_key:
354
+ return _AnaplanCertAuth(certificate, private_key, private_key_password, token)
355
+ if user_email and password:
356
+ return _AnaplanBasicAuth(user_email, password, token)
357
+ if token:
358
+ return _StaticTokenAuth(token)
359
+ raise ValueError(
360
+ "No valid authentication parameters provided. Please provide either:\n"
361
+ "- `user_email` and `password`, or\n"
362
+ "- `certificate` and `private_key`\n"
363
+ )