Skip to content

: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.

feat(data-warehouse): implement 1password import source (#71229)

Tom Owersa276b427173f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 50f43cbd4e41..145661cc5d3e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -348,6 +348,7 @@ the row lists both.
| omnisend | HTTP | requests | ✅ |
| oncehub | HTTP | requests | ✅ |
| onepagecrm | HTTP | requests | ✅ |
+| onepassword | HTTP (cursor pagination) | requests | ✅ |
| onfleet | HTTP (cursor pagination) | requests | ✅ |
| open_exchange_rates | HTTP | requests | ✅ |
| openai | HTTP | requests | ✅ |
@@ -814,7 +815,6 @@ doesn't conflict with concurrent PRs.
- octopus_deploy
- onedrive
- onehundredms
-- onepassword
- onesignal
- open_data_dc
- opuswatch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 8b769d6c0919..0e58f5c64bf6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2953,7 +2953,8 @@ class OneHundredMsSourceConfig(config.Config):
@config.config
class OnePasswordSourceConfig(config.Config):
- pass
+ api_token: str
+ region: Literal["us", "ca", "eu", "enterprise"] = config.value(default="us")
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/canonical_descriptions.py
new file mode 100644
index 000000000000..cca35af065de
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/canonical_descriptions.py
@@ -0,0 +1,74 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official 1Password Events API reference:
+# https://developer.1password.com/docs/events-api/reference
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "sign_in_attempts": {
+ "description": (
+ "Attempts to sign in to a 1Password account: who attempted to sign in, from which client and "
+ "IP address, when the attempt was made, and — for failed attempts — the cause of the failure."
+ ),
+ "docs_url": "https://developer.1password.com/docs/events-api/reference#post-apiv2signinattempts",
+ "columns": {
+ "uuid": "The UUID of the sign-in attempt event.",
+ "session_uuid": "The UUID of the session that created the event.",
+ "timestamp": "The date and time of the sign-in attempt, in RFC 3339 format.",
+ "category": "The category of the sign-in attempt (e.g. success, credentials_failed, mfa_failed, firewall_failed).",
+ "type": "The details of the sign-in attempt (e.g. credentials_ok, password_secret_bad, ip_blocked).",
+ "country": "The ISO 3166 country code of the event's original IP address.",
+ "details": "Additional information about the sign-in attempt, such as the value blocked by a firewall rule.",
+ "target_user": "The user the sign-in attempt targeted (UUID, name, and email).",
+ "client": "The client used for the sign-in attempt: app name and version, platform, OS, and IP address.",
+ "location": "The geolocated city, region, country, latitude, and longitude of the attempt.",
+ "account_uuid": "The UUID of the account the user attempted to sign in to.",
+ },
+ },
+ "item_usages": {
+ "description": (
+ "Usage of items in shared vaults: which item was modified, accessed, or used, by whom, from "
+ "which client and IP address, and the vault where the item is stored."
+ ),
+ "docs_url": "https://developer.1password.com/docs/events-api/reference#post-apiv2itemusages",
+ "columns": {
+ "uuid": "The UUID of the item usage event.",
+ "timestamp": "The date and time the item was used, in RFC 3339 format.",
+ "used_version": "The version of the item that was used.",
+ "vault_uuid": "The UUID of the vault the item is stored in.",
+ "item_uuid": "The UUID of the item that was used.",
+ "user": "The user who used the item (UUID, name, and email).",
+ "client": "The client used to access the item: app name and version, platform, OS, and IP address.",
+ "location": "The geolocated city, region, country, latitude, and longitude of the usage.",
+ "action": "The action performed on the item (e.g. fill, reveal, secure-copy, share, export).",
+ "user_type": "The type of user (user, or external_user for MSP accounts).",
+ "user_account_uuid": "The UUID of the account the user belongs to (MSP accounts).",
+ "account_uuid": "The UUID of the account the item usage occurred in.",
+ },
+ },
+ "audit_events": {
+ "description": (
+ "Administrative actions performed by team members within a 1Password account: when an action "
+ "was performed and by whom, along with the type and object of the action."
+ ),
+ "docs_url": "https://developer.1password.com/docs/events-api/reference#post-apiv2auditevents",
+ "columns": {
+ "uuid": "The UUID of the audit event.",
+ "timestamp": "The date and time the action was performed, in RFC 3339 format.",
+ "actor_uuid": "The UUID of the user who performed the action.",
+ "actor_details": "The user who performed the action (UUID, name, and email).",
+ "actor_type": "The type of user who performed the action (user, or external_user for MSP accounts).",
+ "actor_account_uuid": "The UUID of the account the actor belongs to.",
+ "account_uuid": "The UUID of the account where the action was performed.",
+ "action": "The type of action that was performed (e.g. create, delete, grant, revoke, suspend).",
+ "object_type": "The type of object the action was performed on (e.g. account, device, user, gm for group membership).",
+ "object_uuid": "The UUID of the object the action was performed on.",
+ "aux_id": "An additional ID relevant to the action.",
+ "aux_uuid": "An additional UUID relevant to the action, such as the user a group membership change targeted.",
+ "aux_details": "Additional details about the object of the action, such as the affected user.",
+ "aux_info": "Additional information about the action, such as the role granted.",
+ "session": "The session that created the event: UUID, login time, device UUID, and IP address.",
+ "location": "The geolocated city, region, country, latitude, and longitude of the action.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/onepassword.posthog-doc.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/onepassword.posthog-doc.mdx
new file mode 100644
index 000000000000..590cea91d064
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/onepassword.posthog-doc.mdx
@@ -0,0 +1,77 @@
+<!--
+This is the user-facing source documentation. It belongs in the posthog.com repo at
+contents/docs/cdp/sources/onepassword.md (served at /docs/cdp/sources/onepassword). It is kept here only
+because a posthog.com checkout was not available when the source was implemented — copy it across and
+delete this file from this repo. Run `python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`
+once it lands.
+-->
+
+---
+
+title: Linking 1Password as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: OnePassword
+beta: true
+
+---
+
+import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'
+import SyncModes from '../_snippets/sync-modes.mdx'
+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'
+import AlphaRelease from '../_snippets/alpha-release.mdx'
+
+<AlphaRelease />
+
+This connector pulls your 1Password security event streams — sign-in attempts, item usages in shared
+vaults, and audit events — into the PostHog Data warehouse via the
+[1Password Events API](https://developer.1password.com/docs/events-api/), so you can join access and
+audit data with the rest of your analytics for security monitoring and compliance reporting.
+
+## Prerequisites
+
+The Events API requires a 1Password Business or Enterprise plan, and you need to be an owner or
+administrator of the 1Password account to set up an Events Reporting integration.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+1Password authenticates with an Events Reporting bearer token:
+
+1. [Set up an Events Reporting integration](https://support.1password.com/events-reporting/) in your
+ 1Password admin console.
+2. Issue a bearer token scoped to the event types you want to sync: sign-in attempts, item usages,
+ and audit events. Tables whose event type isn't included in the token can't be synced.
+3. Paste the token into the **Events Reporting token** field.
+4. Select the **Account region** matching where your 1Password account is hosted (1Password.com,
+ 1Password.ca, 1Password.eu, or 1Password Enterprise) — the Events API is served from a
+ region-specific address.
+
+## Sync modes
+
+<SyncModes />
+
+All three tables support incremental sync on the event's `timestamp`, using the API's server-side
+`start_time` filter. Events are immutable, so incremental sync is the recommended mode; the first
+sync pulls up to a year of retained history.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **401 Unauthorized** — the bearer token is invalid, revoked, or doesn't include the event type for
+ the table being synced (1Password returns 401 for both cases). Issue a new token with the required
+ event types in your 1Password admin console and reconnect. Also check that the selected account
+ region matches where your account is hosted.
+- **A table shows a permission warning in the schema picker** — the token wasn't issued with that
+ event type. Issue a new token that includes it, or deselect the table.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/onepassword.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/onepassword.py
new file mode 100644
index 000000000000..ec693c7dd6a1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/onepassword.py
@@ -0,0 +1,216 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+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.onepassword.settings import ONEPASSWORD_ENDPOINTS
+
+# The Events API is served from a regional host matching where the 1Password account is hosted.
+# The region field maps through this fixed allowlist, so the bearer token can only ever be sent
+# to a 1Password-owned host — an unknown region raises instead of building a URL.
+ONEPASSWORD_REGION_HOSTS: dict[str, str] = {
+ "us": "https://events.1password.com",
+ "ca": "https://events.1password.ca",
+ "eu": "https://events.1password.eu",
+ "enterprise": "https://events.ent.1password.com",
+}
+
+INTROSPECT_PATH = "/api/v2/auth/introspect"
+
+# ResetCursor accepts 1-1000 events per page.
+PAGE_LIMIT = 1000
+# ResetCursor's start_time defaults to only one hour ago when omitted, so the first sync must
+# always send one explicitly. The API serves the account's retained history; a year is a
+# reasonable bound for a first pull of security events.
+DEFAULT_LOOKBACK_DAYS = 365
+
+
+class OnePasswordRetryableError(Exception):
+ pass
+
+
+class OnePasswordResumeConfig:
+ # The last cursor returned by the API. 1Password cursors are persistent checkpoints into the
+ # event stream and remain valid across API sessions, so a resumed attempt just POSTs it back.
+ cursor: str | None = None
+
+
+def get_base_url(region: str) -> str:
+ host = ONEPASSWORD_REGION_HOSTS.get(region)
+ if host is None:
+ raise ValueError(f"Unknown 1Password region: {region}")
+ return host
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ }
+
+
+def _format_start_time(value: Any) -> str:
+ """Format an incremental watermark as the RFC 3339 timestamp `start_time` expects."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).isoformat()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()
+ return str(value)
+
+
+def _initial_start_time(should_use_incremental_field: bool, db_incremental_field_last_value: Any) -> str:
+ if should_use_incremental_field and db_incremental_field_last_value:
+ return _format_start_time(db_incremental_field_last_value)
+ return (datetime.now(UTC) - timedelta(days=DEFAULT_LOOKBACK_DAYS)).isoformat()
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ OnePasswordRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ body: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ response = session.post(url, headers=headers, json=body, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise OnePasswordRetryableError(f"1Password API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Log only status and URL — never the response body. Event payloads and error bodies can
+ # carry account-specific data that must not spill into application logs.
+ logger.error(f"1Password API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def introspect(region: str, api_token: str) -> dict[str, Any] | None:
+ """GET /api/v2/auth/introspect: the token's granted feature scopes, or None when the call fails.
+
+ A 200 confirms the token is genuine; the `features` list says which of the three event
+ streams it can read (auditevents, itemusages, signinattempts)."""
+ try:
+ response = make_tracked_session(redact_values=(api_token,), capture=False).get(
+ f"{get_base_url(region)}{INTROSPECT_PATH}", headers=_get_headers(api_token), timeout=10
+ )
+ if response.status_code != 200:
+ return None
+ data = response.json()
+ return data if isinstance(data, dict) else None
+ except Exception:
+ return None
+
+
+def get_rows(
+ region: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OnePasswordResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = ONEPASSWORD_ENDPOINTS[endpoint]
+ url = f"{get_base_url(region)}{config.path}"
+ headers = _get_headers(api_token)
+ # One session reused across every page so urllib3 keeps the connection alive. Register the
+ # token for value-based redaction and disable sample capture: responses carry names, emails,
+ # IPs, and locations of the customer's team members, which must never reach the sample bucket.
+ session = make_tracked_session(redact_values=(api_token,), capture=False)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.cursor:
+ logger.debug(f"1Password: resuming {endpoint} from saved cursor")
+ body: dict[str, Any] = {"cursor": resume.cursor}
+ else:
+ body = {
+ "limit": PAGE_LIMIT,
+ "start_time": _initial_start_time(should_use_incremental_field, db_incremental_field_last_value),
+ }
+
+ previous_cursor = resume.cursor if resume is not None else None
+ while True:
+ data = _fetch_page(session, url, headers, body, logger)
+
+ items = data.get("items") or []
+ cursor = data.get("cursor")
+ has_more = bool(data.get("has_more"))
+
+ if items:
+ yield items
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
+ # merge dedupes the re-pulled events on the `uuid` primary key.
+ if cursor:
+ resumable_source_manager.save_state(OnePasswordResumeConfig(cursor=cursor))
+
+ if not has_more or not cursor:
+ break
+ if not items and cursor == previous_cursor:
+ # Defensive: an empty page whose cursor didn't advance can't make progress; without
+ # this guard a misbehaving `has_more=true` response would loop forever.
+ logger.warning(f"1Password: {endpoint} returned has_more with a stale cursor and no items, stopping")
+ break
+
+ previous_cursor = cursor
+ body = {"cursor": cursor}
+
+
+def onepassword_source(
+ region: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OnePasswordResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = ONEPASSWORD_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ region=region,
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # The docs don't guarantee the cursor stream's ordering, and we couldn't verify it against
+ # a live account, so declare "desc": the watermark then persists only at successful job
+ # end (max timestamp seen), which is safe for any arrival order — per-batch "asc"
+ # checkpointing could advance the watermark past unseen older events if the stream ever
+ # arrives out of order. Mid-job resume still works via the saved cursor.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/settings.py
new file mode 100644
index 000000000000..097dea73ec62
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/settings.py
@@ -0,0 +1,55 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+_TIMESTAMP_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class OnePasswordEndpointConfig:
+ name: str
+ path: str
+ # The Events Reporting feature scope the bearer token needs for this endpoint, as reported
+ # by GET /api/v2/auth/introspect.
+ feature: str
+ # Every Events API stream is an immutable event log keyed by the event's `uuid`, with the
+ # server-side `start_time` filter on `timestamp` as the incremental cursor.
+ primary_keys: list[str] = field(default_factory=lambda: ["uuid"])
+ incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_TIMESTAMP_INCREMENTAL_FIELDS))
+ partition_key: str = "timestamp"
+ should_sync_default: bool = True
+
+
+# All three streams share the same cursor-paginated POST contract: the first request carries a
+# ResetCursor ({limit, start_time}), subsequent requests carry the returned cursor, and the
+# response is {cursor, has_more, items}. See https://developer.1password.com/docs/events-api/reference.
+ONEPASSWORD_ENDPOINTS: dict[str, OnePasswordEndpointConfig] = {
+ "sign_in_attempts": OnePasswordEndpointConfig(
+ name="sign_in_attempts",
+ path="/api/v2/signinattempts",
+ feature="signinattempts",
+ ),
+ "item_usages": OnePasswordEndpointConfig(
+ name="item_usages",
+ path="/api/v2/itemusages",
+ feature="itemusages",
+ ),
+ "audit_events": OnePasswordEndpointConfig(
+ name="audit_events",
+ path="/api/v2/auditevents",
+ feature="auditevents",
+ ),
+}
+
+ENDPOINTS = tuple(ONEPASSWORD_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ONEPASSWORD_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/source.py
index 2691a4b8ca8e..68e887dae654 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/source.py
@@ -1,19 +1,46 @@
-from typing import cast
+from typing import Optional, cast
from 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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OnePasswordSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.onepassword import (
+ ONEPASSWORD_REGION_HOSTS,
+ OnePasswordResumeConfig,
+ introspect,
+ onepassword_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ ONEPASSWORD_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class OnePasswordSource(SimpleSource[OnePasswordSourceConfig]):
+class OnePasswordSource(ResumableSource[OnePasswordSourceConfig, OnePasswordResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ONEPASSWORD
@@ -24,7 +51,148 @@ class OnePasswordSource(SimpleSource[OnePasswordSourceConfig]):
name=SchemaExternalDataSourceType.ONE_PASSWORD,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="1Password",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Pull your 1Password security event streams — sign-in attempts, item usages, and audit events — into the PostHog Data warehouse.
+
+This uses the 1Password Events API, which requires a 1Password Business or Enterprise plan. [Create an Events Reporting integration](https://support.1password.com/events-reporting/) in your 1Password admin console and issue a bearer token with the event types you want to sync:
+- Sign-in attempts
+- Item usages
+- Audit events
+
+Select the region where your 1Password account is hosted — the Events API is served from a region-specific address.""",
iconPath="/static/services/onepassword.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/onepassword",
+ keywords=["agilebits", "events api", "audit log", "security events", "siem"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="region",
+ label="Account region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="1Password.com (events.1password.com)", value="us"),
+ SourceFieldSelectConfigOption(label="1Password.ca (events.1password.ca)", value="ca"),
+ SourceFieldSelectConfigOption(label="1Password.eu (events.1password.eu)", value="eu"),
+ SourceFieldSelectConfigOption(
+ label="1Password Enterprise (events.ent.1password.com)", value="enterprise"
+ ),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Events Reporting token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="eyJhbGciOiJFUzI1NiIsIm...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # 1Password returns 401 both for an invalid/revoked token and for a token missing the
+ # endpoint's feature scope, so one message covers both. One entry per regional host.
+ message = (
+ "Your 1Password Events Reporting token is invalid, revoked, or missing the feature scope for this "
+ "table. Issue a new bearer token with the required event types in your 1Password admin console, "
+ "then reconnect."
+ )
+ return {
+ f"401 Client Error: Unauthorized for url: {host}": message for host in ONEPASSWORD_REGION_HOSTS.values()
+ }
+
+ def get_schemas(
+ self,
+ config: OnePasswordSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = ONEPASSWORD_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ # `start_time` is a genuine server-side timestamp filter on every stream.
+ supports_incremental=True,
+ # Events are immutable, but incremental runs re-pull a boundary window that only
+ # merge dedupes on `uuid` — append would materialize the overlap as duplicates.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: OnePasswordSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ introspection = introspect(config.region, config.api_token)
+ if introspection is None:
+ return False, "Invalid 1Password Events Reporting token. Check the token and the selected account region."
+
+ if schema_name is not None and schema_name in ONEPASSWORD_ENDPOINTS:
+ feature = ONEPASSWORD_ENDPOINTS[schema_name].feature
+ if feature not in (introspection.get("features") or []):
+ return (
+ False,
+ f"Your Events Reporting token doesn't include the `{feature}` event type. Issue a token with "
+ "that event type in your 1Password admin console.",
+ )
+
+ return True, None
+
+ def get_endpoint_permissions(
+ self, config: OnePasswordSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ introspection = introspect(config.region, config.api_token)
+ if introspection is None:
+ # Never block the schema picker on a failed probe; sync-time errors surface separately.
+ return dict.fromkeys(endpoints)
+
+ features = introspection.get("features") or []
+ result: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ endpoint_config = ONEPASSWORD_ENDPOINTS.get(endpoint)
+ if endpoint_config is None or endpoint_config.feature in features:
+ result[endpoint] = None
+ else:
+ result[endpoint] = (
+ f"Your Events Reporting token doesn't include the `{endpoint_config.feature}` event type"
+ )
+ return result
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OnePasswordResumeConfig]:
+ return ResumableSourceManager[OnePasswordResumeConfig](inputs, OnePasswordResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OnePasswordSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OnePasswordResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return onepassword_source(
+ region=config.region,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ 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/onepassword/tests/test_1password.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password.py
new file mode 100644
index 000000000000..eb3fce85d43c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password.py
@@ -0,0 +1,255 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword import onepassword
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.onepassword import (
+ OnePasswordResumeConfig,
+ _initial_start_time,
+ get_base_url,
+ get_rows,
+ introspect,
+ onepassword_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.settings import ONEPASSWORD_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: OnePasswordResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[OnePasswordResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> OnePasswordResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: OnePasswordResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _run_get_rows(
+ pages: list[dict[str, Any]],
+ manager: _FakeResumableManager,
+ **kwargs: Any,
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """Run get_rows against canned pages, returning (rows, request bodies sent)."""
+ bodies: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict, body: dict, logger: Any) -> dict[str, Any]:
+ bodies.append(body)
+ return pages[len(bodies) - 1]
+
+ rows: list[dict[str, Any]] = []
+ with patch.object(onepassword, "_fetch_page", fake_fetch):
+ for batch in get_rows(
+ region="us",
+ api_token="token",
+ endpoint="audit_events",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows, bodies
+
+
+class TestOnePasswordTransport:
+ @parameterized.expand(
+ [
+ ("us", "https://events.1password.com"),
+ ("ca", "https://events.1password.ca"),
+ ("eu", "https://events.1password.eu"),
+ ("enterprise", "https://events.ent.1password.com"),
+ ]
+ )
+ def test_region_maps_to_host(self, region: str, expected: str) -> None:
+ assert get_base_url(region) == expected
+
+ def test_unknown_region_raises(self) -> None:
+ # The bearer token must only ever be sent to a 1Password-owned host; an unmapped region
+ # value must fail instead of building a URL from it.
+ with pytest.raises(ValueError):
+ get_base_url("attacker.example.com")
+
+ @parameterized.expand(
+ [
+ # ResetCursor's start_time defaults to one hour ago server-side, so a first sync that
+ # omitted it (or sent nothing on full refresh) would silently drop all history.
+ ("first_sync_uses_default_lookback", False, None, "2025-07-15T12:00:00+00:00"),
+ ("full_refresh_ignores_watermark", False, "2026-07-01T00:00:00Z", "2025-07-15T12:00:00+00:00"),
+ (
+ "incremental_uses_datetime_watermark",
+ True,
+ datetime(2026, 7, 1, tzinfo=UTC),
+ "2026-07-01T00:00:00+00:00",
+ ),
+ ("incremental_uses_date_watermark", True, date(2026, 7, 1), "2026-07-01T00:00:00+00:00"),
+ ("incremental_passes_string_watermark", True, "2026-07-01T00:00:00Z", "2026-07-01T00:00:00Z"),
+ ]
+ )
+ def test_initial_start_time(self, _name: str, use_incremental: bool, watermark: Any, expected: str) -> None:
+ with freeze_time("2026-07-15T12:00:00Z"):
+ assert _initial_start_time(use_incremental, watermark) == expected
+
+ def test_pagination_follows_cursor_until_has_more_is_false(self) -> None:
+ pages = [
+ {"cursor": "c1", "has_more": True, "items": [{"uuid": "a"}, {"uuid": "b"}]},
+ {"cursor": "c2", "has_more": False, "items": [{"uuid": "c"}]},
+ ]
+ rows, bodies = _run_get_rows(pages, _FakeResumableManager())
+
+ assert [r["uuid"] for r in rows] == ["a", "b", "c"]
+ # First request is a ResetCursor; every subsequent request must carry only the cursor —
+ # resending the ResetCursor would restart the stream from start_time on every page.
+ assert bodies[0] == {"limit": onepassword.PAGE_LIMIT, "start_time": bodies[0]["start_time"]}
+ assert bodies[1] == {"cursor": "c1"}
+
+ def test_incremental_reset_cursor_starts_from_watermark(self) -> None:
+ pages = [{"cursor": "c1", "has_more": False, "items": [{"uuid": "a"}]}]
+ _, bodies = _run_get_rows(
+ pages,
+ _FakeResumableManager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-07-01T00:00:00Z",
+ )
+ assert bodies[0] == {"limit": onepassword.PAGE_LIMIT, "start_time": "2026-07-01T00:00:00Z"}
+
+ def test_state_is_saved_after_each_yielded_page(self) -> None:
+ pages = [
+ {"cursor": "c1", "has_more": True, "items": [{"uuid": "a"}]},
+ {"cursor": "c2", "has_more": False, "items": [{"uuid": "b"}]},
+ ]
+ manager = _FakeResumableManager()
+
+ def fake_fetch(session: Any, url: str, headers: dict, body: dict, logger: Any) -> dict[str, Any]:
+ return pages[0] if not manager.saved else pages[1]
+
+ with patch.object(onepassword, "_fetch_page", fake_fetch):
+ batches = get_rows(
+ region="us",
+ api_token="token",
+ endpoint="audit_events",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ )
+ first = next(batches)
+ # A crash while the pipeline holds this batch must re-enter BEFORE it (merge dedupes
+ # the re-pulled rows on uuid) — saving before the yield would skip the batch entirely.
+ assert first == [{"uuid": "a"}]
+ assert manager.saved == []
+ assert [b["uuid"] for b in next(batches)] == ["b"]
+ assert next(batches, None) is None
+ assert [s.cursor for s in manager.saved] == ["c1", "c2"]
+
+ def test_resume_posts_saved_cursor_instead_of_reset_cursor(self) -> None:
+ pages = [{"cursor": "c9", "has_more": False, "items": [{"uuid": "z"}]}]
+ manager = _FakeResumableManager(OnePasswordResumeConfig(cursor="c8"))
+ rows, bodies = _run_get_rows(pages, manager)
+ # Sending a ResetCursor on resume would re-walk the stream from start_time, re-paying the
+ # whole backfill after every heartbeat timeout.
+ assert bodies == [{"cursor": "c8"}]
+ assert [r["uuid"] for r in rows] == ["z"]
+
+ def test_empty_page_with_stale_cursor_terminates(self) -> None:
+ # Defensive guard: has_more=true with no items and a cursor that never advances would
+ # otherwise loop forever against the API.
+ pages = [
+ {"cursor": "c1", "has_more": True, "items": [{"uuid": "a"}]},
+ {"cursor": "c1", "has_more": True, "items": []},
+ ]
+ rows, bodies = _run_get_rows(pages, _FakeResumableManager())
+ assert [r["uuid"] for r in rows] == ["a"]
+ assert len(bodies) == 2
+
+ def test_empty_page_with_advancing_cursor_continues(self) -> None:
+ # An empty page whose cursor advanced is progress (the API can skip ahead); only a stale
+ # cursor means stuck.
+ pages = [
+ {"cursor": "c1", "has_more": True, "items": []},
+ {"cursor": "c2", "has_more": False, "items": [{"uuid": "a"}]},
+ ]
+ rows, bodies = _run_get_rows(pages, _FakeResumableManager())
+ assert [r["uuid"] for r in rows] == ["a"]
+ assert bodies[1] == {"cursor": "c1"}
+
+
+class TestFetchRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_status_codes_are_retried(self, _name: str, status: int) -> None:
+ bad = MagicMock(status_code=status)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"has_more": False, "items": []}
+ session = MagicMock()
+ session.post.side_effect = [bad, good]
+
+ with patch.object(onepassword._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = onepassword._fetch_page(
+ session, "https://events.1password.com/api/v2/auditevents", {}, {}, MagicMock()
+ )
+
+ assert result == {"has_more": False, "items": []}
+ assert session.post.call_count == 2
+
+ def test_unauthorized_raises_without_retry(self) -> None:
+ # Retrying a 401 can never succeed; it must surface immediately so the job fails with the
+ # non-retryable credential message instead of burning five attempts.
+ bad = requests.Response()
+ bad.status_code = 401
+ bad.url = "https://events.1password.com/api/v2/auditevents"
+ session = MagicMock()
+ session.post.return_value = bad
+
+ with pytest.raises(requests.HTTPError):
+ onepassword._fetch_page(session, "https://events.1password.com/api/v2/auditevents", {}, {}, MagicMock())
+ assert session.post.call_count == 1
+
+
+class TestIntrospect:
+ @parameterized.expand(
+ [
+ ("valid", 200, {"features": ["auditevents"]}, {"features": ["auditevents"]}),
+ ("unauthorized", 401, {"Error": {"Message": "Unauthorized"}}, None),
+ ("server_error", 500, {}, None),
+ ]
+ )
+ def test_status_maps_to_result(self, _name: str, status: int, payload: dict, expected: dict | None) -> None:
+ response = MagicMock(status_code=status)
+ response.json.return_value = payload
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(onepassword, "make_tracked_session", return_value=session):
+ assert introspect("us", "token") == expected
+
+ def test_network_error_returns_none(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with patch.object(onepassword, "make_tracked_session", return_value=session):
+ assert introspect("us", "token") is None
+
+
+class TestSourceResponse:
+ @parameterized.expand([(endpoint,) for endpoint in ONEPASSWORD_ENDPOINTS])
+ def test_response_shape(self, endpoint: str) -> None:
+ # Ordering of the cursor stream is not documented, so "desc" is required: it defers the
+ # watermark to successful job end, which is safe for any arrival order. Flipping to "asc"
+ # per-batch checkpointing could advance the watermark past unseen older events.
+ response = onepassword_source(
+ region="us",
+ api_token="token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.sort_mode == "desc"
+ assert response.primary_keys == ["uuid"]
+ assert response.partition_keys == ["timestamp"]
+ assert response.partition_mode == "datetime"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password_source.py
new file mode 100644
index 000000000000..f9d7ab76caf3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/onepassword/tests/test_1password_source.py
@@ -0,0 +1,166 @@
+from typing import Any, Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+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.generated_configs import OnePasswordSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.onepassword import (
+ OnePasswordResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.onepassword.source import OnePasswordSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+ALL_FEATURES_INTROSPECTION = {
+ "uuid": "OK41XEGLRTH4YKO5YRTCPNX3IU",
+ "features": ["auditevents", "itemusages", "signinattempts"],
+}
+
+
+def _source_inputs(schema_name: str, last_value: Optional[Any] = None, use_incremental: bool = False) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="timestamp" if use_incremental else None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestOnePasswordSource:
+ def setup_method(self) -> None:
+ self.source = OnePasswordSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ONEPASSWORD
+
+ def test_source_config_fields(self) -> None:
+ config = self.source.get_source_config
+ assert len(config.fields) == 2
+ region, token = config.fields
+ assert isinstance(region, SourceFieldSelectConfig)
+ assert region.name == "region"
+ assert [option.value for option in region.options] == ["us", "ca", "eu", "enterprise"]
+ assert isinstance(token, SourceFieldInputConfig)
+ assert token.name == "api_token"
+ assert token.type == SourceFieldInputConfigType.PASSWORD
+ assert token.required is True
+ assert token.secret is True
+
+ def test_source_is_released_as_alpha(self) -> None:
+ config = self.source.get_source_config
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/onepassword"
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static, no-I/O catalog, so the public docs table list must render.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=1, names=["audit_events"])
+ assert [s.name for s in schemas] == ["audit_events"]
+
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_every_stream_is_incremental_merge_only(self, endpoint: str) -> None:
+ # `start_time` is a genuine server-side filter on every stream; append is never offered
+ # because incremental runs re-pull a boundary window that only merge dedupes on `uuid`.
+ schema = next(s for s in self.source.get_schemas(MagicMock(), team_id=1) if s.name == endpoint)
+ assert schema.supports_incremental is True
+ assert schema.supports_append is False
+ assert [f["field"] for f in schema.incremental_fields] == ["timestamp"]
+
+ @parameterized.expand(
+ [
+ ("valid_token", ALL_FEATURES_INTROSPECTION, None, True),
+ ("invalid_token", None, None, False),
+ ("scoped_schema_with_feature", ALL_FEATURES_INTROSPECTION, "audit_events", True),
+ ("scoped_schema_missing_feature", {"features": ["itemusages"]}, "audit_events", False),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, introspection: dict | None, schema_name: str | None, expected_ok: bool
+ ) -> None:
+ config = OnePasswordSourceConfig(api_token="token", region="us")
+ with patch.object(source_module, "introspect", return_value=introspection):
+ ok, error = self.source.validate_credentials(config, team_id=1, schema_name=schema_name)
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_endpoint_permissions_report_missing_features(self) -> None:
+ # A token scoped to a subset of features must surface which tables it can't read so the
+ # schema picker can flag them — without blocking the reachable ones.
+ config = OnePasswordSourceConfig(api_token="token", region="us")
+ with patch.object(source_module, "introspect", return_value={"features": ["signinattempts"]}):
+ permissions = self.source.get_endpoint_permissions(config, team_id=1, endpoints=list(ENDPOINTS))
+ assert permissions["sign_in_attempts"] is None
+ assert permissions["item_usages"] is not None
+ assert permissions["audit_events"] is not None
+
+ def test_endpoint_permissions_never_block_on_probe_failure(self) -> None:
+ config = OnePasswordSourceConfig(api_token="token", region="us")
+ with patch.object(source_module, "introspect", return_value=None):
+ permissions = self.source.get_endpoint_permissions(config, team_id=1, endpoints=list(ENDPOINTS))
+ assert all(reason is None for reason in permissions.values())
+
+ @parameterized.expand(
+ [
+ ("us", "401 Client Error: Unauthorized for url: https://events.1password.com/api/v2/auditevents"),
+ ("eu", "401 Client Error: Unauthorized for url: https://events.1password.eu/api/v2/itemusages"),
+ (
+ "enterprise",
+ "401 Client Error: Unauthorized for url: https://events.ent.1password.com/api/v2/signinattempts",
+ ),
+ ]
+ )
+ def test_credential_errors_are_non_retryable_for_every_region(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs("audit_events"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OnePasswordResumeConfig
+
+ def test_source_for_pipeline_plumbs_config_and_endpoint(self) -> None:
+ config = OnePasswordSourceConfig(api_token="token", region="eu")
+ inputs = _source_inputs("audit_events", last_value="2026-07-01T00:00:00Z", use_incremental=True)
+ with patch.object(source_module, "onepassword_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["region"] == "eu"
+ assert kwargs["api_token"] == "token"
+ assert kwargs["endpoint"] == "audit_events"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-07-01T00:00:00Z"
+
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:
+ # A stale watermark on a full-refresh run would wrongly narrow the start_time window.
+ config = OnePasswordSourceConfig(api_token="token", region="us")
+ inputs = _source_inputs("audit_events", last_value="2026-07-01T00:00:00Z", use_incremental=False)
+ with patch.object(source_module, "onepassword_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ # Drift here (an endpoint renamed in settings but not here) silently drops the curated docs
+ # and falls back to LLM enrichment, so keep the two in lockstep.
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)