:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Canvas LMS import source (#84326)
Tom Owers09942deeb5f6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/canonical_descriptions.pynew file mode 100644index 000000000000..da2196aa1150--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/canonical_descriptions.py@@ -0,0 +1,85 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "courses": {+ "description": "A course in the Canvas account, including its term, workflow state, and dates.",+ "docs_url": "https://developerdocs.instructure.com/services/canvas/resources/courses",+ "columns": {+ "id": "Unique identifier for the course.",+ "sis_course_id": "The SIS identifier for the course, if defined.",+ "name": "The full name of the course.",+ "course_code": "The course code, a short identifier shown in course listings.",+ "workflow_state": "The state of the course, e.g. unpublished, available, completed, or deleted.",+ "account_id": "The ID of the account the course belongs to.",+ "root_account_id": "The ID of the root account for the course.",+ "enrollment_term_id": "The ID of the enrollment term the course belongs to.",+ "created_at": "The time at which the course was created.",+ "start_at": "The start date for the course, if applicable.",+ "end_at": "The end date for the course, if applicable.",+ },+ },+ "users": {+ "description": "A user in the Canvas account, including their name and login information.",+ "docs_url": "https://developerdocs.instructure.com/services/canvas/resources/users",+ "columns": {+ "id": "Unique identifier for the user.",+ "name": "The name of the user.",+ "sortable_name": "A sortable version of the user's name, last name first.",+ "short_name": "A short version of the user's name for search results.",+ "login_id": "The unique login identifier for the user.",+ "email": "The user's email address.",+ "sis_user_id": "The SIS identifier for the user, if defined.",+ },+ },+ "enrollments": {+ "description": "A user's enrollment in a course, including their role and enrollment state.",+ "docs_url": "https://developerdocs.instructure.com/services/canvas/resources/enrollments",+ "columns": {+ "id": "Unique identifier for the enrollment.",+ "course_id": "The unique ID of the course the enrollment is for.",+ "course_section_id": "The unique ID of the course section the enrollment is for.",+ "user_id": "The unique ID of the user the enrollment is for.",+ "type": "The type of enrollment, e.g. StudentEnrollment or TeacherEnrollment.",+ "role": "The course-level role assigned to the enrolled user.",+ "enrollment_state": "The state of the enrollment, e.g. active, invited, or completed.",+ "created_at": "The time at which the enrollment was created.",+ "updated_at": "The time at which the enrollment was last updated.",+ "start_at": "The start date for the enrollment, if applicable.",+ "end_at": "The end date for the enrollment, if applicable.",+ },+ },+ "assignments": {+ "description": "An assignment in a course, including its due date and grading configuration.",+ "docs_url": "https://developerdocs.instructure.com/services/canvas/resources/assignments",+ "columns": {+ "id": "Unique identifier for the assignment.",+ "course_id": "The ID of the course the assignment belongs to.",+ "name": "The name of the assignment.",+ "description": "The assignment's description, in HTML.",+ "created_at": "The time at which the assignment was originally created.",+ "updated_at": "The time at which the assignment was last modified in any way.",+ "due_at": "The due date for the assignment, if applicable.",+ "points_possible": "The maximum points possible for the assignment.",+ "workflow_state": "The state of the assignment, e.g. published or unpublished.",+ },+ },+ "submissions": {+ "description": "A student's submission for an assignment, including grade and submission state.",+ "docs_url": "https://developerdocs.instructure.com/services/canvas/resources/submissions",+ "columns": {+ "assignment_id": "The ID of the assignment the submission is for.",+ "user_id": "The ID of the student the submission belongs to.",+ "grader_id": "The ID of the user who graded the submission, if graded.",+ "score": "The raw score the student earned on the submission.",+ "grade": "The grade the student earned, formatted according to the assignment's grading type.",+ "submitted_at": "The timestamp when the assignment was submitted.",+ "graded_at": "The timestamp when the submission was graded.",+ "workflow_state": "The state of the submission, e.g. submitted, unsubmitted, or graded.",+ "late": "Whether the submission was submitted after the due date.",+ "missing": "Whether the submission is missing.",+ "excused": "Whether the submission has been excused from grading.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/canvas_lms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/canvas_lms.pynew file mode 100644index 000000000000..249e5cc72406--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/canvas_lms.py@@ -0,0 +1,402 @@+import re+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, Optional, cast+from urllib.parse import urlparse++import requests+from requests import Response++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.settings import (+ CANVAS_ENDPOINTS,+ CanvasEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ HeaderLinkPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++REQUEST_TIMEOUT_SECONDS = 30++HOST_NOT_ALLOWED_ERROR = "Canvas domain is not allowed"+++class CanvasHostNotAllowedError(Exception):+ pass+++@frozen+class CanvasLmsResumeConfig:+ # Top-level endpoints (courses, users) resume from the opaque Link-header `next` URL.+ next_url: Optional[str] = None+ # Fan-out endpoints (enrollments, assignments, submissions) resume by parent: course paths+ # already fully synced, the course in progress, and that course's paginator state -- see+ # `common.rest_source.__init__._make_paginate_dependent_resource`.+ completed: Optional[list[str]] = None+ current: Optional[str] = None+ child_state: Optional[dict[str, Any]] = None+++def normalize_domain(domain: str) -> str:+ """Turn whatever the user typed into a bare Canvas host.++ Accepts values like ``yourschool.instructure.com``, ``https://yourschool.instructure.com/``,+ or a custom vanity domain, and returns just the host.+ """+ domain = domain.strip()+ domain = re.sub(r"^https?://", "", domain, flags=re.IGNORECASE)+ domain = domain.split("/")[0]+ return domain.strip().rstrip("/")+++def _base_url(domain: str) -> str:+ return f"https://{normalize_domain(domain)}/api/v1"+++def _get_headers(api_key: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+++def _is_same_host(url: str, domain: str) -> bool:+ """Whether ``url`` points at the configured Canvas host.++ Pagination/resume URLs are server-controlled (they arrive in the Link header), so they're+ pinned to the validated institution host to avoid being redirected at an arbitrary internal+ address (SSRF).+ """+ try:+ return (urlparse(url).hostname or "").lower() == normalize_domain(domain).lower()+ except Exception:+ return False+++class CanvasLinkPaginator(HeaderLinkPaginator):+ """Canvas paginates via the ``Link`` response header (RFC 5988, ``rel="next"``). The link is+ server-controlled, so it's pinned to the configured Canvas domain -- an off-host link stops+ pagination (SSRF guard) instead of being followed."""++ def __init__(self, domain: str) -> None:+ super().__init__()+ self._domain = domain++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ super().update_state(response, data)+ if self._has_next_page and self._next_url is not None and not _is_same_host(self._next_url, self._domain):+ self._has_next_page = False+ self._next_url = None+++def _format_canvas_datetime(value: Any) -> str:+ """Format a date/datetime-like value as the ISO 8601 UTC string Canvas's+ `submitted_since`/`graded_since` filters expect. Falls back to `str(value)` for values that are+ already a formatted string (e.g. our own `initial_value` seed)."""+ normalized = coerce_datetime_to_utc(value)+ if normalized is None:+ return str(value)+ capped = min(normalized, datetime.now(UTC))+ return capped.strftime("%Y-%m-%dT%H:%M:%SZ")+++def _incremental_window(field_name: str, query_param: str) -> IncrementalConfig:+ return {+ "cursor_path": field_name,+ "start_param": query_param,+ "initial_value": "1970-01-01T00:00:00Z",+ "convert": _format_canvas_datetime,+ }+++def _client_config(domain: str, api_key: str) -> ClientConfig:+ return {+ "base_url": _base_url(domain),+ # Auth (the bearer token) rides the framework auth config so it's redacted from logs and+ # raised error messages; only the non-secret Accept header is set here.+ "headers": {"Accept": "application/json"},+ "auth": {"type": "bearer", "token": api_key},+ "paginator": CanvasLinkPaginator(domain),+ # A validated host could 3xx to an internal address; refuse to follow redirects (SSRF).+ "allow_redirects": False,+ # Pins every outgoing request -- including Link-header pagination and resumed fan-out+ # checkpoint URLs -- to the configured domain's exact scheme/host/port (the base_url host+ # is implicitly allowed). The `_is_same_host`/paginator checks above only compare hostname,+ # so this is what actually rejects a same-host scheme downgrade (https->http) or a+ # different port before the Authorization header goes out (SSRF / credential exfiltration).+ "allowed_hosts": [],+ # A source pointed at a customer-controlled host that accepts a connection and then never+ # responds would otherwise hold an import worker forever; bound every request.+ "request_timeout": REQUEST_TIMEOUT_SECONDS,+ # Canvas responses carry student/staff PII and grading data (SIS identifiers, assignment+ # HTML, scores) that the name-based sample scrubbers aren't guaranteed to catch, so keep+ # raw bodies out of HTTP sample capture even where an operator enables it -- same pattern+ # as the Clever source, which carries comparable student/guardian/staff PII.+ "capture": False,+ }+++def _make_source_response(config: CanvasEndpointConfig, items: Any) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items,+ primary_keys=config.primary_keys,+ partition_count=1 if config.partition_key else None,+ partition_size=1 if config.partition_key else None,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Neither `submitted_since`/`graded_since` (submissions) nor plain account-level listings+ # guarantee response ordering, but each sync re-applies the filter and paginates every+ # page, so completeness doesn't depend on it. Merge dedupes on the primary key regardless.+ sort_mode="asc",+ )+++def validate_credentials(+ domain: str,+ account_id: str,+ api_key: str,+ schema_name: Optional[str] = None,+ team_id: Optional[int] = None,+) -> tuple[bool, str | None]:+ """Probe the account-level courses listing to confirm the domain, account ID, and token+ together resolve to something real.++ At source-create (``schema_name is None``) a 403 is accepted: the token may be valid but+ simply lack admin rights on this particular account, which is fine if the user only wants the+ endpoints they can already read. A scoped probe (``schema_name`` set) treats 403 as a hard+ failure.+ """+ try:+ normalized = normalize_domain(domain)+ except Exception:+ return False, "Invalid Canvas domain"++ if not normalized or not re.match(r"^[A-Za-z0-9.\-]+$", normalized):+ return (+ False,+ "That doesn't look like a Canvas domain. Enter your institution's domain, "+ "e.g. 'yourschool.instructure.com'.",+ )++ # The institution domain is fully customer-controlled, so block hosts that resolve to+ # private/internal addresses (SSRF). Only enforced on cloud -- see _is_host_safe.+ if team_id is not None:+ host_ok, host_err = _is_host_safe(normalized, team_id)+ if not host_ok:+ return False, host_err or HOST_NOT_ALLOWED_ERROR++ url = f"{_base_url(domain)}/accounts/{account_id}/courses"+ try:+ # Don't follow redirects: the validated host could 3xx to an internal address, defeating+ # the host check above (SSRF). The probe response body carries real course data, so also+ # keep it out of HTTP sample capture -- same reasoning as `_client_config`.+ response = make_tracked_session(redact_values=(api_key,), capture=False).get(+ url,+ headers=_get_headers(api_key),+ params={"per_page": 1},+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ )+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Canvas access token"+ if response.status_code == 404:+ return False, "Canvas account not found. Check the account ID and try again."+ if response.status_code == 403:+ if schema_name is None:+ # Valid token, missing admin rights on this account -- let source creation through.+ return True, None+ return False, "Your Canvas access token doesn't have admin access to this account."++ return False, f"Could not connect to Canvas (HTTP {response.status_code})"+++def _non_fanout_source(+ config: CanvasEndpointConfig,+ domain: str,+ account_id: str,+ api_key: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CanvasLmsResumeConfig],+) -> SourceResponse:+ path = config.path.replace("{account_id}", account_id)++ rest_config: RESTAPIConfig = {+ "client": _client_config(domain, api_key),+ "resource_defaults": {},+ "resources": [+ {+ "name": config.name,+ "endpoint": {+ "path": path,+ "params": {"per_page": config.page_size},+ },+ "table_format": "delta",+ }+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and resume.next_url and _is_same_host(resume.next_url, domain):+ initial_paginator_state = {"next_url": resume.next_url}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; save AFTER a page is yielded so a crash re-fetches+ # the next page (merge dedupes) rather than skipping data.+ if state and state.get("next_url"):+ resumable_source_manager.save_state(CanvasLmsResumeConfig(next_url=state["next_url"]))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ def items() -> Iterable[Any]:+ # Re-check at run time (not just at source-create) in case the domain was edited or now+ # resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.+ host_ok, host_err = _is_host_safe(normalize_domain(domain), team_id)+ if not host_ok:+ raise CanvasHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ yield from resource++ return _make_source_response(config, items)+++def _fanout_source(+ config: CanvasEndpointConfig,+ domain: str,+ account_id: str,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CanvasLmsResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ incremental_field: str | None,+) -> SourceResponse:+ assert config.fanout is not None++ initial_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and (resume.completed or resume.current):+ initial_state = {+ "completed": resume.completed or [],+ "current": resume.current,+ "child_state": resume.child_state,+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state is not None:+ resumable_source_manager.save_state(+ CanvasLmsResumeConfig(+ completed=state.get("completed"),+ current=state.get("current"),+ child_state=state.get("child_state"),+ )+ )++ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=CANVAS_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=_client_config(domain, api_key),+ path_format_values={"account_id": account_id},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field,+ incremental_config_factory=lambda field_name: _incremental_window(+ field_name, config.incremental_query_params[field_name]+ ),+ page_size_param="per_page",+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ ),+ )++ def items() -> Iterable[Any]:+ host_ok, host_err = _is_host_safe(normalize_domain(domain), team_id)+ if not host_ok:+ raise CanvasHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)+ yield from dependent_resource++ return _make_source_response(config, items)+++def canvas_lms_source(+ domain: str,+ account_id: str,+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CanvasLmsResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = CANVAS_ENDPOINTS[endpoint]++ if config.fanout is not None:+ return _fanout_source(+ config,+ domain,+ account_id,+ api_key,+ endpoint,+ team_id,+ job_id,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,+ )++ return _non_fanout_source(config, domain, account_id, api_key, team_id, job_id, resumable_source_manager)+++__all__ = [+ "CanvasHostNotAllowedError",+ "CanvasLmsResumeConfig",+ "HOST_NOT_ALLOWED_ERROR",+ "canvas_lms_source",+ "normalize_domain",+ "validate_credentials",+]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/settings.pynew file mode 100644index 000000000000..276d151ac035--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/settings.py@@ -0,0 +1,102 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++# Canvas caps per_page well above its documented default of 10; institutions can have thousands of+# courses/users/submissions, so request the largest page the API accepts.+PAGE_SIZE = 100++# Submissions fan out per course. The Submission object carries no `course_id`, so the fan-out+# helper injects the parent course id under this rename.+_COURSE_FANOUT = DependentEndpointConfig(+ parent_name="courses",+ resolve_param="course_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "course_id"},+)+++# Mutable by choice, not oversight: instances flow into `build_dependent_resource`'s+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's+# fields as read-only, which is incompatible with that Protocol's plain (read-write) attributes.+@dataclass(frozen=False)+class CanvasEndpointConfig:+ name: str+ path: str # relative to /api/v1+ primary_keys: list[str]+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: Optional[str] = None+ # Maps an advertised incremental field name to the query param Canvas actually filters on+ # for it (e.g. `submitted_at` -> `submitted_since`).+ incremental_query_params: dict[str, str] = field(default_factory=dict)+ fanout: Optional[DependentEndpointConfig] = None+ page_size: int = PAGE_SIZE+++CANVAS_ENDPOINTS: dict[str, CanvasEndpointConfig] = {+ # Account-level listing requires an account admin token; there is no documented+ # `updated_since`-style filter, so this is full refresh every sync.+ "courses": CanvasEndpointConfig(+ name="courses",+ path="/accounts/{account_id}/courses",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "users": CanvasEndpointConfig(+ name="users",+ path="/accounts/{account_id}/users",+ primary_keys=["id"],+ ),+ # `id` is unique per enrollment but the docs don't state whether it's globally unique across+ # the install, so `course_id` (a native field on the Enrollment object) is kept in the key.+ "enrollments": CanvasEndpointConfig(+ name="enrollments",+ path="/courses/{course_id}/enrollments",+ primary_keys=["id", "course_id"],+ partition_key="created_at",+ fanout=_COURSE_FANOUT,+ ),+ # No documented `updated_since` filter for this endpoint, despite the Assignment object+ # exposing `updated_at` -- full refresh only.+ "assignments": CanvasEndpointConfig(+ name="assignments",+ path="/courses/{course_id}/assignments",+ primary_keys=["id", "course_id"],+ partition_key="created_at",+ fanout=_COURSE_FANOUT,+ ),+ # `assignment_id` + `user_id` is unique per submission by Canvas's data model (one submission+ # per student per assignment) regardless of course, so no parent id is needed in the key.+ "submissions": CanvasEndpointConfig(+ name="submissions",+ path="/courses/{course_id}/students/submissions",+ primary_keys=["assignment_id", "user_id"],+ incremental_fields=[incremental_field("submitted_at"), incremental_field("graded_at")],+ default_incremental_field="submitted_at",+ incremental_query_params={"submitted_at": "submitted_since", "graded_at": "graded_since"},+ fanout=DependentEndpointConfig(+ parent_name="courses",+ resolve_param="course_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "course_id"},+ # `student_ids[]=all` returns every student's submissions rather than just the+ # caller's own. `order=id` matches the endpoint's documented default explicitly, so+ # pagination stays stable even if Canvas ever changes that default.+ child_params={"student_ids[]": "all", "order": "id", "order_direction": "ascending"},+ ),+ ),+}++ENDPOINTS = tuple(CANVAS_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CANVAS_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/source.pyindex 58a15d048716..b337f5d5da01 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/source.py@@ -1,13 +1,35 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms import (+ HOST_NOT_ALLOWED_ERROR,+ CanvasLmsResumeConfig,+ canvas_lms_source,+ validate_credentials as validate_canvas_lms_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.canvaslms import (CanvasLmsSourceConfig,)@@ -15,18 +37,132 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CanvasLmsSource(SimpleSource[CanvasLmsSourceConfig]):+class CanvasLmsSource(ResumableSource[CanvasLmsSourceConfig, CanvasLmsResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs++ # Canvas's REST API has always been served at a bare `/api/v1` with no versioned releases or+ # changelog to pin against.+ api_docs_url = "https://developerdocs.instructure.com/services/canvas"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CANVASLMS+ @property+ def connection_host_fields(self) -> list[str]:+ # `canvas_domain` is where the stored access token is sent, and `account_id` determines+ # which Canvas tenant it acts on -- retargeting either must re-require the token.+ return ["canvas_domain", "account_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CANVAS_LMS,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="Instructure Canvas LMS",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["canvas", "lms", "instructure", "education"],+ caption="""Enter your Canvas domain, account ID, and an access token to pull course, enrollment, assignment, and submission data into the PostHog Data warehouse.++Generate a token from **Account → Settings → Approved Integrations → New access token** in Canvas. Use an admin account so the token can list every course in your account.++Find your account ID in the URL when you view **Admin → [your account] → Settings** — it's the number after `/accounts/` (for example, `1` in `https://yourschool.instructure.com/accounts/1`).""",iconPath="/static/services/canvas_lms.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/canvas-lms",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="canvas_domain",+ label="Canvas domain",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="yourschool.instructure.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="account_id",+ label="Account ID",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="1",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="api_key",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Canvas access token is invalid or has been revoked. Generate a new token and reconnect.",+ "403 Client Error": "Your Canvas access token doesn't have admin access to this account. Check the token's account and try again.",+ HOST_NOT_ALLOWED_ERROR: "The Canvas domain is not allowed. Please use your institution's Canvas domain.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CanvasLmsSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ # Submissions mutate in place (grades/scores change after submission), so append-only+ # would duplicate rows for every graded update -- merge is the only incremental mode.+ merge_only=("submissions",),+ )++ def validate_credentials(+ self,+ config: CanvasLmsSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_canvas_lms_credentials(+ config.canvas_domain, config.account_id, config.api_key, schema_name, team_id+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CanvasLmsResumeConfig]:+ return ResumableSourceManager[CanvasLmsResumeConfig](inputs, CanvasLmsResumeConfig)++ def source_for_pipeline(+ self,+ config: CanvasLmsSourceConfig,+ resumable_source_manager: ResumableSourceManager[CanvasLmsResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return canvas_lms_source(+ domain=config.canvas_domain,+ account_id=config.account_id,+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/tests/test_canvas_lms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/tests/test_canvas_lms.pynew file mode 100644index 000000000000..7adfe5a8d1fc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/tests/test_canvas_lms.py@@ -0,0 +1,495 @@+import json+from datetime import UTC, date, datetime+from typing import Any, Optional, cast++import pytest+from unittest import mock++from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms import canvas_lms as canvas_lms_module+from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms import (+ CanvasHostNotAllowedError,+ CanvasLmsResumeConfig,+ _format_canvas_datetime,+ _incremental_window,+ canvas_lms_source,+ normalize_domain,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager++CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+++def _response(items: Optional[list[dict[str, Any]]], *, status_code: int = 200, link: Optional[str] = None) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(items if items is not None else []).encode()+ if link:+ resp.headers["Link"] = link+ return resp+++def _make_manager(resume_state: Optional[CanvasLmsResumeConfig] = None) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:+ session.headers = {}+ snapshots: list[dict[str, Any]] = []++ def _prepare(request: Any) -> mock.MagicMock:+ snapshots.append({"url": request.url, "params": dict(request.params or {})})+ # Mirror `requests.Session.prepare_request`: the real prepared request's `.url`+ # is what `RESTClient._check_allowed_host` inspects (host/scheme/port pinning), so+ # a bare `MagicMock()` here -- whose `.url` is an unconfigured child mock -- fails+ # `urlparse`/`urlsplit` with a `MagicMock`-vs-`int` `TypeError` once that host check+ # runs, rather than exercising it.+ prepared = mock.MagicMock()+ prepared.url = request.url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return snapshots+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++class TestNormalizeDomain:+ @parameterized.expand(+ [+ ("yourschool.instructure.com", "yourschool.instructure.com"),+ ("https://yourschool.instructure.com", "yourschool.instructure.com"),+ ("http://yourschool.instructure.com/", "yourschool.instructure.com"),+ (" yourschool.instructure.com ", "yourschool.instructure.com"),+ ("yourschool.instructure.com/api/v1", "yourschool.instructure.com"),+ ("canvas.university.edu", "canvas.university.edu"),+ ]+ )+ def test_normalize_domain(self, raw, expected):+ assert normalize_domain(raw) == expected+++class TestFormatCanvasDatetime:+ def test_formats_naive_datetime_as_utc(self):+ assert _format_canvas_datetime(datetime(2024, 1, 15, 9, 30, 0)) == "2024-01-15T09:30:00Z"++ def test_formats_aware_datetime(self):+ assert _format_canvas_datetime(datetime(2024, 1, 15, 9, 30, 0, tzinfo=UTC)) == "2024-01-15T09:30:00Z"++ def test_formats_date(self):+ assert _format_canvas_datetime(date(2024, 1, 15)) == "2024-01-15T00:00:00Z"++ def test_caps_future_datetime_to_now(self):+ far_future = datetime(2999, 1, 1, tzinfo=UTC)+ formatted = _format_canvas_datetime(far_future)+ assert formatted != "2999-01-01T00:00:00Z"+ assert datetime.strptime(formatted, "%Y-%m-%dT%H:%M:%SZ") <= datetime.now(UTC).replace(tzinfo=None)++ def test_passes_through_already_formatted_string(self):+ assert _format_canvas_datetime("1970-01-01T00:00:00Z") == "1970-01-01T00:00:00Z"+++class TestIncrementalWindow:+ @parameterized.expand(+ [+ ("submitted_at", "submitted_since"),+ ("graded_at", "graded_since"),+ ]+ )+ def test_shape(self, field_name, query_param):+ window = _incremental_window(field_name, query_param)++ assert window["cursor_path"] == field_name+ assert window["start_param"] == query_param+ assert window["initial_value"] == "1970-01-01T00:00:00Z"+ assert window["convert"] is _format_canvas_datetime+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(canvas_lms_module, "make_tracked_session", return_value=session)++ def _resp(self, *, status_code=200, text=""):+ response = mock.MagicMock()+ response.status_code = status_code+ response.is_redirect = status_code in (301, 302, 303, 307, 308)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ return response++ def test_success(self):+ with self._patch_session(self._resp(status_code=200)):+ assert validate_credentials("yourschool.instructure.com", "1", "tok") == (True, None)++ def test_invalid_token(self):+ with self._patch_session(self._resp(status_code=401)):+ valid, msg = validate_credentials("yourschool.instructure.com", "1", "tok")+ assert valid is False+ assert msg == "Invalid Canvas access token"++ def test_unknown_account_is_rejected(self):+ with self._patch_session(self._resp(status_code=404)):+ valid, msg = validate_credentials("yourschool.instructure.com", "999", "tok")+ assert valid is False+ assert msg == "Canvas account not found. Check the account ID and try again."++ def test_403_at_source_create_is_accepted(self):+ with self._patch_session(self._resp(status_code=403)):+ assert validate_credentials("yourschool.instructure.com", "1", "tok", schema_name=None) == (True, None)++ def test_403_for_scoped_probe_fails(self):+ with self._patch_session(self._resp(status_code=403)):+ valid, msg = validate_credentials("yourschool.instructure.com", "1", "tok", schema_name="courses")+ assert valid is False+ assert msg is not None++ @pytest.mark.parametrize("bad_domain", ["", "not a domain!", "https://"])+ def test_invalid_domain_short_circuits(self, bad_domain):+ valid, msg = validate_credentials(bad_domain, "1", "tok")+ assert valid is False+ assert msg is not None++ def test_request_exception_returns_failure(self):+ import requests++ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):+ valid, msg = validate_credentials("yourschool.instructure.com", "1", "tok")+ assert valid is False+ assert "boom" in (msg or "")++ def test_rejects_redirect_response(self):+ with self._patch_session(self._resp(status_code=302)) as patched:+ valid, msg = validate_credentials("yourschool.instructure.com", "1", "tok")+ assert valid is False+ assert msg == canvas_lms_module.HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host(self):+ with (+ mock.patch.object(canvas_lms_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(self._resp(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("10.0.0.1", "1", "tok", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()+++class TestCanvasLmsSourceResponse:+ @parameterized.expand(+ [+ ("courses", ["id"], "created_at"),+ ("users", ["id"], None),+ ("enrollments", ["id", "course_id"], "created_at"),+ ("assignments", ["id", "course_id"], "created_at"),+ ("submissions", ["assignment_id", "user_id"], None),+ ]+ )+ def test_response_shape(self, endpoint, primary_keys, partition_key):+ response = canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="1",+ api_key="tok",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=_make_manager(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.sort_mode == "asc"+ if partition_key:+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestCanvasLmsTopLevelPagination:+ def _source(self, endpoint="courses", manager=None, **kwargs):+ return canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="1",+ api_key="tok",+ endpoint=endpoint,+ team_id=1,+ job_id="j",+ resumable_source_manager=manager if manager is not None else _make_manager(),+ **kwargs,+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_link_header_across_pages(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(+ session,+ [+ _response(+ [{"id": "1"}, {"id": "2"}],+ link='<https://yourschool.instructure.com/api/v1/accounts/1/courses?page=bookmark>; rel="next"',+ ),+ _response([{"id": "3"}]),+ ],+ )+ rows = _rows(self._source())++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ assert snaps[0]["url"] == "https://yourschool.instructure.com/api/v1/accounts/1/courses"+ assert snaps[0]["params"]["per_page"] == 100+ assert snaps[1]["url"] == "https://yourschool.instructure.com/api/v1/accounts/1/courses?page=bookmark"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_saves_state_after_yielding(self, MockSession):+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(+ [{"id": "1"}],+ link='<https://yourschool.instructure.com/api/v1/accounts/1/courses?page=bookmark>; rel="next"',+ ),+ _response([{"id": "2"}]),+ ],+ )+ manager = _make_manager()+ _rows(self._source(manager=manager))++ manager.save_state.assert_called_once()+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, CanvasLmsResumeConfig)+ assert saved.next_url == "https://yourschool.instructure.com/api/v1/accounts/1/courses?page=bookmark"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_state(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response([{"id": "9"}])])+ manager = _make_manager(+ CanvasLmsResumeConfig(next_url="https://yourschool.instructure.com/api/v1/accounts/1/courses?page=resume")+ )+ rows = _rows(self._source(manager=manager))++ assert snaps[0]["url"] == "https://yourschool.instructure.com/api/v1/accounts/1/courses?page=resume"+ assert [r["id"] for r in rows] == ["9"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_does_not_follow_next_url_on_foreign_host(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response([{"id": "1"}], link='<http://169.254.169.254/latest/meta-data/>; rel="next"')])+ rows = _rows(self._source())++ assert [r["id"] for r in rows] == ["1"]+ assert session.send.call_count == 1++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_ignores_resume_url_on_foreign_host(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response([{"id": "1"}])])+ manager = _make_manager(CanvasLmsResumeConfig(next_url="http://169.254.169.254/latest/meta-data/"))+ rows = _rows(self._source(manager=manager))++ assert snaps[0]["url"].startswith("https://yourschool.instructure.com/api/v1/accounts/1/courses")+ assert [r["id"] for r in rows] == ["1"]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_runtime_host_check_blocks_unsafe_domain(self, MockSession):+ session = MockSession.return_value+ _wire(session, [_response([{"id": "1"}])])+ with mock.patch.object(canvas_lms_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(CanvasHostNotAllowedError):+ _rows(self._source())+ session.send.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_users_endpoint_builds_correct_path(self, MockSession):+ session = MockSession.return_value+ snaps = _wire(session, [_response([{"id": "1"}])])+ _rows(self._source(endpoint="users"))++ assert snaps[0]["url"] == "https://yourschool.instructure.com/api/v1/accounts/1/users"+++class _FakeDltResource:+ """Stand-in for a DltResource returned by ``rest_api_resources``."""++ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper: Any) -> "_FakeDltResource":+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++class TestCanvasLmsFanout:+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_submissions_injects_course_id_from_parent(self, mock_rest_api_resources):+ mock_rest_api_resources.return_value = [+ _FakeDltResource("courses", [{"id": "1000"}]),+ _FakeDltResource("submissions", [{"assignment_id": "1", "user_id": "2", "_courses_id": "1000"}]),+ ]+ manager = _make_manager()++ resp = canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="1",+ api_key="tok",+ endpoint="submissions",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )++ rows = list(cast(Any, resp.items()))+ assert len(rows) == 1+ row = rows[0]+ assert row["course_id"] == "1000"+ assert "_courses_id" not in row++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms.build_dependent_resource"+ )+ def test_enrollments_fanout_pins_account_id_and_page_size_param(self, mock_build):+ mock_build.return_value = iter([])+ manager = _make_manager()++ canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="42",+ api_key="tok",+ endpoint="enrollments",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )++ _, kwargs = mock_build.call_args+ assert kwargs["path_format_values"] == {"account_id": "42"}+ assert kwargs["page_size_param"] == "per_page"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms.build_dependent_resource"+ )+ def test_submissions_incremental_maps_field_to_query_param(self, mock_build):+ mock_build.return_value = iter([])+ manager = _make_manager()++ canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="1",+ api_key="tok",+ endpoint="submissions",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="graded_at",+ )++ _, kwargs = mock_build.call_args+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["incremental_field"] == "graded_at"+ window = kwargs["incremental_config_factory"]("submitted_at")+ assert window["start_param"] == "submitted_since"+ window = kwargs["incremental_config_factory"]("graded_at")+ assert window["start_param"] == "graded_since"++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms.build_dependent_resource"+ )+ def test_fanout_seeds_resume_state_and_wires_hook(self, mock_build):+ mock_build.return_value = iter([])+ manager = _make_manager(+ CanvasLmsResumeConfig(+ completed=["/courses/1/enrollments"], current="/courses/2/enrollments", child_state={"next_url": "x"}+ )+ )++ canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="1",+ api_key="tok",+ endpoint="enrollments",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )++ _, kwargs = mock_build.call_args+ assert kwargs["initial_paginator_state"] == {+ "completed": ["/courses/1/enrollments"],+ "current": "/courses/2/enrollments",+ "child_state": {"next_url": "x"},+ }++ kwargs["resume_hook"](+ {"completed": ["/courses/1/enrollments", "/courses/2/enrollments"], "current": None, "child_state": None}+ )+ manager.save_state.assert_called_once_with(+ CanvasLmsResumeConfig(+ completed=["/courses/1/enrollments", "/courses/2/enrollments"], current=None, child_state=None+ )+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms.build_dependent_resource"+ )+ def test_fanout_does_not_load_state_when_cannot_resume(self, mock_build):+ mock_build.return_value = iter([])+ manager = _make_manager()++ canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="1",+ api_key="tok",+ endpoint="assignments",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )++ manager.load_state.assert_not_called()+ _, kwargs = mock_build.call_args+ assert kwargs["initial_paginator_state"] is None++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms._is_host_safe")+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms.build_dependent_resource"+ )+ def test_fanout_runtime_host_check_blocks_unsafe_domain(self, mock_build, mock_is_host_safe):+ mock_build.return_value = iter([[{"id": "1"}]])+ mock_is_host_safe.return_value = (False, "internal address")+ manager = _make_manager()++ resp = canvas_lms_source(+ domain="yourschool.instructure.com",+ account_id="1",+ api_key="tok",+ endpoint="assignments",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ )++ with pytest.raises(CanvasHostNotAllowedError):+ _rows(resp)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/tests/test_canvas_lms_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/tests/test_canvas_lms_source.pynew file mode 100644index 000000000000..3348d2bab922--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/canvas_lms/tests/test_canvas_lms_source.py@@ -0,0 +1,153 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.canvas_lms import CanvasLmsResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.source import CanvasLmsSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.canvaslms import (+ CanvasLmsSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCanvasLmsSource:+ def setup_method(self):+ self.source = CanvasLmsSource()+ self.team_id = 123+ self.config = CanvasLmsSourceConfig(canvas_domain="yourschool.instructure.com", account_id="1", api_key="tok")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CANVASLMS++ def test_connection_host_fields(self):+ assert self.source.connection_host_fields == ["canvas_domain", "account_id"]++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "CanvasLms"+ assert config.label == "Instructure Canvas LMS"+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/canvas_lms.png"++ field_names = [f.name for f in config.fields]+ assert field_names == ["canvas_domain", "account_id", "api_key"]++ domain_field, account_field, token_field = config.fields+ assert isinstance(domain_field, SourceFieldInputConfig)+ assert domain_field.type == SourceFieldInputConfigType.TEXT+ assert domain_field.secret is False++ assert isinstance(account_field, SourceFieldInputConfig)+ assert account_field.type == SourceFieldInputConfigType.TEXT+ assert account_field.secret is False++ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("courses", False),+ ("users", False),+ ("enrollments", False),+ ("assignments", False),+ ("submissions", True),+ ]+ )+ def test_schema_incremental_support(self, endpoint, incremental):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[endpoint].supports_incremental is incremental++ def test_submissions_is_merge_only(self):+ # Submissions mutate in place (grades change), so append-only would duplicate rows.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["submissions"].supports_incremental is True+ assert schemas["submissions"].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["courses"])+ assert len(schemas) == 1+ assert schemas[0].name == "courses"++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ @pytest.mark.parametrize(+ "mock_return, expected",+ [+ ((True, None), (True, None)),+ ((False, "Invalid Canvas access token"), (False, "Invalid Canvas access token")),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.source.validate_canvas_lms_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="courses")++ assert result == expected+ mock_validate.assert_called_once_with(+ self.config.canvas_domain, self.config.account_id, self.config.api_key, "courses", self.team_id+ )++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CanvasLmsResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.source.canvas_lms_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_canvas_lms_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "submissions"+ inputs.team_id = 42+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"+ inputs.incremental_field = "submitted_at"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_canvas_lms_source.assert_called_once()+ kwargs = mock_canvas_lms_source.call_args.kwargs+ assert kwargs["domain"] == "yourschool.instructure.com"+ assert kwargs["account_id"] == "1"+ assert kwargs["api_key"] == "tok"+ assert kwargs["endpoint"] == "submissions"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42+ assert kwargs["job_id"] == "job-1"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00Z"+ assert kwargs["incremental_field"] == "submitted_at"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.canvas_lms.source.canvas_lms_source")+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_canvas_lms_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "courses"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "ignored"+ inputs.incremental_field = None++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_canvas_lms_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/canvaslms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/canvaslms.pyindex c3c8962da269..6ba673655305 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/canvaslms.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/canvaslms.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CanvasLmsSourceConfig(config.Config):- pass+ canvas_domain: str+ account_id: str+ api_key: str