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): add 33 tables to the Cloudflare source (#73858)

Tom Owers2da47f14dbed
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/canonical_descriptions.py
index 62847139b833..daa23347ea57 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/canonical_descriptions.py
@@ -58,4 +58,602 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
},
},
+ "firewall_rules": {
+ "description": "A legacy firewall rule that applies an action to requests matching a filter.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/firewall/subresources/rules/",
+ "columns": {
+ "id": "The unique identifier of the firewall rule.",
+ "action": "The action to apply to a matched request.",
+ "filter": "The filter the rule matches requests with.",
+ "description": "An informative summary of the firewall rule.",
+ "paused": "When true, indicates that the firewall rule is currently paused.",
+ "priority": "The priority of the rule. A lower number indicates a higher priority.",
+ "products": "Cloudflare products the bypass action applies to.",
+ "ref": "A short reference tag that groups related firewall rules.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "filters": {
+ "description": "A filter expression that firewall rules match requests against.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/filters/",
+ "columns": {
+ "id": "The unique identifier of the filter.",
+ "expression": "The filter expression, written in the Cloudflare Rules language.",
+ "description": "An informative summary of the filter.",
+ "paused": "When true, indicates that the filter is currently paused.",
+ "ref": "A short reference tag that groups related filters.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "rulesets": {
+ "description": "A zone ruleset from the Ruleset Engine (WAF, transform, redirect, and other phases).",
+ "docs_url": "https://developers.cloudflare.com/api/resources/rulesets/",
+ "columns": {
+ "id": "The unique identifier of the ruleset.",
+ "name": "The human-readable name of the ruleset.",
+ "description": "An informative description of the ruleset.",
+ "kind": "The kind of the ruleset (e.g. managed, custom, zone).",
+ "phase": "The phase the ruleset runs in (e.g. http_request_firewall_custom).",
+ "version": "The version of the ruleset.",
+ "last_updated": "The timestamp of when the ruleset was last modified.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "rate_limits": {
+ "description": "A rate limiting rule that mitigates traffic exceeding a threshold in a time period.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/rate_limits/",
+ "columns": {
+ "id": "The unique identifier of the rate limit.",
+ "action": "The action to perform when the threshold is exceeded.",
+ "match": "Determines which traffic the rate limit counts towards the threshold.",
+ "bypass": "Criteria specifying when the rate limit should be bypassed.",
+ "description": "An informative summary of the rule.",
+ "disabled": "When true, indicates that the rate limit is currently disabled.",
+ "period": "The time in seconds over which matching traffic is counted.",
+ "threshold": "The request count that triggers the configured mitigation action.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "bot_management": {
+ "description": "The Bot Management configuration for a zone. One row per zone.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/bot_management/",
+ "columns": {
+ "fight_mode": "Whether Bot Fight Mode is enabled.",
+ "enable_js": "Whether invisible JavaScript detections are used to improve Bot Management.",
+ "ai_bots_protection": "Whether the rule blocking AI scrapers and crawlers is enabled.",
+ "crawler_protection": "Whether AI scrapers and crawlers are sent through a link maze.",
+ "content_bots_protection": "Whether the rule blocking content bots is enabled.",
+ "is_robots_txt_managed": "Whether Cloudflare manages the zone's robots.txt.",
+ "using_latest_model": "Whether the zone runs the latest bot detection model.",
+ "stale_zone_configuration": "Unauthorized settings currently active on the zone.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "load_balancers": {
+ "description": "A zone load balancer, including its pools and steering configuration.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/load_balancers/",
+ "columns": {
+ "id": "Unique identifier for the load balancer.",
+ "name": "The DNS hostname associated with the load balancer.",
+ "description": "Object description.",
+ "enabled": "Whether the load balancer is enabled.",
+ "proxied": "Whether the hostname is proxied through Cloudflare.",
+ "default_pools": "Pool IDs ordered by failover priority, used by default.",
+ "fallback_pool": "The pool ID used when all other pools are unhealthy.",
+ "region_pools": "Region codes mapped to the pool IDs serving them.",
+ "country_pools": "Country codes mapped to the pool IDs serving them.",
+ "pop_pools": "Cloudflare PoP identifiers mapped to the pool IDs serving them.",
+ "steering_policy": "The steering policy that selects a pool for each request.",
+ "session_affinity": "The type of session affinity the load balancer uses.",
+ "ttl": "Time to live of the DNS entry for unproxied load balancers.",
+ "zone_name": "Name of the zone the load balancer belongs to.",
+ "created_on": "Time at which the load balancer was created.",
+ "modified_on": "Time at which the load balancer was last modified.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "healthchecks": {
+ "description": "A standalone health check monitoring an origin server for a zone.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/healthchecks/",
+ "columns": {
+ "id": "Unique identifier for the health check.",
+ "name": "A short name identifying the health check.",
+ "description": "A human-readable description of the health check.",
+ "address": "The hostname or IP address of the origin server being checked.",
+ "type": "The protocol used for the health check (HTTP, HTTPS, or TCP).",
+ "status": "The current status of the origin server according to the health check.",
+ "failure_reason": "The current failure reason when the status is unhealthy.",
+ "check_regions": "Regions the health check runs from.",
+ "interval": "The interval in seconds between each health check.",
+ "timeout": "The timeout in seconds before the health check is marked failed.",
+ "retries": "The number of retries attempted before marking the origin unhealthy.",
+ "consecutive_fails": "Consecutive failures required before the origin turns unhealthy.",
+ "consecutive_successes": "Consecutive successes required before the origin turns healthy.",
+ "http_config": "Parameters specific to an HTTP or HTTPS health check.",
+ "tcp_config": "Parameters specific to a TCP health check.",
+ "suspended": "Whether health checks are suspended for this origin.",
+ "created_on": "Time at which the health check was created.",
+ "modified_on": "Time at which the health check was last modified.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "waiting_rooms": {
+ "description": "A waiting room that queues visitors for a host and path in a zone.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/waiting_rooms/",
+ "columns": {
+ "id": "Unique identifier for the waiting room.",
+ "name": "A unique name identifying the waiting room.",
+ "description": "A note with more details about the waiting room.",
+ "host": "The host name the waiting room is applied to.",
+ "path": "The path within the host the waiting room is enabled on.",
+ "additional_routes": "Additional host and path combinations the waiting room applies to.",
+ "new_users_per_minute": "The number of new users let into the route every minute.",
+ "total_active_users": "The number of active user sessions allowed on the route at once.",
+ "session_duration": "Lifetime in minutes of the cookie set for users who get access.",
+ "queueing_method": "The queueing method the waiting room uses.",
+ "queueing_status_code": "HTTP status code returned to a user while in the queue.",
+ "queue_all": "Whether all traffic to the route is sent to the waiting room.",
+ "suspended": "Whether traffic to the waiting room is suspended.",
+ "next_event_start_time": "ISO 8601 timestamp marking when the next event starts.",
+ "next_event_prequeue_start_time": "ISO 8601 timestamp marking when the next event starts queueing.",
+ "created_on": "Time at which the waiting room was created.",
+ "modified_on": "Time at which the waiting room was last modified.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "pagerules": {
+ "description": "A Page Rule that overrides settings or redirects requests matching a URL pattern.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/pagerules/",
+ "columns": {
+ "id": "Unique identifier for the Page Rule.",
+ "targets": "The rule targets evaluated on each request.",
+ "actions": "The actions performed when the targets match the request.",
+ "priority": "The priority of the rule. A higher number is processed first.",
+ "status": "The status of the Page Rule (active or disabled).",
+ "created_on": "Time at which the Page Rule was created.",
+ "modified_on": "Time at which the Page Rule was last modified.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "snippets": {
+ "description": "A snippet, the JavaScript code Cloudflare runs at the edge for a zone.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/snippets/",
+ "columns": {
+ "snippet_name": "The name identifying the snippet within its zone.",
+ "created_on": "Time at which the snippet was created.",
+ "modified_on": "Time at which the snippet was last modified.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "spectrum_apps": {
+ "description": "A Spectrum application proxying a TCP or UDP port through Cloudflare.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/spectrum/subresources/apps/",
+ "columns": {
+ "id": "Unique identifier for the Spectrum application.",
+ "protocol": "The port configuration at Cloudflare's edge (e.g. tcp/1000).",
+ "dns": "The name and type of DNS record for the Spectrum application.",
+ "origin_dns": "The name and type of DNS record for the origin.",
+ "origin_direct": "Origin IP addresses traffic is sent to.",
+ "origin_port": "The destination port at the origin.",
+ "traffic_type": "How data travels from the edge to the origin.",
+ "tls": "The type of TLS termination associated with the application.",
+ "ip_firewall": "Whether IP Access Rules are enabled for this application.",
+ "proxy_protocol": "Whether Proxy Protocol is enabled to the origin.",
+ "argo_smart_routing": "Whether Argo Smart Routing is enabled for this application.",
+ "edge_ips": "The anycast edge IP configuration for the application's hostname.",
+ "created_on": "Time at which the application was created.",
+ "modified_on": "Time at which the application was last modified.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "workers_routes": {
+ "description": "A route mapping a URL pattern in a zone to the Worker script that handles it.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/workers/subresources/routes/",
+ "columns": {
+ "id": "Unique identifier for the route.",
+ "pattern": "Pattern that incoming requests are matched against.",
+ "script": "Name of the script that runs when the route matches.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "logpush_jobs": {
+ "description": "A Logpush job that ships a zone's logs to a destination.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/logpush/subresources/jobs/",
+ "columns": {
+ "id": "Unique id of the job.",
+ "name": "Optional human readable job name.",
+ "dataset": "Name of the dataset the job pushes.",
+ "destination_conf": "Identifies the destination the logs are pushed to.",
+ "kind": "Differentiates Logpush jobs from Edge Log Delivery jobs.",
+ "enabled": "Whether the job is enabled.",
+ "error_message": "The last failure reason, when the job is currently failing.",
+ "last_error": "The last time the job failed.",
+ "last_complete": "The last time logs were successfully pushed.",
+ "output_options": "Requested fields, timestamp format, and other output settings.",
+ "max_upload_bytes": "The maximum uncompressed file size of a batch of logs.",
+ "max_upload_records": "The maximum number of log lines per batch.",
+ "max_upload_interval_seconds": "The maximum interval in seconds between log batches.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "custom_hostnames": {
+ "description": "A custom hostname (SSL for SaaS) pointing a third-party domain at a zone.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/custom_hostnames/",
+ "columns": {
+ "id": "Unique identifier for the custom hostname.",
+ "hostname": "The custom hostname that points to the zone via CNAME.",
+ "status": "Status of the hostname's activation.",
+ "ssl": "SSL properties for the custom hostname.",
+ "custom_origin_server": "The origin server requests for this hostname are sent to.",
+ "custom_origin_sni": "The SNI sent to the custom origin server during the TLS handshake.",
+ "custom_metadata": "Per-hostname key/value metadata.",
+ "ownership_verification": "The DNS record that can be placed to activate the hostname.",
+ "ownership_verification_http": "The token served over HTTP to activate the hostname.",
+ "verification_errors": "Errors encountered while activating the hostname.",
+ "created_at": "Time at which the hostname was created.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "ssl_certificate_packs": {
+ "description": "A certificate pack Cloudflare orders and deploys for a zone's hostnames.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/ssl/subresources/certificate_packs/",
+ "columns": {
+ "id": "Unique identifier for the certificate pack.",
+ "type": "Type of certificate pack.",
+ "status": "Status of the certificate pack.",
+ "hosts": "Host names covered by the certificate pack.",
+ "certificates": "Certificates in this pack.",
+ "primary_certificate": "Identifier of the primary certificate in the pack.",
+ "certificate_authority": "Certificate authority selected for the order.",
+ "validation_method": "Validation method selected for the order.",
+ "validation_records": "The certificates' validation records.",
+ "validation_errors": "Domain validation errors received from the certificate authority.",
+ "validity_days": "Validity in days selected for the order.",
+ "cloudflare_branding": "Whether Cloudflare branding was added to the order.",
+ "dcv_delegation_records": "DCV delegation records for domain validation.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "custom_certificates": {
+ "description": "A customer-uploaded SSL certificate installed on a zone.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/custom_certificates/",
+ "columns": {
+ "id": "Unique identifier for the custom certificate.",
+ "hosts": "Host names the certificate covers.",
+ "issuer": "The certificate authority that issued the certificate.",
+ "signature": "The type of hash used for the certificate.",
+ "status": "Status of the zone's custom SSL.",
+ "bundle_method": "The bundling method used when the certificate was uploaded.",
+ "priority": "The order in which the certificate is used in a request.",
+ "geo_restrictions": "The region where the private key can be held locally.",
+ "keyless_server": "The Keyless SSL server associated with the certificate.",
+ "policy_restrictions": "The policy restrictions set on the certificate.",
+ "custom_csr_id": "The identifier of the custom CSR that was used.",
+ "expires_on": "When the certificate from the authority expires.",
+ "uploaded_on": "When the certificate was uploaded to Cloudflare.",
+ "modified_on": "When the certificate was last modified.",
+ "zone_id": "Identifier of the zone the certificate belongs to.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "page_shield_scripts": {
+ "description": "A JavaScript file Page Shield observed loading on a zone's pages.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/page_shield/subresources/scripts/",
+ "columns": {
+ "id": "Unique identifier for the script.",
+ "url": "The URL the script was loaded from.",
+ "host": "The host serving the script.",
+ "hash": "The computed hash of the analyzed script.",
+ "page_urls": "Page URLs the script was seen on.",
+ "first_page_url": "The first page URL the script was seen on.",
+ "first_seen_at": "Time at which the script was first seen.",
+ "last_seen_at": "Time at which the script was last seen.",
+ "added_at": "Time at which the script was added to Page Shield.",
+ "fetched_at": "The timestamp of when the script was last fetched.",
+ "js_integrity_score": "The integrity score of the JavaScript content.",
+ "malware_score": "The malware score of the JavaScript content.",
+ "magecart_score": "The magecart score of the JavaScript content.",
+ "cryptomining_score": "The cryptomining score of the JavaScript content.",
+ "dataflow_score": "The dataflow score of the JavaScript content.",
+ "obfuscation_score": "The obfuscation score of the JavaScript content.",
+ "domain_reported_malicious": "Whether the script's domain was reported as malicious.",
+ "url_reported_malicious": "Whether the script's URL was reported as malicious.",
+ "malicious_domain_categories": "Categories the script's domain was flagged under.",
+ "malicious_url_categories": "Categories the script's URL was flagged under.",
+ "url_contains_cdn_cgi_path": "Whether the URL contains the /cdn-cgi/ path.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "page_shield_connections": {
+ "description": "An outbound connection Page Shield observed a zone's pages making.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/page_shield/subresources/connections/",
+ "columns": {
+ "id": "Unique identifier for the connection.",
+ "url": "The URL the connection was made to.",
+ "host": "The host the connection was made to.",
+ "page_urls": "Page URLs the connection was seen on.",
+ "first_page_url": "The first page URL the connection was seen on.",
+ "first_seen_at": "Time at which the connection was first seen.",
+ "last_seen_at": "Time at which the connection was last seen.",
+ "added_at": "Time at which the connection was added to Page Shield.",
+ "domain_reported_malicious": "Whether the connection's domain was reported as malicious.",
+ "url_reported_malicious": "Whether the connection's URL was reported as malicious.",
+ "malicious_domain_categories": "Categories the connection's domain was flagged under.",
+ "malicious_url_categories": "Categories the connection's URL was flagged under.",
+ "url_contains_cdn_cgi_path": "Whether the URL contains the /cdn-cgi/ path.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "api_gateway_operations": {
+ "description": "An API endpoint (method and path) API Shield tracks on a zone.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/api_gateway/subresources/operations/",
+ "columns": {
+ "operation_id": "Unique identifier for the operation.",
+ "method": "The HTTP method used to access the endpoint.",
+ "host": "The host the endpoint is served on.",
+ "endpoint": "The endpoint path, with path parameters templated in curly braces.",
+ "features": "Per-feature data such as thresholds and traffic statistics.",
+ "last_updated": "Time at which the operation was last updated.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "dns_analytics_report": {
+ "description": "Authoritative DNS query counts for a zone, grouped by query type and response code.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/dns/subresources/analytics/",
+ "columns": {
+ "queryType": "The DNS record type that was queried (e.g. A, AAAA, MX).",
+ "responseCode": "The DNS response code Cloudflare returned (e.g. NOERROR, NXDOMAIN).",
+ "queryCount": "Number of DNS queries in this group.",
+ "uncachedCount": "Number of queries in this group that were not served from cache.",
+ "_zone_id": "Identifier of the parent zone, injected during the fan-out sync.",
+ },
+ },
+ "audit_logs": {
+ "description": "An audit log entry recording a change made in a Cloudflare account.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/accounts/subresources/logs/",
+ "columns": {
+ "id": "A string that uniquely identifies the audit log.",
+ "when": "A UTC RFC 3339 timestamp of when the logged action occurred.",
+ "action": "The action that was taken, including whether it succeeded.",
+ "actor": "The user or token that performed the action.",
+ "owner": "The account or user that owns the affected resource.",
+ "resource": "The resource the action was performed on.",
+ "interface": "The source of the event (e.g. API, dashboard).",
+ "metadata": "Extra context about the action. Varies between actions.",
+ "oldValue": "The value of the resource before it was modified.",
+ "newValue": "The new value of the resource that was modified.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "billing_usage": {
+ "description": "Billable product usage for an account, one row per time period.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/accounts/",
+ "columns": {
+ "ts": "Unix timestamp (epoch seconds) for the start of this time period.",
+ "workersRequests": "Number of Workers requests in this time period.",
+ "workersKVReads": "Number of Workers KV reads in this time period.",
+ "loadBalancingQueries": "Number of load balancing DNS queries in this time period.",
+ "rateLimitingRequestsAllowed": "Number of rate limiting requests allowed in this time period.",
+ "argoAcceleratedBytes": "Number of Argo accelerated bytes in this time period.",
+ "spectrumBytesTransferred": "Number of Spectrum bytes transferred in this time period.",
+ "imageResizingRequests": "Number of Image Resizing requests in this time period.",
+ "mediaUniqueTransformations": "Number of unique image transformations in this time period.",
+ "streamMinutesViewed": "Number of Stream billable minutes viewed in this time period.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "billable_usage": {
+ "description": "A billable usage and cost record for an account, in the FOCUS billing format.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/billing/",
+ "columns": {
+ "BillingAccountId": "Public identifier of the Cloudflare account.",
+ "BillingAccountName": "Display name of the Cloudflare account.",
+ "BillingCurrency": "Currency the charge was billed in (ISO 4217).",
+ "BillingPeriodStart": "Inclusive start of the billing cycle containing this record.",
+ "BillingPeriodEnd": "Exclusive end of the billing cycle containing this record.",
+ "ChargePeriodStart": "Inclusive start of the interval the usage was consumed in.",
+ "ChargePeriodEnd": "Exclusive end of the interval the usage was consumed in.",
+ "ChargeCategory": "Highest-level classification of how the charge is billed.",
+ "ChargeClass": "Whether the row corrects charges from a previous billing period.",
+ "ChargeDescription": "Summary of the charge's purpose and price.",
+ "ChargeFrequency": "How often the charge occurs.",
+ "ConsumedQuantity": "Measured usage amount within the charge period.",
+ "ConsumedUnit": "Unit of measure for the consumed quantity.",
+ "PricingQuantity": "Volume of the service used or purchased, based on the pricing unit.",
+ "PricingUnit": "Measurement unit used to determine unit prices.",
+ "ListUnitPrice": "Published unit price, excluding discounts.",
+ "ListCost": "List unit price multiplied by the pricing quantity.",
+ "ContractedUnitPrice": "Agreed unit price, including negotiated discounts.",
+ "ContractedCost": "Contracted unit price multiplied by the pricing quantity.",
+ "BilledCost": "The charge invoicing is based on, excluding amortization.",
+ "EffectiveCost": "The amortized cost after discounts and prepaid purchases.",
+ "SubAccountId": "Identifier of the subscription or contract the services belong to.",
+ "SubAccountName": "Display name of the subscription or contract.",
+ "RegionId": "Identifier of the geographic area the service was provided in.",
+ "RegionName": "Name of the geographic area the service was provided in.",
+ "ServiceProviderName": "Name of the entity that made the services available.",
+ "InvoiceIssuerName": "Name of the entity responsible for invoicing.",
+ "HostProviderName": "Name of the entity providing the underlying infrastructure.",
+ "x_BillableMetricId": "Identifier of the billable metric in the Cloudflare catalog.",
+ "x_BillableMetricName": "Display name of the billable metric.",
+ "x_ProductCategoryName": "The product category the charge belongs to.",
+ "x_ProductFamilyName": "The product family the charge belongs to.",
+ "x_ZoneId": "Identifier of the Cloudflare zone the charge relates to.",
+ "x_ZoneName": "Display name of the Cloudflare zone the charge relates to.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "access_apps": {
+ "description": "A Zero Trust Access application protecting a domain or resource.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/zero_trust/subresources/access/subresources/applications/",
+ "columns": {
+ "id": "Unique identifier for the application.",
+ "aud": "Audience tag used in the application's Access JWT.",
+ "name": "The name of the application.",
+ "type": "The type of application (e.g. self_hosted, saas, ssh).",
+ "domain": "The primary hostname and path secured by Access.",
+ "destinations": "The destinations secured by Access for this application.",
+ "self_hosted_domains": "Public domains Access secures. Deprecated in favor of destinations.",
+ "allowed_idps": "The identity providers users can select when connecting.",
+ "policies": "The policies attached to the application.",
+ "tags": "The tags assigned to the application.",
+ "session_duration": "How long tokens issued for this application stay valid.",
+ "app_launcher_visible": "Whether the application shows in the App Launcher.",
+ "auto_redirect_to_identity": "Whether users skip the identity provider selection step.",
+ "logo_url": "The image URL for the logo shown in the App Launcher.",
+ "custom_deny_message": "The error message shown when a user is denied access.",
+ "custom_deny_url": "Where a user is redirected when denied by identity-based rules.",
+ "created_at": "Time at which the application was created.",
+ "updated_at": "Time at which the application was last updated.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "access_policies": {
+ "description": "A reusable Zero Trust Access policy deciding who can reach an application.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/zero_trust/subresources/access/subresources/policies/",
+ "columns": {
+ "id": "The UUID of the policy.",
+ "name": "The name of the Access policy.",
+ "decision": "The action Access takes if a user matches this policy.",
+ "include": "Rules evaluated with an OR operator. A user needs to meet one.",
+ "exclude": "Rules evaluated with a NOT operator. A user must meet none.",
+ "require": "Rules evaluated with an AND operator. A user must meet all.",
+ "reusable": "Whether the policy can be attached to several applications.",
+ "app_count": "Number of Access applications currently using this policy.",
+ "session_duration": "How long tokens issued for the application stay valid.",
+ "approval_required": "Whether a session needs administrator approval to start.",
+ "approval_groups": "Administrators who can approve a temporary access request.",
+ "isolation_required": "Whether matching users are served in an isolated browser.",
+ "purpose_justification_required": "Whether users must enter a justification when logging in.",
+ "purpose_justification_prompt": "The message shown on the purpose justification screen.",
+ "connection_rules": "How users may connect to targets secured by the application.",
+ "created_at": "Time at which the policy was created.",
+ "updated_at": "Time at which the policy was last updated.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "access_groups": {
+ "description": "A Zero Trust Access group, a reusable set of rules matching users.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/zero_trust/subresources/access/subresources/groups/",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "name": "The name of the Access group.",
+ "include": "Rules evaluated with an OR operator. A user needs to meet one.",
+ "exclude": "Rules evaluated with a NOT operator. A user must meet none.",
+ "require": "Rules evaluated with an AND operator. A user must meet all.",
+ "is_default": "Whether the group is automatically applied to new applications.",
+ "created_at": "Time at which the group was created.",
+ "updated_at": "Time at which the group was last updated.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "access_users": {
+ "description": "A user seen by Zero Trust in an account, with their seat and device counts.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/zero_trust/subresources/access/subresources/users/",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "uid": "The unique API identifier for the user.",
+ "seat_uid": "The unique API identifier for the Zero Trust seat.",
+ "name": "The name of the user.",
+ "email": "The email of the user.",
+ "access_seat": "Whether the user has authenticated with Cloudflare Access.",
+ "gateway_seat": "Whether the user has logged into the WARP client.",
+ "active_device_count": "The number of active devices registered to the user.",
+ "last_successful_login": "The time at which the user last successfully logged in.",
+ "created_at": "Time at which the user was created.",
+ "updated_at": "Time at which the user was last updated.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "workers_scripts": {
+ "description": "A Worker script deployed in an account.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/workers/subresources/scripts/",
+ "columns": {
+ "id": "The name used to identify the script.",
+ "tag": "The immutable ID of the script.",
+ "tags": "Tags associated with the Worker.",
+ "etag": "Hashed script content.",
+ "routes": "Routes associated with the Worker.",
+ "handlers": "The names of handlers exported as part of the default export.",
+ "named_handlers": "Named exports, such as Durable Object classes and entrypoints.",
+ "compatibility_date": "Date indicating targeted support in the Workers runtime.",
+ "compatibility_flags": "Flags that enable or disable features in the Workers runtime.",
+ "usage_model": "Usage model for the Worker invocations.",
+ "logpush": "Whether Logpush is turned on for the Worker.",
+ "observability": "Observability settings for the Worker.",
+ "placement": "Smart Placement configuration for the Worker.",
+ "has_assets": "Whether the Worker contains assets.",
+ "has_modules": "Whether the Worker contains modules.",
+ "migration_tag": "The Durable Object migration most recently applied.",
+ "last_deployed_from": "The client most recently used to deploy this Worker.",
+ "tail_consumers": "Workers that consume logs from this Worker.",
+ "created_on": "When the script was created.",
+ "modified_on": "When the script was last modified.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "r2_buckets": {
+ "description": "An R2 object storage bucket in an account.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/r2/subresources/buckets/",
+ "columns": {
+ "name": "Name of the bucket.",
+ "location": "Location of the bucket.",
+ "jurisdiction": "Jurisdiction objects in this bucket are stored in.",
+ "storage_class": "Storage class for newly uploaded objects.",
+ "creation_date": "Time at which the bucket was created.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "kv_namespaces": {
+ "description": "A Workers KV namespace in an account.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/kv/subresources/namespaces/",
+ "columns": {
+ "id": "Namespace identifier tag.",
+ "title": "A human-readable name for the namespace.",
+ "supports_url_encoding": "Whether keys written on the URL are URL-decoded before storing.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "d1_databases": {
+ "description": "A D1 SQL database in an account.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/d1/subresources/database/",
+ "columns": {
+ "uuid": "D1 database identifier.",
+ "name": "D1 database name.",
+ "version": "The D1 backend version the database runs on.",
+ "jurisdiction": "The location the database is restricted to running and storing data in.",
+ "created_at": "Time at which the database was created.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "stream_usage": {
+ "description": "Stream billable minutes viewed for an account, one row per time period.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/stream/",
+ "columns": {
+ "ts": "Unix timestamp (epoch seconds) for the start of this time period.",
+ "streamMinutesViewed": "Number of Stream billable minutes viewed in this time period.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
+ "security_center_insights": {
+ "description": "A Security Center insight, a security issue Cloudflare found in an account.",
+ "docs_url": "https://developers.cloudflare.com/api/resources/security_center/",
+ "columns": {
+ "id": "Unique identifier for the insight.",
+ "issue_class": "The class of issue the insight belongs to.",
+ "issue_type": "The type of issue the insight reports.",
+ "severity": "The severity of the insight (Low, Moderate, or Critical).",
+ "status": "The current status of the insight (active or resolved).",
+ "subject": "The resource the insight was raised against.",
+ "payload": "Details of the finding, including how it was detected.",
+ "resolve_text": "The suggested action to resolve the insight.",
+ "resolve_link": "A link to where the insight can be resolved.",
+ "dismissed": "Whether the insight has been dismissed.",
+ "has_extended_context": "Whether the insight has a payload fetched from the context endpoint.",
+ "user_classification": "User-defined classification for the insight.",
+ "since": "Time at which the insight was first raised.",
+ "timestamp": "Time at which the insight was last updated.",
+ "_account_id": "Identifier of the parent account, injected during the fan-out sync.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.py
index 9909fb13319e..f5fd32d0e1a5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/cloudflare.py
@@ -1,10 +1,19 @@
+from datetime import UTC, date, datetime
from typing import Any, Optional
+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import (
+ ACCOUNTS_PARENT,
CLOUDFLARE_ENDPOINTS,
+ CURSOR_PAGINATION,
+ DNS_ANALYTICS_DIMENSIONS,
+ DNS_ANALYTICS_METRICS,
+ PAGE_PAGINATION,
+ SINGLE_PAGE,
+ ZONES_PARENT,
CloudflareEndpointConfig,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
@@ -17,21 +26,31 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
find_values,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ JSONResponseCursorPaginator,
PageNumberPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
+ Endpoint,
EndpointResource,
)
CLOUDFLARE_BASE_URL = "https://api.cloudflare.com/client/v4"
# Cloudflare list pages cap at 50 by default; most endpoints allow more.
PAGE_SIZE = 50
-# A token can list zones (account-level Zone:Read) without holding DNS:Read on
-# every one of them. Per-zone 403/404s mean "this zone is inaccessible/gone" —
-# skip it and keep syncing the rest rather than failing the whole stream.
-ZONE_SKIP_STATUS_CODES = (403, 404)
+# A token can list zones or accounts (account-level Zone:Read) without holding read
+# access on every one of them. Per-parent 403/404s mean "this zone/account is
+# inaccessible/gone" — skip it and keep syncing the rest rather than failing the
+# whole stream.
+FANOUT_SKIP_STATUS_CODES = (403, 404)
+
+# Top-level list each fan-out parent is paginated from, and the path placeholder the
+# parent's id is resolved into.
+_PARENT_PATHS = {ZONES_PARENT: "/zones", ACCOUNTS_PARENT: "/accounts"}
+_PARENT_RESOLVE_PARAMS = {ZONES_PARENT: "zone_id", ACCOUNTS_PARENT: "account_id"}
class CloudflarePaginator(PageNumberPaginator):
@@ -56,6 +75,124 @@ class CloudflarePaginator(PageNumberPaginator):
self._has_next_page = False
+def _to_rfc3339(value: Any) -> Optional[str]:
+ """Coerce an incremental watermark to the RFC 3339 date-time Cloudflare's `since`
+ filter documents. Watermarks arrive as datetimes, dates, or already-formatted
+ strings depending on how the pipeline stored them."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ moment = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return moment.isoformat().replace("+00:00", "Z")
+ if isinstance(value, date):
+ return f"{value.isoformat()}T00:00:00Z"
+ return str(value)
+
+
+def _flatten_dns_analytics_row(row: dict[str, Any]) -> dict[str, Any]:
+ """The DNS analytics report returns positional `dimensions`/`metrics` arrays that
+ line up with the names we requested, so name them into their own columns."""
+ flattened = {key: value for key, value in row.items() if key not in ("dimensions", "metrics")}
+ flattened.update(zip(DNS_ANALYTICS_DIMENSIONS, row.get("dimensions") or []))
+ flattened.update(zip(DNS_ANALYTICS_METRICS, row.get("metrics") or []))
+ return flattened
+
+
+# A logpush job's `destination_conf` is a URI whose query string can carry the
+# credentials a Cloudflare admin configured for the sink — an S3-compatible
+# `secret-access-key`, or auth tokens passed as `header_*` params on HTTP sinks.
+# Redact those values so a warehouse reader can't recover secrets they were never
+# granted, while keeping the destination shape (scheme, bucket, region) legible.
+def _is_secret_logpush_param(key: str) -> bool:
+ lowered = key.lower()
+ return lowered in ("secret-access-key", "access-key-id") or lowered.startswith("header_")
+
+
+def _redact_logpush_destination(row: dict[str, Any]) -> dict[str, Any]:
+ conf = row.get("destination_conf")
+ if not isinstance(conf, str):
+ return row
+ split = urlsplit(conf)
+ if not split.query:
+ return row
+ params = parse_qsl(split.query, keep_blank_values=True)
+ if not any(_is_secret_logpush_param(key) for key, _ in params):
+ return row
+ redacted = [(key, "REDACTED" if _is_secret_logpush_param(key) else value) for key, value in params]
+ row["destination_conf"] = urlunsplit(split._replace(query=urlencode(redacted)))
+ return row
+
+
+def _redact_scim_authentication(auth: Any) -> Any:
+ """An Access app's SCIM `authentication` block holds the credentials Cloudflare
+ uses to push to the customer's SCIM endpoint (basic user/password, a bearer
+ token, or an OAuth client secret). Keep only the non-secret `scheme` and redact
+ everything else, so a warehouse reader can't recover them."""
+ if isinstance(auth, list):
+ return [_redact_scim_authentication(item) for item in auth]
+ if isinstance(auth, dict):
+ return {key: (value if key.lower() == "scheme" else "REDACTED") for key, value in auth.items()}
+ return auth
+
+
+# Keys inside an Access app's `saas_app` block that hold an OIDC client secret.
+_SAAS_APP_SECRET_KEYS = frozenset({"client_secret", "secret"})
+
+
+def _redact_access_app(row: dict[str, Any]) -> dict[str, Any]:
+ scim = row.get("scim_config")
+ if isinstance(scim, dict) and "authentication" in scim:
+ row["scim_config"] = {**scim, "authentication": _redact_scim_authentication(scim["authentication"])}
+ saas = row.get("saas_app")
+ if isinstance(saas, dict):
+ row["saas_app"] = {
+ key: ("REDACTED" if key.lower() in _SAAS_APP_SECRET_KEYS else value) for key, value in saas.items()
+ }
+ return row
+
+
+def _redact_header_values(value: Any) -> Any:
+ if isinstance(value, list):
+ return ["REDACTED" for _ in value]
+ return "REDACTED"
+
+
+def _redact_healthcheck(row: dict[str, Any]) -> dict[str, Any]:
+ """A health check's `http_config.header` map is user-configured request headers
+ that can carry an `Authorization` (or other auth) header. Redact the values while
+ keeping the header names, so the check's shape stays legible without leaking secrets."""
+ http_config = row.get("http_config")
+ if not isinstance(http_config, dict):
+ return row
+ header = http_config.get("header")
+ if not isinstance(header, dict):
+ return row
+ row["http_config"] = {
+ **http_config,
+ "header": {name: _redact_header_values(value) for name, value in header.items()},
+ }
+ return row
+
+
+def _redact_custom_hostname(row: dict[str, Any]) -> dict[str, Any]:
+ """A custom hostname's `ssl` object echoes back the private key uploaded for a
+ custom certificate under `custom_key`. Drop it so a warehouse reader can't lift
+ the key and impersonate the hostname; the rest of the SSL metadata is safe."""
+ ssl = row.get("ssl")
+ if isinstance(ssl, dict) and "custom_key" in ssl:
+ row["ssl"] = {key: value for key, value in ssl.items() if key != "custom_key"}
+ return row
+
+
+_DATA_MAPS = {
+ "dns_analytics_report": _flatten_dns_analytics_row,
+ "logpush_jobs": _redact_logpush_destination,
+ "access_apps": _redact_access_app,
+ "healthchecks": _redact_healthcheck,
+ "custom_hostnames": _redact_custom_hostname,
+}
+
+
def _client_config(api_token: str) -> ClientConfig:
return {
"base_url": CLOUDFLARE_BASE_URL,
@@ -64,6 +201,40 @@ def _client_config(api_token: str) -> ClientConfig:
}
+def _paginator(config: CloudflareEndpointConfig) -> BasePaginator:
+ if config.pagination == SINGLE_PAGE:
+ return SinglePagePaginator()
+ if config.pagination == CURSOR_PAGINATION:
+ assert config.cursor_path is not None, (
+ f"Cursor-paginated endpoint '{config.name}' must define cursor_path in CLOUDFLARE_ENDPOINTS"
+ )
+ return JSONResponseCursorPaginator(cursor_path=config.cursor_path, cursor_param="cursor")
+ return CloudflarePaginator()
+
+
+def _params(config: CloudflareEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = dict(config.params)
+ if config.pagination in (PAGE_PAGINATION, CURSOR_PAGINATION):
+ params["per_page"] = PAGE_SIZE
+ return params
+
+
+def _endpoint(
+ config: CloudflareEndpointConfig,
+ params: dict[str, Any],
+ should_use_incremental_field: bool,
+) -> Endpoint:
+ endpoint: Endpoint = {
+ "path": config.path,
+ "params": params,
+ "data_selector": config.data_selector,
+ "paginator": _paginator(config),
+ }
+ if should_use_incremental_field and config.incremental_param is not None:
+ endpoint["incremental"] = {"start_param": config.incremental_param, "convert": _to_rfc3339}
+ return endpoint
+
+
def _list_resource(name: str, path: str) -> EndpointResource:
return {
"name": name,
@@ -75,50 +246,66 @@ def _list_resource(name: str, path: str) -> EndpointResource:
}
+def _resource(endpoint: str, endpoint_config: Endpoint) -> EndpointResource:
+ resource: EndpointResource = {"name": endpoint, "endpoint": endpoint_config}
+ data_map = _DATA_MAPS.get(endpoint)
+ if data_map is not None:
+ resource["data_map"] = data_map
+ return resource
+
+
def _flat_resource(
api_token: str, endpoint: str, config: CloudflareEndpointConfig, team_id: int, job_id: str
) -> Resource:
rest_config: RESTAPIConfig = {
"client": _client_config(api_token),
"resource_defaults": {},
- "resources": [_list_resource(endpoint, config.path)],
+ "resources": [_resource(endpoint, _endpoint(config, _params(config), False))],
}
return rest_api_resource(rest_config, team_id, job_id, None)
-def _zone_fanout_resource(
- api_token: str, endpoint: str, config: CloudflareEndpointConfig, team_id: int, job_id: str
+def _fanout_resource(
+ api_token: str,
+ endpoint: str,
+ config: CloudflareEndpointConfig,
+ team_id: int,
+ job_id: str,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
) -> Resource:
- assert config.parent_key is not None, (
- f"Zone-scoped endpoint '{endpoint}' must define parent_key in CLOUDFLARE_ENDPOINTS"
+ assert config.parent is not None and config.parent_key is not None, (
+ f"Fan-out endpoint '{endpoint}' must define parent and parent_key in CLOUDFLARE_ENDPOINTS"
)
+ parent = config.parent
parent_key = config.parent_key
+ resolve_param = _PARENT_RESOLVE_PARAMS[parent]
+
+ params = _params(config)
+ params[resolve_param] = {"type": "resolve", "resource": parent, "field": "id"}
+
+ child_endpoint = _endpoint(config, params, should_use_incremental_field)
+ child_endpoint["response_actions"] = [
+ {"status_code": status, "action": "ignore"} for status in FANOUT_SKIP_STATUS_CODES
+ ]
+
+ child = _resource(endpoint, child_endpoint)
+ child["include_from_parent"] = ["id"]
- child: EndpointResource = {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": {
- "per_page": PAGE_SIZE,
- "zone_id": {"type": "resolve", "resource": "zones", "field": "id"},
- },
- "data_selector": "result",
- "response_actions": [{"status_code": status, "action": "ignore"} for status in ZONE_SKIP_STATUS_CODES],
- },
- "include_from_parent": ["id"],
- }
rest_config: RESTAPIConfig = {
"client": _client_config(api_token),
"resource_defaults": {},
- "resources": [_list_resource("zones", "/zones"), child],
+ "resources": [_list_resource(parent, _PARENT_PATHS[parent]), child],
}
- resources = {r.name: r for r in rest_api_resources(rest_config, team_id, job_id, None)}
- # A zone row without an id can't be fanned out — skip it rather than failing the stream.
- resources["zones"].add_filter(lambda zone: bool(zone.get("id")))
+ resources = {r.name: r for r in rest_api_resources(rest_config, team_id, job_id, db_incremental_field_last_value)}
+ # A parent row without an id can't be fanned out — skip it rather than failing the stream.
+ resources[parent].add_filter(lambda row: bool(row.get("id")))
+
+ injected_key = f"_{parent}_id"
def _rename_parent_key(row: dict[str, Any]) -> dict[str, Any]:
- if "_zones_id" in row:
- row[parent_key] = row.pop("_zones_id")
+ if injected_key in row:
+ row[parent_key] = row.pop(injected_key)
return row
return resources[endpoint].add_map(_rename_parent_key)
@@ -151,18 +338,28 @@ def cloudflare_source(
endpoint: str,
team_id: int,
job_id: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config = CLOUDFLARE_ENDPOINTS[endpoint]
- if config.zone_scoped:
- resource = _zone_fanout_resource(api_token, endpoint, config, team_id, job_id)
+ if config.parent is not None:
+ resource = _fanout_resource(
+ api_token,
+ endpoint,
+ config,
+ team_id,
+ job_id,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
else:
resource = _flat_resource(api_token, endpoint, config, team_id, job_id)
return SourceResponse(
name=endpoint,
items=lambda: resource,
- primary_keys=[config.primary_key],
+ primary_keys=list(config.primary_keys),
partition_count=1,
partition_size=1,
sort_mode="asc",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/settings.py
index 8e6e7c3edd0f..2a8e1656b5e2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/settings.py
@@ -1,23 +1,52 @@
-from dataclasses import dataclass
-from typing import Optional
+from dataclasses import dataclass, field
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Fan-out parents. Both are top-level Cloudflare list endpoints that are already
+# synced as tables in their own right.
+ZONES_PARENT = "zones"
+ACCOUNTS_PARENT = "accounts"
+
+# Pagination styles Cloudflare's v4 REST API uses.
+PAGE_PAGINATION = "page" # ?page= / ?per_page=, terminated by result_info
+CURSOR_PAGINATION = "cursor" # ?cursor=, terminated by an absent next cursor
+SINGLE_PAGE = "single" # the whole collection comes back in one response
+
+# Metrics and dimensions requested from the DNS analytics report. Cloudflare returns
+# each row as positional `metrics`/`dimensions` arrays, so these names are also what
+# the rows are flattened into. Both lists come from the vendor spec's examples for
+# `dns-analytics_metrics` / `dns-analytics_query.dimensions`.
+DNS_ANALYTICS_METRICS = ("queryCount", "uncachedCount")
+DNS_ANALYTICS_DIMENSIONS = ("queryType", "responseCode")
@dataclass
class CloudflareEndpointConfig:
name: str
- # Path under https://api.cloudflare.com/client/v4; `{zone_id}` is
- # substituted during the per-zone fan-out.
+ # Path under https://api.cloudflare.com/client/v4; `{zone_id}` / `{account_id}`
+ # are substituted during the per-parent fan-out.
path: str
- primary_key: str = "id"
- # Fan-out parent (today only zones).
- zone_scoped: bool = False
+ primary_keys: tuple[str, ...] = ("id",)
+ # Fan-out parent: `zones`, `accounts`, or None for a top-level list.
+ parent: Optional[str] = None
# Field injected to keep the parent linkage on fan-out rows.
parent_key: Optional[str] = None
+ pagination: str = PAGE_PAGINATION
+ # Where the next cursor lives in the response, for CURSOR_PAGINATION endpoints.
+ cursor_path: Optional[str] = None
+ data_selector: str = "result"
+ # Extra query params this endpoint always needs (filters, report metrics, ...).
+ params: dict[str, Any] = field(default_factory=dict)
+ # Query param carrying the incremental watermark, when the API filters server-side.
+ incremental_param: Optional[str] = None
-# Cloudflare's v4 REST lists have no updated-since filters and are small
-# configuration tables, so every stream is a full refresh. The high-volume
-# analytics datasets live in the separate GraphQL API — a follow-up.
+# Most Cloudflare v4 REST lists are small configuration tables with no updated-since
+# filter, so they sync as full refreshes. `audit_logs` is the exception — it takes a
+# server-side `since` filter and can be sorted ascending, so it syncs incrementally.
+# The high-volume traffic datasets live in the separate GraphQL Analytics API, which
+# this REST source has no transport for.
CLOUDFLARE_ENDPOINTS: dict[str, CloudflareEndpointConfig] = {
"accounts": CloudflareEndpointConfig(
name="accounts",
@@ -30,9 +59,264 @@ CLOUDFLARE_ENDPOINTS: dict[str, CloudflareEndpointConfig] = {
"dns_records": CloudflareEndpointConfig(
name="dns_records",
path="/zones/{zone_id}/dns_records",
- zone_scoped=True,
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ # --- Zone-scoped security configuration ---
+ "firewall_rules": CloudflareEndpointConfig(
+ name="firewall_rules",
+ path="/zones/{zone_id}/firewall/rules",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "filters": CloudflareEndpointConfig(
+ name="filters",
+ path="/zones/{zone_id}/filters",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "rulesets": CloudflareEndpointConfig(
+ name="rulesets",
+ path="/zones/{zone_id}/rulesets",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ pagination=CURSOR_PAGINATION,
+ cursor_path="result_info.cursors.after",
+ ),
+ "rate_limits": CloudflareEndpointConfig(
+ name="rate_limits",
+ path="/zones/{zone_id}/rate_limits",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "bot_management": CloudflareEndpointConfig(
+ name="bot_management",
+ path="/zones/{zone_id}/bot_management",
+ # A single configuration object per zone, so the zone is the whole key.
+ primary_keys=("_zone_id",),
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ pagination=SINGLE_PAGE,
+ ),
+ # --- Zone-scoped delivery configuration ---
+ "load_balancers": CloudflareEndpointConfig(
+ name="load_balancers",
+ path="/zones/{zone_id}/load_balancers",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ # The spec documents no page params for this list.
+ pagination=SINGLE_PAGE,
+ ),
+ "healthchecks": CloudflareEndpointConfig(
+ name="healthchecks",
+ path="/zones/{zone_id}/healthchecks",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "waiting_rooms": CloudflareEndpointConfig(
+ name="waiting_rooms",
+ path="/zones/{zone_id}/waiting_rooms",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "pagerules": CloudflareEndpointConfig(
+ name="pagerules",
+ path="/zones/{zone_id}/pagerules",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ pagination=SINGLE_PAGE,
+ ),
+ "snippets": CloudflareEndpointConfig(
+ name="snippets",
+ path="/zones/{zone_id}/snippets",
+ # Snippets are keyed by name within a zone; the rows carry no id.
+ primary_keys=("_zone_id", "snippet_name"),
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "spectrum_apps": CloudflareEndpointConfig(
+ name="spectrum_apps",
+ path="/zones/{zone_id}/spectrum/apps",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "workers_routes": CloudflareEndpointConfig(
+ name="workers_routes",
+ path="/zones/{zone_id}/workers/routes",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ pagination=SINGLE_PAGE,
+ ),
+ "logpush_jobs": CloudflareEndpointConfig(
+ name="logpush_jobs",
+ path="/zones/{zone_id}/logpush/jobs",
+ parent=ZONES_PARENT,
parent_key="_zone_id",
+ pagination=SINGLE_PAGE,
+ ),
+ # --- Zone-scoped certificates and hostnames ---
+ "custom_hostnames": CloudflareEndpointConfig(
+ name="custom_hostnames",
+ path="/zones/{zone_id}/custom_hostnames",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "ssl_certificate_packs": CloudflareEndpointConfig(
+ name="ssl_certificate_packs",
+ path="/zones/{zone_id}/ssl/certificate_packs",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ # Only `status=all` returns packs in every state; the default hides some.
+ params={"status": "all"},
+ ),
+ "custom_certificates": CloudflareEndpointConfig(
+ name="custom_certificates",
+ path="/zones/{zone_id}/custom_certificates",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ # --- Zone-scoped client-side security ---
+ "page_shield_scripts": CloudflareEndpointConfig(
+ name="page_shield_scripts",
+ path="/zones/{zone_id}/page_shield/scripts",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "page_shield_connections": CloudflareEndpointConfig(
+ name="page_shield_connections",
+ path="/zones/{zone_id}/page_shield/connections",
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ "api_gateway_operations": CloudflareEndpointConfig(
+ name="api_gateway_operations",
+ path="/zones/{zone_id}/api_gateway/operations",
+ primary_keys=("operation_id",),
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ ),
+ # --- Zone-scoped analytics ---
+ "dns_analytics_report": CloudflareEndpointConfig(
+ name="dns_analytics_report",
+ path="/zones/{zone_id}/dns_analytics/report",
+ primary_keys=("_zone_id", *DNS_ANALYTICS_DIMENSIONS),
+ parent=ZONES_PARENT,
+ parent_key="_zone_id",
+ pagination=SINGLE_PAGE,
+ data_selector="result.data",
+ params={
+ "metrics": ",".join(DNS_ANALYTICS_METRICS),
+ "dimensions": ",".join(DNS_ANALYTICS_DIMENSIONS),
+ },
+ ),
+ # --- Account-scoped ---
+ "audit_logs": CloudflareEndpointConfig(
+ name="audit_logs",
+ path="/accounts/{account_id}/audit_logs",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ # `since` filters server-side and `direction=asc` makes the response order
+ # match SourceResponse's ascending sort mode.
+ params={"direction": "asc"},
+ incremental_param="since",
+ ),
+ "billing_usage": CloudflareEndpointConfig(
+ name="billing_usage",
+ path="/accounts/{account_id}/billing/usage",
+ primary_keys=("_account_id", "ts"),
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ pagination=SINGLE_PAGE,
+ ),
+ "billable_usage": CloudflareEndpointConfig(
+ name="billable_usage",
+ path="/accounts/{account_id}/billable/usage",
+ primary_keys=("_account_id", "ChargePeriodStart", "x_BillableMetricId"),
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ pagination=SINGLE_PAGE,
+ ),
+ "access_apps": CloudflareEndpointConfig(
+ name="access_apps",
+ path="/accounts/{account_id}/access/apps",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ ),
+ "access_policies": CloudflareEndpointConfig(
+ name="access_policies",
+ path="/accounts/{account_id}/access/policies",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ ),
+ "access_groups": CloudflareEndpointConfig(
+ name="access_groups",
+ path="/accounts/{account_id}/access/groups",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ ),
+ "access_users": CloudflareEndpointConfig(
+ name="access_users",
+ path="/accounts/{account_id}/access/users",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ ),
+ "workers_scripts": CloudflareEndpointConfig(
+ name="workers_scripts",
+ path="/accounts/{account_id}/workers/scripts",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ pagination=SINGLE_PAGE,
+ ),
+ "r2_buckets": CloudflareEndpointConfig(
+ name="r2_buckets",
+ path="/accounts/{account_id}/r2/buckets",
+ # Buckets are keyed by name within an account; the rows carry no id.
+ primary_keys=("_account_id", "name"),
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ pagination=CURSOR_PAGINATION,
+ cursor_path="result_info.cursor",
+ data_selector="result.buckets",
+ ),
+ "kv_namespaces": CloudflareEndpointConfig(
+ name="kv_namespaces",
+ path="/accounts/{account_id}/storage/kv/namespaces",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ ),
+ "d1_databases": CloudflareEndpointConfig(
+ name="d1_databases",
+ path="/accounts/{account_id}/d1/database",
+ primary_keys=("uuid",),
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ ),
+ "stream_usage": CloudflareEndpointConfig(
+ name="stream_usage",
+ path="/accounts/{account_id}/stream/usage",
+ primary_keys=("_account_id", "ts"),
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ pagination=SINGLE_PAGE,
+ ),
+ "security_center_insights": CloudflareEndpointConfig(
+ name="security_center_insights",
+ path="/accounts/{account_id}/security-center/insights",
+ parent=ACCOUNTS_PARENT,
+ parent_key="_account_id",
+ data_selector="result.issues",
),
}
ENDPOINTS = tuple(CLOUDFLARE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "audit_logs": [
+ {
+ "label": "when",
+ "type": IncrementalFieldType.DateTime,
+ "field": "when",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.py
index fe9237fa2354..6162c17dcaeb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/source.py
@@ -17,7 +17,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare
cloudflare_source,
validate_credentials as validate_cloudflare_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
@@ -54,9 +57,9 @@ class CloudflareSource(SimpleSource[CloudflareSourceConfig]):
name=SchemaExternalDataSourceType.CLOUDFLARE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Cloudflare",
- caption="""Enter your Cloudflare API token to pull your Cloudflare configuration data into the PostHog Data warehouse.
+ caption="""Enter your Cloudflare API token to pull your Cloudflare configuration, security, and usage data into the PostHog Data warehouse.
-Create an API token in the [Cloudflare dashboard](https://dash.cloudflare.com/profile/api-tokens) with read permissions for Account Settings, Zone, and DNS. DNS records are synced from every zone the token can access.""",
+Create an API token in the [Cloudflare dashboard](https://dash.cloudflare.com/profile/api-tokens) with read permissions for the areas you want to sync, such as Account Settings, Zone, DNS, Firewall Services, Logs, Workers, and Access. Zone tables are synced from every zone the token can read, and account tables from every account. Zones and accounts the token can't read are skipped.""",
iconPath="/static/services/cloudflare.svg",
docsUrl="https://posthog.com/docs/cdp/sources/cloudflare",
releaseStatus=ReleaseStatus.BETA,
@@ -91,14 +94,15 @@ Create an API token in the [Cloudflare dashboard](https://dash.cloudflare.com/pr
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # v4 REST lists are small configuration tables with no updated-since
- # filters; the analytics datasets live in the GraphQL API (follow-up).
+ # Most v4 REST lists are small configuration tables with no updated-since
+ # filter, so they full refresh. Only endpoints in INCREMENTAL_FIELDS take a
+ # server-side timestamp filter.
schemas = [
SourceSchema(
name=endpoint,
- supports_incremental=False,
- supports_append=False,
- incremental_fields=[],
+ supports_incremental=endpoint in INCREMENTAL_FIELDS,
+ supports_append=endpoint in INCREMENTAL_FIELDS,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
)
for endpoint in ENDPOINTS
]
@@ -136,4 +140,8 @@ Create an API token in the [Cloudflare dashboard](https://dash.cloudflare.com/pr
endpoint=inputs.schema_name,
team_id=inputs.team_id,
job_id=inputs.job_id,
+ 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/cloudflare/tests/test_cloudflare_client.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py
index adb29ad7b10d..d78257d117d9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_client.py
@@ -1,4 +1,5 @@
import json
+from datetime import UTC, date, datetime
from typing import Any
import pytest
@@ -9,12 +10,19 @@ from requests import Response
from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.cloudflare import (
PAGE_SIZE,
+ _redact_access_app,
+ _redact_custom_hostname,
+ _redact_healthcheck,
+ _redact_logpush_destination,
cloudflare_source,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import (
+ ACCOUNTS_PARENT,
CLOUDFLARE_ENDPOINTS,
ENDPOINTS,
+ SINGLE_PAGE,
+ ZONES_PARENT,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
@@ -45,6 +53,13 @@ def _response(
return resp
+def _raw_response(body: dict[str, Any]) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
def _error_response(status_code: int) -> Response:
resp = Response()
resp.status_code = status_code
@@ -258,7 +273,384 @@ class TestCloudflareSourceResponse:
response = cloudflare_source("token", endpoint, team_id=1, job_id="j")
assert response.name == endpoint
- assert response.primary_keys == [config.primary_key]
+ assert response.primary_keys == list(config.primary_keys)
assert response.sort_mode == "asc"
assert response.partition_mode is None
assert response.partition_keys is None
+
+
+class TestEndpointConfigConsistency:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_path_placeholder_matches_declared_parent(self, endpoint) -> None:
+ # A path templated on one parent but fanned out from the other raises KeyError
+ # mid-sync, which only shows up once a customer syncs that table.
+ config = CLOUDFLARE_ENDPOINTS[endpoint]
+ assert ("{zone_id}" in config.path) is (config.parent == ZONES_PARENT)
+ assert ("{account_id}" in config.path) is (config.parent == ACCOUNTS_PARENT)
+ if config.parent is not None:
+ assert config.parent_key is not None
+
+
+class TestAccountFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_account_scoped_endpoint_fans_out_over_accounts(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "a1"}, {"id": "a2"}], total_pages=1),
+ _response([{"id": "n1"}], total_pages=1),
+ _response([{"id": "n2"}], total_pages=1),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "kv_namespaces", team_id=1, job_id="j"))
+
+ assert [(r["id"], r["_account_id"]) for r in rows] == [("n1", "a1"), ("n2", "a2")]
+ assert snapshots[0]["url"] == "https://api.cloudflare.com/client/v4/accounts"
+ assert snapshots[1]["url"] == "https://api.cloudflare.com/client/v4/accounts/a1/storage/kv/namespaces"
+ assert snapshots[2]["url"] == "https://api.cloudflare.com/client/v4/accounts/a2/storage/kv/namespaces"
+
+ @pytest.mark.parametrize("status_code", [403, 404])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_skips_account_the_token_cannot_read(self, MockSession, status_code) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "a1"}, {"id": "a2"}], total_pages=1),
+ _error_response(status_code),
+ _response([{"id": "n2"}], total_pages=1),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "kv_namespaces", team_id=1, job_id="j"))
+
+ assert [(r["id"], r["_account_id"]) for r in rows] == [("n2", "a2")]
+
+
+class TestSinglePageEndpoints:
+ @pytest.mark.parametrize(
+ "endpoint",
+ [name for name, config in CLOUDFLARE_ENDPOINTS.items() if config.pagination == SINGLE_PAGE],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_never_requests_a_second_page(self, MockSession, endpoint) -> None:
+ # These endpoints document no page params, so Cloudflare ignores `page` and would
+ # return the same rows forever if the page-number paginator were used.
+ session = MockSession.return_value
+ full_page = [{"id": str(i)} for i in range(PAGE_SIZE)]
+ snapshots = _wire(session, [_response([{"id": "z1"}], total_pages=1), _response(full_page)])
+
+ _rows(cloudflare_source("token", endpoint, team_id=1, job_id="j"))
+
+ assert session.send.call_count == 2
+ assert "page" not in snapshots[1]["params"]
+ assert "per_page" not in snapshots[1]["params"]
+
+
+class TestCursorPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_rulesets_follow_the_after_cursor(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "z1"}], total_pages=1),
+ _raw_response(
+ {"success": True, "result": [{"id": "r1"}], "result_info": {"cursors": {"after": "next-page"}}}
+ ),
+ _raw_response({"success": True, "result": [{"id": "r2"}], "result_info": {"cursors": {}}}),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "rulesets", team_id=1, job_id="j"))
+
+ assert [r["id"] for r in rows] == ["r1", "r2"]
+ assert "cursor" not in snapshots[1]["params"]
+ assert snapshots[2]["params"]["cursor"] == "next-page"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_r2_buckets_read_rows_from_the_nested_buckets_key(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "a1"}], total_pages=1),
+ _raw_response(
+ {"success": True, "result": {"buckets": [{"name": "b1"}]}, "result_info": {"cursor": "c1"}}
+ ),
+ _raw_response({"success": True, "result": {"buckets": [{"name": "b2"}]}, "result_info": {}}),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "r2_buckets", team_id=1, job_id="j"))
+
+ assert [(r["name"], r["_account_id"]) for r in rows] == [("b1", "a1"), ("b2", "a1")]
+
+
+class TestSecurityCenterInsights:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_reads_rows_from_the_nested_issues_key(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "a1"}], total_pages=1),
+ _raw_response({"success": True, "result": {"issues": [{"id": "i1"}], "count": 1}}),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "security_center_insights", team_id=1, job_id="j"))
+
+ assert [(r["id"], r["_account_id"]) for r in rows] == [("i1", "a1")]
+
+
+class TestDnsAnalyticsReport:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_positional_report_arrays_become_named_columns(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [
+ _response([{"id": "z1"}], total_pages=1),
+ _raw_response(
+ {
+ "success": True,
+ "result": {
+ "rows": 1,
+ "data": [{"dimensions": ["A", "NOERROR"], "metrics": [10, 4]}],
+ },
+ }
+ ),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "dns_analytics_report", team_id=1, job_id="j"))
+
+ assert rows == [
+ {
+ "queryType": "A",
+ "responseCode": "NOERROR",
+ "queryCount": 10,
+ "uncachedCount": 4,
+ "_zone_id": "z1",
+ }
+ ]
+ assert snapshots[1]["params"]["metrics"] == "queryCount,uncachedCount"
+ assert snapshots[1]["params"]["dimensions"] == "queryType,responseCode"
+
+
+class TestLogpushDestinationRedaction:
+ @pytest.mark.parametrize(
+ "conf,expected",
+ [
+ (
+ "s3://bucket/logs?region=us-east-1&access-key-id=AKIA&secret-access-key=shh",
+ "s3://bucket/logs?region=us-east-1&access-key-id=REDACTED&secret-access-key=REDACTED",
+ ),
+ (
+ "https://logs.example.com?header_Authorization=Bearer+tok&ddsource=cloudflare",
+ "https://logs.example.com?header_Authorization=REDACTED&ddsource=cloudflare",
+ ),
+ # No secret-bearing param — left byte-for-byte unchanged.
+ ("s3://bucket/logs?region=us-east-1", "s3://bucket/logs?region=us-east-1"),
+ ("gs://bucket/logs", "gs://bucket/logs"),
+ ],
+ )
+ def test_redacts_only_secret_query_params(self, conf, expected) -> None:
+ assert _redact_logpush_destination({"destination_conf": conf}) == {"destination_conf": expected}
+
+ def test_leaves_non_string_conf_untouched(self) -> None:
+ row = {"destination_conf": None, "id": "j1"}
+ assert _redact_logpush_destination(row) == row
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_secret_is_stripped_when_synced(self, MockSession) -> None:
+ # Guards that the redaction data_map is actually wired to the logpush_jobs resource.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "z1"}], total_pages=1),
+ _response([{"id": "j1", "destination_conf": "s3://b/logs?secret-access-key=SUPERSECRET"}]),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "logpush_jobs", team_id=1, job_id="j"))
+
+ assert "SUPERSECRET" not in rows[0]["destination_conf"]
+ assert rows[0]["destination_conf"] == "s3://b/logs?secret-access-key=REDACTED"
+
+
+class TestAccessAppRedaction:
+ def test_redacts_scim_authentication_but_keeps_scheme(self) -> None:
+ row = {
+ "id": "app1",
+ "scim_config": {"enabled": True, "authentication": {"scheme": "oauthbearertoken", "token": "shh"}},
+ }
+
+ result = _redact_access_app(row)
+
+ assert result["scim_config"] == {
+ "enabled": True,
+ "authentication": {"scheme": "oauthbearertoken", "token": "REDACTED"},
+ }
+
+ def test_redacts_each_authentication_in_a_list(self) -> None:
+ row = {"scim_config": {"authentication": [{"scheme": "httpbasic", "user": "u", "password": "p"}]}}
+
+ result = _redact_access_app(row)
+
+ assert result["scim_config"]["authentication"] == [
+ {"scheme": "httpbasic", "user": "REDACTED", "password": "REDACTED"}
+ ]
+
+ def test_redacts_saas_app_client_secret_only(self) -> None:
+ row = {"saas_app": {"auth_type": "oidc", "client_id": "cid", "client_secret": "shh"}}
+
+ result = _redact_access_app(row)
+
+ assert result["saas_app"] == {"auth_type": "oidc", "client_id": "cid", "client_secret": "REDACTED"}
+
+ def test_leaves_rows_without_secret_blocks_untouched(self) -> None:
+ row = {"id": "app1", "name": "My app"}
+ assert _redact_access_app(row) == row
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_secrets_are_stripped_when_synced(self, MockSession) -> None:
+ # Guards that the redaction data_map is actually wired to the access_apps resource.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "a1"}], total_pages=1),
+ _response(
+ [
+ {
+ "id": "app1",
+ "scim_config": {"authentication": {"scheme": "oauthbearertoken", "token": "SUPERSECRET"}},
+ }
+ ],
+ total_pages=1,
+ ),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "access_apps", team_id=1, job_id="j"))
+
+ assert rows[0]["scim_config"]["authentication"] == {"scheme": "oauthbearertoken", "token": "REDACTED"}
+
+
+class TestHealthcheckRedaction:
+ def test_redacts_http_config_header_values_keeping_names(self) -> None:
+ row = {
+ "id": "hc1",
+ "http_config": {"method": "GET", "header": {"Host": ["example.com"], "Authorization": ["Bearer tok"]}},
+ }
+
+ result = _redact_healthcheck(row)
+
+ assert result["http_config"] == {
+ "method": "GET",
+ "header": {"Host": ["REDACTED"], "Authorization": ["REDACTED"]},
+ }
+
+ def test_leaves_rows_without_http_headers_untouched(self) -> None:
+ row = {"id": "hc1", "http_config": {"method": "GET"}}
+ assert _redact_healthcheck(row) == row
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_auth_header_is_stripped_when_synced(self, MockSession) -> None:
+ # Guards that the redaction data_map is actually wired to the healthchecks resource.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "z1"}], total_pages=1),
+ _response(
+ [{"id": "hc1", "http_config": {"header": {"Authorization": ["Bearer SUPERSECRET"]}}}], total_pages=1
+ ),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "healthchecks", team_id=1, job_id="j"))
+
+ assert rows[0]["http_config"]["header"] == {"Authorization": ["REDACTED"]}
+
+
+class TestCustomHostnameRedaction:
+ def test_drops_ssl_custom_key_keeping_other_metadata(self) -> None:
+ row = {
+ "id": "h1",
+ "ssl": {"status": "active", "custom_certificate": "-----CERT-----", "custom_key": "-----PRIVATE KEY-----"},
+ }
+
+ result = _redact_custom_hostname(row)
+
+ assert result["ssl"] == {"status": "active", "custom_certificate": "-----CERT-----"}
+
+ def test_leaves_rows_without_a_custom_key_untouched(self) -> None:
+ row = {"id": "h1", "ssl": {"status": "active"}}
+ assert _redact_custom_hostname(row) == row
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_private_key_is_dropped_when_synced(self, MockSession) -> None:
+ # Guards that the redaction data_map is actually wired to the custom_hostnames resource.
+ session = MockSession.return_value
+ _wire(
+ session,
+ [
+ _response([{"id": "z1"}], total_pages=1),
+ _response([{"id": "h1", "ssl": {"status": "active", "custom_key": "SUPERSECRET"}}], total_pages=1),
+ ],
+ )
+
+ rows = _rows(cloudflare_source("token", "custom_hostnames", team_id=1, job_id="j"))
+
+ assert "custom_key" not in rows[0]["ssl"]
+
+
+class TestAuditLogsIncremental:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_sends_ascending_direction_and_no_since_on_a_full_refresh(self, MockSession) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [_response([{"id": "a1"}], total_pages=1), _response([{"id": "l1"}], total_pages=1)],
+ )
+
+ _rows(cloudflare_source("token", "audit_logs", team_id=1, job_id="j"))
+
+ assert snapshots[1]["params"]["direction"] == "asc"
+ assert "since" not in snapshots[1]["params"]
+
+ @pytest.mark.parametrize(
+ "last_value, expected_since",
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC), "2024-01-02T03:04:05Z"),
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05Z"),
+ (date(2024, 1, 2), "2024-01-02T00:00:00Z"),
+ ("2024-01-02T03:04:05Z", "2024-01-02T03:04:05Z"),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_filters_server_side_from_the_watermark(self, MockSession, last_value, expected_since) -> None:
+ session = MockSession.return_value
+ snapshots = _wire(
+ session,
+ [_response([{"id": "a1"}], total_pages=1), _response([{"id": "l1"}], total_pages=1)],
+ )
+
+ _rows(
+ cloudflare_source(
+ "token",
+ "audit_logs",
+ team_id=1,
+ job_id="j",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ )
+ )
+
+ assert snapshots[1]["params"]["since"] == expected_since
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.py
index 7e4b8c5c032a..4e1d2f28f7b6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudflare/tests/test_cloudflare_source.py
@@ -3,7 +3,13 @@ from unittest import mock
from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
-from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.source import CloudflareSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cloudflare import (
CloudflareSourceConfig,
@@ -61,13 +67,15 @@ class TestCloudflareSource:
non_retryable_errors = self.source.get_non_retryable_errors()
assert not any(key in other_vendor_error for key in non_retryable_errors)
- def test_get_schemas_are_full_refresh_only(self):
- schemas = self.source.get_schemas(self.config, self.team_id)
+ def test_get_schemas_only_advertise_incremental_where_the_api_filters_server_side(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
- assert {schema.name for schema in schemas} == set(ENDPOINTS)
- assert all(not schema.supports_incremental for schema in schemas)
- assert all(not schema.supports_append for schema in schemas)
- assert all(schema.incremental_fields == [] for schema in schemas)
+ assert set(schemas) == set(ENDPOINTS)
+ assert {name for name, schema in schemas.items() if schema.supports_incremental} == set(INCREMENTAL_FIELDS)
+ assert [field["field"] for field in schemas["audit_logs"].incremental_fields] == ["when"]
+ assert all(
+ schema.incremental_fields == [] for name, schema in schemas.items() if name not in INCREMENTAL_FIELDS
+ )
def test_get_schemas_filtered_by_names(self):
schemas = self.source.get_schemas(self.config, self.team_id, names=["zones"])
@@ -104,6 +112,10 @@ class TestCloudflareSource:
assert expected_substring in error_message
mock_validate.assert_called_once_with(self.config.api_token)
+ def test_every_endpoint_is_documented_for_semantic_enrichment(self):
+ # A table with no canonical entry silently falls back to LLM-derived descriptions.
+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)
+
@mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.source.cloudflare_source")
def test_source_for_pipeline_plumbs_arguments(self, mock_cf_source):
inputs = mock.MagicMock()
@@ -115,3 +127,21 @@ class TestCloudflareSource:
kwargs = mock_cf_source.call_args.kwargs
assert kwargs["api_token"] == "api-token"
assert kwargs["endpoint"] == "dns_records"
+
+ @pytest.mark.parametrize("should_use_incremental_field", [True, False])
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cloudflare.source.cloudflare_source")
+ def test_source_for_pipeline_only_forwards_the_watermark_when_syncing_incrementally(
+ self, mock_cf_source, should_use_incremental_field
+ ):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "audit_logs"
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ kwargs = mock_cf_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field
+ assert kwargs["db_incremental_field_last_value"] == (
+ "2024-01-02T03:04:05Z" if should_use_incremental_field else None
+ )