From 7e7c60a519fd6b6a4c483c8efc6c2ad782304b8b Mon Sep 17 00:00:00 2001 From: Anthony Giacalone Date: Wed, 21 Oct 2026 10:17:28 -0700 Subject: [PATCH] Add reg-canvas: Canvas API support for grades, roster and content CSULB ATS issued a personal Canvas token on 2026-10-21. Until now every Canvas step was a manual export, upload or paste. canvas_api is the only module that reads the token. It reads it from a mode-600 file, sends it only to the configured host, refuses redirects and scrubs it from errors. It uses only the standard library. reg-canvas adds read commands (whoami, courses --bind, grades-export, roster-check) and write commands (grades-push, announce, discussion, assignment, syllabus). Every write is a dry run until --apply. grades-export keeps only score fields from the submissions endpoint and writes exports mode 600. The README, SKILL.md, AGENTS.md and docs describe the API path. The dry-run rule is repeated in each of them on purpose. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01N64GRxn3cQDJKAJLdfrso2 --- AGENTS.md | 3 + CHANGELOG.md | 1 + README.md | 32 +- SKILL.md | 39 +- docs/README.md | 1 + docs/canvas-api.md | 262 +++++++++++ docs/canvas-grades-workflow.md | 6 + install.sh | 1 + lectern/c50.py | 5 +- lectern/canvas.py | 764 +++++++++++++++++++++++++++++++++ lectern/canvas_api.py | 279 ++++++++++++ tests/test_canvas.py | 407 ++++++++++++++++++ 12 files changed, 1793 insertions(+), 7 deletions(-) create mode 100644 docs/canvas-api.md create mode 100644 lectern/canvas.py create mode 100644 lectern/canvas_api.py create mode 100644 tests/test_canvas.py diff --git a/AGENTS.md b/AGENTS.md index 6b721db..4a20771 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,7 @@ Every skill action maps to a `reg-*` CLI command. An agent performing any Lecter | Run item analysis from Gradescope evaluations | `reg-gradescope-stats` | `gradescope_stats` | | Normalize Canvas grades export | `reg-lms-grades-import` | `lms_grades` | | Normalize CSULB enrollment roster | `reg-lms-roster-import` | `lms_roster` | +| Canvas API: export/push grades, roster check, post announcements, discussions, assignments, syllabus | `reg-canvas` | `canvas` (client: `canvas_api`) | | Pre-seed GitHub Classroom roster | `reg-classroom-roster-seed` | `classroom_seed` | | Bind student GitHub IDs to roster entries | `reg-github-bind` | `github_bind` | | Publish ISA grading artifacts to Drive | `reg-isa-publish` | `isa_publish` | @@ -43,6 +44,8 @@ releases. `reg-exam-readinglist` is installed as a standalone `~/bin` wrapper (n - All commands accept `--vault-root ` to locate vault notes. Pass it explicitly; never rely on a hard-coded default. - Prefer `--dry-run` on `reg-term-finalize` before committing; the agent should surface the preview output for review. - `reg-term-archive --check` exits 0 on a clean bundle and nonzero on drift — use the exit code as a quality gate. +- **`reg-canvas` writes are dry runs until `--apply`.** Show the dry run first. An agent never passes `--apply` to a live section (announcements notify students at once; grades are visible once posted) without the instructor's go-ahead for that specific run. Test against the sandbox course with `--course-id`. +- **Never read the Canvas token file** (`~/.config/lectern/canvas-token`). The client reads it; nothing else needs to. - All state lives in plain files (Markdown · CSV · YAML · LaTeX) — the agent can read and diff these directly. ## Skill file diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d93e1b..6152f3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to lectern are documented here. ## [Unreleased] ### Added +- **`reg-canvas`: Canvas API support.** CSULB ATS issued a personal Canvas token on 2026-10-21. Until then lectern had no Canvas integration, and every Canvas step was a manual export, upload or paste. The new `canvas_api` module is the only code that touches the token. It reads the token from `~/.config/lectern/canvas-token` and refuses a file that group or other can read. It never takes the token from argv or the environment, sends it only to the configured host, refuses redirects (urllib would forward the `Authorization` header to the redirect's host), and scrubs it from every error. It uses only the standard library, so lectern's runtime dependencies do not change. `reg-canvas` puts nine subcommands on top of it. The read commands are `whoami`, `courses` (`--bind` writes `canvas.course-id` into each class note, using the term name when a class number recurs across years), `grades-export` and `roster-check` (Canvas compared with the registrar roster, for census week). `grades-export` writes the same CSV that Canvas's *Export* button does, so `reg-lms-grades-import` and `reg-gradebook export-canvas --template` take it unchanged; the per-group subtotal columns are the one difference, and nothing reads them. The write commands are `grades-push`, `announce`, `discussion`, `assignment` and `syllabus`, and each is a dry run until `--apply`. `grades-push` applies an overlay CSV, changed cells only. A blank cell never clears a grade, and a file whose assignment IDs belong to another course is refused. `discussion` and `assignment` create items unpublished, `assignment --lab N` takes its name and points from the vault, `syllabus` refuses a file without the class note's serial, and all three content commands skip a title that already exists. Data scope is what was promised to CSULB IT: names, student IDs and grades for the instructor's own sections. Scores come from the submissions endpoint, but only score fields are kept and submission content is dropped on arrival. Exports are written mode 600. Live-checked on 2026-10-21 against the three Fa26 sections (reads) and the sandbox course (an unpublished discussion and assignment, since deleted). Runbook: `docs/canvas-api.md`, which opens with how the pieces fit and ends with troubleshooting. The README (intro, command table, architecture, dependencies, an optional quickstart), `SKILL.md`, `AGENTS.md` and `docs/canvas-grades-workflow.md` all describe the API path, and each repeats that writes are dry runs until `--apply`. - **`reg-exam-build` writes a per-outcome `GRADING_NOTE.md` for every Gradescope build.** The note was a one-line-per-question summary table, which left the grader to invent the Gradescope rubric. It is now the ISA work order: every question gets one rubric row per possible outcome (each MC choice, both T/F sides, each FIB blank plus a wrong-order row, and every item of an authored `Gradescope rubric` block on written questions), with the points that row carries and a stable `form·Qn·slot` key. Graders enter the rows verbatim and only choose which one applies, so points land the same way whoever grades, and `reg-gradescope-stats` reads the note directly. Graduated from the CECS 378 Su26 prototype (`build_grading_note.py`) into `lectern.grading_note`, with two fixes on the way: a code question keyed True/False no longer loses its credit to a trailing brace, and math in choices renders as `2^(n/2)` rather than `2^{n/2`. `% order: any` before a multi-blank fill drops the wrong-order row. New **`--grading-note-only`** rewrites just the note for an exam that is already printed. - **`reg-guardcheck`: the student's half of the guard-file check.** The instructor-side check reads git history from outside the student's control and is the record; this is the notice the *student* sees, in the CI run they already look at. `stamp` records a template's expected digests to `grading/guard.sha256` (`sha256sum`-format, so `sha256sum -c` verifies it with no tooling); `check` runs as one step in the lab's own `autograde.yml` and reports what changed. ==It notifies, it never grades==: no points, no pass/fail, and it always exits 0 (`--strict` opts out) because failing a student's build over a file that does not affect their program is a bad way to open a conversation. It never invents a `result.json` either, since a result file conjured from nothing reads downstream as a zero-point run; it only records a `notices` array in one that already exists. The message is deliberately unaccusing: what changed, that it does not affect the assignment or the grade, that the instructor sees it in the history, and the `git checkout` line that restores it, plus a GitHub Actions run annotation. Stdlib-only, so a template vendors the single file as `grading/guardcheck.py` and the runner's bare `python3` runs it. Workflow snippet at `lectern/references/guardcheck.workflow.yml`. ==A student controls their own workflow, so this is a courtesy and not evidence==: the sweep is what counts. - **Guard-file integrity: grading checks for repos that modify `AGENTS.md`.** Every lab template ships `AGENTS.md`, the high-authority AI-assistant surface, and the doctrine has always been that a student may delete it because doing so is a visible act in the git history. Nothing actually looked. The new `lectern.triage_guardfile` module compares each declared **guard file** at the grading commit against its baseline and reports `intact`, `modified`, `deleted` or `absent`, with the commits that touched it and a copy-pasteable reproduce command. Wired into all three surfaces: `reg-triage sweep` (a `guard` column in `results.csv`, a Guard column and a *Guard files* roll-up in `TRIAGE.md`), `reg-triage report` (section **A.6 Guard-file integrity**), and `reg-lab-recon` (a `guard` column in `cohort.csv`, a *Guard files* section in `FACTS.md`). Both manifests take `guard_files:`, defaulting to `["AGENTS.md"]`; an entry may be `{path, sha256}` to compare against the file **as distributed**, which is the only way to catch an edit made inside a squashed initial commit. Otherwise the baseline is the file's first appearance in that repo, and a file born modified reads as intact. ==It is a Part A fact and never a score==: `guardfile_forensics` does not register in `SIGNALS`, awards no points, and cannot move a bucket, because there are innocuous reasons to touch these files and the engine's standing rule is that no adverse finding is automated. Report schema bumped to v2; the signal set is unchanged. diff --git a/README.md b/README.md index b3dd1bc..3ffb965 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ **The Registrar** — a 100% open-source teaching-operations toolkit for university instructors. -Lectern handles the full administrative lifecycle of running courses: term scaffolding, gradebook consolidation, exam build and verification, ISA grading artifact publishing, GitHub Classroom binding, campus-LMS (Canvas) roster/grade import, and end-of-term archival. All state lives in plain, version-controllable files. All tools are scriptable CLI commands in the `reg-*` family. +Lectern handles the full administrative lifecycle of running courses: term scaffolding, gradebook consolidation, exam build and verification, ISA grading artifact publishing, GitHub Classroom binding, campus-LMS (Canvas) integration, and end-of-term archival. With a Canvas API token, Lectern exports the gradebook, pushes grades back, checks the roster, and posts announcements, discussions, assignments and the syllabus; without one, the same records move through Canvas's CSV export and import. All state lives in plain, version-controllable files. All tools are scriptable CLI commands in the `reg-*` family. --- @@ -22,7 +22,7 @@ ways: driven by an AI agent (Claude Code skill) *or* run directly by a human via | Tool | Role | Repo | |---|---|---| -| **[Lectern](https://github.com/agiacalone/lectern)** — the Registrar | Course **administration** — terms, sections, gradebook, exam build/verify, Classroom binding, archival. | `agiacalone/lectern` | +| **[Lectern](https://github.com/agiacalone/lectern)** — the Registrar | Course **administration** — terms, sections, gradebook, exam build/verify, Classroom binding, Canvas sync, archival. | `agiacalone/lectern` | | **[Scriptorium](https://github.com/agiacalone/scriptorium)** — the workshop | Course **content** — lecture notes, Cornell handouts, quizzes, slides, question banks. | `agiacalone/scriptorium` | | **[Oracle](https://github.com/agiacalone/oracle)** *(private)* — the secret box | **Grading** — a verify-by-proof oracle service + a sandboxed code-runner (gradebox). | `agiacalone/oracle` *(private — licensed)* | @@ -70,6 +70,7 @@ This is a deliberate design principle, not an accident. Proprietary LMS gradeboo | `reg-exam-build` | `exam_build` | Assemble exam PDFs — single-source `.tex` mode or pack-mode `.yaml` manifest (multi-form A/B/C, per-student individualized, Gradescope products). See below. | | `reg-exam-verify` | `exam_verify` | Verify a student exam serial against the register. Confirms which form and which student a paper belongs to. | | `reg-lms-grades-import` | `lms_grades` | Normalize a Canvas `grades.csv` export to Lectern's canonical format. | +| `reg-canvas` | `canvas` + `canvas_api` | **Canvas API.** Reads: `whoami`, `courses` (`--bind` links each section to its Canvas course in the class note), `grades-export` (the gradebook in Canvas's own export layout, so `reg-lms-grades-import` and `reg-gradebook export-canvas --template` take it unchanged), `roster-check` (Canvas compared with the registrar roster). Writes, each a **dry run until `--apply`**: `grades-push` (an overlay CSV, changed cells only; a blank never clears a grade), `announce`, `discussion` and `assignment` (both unpublished by default), and `syllabus` (refuses a file without its serial). The token lives in one mode-600 file and is sent to one host. See [docs/canvas-api.md](docs/canvas-api.md). | | `reg-lms-roster-import` | `lms_roster` | Normalize a faculty-center enrollment roster (`.xls`/`.xlsx`) to Lectern's canonical format. | | `reg-classroom-roster-seed` | `classroom_seed` | Pre-seed a GitHub Classroom roster from a normalized roster CSV, using the 9-digit student ID as the identifier. | | `reg-github-bind` | `github_bind` | Bind student GitHub usernames to roster entries — from a Google Form CSV, a GitHub Classroom roster CSV, or org-scrape mode. | @@ -139,6 +140,8 @@ lectern/ exam_verify.py register-based serial verification lms_grades.py Canvas grades CSV normalization lms_roster.py enrollment roster normalization (.xls → .csv) + canvas_api.py Canvas REST client: the only module that reads the token + canvas.py reg-canvas: gradebook export/push, roster check, content posting classroom_seed.py GitHub Classroom roster pre-seeding github_bind.py student-id → GitHub username binding isa_publish.py Drive publishing (rclone/service-account backend) @@ -174,7 +177,7 @@ See `docs/design/lab-digest.md` and `docs/design/lab-report.md` for the contract **Vault awareness.** Most commands accept `--vault-root ` to locate course notes, class notes, and archive bundles relative to a notes root. If you do not use a notes-based workflow, pass explicit `--vault-root .` or use the modules as a library with fully explicit paths. The vault path is never hard-coded. -**Dependencies.** Python 3.11+. `pyyaml`, `jsonschema`. LaTeX toolchain (`pdflatex`, `pdfunite` or `qpdf`) for exam builds. `rclone` or a service-account credential for ISA publish. *Optional for `reg-exam-verify`:* `pdfplumber` (else falls back to the `pdftotext` CLI). The former `vaultkit` dependency was removed — the one helper used (`slugify`) is vendored into `lectern/_text.py` (the PyPI name `vaultkit` is an unrelated third-party package, so depending on it was a dependency-confusion risk). +**Dependencies.** Python 3.11+. `pyyaml`, `jsonschema`. The Canvas API client uses only the standard library; it needs a personal Canvas token, and `pandoc` to turn Markdown into Canvas HTML. LaTeX toolchain (`pdflatex`, `pdfunite` or `qpdf`) for exam builds. `rclone` or a service-account credential for ISA publish. *Optional for `reg-exam-verify`:* `pdfplumber` (else falls back to the `pdftotext` CLI). The former `vaultkit` dependency was removed — the one helper used (`slugify`) is vendored into `lectern/_text.py` (the PyPI name `vaultkit` is an unrelated third-party package, so depending on it was a dependency-confusion risk). --- @@ -206,6 +209,26 @@ reg-term-create --help reg-exam-build --help ``` +### Canvas API (optional) + +Everything above works without Canvas access. To let Lectern talk to Canvas +directly, store a personal token and link each section to its course: + +```bash +mkdir -p ~/.config/lectern && chmod 700 ~/.config/lectern +( umask 077; read -rsp "Canvas token: " t; echo; printf '%s\n' "$t" > ~/.config/lectern/canvas-token ) +reg-canvas whoami +reg-canvas courses --bind --term fa26 --vault-root +reg-canvas grades-export --term fa26 --vault-root --import +``` + +> [!CAUTION] +> Every `reg-canvas` write is a dry run until you add `--apply`. Read the dry +> run first: announcements notify students as soon as they post. + +The full guide, including token activation and troubleshooting, is +[docs/canvas-api.md](docs/canvas-api.md). + ### Minimal exam build (single form) ```bash @@ -275,7 +298,7 @@ Lectern addresses several standardized-infrastructure concerns directly: **Autograding integration.** Code and lab autograding is performed by **[Oracle](https://github.com/agiacalone/oracle)** — a verify-by-proof oracle service paired with a sandboxed `gradebox` runner. Lectern *coordinates and records* the results: the archive bundle's `manifest.yaml` tracks template repo commits and lab names alongside exam serials and grade distributions, and ISA-published artifacts (keys, rubrics) live in a structured Drive folder matching the term/section/course hierarchy so graders can always find the authoritative rubric for a given assignment. (MC-bubble and Gradescope exam autograding are Lectern's own — see [`docs/gradescope-workflow.md`](docs/gradescope-workflow.md).) -**Gradebook as data.** `reg-gradebook` produces `gradebook.csv` — a plain CSV that is the canonical, diff-able record of every student's grades. It is never the sole copy: Canvas is the student-facing authority, the archive bundle is the institutional record, and the CSV is the analytical layer that enables DFW rollups, section-to-section comparisons, and grade-appeal lookups from the command line. +**Gradebook as data.** `reg-gradebook` produces `gradebook.csv` — a plain CSV that is the canonical, diff-able record of every student's grades. It is never the sole copy: Canvas is the student-facing authority (grades reach it through `reg-canvas grades-push`, or a CSV import without a token), the archive bundle is the institutional record, and the CSV is the analytical layer that enables DFW rollups, section-to-section comparisons, and grade-appeal lookups from the command line. --- @@ -286,6 +309,7 @@ Lectern addresses several standardized-infrastructure concerns directly: | [docs/README.md](docs/README.md) | Documentation index | | [docs/design/exam-system.md](docs/design/exam-system.md) | Multi-form exam system design: A/B variants, individualized builds, Gradescope products, defensibility | | [docs/design/exam-tex-format.md](docs/design/exam-tex-format.md) | House `.tex` format: header block, answer key toggle, per-student serials, color conventions, appeals runbook | +| [docs/canvas-api.md](docs/canvas-api.md) | `reg-canvas`: token setup, the read and write commands, data scope, and the safety rules | | [docs/gradescope-workflow.md](docs/gradescope-workflow.md) | Using Lectern-built exams with Gradescope: region/bubble, A/B Version Sets, roster, identity verification | --- diff --git a/SKILL.md b/SKILL.md index b1897ea..5843caf 100644 --- a/SKILL.md +++ b/SKILL.md @@ -26,6 +26,7 @@ records of running courses. All tools are vault-aware via an explicit | `reg-lms-roster-import` | lms_roster | Normalize a CSULB faculty-center roster export | | `reg-c50` | c50 | **Classroom 50** — the GitHub Classroom successor (legacy sunset 2026-08-28). `classroom-add` creates one classroom per section from the term-spec · `codes` mints the per-section self-enrollment codes · `roster-import` turns collected GitHub usernames into a roster + org invitations · `post` registers a lab as an assignment in every section that teaches it, binds it into the class notes, and writes the Canvas announcement · `status` reads back what is actually registered. Resolves org, classroom, slug, template, points and due date from the vault rather than the command line | | `reg-guardcheck` | guardcheck | **In-CI course-file notification.** `stamp` records the expected digests of a template's guard files; `check` runs inside the lab's own autograde workflow and tells the *student* when one has changed. ==Notifies, never grades==: no points, no pass/fail, always exits 0 (`--strict` opts out). Stdlib-only so a template can vendor the single file. The authoritative check is instructor-side `reg-triage`, which reads git history from outside the student's control | +| `reg-canvas` | canvas | **Canvas API.** Reads: `whoami`, `courses` (`--bind` records each section's `canvas.course-id` in its class note), `grades-export` (the gradebook as the same CSV Canvas's *Export* writes, into `archives/-/canvas/`, `--import` chains `reg-lms-grades-import`), `roster-check` (Canvas vs registrar roster). Writes, ==dry run unless `--apply`==: `grades-push` (a Canvas-format import CSV, changed cells only), `announce`, `discussion` (unpublished by default), `assignment` (`--lab N` fills name + points from the vault), `syllabus` (refuses a file without the class note's serial). Token: `~/.config/lectern/canvas-token`, mode 600, never in argv, logs or the vault. Runbook: `docs/canvas-api.md` | | `reg-classroom-roster-seed` | classroom_seed | ==**RETIRED** — legacy GitHub Classroom, and it never worked live== (it POSTed to a read-only endpoint). Kept only so old runbooks resolve. Use `reg-c50 roster-import` | | `reg-github-bind` | github_bind | Bind student GitHub IDs to roster entries | | `reg-isa-publish` | isa_publish | Publish ISA grading artifacts to Drive (rclone/gdrive backend) | @@ -208,7 +209,7 @@ At CSULB an instructor can obtain **neither** identifier for their own students: | Canvas gradebook export | No — `SIS Login ID` is the 9-digit student number | | MyCSULB faculty-center roster | No — "Notify" is a mail-merge checkbox, not an address | | Canvas People page or its export | Not shown, and not offered to instructors | -| Canvas API | "New Access Token" is disabled for instructor accounts | +| Canvas API | Not used for this. Instructors cannot mint tokens; ATS issues one on request (granted 2026-10-21, see `reg-canvas`), and lectern reads only names and student IDs through it | Deriving `first.last@student.csulb.edu` does not rescue it either: of 171 Fa26 students only **69** have unambiguous two-token names, and six collide outright. @@ -262,6 +263,42 @@ but real* username silently invites a stranger. Runbook: `notes/c50-self-enrollment.md`. Gotchas: `notes/classroom-50-gotchas.md`. +## Canvas API (`reg-canvas`) + +ATS issued a personal Canvas token on 2026-10-21 (Instructure caps it at 90 +days, so it expires **2027-01-19**). Lectern holds the token in one module, +`canvas_api`, which reads it from `~/.config/lectern/canvas-token`, checks the +file is mode 600, sends it only to the configured Canvas host, refuses +redirects, and scrubs it from every error. + +```sh +reg-canvas whoami +reg-canvas courses --bind --term fa26 --vault-root # once per term +reg-canvas grades-export --term fa26 --vault-root --import # all sections +reg-canvas roster-check --term fa26 --vault-root --roster '/…/fa26-{section}/roster.csv' +reg-canvas grades-push --term fa26 --vault-root --course "CECS 326" --section 01 \ + --file canvas-lab2-import.csv --only "Lab 2 - …" # dry run; add --apply +reg-canvas announce --term fa26 --vault-root --course "CECS 326" \ + --file '/posted/fa26-{section}-ANNOUNCE.md' # dry run; add --apply +``` + +==Every write is a dry run until `--apply`.== An agent shows the dry run and +waits for the instructor's go-ahead before applying to a live section: +announcements notify students the moment they post. `--course-id 14635` (the +sandbox) bypasses the vault for testing. ==Never read the token file.== + +**Data scope** matches what was promised to CSULB IT on 2026-10-16: course +content, plus names, student IDs and grades for the instructor's own sections. +`grades-export` reads scores from the submissions endpoint but keeps only +score fields, dropping submission content on arrival. Exports are written +mode 600. + +The grade push reuses the existing overlay: `reg-canvas grades-export` → +`reg-gradebook export-canvas --template --only ` → +`reg-canvas grades-push`. The push re-reads live Canvas and posts only the +cells that differ, never clears a grade from a blank cell, and refuses a file +whose assignment ids belong to another course. Runbook: `docs/canvas-api.md`. + ## Authoring assignments Author every coding assignment with its **graders' contract** included — a student-facing spec diff --git a/docs/README.md b/docs/README.md index 36cfe27..bc56dac 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,6 +15,7 @@ | Document | Description | |---|---| | [gradescope-workflow.md](gradescope-workflow.md) | Step-by-step for taking a lectern-built exam into Gradescope: region/bubble setup, A/B Version Sets, roster import, per-student serial identity verification | +| [canvas-api.md](canvas-api.md) | *About 15 min to set up.* `reg-canvas`: Canvas token setup, linking sections to courses, gradebook export, roster check, and the dry-run-first write commands (grades, announcements, discussions, assignments, syllabus) | | [canvas-grades-workflow.md](canvas-grades-workflow.md) | Pushing vault grades to Canvas for one assignment via a Canvas-export **template overlay**: id-suffixed assignment match, `--only` targeting, minimal diff, extra-credit handling | | [admin-forms.md](admin-forms.md) | Filling a campus administrative form (Notice of Absence and friends) from the vault's own records: identity setup, campus closures in the term-spec, the three rendered products, and how to add a new form as a profile | diff --git a/docs/canvas-api.md b/docs/canvas-api.md new file mode 100644 index 0000000..898836a --- /dev/null +++ b/docs/canvas-api.md @@ -0,0 +1,262 @@ +# Using the Canvas API with `reg-canvas` + +**Time:** about 15 minutes to set up, once per token. After that, each command takes seconds. + +`reg-canvas` replaces the copy-and-paste steps between your course records and +Canvas. It exports the gradebook, pushes grades back, checks the roster, and +posts announcements, discussions, assignments and the syllabus. + +> [!CAUTION] +> **Every write is a dry run until you add `--apply`.** A dry run shows exactly +> what would change and sends nothing. Read it before you apply, because an +> announcement notifies students the moment it posts and a grade is visible as +> soon as it is posted. + +## 1. How the pieces fit + +```mermaid +flowchart LR + T["Token file
~/.config/lectern/canvas-token"] --> C["canvas_api
the only code that reads it"] + C <-->|"HTTPS, one host only"| K[("Canvas")] + N["Class note
canvas.course-id"] --> R["reg-canvas"] + R --> C + R -- "grades-export" --> E["Canvas-format CSV
in the section archive"] + E --> G["reg-lms-grades-import
reg-gradebook export-canvas"] + G -- "overlay CSV" --> R +``` + +| Piece | What it is | Who touches it | +|---|---|---| +| The token | A personal access token. It acts as you, with all your Canvas permissions. | You, once: store it, and renew it before it expires. | +| `canvas_api` | The client module. It is the only code that reads the token. | Nobody edits it day to day. | +| The class note's `canvas:` block | Links one section to its Canvas course ID. | `reg-canvas courses --bind`, once per term. | +| `reg-canvas` | The commands. Each one finds its course through the class note. | You, or an AI agent working for you. | +| The export CSV | The gradebook in the same layout as Canvas's *Export* button. | The existing grade tools read it unchanged. | + +> [!IMPORTANT] +> **A common misconception is that a token can be limited to reading.** It +> cannot. A Canvas user token carries every permission your account has, in +> every course you teach. Lectern compensates in three ways: the token never +> leaves one file, it is sent to only one host, and every write is a dry run +> until you say otherwise. + +## 2. Get a token + +Many institutions, CSULB among them, do not let instructors create tokens +themselves. Ask your campus Canvas administrators for one. Two things to know: + +- **It must be activated.** An administrator can create the token, but it + stays inactive until you open Canvas → **Account → Settings** and activate + it. Until then every call returns `HTTP 401`. +- **It expires.** Instructure limits tokens to 90 days. Ask for a new one + before the old one expires. + +## 3. Store the token + +```sh +mkdir -p ~/.config/lectern && chmod 700 ~/.config/lectern +( umask 077; read -rsp "Canvas token: " t; echo; printf '%s\n' "$t" > ~/.config/lectern/canvas-token ) +reg-canvas whoami +``` + +`read -rs` keeps the token off the screen and out of your shell history. If the +token works, `whoami` prints your Canvas name. + +> [!WARNING] +> Never put the token in a repository, a notes vault, a command line or an +> environment variable. Lectern reads it only from the file. It refuses to +> start if anyone but you can read that file. + +To use a Canvas host other than CSULB's, set it in `~/.config/lectern/config.toml`: + +```toml +[canvas] +base_url = "https://canvas.example.edu" +``` + +If you use an AI coding assistant, block it from reading the token file. In +Claude Code, add deny rules to `~/.claude/settings.json`: + +```json +"permissions": { "deny": ["Read(~/.config/lectern/canvas-token)", + "Edit(~/.config/lectern/canvas-token)"] } +``` + +## 4. Link each section to its Canvas course + +Run this once per term: + +```sh +reg-canvas courses # list your courses +reg-canvas courses --bind --term fa26 --vault-root +``` + +`--bind` matches each section to its course by course number, section and +class number. It then writes the course ID into the class note: + +```yaml +canvas: + course-id: 123142 + url: https://csulb.instructure.com/courses/123142 +``` + +Class numbers can repeat across years. When more than one course matches, the +Canvas term name (for example `Fall 2026`) decides. If the match is still not +clear, the command stops and lists the candidates, and you can write the block +by hand. + +To test against another course, such as your sandbox, pass `--course-id ` +in place of `--term`. + +## 5. Commands that only read + +| Command | What it does | +|---|---| +| `whoami` | Checks the token. | +| `courses` | Lists your courses. `--bind` links them to class notes. | +| `grades-export` | Writes the gradebook as the CSV Canvas's *Export* button produces. | +| `roster-check` | Compares Canvas enrolments with the registrar roster. | + +### Export the gradebook + +```sh +reg-canvas grades-export --term fa26 --vault-root --import +``` + +Each section's export goes to +`classes//archives/-
/canvas/_Grades-CECS_326_Sec01.csv`. +`--import` then runs `reg-lms-grades-import` into that archive's `grades.csv`. +Without `--import`, the command prints the import command to run next. + +The layout matches Canvas's own export, with two differences: + +- **No per-group subtotals.** The API does not return columns such as "Class + Participation Current Score". No lectern tool reads them. +- **Active students only.** Add `--include-inactive` for concluded and + inactive enrolments. + +### Check the roster at census + +```sh +reg-canvas roster-check --term fa26 --vault-root \ + --roster '/classes/326/archives/fa26-{section}/roster.csv' +``` + +The roster is a `reg-lms-roster-import` CSV, and `{section}` expands for each +section. The command lists every student found in only one of the two sources: + +- **In Canvas only:** often a dropped student still in the course shell. +- **In the roster only:** often a late add that has not reached Canvas yet. + +It exits with status 1 when the sources disagree, so a script can check it. + +## 6. Commands that write + +All of these are dry runs until you add `--apply`. + +| Command | What it creates or changes | Default | +|---|---|---| +| `grades-push` | Grades, from a Canvas-format import CSV | Changed cells only | +| `announce` | An announcement | Posts at once (use `--delay-until` to schedule) | +| `discussion` | A discussion topic | Unpublished | +| `assignment` | An assignment | Unpublished, submission type `none` | +| `syllabus` | The course syllabus page | Refuses a file without its serial | + +`announce`, `discussion` and `assignment` skip a section that already has an +item with the same title. `--force` overrides that check. + +### Push grades + +The push reuses the overlay in [canvas-grades-workflow.md](canvas-grades-workflow.md). +The API export replaces the manual export, and the push replaces the manual +upload: + +```sh +reg-canvas grades-export --term fa26 --vault-root --course "CECS 326" --section 01 +reg-gradebook export-canvas --gradebook gradebook.csv --course CECS_326 \ + --template .csv --only lab2 --out canvas-lab2-import.csv +reg-canvas grades-push --term fa26 --vault-root --course "CECS 326" --section 01 \ + --file canvas-lab2-import.csv # read the list, then add --apply +``` + +Before writing, the push reads the live gradebook again and lists every change +as `old → new`. It also has four safeguards: + +- **A blank cell never clears a grade.** +- **`EX` excuses the student.** +- **It refuses a file for another course.** If any assignment ID in the file is + not in the target course, nothing is sent. This catches a file from the + wrong section. +- **It warns about scores above points possible.** Extra credit still goes + through. + +`--only` limits the push to the named assignments. The push acts on one +section at a time. + +### Post an announcement + +`reg-c50 post` already writes one announcement per section. Post them with: + +```sh +reg-canvas announce --term fa26 --vault-root --course "CECS 326" \ + --file 'classes/326/labs//posted/fa26-{section}-ANNOUNCE.md' +``` + +The file's first `# ` heading becomes the title, and pandoc converts the rest +to HTML. A `.html` file is sent as written. To schedule the post, add +`--delay-until 2026-11-02T08:00:00-08:00`. + +### Create a lab assignment + +```sh +reg-canvas assignment --term fa26 --vault-root --course "CECS 326" --lab 3 \ + --due 2026-11-20T23:59:00-08:00 --group "Assignments and Labs" +``` + +`--lab` takes the column name and points from the lab's index note, the same +source `reg-c50 post` uses. The assignment is created unpublished. Its +submission type is `none`, because labs are submitted on GitHub. + +### Update the syllabus + +```sh +reg-canvas syllabus --term fa26 --vault-root --course "CECS 326" --section 01 \ + --file ~/git/cecs-326-fa26-01-syllabus-1131/syllabus_canvas.html +``` + +The command refuses a file that does not contain the class note's +`syllabus.serial`. It also reports whether the live page already carries that +serial. If the syllabus was already distributed, a changed version needs a +`revision-of` row in the register. + +## 7. What lectern reads, and what it never keeps + +- **Read:** course structure (assignments, groups, sections), plus names, + student IDs and grades for your own sections. +- **Written:** grades, announcements, discussions, assignments and the + syllabus, for your own courses, and only with `--apply`. +- **Never kept:** submission content. Scores come from the submissions + endpoint, which also returns text and links. Lectern keeps only the score + fields (`score`, `grade`, `excused`, `missing`, `late`, `workflow_state` and + the two IDs) and drops everything else as each page arrives. +- **Exports are student records.** Lectern writes them readable only by you + (mode 600). + +The token goes only to the configured Canvas host. Lectern refuses redirects, +because following one would send the token to the redirect's host. No message +or error contains the token. + +If you think the token has leaked, revoke it in Canvas → Account → Settings, +and tell your Canvas administrators the same day. + +## 8. Troubleshooting + +| Symptom | Confirm the cause | Fix | +|---|---|---| +| `HTTP 401` on every command | `reg-canvas whoami` fails the same way. In Canvas → Account → Settings, the token is not shown as active. | Activate the token. If it is active, check its expiry date there. | +| `readable by group or other` | `stat -c %a ~/.config/lectern/canvas-token` prints anything other than `600`. | `chmod 600 ~/.config/lectern/canvas-token` | +| `does not look like a Canvas token` | The file holds quotes, spaces or a `Bearer ` prefix. Check the shape without printing the token: `grep -cE '^[0-9]+~[A-Za-z0-9]+$' ~/.config/lectern/canvas-token` should print `1`. | Store the token again with the commands in section 3. | +| `no canvas.course-id in ` | The class note has no `canvas:` block. | `reg-canvas courses --bind --term --vault-root ` | +| `expected one Canvas course, found …` | `reg-canvas courses` lists two courses with the same class number, or none. | Write the `canvas:` block into the class note by hand. | +| `names assignments this course does not have` | The import file's `(id)` columns come from another section's export. | Export that section again, rebuild the overlay, and push it. | +| An export has fewer columns than Canvas's own | `reg-canvas grades-export --stdout --course-id \| head -1` lists the assignment columns. Unpublished and hidden assignments are left out. | Publish the assignment, or ignore the column if it is not graded yet. | diff --git a/docs/canvas-grades-workflow.md b/docs/canvas-grades-workflow.md index d144a58..ae613cc 100644 --- a/docs/canvas-grades-workflow.md +++ b/docs/canvas-grades-workflow.md @@ -30,6 +30,12 @@ reg-gradebook export-canvas \ # 3. In Canvas: Grades → Import → upload canvas--import.csv → review → save. ``` +> [!TIP] +> **With a Canvas API token**, `reg-canvas grades-export` replaces step 1 and +> `reg-canvas grades-push` replaces step 3. The push re-reads live Canvas, lists +> each change, and writes nothing until you add `--apply`. See [canvas-api.md](canvas-api.md#push-grades). The manual steps +> below still work and need no token. + Step 2 changes only the cells whose value actually moved. Everything else — the identity columns, the other assignment columns, the points/posting row — is passed through byte-for-byte. diff --git a/install.sh b/install.sh index f73db0f..d0dd66f 100755 --- a/install.sh +++ b/install.sh @@ -44,5 +44,6 @@ make_wrapper reg-lab-report lectern.lab_report make_wrapper reg-admin-form lectern.admin_form make_wrapper reg-c50 lectern.c50 +make_wrapper reg-canvas lectern.canvas echo "lectern installed. reg-* wrappers in $BIN." diff --git a/lectern/c50.py b/lectern/c50.py index 66514b8..99046bf 100644 --- a/lectern/c50.py +++ b/lectern/c50.py @@ -16,8 +16,9 @@ each account exists, then send the organization invitations. Needed because ==nothing enrols a student automatically==: C50 will not add someone to the org just because they signed in, and at CSULB an instructor can obtain - neither student email addresses nor a Canvas API token, so usernames - collected from the students are the only identifier available. + no student email addresses (the Canvas API, available since 2026-10-21, + does not change that: lectern reads names and student IDs only), so + usernames collected from the students are the only identifier available. ``post`` Register a lab as an assignment in every section that teaches it, then emit diff --git a/lectern/canvas.py b/lectern/canvas.py new file mode 100644 index 0000000..8dc3e70 --- /dev/null +++ b/lectern/canvas.py @@ -0,0 +1,764 @@ +"""``reg-canvas`` — the Canvas API half of lectern. + +Every Canvas step lectern used to hand back as "now paste this into Canvas" +has a subcommand here. The vault stays the proprietary record and Canvas +stays student-facing; the API only removes the copy-and-paste between them. + +Read-only: + +- ``whoami`` check the token +- ``courses`` list your courses; ``--bind`` records each section's + Canvas course id in its class note +- ``grades-export`` the gradebook, as the same CSV Canvas's *Export* button + writes, so ``reg-lms-grades-import`` and + ``reg-gradebook export-canvas --template`` take it unchanged +- ``roster-check`` diff Canvas enrolments against the registrar roster + +Writes (**dry run unless ``--apply``**): + +- ``grades-push`` apply a Canvas-format import CSV, changed cells only +- ``announce`` post an announcement (e.g. ``reg-c50 post``'s ANNOUNCE.md) +- ``discussion`` create a discussion topic, unpublished by default +- ``assignment`` create an assignment (``--lab N`` fills it from the vault) +- ``syllabus`` set the syllabus page, refusing a file without its serial + +Data scope is what the instructor already exports by hand: roster and grades +for their own sections. ``grades-export`` reads scores through the +submissions endpoint but keeps only score fields (:data:`SCORE_FIELDS`); +submission content is dropped as each page arrives and never written. + +Targets resolve from the vault: ``--term`` + ``--course`` / ``--section`` → +the term-spec's sections → each class note's ``canvas.course-id`` (written by +``courses --bind``). ``--course-id`` bypasses the vault, for the sandbox. +""" +from __future__ import annotations + +import argparse +import csv +import re +import subprocess +import sys +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path + +from lectern.canvas_api import CanvasClient, CanvasError +from lectern.c50 import C50Error, class_note_path, sections_for, spec_path +from lectern.student_id import pad_student_id +from lectern.term_spec import TermSpecError, load_term_spec +from lectern.vault_notes import course_dir, set_frontmatter_fields, split_frontmatter + +# The only submission fields lectern keeps. Everything else the endpoint +# returns (body, url, attachments, preview links) is discarded on arrival. +SCORE_FIELDS = ("user_id", "assignment_id", "score", "grade", "excused", + "missing", "late", "workflow_state") + +IDENTITY_COLS = ["Student", "ID", "SIS User ID", "SIS Login ID", "Section"] +TOTAL_COLS = [ + ("Current Score", "current_score"), + ("Unposted Current Score", "unposted_current_score"), + ("Final Score", "final_score"), + ("Unposted Final Score", "unposted_final_score"), + ("Current Grade", "current_grade"), + ("Unposted Current Grade", "unposted_current_grade"), + ("Final Grade", "final_grade"), + ("Unposted Final Grade", "unposted_final_grade"), + ("Override Score", "override_score"), + ("Override Grade", "override_grade"), + ("Override Status", "override_status"), +] +# Canvas's points row marks the totals "(read only)" but leaves these blank. +_POINTS_BLANK = {"Override Score", "Override Status"} +_ASSIGNMENT_COL = re.compile(r"^(.*?)\s*\((\d+)\)\s*$") + + +class CanvasCmdError(Exception): + """A user-facing failure of a ``reg-canvas`` command.""" + + +@dataclass +class Target: + """One Canvas course to act on, with the vault section it came from.""" + + course_id: int + label: str + section: dict | None = None + class_note: Path | None = None + + +# ── target resolution ──────────────────────────────────────────────────────── + + +def resolve_targets(args) -> list[Target]: + """Turn ``--course-id`` or ``--term``/``--course``/``--section`` into targets.""" + if getattr(args, "course_id", None): + sec = {"section": args.section, "course": args.course} if args.section else None + return [Target(int(args.course_id), "Canvas", sec)] + if not (args.term and args.vault_root): + raise CanvasCmdError("pass --term and --vault-root, or --course-id") + vault = Path(args.vault_root) + spec = load_term_spec(spec_path(vault, args.term)) + out = [] + for sec in sections_for(spec, args.course, args.section): + note = class_note_path(vault, sec, args.term) + cid = canvas_course_id(note) + label = f"{sec['course']} §{sec['section']}" + if cid is None: + raise CanvasCmdError( + f"{label}: no canvas.course-id in {note.name}; run " + f"reg-canvas courses --bind --term {args.term} --vault-root {args.vault_root}") + out.append(Target(cid, label, sec, note)) + return out + + +def canvas_course_id(note: Path) -> int | None: + if not note.exists(): + return None + fm, _ = split_frontmatter(note.read_text(encoding="utf-8")) + cid = (fm.get("canvas") or {}).get("course-id") + return int(cid) if cid else None + + +def expand_path(template: str, target: Target, term: str | None) -> Path: + """Fill ``{section}``/``{term}``/``{course}`` in a per-section file argument.""" + sec = target.section or {} + if "{" in template and not sec.get("section"): + raise CanvasCmdError(f"{template}: placeholders need --section with --course-id") + num = str(sec.get("course", "")).split()[-1] if sec.get("course") else "" + return Path(template.format(section=sec.get("section", ""), term=term or "", course=num)) + + +# ── courses / bind ─────────────────────────────────────────────────────────── + + +def teacher_courses(client: CanvasClient) -> list[dict]: + return list(client.get_all("courses", [ + ("enrollment_type", "teacher"), ("include[]", "term"), + ("state[]", "available"), ("state[]", "unpublished"), + ])) + + +def match_course(courses: list[dict], sec: dict, term_name: str | None) -> dict: + """Find the one Canvas course for a term-spec section. + + CSULB names shells ``CECS 326 Sec01 1131 Operating Systems``. The class + number is the strongest key, but class numbers recur across years, so a + tie is broken by the Canvas term name (``Fall 2026``) when the spec has one. + """ + num = str(sec["course"]).split()[-1] + cls = str(sec.get("class-number", "")) + pat = re.compile(rf"\b{re.escape(num)}\b.*\bSec\s*0*{int(sec['section'])}\b.*\b{re.escape(cls)}\b") + hits = [c for c in courses if cls and pat.search(c.get("name", ""))] + if len(hits) > 1 and term_name: + words = term_name.lower().split() + narrowed = [c for c in hits + if all(w in str((c.get("term") or {}).get("name", "")).lower() for w in words)] + hits = narrowed or hits + if len(hits) != 1: + found = ", ".join(f"{c['id']} {c.get('name')}" for c in hits) or "none" + raise CanvasCmdError( + f"{sec['course']} §{sec['section']} (class {cls}): expected one Canvas course, " + f"found {found}. Bind it by hand with canvas.course-id in the class note.") + return hits[0] + + +def cmd_whoami(client: CanvasClient, args) -> int: + me = client.get("users/self") + print(f"Canvas OK: {me.get('name')} (user {me.get('id')}) at {client.base}") + return 0 + + +def cmd_courses(client: CanvasClient, args) -> int: + courses = teacher_courses(client) + if not args.bind: + for c in sorted(courses, key=lambda c: c["id"], reverse=True): + term = (c.get("term") or {}).get("name", "") + print(f"{c['id']:>8} {c.get('workflow_state', ''):<11} {term:<14} {c.get('name')}") + return 0 + if not (args.term and args.vault_root): + raise CanvasCmdError("--bind needs --term and --vault-root") + vault = Path(args.vault_root) + spec = load_term_spec(spec_path(vault, args.term)) + for sec in sections_for(spec, args.course, args.section): + c = match_course(courses, sec, spec.get("term-name")) + note = class_note_path(vault, sec, args.term) + label = f"{sec['course']} §{sec['section']}" + if canvas_course_id(note) == c["id"]: + print(f"{label}: {c['id']} (already bound)") + continue + print(f"{label}: {c['id']} {c.get('name')}") + if args.dry_run or not note.exists(): + if not note.exists(): + print(f" no class note at {note}") + continue + now = datetime.now().astimezone().isoformat(timespec="seconds") + note.write_text(set_frontmatter_fields(note.read_text(encoding="utf-8"), { + "canvas.course-id": c["id"], + "canvas.url": f"{client.base}/courses/{c['id']}", + "updated": now, + }), encoding="utf-8") + print(f" bound in {note.relative_to(vault)}") + return 0 + + +# ── gradebook read ─────────────────────────────────────────────────────────── + + +@dataclass +class Gradebook: + assignments: list[dict] # gradebook column order + students: list[dict] # one per user: user, sections, grades + scores: dict[tuple[int, int], dict] # (user_id, assignment_id) → SCORE_FIELDS + + +def read_gradebook(client: CanvasClient, course_id: int, include_inactive: bool = False) -> Gradebook: + """Read assignments, student enrolments and scores for one course.""" + groups = {g["id"]: g.get("position", 0) + for g in client.get_all(f"courses/{course_id}/assignment_groups")} + assignments = [ + a for a in client.get_all(f"courses/{course_id}/assignments") + if a.get("published", True) and not a.get("hide_in_gradebook") + ] + assignments.sort(key=lambda a: (groups.get(a.get("assignment_group_id"), 0), + a.get("position") or 0, a["id"])) + + sections = {s["id"]: s.get("name", "") + for s in client.get_all(f"courses/{course_id}/sections")} + states = ["active", "invited"] + (["inactive", "completed"] if include_inactive else []) + params = [("type[]", "StudentEnrollment")] + [("state[]", s) for s in states] + by_user: dict[int, dict] = {} + for e in client.get_all(f"courses/{course_id}/enrollments", params): + uid = e["user_id"] + rec = by_user.setdefault(uid, {"user": e.get("user") or {}, "sections": [], + "grades": e.get("grades") or {}}) + name = sections.get(e.get("course_section_id"), "") + if name and name not in rec["sections"]: + rec["sections"].append(name) + + scores: dict[tuple[int, int], dict] = {} + for s in client.get_all(f"courses/{course_id}/students/submissions", + [("student_ids[]", "all")]): + kept = {k: s.get(k) for k in SCORE_FIELDS} + scores[(kept["user_id"], kept["assignment_id"])] = kept + + students = sorted(by_user.values(), + key=lambda r: (r["user"].get("sortable_name") or "").lower()) + return Gradebook(assignments, students, scores) + + +def _num(v) -> str: + if v is None or v == "": + return "" + try: + return f"{float(v):.2f}" + except (TypeError, ValueError): + return str(v) + + +def assignment_header(a: dict) -> str: + return f"{a['name']} ({a['id']})" + + +def gradebook_rows(gb: Gradebook) -> list[list[str]]: + """Render a :class:`Gradebook` as Canvas's export: three header rows, then students.""" + headers = IDENTITY_COLS + [assignment_header(a) for a in gb.assignments] + [c for c, _ in TOTAL_COLS] + posting = [""] * len(IDENTITY_COLS) + [ + "Manual Posting" if a.get("post_manually") else "" for a in gb.assignments + ] + [""] * len(TOTAL_COLS) + points = [" Points Possible"] + [""] * (len(IDENTITY_COLS) - 1) + [ + _num(a.get("points_possible")) for a in gb.assignments + ] + ["" if c in _POINTS_BLANK else "(read only)" for c, _ in TOTAL_COLS] + rows = [headers, posting, points] + for st in gb.students: + u, g = st["user"], st["grades"] + row = [u.get("sortable_name") or u.get("name") or "", str(u.get("id", "")), + u.get("sis_user_id") or "", u.get("login_id") or "", ", ".join(st["sections"])] + for a in gb.assignments: + s = gb.scores.get((u.get("id"), a["id"])) + if not s: + row.append("") + elif s.get("excused"): + row.append("EX") + else: + row.append(_num(s.get("score"))) + for _, key in TOTAL_COLS: + val = g.get(key) + row.append(_num(val) if key.endswith("score") else (val or "")) + rows.append(row) + return rows + + +def write_csv(rows: list[list[str]], path: Path) -> None: + """Write student data owner-only (mode 600): it is a FERPA record.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.touch(mode=0o600, exist_ok=True) + path.chmod(0o600) + with path.open("w", newline="", encoding="utf-8") as fh: + csv.writer(fh).writerows(rows) + + +def default_export_path(vault: Path, target: Target, term: str, stamp: str) -> Path: + sec = target.section + num = sec["course"].split()[-1] + dept = sec["course"].split()[0] + return (vault / "classes" / course_dir(sec["course"]) / "archives" / f"{term}-{sec['section']}" + / "canvas" / f"{stamp}_Grades-{dept}_{num}_Sec{sec['section']}.csv") + + +def cmd_grades_export(client: CanvasClient, args) -> int: + stamp = datetime.now().strftime("%Y-%m-%dT%H%M") + for t in resolve_targets(args): + gb = read_gradebook(client, t.course_id, args.include_inactive) + rows = gradebook_rows(gb) + if args.stdout: + csv.writer(sys.stdout).writerows(rows) + continue + if args.out: + dest = expand_path(args.out, t, args.term) + if dest.suffix != ".csv": + dest = dest / f"{stamp}_Grades-course-{t.course_id}.csv" + elif t.section and args.vault_root: + dest = default_export_path(Path(args.vault_root), t, args.term, stamp) + else: + raise CanvasCmdError("--course-id needs --out") + write_csv(rows, dest) + print(f"{t.label}: {len(gb.students)} students × {len(gb.assignments)} assignments → {dest}") + # The archive layout keeps exports in /canvas/ beside grades.csv. + grades = (dest.parent.parent if dest.parent.name == "canvas" else dest.parent) / "grades.csv" + if args.do_import: + from lectern import lms_grades + lms_grades.main([str(dest), "--out", str(grades)]) + else: + print(f" next: reg-lms-grades-import {dest} --out {grades}") + return 0 + + +# ── roster check ───────────────────────────────────────────────────────────── + + +def read_roster_ids(path: Path) -> dict[str, str]: + """``student_id → display name`` from a ``reg-lms-roster-import`` CSV.""" + with path.open(newline="", encoding="utf-8-sig") as fh: + rows = list(csv.DictReader(fh)) + if rows and "student_id" not in rows[0]: + raise CanvasCmdError(f"{path}: no student_id column (is this a reg-lms-roster-import CSV?)") + return {pad_student_id(r["student_id"]): r.get("display_name") or r.get("lms_name", "") + for r in rows if (r.get("enrollment_status") or "Enrolled").lower() != "dropped"} + + +def cmd_roster_check(client: CanvasClient, args) -> int: + drift = 0 + for t in resolve_targets(args): + roster = read_roster_ids(expand_path(args.roster, t, args.term)) + canvas = {} + for e in client.get_all(f"courses/{t.course_id}/enrollments", + [("type[]", "StudentEnrollment"), ("state[]", "active"), + ("state[]", "invited")]): + u = e.get("user") or {} + sis = u.get("sis_user_id") or "" + if sis and not sis.endswith("SA"): + canvas[pad_student_id(sis)] = u.get("sortable_name", "") + only_canvas = sorted(set(canvas) - set(roster)) + only_roster = sorted(set(roster) - set(canvas)) + print(f"{t.label}: roster {len(roster)}, Canvas {len(canvas)}, " + f"matched {len(set(canvas) & set(roster))}") + for sid in only_canvas: + print(f" in Canvas only (drop still in the shell?) {sid} {canvas[sid]}") + for sid in only_roster: + print(f" in roster only (add not yet in Canvas?) {sid} {roster[sid]}") + drift += len(only_canvas) + len(only_roster) + return 1 if drift else 0 + + +# ── grades push ────────────────────────────────────────────────────────────── + + +@dataclass +class Change: + user_id: int + sis: str + name: str + assignment_id: int + assignment: str + old: str + new: str + + +def parse_import_csv(path: Path) -> tuple[dict[int, str], list[dict]]: + """Read a Canvas-format import CSV → (assignment id → title, student rows).""" + with path.open(newline="", encoding="utf-8-sig") as fh: + rows = list(csv.reader(fh)) + if not rows: + raise CanvasCmdError(f"{path}: empty") + headers = rows[0] + if "SIS User ID" not in headers: + raise CanvasCmdError(f"{path}: no 'SIS User ID' column; expected a Canvas-format CSV") + cols = {} + for h in headers: + m = _ASSIGNMENT_COL.match(h) + if m and h not in {c for c, _ in TOTAL_COLS}: + cols[int(m.group(2))] = h + # The posting and points-possible rows carry no SIS User ID, so this one + # filter drops both along with blank lines. + body = [dict(zip(headers, r)) for r in rows[1:]] + body = [r for r in body if (r.get("SIS User ID") or "").strip()] + return cols, body + + +def _same(a: str, b: str) -> bool: + if a == b: + return True + try: + return abs(float(a) - float(b)) < 1e-6 + except ValueError: + return a.strip().upper() == b.strip().upper() + + +def plan_push(gb: Gradebook, cols: dict[int, str], rows: list[dict], + only: list[str] | None) -> tuple[list[Change], list[str]]: + """Diff an import file against live Canvas. Returns (changes, warnings).""" + live_ids = {a["id"]: a for a in gb.assignments} + warnings = [] + unknown = [cols[i] for i in cols if i not in live_ids] + if unknown: + raise CanvasCmdError( + "the file names assignments this course does not have (wrong section's file?): " + + "; ".join(unknown)) + wanted = set(cols) + if only: + keys = {o.lower() for o in only} + wanted = {i for i in cols + if str(i) in keys or live_ids[i]["name"].lower() in keys} + if not wanted: + raise CanvasCmdError(f"--only matched no assignment column: {', '.join(only)}") + by_sis = {pad_student_id(s["user"].get("sis_user_id") or ""): s + for s in gb.students if s["user"].get("sis_user_id")} + changes = [] + for r in rows: + sis = pad_student_id(r["SIS User ID"].strip()) + st = by_sis.get(sis) + if st is None: + warnings.append(f"{sis} {r.get('Student', '')}: not enrolled in this course; skipped") + continue + uid = st["user"]["id"] + for aid in sorted(wanted): + new = (r.get(cols[aid]) or "").strip() + if new == "": + continue # a blank cell never clears a grade + s = gb.scores.get((uid, aid)) or {} + old = "EX" if s.get("excused") else _num(s.get("score")) + if new.upper() != "EX": + try: + float(new) + except ValueError: + warnings.append(f"{sis} {cols[aid]}: {new!r} is not a score; skipped") + continue + if _same(old, new): + continue + pts = live_ids[aid].get("points_possible") + if new.upper() != "EX" and pts and float(new) > float(pts): + warnings.append(f"{sis} {live_ids[aid]['name']}: {new} exceeds {pts} points " + "(extra credit?)") + changes.append(Change(uid, sis, st["user"].get("sortable_name", ""), aid, + live_ids[aid]["name"], old, new)) + return changes, warnings + + +def apply_push(client: CanvasClient, course_id: int, changes: list[Change]) -> None: + by_assignment: dict[int, dict] = {} + for c in changes: + cell = {"excuse": True} if c.new.upper() == "EX" else {"posted_grade": c.new} + by_assignment.setdefault(c.assignment_id, {})[str(c.user_id)] = cell + for aid, grade_data in by_assignment.items(): + prog = client.post(f"courses/{course_id}/assignments/{aid}/submissions/update_grades", + {"grade_data": grade_data}) + client.wait_progress(prog) + + +def cmd_grades_push(client: CanvasClient, args) -> int: + targets = resolve_targets(args) + if len(targets) != 1: + raise CanvasCmdError("grades-push acts on one section at a time; pass --section") + t = targets[0] + path = expand_path(args.file, t, args.term) + cols, rows = parse_import_csv(path) + gb = read_gradebook(client, t.course_id) + changes, warnings = plan_push(gb, cols, rows, args.only) + for w in warnings: + print(f" WARNING {w}") + print(f"{t.label} (course {t.course_id}): {len(changes)} changed cell(s) from {path.name}") + for c in changes: + print(f" {c.sis} {c.name:<28} {c.assignment:<36} {c.old or '—':>7} → {c.new}") + if not changes: + return 0 + if not args.apply: + print("dry run: nothing written. Re-run with --apply to post these grades.") + return 0 + apply_push(client, t.course_id, changes) + print(f"posted {len(changes)} grade(s)") + return 0 + + +# ── content: announcements, discussions, assignments, syllabus ────────────── + + +def render_body(path: Path) -> tuple[str | None, str]: + """Read a content file → (title from a leading H1, HTML body). + + Markdown goes through pandoc (already a lectern dependency for syllabi); + ``.html`` is sent as-is. + """ + text = path.read_text(encoding="utf-8") + if path.suffix.lower() in (".html", ".htm"): + return None, text + title = None + m = re.match(r"\A\s*#\s+(.+?)\s*\n", text) + if m: + title, text = m.group(1).strip(), text[m.end():] + try: + proc = subprocess.run(["pandoc", "-f", "gfm", "-t", "html", "--wrap=none"], + input=text, capture_output=True, text=True, check=True) + except FileNotFoundError: + raise CanvasCmdError("pandoc is needed to convert Markdown; install it or pass .html") from None + except subprocess.CalledProcessError as e: + raise CanvasCmdError(f"pandoc failed on {path}: {e.stderr.strip()}") from None + return title, proc.stdout + + +def existing_titles(client: CanvasClient, course_id: int, announcements: bool) -> set[str]: + params = [("only_announcements", "true")] if announcements else [] + return {d.get("title", "") for d in client.get_all(f"courses/{course_id}/discussion_topics", params)} + + +def _preview(html: str, n: int = 160) -> str: + plain = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html)).strip() + return plain[:n] + ("…" if len(plain) > n else "") + + +def _topic(client: CanvasClient, args, *, announcement: bool) -> int: + kind = "announcement" if announcement else "discussion" + for t in resolve_targets(args): + path = expand_path(args.file, t, args.term) + h1, html = render_body(path) + title = args.title or h1 + if not title: + raise CanvasCmdError(f"{path}: no '# Title' line; pass --title") + print(f"{t.label} (course {t.course_id}): {kind} {title!r} from {path.name}") + print(f" {_preview(html)}") + if title in existing_titles(client, t.course_id, announcement) and not args.force: + print(f" already exists with that title; skipped (--force posts a second copy)") + continue + data = {"title": title, "message": html} + if announcement: + data["is_announcement"] = True + else: + data["published"] = bool(args.publish) + data["discussion_type"] = "threaded" + if args.delay_until: + data["delayed_post_at"] = args.delay_until + if not args.apply: + when = f"at {args.delay_until}" if args.delay_until else "immediately" + vis = ("visible to students " + when) if (announcement or args.publish) else "unpublished" + print(f" dry run: would create it, {vis}. Re-run with --apply.") + continue + made = client.post(f"courses/{t.course_id}/discussion_topics", data) + print(f" created {made.get('html_url', made.get('id'))}") + return 0 + + +def cmd_announce(client: CanvasClient, args) -> int: + return _topic(client, args, announcement=True) + + +def cmd_discussion(client: CanvasClient, args) -> int: + return _topic(client, args, announcement=False) + + +def _group_id(client: CanvasClient, course_id: int, name: str | None) -> int | None: + if not name: + return None + groups = list(client.get_all(f"courses/{course_id}/assignment_groups")) + for g in groups: + if g.get("name", "").lower() == name.lower(): + return g["id"] + raise CanvasCmdError(f"course {course_id} has no assignment group {name!r}; it has: " + + ", ".join(g.get("name", "") for g in groups)) + + +def cmd_assignment(client: CanvasClient, args) -> int: + name, points = args.name, args.points + if args.lab is not None: + if not (args.course and args.vault_root): + raise CanvasCmdError("--lab needs --course and --vault-root") + from lectern.c50 import find_lab + lab = find_lab(Path(args.vault_root), args.course, args.lab) + name = name or lab.canvas_column or lab.title + points = points if points is not None else lab.points + if not name: + raise CanvasCmdError("pass --name or --lab") + for t in resolve_targets(args): + html = render_body(expand_path(args.description, t, args.term))[1] if args.description else "" + existing = {a.get("name") for a in client.get_all(f"courses/{t.course_id}/assignments")} + print(f"{t.label} (course {t.course_id}): assignment {name!r}, " + f"{points if points is not None else '?'} pts, due {args.due or 'none'}, " + f"group {args.group or 'default'}") + if name in existing and not args.force: + print(" already exists with that name; skipped (--force creates a second one)") + continue + body = {"name": name, "submission_types": args.submission_types.split(","), + "published": bool(args.publish), "description": html} + if points is not None: + body["points_possible"] = points + if args.due: + body["due_at"] = args.due + gid = _group_id(client, t.course_id, args.group) + if gid: + body["assignment_group_id"] = gid + if not args.apply: + print(f" dry run: would create it {'published' if args.publish else 'unpublished'}. " + "Re-run with --apply.") + continue + made = client.post(f"courses/{t.course_id}/assignments", {"assignment": body}) + print(f" created {made.get('html_url', made.get('id'))} " + f"(gradebook column: {assignment_header(made)})") + return 0 + + +def cmd_syllabus(client: CanvasClient, args) -> int: + for t in resolve_targets(args): + path = expand_path(args.file, t, args.term) + html = path.read_text(encoding="utf-8") + serial = None + if t.class_note and t.class_note.exists(): + fm, _ = split_frontmatter(t.class_note.read_text(encoding="utf-8")) + serial = (fm.get("syllabus") or {}).get("serial") + distributed = (fm.get("syllabus") or {}).get("distributed") + else: + distributed = None + if serial and str(serial) not in html: + raise CanvasCmdError(f"{t.label}: {path.name} does not carry serial {serial} from " + "the class note; refusing to post an unstamped syllabus") + if not serial and not args.allow_unstamped: + raise CanvasCmdError(f"{t.label}: no syllabus.serial to check against " + "(--allow-unstamped overrides)") + live = (client.get(f"courses/{t.course_id}", [("include[]", "syllabus_body")]) + or {}).get("syllabus_body") or "" + same_serial = bool(serial) and str(serial) in live + print(f"{t.label} (course {t.course_id}): syllabus from {path.name}, serial {serial or '—'}; " + f"live page {'already carries it' if same_serial else 'differs'}") + if distributed and not same_serial: + print(f" NOTE distributed {distributed}: a changed syllabus needs a revision-of row") + if not args.apply: + print(" dry run: nothing written. Re-run with --apply.") + continue + client.put(f"courses/{t.course_id}", {"course": {"syllabus_body": html}}) + print(" syllabus updated") + return 0 + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def build_parser() -> argparse.ArgumentParser: + p = argparse.ArgumentParser( + prog="reg-canvas", + description="Canvas API commands. Reads are immediate; writes are dry runs until --apply.") + sub = p.add_subparsers(dest="cmd", required=True) + + def target(sp, *, need_section=False): + sp.add_argument("--term", help="term code, e.g. fa26") + sp.add_argument("--vault-root") + sp.add_argument("--course", help='e.g. "CECS 326" (default: every course)') + sp.add_argument("--section", help="e.g. 01" + (" (required)" if need_section else "")) + sp.add_argument("--course-id", type=int, help="act on this Canvas course id directly " + "(the sandbox), bypassing the vault") + + def writes(sp): + sp.add_argument("--apply", action="store_true", help="actually write to Canvas") + + sp = sub.add_parser("whoami", help="check the token") + sp.set_defaults(func=cmd_whoami) + + sp = sub.add_parser("courses", help="list your Canvas courses; --bind records ids") + target(sp) + sp.add_argument("--bind", action="store_true", + help="write canvas.course-id into each section's class note") + sp.add_argument("--dry-run", action="store_true") + sp.set_defaults(func=cmd_courses) + + sp = sub.add_parser("grades-export", help="gradebook → Canvas-export CSV") + target(sp) + sp.add_argument("--out", help="file or directory ({section}/{term}/{course} expand); " + "default /archives/-/canvas/") + sp.add_argument("--stdout", action="store_true") + sp.add_argument("--include-inactive", action="store_true", + help="also export inactive and concluded enrolments") + sp.add_argument("--import", dest="do_import", action="store_true", + help="then run reg-lms-grades-import into the archive's grades.csv") + sp.set_defaults(func=cmd_grades_export) + + sp = sub.add_parser("roster-check", help="diff Canvas enrolments against a roster CSV") + target(sp) + sp.add_argument("--roster", required=True, + help="reg-lms-roster-import CSV ({section}/{term}/{course} expand)") + sp.set_defaults(func=cmd_roster_check) + + sp = sub.add_parser("grades-push", help="apply a Canvas-format import CSV (changed cells)") + target(sp, need_section=True) + sp.add_argument("--file", required=True, + help="e.g. reg-gradebook export-canvas --template output") + sp.add_argument("--only", nargs="+", help="assignment titles or ids to push") + writes(sp) + sp.set_defaults(func=cmd_grades_push) + + for name, helptext in (("announce", "post an announcement"), + ("discussion", "create a discussion topic")): + sp = sub.add_parser(name, help=helptext) + target(sp) + sp.add_argument("--file", required=True, help=".md (via pandoc) or .html; " + "{section}/{term}/{course} expand") + sp.add_argument("--title", help="default: the file's leading '# ' heading") + sp.add_argument("--delay-until", help="ISO time to post at instead of now") + sp.add_argument("--force", action="store_true", help="post even if the title exists") + if name == "discussion": + sp.add_argument("--publish", action="store_true", help="publish (default unpublished)") + writes(sp) + sp.set_defaults(func=cmd_announce if name == "announce" else cmd_discussion) + + sp = sub.add_parser("assignment", help="create an assignment") + target(sp) + sp.add_argument("--lab", type=int, help="fill name and points from the vault lab index") + sp.add_argument("--name") + sp.add_argument("--points", type=float) + sp.add_argument("--due", help="ISO due timestamp") + sp.add_argument("--group", help="assignment group name, e.g. 'Assignments and Labs'") + sp.add_argument("--description", help=".md or .html ({section}/{term}/{course} expand)") + sp.add_argument("--submission-types", default="none", + help="comma list; default none (labs are submitted on GitHub)") + sp.add_argument("--publish", action="store_true", help="publish (default unpublished)") + sp.add_argument("--force", action="store_true", help="create even if the name exists") + writes(sp) + sp.set_defaults(func=cmd_assignment) + + sp = sub.add_parser("syllabus", help="set the course syllabus page") + target(sp) + sp.add_argument("--file", required=True, + help="syllabus_canvas.html ({section}/{term}/{course} expand)") + sp.add_argument("--allow-unstamped", action="store_true") + writes(sp) + sp.set_defaults(func=cmd_syllabus) + return p + + +def main(argv=None, client: CanvasClient | None = None) -> int: + args = build_parser().parse_args(argv) + try: + client = client or CanvasClient.from_config() + return args.func(client, args) + except (CanvasError, CanvasCmdError, C50Error, TermSpecError) as e: + print(f"reg-canvas: {e}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/lectern/canvas_api.py b/lectern/canvas_api.py new file mode 100644 index 0000000..7da43e3 --- /dev/null +++ b/lectern/canvas_api.py @@ -0,0 +1,279 @@ +"""Canvas LMS REST client — the only module that holds a Canvas token. + +Lectern talks to Canvas with one personal access token per instructor. The +token carries that instructor's full permissions and cannot be scoped, so this +module is deliberately narrow about where it goes: + +- **Read from a file, never from argv or the environment.** The default path + is ``~/.config/lectern/canvas-token``; ``LECTERN_CANVAS_TOKEN_FILE`` may point + elsewhere. The file must be owned by the caller and unreadable by group and + other (the ``ssh`` rule), or the client refuses to start. +- **Sent only to the configured Canvas host.** Redirects are refused rather + than followed, because urllib forwards the ``Authorization`` header to + whatever host a redirect names. Pagination links on another host are refused + the same way. +- **Never printed.** No message, exception or log line this module produces + contains the token; :func:`_scrub` removes it from anything Canvas echoes back. + +The client is stdlib-only (``urllib``) to keep lectern's runtime dependencies +at ``pyyaml`` + ``jsonschema``. Tests inject a fake ``transport``. + +Config (``~/.config/lectern/config.toml``):: + + [canvas] + base_url = "https://csulb.instructure.com" # default + +``LECTERN_CANVAS_URL`` overrides the config file. +""" +from __future__ import annotations + +import json +import os +import re +import stat +import time +import tomllib +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable, Iterator + +DEFAULT_BASE_URL = "https://csulb.instructure.com" +DEFAULT_TOKEN_FILE = "~/.config/lectern/canvas-token" +CONFIG = Path(os.environ.get("LECTERN_CONFIG", "~/.config/lectern/config.toml")).expanduser() + +# Canvas tokens are "~". +_TOKEN_SHAPE = re.compile(r"^\d+~[A-Za-z0-9]+$") + +# A transport takes (method, url, headers, body) and returns +# (status, response headers, response body). +Transport = Callable[[str, str, dict, bytes | None], tuple[int, dict, bytes]] + + +class CanvasError(Exception): + """A Canvas call failed, or the client could not be configured.""" + + def __init__(self, message: str, status: int | None = None): + super().__init__(message) + self.status = status + + +# ── configuration ──────────────────────────────────────────────────────────── + + +def token_path() -> Path: + """Where the token file lives (``LECTERN_CANVAS_TOKEN_FILE`` or the default).""" + return Path(os.environ.get("LECTERN_CANVAS_TOKEN_FILE", DEFAULT_TOKEN_FILE)).expanduser() + + +def load_token(path: Path | None = None) -> str: + """Read and check the token file. Raises :class:`CanvasError`, never echoing it.""" + path = path or token_path() + try: + st = path.stat() + except FileNotFoundError: + raise CanvasError( + f"no Canvas token at {path}. Store one with a hidden prompt " + "(read -rs) into that file, mode 600; see docs/canvas-api.md" + ) from None + if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO): + raise CanvasError( + f"{path} is readable by group or other (mode {stat.S_IMODE(st.st_mode):o}); " + f"run: chmod 600 {path}" + ) + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + raise CanvasError(f"{path} is not owned by the current user") + token = path.read_text(encoding="utf-8").strip() + if not _TOKEN_SHAPE.match(token): + raise CanvasError( + f"{path} does not look like a Canvas token (expected digits~alphanumerics, " + "with no quotes, spaces or 'Bearer ' prefix)" + ) + return token + + +def base_url() -> str: + """The Canvas origin: ``LECTERN_CANVAS_URL``, then ``[canvas] base_url``, then CSULB.""" + env = os.environ.get("LECTERN_CANVAS_URL") + if env: + return env.rstrip("/") + if CONFIG.exists(): + try: + cfg = tomllib.loads(CONFIG.read_text(encoding="utf-8")) + except tomllib.TOMLDecodeError as e: + raise CanvasError(f"{CONFIG}: {e}") from None + url = (cfg.get("canvas") or {}).get("base_url") + if url: + return str(url).rstrip("/") + return DEFAULT_BASE_URL + + +# ── transport ──────────────────────────────────────────────────────────────── + + +class _NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse redirects: following one would forward the Authorization header.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401 + raise urllib.error.HTTPError( + req.full_url, code, f"refused redirect to {newurl}", headers, fp + ) + + +_OPENER = urllib.request.build_opener(_NoRedirect) + + +def urllib_transport(method: str, url: str, headers: dict, body: bytes | None): + """Default transport over urllib, with redirects disabled.""" + req = urllib.request.Request(url, data=body, method=method, headers=headers) + try: + with _OPENER.open(req, timeout=60) as resp: + return resp.status, dict(resp.headers), resp.read() + except urllib.error.HTTPError as e: + return e.code, dict(e.headers or {}), e.read() if e.fp else b"" + except urllib.error.URLError as e: + raise CanvasError(f"cannot reach Canvas: {e.reason}") from None + + +# ── client ─────────────────────────────────────────────────────────────────── + + +_LINK_RE = re.compile(r'<([^>]+)>;\s*rel="([a-z]+)"') + + +def _next_link(headers: dict) -> str | None: + link = next((v for k, v in headers.items() if k.lower() == "link"), "") + for url, rel in _LINK_RE.findall(link): + if rel == "next": + return url + return None + + +@dataclass +class CanvasClient: + """A Canvas REST client bound to one host and one token.""" + + base: str + token: str = field(repr=False) + transport: Transport = urllib_transport + retries: int = 3 + sleep: Callable[[float], None] = time.sleep + + @classmethod + def from_config(cls, transport: Transport | None = None) -> "CanvasClient": + return cls(base=base_url(), token=load_token(), + transport=transport or urllib_transport) + + # -- internals -- + + @property + def host(self) -> str: + return urllib.parse.urlsplit(self.base).netloc + + def _url(self, path: str, params: dict | list | None = None) -> str: + if path.startswith("http"): + url = path + else: + url = f"{self.base}/api/v1/{path.lstrip('/')}" + if params: + sep = "&" if "?" in url else "?" + url += sep + urllib.parse.urlencode(params, doseq=True) + return url + + def _scrub(self, text: str) -> str: + return text.replace(self.token, "[token]") if self.token else text + + def request(self, method: str, path: str, params=None, data=None): + """One call. Returns ``(parsed JSON, response headers)``.""" + url = self._url(path, params) + if urllib.parse.urlsplit(url).netloc != self.host: + raise CanvasError(f"refusing to send the token to {urllib.parse.urlsplit(url).netloc}") + headers = {"Authorization": f"Bearer {self.token}", "Accept": "application/json"} + body = None + if data is not None: + body = json.dumps(data).encode("utf-8") + headers["Content-Type"] = "application/json" + + for attempt in range(self.retries + 1): + status, rh, raw = self.transport(method, url, headers, body) + text = raw.decode("utf-8", errors="replace") + # Canvas throttles with 403 + "Rate Limit Exceeded"; 429 on some hosts. + throttled = status == 429 or (status == 403 and "Rate Limit Exceeded" in text) + if throttled and attempt < self.retries: + self.sleep(2 ** attempt) + continue + break + + if status >= 400: + raise CanvasError(f"{method} {self._display(url)}: HTTP {status}: " + f"{self._error_text(text)}", status) + if not raw.strip(): + return None, rh + try: + return json.loads(text), rh + except json.JSONDecodeError: + raise CanvasError(f"{method} {self._display(url)}: non-JSON response " + f"(HTTP {status})", status) from None + + def _display(self, url: str) -> str: + """The URL without host or query, for messages.""" + return urllib.parse.urlsplit(url).path + + def _error_text(self, text: str) -> str: + try: + doc = json.loads(text) + except json.JSONDecodeError: + return self._scrub(text.strip()[:200]) or "(empty body)" + if isinstance(doc, dict): + errs = doc.get("errors") + if isinstance(errs, list): + return self._scrub("; ".join(str(e.get("message", e)) if isinstance(e, dict) + else str(e) for e in errs)) + if errs: + return self._scrub(json.dumps(errs)[:300]) + if doc.get("message"): + return self._scrub(str(doc["message"])) + return self._scrub(text.strip()[:200]) + + # -- public verbs -- + + def get(self, path: str, params=None): + return self.request("GET", path, params)[0] + + def get_all(self, path: str, params=None) -> Iterator[dict]: + """Yield every item of a paginated list, following ``rel="next"``.""" + params = list(params.items()) if isinstance(params, dict) else list(params or []) + if not any(k == "per_page" for k, _ in params): + params.append(("per_page", 100)) + page, headers = self.request("GET", path, params) + while True: + yield from page or [] + nxt = _next_link(headers) + if not nxt: + return + page, headers = self.request("GET", nxt) + + def post(self, path: str, data: dict): + return self.request("POST", path, data=data)[0] + + def put(self, path: str, data: dict): + return self.request("PUT", path, data=data)[0] + + def wait_progress(self, progress: dict, timeout: float = 120.0) -> dict: + """Poll a Canvas Progress object until it completes or fails.""" + url = progress.get("url") or f"progress/{progress['id']}" + waited = 0.0 + while True: + state = progress.get("workflow_state") + if state == "completed": + return progress + if state == "failed": + raise CanvasError(f"Canvas job failed: {progress.get('message') or 'no message'}") + if waited >= timeout: + raise CanvasError(f"Canvas job still {state} after {timeout:.0f}s; " + f"check progress {progress.get('id')}") + self.sleep(1.0) + waited += 1.0 + progress = self.get(url) diff --git a/tests/test_canvas.py b/tests/test_canvas.py new file mode 100644 index 0000000..6acd667 --- /dev/null +++ b/tests/test_canvas.py @@ -0,0 +1,407 @@ +"""Tests for the Canvas API client and ``reg-canvas``. + +No network: a fake transport answers by (method, path) and records every +request, so the tests can assert both what was read and that dry runs write +nothing. +""" +import csv +import json +import os +import urllib.parse +from pathlib import Path + +import pytest + +from lectern import canvas, canvas_api, lms_grades +from lectern.canvas_api import CanvasClient, CanvasError +from tests.test_c50 import CLASS_NOTE, SPEC_YAML + +TOKEN = "1234~AbCdEfGhIjKlMnOpQrStUvWxYz0123456789" +BASE = "https://canvas.test" + + +class FakeCanvas: + """A transport that serves canned JSON and records requests.""" + + def __init__(self, routes: dict): + self.routes = routes + self.calls: list[tuple[str, str, dict | None]] = [] + + def __call__(self, method, url, headers, body): + assert headers["Authorization"] == f"Bearer {TOKEN}" + parts = urllib.parse.urlsplit(url) + path = parts.path.removeprefix("/api/v1/") + data = json.loads(body) if body else None + self.calls.append((method, path, data)) + page = dict(urllib.parse.parse_qsl(parts.query)).get("page") + key = (method, path) if page is None else (method, f"{path}#{page}") + resp = self.routes.get(key) + if resp is None: + return 404, {}, json.dumps({"errors": [{"message": f"no route {key}"}]}).encode() + if callable(resp): + resp = resp(data) + status, hdrs, payload = resp if isinstance(resp, tuple) else (200, {}, resp) + return status, hdrs, json.dumps(payload).encode() + + def writes(self): + return [c for c in self.calls if c[0] != "GET"] + + +def client_for(routes) -> tuple[CanvasClient, FakeCanvas]: + fake = FakeCanvas(routes) + return CanvasClient(BASE, TOKEN, transport=fake, sleep=lambda s: None), fake + + +# A two-student course: one graded, one excused, one Test Student absent +# (Canvas files those under StudentViewEnrollment, which is never requested). +ASSIGNMENTS = [ + {"id": 11, "name": "Lab 1 - Threads", "points_possible": 60, "assignment_group_id": 2, + "position": 1, "published": True, "post_manually": True}, + {"id": 10, "name": "Week 1 - Intro", "points_possible": 5, "assignment_group_id": 1, + "position": 1, "published": True, "post_manually": False}, + {"id": 12, "name": "Hidden", "points_possible": 1, "assignment_group_id": 1, + "position": 2, "published": True, "hide_in_gradebook": True}, +] +GROUPS = [{"id": 1, "name": "Class Participation", "position": 1}, + {"id": 2, "name": "Assignments and Labs", "position": 2}] +ENROLLMENTS = [ + {"user_id": 501, "course_section_id": 9, + "user": {"id": 501, "sortable_name": "Zed, Ann", "sis_user_id": "12345678", + "login_id": "012345678"}, + "grades": {"current_score": 91.5, "final_score": 80, "current_grade": "A", + "final_grade": "B"}}, + {"user_id": 502, "course_section_id": 9, + "user": {"id": 502, "sortable_name": "Able, Bo", "sis_user_id": "023456789", + "login_id": "023456789"}, + "grades": {"current_score": None, "final_score": 0}}, +] +SUBMISSIONS = [ + {"user_id": 501, "assignment_id": 10, "score": 5, "excused": False, + "body": "SECRET ESSAY TEXT", "url": "https://x", "attachments": [{"url": "y"}]}, + {"user_id": 501, "assignment_id": 11, "score": 55.5, "excused": False}, + {"user_id": 502, "assignment_id": 10, "score": None, "excused": True}, +] + + +def course_routes(cid=77): + p = f"courses/{cid}" + return { + ("GET", f"{p}/assignment_groups"): GROUPS, + ("GET", f"{p}/assignments"): ASSIGNMENTS, + ("GET", f"{p}/sections"): [{"id": 9, "name": "CECS 326 Sec01 1131"}], + ("GET", f"{p}/enrollments"): ENROLLMENTS, + ("GET", f"{p}/students/submissions"): SUBMISSIONS, + ("GET", f"{p}/discussion_topics"): [{"title": "Old news"}], + } + + +@pytest.fixture +def vault(tmp_path: Path) -> Path: + root = tmp_path / "vault" + (root / "classes" / "semesters").mkdir(parents=True) + (root / "classes" / "semesters" / "fa26.spec.yaml").write_text(SPEC_YAML) + (root / "classes" / "326").mkdir(parents=True) + (root / "classes" / "326" / "326-01-fa26.md").write_text(CLASS_NOTE) + return root + + +# ── token handling ─────────────────────────────────────────────────────────── + + +def write_token(tmp_path, text=TOKEN, mode=0o600) -> Path: + p = tmp_path / "canvas-token" + p.write_text(text + "\n") + p.chmod(mode) + return p + + +def test_token_loads_from_an_owner_only_file(tmp_path): + assert canvas_api.load_token(write_token(tmp_path)) == TOKEN + + +def test_a_group_readable_token_file_is_refused(tmp_path): + with pytest.raises(CanvasError, match="chmod 600"): + canvas_api.load_token(write_token(tmp_path, mode=0o644)) + + +def test_a_malformed_token_is_refused_without_echoing_it(tmp_path): + bad = '"' + TOKEN + '"' + with pytest.raises(CanvasError) as e: + canvas_api.load_token(write_token(tmp_path, bad)) + assert TOKEN not in str(e.value) + + +def test_a_missing_token_file_says_where_it_looked(tmp_path): + with pytest.raises(CanvasError, match="no Canvas token"): + canvas_api.load_token(tmp_path / "nope") + + +def test_base_url_reads_the_config_file(tmp_path, monkeypatch): + cfg = tmp_path / "config.toml" + cfg.write_text('[canvas]\nbase_url = "https://canvas.example.edu/"\n') + monkeypatch.delenv("LECTERN_CANVAS_URL", raising=False) + monkeypatch.setattr(canvas_api, "CONFIG", cfg) + assert canvas_api.base_url() == "https://canvas.example.edu" + + +# ── client ─────────────────────────────────────────────────────────────────── + + +def test_get_all_follows_next_links(): + nxt = {"Link": f'<{BASE}/api/v1/things?page=2>; rel="next"'} + client, fake = client_for({ + ("GET", "things"): (200, nxt, [{"id": 1}]), + ("GET", "things#2"): [{"id": 2}], + }) + assert [x["id"] for x in client.get_all("things")] == [1, 2] + + +def test_the_token_is_never_sent_to_another_host(): + evil = {"Link": '; rel="next"'} + client, fake = client_for({("GET", "things"): (200, evil, [{"id": 1}])}) + with pytest.raises(CanvasError, match="refusing to send the token"): + list(client.get_all("things")) + assert len(fake.calls) == 1 + + +def test_an_error_echoing_the_token_is_scrubbed(): + client, _ = client_for({("GET", "x"): (401, {}, {"errors": [{"message": f"bad {TOKEN}"}]})}) + with pytest.raises(CanvasError) as e: + client.get("x") + assert TOKEN not in str(e.value) and "[token]" in str(e.value) + assert e.value.status == 401 + + +def test_rate_limiting_is_retried(): + answers = iter([(403, {}, {"errors": "Rate Limit Exceeded"}), (200, {}, {"ok": 1})]) + client, _ = client_for({("GET", "x"): lambda d: next(answers)}) + assert client.get("x") == {"ok": 1} + + +def test_redirects_are_refused_by_the_default_opener(): + handler = canvas_api._NoRedirect() + with pytest.raises(Exception, match="refused redirect"): + handler.redirect_request(type("R", (), {"full_url": "u"})(), None, 302, "", {}, "https://x") + + +# ── gradebook export ───────────────────────────────────────────────────────── + + +def test_read_gradebook_keeps_only_score_fields(): + client, _ = client_for(course_routes()) + gb = canvas.read_gradebook(client, 77) + for s in gb.scores.values(): + assert set(s) == set(canvas.SCORE_FIELDS) + assert "SECRET ESSAY TEXT" not in repr(gb) + + +def test_export_matches_the_canvas_layout_and_round_trips(tmp_path): + client, _ = client_for(course_routes()) + rows = canvas.gradebook_rows(canvas.read_gradebook(client, 77)) + headers, posting, points = rows[:3] + assert headers[:5] == canvas.IDENTITY_COLS + # Group order, then position; the hidden column is left out. + assert headers[5:7] == ["Week 1 - Intro (10)", "Lab 1 - Threads (11)"] + assert posting[5:7] == ["", "Manual Posting"] + assert points[0] == " Points Possible" and points[5:7] == ["5.00", "60.00"] + assert points[headers.index("Override Score")] == "" + assert points[headers.index("Current Score")] == "(read only)" + # Students in sortable-name order; EX and blanks as Canvas writes them. + assert [r[0] for r in rows[3:]] == ["Able, Bo", "Zed, Ann"] + assert rows[3][5:7] == ["EX", ""] + assert rows[4][5:7] == ["5.00", "55.50"] + + out = tmp_path / "export.csv" + canvas.write_csv(rows, out) + assert oct(out.stat().st_mode & 0o777) == "0o600" + norm = lms_grades.normalize_grades(lms_grades.parse_canvas_csv(out)) + zed = next(g for g in norm.grades if g.display_name == "Zed, Ann") + assert zed.student_id == "012345678" # re-padded to nine digits + assert json.loads(zed.assignment_scores) == {"Lab 1 - Threads": "55.50", + "Week 1 - Intro": "5.00"} + assert zed.current_score == "91.50" and zed.final_grade == "B" + + +def test_grades_export_writes_into_the_archive_by_default(vault, monkeypatch): + note = vault / "classes" / "326" / "326-01-fa26.md" + note.write_text(note.read_text().replace("---\n\n#", "canvas:\n course-id: 77\n---\n\n#", 1)) + client, _ = client_for(course_routes()) + rc = canvas.main(["grades-export", "--term", "fa26", "--vault-root", str(vault), + "--course", "CECS 326", "--section", "01"], client=client) + assert rc == 0 + out = list((vault / "classes" / "326" / "archives" / "fa26-01" / "canvas").glob("*.csv")) + assert len(out) == 1 and out[0].name.endswith("_Grades-CECS_326_Sec01.csv") + + +# ── binding ────────────────────────────────────────────────────────────────── + + +COURSES = [ + {"id": 123142, "name": "CECS 326 Sec01 1131 Operating Systems", "term": {"name": "Fall 2026"}}, + {"id": 50000, "name": "CECS 326 Sec01 1131 Operating Systems", "term": {"name": "Fall 2021"}}, + {"id": 123151, "name": "CECS 326 Sec03 10674 Operating Systems", "term": {"name": "Fall 2026"}}, +] + + +def test_a_recurring_class_number_is_settled_by_the_term(): + sec = {"course": "CECS 326", "section": "01", "class-number": 1131} + assert canvas.match_course(COURSES, sec, "Fall 2026")["id"] == 123142 + + +def test_no_match_is_an_error_naming_the_section(): + sec = {"course": "CECS 378", "section": "01", "class-number": 4785} + with pytest.raises(canvas.CanvasCmdError, match="CECS 378 §01"): + canvas.match_course(COURSES, sec, "Fall 2026") + + +def test_bind_records_the_course_id_in_the_class_note(vault): + client, _ = client_for({("GET", "courses"): COURSES}) + rc = canvas.main(["courses", "--bind", "--term", "fa26", "--vault-root", str(vault), + "--course", "CECS 326", "--section", "01"], client=client) + assert rc == 0 + note = (vault / "classes" / "326" / "326-01-fa26.md").read_text() + assert "canvas:\n course-id: 123142\n url: https://canvas.test/courses/123142" in note + + +def test_an_unbound_section_points_at_bind(vault, capsys): + client, _ = client_for({}) + rc = canvas.main(["grades-export", "--term", "fa26", "--vault-root", str(vault), + "--course", "CECS 326", "--section", "01"], client=client) + assert rc == 2 and "courses --bind" in capsys.readouterr().err + + +# ── grades push ────────────────────────────────────────────────────────────── + + +def import_file(tmp_path, rows) -> Path: + p = tmp_path / "import.csv" + with p.open("w", newline="") as fh: + w = csv.writer(fh) + w.writerow(["Student", "ID", "SIS User ID", "SIS Login ID", "Section", + "Week 1 - Intro (10)", "Lab 1 - Threads (11)", "Current Score"]) + w.writerow([" Points Possible", "", "", "", "", "5.00", "60.00", "(read only)"]) + w.writerows(rows) + return p + + +def push_routes(cid=77): + r = course_routes(cid) + r[("POST", f"courses/{cid}/assignments/11/submissions/update_grades")] = { + "id": 1, "workflow_state": "queued", "url": f"{BASE}/api/v1/progress/1"} + r[("GET", "progress/1")] = {"id": 1, "workflow_state": "completed"} + return r + + +def test_push_plans_only_changed_cells(tmp_path): + client, _ = client_for(course_routes()) + gb = canvas.read_gradebook(client, 77) + cols, rows = canvas.parse_import_csv(import_file(tmp_path, [ + ["Zed, Ann", "501", "12345678", "", "", "5.00", "58"], # lab changed + ["Able, Bo", "502", "023456789", "", "", "EX", ""], # same, blank lab + ["Ghost, G", "999", "999999999", "", "", "5", "60"], # not enrolled + ])) + changes, warnings = canvas.plan_push(gb, cols, rows, None) + assert [(c.sis, c.assignment_id, c.old, c.new) for c in changes] == [("012345678", 11, "55.50", "58")] + assert any("not enrolled" in w for w in warnings) + + +def test_push_refuses_another_courses_file(tmp_path): + client, _ = client_for(course_routes()) + gb = canvas.read_gradebook(client, 77) + cols = {999: "Lab 9 (999)"} + with pytest.raises(canvas.CanvasCmdError, match="wrong section"): + canvas.plan_push(gb, cols, [], None) + + +def test_push_is_a_dry_run_without_apply(tmp_path): + client, fake = client_for(push_routes()) + f = import_file(tmp_path, [["Zed, Ann", "501", "12345678", "", "", "5", "58"]]) + rc = canvas.main(["grades-push", "--course-id", "77", "--file", str(f)], client=client) + assert rc == 0 and fake.writes() == [] + + +def test_push_apply_posts_one_bulk_update(tmp_path): + client, fake = client_for(push_routes()) + f = import_file(tmp_path, [["Zed, Ann", "501", "12345678", "", "", "5", "58"]]) + rc = canvas.main(["grades-push", "--course-id", "77", "--file", str(f), "--apply"], + client=client) + assert rc == 0 + assert fake.writes() == [("POST", "courses/77/assignments/11/submissions/update_grades", + {"grade_data": {"501": {"posted_grade": "58"}}})] + + +# ── content ────────────────────────────────────────────────────────────────── + + +def test_announce_dry_run_writes_nothing(tmp_path): + f = tmp_path / "a.html" + f.write_text("

hello

") + client, fake = client_for(course_routes()) + rc = canvas.main(["announce", "--course-id", "77", "--file", str(f), "--title", "New"], + client=client) + assert rc == 0 and fake.writes() == [] + + +def test_announce_skips_a_title_that_already_exists(tmp_path, capsys): + f = tmp_path / "a.html" + f.write_text("

hello

") + client, fake = client_for(course_routes()) + canvas.main(["announce", "--course-id", "77", "--file", str(f), "--title", "Old news", + "--apply"], client=client) + assert fake.writes() == [] and "already exists" in capsys.readouterr().out + + +def test_announce_apply_posts_an_announcement(tmp_path): + f = tmp_path / "a.html" + f.write_text("

hello

") + routes = course_routes() + routes[("POST", "courses/77/discussion_topics")] = {"id": 5, "html_url": "u"} + client, fake = client_for(routes) + canvas.main(["announce", "--course-id", "77", "--file", str(f), "--title", "New", + "--apply"], client=client) + (method, path, data), = fake.writes() + assert data == {"title": "New", "message": "

hello

", "is_announcement": True} + + +def test_markdown_title_comes_from_the_h1(tmp_path): + pytest.importorskip("shutil").which("pandoc") or pytest.skip("pandoc not installed") + f = tmp_path / "a.md" + f.write_text("# Lab 2 posted\n\nAccept it **now**.\n") + title, html = canvas.render_body(f) + assert title == "Lab 2 posted" and "now" in html and "Lab 2 posted" not in html + + +def test_discussion_is_unpublished_unless_asked(tmp_path): + f = tmp_path / "d.html" + f.write_text("

prompt

") + routes = course_routes() + routes[("POST", "courses/77/discussion_topics")] = {"id": 6} + client, fake = client_for(routes) + canvas.main(["discussion", "--course-id", "77", "--file", str(f), "--title", "Week 8", + "--apply"], client=client) + assert fake.writes()[0][2]["published"] is False + + +def test_assignment_resolves_its_group_and_stays_unpublished(): + routes = course_routes() + routes[("POST", "courses/77/assignments")] = {"id": 13, "name": "Lab 3"} + client, fake = client_for(routes) + canvas.main(["assignment", "--course-id", "77", "--name", "Lab 3", "--points", "100", + "--group", "assignments and labs", "--due", "2026-11-20T23:59:00-08:00", + "--apply"], client=client) + body = fake.writes()[0][2]["assignment"] + assert body["assignment_group_id"] == 2 and body["published"] is False + assert body["submission_types"] == ["none"] and body["points_possible"] == 100 + + +def test_syllabus_refuses_a_file_without_the_notes_serial(vault, tmp_path, capsys): + note = vault / "classes" / "326" / "326-01-fa26.md" + note.write_text(note.read_text().replace( + "---\n\n#", "canvas:\n course-id: 77\nsyllabus:\n serial: 487BD388\n---\n\n#", 1)) + f = tmp_path / "syllabus_canvas.html" + f.write_text("

no serial here

") + client, fake = client_for({}) + rc = canvas.main(["syllabus", "--term", "fa26", "--vault-root", str(vault), + "--course", "CECS 326", "--section", "01", "--file", str(f), "--apply"], + client=client) + assert rc == 2 and "487BD388" in capsys.readouterr().err and fake.writes() == []