dq-export-connector 0.1.0.dev27__tar.gz → 0.1.0.dev28__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 (69) hide show
  1. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/.gitignore +1 -1
  2. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/PKG-INFO +13 -18
  3. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/README.md +12 -17
  4. dq_export_connector-0.1.0.dev28/dq_export_connector/_models/destination_accounts.py +25 -0
  5. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/_models/export_connector_credentials.py +42 -4
  6. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/_models/export_worker_config.py +36 -12
  7. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/audience/classify.py +0 -17
  8. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/errors.py +3 -5
  9. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/models/__init__.py +7 -0
  10. dq_export_connector-0.1.0.dev28/dq_export_connector/oauth.py +229 -0
  11. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/redact.py +4 -2
  12. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/runner.py +60 -17
  13. dq_export_connector-0.1.0.dev28/dq_export_connector/snap/accounts.py +18 -0
  14. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/snap/client.py +27 -1
  15. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/snap/destination.py +1 -37
  16. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/snap/export.py +28 -38
  17. dq_export_connector-0.1.0.dev28/dq_export_connector/snap/session.py +103 -0
  18. dq_export_connector-0.1.0.dev28/dq_export_connector/snap/validate.py +29 -0
  19. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/pyproject.toml +1 -1
  20. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/scripts/_local.py +33 -7
  21. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/scripts/codegen-models.sh +1 -1
  22. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/scripts/run_local.py +11 -3
  23. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/fakes/snap_fake.py +29 -0
  24. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_http_and_oauth.py +52 -91
  25. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_live_snap.py +42 -20
  26. dq_export_connector-0.1.0.dev28/tests/test_oauth.py +185 -0
  27. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_redact.py +5 -0
  28. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_runner.py +19 -0
  29. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_snap_runner.py +66 -30
  30. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/uv.lock +1 -1
  31. dq_export_connector-0.1.0.dev27/dq_export_connector/audience/oauth.py +0 -321
  32. dq_export_connector-0.1.0.dev27/dq_export_connector/snap/session.py +0 -70
  33. dq_export_connector-0.1.0.dev27/dq_export_connector/snap/validate.py +0 -37
  34. dq_export_connector-0.1.0.dev27/scripts/consent.py +0 -99
  35. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/.python-version +0 -0
  36. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/__init__.py +0 -0
  37. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/_models/__init__.py +0 -0
  38. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/_models/application_message.py +0 -0
  39. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/_models/bucket_validation_result.py +0 -0
  40. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/_models/export_receipt.py +0 -0
  41. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/_models/snap_validation_result.py +0 -0
  42. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/audience/__init__.py +0 -0
  43. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/audience/http.py +0 -0
  44. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/audience/identifiers.py +0 -0
  45. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/audience/inputs.py +0 -0
  46. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/audience/sync.py +0 -0
  47. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/bucket/__init__.py +0 -0
  48. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/bucket/export.py +0 -0
  49. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/bucket/paths.py +0 -0
  50. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/bucket/store.py +0 -0
  51. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/bucket/upload.py +0 -0
  52. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/bucket/validate.py +0 -0
  53. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/datasets.py +0 -0
  54. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/log.py +0 -0
  55. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/models/bucket.py +0 -0
  56. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/models/snap.py +0 -0
  57. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/outcome.py +0 -0
  58. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/dq_export_connector/snap/__init__.py +0 -0
  59. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/__init__.py +0 -0
  60. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/conftest.py +0 -0
  61. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/fakes/__init__.py +0 -0
  62. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_identifiers_and_inputs.py +0 -0
  63. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_live_buckets.py +0 -0
  64. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_models_are_current.py +0 -0
  65. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_paths.py +0 -0
  66. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_scripts.py +0 -0
  67. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_store.py +0 -0
  68. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_sync_input.py +0 -0
  69. {dq_export_connector-0.1.0.dev27 → dq_export_connector-0.1.0.dev28}/tests/test_upload.py +0 -0
@@ -1,4 +1,4 @@
1
- # Local secrets for the consent CLI and the local runner.
1
+ # Local secrets for the local runner.
2
2
  credentials*.json
3
3
  platform_secrets*.json
4
4
  local/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: dq-export-connector
3
- Version: 0.1.0.dev27
3
+ Version: 0.1.0.dev28
4
4
  Summary: Worker logic for the Export Connector DCR.
5
5
  Author: Decentriq
6
6
  Requires-Python: >=3.12
@@ -67,11 +67,14 @@ uv run mypy dq_export_connector tests scripts
67
67
 
68
68
  ## Snap
69
69
 
70
- A Snap connector's config names the ad account and, per Input, a Segment, the
71
- identifier type its lines hold and a Merge Mode. ddc validates it. The
72
- credentials are the refresh token of the Snap user who consented; Decentriq's
73
- Snap app is the `export_connector_snap_app` platform secret
74
- (`{"clientId", "clientSecret"}`).
70
+ A Snap connector's config names the ad account (set after consent, from
71
+ `ListDestinationAccounts`) and, per Input, a Segment, the identifier type its
72
+ lines hold and a Merge Mode. ddc validates it. The credentials are the OAuth
73
+ Grant of the Snap user who consented; each run turns it into an Access Token
74
+ with `dq_export_connector.oauth`. Decentriq's Snap app is the
75
+ `export_connector_snap_app` platform secret (`{"clientId", "clientSecret"}`),
76
+ mounted at `/input/oauth_app.json`. `ListDestinationAccounts` lists the ad
77
+ accounts of every organization the grant reaches.
75
78
 
76
79
  A run looks each Segment up by name in the ad account and creates it when
77
80
  there is none, marked `Managed by Decentriq`. It writes into a same-named
@@ -121,18 +124,10 @@ warning or error message), never with the values themselves:
121
124
  The local files are gitignored in this directory:
122
125
 
123
126
  - `platform_secrets.json`: `{"export_connector_snap_app": {"clientId": …, "clientSecret": …}}`, the dev app.
124
- - `credentials.json`: written by the consent CLI.
125
- - `config.json`: `{"connector": {"type": "snap", "adAccountId": …, "grantExpiresAt": null, "inputs": [{"leafId": "segA", "segmentName": …, "identifierType": "EMAIL", "mergeMode": "ADD", "retentionDays": 180}]}}`.
127
+ - `credentials.json`: `{"type": "snap", "credentials": {"refreshToken": …}}`, a refresh token the owner got through consent on a dev environment. Snap doesn't rotate it, so it can be reused.
128
+ - `config.json`: `{"connector": {"type": "snap", "adAccountId": …, "inputs": [{"leafId": "segA", "segmentName": …, "identifierType": "EMAIL", "mergeMode": "ADD", "retentionDays": 180}]}}`.
126
129
 
127
- 1. Consent, as the Snap user who has a role on the test ad account. The
128
- redirect URI must be an https URI registered on the app; only the URL the
129
- browser lands on matters.
130
-
131
- ```sh
132
- uv run python scripts/consent.py snap --platform-secrets platform_secrets.json \
133
- --redirect-uri "$REDIRECT_URI" --out credentials.json --config config.json
134
- ```
135
- 2. Run:
130
+ 1. Run:
136
131
 
137
132
  ```sh
138
133
  mkdir -p local/inputs && printf 'a@example.com\nb@example.com\n' > local/inputs/segA
@@ -141,7 +136,7 @@ The local files are gitignored in this directory:
141
136
  uv run python scripts/run_local.py --config config.json --credentials credentials.json \
142
137
  --platform-secrets platform_secrets.json
143
138
  ```
144
- 3. Live tests, including the check that Snap doesn't rotate refresh tokens:
139
+ 2. Live tests, including the check that Snap doesn't rotate refresh tokens:
145
140
 
146
141
  ```sh
147
142
  DQ_EXPORT_LIVE_SNAP_DIR=$PWD uv run pytest -m live -s tests/test_live_snap.py
@@ -54,11 +54,14 @@ uv run mypy dq_export_connector tests scripts
54
54
 
55
55
  ## Snap
56
56
 
57
- A Snap connector's config names the ad account and, per Input, a Segment, the
58
- identifier type its lines hold and a Merge Mode. ddc validates it. The
59
- credentials are the refresh token of the Snap user who consented; Decentriq's
60
- Snap app is the `export_connector_snap_app` platform secret
61
- (`{"clientId", "clientSecret"}`).
57
+ A Snap connector's config names the ad account (set after consent, from
58
+ `ListDestinationAccounts`) and, per Input, a Segment, the identifier type its
59
+ lines hold and a Merge Mode. ddc validates it. The credentials are the OAuth
60
+ Grant of the Snap user who consented; each run turns it into an Access Token
61
+ with `dq_export_connector.oauth`. Decentriq's Snap app is the
62
+ `export_connector_snap_app` platform secret (`{"clientId", "clientSecret"}`),
63
+ mounted at `/input/oauth_app.json`. `ListDestinationAccounts` lists the ad
64
+ accounts of every organization the grant reaches.
62
65
 
63
66
  A run looks each Segment up by name in the ad account and creates it when
64
67
  there is none, marked `Managed by Decentriq`. It writes into a same-named
@@ -108,18 +111,10 @@ warning or error message), never with the values themselves:
108
111
  The local files are gitignored in this directory:
109
112
 
110
113
  - `platform_secrets.json`: `{"export_connector_snap_app": {"clientId": …, "clientSecret": …}}`, the dev app.
111
- - `credentials.json`: written by the consent CLI.
112
- - `config.json`: `{"connector": {"type": "snap", "adAccountId": …, "grantExpiresAt": null, "inputs": [{"leafId": "segA", "segmentName": …, "identifierType": "EMAIL", "mergeMode": "ADD", "retentionDays": 180}]}}`.
114
+ - `credentials.json`: `{"type": "snap", "credentials": {"refreshToken": …}}`, a refresh token the owner got through consent on a dev environment. Snap doesn't rotate it, so it can be reused.
115
+ - `config.json`: `{"connector": {"type": "snap", "adAccountId": …, "inputs": [{"leafId": "segA", "segmentName": …, "identifierType": "EMAIL", "mergeMode": "ADD", "retentionDays": 180}]}}`.
113
116
 
114
- 1. Consent, as the Snap user who has a role on the test ad account. The
115
- redirect URI must be an https URI registered on the app; only the URL the
116
- browser lands on matters.
117
-
118
- ```sh
119
- uv run python scripts/consent.py snap --platform-secrets platform_secrets.json \
120
- --redirect-uri "$REDIRECT_URI" --out credentials.json --config config.json
121
- ```
122
- 2. Run:
117
+ 1. Run:
123
118
 
124
119
  ```sh
125
120
  mkdir -p local/inputs && printf 'a@example.com\nb@example.com\n' > local/inputs/segA
@@ -128,7 +123,7 @@ The local files are gitignored in this directory:
128
123
  uv run python scripts/run_local.py --config config.json --credentials credentials.json \
129
124
  --platform-secrets platform_secrets.json
130
125
  ```
131
- 3. Live tests, including the check that Snap doesn't rotate refresh tokens:
126
+ 2. Live tests, including the check that Snap doesn't rotate refresh tokens:
132
127
 
133
128
  ```sh
134
129
  DQ_EXPORT_LIVE_SNAP_DIR=$PWD uv run pytest -m live -s tests/test_live_snap.py
@@ -0,0 +1,25 @@
1
+ # generated by datamodel-codegen:
2
+ # filename: destination_accounts.json
3
+
4
+ from __future__ import annotations
5
+
6
+ from typing import Annotated
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field
9
+
10
+
11
+ class DestinationAccount(BaseModel):
12
+ model_config = ConfigDict(
13
+ populate_by_name=True,
14
+ )
15
+ id: str
16
+ name: str
17
+
18
+
19
+ class DestinationAccounts(BaseModel):
20
+ model_config = ConfigDict(
21
+ populate_by_name=True,
22
+ )
23
+ destination_accounts: Annotated[
24
+ list[DestinationAccount], Field(alias='destinationAccounts')
25
+ ]
@@ -56,17 +56,55 @@ class BucketExportCredentials(
56
56
  ]
57
57
 
58
58
 
59
- class SnapExportCredentials(BaseModel):
59
+ class GrantTokenRefreshToken(BaseModel):
60
60
  model_config = ConfigDict(
61
61
  populate_by_name=True,
62
62
  )
63
- refresh_token: Annotated[
63
+ type: Literal['refreshToken']
64
+ value: str
65
+
66
+
67
+ class GrantTokenAccessToken(BaseModel):
68
+ model_config = ConfigDict(
69
+ populate_by_name=True,
70
+ )
71
+ type: Literal['accessToken']
72
+ value: str
73
+
74
+
75
+ class GrantToken(RootModel[GrantTokenRefreshToken | GrantTokenAccessToken]):
76
+ root: GrantTokenRefreshToken | GrantTokenAccessToken
77
+
78
+
79
+ class OAuthGrant(BaseModel):
80
+ model_config = ConfigDict(
81
+ populate_by_name=True,
82
+ )
83
+ client_id: Annotated[
64
84
  str,
65
85
  Field(
66
- alias='refreshToken',
67
- description="The refresh token of the Snap user who consented. Snap doesn't rotate it.",
86
+ alias='clientId',
87
+ description='The OAuth App the grant was issued to; it only works with that app.',
68
88
  ),
69
89
  ]
90
+ obtained_at: Annotated[
91
+ str, Field(alias='obtainedAt', description='RFC 3339, in UTC.')
92
+ ]
93
+ token: GrantToken
94
+
95
+
96
+ class SnapExportCredentialsOauth(BaseModel):
97
+ model_config = ConfigDict(
98
+ populate_by_name=True,
99
+ )
100
+ grant: OAuthGrant
101
+ type: Literal['oauth']
102
+
103
+
104
+ class SnapExportCredentials(RootModel[SnapExportCredentialsOauth]):
105
+ root: Annotated[
106
+ SnapExportCredentialsOauth, Field(description='What is sealed for Snap.')
107
+ ]
70
108
 
71
109
 
72
110
  class ExportConnectorCredentialsBucket(BaseModel):
@@ -4,7 +4,7 @@
4
4
  from __future__ import annotations
5
5
 
6
6
  from enum import Enum
7
- from typing import Annotated, Literal
7
+ from typing import Annotated, Any, Literal
8
8
 
9
9
  from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, RootModel
10
10
 
@@ -57,6 +57,21 @@ class BucketInput(BaseModel):
57
57
  leaf_id: Annotated[str, Field(alias='leafId')]
58
58
 
59
59
 
60
+ class ClientAuth(Enum):
61
+ form_body = 'formBody'
62
+ http_basic = 'httpBasic'
63
+
64
+
65
+ class ExportConnectorDcrComputeActionListDestinationAccounts(BaseModel):
66
+ model_config = ConfigDict(
67
+ extra='forbid',
68
+ populate_by_name=True,
69
+ )
70
+ list_destination_accounts: Annotated[
71
+ dict[str, Any], Field(alias='listDestinationAccounts')
72
+ ]
73
+
74
+
60
75
  class ExportConnectorKindBucket(BaseModel):
61
76
  model_config = ConfigDict(
62
77
  populate_by_name=True,
@@ -107,6 +122,15 @@ class MergeMode(Enum):
107
122
  replace = 'REPLACE'
108
123
 
109
124
 
125
+ class OAuthWorkerConfig(BaseModel):
126
+ model_config = ConfigDict(
127
+ populate_by_name=True,
128
+ )
129
+ client_auth: Annotated[ClientAuth, Field(alias='clientAuth')]
130
+ platform_secret: Annotated[str, Field(alias='platformSecret')]
131
+ token_url: Annotated[str, Field(alias='tokenUrl')]
132
+
133
+
110
134
  class ProvisionedPolicy(BaseModel):
111
135
  model_config = ConfigDict(
112
136
  populate_by_name=True,
@@ -220,11 +244,13 @@ class ExportConnectorDcrComputeAction(
220
244
  RootModel[
221
245
  ExportConnectorDcrComputeActionValidateConnection
222
246
  | ExportConnectorDcrComputeActionExport
247
+ | ExportConnectorDcrComputeActionListDestinationAccounts
223
248
  ]
224
249
  ):
225
250
  root: Annotated[
226
251
  ExportConnectorDcrComputeActionValidateConnection
227
- | ExportConnectorDcrComputeActionExport,
252
+ | ExportConnectorDcrComputeActionExport
253
+ | ExportConnectorDcrComputeActionListDestinationAccounts,
228
254
  Field(
229
255
  description='Compute actions for an Export Connector DCR, started through `POST /jobs`.'
230
256
  ),
@@ -236,13 +262,10 @@ class ExportConnectorKindSnap(BaseModel):
236
262
  populate_by_name=True,
237
263
  )
238
264
  ad_account_id: Annotated[
239
- str, Field(alias='adAccountId', description='A canonical, lowercase UUID.')
240
- ]
241
- grant_expires_at: Annotated[
242
265
  str | None,
243
266
  Field(
244
- alias='grantExpiresAt',
245
- description='RFC 3339. When the grant behind the credentials expires; runs warn as\nit nears.',
267
+ alias='adAccountId',
268
+ description='A canonical, lowercase UUID. `None` until the owner picks one from the\nad accounts the grant reaches.',
246
269
  ),
247
270
  ] = None
248
271
  inputs: list[SnapInput]
@@ -260,13 +283,10 @@ class SnapExportConfig(BaseModel):
260
283
  populate_by_name=True,
261
284
  )
262
285
  ad_account_id: Annotated[
263
- str, Field(alias='adAccountId', description='A canonical, lowercase UUID.')
264
- ]
265
- grant_expires_at: Annotated[
266
286
  str | None,
267
287
  Field(
268
- alias='grantExpiresAt',
269
- description='RFC 3339. When the grant behind the credentials expires; runs warn as\nit nears.',
288
+ alias='adAccountId',
289
+ description='A canonical, lowercase UUID. `None` until the owner picks one from the\nad accounts the grant reaches.',
270
290
  ),
271
291
  ] = None
272
292
  inputs: list[SnapInput]
@@ -282,4 +302,8 @@ class ExportWorkerConfig(BaseModel):
282
302
  AwareDatetime | None,
283
303
  Field(alias='credentialsExpireAt', description='From the Credentials Info.'),
284
304
  ] = None
305
+ oauth: Annotated[
306
+ OAuthWorkerConfig | None,
307
+ Field(description='For a kind whose credentials are an OAuth Grant.'),
308
+ ] = None
285
309
  policies: list[ProvisionedPolicy]
@@ -79,20 +79,3 @@ def classify_status(status: int, raw_code: object = None, platform_message: obje
79
79
  return Classification(Verdict.RETRY, ErrorCode.UNKNOWN, code, message)
80
80
  return Classification(Verdict.FAIL, ErrorCode.UNKNOWN, code, message)
81
81
 
82
-
83
- def classify_oauth_token_response(response: requests.Response) -> Classification:
84
- """RFC 6749 token endpoint errors (Snap, LinkedIn)."""
85
- body = json_body(response)
86
- error = platform_code(body.get("error"))
87
- description = body.get("error_description")
88
- if 200 <= response.status_code < 300:
89
- return Classification(Verdict.OK)
90
- if error == "invalid_grant":
91
- return Classification(Verdict.FAIL, ErrorCode.UNAUTHENTICATED, error, platform_text(description))
92
- if error in ("invalid_client", "unauthorized_client"):
93
- return Classification(Verdict.FAIL, ErrorCode.APP_CREDENTIALS_REJECTED, error, platform_text(description))
94
- result = classify_status(response.status_code, error, description)
95
- if result.code is ErrorCode.UNAUTHENTICATED:
96
- # A 401 from the token endpoint means the client authentication failed.
97
- return Classification(Verdict.FAIL, ErrorCode.APP_CREDENTIALS_REJECTED, error, result.platform_message)
98
- return result
@@ -20,23 +20,21 @@ class ErrorCode(str, Enum):
20
20
  UNKNOWN = "UNKNOWN"
21
21
  READ_FAILED = "READ_FAILED"
22
22
  INTERNAL_ERROR = "INTERNAL_ERROR"
23
+ OAUTH_REAUTHORISATION_NEEDED = "OAUTH_REAUTHORISATION_NEEDED"
24
+ OAUTH_APP_CREDENTIALS_REJECTED = "OAUTH_APP_CREDENTIALS_REJECTED"
23
25
  BUCKET_INVALID_PATH = "BUCKET_INVALID_PATH"
24
- # Decentriq's own app credentials for the platform were rejected.
25
- APP_CREDENTIALS_REJECTED = "APP_CREDENTIALS_REJECTED"
26
26
  RATE_LIMITED = "RATE_LIMITED"
27
27
  AMBIGUOUS_SEGMENT = "AMBIGUOUS_SEGMENT"
28
28
  TOO_MANY_INVALID_ROWS = "TOO_MANY_INVALID_ROWS"
29
29
  # A request that isn't safe to repeat may or may not have been applied.
30
30
  OUTCOME_UNKNOWN = "OUTCOME_UNKNOWN"
31
- # The platform issued a new refresh token, which the worker can't store.
32
- REFRESH_TOKEN_ROTATED = "REFRESH_TOKEN_ROTATED"
33
31
 
34
32
 
35
33
  class WarningCode(str, Enum):
36
34
  EMPTY_DATASET = "EMPTY_DATASET"
35
+ OAUTH_REFRESH_TOKEN_ROTATED = "OAUTH_REFRESH_TOKEN_ROTATED"
37
36
  BUCKET_PROBE_NOT_DELETED = "BUCKET_PROBE_NOT_DELETED"
38
37
  BUCKET_PARTS_MAY_REMAIN = "BUCKET_PARTS_MAY_REMAIN"
39
- REAUTHORISATION_DUE = "REAUTHORISATION_DUE"
40
38
  INVALID_ROWS = "INVALID_ROWS"
41
39
  SEGMENT_SETTINGS_DIFFER = "SEGMENT_SETTINGS_DIFFER"
42
40
  # The run wrote into a Segment this connector didn't create.
@@ -3,16 +3,19 @@ schemas. The types of every Connector Kind are here, a kind's own types in its
3
3
  submodule."""
4
4
 
5
5
  from dq_export_connector._models.application_message import ApplicationMessage
6
+ from dq_export_connector._models.destination_accounts import DestinationAccount, DestinationAccounts
6
7
  from dq_export_connector._models.export_connector_credentials import ExportConnectorCredentials
7
8
  from dq_export_connector._models.export_receipt import ExportReceipt, ExportReceiptV0, ExportTotals
8
9
  from dq_export_connector._models.export_worker_config import (
9
10
  Export,
10
11
  ExportConnectorDcrComputeAction,
11
12
  ExportConnectorDcrComputeActionExport,
13
+ ExportConnectorDcrComputeActionListDestinationAccounts,
12
14
  ExportConnectorDcrComputeActionValidateConnection,
13
15
  ExportConnectorKind,
14
16
  ExportParams,
15
17
  ExportWorkerConfig,
18
+ OAuthWorkerConfig,
16
19
  ProvisionedPolicy,
17
20
  ValidateConnection,
18
21
  ValidateConnectionParams,
@@ -20,10 +23,13 @@ from dq_export_connector._models.export_worker_config import (
20
23
 
21
24
  __all__ = [
22
25
  "ApplicationMessage",
26
+ "DestinationAccount",
27
+ "DestinationAccounts",
23
28
  "Export",
24
29
  "ExportConnectorCredentials",
25
30
  "ExportConnectorDcrComputeAction",
26
31
  "ExportConnectorDcrComputeActionExport",
32
+ "ExportConnectorDcrComputeActionListDestinationAccounts",
27
33
  "ExportConnectorDcrComputeActionValidateConnection",
28
34
  "ExportConnectorKind",
29
35
  "ExportParams",
@@ -31,6 +37,7 @@ __all__ = [
31
37
  "ExportReceiptV0",
32
38
  "ExportTotals",
33
39
  "ExportWorkerConfig",
40
+ "OAuthWorkerConfig",
34
41
  "ProvisionedPolicy",
35
42
  "ValidateConnection",
36
43
  "ValidateConnectionParams",
@@ -0,0 +1,229 @@
1
+ """OAuth for every Connector Kind that uses it: turns the OAuth Grant sealed in
2
+ `credentials.json` into the Access Token a run's API calls carry. ddc's OAuth
3
+ Profile reaches the worker as `config.json`'s `oauth` key, and the OAuth App's
4
+ `{clientId, clientSecret}` as the Platform Secret at `/input/oauth_app.json`.
5
+
6
+ A kind whose provider reports a dead grant in its own way passes its own
7
+ classifier and retry policy; the default follows RFC 6749.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import base64
13
+ import json
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+ from typing import Any, NamedTuple, TypeVar
22
+
23
+ from dq_export_connector.errors import ErrorCode, ExportConnectorError, WarningCode
24
+ from dq_export_connector.log import logger
25
+ from dq_export_connector.models import OAuthWorkerConfig
26
+ from dq_export_connector.outcome import RunOutcome
27
+
28
+ APP_SECRET_PATH = Path("/input/oauth_app.json")
29
+
30
+ T = TypeVar("T")
31
+
32
+
33
+ class ProviderResponse(NamedTuple):
34
+ status: int
35
+ body: bytes
36
+
37
+
38
+ # (url, headers, form, timeout in seconds) -> the provider's answer. A
39
+ # connection that can't be made raises `OSError`.
40
+ Post = Callable[[str, dict[str, str], dict[str, str], float], ProviderResponse]
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Retry:
45
+ """Ask again. Once the attempts are spent, the refresh fails with `exhausted`."""
46
+
47
+ exhausted: ErrorCode = ErrorCode.UNREACHABLE
48
+
49
+
50
+ # What a refresh's answer means: usable, to be asked again, or a failure with its code.
51
+ Verdict = ErrorCode | Retry | None
52
+ Classifier = Callable[[int, dict[str, Any]], Verdict]
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class RetryPolicy:
57
+ attempts: int = 3
58
+ backoff_seconds: float = 1.0
59
+ timeout_seconds: float = 30.0
60
+
61
+
62
+ def classify_refresh_response(status: int, body: dict[str, Any]) -> Verdict:
63
+ """RFC 6749's errors: `invalid_grant` is the grant's death, `invalid_client`
64
+ and `unauthorized_client` the OAuth App's rejection, and a 5xx an outage."""
65
+ error = body.get("error")
66
+ if 200 <= status < 300:
67
+ return None
68
+ if error == "invalid_grant":
69
+ return ErrorCode.OAUTH_REAUTHORISATION_NEEDED
70
+ if error in ("invalid_client", "unauthorized_client") or status == 401:
71
+ return ErrorCode.OAUTH_APP_CREDENTIALS_REJECTED
72
+ if status >= 500:
73
+ return Retry()
74
+ return ErrorCode.UNKNOWN
75
+
76
+
77
+ def default_post(url: str, headers: dict[str, str], form: dict[str, str], timeout: float) -> ProviderResponse:
78
+ request = urllib.request.Request(
79
+ url, data=urllib.parse.urlencode(form).encode(), headers=headers, method="POST"
80
+ )
81
+ try:
82
+ with urllib.request.urlopen(request, timeout=timeout) as response:
83
+ return ProviderResponse(response.status, response.read())
84
+ except urllib.error.HTTPError as error:
85
+ return ProviderResponse(error.code, error.read())
86
+ except urllib.error.URLError as error:
87
+ raise OSError("The token endpoint couldn't be reached") from error
88
+
89
+
90
+ def read_app_secret(path: Path = APP_SECRET_PATH) -> dict[str, str]:
91
+ return json.loads(path.read_text())
92
+
93
+
94
+ class AccessTokenProvider:
95
+ """Mints Access Tokens from a grant, and a new one when the API refuses the
96
+ one it has. `classify` judges refreshes until one succeeds; after that the
97
+ grant is known to be alive, and the RFC 6749 classifier takes over."""
98
+
99
+ def __init__(
100
+ self,
101
+ profile: OAuthWorkerConfig,
102
+ grant: dict[str, Any],
103
+ app: dict[str, str],
104
+ outcome: RunOutcome,
105
+ *,
106
+ classify: Classifier = classify_refresh_response,
107
+ retry: RetryPolicy = RetryPolicy(),
108
+ post: Post = default_post,
109
+ sleep: Callable[[float], None] = time.sleep,
110
+ ) -> None:
111
+ self._profile = profile
112
+ self._grant = grant
113
+ self._app = app
114
+ self._outcome = outcome
115
+ self._classify = classify
116
+ self._retry = retry
117
+ self._post = post
118
+ self._sleep = sleep
119
+ self._token: str | None = None
120
+ self._grant_known_good = False
121
+ self._warned = False
122
+
123
+ def token(self) -> str:
124
+ if self._token is None:
125
+ self._token = self._mint()
126
+ return self._token
127
+
128
+ def refresh(self) -> str:
129
+ self._token = self._mint()
130
+ return self._token
131
+
132
+ def call(self, do: Callable[[str], T], is_unauthorised: Callable[[T], bool]) -> T:
133
+ """Runs `do` with the Access Token. If the API refuses it, refreshes once
134
+ and runs it again; a second refusal means the grant no longer reaches the
135
+ account."""
136
+ result = do(self.token())
137
+ if not is_unauthorised(result):
138
+ return result
139
+ result = do(self.refresh())
140
+ if is_unauthorised(result):
141
+ raise ExportConnectorError(
142
+ ErrorCode.OAUTH_REAUTHORISATION_NEEDED,
143
+ "The provider refuses the access the owner granted: connect the Export Connector again",
144
+ )
145
+ return result
146
+
147
+ def _mint(self) -> str:
148
+ if self._grant["clientId"] != self._app["clientId"]:
149
+ raise ExportConnectorError(
150
+ ErrorCode.OAUTH_REAUTHORISATION_NEEDED,
151
+ "The OAuth App changed since the owner connected: connect the Export Connector again",
152
+ )
153
+ token = self._grant["token"]
154
+ if token["type"] == "accessToken":
155
+ return token["value"]
156
+ refresh_token = token["value"]
157
+ response = self._refresh(refresh_token)
158
+ body = _json_object(response.body)
159
+ rotated = body.get("refresh_token")
160
+ if rotated is not None and rotated != refresh_token and not self._warned:
161
+ self._warned = True
162
+ self._outcome.warn(
163
+ WarningCode.OAUTH_REFRESH_TOKEN_ROTATED,
164
+ "The provider issued a new refresh token, which can't be kept: the next run will fail",
165
+ )
166
+ access_token = body.get("access_token")
167
+ if not isinstance(access_token, str) or not access_token:
168
+ raise ExportConnectorError(ErrorCode.UNKNOWN, "The token endpoint's answer holds no access token")
169
+ return access_token
170
+
171
+ def _refresh(self, refresh_token: str) -> ProviderResponse:
172
+ form = {"grant_type": "refresh_token", "refresh_token": refresh_token}
173
+ headers = {"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"}
174
+ if self._profile.client_auth.value == "httpBasic":
175
+ credentials = f"{self._app['clientId']}:{self._app['clientSecret']}".encode()
176
+ headers["Authorization"] = "Basic " + base64.b64encode(credentials).decode()
177
+ else:
178
+ form["client_id"] = self._app["clientId"]
179
+ form["client_secret"] = self._app["clientSecret"]
180
+ classify = classify_refresh_response if self._grant_known_good else self._classify
181
+ last: Verdict = Retry()
182
+ for attempt in range(self._retry.attempts):
183
+ if attempt:
184
+ self._sleep(self._retry.backoff_seconds * 2 ** (attempt - 1))
185
+ try:
186
+ response = self._post(str(self._profile.token_url), headers, form, self._retry.timeout_seconds)
187
+ except OSError:
188
+ last = Retry()
189
+ logger.warning("The token endpoint couldn't be reached (attempt %d)", attempt + 1)
190
+ continue
191
+ verdict = classify(response.status, _json_object(response.body))
192
+ if verdict is None:
193
+ self._grant_known_good = True
194
+ return response
195
+ if not isinstance(verdict, Retry):
196
+ raise ExportConnectorError(verdict, _failure_sentence(verdict))
197
+ last = verdict
198
+ logger.warning("The token endpoint answered %d (attempt %d)", response.status, attempt + 1)
199
+ assert isinstance(last, Retry)
200
+ raise ExportConnectorError(last.exhausted, _failure_sentence(last.exhausted))
201
+
202
+
203
+ def oauth_access_token(
204
+ profile: OAuthWorkerConfig,
205
+ grant: dict[str, Any],
206
+ outcome: RunOutcome,
207
+ *,
208
+ app: dict[str, str] | None = None,
209
+ **options: Any,
210
+ ) -> str:
211
+ """A single Access Token, for a kind that makes no call it would retry."""
212
+ provider = AccessTokenProvider(profile, grant, app if app is not None else read_app_secret(), outcome, **options)
213
+ return provider.token()
214
+
215
+
216
+ def _json_object(body: bytes) -> dict[str, Any]:
217
+ try:
218
+ parsed = json.loads(body)
219
+ except ValueError:
220
+ return {}
221
+ return parsed if isinstance(parsed, dict) else {}
222
+
223
+
224
+ def _failure_sentence(code: ErrorCode) -> str:
225
+ return {
226
+ ErrorCode.OAUTH_REAUTHORISATION_NEEDED: "The provider no longer honours the owner's consent: connect the Export Connector again",
227
+ ErrorCode.OAUTH_APP_CREDENTIALS_REJECTED: "The provider rejected Decentriq's OAuth App credentials",
228
+ ErrorCode.UNREACHABLE: "The provider's token endpoint couldn't be reached",
229
+ }.get(code, "The provider's token endpoint answered unexpectedly")
@@ -17,11 +17,13 @@ from typing import Any
17
17
 
18
18
  MASK = "***"
19
19
 
20
- # The `type` tags of the credentials, such as `s3`, and the public fields of a
21
- # GCS service account key, which error messages and URLs carry.
20
+ # The `type` tags of the credentials, such as `s3`, the public fields of a GCS
21
+ # service account key and of an OAuth Grant, which error messages and URLs carry.
22
22
  PUBLIC_FIELDS = frozenset(
23
23
  {
24
24
  "type",
25
+ "clientId",
26
+ "obtainedAt",
25
27
  "project_id",
26
28
  "client_email",
27
29
  "client_id",