:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement docusign source (#73798)
Tom Owersede98b5e42e0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex c113e97cdf6f..e8da7dbc6a1c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -203,6 +203,7 @@ the row lists both.| dixa | HTTP | requests | ✅ || dockerhub | HTTP | requests | ✅ || docuseal | HTTP | requests | ✅ |+| docusign | HTTP | requests | ✅ || doit | HTTP | requests | ✅ || doppler | HTTP | requests | ✅ || dovetail | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -877,7 +878,6 @@ doesn't conflict with concurrent PRs.- dialpad- discord- display_video_360-- docusign- dodopayments- dolibarr- donorboxdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/canonical_descriptions.pynew file mode 100644index 000000000000..27cc71d687a5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/canonical_descriptions.py@@ -0,0 +1,115 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_ENVELOPES_DOCS = "https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopes/liststatuschanges/"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "envelopes": {+ "description": "Envelopes sent from the account — the container that holds the documents, recipients, and signing status for one agreement.",+ "docs_url": _ENVELOPES_DOCS,+ "columns": {+ "envelopeId": "Unique identifier of the envelope.",+ "status": "Current status of the envelope, such as sent, delivered, completed, declined, or voided.",+ "emailSubject": "Subject line of the email sent to all recipients of the envelope.",+ "sentDateTime": "Date and time the envelope was sent to the first recipient.",+ "createdDateTime": "Date and time the envelope was created as a draft.",+ "completedDateTime": "Date and time every recipient finished their required actions.",+ "deliveredDateTime": "Date and time the envelope was delivered to the recipients.",+ "statusChangedDateTime": "Date and time the envelope's status last changed. This is what the from_date filter matches on.",+ "voidedDateTime": "Date and time the envelope was voided.",+ "voidedReason": "Reason the sender gave for voiding the envelope.",+ "expireDateTime": "Date and time the envelope will expire if it has not been completed.",+ "purgeState": "Whether the envelope's documents and fields are queued for or already purged from DocuSign.",+ "sender": "Account user who sent the envelope, including their user ID, name, and email.",+ "customFieldsUri": "Relative URI of the envelope's custom fields.",+ "documentsUri": "Relative URI of the envelope's documents.",+ "recipientsUri": "Relative URI of the envelope's recipients.",+ },+ },+ "envelope_recipients": {+ "description": "One row per recipient on each envelope, flattened from the per-role recipient buckets (signers, carbon copies, agents, certified deliveries, and so on).",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/enveloperecipients/list/",+ "columns": {+ "envelopeId": "Envelope this recipient belongs to.",+ "recipientId": "Identifier of the recipient within its envelope. Only unique per envelope.",+ "recipientType": "Recipient role bucket the row came from, such as signers, carbonCopies, or certifiedDeliveries.",+ "recipientIdGuid": "Globally unique identifier DocuSign assigns to the recipient.",+ "name": "Full name of the recipient.",+ "email": "Email address the envelope was sent to.",+ "status": "Recipient's signing status, such as created, sent, delivered, completed, or declined.",+ "routingOrder": "Order in the signing sequence in which this recipient receives the envelope.",+ "signedDateTime": "Date and time the recipient completed signing.",+ "deliveredDateTime": "Date and time the envelope was delivered to the recipient.",+ "declinedDateTime": "Date and time the recipient declined to sign.",+ "declinedReason": "Reason the recipient gave for declining.",+ "clientUserId": "Set when the recipient is an embedded (captive) signer rather than one who signs by email.",+ "envelopeCreatedDateTime": "Creation time of the parent envelope, carried over for partitioning.",+ "envelopeStatusChangedDateTime": "Last status change of the parent envelope, carried over as the incremental cursor.",+ },+ },+ "envelope_documents": {+ "description": "Metadata for each document attached to an envelope. Document content itself is not synced.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopedocuments/list/",+ "columns": {+ "envelopeId": "Envelope this document belongs to.",+ "documentId": "Identifier of the document within its envelope. Restarts at 1 for every envelope.",+ "name": "File name of the document.",+ "type": "Document type, such as content, summary, or certificate of completion.",+ "uri": "Relative URI used to download the document.",+ "order": "Position of the document within the envelope.",+ "pages": "Number of pages in the document.",+ "containsPdfFormFields": "Whether the document carries PDF form fields.",+ "envelopeCreatedDateTime": "Creation time of the parent envelope, carried over for partitioning.",+ "envelopeStatusChangedDateTime": "Last status change of the parent envelope, carried over as the incremental cursor.",+ },+ },+ "templates": {+ "description": "Reusable envelope templates defined on the account.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/templates/templates/list/",+ "columns": {+ "templateId": "Unique identifier of the template.",+ "name": "Name of the template.",+ "description": "Description the author gave the template.",+ "shared": "Whether the template is shared with other users on the account.",+ "created": "Date and time the template was created.",+ "lastModified": "Date and time the template was last modified.",+ "lastUsed": "Date and time the template was last used to create an envelope.",+ "owner": "User who owns the template.",+ "emailSubject": "Default email subject applied to envelopes created from the template.",+ "folderName": "Folder the template is stored in.",+ "pageCount": "Number of pages across the template's documents.",+ },+ },+ "users": {+ "description": "Users belonging to the DocuSign account.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/users/users/list/",+ "columns": {+ "userId": "Unique identifier of the user.",+ "userName": "Display name of the user.",+ "email": "Email address of the user.",+ "userStatus": "Account status of the user, such as Active, Created, or Closed.",+ "userType": "Type of user, for example CompanyUser.",+ "permissionProfileId": "Identifier of the permission profile assigned to the user.",+ "permissionProfileName": "Name of the permission profile assigned to the user.",+ "createdDateTime": "Date and time the user was created.",+ "lastLogin": "Date and time of the user's most recent login.",+ "isAdmin": "Whether the user is an account administrator.",+ "jobTitle": "Job title recorded on the user's profile.",+ },+ },+ "folders": {+ "description": "Folders used to organize envelopes and templates on the account.",+ "docs_url": "https://developers.docusign.com/docs/esign-rest-api/reference/folders/folders/list/",+ "columns": {+ "folderId": "Unique identifier of the folder.",+ "name": "Name of the folder.",+ "type": "Folder type, such as sentitems, draft, inbox, or recyclebin.",+ "uri": "Relative URI of the folder.",+ "parentFolderId": "Identifier of the folder this one sits inside, when nested.",+ "owner": "User who owns the folder.",+ "hasSubFolders": "Whether the folder contains other folders.",+ "itemCount": "Number of items stored in the folder.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/docusign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/docusign.pynew file mode 100644index 000000000000..4f391f3ff706--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/docusign.py@@ -0,0 +1,388 @@+import time+import datetime as dt+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import jwt+import requests+from requests.auth import HTTPBasicAuth+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.settings import (+ API_VERSION_PATH,+ DEFAULT_LOOKBACK_DAYS,+ DOCUSIGN_ENDPOINTS,+ PAGE_SIZE,+ DocusignEndpointConfig,+)++# DocuSign runs completely separate demo and production stacks: an integration key only works+# against production once it has passed DocuSign's go-live review.+AUTH_HOSTS: dict[str, str] = {+ "production": "https://account.docusign.com",+ "demo": "https://account-d.docusign.com",+}++JWT_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"+# `impersonation` is what lets the JWT grant mint a token for `sub` without a browser round trip.+JWT_SCOPES = "signature impersonation"+JWT_ASSERTION_LIFETIME_SECONDS = 3600++REQUEST_TIMEOUT_SECONDS = 120++# Hard stop so a misbehaving endpoint that keeps advertising `nextUri` can't page forever.+MAX_PAGES = 20_000+++class DocusignAuthError(Exception):+ """Raised when DocuSign refuses to issue an access token."""+++class DocusignResumeConfig:+ """Resume cursor: the 0-based offset of the next page to request."""++ start_position: int++[email protected](frozen=True)+class DocusignCredentials:+ environment: str+ selection: str+ integration_key: str+ user_id: Optional[str] = None+ private_key: Optional[str] = None+ secret_key: Optional[str] = None+ refresh_token: Optional[str] = None+ account_id: Optional[str] = None++ @property+ def auth_host(self) -> str:+ host = AUTH_HOSTS.get(self.environment)+ if host is None:+ raise ValueError(f"Invalid DocuSign environment: {self.environment}")+ return host++ @property+ def secret_values(self) -> tuple[str, ...]:+ return tuple(v for v in (self.private_key, self.secret_key, self.refresh_token) if v)++[email protected](frozen=True)+class DocusignAccount:+ """The account-specific REST base URL DocuSign hands back from `/oauth/userinfo`."""++ account_id: str+ base_url: str+++def _auth_session(credentials: DocusignCredentials) -> requests.Session:+ # Token exchanges carry the private key / refresh token in the request and the freshly+ # minted access token in the response, so they stay out of HTTP sample capture entirely.+ return make_tracked_session(redact_values=credentials.secret_values, capture=False)+++def _api_session(credentials: DocusignCredentials) -> requests.Session:+ return make_tracked_session(+ headers={"Accept": "application/json"},+ redact_values=credentials.secret_values,+ )+++def _build_jwt_assertion(credentials: DocusignCredentials) -> str:+ if not credentials.user_id or not credentials.private_key:+ raise DocusignAuthError("JWT grant requires both an impersonated user ID and an RSA private key.")++ issued_at = int(time.time())+ claims: dict[str, Any] = {+ "iss": credentials.integration_key,+ "sub": credentials.user_id,+ # DocuSign wants the bare auth host, without a scheme.+ "aud": urlparse(credentials.auth_host).netloc,+ "iat": issued_at,+ "exp": issued_at + JWT_ASSERTION_LIFETIME_SECONDS,+ "scope": JWT_SCOPES,+ }+ try:+ return jwt.encode(claims, credentials.private_key, algorithm="RS256")+ except Exception as e:+ raise DocusignAuthError(+ "Your DocuSign RSA private key could not be read. Paste the full PEM key including the "+ "-----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY----- lines."+ ) from e+++def mint_access_token(session: requests.Session, credentials: DocusignCredentials) -> str:+ """Exchange the stored credentials for a short-lived (~1h) DocuSign access token."""+ url = f"{credentials.auth_host}/oauth/token"++ if credentials.selection == "jwt":+ response = session.post(+ url,+ data={"grant_type": JWT_GRANT_TYPE, "assertion": _build_jwt_assertion(credentials)},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ else:+ if not credentials.secret_key or not credentials.refresh_token:+ raise DocusignAuthError("Refresh token auth requires both a secret key and a refresh token.")+ response = session.post(+ url,+ data={"grant_type": "refresh_token", "refresh_token": credentials.refresh_token},+ auth=HTTPBasicAuth(credentials.integration_key, credentials.secret_key),+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ if not response.ok:+ raise DocusignAuthError(f"DocuSign token request failed: {_error_detail(response)}")++ token = response.json().get("access_token")+ if not token:+ raise DocusignAuthError("DocuSign token response did not contain an access token.")+ return str(token)+++def _error_detail(response: requests.Response) -> str:+ """DocuSign reports permanent auth problems in the body (`consent_required`, `invalid_grant`)."""+ try:+ body = response.json()+ except ValueError:+ return f"status={response.status_code}"+ if isinstance(body, dict):+ error = body.get("error") or body.get("errorCode")+ description = body.get("error_description") or body.get("message")+ if error:+ return f"status={response.status_code} error={error} description={description}"+ return f"status={response.status_code}"+++def resolve_account(session: requests.Session, credentials: DocusignCredentials, token: str) -> DocusignAccount:+ """Look up the account-specific REST base URL, which differs per account (na3, eu1, ...)."""+ response = session.get(+ f"{credentials.auth_host}/oauth/userinfo",+ headers={"Authorization": f"Bearer {token}"},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if not response.ok:+ raise DocusignAuthError(f"DocuSign userinfo request failed: {_error_detail(response)}")++ accounts = response.json().get("accounts") or []+ if not accounts:+ raise DocusignAuthError("The DocuSign user has no accounts available to this integration key.")++ if credentials.account_id:+ matched = next((a for a in accounts if str(a.get("account_id")) == credentials.account_id), None)+ if matched is None:+ raise DocusignAuthError(f"DocuSign account {credentials.account_id} is not accessible to this user.")+ else:+ matched = next((a for a in accounts if a.get("is_default")), accounts[0])++ base_uri = str(matched["base_uri"]).rstrip("/")+ return DocusignAccount(+ account_id=str(matched["account_id"]),+ base_url=f"{base_uri}/restapi/{API_VERSION_PATH}/accounts/{matched['account_id']}",+ )+++def _to_iso8601(value: Any) -> Optional[str]:+ """Coerce an incremental watermark to the UTC ISO-8601 string DocuSign's date filters take."""+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, dt.datetime):+ moment = value.replace(tzinfo=dt.UTC) if value.tzinfo is None else value.astimezone(dt.UTC)+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, dt.date):+ return dt.datetime.combine(value, dt.time.min, tzinfo=dt.UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ text = str(value).strip()+ return text or None+++def _default_from_date(start_date: Optional[str]) -> str:+ if start_date and start_date.strip():+ return start_date.strip()+ floor = dt.datetime.now(dt.UTC) - dt.timedelta(days=DEFAULT_LOOKBACK_DAYS)+ return floor.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _build_params(+ endpoint: DocusignEndpointConfig,+ start_position: int,+ from_date: Optional[str],+) -> dict[str, str]:+ params: dict[str, str] = {**endpoint.params, "count": str(PAGE_SIZE), "start_position": str(start_position)}+ if endpoint.date_filter_param and from_date:+ params[endpoint.date_filter_param] = from_date+ return params+++def _has_next_page(body: dict[str, Any], items: list[dict[str, Any]]) -> bool:+ """DocuSign advertises more rows via `nextUri`; fall back to a full page as the signal.++ We drive pagination off `start_position` arithmetic rather than following `nextUri`, because+ `nextUri` is a host-relative path and re-joining it against the account base URL is a+ needless place to get the account-specific host wrong.+ """+ if body.get("nextUri"):+ return True+ return len(items) >= PAGE_SIZE+++def _flatten_recipients(envelope: dict[str, Any], parent: dict[str, Any]) -> list[dict[str, Any]]:+ """Split the per-role recipient buckets DocuSign nests under `recipients` into flat rows."""+ recipients = envelope.get("recipients")+ if not isinstance(recipients, dict):+ return []++ rows: list[dict[str, Any]] = []+ for recipient_type, bucket in recipients.items():+ if not isinstance(bucket, list):+ # `recipients` also carries scalars like `recipientCount` alongside the role buckets.+ continue+ for recipient in bucket:+ if isinstance(recipient, dict):+ rows.append({**recipient, **parent, "recipientType": recipient_type})+ return rows+++def _flatten_envelope_children(+ endpoint: DocusignEndpointConfig, envelopes: list[dict[str, Any]]+) -> list[dict[str, Any]]:+ rows: list[dict[str, Any]] = []+ for envelope in envelopes:+ envelope_id = envelope.get("envelopeId")+ if not envelope_id:+ continue+ # Carry the parent's timestamps so the child table can be synced incrementally against+ # the same `from_date` window that produced its parent, and partitioned on a stable key.+ parent = {+ "envelopeId": str(envelope_id),+ "envelopeCreatedDateTime": envelope.get("createdDateTime"),+ "envelopeStatusChangedDateTime": envelope.get("statusChangedDateTime"),+ }++ if endpoint.derived_from_envelopes == "recipients":+ rows.extend(_flatten_recipients(envelope, parent))+ continue++ for key in endpoint.envelope_child_keys:+ children = envelope.get(key)+ if isinstance(children, list):+ rows.extend({**child, **parent} for child in children if isinstance(child, dict))+ break+ return rows+++def get_rows(+ credentials: DocusignCredentials,+ endpoint_name: str,+ start_date: Optional[str],+ resumable_source_manager: ResumableSourceManager[DocusignResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> Iterator[list[dict[str, Any]]]:+ endpoint = DOCUSIGN_ENDPOINTS[endpoint_name]++ auth_session = _auth_session(credentials)+ api_session = _api_session(credentials)+ token = mint_access_token(auth_session, credentials)+ account = resolve_account(auth_session, credentials, token)++ from_date: Optional[str] = None+ if endpoint.date_filter_param:+ watermark = _to_iso8601(db_incremental_field_last_value) if should_use_incremental_field else None+ from_date = watermark or _default_from_date(start_date)++ start_position = 0+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ start_position = resume.start_position+ logger.debug(f"Resuming DocuSign {endpoint_name} from start_position={start_position}")++ def request_page(position: int) -> dict[str, Any]:+ nonlocal token+ url = f"{account.base_url}{endpoint.path}?{urlencode(_build_params(endpoint, position, from_date))}"++ def _do() -> requests.Response:+ return api_session.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=REQUEST_TIMEOUT_SECONDS)++ response = _do()+ # Access tokens last ~1h; re-mint once if a long sync outlives one.+ if response.status_code == 401:+ token = mint_access_token(auth_session, credentials)+ response = _do()++ if not response.ok:+ logger.error(f"DocuSign API error: url={url}, {_error_detail(response)}")+ response.raise_for_status()++ body = response.json()+ return body if isinstance(body, dict) else {}++ for _ in range(MAX_PAGES):+ body = request_page(start_position)+ page = [item for item in (body.get(endpoint.data_key) or []) if isinstance(item, dict)]++ rows = _flatten_envelope_children(endpoint, page) if endpoint.derived_from_envelopes else page+ if rows:+ yield rows++ if not endpoint.supports_pagination or not page or not _has_next_page(body, page):+ break++ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on the primary+ # key) rather than skipping it.+ start_position += len(page)+ resumable_source_manager.save_state(DocusignResumeConfig(start_position=start_position))++ resumable_source_manager.clear_state()+++def validate_credentials(credentials: DocusignCredentials) -> tuple[bool, Optional[str]]:+ """Mint a token and resolve the account — the cheapest end-to-end proof the setup works."""+ try:+ session = _auth_session(credentials)+ token = mint_access_token(session, credentials)+ resolve_account(session, credentials, token)+ except DocusignAuthError as e:+ return False, str(e)+ except Exception:+ return False, "Could not reach DocuSign with the provided credentials."+ return True, None+++def docusign_source(+ credentials: DocusignCredentials,+ endpoint_name: str,+ start_date: Optional[str],+ resumable_source_manager: ResumableSourceManager[DocusignResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint = DOCUSIGN_ENDPOINTS[endpoint_name]++ return SourceResponse(+ name=endpoint_name,+ items=lambda: get_rows(+ credentials=credentials,+ endpoint_name=endpoint_name,+ start_date=start_date,+ resumable_source_manager=resumable_source_manager,+ logger=logger,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint.primary_key,+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint.partition_key else None,+ partition_format="month" if endpoint.partition_key else None,+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/settings.pynew file mode 100644index 000000000000..b6042da7e932--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/settings.py@@ -0,0 +1,144 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# eSignature REST API version segment. DocuSign pins its API behind an explicit path version,+# and v2.1 is the current generally available one.+API_VERSION_PATH = "v2.1"++# DocuSign caps list pages at 100 rows across the account-scoped list endpoints.+PAGE_SIZE = 100++# `listStatusChanges` requires one of from_date / envelope_ids / transaction_ids, and silently+# limits results to the last two years when from_date is omitted. We always send an explicit+# from_date so the window is ours, not DocuSign's.+DEFAULT_LOOKBACK_DAYS = 730+++@dataclass+class DocusignEndpointConfig:+ name: str+ # Path under `/restapi/v2.1/accounts/{accountId}`.+ path: str+ # Key the list of objects is nested under in the response body.+ data_key: str+ primary_key: list[str]+ # Query params sent on every page (page size and start_position are added by the transport).+ params: dict[str, str] = field(default_factory=dict)+ # Server-side filter name for the incremental watermark. Only set where DocuSign actually+ # filters on it; endpoints without one are full refresh.+ date_filter_param: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable creation-time field used for datetime partitioning — never an updated-at style+ # field, which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ # Endpoints derived from the envelope listing: DocuSign returns the child collection inline+ # when `include` is set, which avoids the per-envelope GET that DocuSign rate-limits to one+ # request per envelope per 15 minutes.+ derived_from_envelopes: Optional[str] = None+ # Candidate keys the inline child collection arrives under on each envelope. DocuSign is not+ # consistent between the list and per-envelope shapes, so we accept either spelling.+ envelope_child_keys: tuple[str, ...] = ()+ # False for endpoints that return everything in one response and ignore `start_position` —+ # re-requesting with an advanced offset would replay the same rows forever.+ supports_pagination: bool = True+++_ENVELOPE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "statusChangedDateTime",+ "type": IncrementalFieldType.DateTime,+ "field": "statusChangedDateTime",+ "field_type": IncrementalFieldType.DateTime,+ },+]++_DERIVED_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "envelopeStatusChangedDateTime",+ "type": IncrementalFieldType.DateTime,+ "field": "envelopeStatusChangedDateTime",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++DOCUSIGN_ENDPOINTS: dict[str, DocusignEndpointConfig] = {+ "envelopes": DocusignEndpointConfig(+ name="envelopes",+ path="/envelopes",+ data_key="envelopes",+ primary_key=["envelopeId"],+ # `status_changed` is the only ordering that lines up with what `from_date` filters on,+ # so the ascending watermark the pipeline checkpoints stays monotonic.+ params={"order_by": "status_changed", "order": "asc"},+ date_filter_param="from_date",+ incremental_fields=_ENVELOPE_INCREMENTAL_FIELDS,+ partition_key="createdDateTime",+ ),+ "envelope_recipients": DocusignEndpointConfig(+ name="envelope_recipients",+ path="/envelopes",+ data_key="envelopes",+ # Recipient ids are only unique within their envelope.+ primary_key=["envelopeId", "recipientId"],+ params={"order_by": "status_changed", "order": "asc", "include": "recipients"},+ date_filter_param="from_date",+ incremental_fields=_DERIVED_INCREMENTAL_FIELDS,+ partition_key="envelopeCreatedDateTime",+ derived_from_envelopes="recipients",+ envelope_child_keys=("recipients",),+ ),+ "envelope_documents": DocusignEndpointConfig(+ name="envelope_documents",+ path="/envelopes",+ data_key="envelopes",+ # Document ids restart at 1 in every envelope.+ primary_key=["envelopeId", "documentId"],+ params={"order_by": "status_changed", "order": "asc", "include": "documents"},+ date_filter_param="from_date",+ incremental_fields=_DERIVED_INCREMENTAL_FIELDS,+ partition_key="envelopeCreatedDateTime",+ derived_from_envelopes="documents",+ envelope_child_keys=("envelopeDocuments", "documents"),+ ),+ "templates": DocusignEndpointConfig(+ name="templates",+ path="/templates",+ data_key="envelopeTemplates",+ primary_key=["templateId"],+ params={"order_by": "modified", "order": "asc"},+ date_filter_param="from_date",+ incremental_fields=[+ {+ "label": "lastModified",+ "type": IncrementalFieldType.DateTime,+ "field": "lastModified",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ partition_key="created",+ ),+ "users": DocusignEndpointConfig(+ name="users",+ path="/users",+ data_key="users",+ primary_key=["userId"],+ params={"additional_info": "true"},+ partition_key="createdDateTime",+ ),+ "folders": DocusignEndpointConfig(+ name="folders",+ path="/folders",+ data_key="folders",+ primary_key=["folderId"],+ supports_pagination=False,+ ),+}++ENDPOINTS = tuple(DOCUSIGN_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in DOCUSIGN_ENDPOINTS.items() if config.incremental_fields+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.pyindex cde35621e300..d02b67eb2002 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/source.py@@ -1,13 +1,40 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.docusign import (+ DocusignCredentials,+ DocusignResumeConfig,+ docusign_source,+ validate_credentials as validate_docusign_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.docusign import (DocusignSourceConfig,)@@ -15,18 +42,211 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class DocusignSource(SimpleSource[DocusignSourceConfig]):+class DocusignSource(ResumableSource[DocusignSourceConfig, DocusignResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ supported_versions = ("v2.1",)+ default_version = "v2.1"+ api_docs_url = "https://developers.docusign.com/docs/esign-rest-api/reference/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DOCUSIGN+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "error=consent_required": "DocuSign needs one-time consent for this integration key. Grant consent for the impersonated user, then reconnect.",+ "error=invalid_grant": "DocuSign rejected these credentials. Check the integration key, the impersonated user ID, and that the key is authorized for the selected environment.",+ "error=unauthorized_client": "This DocuSign integration key is not authorized for the selected environment. Production keys have to pass DocuSign's go-live review first.",+ "DocuSign token request failed": "DocuSign could not issue an access token. Please check your integration key and credentials.",+ "401 Client Error: Unauthorized": "DocuSign authentication failed. Your credentials may have been revoked — please reconnect.",+ "403 Client Error: Forbidden": "DocuSign denied access. Check that the impersonated user can read this account's data.",+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.DOCUSIGN,category=DataWarehouseSourceCategory.SALES,label="DocuSign",+ caption="""Connect your DocuSign account to pull envelopes, recipients, documents, templates, users, and folders into the PostHog Data warehouse.++Create an integration key in [DocuSign Apps and Keys](https://apps.docusign.com/admin/apps-and-keys). JWT grant is the option to pick: add an RSA keypair to the key, grant consent once for the user you want to impersonate, and paste that user's API user ID. Production keys have to pass DocuSign's go-live review before they work outside the demo environment.""",iconPath="/static/services/docusign.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/docusign",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["esignature", "e-signature", "contracts", "agreements"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldSelectConfig(+ name="environment",+ label="Environment",+ required=True,+ defaultValue="production",+ options=[+ SourceFieldSelectConfigOption(label="Production", value="production"),+ SourceFieldSelectConfigOption(label="Demo (sandbox)", value="demo"),+ ],+ ),+ SourceFieldSelectConfig(+ name="auth_type",+ label="Authentication type",+ required=True,+ defaultValue="jwt",+ options=[+ SourceFieldSelectConfigOption(+ label="JWT grant",+ value="jwt",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="integration_key",+ label="Integration key",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="user_id",+ label="Impersonated user ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="private_key",+ label="RSA private key",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="-----BEGIN RSA PRIVATE KEY-----",+ secret=True,+ ),+ ],+ ),+ ),+ SourceFieldSelectConfigOption(+ label="Refresh token",+ value="refresh_token",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="integration_key",+ label="Integration key",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="00000000-0000-0000-0000-000000000000",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="secret_key",+ label="Secret key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="refresh_token",+ label="Refresh token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ ),+ ],+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="Leave blank to use your default account",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="2023-01-01T00:00:00Z (defaults to the last 2 years)",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: DocusignSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def _credentials(self, config: DocusignSourceConfig) -> DocusignCredentials:+ return DocusignCredentials(+ environment=config.environment,+ selection=config.auth_type.selection,+ integration_key=config.auth_type.integration_key,+ user_id=config.auth_type.user_id,+ private_key=config.auth_type.private_key,+ secret_key=config.auth_type.secret_key,+ refresh_token=config.auth_type.refresh_token,+ account_id=config.account_id,+ )++ def validate_credentials(+ self,+ config: DocusignSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ # The per-option fields are optional on the form (only one auth branch is ever filled+ # in), so the combination is checked here rather than by the config schema.+ auth = config.auth_type+ if auth.selection == "jwt" and not (auth.user_id and auth.private_key):+ return False, "JWT grant needs both an impersonated user ID and an RSA private key."+ if auth.selection == "refresh_token" and not (auth.secret_key and auth.refresh_token):+ return False, "Refresh token auth needs both a secret key and a refresh token."++ return validate_docusign_credentials(self._credentials(config))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DocusignResumeConfig]:+ return ResumableSourceManager[DocusignResumeConfig](inputs, DocusignResumeConfig)++ def source_for_pipeline(+ self,+ config: DocusignSourceConfig,+ resumable_source_manager: ResumableSourceManager[DocusignResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return docusign_source(+ credentials=self._credentials(config),+ endpoint_name=inputs.schema_name,+ start_date=config.start_date,+ resumable_source_manager=resumable_source_manager,+ logger=inputs.logger,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/conftest.pynew file mode 100644index 000000000000..c4f4bdc8d7e1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/conftest.py@@ -0,0 +1,115 @@+from collections.abc import Iterator+from typing import Any, Optional, cast++import pytest++import requests+import structlog+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.docusign import DocusignResumeConfig++_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)++PRIVATE_KEY_PEM: str = _KEY.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.TraditionalOpenSSL,+ encryption_algorithm=serialization.NoEncryption(),+).decode()++PUBLIC_KEY_PEM: str = (+ _KEY.public_key()+ .public_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ .decode()+)+++class FakeResponse:+ def __init__(self, status_code: int = 200, payload: Any = None, url: str = "https://na3.docusign.net") -> None:+ self.status_code = status_code+ self._payload = payload+ self.url = url++ @property+ def ok(self) -> bool:+ return self.status_code < 400++ @property+ def text(self) -> str:+ return str(self._payload)++ def json(self) -> Any:+ if self._payload is None:+ raise ValueError("no json body")+ return self._payload++ def raise_for_status(self) -> None:+ if self.ok:+ return+ label = "Client Error" if self.status_code < 500 else "Server Error"+ response = requests.Response()+ response.status_code = self.status_code+ response.url = self.url+ raise requests.HTTPError(f"{self.status_code} {label}: for url: {self.url}", response=response)+++class FakeSession:+ """Stand-in for the tracked session: pops queued responses and records every call."""++ def __init__(+ self,+ get_responses: Optional[list[FakeResponse]] = None,+ post_responses: Optional[list[FakeResponse]] = None,+ ) -> None:+ self.get_queue: list[FakeResponse] = list(get_responses or [])+ self.post_queue: list[FakeResponse] = list(post_responses or [])+ self.get_calls: list[tuple[str, dict[str, Any]]] = []+ self.post_calls: list[tuple[str, dict[str, Any]]] = []++ def get(self, url: str, **kwargs: Any) -> FakeResponse:+ self.get_calls.append((url, kwargs))+ if not self.get_queue:+ raise AssertionError(f"unexpected GET {url}")+ return self.get_queue.pop(0)++ def post(self, url: str, **kwargs: Any) -> FakeResponse:+ self.post_calls.append((url, kwargs))+ if not self.post_queue:+ raise AssertionError(f"unexpected POST {url}")+ return self.post_queue.pop(0)++ def as_session(self) -> requests.Session:+ """Hand this fake to helpers that take a real `requests.Session`."""+ return cast("requests.Session", self)+++class FakeResumeManager(ResumableSourceManager[DocusignResumeConfig]):+ """In-memory resume manager so transport tests don't need Redis."""++ def __init__(self, state: Optional[DocusignResumeConfig] = None) -> None:+ self.state = state+ self.saved: list[DocusignResumeConfig] = []+ self.cleared = False++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> Optional[DocusignResumeConfig]:+ return self.state++ def save_state(self, data: DocusignResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self.cleared = True+++def logger() -> Iterator[FilteringBoundLogger]:+ yield structlog.get_logger("docusign-test")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign.pynew file mode 100644index 000000000000..07ebf656dbf1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign.py@@ -0,0 +1,539 @@+import datetime as dt+from collections.abc import Iterable+from typing import Any, Optional, cast+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import jwt+import requests+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.docusign import (+ PAGE_SIZE,+ DocusignAuthError,+ DocusignCredentials,+ DocusignResumeConfig,+ _default_from_date,+ _to_iso8601,+ docusign_source,+ get_rows,+ mint_access_token,+ resolve_account,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.settings import DOCUSIGN_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.tests.conftest import (+ PRIVATE_KEY_PEM,+ PUBLIC_KEY_PEM,+ FakeResponse,+ FakeResumeManager,+ FakeSession,+)++_SESSION_FACTORY = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.docusign.docusign.make_tracked_session"+)++USERINFO_PAYLOAD: dict[str, Any] = {+ "sub": "user-guid",+ "accounts": [+ {"account_id": "111", "is_default": False, "account_name": "Old", "base_uri": "https://na2.docusign.net"},+ {"account_id": "222", "is_default": True, "account_name": "Main", "base_uri": "https://na3.docusign.net/"},+ ],+}++TOKEN_PAYLOAD: dict[str, Any] = {"access_token": "tok-1", "expires_in": 3600, "token_type": "Bearer"}++EXPECTED_BASE_URL = "https://na3.docusign.net/restapi/v2.1/accounts/222"+++def jwt_credentials(**overrides: Any) -> DocusignCredentials:+ defaults: dict[str, Any] = {+ "environment": "production",+ "selection": "jwt",+ "integration_key": "int-key",+ "user_id": "user-guid",+ "private_key": PRIVATE_KEY_PEM,+ }+ defaults.update(overrides)+ return DocusignCredentials(**defaults)+++def refresh_credentials(**overrides: Any) -> DocusignCredentials:+ defaults: dict[str, Any] = {+ "environment": "demo",+ "selection": "refresh_token",+ "integration_key": "int-key",+ "secret_key": "sek-ret",+ "refresh_token": "ref-tok",+ }+ defaults.update(overrides)+ return DocusignCredentials(**defaults)+++def envelope_page(count: int, offset: int = 0, next_uri: Optional[str] = None) -> dict[str, Any]:+ body: dict[str, Any] = {+ "envelopes": [+ {+ "envelopeId": f"env-{offset + i}",+ "status": "completed",+ "createdDateTime": "2024-01-01T00:00:00.0000000Z",+ "statusChangedDateTime": "2024-02-01T00:00:00.0000000Z",+ }+ for i in range(count)+ ],+ "resultSetSize": str(count),+ "startPosition": str(offset),+ }+ if next_uri is not None:+ body["nextUri"] = next_uri+ return body+++def run_rows(+ session: FakeSession,+ credentials: DocusignCredentials,+ endpoint: str,+ logger: FilteringBoundLogger,+ manager: Optional[FakeResumeManager] = None,+ **kwargs: Any,+) -> tuple[list[list[dict[str, Any]]], FakeResumeManager]:+ resume_manager = manager or FakeResumeManager()+ with mock.patch(_SESSION_FACTORY, return_value=session):+ batches = list(+ get_rows(+ credentials=credentials,+ endpoint_name=endpoint,+ start_date=kwargs.pop("start_date", None),+ resumable_source_manager=resume_manager,+ logger=logger,+ **kwargs,+ )+ )+ return batches, resume_manager+++class TestDocusignTransport:+ def test_jwt_assertion_carries_the_claims_docusign_requires(self) -> None:+ session = FakeSession(post_responses=[FakeResponse(200, TOKEN_PAYLOAD)])++ token = mint_access_token(session.as_session(), jwt_credentials())++ assert token == "tok-1"+ url, kwargs = session.post_calls[0]+ assert url == "https://account.docusign.com/oauth/token"+ assert kwargs["data"]["grant_type"] == "urn:ietf:params:oauth:grant-type:jwt-bearer"++ claims = jwt.decode(+ kwargs["data"]["assertion"],+ PUBLIC_KEY_PEM,+ algorithms=["RS256"],+ audience="account.docusign.com",+ )+ assert claims["iss"] == "int-key"+ assert claims["sub"] == "user-guid"+ assert claims["scope"] == "signature impersonation"+ assert claims["exp"] > claims["iat"]++ def test_demo_environment_signs_against_the_demo_auth_host(self) -> None:+ session = FakeSession(post_responses=[FakeResponse(200, TOKEN_PAYLOAD)])++ mint_access_token(session.as_session(), jwt_credentials(environment="demo"))++ url, kwargs = session.post_calls[0]+ assert url == "https://account-d.docusign.com/oauth/token"+ claims = jwt.decode(+ kwargs["data"]["assertion"],+ PUBLIC_KEY_PEM,+ algorithms=["RS256"],+ audience="account-d.docusign.com",+ )+ assert claims["iss"] == "int-key"++ def test_refresh_token_grant_uses_basic_auth_with_the_integration_key(self) -> None:+ session = FakeSession(post_responses=[FakeResponse(200, TOKEN_PAYLOAD)])++ mint_access_token(session.as_session(), refresh_credentials())++ url, kwargs = session.post_calls[0]+ assert url == "https://account-d.docusign.com/oauth/token"+ assert kwargs["data"] == {"grant_type": "refresh_token", "refresh_token": "ref-tok"}+ assert kwargs["auth"].username == "int-key"+ assert kwargs["auth"].password == "sek-ret"++ @pytest.mark.parametrize(+ "credentials,expected",+ [+ (jwt_credentials(private_key=None), "RSA private key"),+ (jwt_credentials(user_id=None), "impersonated user ID"),+ (refresh_credentials(refresh_token=None), "refresh token"),+ (refresh_credentials(secret_key=None), "secret key"),+ ],+ )+ def test_incomplete_credentials_fail_before_any_request(+ self, credentials: DocusignCredentials, expected: str+ ) -> None:+ session = FakeSession()++ with pytest.raises(DocusignAuthError) as excinfo:+ mint_access_token(session.as_session(), credentials)++ assert expected in str(excinfo.value)+ assert session.post_calls == []++ @pytest.mark.parametrize(+ "payload,expected_fragment",+ [+ ({"error": "consent_required"}, "error=consent_required"),+ ({"error": "invalid_grant", "error_description": "no soup"}, "error=invalid_grant"),+ ],+ )+ def test_token_errors_surface_docusigns_error_code(self, payload: dict[str, Any], expected_fragment: str) -> None:+ session = FakeSession(post_responses=[FakeResponse(400, payload)])++ with pytest.raises(DocusignAuthError) as excinfo:+ mint_access_token(session.as_session(), jwt_credentials())++ assert expected_fragment in str(excinfo.value)++ def test_token_response_without_access_token_is_an_auth_error(self) -> None:+ session = FakeSession(post_responses=[FakeResponse(200, {"expires_in": 3600})])++ with pytest.raises(DocusignAuthError):+ mint_access_token(session.as_session(), jwt_credentials())++ def test_resolve_account_defaults_to_the_users_default_account(self) -> None:+ session = FakeSession(get_responses=[FakeResponse(200, USERINFO_PAYLOAD)])++ account = resolve_account(session.as_session(), jwt_credentials(), "tok-1")++ assert account.account_id == "222"+ # Trailing slash on base_uri must not double up in the built URL.+ assert account.base_url == EXPECTED_BASE_URL+ assert session.get_calls[0][1]["headers"]["Authorization"] == "Bearer tok-1"++ def test_resolve_account_honors_an_explicitly_configured_account(self) -> None:+ session = FakeSession(get_responses=[FakeResponse(200, USERINFO_PAYLOAD)])++ account = resolve_account(session.as_session(), jwt_credentials(account_id="111"), "tok-1")++ assert account.base_url == "https://na2.docusign.net/restapi/v2.1/accounts/111"++ @pytest.mark.parametrize(+ "payload,account_id",+ [+ ({"accounts": []}, None),+ (USERINFO_PAYLOAD, "999"),+ ],+ )+ def test_resolve_account_rejects_unreachable_accounts(+ self, payload: dict[str, Any], account_id: Optional[str]+ ) -> None:+ session = FakeSession(get_responses=[FakeResponse(200, payload)])++ with pytest.raises(DocusignAuthError):+ resolve_account(session.as_session(), jwt_credentials(account_id=account_id), "tok-1")++ def test_pagination_follows_next_uri_and_advances_start_position(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[+ FakeResponse(200, USERINFO_PAYLOAD),+ FakeResponse(200, envelope_page(PAGE_SIZE, offset=0, next_uri="/restapi/next")),+ FakeResponse(200, envelope_page(3, offset=PAGE_SIZE)),+ ],+ )++ batches, manager = run_rows(session, jwt_credentials(), "envelopes", logger)++ assert [len(batch) for batch in batches] == [PAGE_SIZE, 3]+ positions = [+ parse_qs(urlparse(url).query)["start_position"][0] for url, _ in session.get_calls if "/envelopes" in url+ ]+ assert positions == ["0", str(PAGE_SIZE)]+ # Checkpoint written after the first page was yielded, then dropped once the walk finished.+ assert [state.start_position for state in manager.saved] == [PAGE_SIZE]+ assert manager.cleared is True++ def test_pagination_stops_on_a_short_page_without_next_uri(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, envelope_page(2))],+ )++ batches, manager = run_rows(session, jwt_credentials(), "envelopes", logger)++ assert len(batches) == 1+ assert manager.saved == []++ def test_unpaginated_endpoint_is_requested_once_even_on_a_full_page(self, logger: FilteringBoundLogger) -> None:+ folders = {"folders": [{"folderId": str(i), "name": f"f{i}"} for i in range(PAGE_SIZE)]}+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, folders)],+ )++ batches, _ = run_rows(session, jwt_credentials(), "folders", logger)++ assert len(batches) == 1+ assert len([url for url, _ in session.get_calls if "/folders" in url]) == 1++ def test_resume_starts_from_the_saved_offset(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, envelope_page(1, offset=400))],+ )++ _, manager = run_rows(+ session,+ jwt_credentials(),+ "envelopes",+ logger,+ manager=FakeResumeManager(DocusignResumeConfig(start_position=400)),+ )++ envelope_url = next(url for url, _ in session.get_calls if "/envelopes" in url)+ assert parse_qs(urlparse(envelope_url).query)["start_position"] == ["400"]+ assert manager.cleared is True++ def test_expired_access_token_is_reminted_once(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[+ FakeResponse(200, TOKEN_PAYLOAD),+ FakeResponse(200, {"access_token": "tok-2"}),+ ],+ get_responses=[+ FakeResponse(200, USERINFO_PAYLOAD),+ FakeResponse(401, {"errorCode": "USER_AUTHENTICATION_FAILED"}),+ FakeResponse(200, envelope_page(1)),+ ],+ )++ batches, _ = run_rows(session, jwt_credentials(), "envelopes", logger)++ assert len(batches) == 1+ assert len(session.post_calls) == 2+ retried_headers = session.get_calls[-1][1]["headers"]+ assert retried_headers["Authorization"] == "Bearer tok-2"++ def test_persistent_api_error_is_raised(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[+ FakeResponse(200, USERINFO_PAYLOAD),+ FakeResponse(403, {"errorCode": "USER_LACKS_PERMISSIONS"}),+ ],+ )++ with pytest.raises(requests.HTTPError):+ run_rows(session, jwt_credentials(), "envelopes", logger)++ def test_incremental_watermark_becomes_the_from_date_filter(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, envelope_page(1))],+ )++ run_rows(+ session,+ jwt_credentials(),+ "envelopes",+ logger,+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.datetime(2024, 5, 1, 12, 30, tzinfo=dt.UTC),+ )++ query = parse_qs(urlparse(next(url for url, _ in session.get_calls if "/envelopes" in url)).query)+ assert query["from_date"] == ["2024-05-01T12:30:00Z"]+ assert query["order_by"] == ["status_changed"]+ assert query["order"] == ["asc"]++ def test_full_refresh_falls_back_to_the_configured_start_date(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, envelope_page(1))],+ )++ run_rows(session, jwt_credentials(), "envelopes", logger, start_date="2021-01-01T00:00:00Z")++ query = parse_qs(urlparse(next(url for url, _ in session.get_calls if "/envelopes" in url)).query)+ assert query["from_date"] == ["2021-01-01T00:00:00Z"]++ def test_endpoint_without_a_date_filter_sends_no_from_date(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, {"users": [{"userId": "u1"}]})],+ )++ run_rows(+ session,+ jwt_credentials(),+ "users",+ logger,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01T00:00:00Z",+ )++ query = parse_qs(urlparse(next(url for url, _ in session.get_calls if "/users" in url)).query)+ assert "from_date" not in query++ def test_recipients_are_flattened_out_of_every_role_bucket(self, logger: FilteringBoundLogger) -> None:+ page = envelope_page(1)+ page["envelopes"][0]["recipients"] = {+ "signers": [{"recipientId": "1", "email": "[email protected]"}],+ "carbonCopies": [{"recipientId": "2", "email": "[email protected]"}],+ "recipientCount": "2",+ }+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, page)],+ )++ batches, _ = run_rows(session, jwt_credentials(), "envelope_recipients", logger)++ rows = batches[0]+ assert [row["recipientType"] for row in rows] == ["signers", "carbonCopies"]+ assert {row["envelopeId"] for row in rows} == {"env-0"}+ assert rows[0]["envelopeStatusChangedDateTime"] == "2024-02-01T00:00:00.0000000Z"+ assert rows[0]["envelopeCreatedDateTime"] == "2024-01-01T00:00:00.0000000Z"+ query = parse_qs(urlparse(session.get_calls[-1][0]).query)+ assert query["include"] == ["recipients"]++ @pytest.mark.parametrize("child_key", ["envelopeDocuments", "documents"])+ def test_documents_are_flattened_under_either_key_docusign_uses(+ self, child_key: str, logger: FilteringBoundLogger+ ) -> None:+ page = envelope_page(1)+ page["envelopes"][0][child_key] = [{"documentId": "1", "name": "contract.pdf"}]+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, page)],+ )++ batches, _ = run_rows(session, jwt_credentials(), "envelope_documents", logger)++ assert batches[0] == [+ {+ "documentId": "1",+ "name": "contract.pdf",+ "envelopeId": "env-0",+ "envelopeCreatedDateTime": "2024-01-01T00:00:00.0000000Z",+ "envelopeStatusChangedDateTime": "2024-02-01T00:00:00.0000000Z",+ }+ ]++ def test_envelopes_without_children_yield_no_rows_but_still_paginate(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[+ FakeResponse(200, USERINFO_PAYLOAD),+ FakeResponse(200, envelope_page(PAGE_SIZE, next_uri="/restapi/next")),+ FakeResponse(200, envelope_page(1, offset=PAGE_SIZE)),+ ],+ )++ batches, manager = run_rows(session, jwt_credentials(), "envelope_recipients", logger)++ assert batches == []+ assert [state.start_position for state in manager.saved] == [PAGE_SIZE]++ @pytest.mark.parametrize(+ "value,expected",+ [+ (None, None),+ (True, None),+ ("", None),+ ("2024-01-01T00:00:00Z", "2024-01-01T00:00:00Z"),+ (dt.datetime(2024, 3, 2, 4, 5, 6), "2024-03-02T04:05:06Z"),+ (+ dt.datetime(2024, 3, 2, 4, 5, 6, tzinfo=dt.timezone(dt.timedelta(hours=2))),+ "2024-03-02T02:05:06Z",+ ),+ (dt.date(2024, 3, 2), "2024-03-02T00:00:00Z"),+ ],+ )+ def test_watermark_coercion(self, value: Any, expected: Optional[str]) -> None:+ assert _to_iso8601(value) == expected++ def test_default_from_date_falls_back_to_a_bounded_lookback(self) -> None:+ fallback = _default_from_date(None)++ parsed = dt.datetime.strptime(fallback, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.UTC)+ assert dt.datetime.now(dt.UTC) - parsed > dt.timedelta(days=700)+ assert _default_from_date(" 2020-06-01T00:00:00Z ") == "2020-06-01T00:00:00Z"++ def test_validate_credentials_reports_docusign_error_text(self) -> None:+ session = FakeSession(post_responses=[FakeResponse(400, {"error": "consent_required"})])++ with mock.patch(_SESSION_FACTORY, return_value=session):+ valid, message = validate_credentials(jwt_credentials())++ assert valid is False+ assert message is not None and "consent_required" in message++ def test_validate_credentials_succeeds_when_an_account_resolves(self) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD)],+ )++ with mock.patch(_SESSION_FACTORY, return_value=session):+ assert validate_credentials(jwt_credentials()) == (True, None)++ def test_validate_credentials_swallows_transport_failures(self) -> None:+ with mock.patch(_SESSION_FACTORY, side_effect=requests.ConnectionError("boom")):+ valid, message = validate_credentials(jwt_credentials())++ assert valid is False+ assert message == "Could not reach DocuSign with the provided credentials."++ def test_unknown_environment_is_rejected(self) -> None:+ with pytest.raises(ValueError):+ _ = jwt_credentials(environment="staging").auth_host++ @pytest.mark.parametrize("endpoint_name", sorted(DOCUSIGN_ENDPOINTS))+ def test_source_response_matches_the_endpoint_catalog(+ self, endpoint_name: str, logger: FilteringBoundLogger+ ) -> None:+ endpoint = DOCUSIGN_ENDPOINTS[endpoint_name]++ response = docusign_source(+ credentials=jwt_credentials(),+ endpoint_name=endpoint_name,+ start_date=None,+ resumable_source_manager=FakeResumeManager(),+ logger=logger,+ )++ assert response.name == endpoint_name+ assert response.primary_keys == endpoint.primary_key+ assert response.sort_mode == "asc"+ if endpoint.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [endpoint.partition_key]+ else:+ assert response.partition_keys is None++ def test_source_response_items_are_lazy(self, logger: FilteringBoundLogger) -> None:+ session = FakeSession(+ post_responses=[FakeResponse(200, TOKEN_PAYLOAD)],+ get_responses=[FakeResponse(200, USERINFO_PAYLOAD), FakeResponse(200, envelope_page(2))],+ )++ response = docusign_source(+ credentials=jwt_credentials(),+ endpoint_name="envelopes",+ start_date=None,+ resumable_source_manager=FakeResumeManager(),+ logger=logger,+ )+ # Nothing is requested until the pipeline iterates.+ assert session.post_calls == []++ with mock.patch(_SESSION_FACTORY, return_value=session):+ batches = list(cast("Iterable[list[dict[str, Any]]]", response.items()))++ assert [len(batch) for batch in batches] == [2]+ assert isinstance(batches[0], list)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign_source.pynew file mode 100644index 000000000000..b0926008f708--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/docusign/tests/test_docusign_source.py@@ -0,0 +1,247 @@+from typing import Any, Optional++import pytest+from unittest import mock++import structlog++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.docusign import DocusignResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.settings import (+ DOCUSIGN_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.docusign.source import DocusignSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.docusign import (+ DocusignAuthTypeConfig,+ DocusignSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_VALIDATE = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.docusign.source.validate_docusign_credentials"+)+++def jwt_config(**overrides: Any) -> DocusignSourceConfig:+ auth_kwargs: dict[str, Any] = {+ "selection": "jwt",+ "integration_key": "int-key",+ "user_id": "user-guid",+ "private_key": "-----BEGIN RSA PRIVATE KEY-----",+ }+ auth_kwargs.update(overrides.pop("auth", {}))+ return DocusignSourceConfig(+ auth_type=DocusignAuthTypeConfig(**auth_kwargs),+ environment=overrides.pop("environment", "production"),+ account_id=overrides.pop("account_id", None),+ start_date=overrides.pop("start_date", None),+ )+++def source_inputs(schema_name: str, **overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": schema_name,+ "schema_id": "schema-id",+ "source_id": "source-id",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-id",+ "logger": structlog.get_logger("docusign-test"),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestDocusignSource:+ def setup_method(self) -> None:+ self.source = DocusignSource()+ self.team_id = 123++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.DOCUSIGN++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Docusign"+ assert config.label == "DocuSign"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/docusign.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/docusign"++ select_names = [f.name for f in config.fields if isinstance(f, SourceFieldSelectConfig)]+ assert select_names == ["environment", "auth_type"]+ input_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert input_names == ["account_id", "start_date"]++ def test_api_version_metadata_pins_what_the_transport_calls(self) -> None:+ assert self.source.supported_versions == ("v2.1",)+ assert self.source.default_version in self.source.supported_versions+ assert self.source.api_docs_url is not None+ assert self.source.api_docs_url.startswith("https://")++ @pytest.mark.parametrize("secret_field", ["private_key", "secret_key", "refresh_token"])+ def test_credential_fields_are_marked_secret(self, secret_field: str) -> None:+ auth_field = next(+ f+ for f in self.source.get_source_config.fields+ if isinstance(f, SourceFieldSelectConfig) and f.name == "auth_type"+ )+ candidates = [+ sub+ for option in auth_field.options+ for sub in (option.fields or [])+ if isinstance(sub, SourceFieldInputConfig) and sub.name == secret_field+ ]++ assert candidates, f"{secret_field} is not offered by any auth option"+ for field in candidates:+ assert field.secret is True+ assert field.type in (SourceFieldInputConfigType.PASSWORD, SourceFieldInputConfigType.TEXTAREA)++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(jwt_config(), self.team_id)++ assert [s.name for s in schemas] == list(ENDPOINTS)++ @pytest.mark.parametrize("endpoint_name", sorted(DOCUSIGN_ENDPOINTS))+ def test_incremental_support_matches_the_endpoint_catalog(self, endpoint_name: str) -> None:+ endpoint = DOCUSIGN_ENDPOINTS[endpoint_name]+ schema = self.source.get_schemas(jwt_config(), self.team_id, names=[endpoint_name])[0]++ # Only endpoints with a real server-side date filter advertise incremental sync.+ assert schema.supports_incremental is bool(endpoint.date_filter_param)+ assert [f["field"] for f in schema.incremental_fields] == [f["field"] for f in endpoint.incremental_fields]++ def test_get_schemas_filters_by_name(self) -> None:+ schemas = self.source.get_schemas(jwt_config(), self.team_id, names=["envelopes", "users"])++ assert {s.name for s in schemas} == {"envelopes", "users"}++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()++ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all(t["description"] for t in tables)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)+ for name, entry in descriptions.items():+ primary_keys = DOCUSIGN_ENDPOINTS[name].primary_key+ assert set(primary_keys) <= set(entry.get("columns", {})), name++ @pytest.mark.parametrize(+ "auth_overrides,expected_fragment",+ [+ ({"private_key": None}, "RSA private key"),+ ({"user_id": None}, "impersonated user ID"),+ (+ {"selection": "refresh_token", "user_id": None, "private_key": None, "secret_key": "s"},+ "refresh token",+ ),+ (+ {"selection": "refresh_token", "user_id": None, "private_key": None, "refresh_token": "r"},+ "secret key",+ ),+ ],+ )+ def test_validate_credentials_rejects_a_half_filled_auth_option(+ self, auth_overrides: dict[str, Any], expected_fragment: str+ ) -> None:+ config = jwt_config(auth=auth_overrides)++ with mock.patch(_VALIDATE) as probe:+ valid, message = self.source.validate_credentials(config, self.team_id)++ assert valid is False+ assert message is not None and expected_fragment in message+ # A half-filled form must not cost a DocuSign round trip.+ probe.assert_not_called()++ def test_validate_credentials_delegates_to_the_transport(self) -> None:+ with mock.patch(_VALIDATE, return_value=(True, None)) as probe:+ assert self.source.validate_credentials(jwt_config(account_id="222"), self.team_id) == (True, None)++ credentials = probe.call_args.args[0]+ assert credentials.environment == "production"+ assert credentials.selection == "jwt"+ assert credentials.integration_key == "int-key"+ assert credentials.account_id == "222"++ def test_validate_credentials_passes_the_transport_failure_through(self) -> None:+ with mock.patch(_VALIDATE, return_value=(False, "nope")):+ assert self.source.validate_credentials(jwt_config(), self.team_id) == (False, "nope")++ def test_resumable_manager_is_bound_to_the_docusign_cursor(self) -> None:+ manager = self.source.get_resumable_source_manager(source_inputs("envelopes"))++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is DocusignResumeConfig++ @pytest.mark.parametrize("endpoint_name", sorted(DOCUSIGN_ENDPOINTS))+ def test_source_for_pipeline_wires_the_endpoint_through(self, endpoint_name: str) -> None:+ manager: ResumableSourceManager[DocusignResumeConfig] = ResumableSourceManager(+ source_inputs(endpoint_name), DocusignResumeConfig+ )++ response = self.source.source_for_pipeline(jwt_config(), manager, source_inputs(endpoint_name))++ assert response.name == endpoint_name+ assert response.primary_keys == DOCUSIGN_ENDPOINTS[endpoint_name].primary_key++ def test_source_for_pipeline_only_forwards_the_watermark_when_incremental(self) -> None:+ target = "products.warehouse_sources.backend.temporal.data_imports.sources.docusign.source.docusign_source"+ manager: ResumableSourceManager[DocusignResumeConfig] = ResumableSourceManager(+ source_inputs("envelopes"), DocusignResumeConfig+ )+ inputs = source_inputs(+ "envelopes", should_use_incremental_field=False, db_incremental_field_last_value="2024-01-01T00:00:00Z"+ )++ with mock.patch(target) as build:+ self.source.source_for_pipeline(jwt_config(start_date="2020-01-01T00:00:00Z"), manager, inputs)++ assert build.call_args.kwargs["db_incremental_field_last_value"] is None+ assert build.call_args.kwargs["start_date"] == "2020-01-01T00:00:00Z"++ @pytest.mark.parametrize(+ "observed_error",+ [+ "DocuSign token request failed: status=400 error=consent_required description=None",+ "DocuSign token request failed: status=400 error=invalid_grant description=bad user",+ "401 Client Error: Unauthorized for url: https://na3.docusign.net/restapi/v2.1/accounts/222/envelopes",+ "403 Client Error: Forbidden for url: https://na3.docusign.net/restapi/v2.1/accounts/222/users",+ ],+ )+ def test_non_retryable_errors_match_permanent_failures(self, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "transient_error",+ [+ "429 Client Error: Too Many Requests for url: https://na3.docusign.net/restapi/v2.1/accounts/222/envelopes",+ "500 Server Error: Internal Server Error for url: https://na3.docusign.net/restapi",+ ],+ )+ def test_transient_errors_stay_retryable(self, transient_error: str) -> None:+ assert not any(key in transient_error for key in self.source.get_non_retryable_errors())++ def test_optional_config_fields_default_to_none(self) -> None:+ config: Optional[DocusignSourceConfig] = jwt_config()++ assert config is not None+ assert config.account_id is None+ assert config.start_date is None+ assert config.environment == "production"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/docusign.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/docusign.pyindex bb949527ae6f..48e2b8c6eeab 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/docusign.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/docusign.py@@ -1,9 +1,24 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class DocusignAuthTypeConfig(config.Config):+ integration_key: str+ selection: Literal["jwt", "refresh_token"] = "jwt"+ user_id: str | None = None+ private_key: str | None = None+ secret_key: str | None = None+ refresh_token: str | None = None++@config.configclass DocusignSourceConfig(config.Config):- pass+ auth_type: DocusignAuthTypeConfig+ environment: Literal["production", "demo"] = config.value(default="production")+ account_id: str | None = None+ start_date: str | None = None