bapp-api-client 0.4.4__tar.gz → 0.6.0__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.
@@ -0,0 +1,71 @@
1
+ # Changelog
2
+
3
+ ## 0.6.0
4
+
5
+ - Embed token verification (`verify_embed_token` / `VerifyEmbedToken` /
6
+ `verifyEmbedToken` / `VerifyEmbedTokenAsync`, by language) checks a signed embed page token
7
+ (`bapp-embed+jwt`, ES256) against the configured issuer, audience and
8
+ allowed tenants, with the JWKS fetched only from
9
+ `{issuer}/.well-known/jwks.json` and cached in memory.
10
+ - Flow webhook: sign and send helpers producing the `X-Bapp-Timestamp`,
11
+ `X-Bapp-Idempotency-Key` and `X-Bapp-Signature` headers, with retries that
12
+ keep the same idempotency key.
13
+ - Available in all six SDKs:
14
+ - Python: optional extra `embed` (`cryptography`).
15
+ - Rust: optional feature `embed`.
16
+ - Dart: new dependencies `pointycastle` and `crypto`; Dart SDK 3.2 or newer.
17
+ - PHP: requires `ext-openssl` and `ext-json`.
18
+ - Go: standard library only.
19
+ - C#: token verification on `net8.0` only.
20
+
21
+ ## 0.5.0
22
+
23
+ - Configurable HTTP timeout (default 30 seconds).
24
+ - Retry with exponential backoff and jitter on 5xx, 429 and connection errors
25
+ (default 3 retries).
26
+ - URL encoding of all document render query parameters.
27
+ - Streaming document downloads to a file or writer instead of buffering the
28
+ whole response in memory.
29
+ - New C# / .NET SDK.
30
+
31
+ ## 0.4.4
32
+
33
+ - Go: JSON tags on the `PagedList` struct.
34
+
35
+ ## 0.4.3
36
+
37
+ - Configurable User-Agent header option.
38
+
39
+ ## 0.4.2
40
+
41
+ - `download` parameter for document URLs and content.
42
+ - `pdf.view` support for inline PDF documents.
43
+
44
+ ## 0.4.1
45
+
46
+ - Document views: list the available views, build a document URL and fetch
47
+ its content.
48
+
49
+ ## 0.4.0
50
+
51
+ - Dart: pub.dev publish workflow.
52
+
53
+ ## 0.3.0
54
+
55
+ - `readme` field in the package manifests.
56
+
57
+ ## 0.2.0
58
+
59
+ - Repository URLs and keywords in all package manifests.
60
+ - Dart: pub.dev score fixes.
61
+
62
+ ## 0.1.0
63
+
64
+ - Initial release.
65
+ - Authentication: Bearer (JWT/OAuth) and Token (API key).
66
+ - Entity CRUD: list, get, create, update, patch, delete.
67
+ - Paginated list responses with metadata (count, next, previous).
68
+ - Entity introspection: list_introspect, detail_introspect.
69
+ - Tasks: list, detail, run (sync and async with polling).
70
+ - Long-running task support via run_task_async with automatic polling.
71
+ - File uploads: automatic multipart/form-data detection.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: bapp-api-client
3
- Version: 0.4.4
3
+ Version: 0.6.0
4
4
  Summary: BAPP Auto API Client for Python
5
5
  Project-URL: Homepage, https://www.bapp.ro
6
6
  Project-URL: Repository, https://github.com/bapp-open/sdk-python
@@ -9,6 +9,8 @@ License-File: LICENSE
9
9
  Keywords: api,bapp,client
10
10
  Requires-Python: >=3.9
11
11
  Requires-Dist: requests>=2.20
12
+ Provides-Extra: embed
13
+ Requires-Dist: cryptography>=41; extra == 'embed'
12
14
  Description-Content-Type: text/markdown
13
15
 
14
16
  # BAPP Auto API Client — Python
@@ -16,6 +18,8 @@ Description-Content-Type: text/markdown
16
18
  Official Python client for the [BAPP Auto API](https://www.bapp.ro). Provides a
17
19
  simple, consistent interface for authentication, entity CRUD, and task execution.
18
20
 
21
+ Verifying signed embed tokens needs the `embed` extra (`pip install "bapp-api-client[embed]"`); everything else, flow webhooks included, works without it.
22
+
19
23
  ## Getting Started
20
24
 
21
25
  ### 1. Install
@@ -87,6 +91,8 @@ client.app = "wms"
87
91
  | `host` | API base URL | `https://panel.bapp.ro/api` |
88
92
  | `tenant` | Tenant ID (`x-tenant-id` header) | `None` |
89
93
  | `app` | App slug (`x-app-slug` header) | `"account"` |
94
+ | `timeout` | HTTP request timeout (seconds) | `30` |
95
+ | `max_retries` | Max retries on transient errors (5xx, 429, connection) | `3` |
90
96
 
91
97
  ### Methods
92
98
 
@@ -105,6 +111,7 @@ client.app = "wms"
105
111
  | `get_document_views(record)` | Extract available views from a record |
106
112
  | `get_document_url(record, output?, label?, variation?)` | Build a render/download URL |
107
113
  | `get_document_content(record, output?, label?, variation?)` | Fetch document bytes (PDF, HTML, JPG) |
114
+ | `download_document(record, dest, output?, label?, variation?)` | Stream document to file (memory-efficient) |
108
115
  | `list_tasks()` | List available task codes |
109
116
  | `detail_task(code)` | Get task configuration |
110
117
  | `run_task(code, payload?)` | Execute a task |
@@ -203,6 +210,95 @@ that can be polled via `bapp_framework.taskdata`. Use `run_task_async()` to
203
210
  handle this automatically — it polls until `finished` is `true` and returns the
204
211
  final task data (which includes a `file` URL when the task produces a download).
205
212
 
213
+ ## Signed embeds and flow webhooks
214
+
215
+ BAPP can open a page of your platform in a dialog (an iframe) and hand it a
216
+ short-lived signed token: a JWT with `typ` `bapp-embed+jwt`, signed with ES256,
217
+ valid for at most 5 minutes. Verify it **on your server only**; the page in the
218
+ browser just passes the token on to your server.
219
+
220
+ - `issuer` defaults to `https://panel.bapp.ro/api`;
221
+ give it explicitly as the API address of the project you serve.
222
+ - The keys come only from `{issuer}/.well-known/jwks.json` (cached in memory for
223
+ 5 minutes; an unknown `kid` refetches at most once a minute). The `jku`, `x5u`,
224
+ `jwk` and `x5c` headers of the token are ignored, and so is its `iss` as a key
225
+ address.
226
+ - `audience` is your origin and must match exactly: write it as the browser's
227
+ `location.origin` gives it (lowercase scheme and host, the port only when it is
228
+ not the default one, no path); a trailing slash is not needed.
229
+ - `tenants` is required: the tenant ids (strings) you accept, or the "any tenant"
230
+ constant, said explicitly. An empty list accepts none.
231
+ - A verified token gives `tenant`, `sub`, `email`, `email_verified`, `data`,
232
+ `jti` and `exp`. A token that fails is refused with one of these error codes:
233
+ `malformed`, `unsupported_alg`, `bad_typ`, `unknown_kid`, `bad_signature`,
234
+ `expired`, `not_yet_valid`, `bad_issuer`, `bad_audience`, `bad_tenant`,
235
+ `replayed`, `jwks_unavailable`.
236
+
237
+ Rules:
238
+
239
+ 1. `data` is what a flow of company `tenant` said, nothing more.
240
+ 2. Identify people by (the issuer you configured, `tenant`, `sub`), never by email. An email with `email_verified: false` proves nothing.
241
+ 3. Exchange the token at once for your own session; do not store or reuse it.
242
+ Use the `jti` hook of the verification (shown in the example below) to refuse
243
+ a second use of the same token.
244
+
245
+ Install the `embed` extra; it adds `cryptography`, needed only to verify
246
+ (signing and sending webhooks work without it):
247
+
248
+ ```bash
249
+ pip install "bapp-api-client[embed]"
250
+ ```
251
+
252
+ ```python
253
+ from bapp_api_client.embed import (
254
+ ANY_TENANT, EmbedVerifyError, send_flow_webhook, verify_embed_token,
255
+ )
256
+
257
+ try:
258
+ claims = verify_embed_token(
259
+ token,
260
+ audience="https://editor.exemplu.ro", # your origin
261
+ tenants=["42"], # or ANY_TENANT, said explicitly
262
+ issuer="https://exemplu.ro/api", # the API address of the project you serve
263
+ on_jti=remember_once, # (jti, exp) -> False when already used
264
+ )
265
+ except EmbedVerifyError as err:
266
+ ... # refuse the request; err.code says why
267
+ # claims.tenant, claims.sub, claims.email, claims.email_verified,
268
+ # claims.data, claims.jti, claims.exp
269
+
270
+ # Start a flow: the body is posted exactly as signed
271
+ result = send_flow_webhook(
272
+ "https://exemplu.ro/api/flow-hook/<tenant>/<flow>/", secret, body,
273
+ )
274
+ # result.status, result.body (decoded JSON or None), result.idempotency_key
275
+ ```
276
+
277
+ ### Flow webhooks
278
+
279
+ A BAPP flow can start from a webhook. The address and the secret come from BAPP
280
+ (the flow action "Arată secretul webhook", "Show webhook secret"). The body is
281
+ signed byte for byte (HMAC-SHA256 with the `X-Bapp-Timestamp`,
282
+ `X-Bapp-Idempotency-Key` and `X-Bapp-Signature` headers) and exactly those bytes
283
+ are posted.
284
+
285
+ - No API credentials are sent (no `Authorization`, no cookies, no tenant or app
286
+ headers) with the default client: the signature is the only authentication. A
287
+ client or session you pass in keeps its own settings, so it must carry no
288
+ credentials.
289
+ - Retries (transport errors, 429, 500, 502, 503, 504) keep the same idempotency
290
+ key, so the flow runs once; pass your own key to retry the same event later.
291
+ - A request repeated with an idempotency key that was already received is answered
292
+ `200` with `{"status": "duplicate"}` and no `run_id`.
293
+ - Leave the key unset to get a generated one. An explicitly empty key (`""`) is
294
+ sent as given, except in Go, where an empty `IdempotencyKey` counts as unset and
295
+ a key is generated. With an empty key BAPP deduplicates only on the timestamp
296
+ and the body; each retry is signed again with the current time, so retries are
297
+ in practice not deduplicated.
298
+ - The send helper does not check the address. Before sending to an address
299
+ received through `data`, check that its host is the host of the issuer you
300
+ configured, so that a flow author cannot point your server at another host.
301
+
206
302
  ## License
207
303
 
208
304
  MIT
@@ -3,6 +3,8 @@
3
3
  Official Python client for the [BAPP Auto API](https://www.bapp.ro). Provides a
4
4
  simple, consistent interface for authentication, entity CRUD, and task execution.
5
5
 
6
+ Verifying signed embed tokens needs the `embed` extra (`pip install "bapp-api-client[embed]"`); everything else, flow webhooks included, works without it.
7
+
6
8
  ## Getting Started
7
9
 
8
10
  ### 1. Install
@@ -74,6 +76,8 @@ client.app = "wms"
74
76
  | `host` | API base URL | `https://panel.bapp.ro/api` |
75
77
  | `tenant` | Tenant ID (`x-tenant-id` header) | `None` |
76
78
  | `app` | App slug (`x-app-slug` header) | `"account"` |
79
+ | `timeout` | HTTP request timeout (seconds) | `30` |
80
+ | `max_retries` | Max retries on transient errors (5xx, 429, connection) | `3` |
77
81
 
78
82
  ### Methods
79
83
 
@@ -92,6 +96,7 @@ client.app = "wms"
92
96
  | `get_document_views(record)` | Extract available views from a record |
93
97
  | `get_document_url(record, output?, label?, variation?)` | Build a render/download URL |
94
98
  | `get_document_content(record, output?, label?, variation?)` | Fetch document bytes (PDF, HTML, JPG) |
99
+ | `download_document(record, dest, output?, label?, variation?)` | Stream document to file (memory-efficient) |
95
100
  | `list_tasks()` | List available task codes |
96
101
  | `detail_task(code)` | Get task configuration |
97
102
  | `run_task(code, payload?)` | Execute a task |
@@ -190,6 +195,95 @@ that can be polled via `bapp_framework.taskdata`. Use `run_task_async()` to
190
195
  handle this automatically — it polls until `finished` is `true` and returns the
191
196
  final task data (which includes a `file` URL when the task produces a download).
192
197
 
198
+ ## Signed embeds and flow webhooks
199
+
200
+ BAPP can open a page of your platform in a dialog (an iframe) and hand it a
201
+ short-lived signed token: a JWT with `typ` `bapp-embed+jwt`, signed with ES256,
202
+ valid for at most 5 minutes. Verify it **on your server only**; the page in the
203
+ browser just passes the token on to your server.
204
+
205
+ - `issuer` defaults to `https://panel.bapp.ro/api`;
206
+ give it explicitly as the API address of the project you serve.
207
+ - The keys come only from `{issuer}/.well-known/jwks.json` (cached in memory for
208
+ 5 minutes; an unknown `kid` refetches at most once a minute). The `jku`, `x5u`,
209
+ `jwk` and `x5c` headers of the token are ignored, and so is its `iss` as a key
210
+ address.
211
+ - `audience` is your origin and must match exactly: write it as the browser's
212
+ `location.origin` gives it (lowercase scheme and host, the port only when it is
213
+ not the default one, no path); a trailing slash is not needed.
214
+ - `tenants` is required: the tenant ids (strings) you accept, or the "any tenant"
215
+ constant, said explicitly. An empty list accepts none.
216
+ - A verified token gives `tenant`, `sub`, `email`, `email_verified`, `data`,
217
+ `jti` and `exp`. A token that fails is refused with one of these error codes:
218
+ `malformed`, `unsupported_alg`, `bad_typ`, `unknown_kid`, `bad_signature`,
219
+ `expired`, `not_yet_valid`, `bad_issuer`, `bad_audience`, `bad_tenant`,
220
+ `replayed`, `jwks_unavailable`.
221
+
222
+ Rules:
223
+
224
+ 1. `data` is what a flow of company `tenant` said, nothing more.
225
+ 2. Identify people by (the issuer you configured, `tenant`, `sub`), never by email. An email with `email_verified: false` proves nothing.
226
+ 3. Exchange the token at once for your own session; do not store or reuse it.
227
+ Use the `jti` hook of the verification (shown in the example below) to refuse
228
+ a second use of the same token.
229
+
230
+ Install the `embed` extra; it adds `cryptography`, needed only to verify
231
+ (signing and sending webhooks work without it):
232
+
233
+ ```bash
234
+ pip install "bapp-api-client[embed]"
235
+ ```
236
+
237
+ ```python
238
+ from bapp_api_client.embed import (
239
+ ANY_TENANT, EmbedVerifyError, send_flow_webhook, verify_embed_token,
240
+ )
241
+
242
+ try:
243
+ claims = verify_embed_token(
244
+ token,
245
+ audience="https://editor.exemplu.ro", # your origin
246
+ tenants=["42"], # or ANY_TENANT, said explicitly
247
+ issuer="https://exemplu.ro/api", # the API address of the project you serve
248
+ on_jti=remember_once, # (jti, exp) -> False when already used
249
+ )
250
+ except EmbedVerifyError as err:
251
+ ... # refuse the request; err.code says why
252
+ # claims.tenant, claims.sub, claims.email, claims.email_verified,
253
+ # claims.data, claims.jti, claims.exp
254
+
255
+ # Start a flow: the body is posted exactly as signed
256
+ result = send_flow_webhook(
257
+ "https://exemplu.ro/api/flow-hook/<tenant>/<flow>/", secret, body,
258
+ )
259
+ # result.status, result.body (decoded JSON or None), result.idempotency_key
260
+ ```
261
+
262
+ ### Flow webhooks
263
+
264
+ A BAPP flow can start from a webhook. The address and the secret come from BAPP
265
+ (the flow action "Arată secretul webhook", "Show webhook secret"). The body is
266
+ signed byte for byte (HMAC-SHA256 with the `X-Bapp-Timestamp`,
267
+ `X-Bapp-Idempotency-Key` and `X-Bapp-Signature` headers) and exactly those bytes
268
+ are posted.
269
+
270
+ - No API credentials are sent (no `Authorization`, no cookies, no tenant or app
271
+ headers) with the default client: the signature is the only authentication. A
272
+ client or session you pass in keeps its own settings, so it must carry no
273
+ credentials.
274
+ - Retries (transport errors, 429, 500, 502, 503, 504) keep the same idempotency
275
+ key, so the flow runs once; pass your own key to retry the same event later.
276
+ - A request repeated with an idempotency key that was already received is answered
277
+ `200` with `{"status": "duplicate"}` and no `run_id`.
278
+ - Leave the key unset to get a generated one. An explicitly empty key (`""`) is
279
+ sent as given, except in Go, where an empty `IdempotencyKey` counts as unset and
280
+ a key is generated. With an empty key BAPP deduplicates only on the timestamp
281
+ and the body; each retry is signed again with the current time, so retries are
282
+ in practice not deduplicated.
283
+ - The send helper does not check the address. Before sending to an address
284
+ received through `data`, check that its host is the host of the issuer you
285
+ configured, so that a flow author cannot point your server at another host.
286
+
193
287
  ## License
194
288
 
195
289
  MIT
@@ -1,7 +1,10 @@
1
1
  """BAPP Auto API Client for Python."""
2
2
 
3
3
  import io
4
+ import random
4
5
  import time
6
+ import urllib.parse
7
+
5
8
  import requests
6
9
 
7
10
 
@@ -55,11 +58,15 @@ class BappApiClient:
55
58
  tenant=None,
56
59
  app="account",
57
60
  user_agent=None,
61
+ timeout=30,
62
+ max_retries=3,
58
63
  ):
59
64
  self.host = host.rstrip("/")
60
65
  self.tenant = tenant
61
66
  self.app = app
62
67
  self.user_agent = user_agent
68
+ self._timeout = timeout
69
+ self._max_retries = max_retries
63
70
  self._session = requests.Session()
64
71
  if bearer:
65
72
  self._session.headers["Authorization"] = f"Bearer {bearer}"
@@ -96,17 +103,29 @@ class BappApiClient:
96
103
  kwargs["data"] = data
97
104
  else:
98
105
  kwargs["json"] = json
99
- resp = self._session.request(
100
- method,
101
- f"{self.host}{path}",
102
- params=params,
103
- headers=self._headers(headers),
104
- **kwargs,
105
- )
106
- resp.raise_for_status()
107
- if resp.status_code == 204:
108
- return None
109
- return resp.json()
106
+
107
+ for attempt in range(self._max_retries + 1):
108
+ try:
109
+ resp = self._session.request(
110
+ method,
111
+ f"{self.host}{path}",
112
+ params=params,
113
+ headers=self._headers(headers),
114
+ timeout=self._timeout,
115
+ **kwargs,
116
+ )
117
+ if resp.status_code in (429, 502, 503, 504) and attempt < self._max_retries:
118
+ time.sleep(min(2 ** attempt + random.random(), 10))
119
+ continue
120
+ resp.raise_for_status()
121
+ if resp.status_code == 204:
122
+ return None
123
+ return resp.json()
124
+ except requests.exceptions.ConnectionError:
125
+ if attempt >= self._max_retries:
126
+ raise
127
+ time.sleep(min(2 ** attempt + random.random(), 10))
128
+ return None # unreachable
110
129
 
111
130
  # -- user ----------------------------------------------------------------
112
131
 
@@ -249,13 +268,13 @@ class BappApiClient:
249
268
  return None
250
269
 
251
270
  if view["type"] == "public_view":
252
- url = f"{self.host}/render/{token}?output={output}"
271
+ params = {"output": output}
253
272
  v = variation or view.get("default_variation")
254
273
  if v:
255
- url += f"&variation={v}"
274
+ params["variation"] = v
256
275
  if download:
257
- url += "&download=true"
258
- return url
276
+ params["download"] = "true"
277
+ return f"{self.host}/render/{token}?{urllib.parse.urlencode(params)}"
259
278
 
260
279
  # Legacy view_token
261
280
  if output == "pdf":
@@ -264,7 +283,7 @@ class BappApiClient:
264
283
  action = "pdf.context"
265
284
  else:
266
285
  action = "pdf.preview"
267
- return f"{self.host}/documents/{action}?token={token}"
286
+ return f"{self.host}/documents/{action}?{urllib.parse.urlencode({'token': token})}"
268
287
 
269
288
  def get_document_content(self, record, output="html", label=None,
270
289
  variation=None, download=False):
@@ -294,10 +313,47 @@ class BappApiClient:
294
313
  )
295
314
  if url is None:
296
315
  return None
297
- resp = self._session.get(url)
316
+ resp = self._session.get(url, timeout=self._timeout)
298
317
  resp.raise_for_status()
299
318
  return resp.content
300
319
 
320
+ def download_document(self, record, dest, output="html", label=None,
321
+ variation=None, download=False, chunk_size=8192):
322
+ """Stream document content directly to a file.
323
+
324
+ Like :meth:`get_document_content` but writes to *dest* in chunks,
325
+ avoiding loading the entire document into memory.
326
+
327
+ Args:
328
+ record: Entity dict from :meth:`list` or :meth:`get`.
329
+ dest: File path to write to.
330
+ output: Desired format — ``"html"``, ``"pdf"``, ``"jpg"``, or
331
+ ``"context"``.
332
+ label: Select a specific view by label.
333
+ variation: Variation code for ``public_view`` entries.
334
+ download: When *True* the server sends the response as an
335
+ attachment.
336
+ chunk_size: Size of chunks to stream (default 8192 bytes).
337
+
338
+ Returns:
339
+ *True* if the document was saved, *False* if no view tokens.
340
+
341
+ Raises:
342
+ requests.HTTPError: On non-2xx responses.
343
+ """
344
+ url = self.get_document_url(
345
+ record, output=output, label=label, variation=variation,
346
+ download=download,
347
+ )
348
+ if url is None:
349
+ return False
350
+ with self._session.get(url, stream=True, timeout=self._timeout) as resp:
351
+ resp.raise_for_status()
352
+ with open(dest, "wb") as f:
353
+ for chunk in resp.iter_content(chunk_size=chunk_size):
354
+ f.write(chunk)
355
+ return True
356
+
301
357
  # -- tasks ---------------------------------------------------------------
302
358
 
303
359
  def list_tasks(self):
@@ -0,0 +1,435 @@
1
+ """Embed token verification and signed flow webhooks.
2
+
3
+ ``verify_embed_token`` checks a ``bapp-embed+jwt`` page token (ES256) against the
4
+ JWKS published at ``{issuer}/.well-known/jwks.json``. It needs the optional
5
+ ``cryptography`` dependency::
6
+
7
+ pip install 'bapp-api-client[embed]'
8
+
9
+ ``sign_flow_webhook`` / ``send_flow_webhook`` sign and send a flow webhook with
10
+ an HMAC-SHA256 shared secret; they only need the standard library and
11
+ ``requests``.
12
+
13
+ Example::
14
+
15
+ from bapp_api_client.embed import verify_embed_token
16
+
17
+ claims = verify_embed_token(
18
+ token,
19
+ audience="https://exemplu.ro",
20
+ tenants=["42"],
21
+ issuer="https://exemplu.ro/api", # the API address of the platform that signed it
22
+ )
23
+ claims.tenant, claims.sub, claims.data
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import base64
29
+ import binascii
30
+ import hashlib
31
+ import hmac
32
+ import http.cookiejar
33
+ import json
34
+ import re
35
+ import secrets
36
+ import threading
37
+ import time
38
+ from dataclasses import dataclass
39
+ from typing import Any, Callable
40
+
41
+ import requests
42
+
43
+ __all__ = [
44
+ "ANY_TENANT",
45
+ "DEFAULT_ISSUER",
46
+ "EMBED_TOKEN_TYP",
47
+ "JWKS_PATH",
48
+ "EmbedVerifyError",
49
+ "EmbedClaims",
50
+ "JwksCache",
51
+ "verify_embed_token",
52
+ "sign_flow_webhook",
53
+ "WebhookResult",
54
+ "send_flow_webhook",
55
+ ]
56
+
57
+ ANY_TENANT = ("*",)
58
+ DEFAULT_ISSUER = "https://panel.bapp.ro/api"
59
+ EMBED_TOKEN_TYP = "bapp-embed+jwt"
60
+ JWKS_PATH = "/.well-known/jwks.json"
61
+
62
+ JWKS_TTL = 300
63
+ JWKS_REFETCH_INTERVAL = 60
64
+ JWKS_TIMEOUT = 10
65
+ RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
66
+
67
+ _EXTRA_MISSING = "verify_embed_token needs the 'embed' extra: pip install 'bapp-api-client[embed]'"
68
+ _SEGMENT = re.compile(r"^[A-Za-z0-9_-]+$")
69
+ _SIGNATURE = re.compile(r"^[A-Za-z0-9_-]*$")
70
+
71
+
72
+ class EmbedVerifyError(Exception):
73
+ """A token was refused. ``code`` is one of the shared error codes."""
74
+
75
+ def __init__(self, code: str):
76
+ super().__init__(code)
77
+ self.code = code
78
+
79
+
80
+ @dataclass(frozen=True)
81
+ class EmbedClaims:
82
+ tenant: str
83
+ sub: str | None
84
+ email: str | None
85
+ email_verified: bool
86
+ data: dict | None
87
+ jti: str
88
+ exp: int
89
+
90
+
91
+ def _b64url_decode(value: str) -> bytes:
92
+ return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
93
+
94
+
95
+ def _default_fetch(url: str) -> dict:
96
+ response = requests.get(url, timeout=JWKS_TIMEOUT)
97
+ if response.status_code != 200:
98
+ raise ValueError(f"JWKS answered HTTP {response.status_code}")
99
+ return response.json()
100
+
101
+
102
+ def _usable_key(jwk: Any, kid: str) -> bool:
103
+ if not isinstance(jwk, dict) or jwk.get("kid") != kid:
104
+ return False
105
+ if jwk.get("kty") != "EC" or jwk.get("crv") != "P-256":
106
+ return False
107
+ if "alg" in jwk and jwk["alg"] != "ES256":
108
+ return False
109
+ if "use" in jwk and jwk["use"] != "sig":
110
+ return False
111
+ for coordinate in ("x", "y"):
112
+ value = jwk.get(coordinate)
113
+ if not isinstance(value, str) or not _SEGMENT.match(value):
114
+ return False
115
+ try:
116
+ if len(_b64url_decode(value)) != 32:
117
+ return False
118
+ except (binascii.Error, ValueError):
119
+ return False
120
+ return True
121
+
122
+
123
+ def _find_key(jwks: Any, kid: str) -> dict | None:
124
+ keys = jwks.get("keys") if isinstance(jwks, dict) else None
125
+ if not isinstance(keys, list):
126
+ return None
127
+ for jwk in keys:
128
+ if _usable_key(jwk, kid):
129
+ return jwk
130
+ return None
131
+
132
+
133
+ class JwksCache:
134
+ """Per-issuer JWKS cache: entries live 300 s; an unknown ``kid`` refetches at
135
+ most once every 60 s. Thread-safe.
136
+
137
+ ``fetch(url) -> dict`` returns the JWKS document; the default is an HTTP GET
138
+ with a 10 s timeout.
139
+ """
140
+
141
+ def __init__(self, fetch: Callable[[str], dict] | None = None):
142
+ self._fetch = fetch or _default_fetch
143
+ self._entries: dict[str, tuple[float, dict]] = {}
144
+ self._lock = threading.Lock()
145
+
146
+ def _load(self, url: str, now: float) -> dict:
147
+ try:
148
+ document = self._fetch(url)
149
+ except Exception:
150
+ raise EmbedVerifyError("jwks_unavailable") from None
151
+ if not isinstance(document, dict) or not isinstance(document.get("keys"), list):
152
+ raise EmbedVerifyError("jwks_unavailable")
153
+ self._entries[url] = (now, document)
154
+ return document
155
+
156
+ def key_for(self, issuer: str, kid: str, now: float) -> dict:
157
+ """Return the JWK for ``kid`` from ``{issuer}/.well-known/jwks.json``."""
158
+ url = issuer.rstrip("/") + JWKS_PATH
159
+ with self._lock:
160
+ entry = self._entries.get(url)
161
+ if entry is None or now - entry[0] >= JWKS_TTL:
162
+ document = self._load(url, now)
163
+ fetched_at = now
164
+ else:
165
+ fetched_at, document = entry
166
+ key = _find_key(document, kid)
167
+ if key is None and now - fetched_at >= JWKS_REFETCH_INTERVAL:
168
+ key = _find_key(self._load(url, now), kid)
169
+ if key is None:
170
+ raise EmbedVerifyError("unknown_kid")
171
+ return key
172
+
173
+
174
+ _DEFAULT_CACHE = JwksCache()
175
+
176
+
177
+ def _is_number(value: Any) -> bool:
178
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
179
+
180
+
181
+ def _tenant_list(tenants: Any) -> tuple:
182
+ if tenants is None or isinstance(tenants, (str, bytes, bytearray, dict)):
183
+ raise TypeError("tenants must be a list of tenant ids or ANY_TENANT, not "
184
+ + type(tenants).__name__)
185
+ try:
186
+ return tuple(tenants)
187
+ except TypeError:
188
+ raise TypeError("tenants must be a list of tenant ids or ANY_TENANT, not "
189
+ + type(tenants).__name__) from None
190
+
191
+
192
+ def _parse(token: Any) -> tuple[dict, dict, bytes, bytes]:
193
+ if not isinstance(token, str):
194
+ raise EmbedVerifyError("malformed")
195
+ parts = token.split(".")
196
+ if len(parts) != 3:
197
+ raise EmbedVerifyError("malformed")
198
+ header_b64, payload_b64, signature_b64 = parts
199
+ if not _SEGMENT.match(header_b64) or not _SEGMENT.match(payload_b64) \
200
+ or not _SIGNATURE.match(signature_b64):
201
+ raise EmbedVerifyError("malformed")
202
+ try:
203
+ header = json.loads(_b64url_decode(header_b64).decode("utf-8"))
204
+ payload = json.loads(_b64url_decode(payload_b64).decode("utf-8"))
205
+ signature = _b64url_decode(signature_b64)
206
+ except (binascii.Error, ValueError, UnicodeDecodeError, RecursionError):
207
+ raise EmbedVerifyError("malformed") from None
208
+ if not isinstance(header, dict) or not isinstance(payload, dict):
209
+ raise EmbedVerifyError("malformed")
210
+ signing_input = (header_b64 + "." + payload_b64).encode("ascii")
211
+ return header, payload, signature, signing_input
212
+
213
+
214
+ def verify_embed_token(
215
+ token: str,
216
+ *,
217
+ audience: str,
218
+ tenants,
219
+ issuer: str = DEFAULT_ISSUER,
220
+ jwks: dict | None = None,
221
+ cache: JwksCache | None = None,
222
+ now: float | None = None,
223
+ leeway: int = 60,
224
+ on_jti: Callable[[str, int], bool] | None = None,
225
+ ) -> EmbedClaims:
226
+ """Verify a ``bapp-embed+jwt`` token and return its claims.
227
+
228
+ Args:
229
+ token: the token received by the external page.
230
+ audience: the origin of the external page (``aud``).
231
+ tenants: tenant ids accepted (strings), or ``ANY_TENANT``. An empty list accepts none.
232
+ issuer: the API address of the platform that signed the token; the keys come
233
+ only from ``{issuer}/.well-known/jwks.json``.
234
+ jwks: a JWKS document to use instead of fetching one (no network).
235
+ cache: the JWKS cache (default: one shared per process).
236
+ now: current Unix time (default: ``time.time()``).
237
+ leeway: clock tolerance in seconds for ``exp`` / ``nbf``.
238
+ on_jti: ``on_jti(jti, exp) -> bool``; ``False`` refuses the token as replayed.
239
+
240
+ Raises:
241
+ EmbedVerifyError: with ``.code`` set to the reason.
242
+ ImportError: when the ``embed`` extra (``cryptography``) is not installed.
243
+ """
244
+ try:
245
+ from cryptography.exceptions import InvalidSignature
246
+ from cryptography.hazmat.primitives import hashes
247
+ from cryptography.hazmat.primitives.asymmetric import ec
248
+ from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
249
+ except ImportError:
250
+ raise ImportError(_EXTRA_MISSING) from None
251
+
252
+ accepted = _tenant_list(tenants)
253
+ if now is None:
254
+ now = time.time()
255
+ issuer = issuer.rstrip("/")
256
+
257
+ # Token format.
258
+ header, payload, signature, signing_input = _parse(token)
259
+ # Algorithm and type.
260
+ if header.get("alg") != "ES256":
261
+ raise EmbedVerifyError("unsupported_alg")
262
+ if header.get("typ") != EMBED_TOKEN_TYP:
263
+ raise EmbedVerifyError("bad_typ")
264
+ # Key headers: jku, x5u, jwk, x5c are never read; the key is looked up by kid only.
265
+ kid = header.get("kid")
266
+ if not isinstance(kid, str):
267
+ raise EmbedVerifyError("unknown_kid")
268
+ # Signature length.
269
+ if len(signature) != 64:
270
+ raise EmbedVerifyError("bad_signature")
271
+ # Key lookup by kid.
272
+ if jwks is not None:
273
+ jwk = _find_key(jwks, kid)
274
+ if jwk is None:
275
+ raise EmbedVerifyError("unknown_kid")
276
+ else:
277
+ jwk = (cache or _DEFAULT_CACHE).key_for(issuer, kid, now)
278
+ # Signature.
279
+ try:
280
+ public_key = ec.EllipticCurvePublicNumbers(
281
+ int.from_bytes(_b64url_decode(jwk["x"]), "big"),
282
+ int.from_bytes(_b64url_decode(jwk["y"]), "big"),
283
+ ec.SECP256R1(),
284
+ ).public_key()
285
+ der = encode_dss_signature(int.from_bytes(signature[:32], "big"),
286
+ int.from_bytes(signature[32:], "big"))
287
+ public_key.verify(der, signing_input, ec.ECDSA(hashes.SHA256()))
288
+ except (InvalidSignature, ValueError):
289
+ raise EmbedVerifyError("bad_signature") from None
290
+ # Issuer.
291
+ iss = payload.get("iss")
292
+ if not isinstance(iss, str) or iss != issuer:
293
+ raise EmbedVerifyError("bad_issuer")
294
+ # Audience.
295
+ aud = payload.get("aud")
296
+ if not isinstance(aud, str) or aud != audience.rstrip("/"):
297
+ raise EmbedVerifyError("bad_audience")
298
+ # Expiry and not-before.
299
+ exp = payload.get("exp")
300
+ if not _is_number(exp):
301
+ raise EmbedVerifyError("malformed")
302
+ if now > exp + leeway:
303
+ raise EmbedVerifyError("expired")
304
+ nbf = payload.get("nbf")
305
+ if nbf is not None:
306
+ if not _is_number(nbf):
307
+ raise EmbedVerifyError("malformed")
308
+ if now < nbf - leeway:
309
+ raise EmbedVerifyError("not_yet_valid")
310
+ # Tenant.
311
+ tenant = payload.get("tenant")
312
+ if not isinstance(tenant, str):
313
+ raise EmbedVerifyError("malformed")
314
+ if "*" not in accepted and tenant not in accepted:
315
+ raise EmbedVerifyError("bad_tenant")
316
+ # Claims.
317
+ jti = payload.get("jti")
318
+ if not isinstance(jti, str):
319
+ raise EmbedVerifyError("malformed")
320
+ sub = payload.get("sub")
321
+ email = payload.get("email")
322
+ if (sub is not None and not isinstance(sub, str)) \
323
+ or (email is not None and not isinstance(email, str)):
324
+ raise EmbedVerifyError("malformed")
325
+ email_verified = payload.get("email_verified", False)
326
+ if email_verified is None:
327
+ email_verified = False
328
+ if not isinstance(email_verified, bool):
329
+ raise EmbedVerifyError("malformed")
330
+ data = payload.get("data")
331
+ if data is not None and not isinstance(data, dict):
332
+ raise EmbedVerifyError("malformed")
333
+ exp = int(exp)
334
+ # Replay hook.
335
+ if on_jti is not None and not on_jti(jti, exp):
336
+ raise EmbedVerifyError("replayed")
337
+ return EmbedClaims(tenant=tenant, sub=sub, email=email, email_verified=email_verified,
338
+ data=data, jti=jti, exp=exp)
339
+
340
+
341
+ def sign_flow_webhook(
342
+ secret: str,
343
+ body: bytes | str,
344
+ *,
345
+ timestamp: int | None = None,
346
+ idempotency_key: str | None = None,
347
+ ) -> dict[str, str]:
348
+ """Return the headers that sign ``body`` for a flow webhook.
349
+
350
+ The signature is ``sha256=`` + hex HMAC-SHA256(secret, f"{timestamp}.{key}." + body).
351
+ Without ``idempotency_key`` a random 32-character hex key is used; send the same
352
+ key again when retrying the same event.
353
+ """
354
+ if isinstance(body, str):
355
+ body = body.encode("utf-8")
356
+ if timestamp is None:
357
+ timestamp = int(time.time())
358
+ if idempotency_key is None:
359
+ idempotency_key = secrets.token_hex(16)
360
+ message = f"{timestamp}.{idempotency_key}.".encode("utf-8") + bytes(body)
361
+ digest = hmac.new(secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
362
+ return {
363
+ "X-Bapp-Timestamp": str(timestamp),
364
+ "X-Bapp-Idempotency-Key": idempotency_key,
365
+ "X-Bapp-Signature": "sha256=" + digest,
366
+ }
367
+
368
+
369
+ def _no_auth(request):
370
+ return request
371
+
372
+
373
+ @dataclass(frozen=True)
374
+ class WebhookResult:
375
+ status: int
376
+ body: Any
377
+ idempotency_key: str
378
+
379
+
380
+ def send_flow_webhook(
381
+ url: str,
382
+ secret: str,
383
+ body: bytes | str,
384
+ *,
385
+ idempotency_key: str | None = None,
386
+ max_retries: int = 3,
387
+ timeout: float = 10,
388
+ backoff: float = 0.5,
389
+ session=None,
390
+ ) -> WebhookResult:
391
+ """POST ``body`` (sent byte for byte as signed) to a flow webhook URL.
392
+
393
+ Retries transport errors and HTTP 429/500/502/503/504 up to ``max_retries``
394
+ times (waiting ``backoff * 2**attempt`` seconds), with a fresh timestamp and
395
+ the same idempotency key. Any other status, a redirect included, is returned
396
+ at once: redirects are not followed. With the default session no client
397
+ credentials are sent: the signature is the only authentication. A ``session``
398
+ you pass in is used as it is, so it must carry no credentials.
399
+ """
400
+ if isinstance(body, str):
401
+ body = body.encode("utf-8")
402
+ body = bytes(body)
403
+ if idempotency_key is None:
404
+ idempotency_key = secrets.token_hex(16)
405
+ own_session = session is None
406
+ if own_session:
407
+ session = requests.Session()
408
+ # A truthy no-op auth keeps requests from adding Authorization from ~/.netrc.
409
+ session.auth = _no_auth
410
+ # No cookie is kept, so a retry never sends one back.
411
+ session.cookies.set_policy(http.cookiejar.DefaultCookiePolicy(allowed_domains=[]))
412
+ try:
413
+ attempt = 0
414
+ while True:
415
+ headers = sign_flow_webhook(secret, body, idempotency_key=idempotency_key)
416
+ headers["Content-Type"] = "application/json"
417
+ try:
418
+ response = session.post(url, data=body, headers=headers, timeout=timeout,
419
+ allow_redirects=False)
420
+ except (requests.RequestException, OSError):
421
+ if attempt >= max_retries:
422
+ raise
423
+ else:
424
+ if response.status_code not in RETRY_STATUSES or attempt >= max_retries:
425
+ try:
426
+ payload = response.json()
427
+ except ValueError:
428
+ payload = None
429
+ return WebhookResult(status=response.status_code, body=payload,
430
+ idempotency_key=idempotency_key)
431
+ time.sleep(backoff * (2 ** attempt))
432
+ attempt += 1
433
+ finally:
434
+ if own_session:
435
+ session.close()
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "bapp-api-client"
7
- version = "0.4.4"
7
+ version = "0.6.0"
8
8
  description = "BAPP Auto API Client for Python"
9
9
  requires-python = ">=3.9"
10
10
  license = "MIT"
@@ -12,6 +12,9 @@ keywords = ["bapp", "api", "client"]
12
12
  readme = "README.md"
13
13
  dependencies = ["requests>=2.20"]
14
14
 
15
+ [project.optional-dependencies]
16
+ embed = ["cryptography>=41"]
17
+
15
18
  [project.urls]
16
19
  Homepage = "https://www.bapp.ro"
17
20
  Repository = "https://github.com/bapp-open/sdk-python"
@@ -1,12 +0,0 @@
1
- # Changelog
2
-
3
- ## 0.4.4
4
-
5
- - Initial release.
6
- - Authentication: Bearer (JWT/OAuth) and Token (API key).
7
- - Entity CRUD: list, get, create, update, patch, delete.
8
- - Paginated list responses with metadata (count, next, previous).
9
- - Entity introspection: list_introspect, detail_introspect.
10
- - Tasks: list, detail, run (sync and async with polling).
11
- - Long-running task support via run_task_async with automatic polling.
12
- - File uploads: automatic multipart/form-data detection.
File without changes