diff --git a/CHANGELOG.md b/CHANGELOG.md index ac06114..58bff19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,24 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). A `Retry-After` hint is capped at 60s so a hostile or broken value cannot stall a pass. Permanent failures (404, 400) and expired sessions are still not retried. +- **PowerSchool MyCBE support (`sis` command tree).** The CBE parent/student + portal (https://sis.cbe.ab.ca) is now a first-class surface: + - `sis login` / `sis logout` — session-cookie auth against MyCBE + - `sis whoami` — student profile and section count + - `sis years` — academic-year picker + - `sis grades` — enrolled classes for the active year + - `sis grades --marks` — current T1/S1 course marks from the guardian + "Assignments & Grades" page + - `sis standards` — rubric outcomes per section + - `sis standard-grades` — outcome grades with proficiency codes and + calculated percentages + - `sis assignments` — posted assignments with due dates, categories, + scores and flags; bounded per-cell fan-out + - `sis scale` — the CBE High School Proficiency Scale + - `sis school` — per-school config + The `.env` file is optional for read-only commands; only login and the + 401/403 re-auth path need credentials. Every `sis --json` payload is a + `count` envelope with snake_case keys. ### Changed - **Output overhaul across every command.** Human-readable output is now a diff --git a/README.md b/README.md index 57ceea0..41ca504 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ README spotlight; everything else lives further down. | `archive` | Snapshot courses into a versioned, UUID-named blob store. Subcommand `list` for the saved index. | | `assignment` / `dropbox` | List folders, show my submissions, download files. Scope with `--course `. | | `quiz` | List quizzes and show my attempts. Scope with `--course `. | +| `sis` | PowerSchool MyCBE parent/student portal (`sis login`, `sis whoami`, `sis grades`, `sis grades --marks`, `sis standards`, `sis standard-grades`, `sis assignments`, `sis scale`, `sis years`, `sis school`). | ## Common flags @@ -322,6 +323,69 @@ specifically need scriptable access. Each of these has full `--help` text with endpoint details. +### PowerSchool MyCBE (`sis` subtree) + +The Calgary Board of Education's parent/student portal +(https://sis.cbe.ab.ca) is the PowerSchool SIS in a different skin. We +talk to it through the Angular SPA's internal REST endpoints at +`/ws/xte/…`, with session-cookie auth. + +```sh +schooltools sis login # sign in to MyCBE (saves to ~/.config/schooltools/sis-session.json) +schooltools sis whoami # student profile + section count +schooltools sis years # year picker +schooltools sis grades # every enrolled section for the active year +schooltools sis grades --marks # course marks for every reporting term (T1, T2, S1, …) +schooltools sis standards # standards (rubric items) per section +schooltools sis standard-grades # outcome grades + calculated percentages +schooltools sis assignments # posted assignments (often empty early in a term) +schooltools sis scale # CBE High School Proficiency Scale +schooltools sis school # per-school config (max comment size, etc.) +schooltools sis logout # clear the SIS session +``` + +The `.env` file is required only when credentials are actually needed: +`sis login` and any automatic re-authentication (when the saved session +is missing or the portal returns 401/403). Every read-only subcommand +works from the saved session alone, so `sis whoami`, +`sis grades --marks` and friends run fine in a directory without an +`.env`. + +Every `sis --json` payload is an envelope with a `count` field and +snake_case keys, so `sis grades`, `sis standard-grades`, `sis +assignments`, `sis standards`, `sis years` and `sis school` can be +consumed without special-casing each command. + +Auth uses `SIS_STUDENT_NUMBER` + `SIS_PASSWORD` from `.env` (fall +back to `CBE_STUDENT_NUMBER` + `CBE_PASSWORD`, then `CBE_EMAIL` + +`CBE_PASSWORD` — the last of which warns on stderr, because MyCBE +expects the student number and will reject an email address). CBE +customised PowerSchool's `doPCASLogin` to send +plaintext passwords, so no HMAC or `pskey` is required. The login +follows the browser's flow: + +1. `GET /public/` seeds the `JSESSIONID` cookie +2. `POST /guardian/home.html` with form-urlencoded credentials → 302 + back to `/guardian/home.html`, which sets the four session + cookies (`JSESSIONID`, `psaid`, `currentSchool`, `current_locale`) +3. The four cookies are saved to the SIS session file + +Redirects that leave the portal's origin are refused. + +`--auto-refresh` (on by default) re-authenticates when the saved +session is missing. To keep a logout sticky, pass +`--auto-refresh=false` to each subsequent command. A `sis` command +that gets a 401/403 from the portal also re-authenticates once and +retries, because PowerSchool issues `psaid`/`JSESSIONID` without an +`Expires` and a server-side revocation is invisible to the local expiry +check. + +Set `SIS_DCID=` in `.env` to skip the credentials-link scrape +that `sis whoami` uses to discover the internal DCID. `sis assignments` +drills into the per-cell legacy endpoint once per standard, so it takes +`--section ` to narrow a run and `--max-cells` (default 200) to +cap it. + ## Migration notes ### 0.1.0 → 0.2.0 diff --git a/cmd/assignment.go b/cmd/assignment.go index 6aaebd7..f5e864a 100644 --- a/cmd/assignment.go +++ b/cmd/assignment.go @@ -543,7 +543,7 @@ func fetchMySubmissions(jar *cookiejar.Jar, courseID, folderID string) ([]Entity if err != nil { return nil, err } - defer res.Body.Close() + defer func() { _ = res.Body.Close() }() if res.StatusCode == 403 { return nil, errSubmissionsBlocked } @@ -565,7 +565,7 @@ func fetchFeedback(jar *cookiejar.Jar, courseID, folderID, entityType, entityID if err != nil { return nil, err } - defer res.Body.Close() + defer func() { _ = res.Body.Close() }() if res.StatusCode == 404 { return nil, nil } @@ -786,9 +786,9 @@ func submissionsSection(rep assignmentReport) string { } var b strings.Builder for i, s := range rep.Submissions { - b.WriteString(fmt.Sprintf(" %s %s\n", + fmt.Fprintf(&b, " %s %s\n", render.Accent(fmt.Sprintf("#%d", i+1)), - render.When(s.Date()))) + render.When(s.Date())) if note := s.Note(); note != "" { b.WriteString(" " + render.Wrap(note, render.Width()-4) + "\n") } @@ -973,7 +973,7 @@ func formatFeedbackRubric(out Feedback, rubric *Rubric, folderID int, courseID s if lvl := rubric.OverallLevelName(score); lvl != "" { value += " → " + render.Accent(lvl) } - b.WriteString(fmt.Sprintf("\n %-*s %s\n", 46, "Overall", value)) + fmt.Fprintf(&b, "\n %-*s %s\n", 46, "Overall", value) } } } diff --git a/cmd/course.go b/cmd/course.go index 85b27b9..9f0336e 100644 --- a/cmd/course.go +++ b/cmd/course.go @@ -389,7 +389,7 @@ func renderCourseReport(rep courseReportOut, id string, own d2lCourse, haveOwn b break } when := n.Date() - b.WriteString(fmt.Sprintf(" %s %s\n", render.Muted(render.Truncate(render.Rel(when), 12)), render.Truncate(n.Title, 60))) + fmt.Fprintf(&b, " %s %s\n", render.Muted(render.Truncate(render.Rel(when), 12)), render.Truncate(n.Title, 60)) } b.WriteString(render.Hint("schooltools news --course %s", id)) } @@ -554,10 +554,6 @@ func dateOrEmpty(s *string) string { return *s } -func formatDate(s *string) string { - return render.Date(dateOrEmpty(s)) -} - func plural(n int) string { if n == 1 { return "" diff --git a/cmd/quiz.go b/cmd/quiz.go index 18bbcd2..10f4d47 100644 --- a/cmd/quiz.go +++ b/cmd/quiz.go @@ -421,7 +421,7 @@ func fetchQuizAttemptsFor(jar *cookiejar.Jar, courseID, quizID string) ([]QuizAt if err != nil { return nil, err } - defer res.Body.Close() + defer func() { _ = res.Body.Close() }() if res.StatusCode == 403 { return nil, fmt.Errorf("D2L refused (403) — students cannot read this quiz's attempts") } @@ -564,10 +564,10 @@ func attemptsSection(ats []QuizAttempt) string { if !a.Done() { done = render.When(a.StartTime()) + " " + render.Warn("in progress") } - b.WriteString(fmt.Sprintf(" %-6s %-44s %s\n", + fmt.Fprintf(&b, " %-6s %-44s %s\n", fmt.Sprintf("#%d", a.AttemptNumber), done, - score)) + score) } if best := bestAttemptScore(ats); best != "" { b.WriteString(render.KV(render.Row{Key: "Best", Value: render.Accent(best)})) diff --git a/cmd/root.go b/cmd/root.go index 9b9890d..c1cd381 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -8,6 +8,7 @@ import ( "github.com/spf13/cobra" + "github.com/IamCoder18/schooltools/internal/authlog" "github.com/IamCoder18/schooltools/internal/httpclient" "github.com/IamCoder18/schooltools/internal/login" ) @@ -28,6 +29,7 @@ func init() { rootCmd.SilenceErrors = true rootCmd.PersistentFlags().BoolVar(&noAuthLog, "no-auth-log", false, "Disable the JSONL auth log (~/.config/schooltools/auth.log)") cobra.OnInitialize(func() { + authlog.SetEnabled(!noAuthLog) httpclient.RegisterTokenRefresher(login.TokenRefresher()) }) } diff --git a/cmd/sis.go b/cmd/sis.go new file mode 100644 index 0000000..b023da7 --- /dev/null +++ b/cmd/sis.go @@ -0,0 +1,128 @@ +package cmd + +import ( + goerrors "errors" + "fmt" + "io/fs" + "net/http/cookiejar" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/authlog" + "github.com/IamCoder18/schooltools/internal/cookies" + "github.com/IamCoder18/schooltools/internal/env" + "github.com/IamCoder18/schooltools/internal/ps" +) + +var sisCmd = &cobra.Command{ + Use: "sis", + Short: "PowerSchool MyCBE parent/student portal (sis.cbe.ab.ca)", + Long: "Access the Calgary Board of Education's PowerSchool SIS parent\n" + + "and student portal (https://sis.cbe.ab.ca). The portal is an Angular\n" + + "SPA on top of PowerSchool 21.06 / PDS 31.0.3 with internal REST\n" + + "endpoints under /ws/xte/....\n\n" + + "Login uses the student number (NOT email) + password. CBE customised\n" + + "PowerSchool's doPCASLogin to send plaintext passwords, so no HMAC\n" + + "or pskey is required.\n\n" + + "Use SIS_STUDENT_NUMBER + SIS_PASSWORD in .env (falls back to\n" + + "CBE_EMAIL + CBE_PASSWORD).", + Args: cobra.NoArgs, + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + envFile, _ := cmd.Flags().GetString("env-file") + return loadEnvOptional(envFile) + }, + RunE: func(cmd *cobra.Command, args []string) error { + return cmd.Help() + }, +} + +func init() { + sisCmd.PersistentFlags().StringP("env-file", "e", ".env", "Path to .env (read for SIS_STUDENT_NUMBER / SIS_PASSWORD)") + sisCmd.PersistentFlags().Bool("auto-refresh", true, "Re-run 'sis login' automatically when the saved session is missing or the portal rejects it") + sisCmd.PersistentFlags().Bool("json", false, "Emit machine-readable JSON instead of a table") + rootCmd.AddCommand(sisCmd) +} + +func loadEnvOptional(envFile string) error { + if err := env.LoadEnv(envFile); err != nil && !goerrors.Is(err, fs.ErrNotExist) { + return err + } + return nil +} + +func sisClient(cmd *cobra.Command) (*ps.Client, error) { + envFile, _ := cmd.Flags().GetString("env-file") + autoRefresh, _ := cmd.Flags().GetBool("auto-refresh") + + loginFn := func() ([]cookies.Record, error) { return sisLoginRunner(envFile) } + if !autoRefresh { + loginFn = nil + } + + jar, err := ps.EnsureSession(ps.EnsureSessionOptions{ + AutoRefresh: autoRefresh, + LoginFn: loginFn, + }) + if err != nil { + return nil, err + } + + client := ps.NewClient(jar) + if autoRefresh { + client.SetReauth(func() (*cookiejar.Jar, error) { + _ = authlog.Log("sis.reauth", map[string]any{"reason": "portal returned 401/403"}) + return ps.Reauthenticate(loginFn) + }) + } + return client, nil +} + +func resolveYearID(client *ps.Client, dcid int64, override int) (int, error) { + if override != 0 { + return override, nil + } + years, err := client.GetYears(dcid) + if err != nil { + return 0, err + } + if len(years) == 0 { + return 0, fmt.Errorf("year picker returned no entries for this student; pass --year to select one explicitly") + } + latest := years[0].YearID + for _, y := range years[1:] { + if y.YearID > latest { + latest = y.YearID + } + } + return latest, nil +} + +func sisLoginRunner(envFile string) ([]cookies.Record, error) { + if err := env.LoadEnv(envFile); err != nil { + return nil, err + } + creds, err := env.GetSISCreds() + if err != nil { + return nil, err + } + _ = authlog.Log("sis.login.start", map[string]any{"account": creds.Account}) + records, err := ps.Login(ps.LoginOptions{ + Account: creds.Account, + Password: creds.Password, + }) + if err != nil { + logSISLoginFailure(err) + return nil, err + } + _ = authlog.Log("sis.login.success", map[string]any{"cookie_count": len(records)}) + return records, nil +} + +func logSISLoginFailure(err error) { + code := "PS_LOGIN_ERROR" + var coder interface{ AuthCode() string } + if goerrors.As(err, &coder) { + code = coder.AuthCode() + } + _ = authlog.Log("sis.login.failure", map[string]any{"code": code, "message": err.Error()}) +} diff --git a/cmd/sis_assignments.go b/cmd/sis_assignments.go new file mode 100644 index 0000000..c73cc98 --- /dev/null +++ b/cmd/sis_assignments.go @@ -0,0 +1,342 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "html" + "os" + "sort" + "strconv" + "strings" + "sync" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +var ( + sisAssignmentsYear int + sisAssignmentsSection int64 + + sisAssignmentsMaxCells int +) + +// sisAssignment is the flattened row we surface to the user. PowerSchool +// stores assignments keyed by (student, section, standard) and only one +// assignment can live in each cell, but the legacy +// /guardian/studentSectionStemAssignments.json endpoint returns the +// human-friendly fields (assignmentName, category, dueDate, score +// token) so we don't need to fetch /ws/xte/assignment/lookup at all. +type sisAssignment struct { + SectionDCID int64 `json:"section_dcid"` + SectionName string `json:"section_name"` + StandardID int64 `json:"standard_id"` + AssignmentID int64 `json:"assignment_id"` + AssignmentName string `json:"assignment_name"` + Category string `json:"category"` + DueDate string `json:"due_date"` + Score string `json:"score"` + ScoreLabel string `json:"score_label,omitempty"` + ScorePercent *float64 `json:"score_percent,omitempty"` + IsCollected bool `json:"is_collected"` + IsLate bool `json:"is_late"` + IsMissing bool `json:"is_missing"` + IsExempt bool `json:"is_exempt"` + IsAbsent bool `json:"is_absent"` + IsIncomplete bool `json:"is_incomplete"` +} + +const ( + // sisCellWorkers bounds concurrent legacy-endpoint calls. PowerSchool + // issues session cookies with no Expires and may rate-limit a student + // account, so the fan-out is deliberately capped rather than opened + // to one goroutine per cell. + sisCellWorkers = 6 + // sisMaxCells is the default ceiling on per-cell requests. A student + // with ~13 sections and ~5 standards each is ~65 cells, so the default + // covers a normal full run while stopping a mistyped --section from + // turning into hundreds of live calls. + sisMaxCells = 200 +) + +// sisCell is one (section, standard) pair to drill into. +type sisCell struct { + sectionDCID int64 + standardID int64 +} + +// fetchStemCells drills into the legacy per-cell endpoint with bounded +// concurrency. Per-cell failures are collected rather than aborting the +// run, so one flaky cell does not discard every other assignment. +func fetchStemCells(client *ps.Client, studentID int64, cells []sisCell) ([]sisAssignment, map[sisCell]error) { + failures := make(map[sisCell]error) + results := make([][]sisAssignment, len(cells)) + var failMu sync.Mutex + + work := make(chan int) + var wg sync.WaitGroup + for w := 0; w < sisCellWorkers; w++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := range work { + c := cells[i] + cell, err := client.GetStemAssignment(studentID, c.sectionDCID, c.standardID) + if err != nil { + failMu.Lock() + failures[c] = err + failMu.Unlock() + continue + } + results[i] = stemRows(cell.Data) + } + }() + } + for i := range cells { + work <- i + } + close(work) + wg.Wait() + + var out []sisAssignment + for _, rs := range results { + out = append(out, rs...) + } + return out, failures +} + +// stemRows converts one cell's payload into assignment rows, dropping +// the sentinel empty cell the endpoint returns when no assignment has +// been posted. +func stemRows(data []ps.StemAssignment) []sisAssignment { + var out []sisAssignment + for _, d := range data { + if d.AssignmentID == "" { + continue + } + id, _ := strconv.ParseInt(d.AssignmentID, 10, 64) + sec, _ := strconv.ParseInt(d.SectionDCID, 10, 64) + stdid, _ := strconv.ParseInt(d.StandardID, 10, 64) + label, percent := proficiencyFor(d.ActualScoreEntered) + out = append(out, sisAssignment{ + SectionDCID: sec, + StandardID: stdid, + AssignmentID: id, + AssignmentName: html.UnescapeString(d.AssignmentName), + Category: html.UnescapeString(d.Category), + DueDate: d.DueDate, + Score: d.ActualScoreEntered, + ScoreLabel: label, + ScorePercent: percent, + IsCollected: d.IsCollected == "1", + IsLate: d.IsLate == "1", + IsMissing: d.IsMissing == "1", + IsExempt: d.IsExempt == "1", + IsAbsent: d.IsAbsent == "1", + IsIncomplete: d.IsIncomplete == "1", + }) + } + return out +} + +// proficiencyFor maps a PowerSchool score token to its human label and +// nominal percentage. Unknown or empty tokens return empty values. +func proficiencyFor(code string) (string, *float64) { + p, ok := ps.LookupProficiency(code) + if !ok { + return "", nil + } + if p.Percent == nil { + return p.Label, nil + } + v := float64(*p.Percent) + return p.Label, &v +} + +func formatScore(code, label string) string { + if code == "" { + return "—" + } + if label == "" { + return code + } + return code + " (" + label + ")" +} + +func assignmentFlags(a sisAssignment) string { + var flags []string + if a.IsCollected { + flags = append(flags, "collected") + } + if a.IsLate { + flags = append(flags, "late") + } + if a.IsMissing { + flags = append(flags, "missing") + } + if a.IsExempt { + flags = append(flags, "exempt") + } + if a.IsAbsent { + flags = append(flags, "absent") + } + if a.IsIncomplete { + flags = append(flags, "incomplete") + } + return strings.Join(flags, ",") +} + +var sisAssignmentsCmd = &cobra.Command{ + Use: "assignments", + Short: "List assignments posted to the student's sections", + Long: "Walks every (student, section, standard) tuple from\n" + + "/ws/xte/standard_grade_section and drills into the per-cell\n" + + "/guardian/studentSectionStemAssignments.json endpoint to surface\n" + + "every assignment a teacher has posted. PowerSchool stores each\n" + + "assignment against a specific standard, so this command makes\n" + + "one API call per standard — pass --section to limit to a single\n" + + "class and reduce the number of calls.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + + client, err := sisClient(cmd) + if err != nil { + return err + } + dcid, err := resolveStudentDCID(client) + if err != nil { + return err + } + yearID, err := resolveYearID(client, dcid, sisAssignmentsYear) + if err != nil { + return err + } + stu, err := client.GetEnrollments(dcid, yearID) + if err != nil { + return err + } + // Build a sectionDCID → course name map so we can label each row. + sectionName := map[int64]string{} + sectionIDs := make([]int64, 0, len(stu.Enrollments)) + for _, e := range stu.Enrollments { + if sisAssignmentsSection == 0 || e.SectionDCID == sisAssignmentsSection { + sectionIDs = append(sectionIDs, e.SectionDCID) + sectionName[e.SectionDCID] = e.Section.CourseName + } + } + if len(sectionIDs) == 0 { + if sisAssignmentsSection != 0 { + return fmt.Errorf("section %d is not among this student's enrollments for year %d", sisAssignmentsSection, yearID) + } + return fmt.Errorf("no enrollments for school year %d; pass --year to select a different year", yearID) + } + // Get the (student, section, standard) join — one row per standard. + rows, err := client.GetStandardGrades(dcid, sectionIDs, yearID) + if err != nil { + return err + } + cells := make([]sisCell, 0, len(rows)) + for _, r := range rows { + cells = append(cells, sisCell{sectionDCID: r.SectionDCID, standardID: r.StandardID}) + } + if sisAssignmentsMaxCells > 0 && len(cells) > sisAssignmentsMaxCells { + return fmt.Errorf("%d standard cells exceed --max-cells %d; narrow the run with --section or raise --max-cells", len(cells), sisAssignmentsMaxCells) + } + + fmt.Fprintf(os.Stderr, "Fetching %d standard cell(s) across %d section(s) (year %d)…\n", len(cells), len(sectionIDs), yearID) + fetched, failures := fetchStemCells(client, stu.ID, cells) + + // De-dup on (section, assignment); assignmentId can recur. + seen := map[string]bool{} + out := make([]sisAssignment, 0, len(fetched)) + for _, a := range fetched { + a.SectionName = sectionName[a.SectionDCID] + key := fmt.Sprintf("%d|%d", a.SectionDCID, a.AssignmentID) + if seen[key] { + continue + } + seen[key] = true + out = append(out, a) + } + sort.Slice(out, func(i, j int) bool { + if out[i].SectionName != out[j].SectionName { + return out[i].SectionName < out[j].SectionName + } + if out[i].DueDate != out[j].DueDate { + return out[i].DueDate < out[j].DueDate + } + return out[i].AssignmentID < out[j].AssignmentID + }) + + if len(failures) > 0 { + keys := make([]string, 0, len(failures)) + for c := range failures { + keys = append(keys, fmt.Sprintf("section %d/standard %d", c.sectionDCID, c.standardID)) + } + sort.Strings(keys) + shown := keys + if len(shown) > 5 { + shown = shown[:5] + } + fmt.Fprintf(os.Stderr, "Warning: %d of %d cell(s) failed to load and are missing from the results: %s\n", len(failures), len(cells), strings.Join(shown, ", ")) + if len(keys) > len(shown) { + fmt.Fprintf(os.Stderr, " …and %d more.\n", len(keys)-len(shown)) + } + } + + if asJSON { + j := map[string]any{ + "count": len(out), + "year_id": yearID, + "section_ids": sectionIDs, + "cells_total": len(cells), + "cells_failed": len(failures), + "assignments": out, + } + b, _ := json.MarshalIndent(j, "", " ") + fmt.Println(string(b)) + return nil + } + if len(out) == 0 { + fmt.Fprintln(os.Stderr, "No assignments posted yet (PowerSchool returns empty cells until teachers grade).") + return nil + } + fmt.Fprintf(os.Stderr, "Found %d assignment(s) across %d section(s) (year %d)\n", len(out), len(sectionIDs), yearID) + trows := make([][]string, len(out)) + for i, a := range out { + name := a.AssignmentName + if flags := assignmentFlags(a); flags != "" { + name += " [" + flags + "]" + } + trows[i] = []string{ + a.SectionName, + a.DueDate, + a.Category, + name, + formatScore(a.Score, a.ScoreLabel), + } + } + fmt.Print(table.Render(table.Options{ + Headers: []string{"Course", "Due", "Category", "Assignment", "Score"}, + Widths: table.Widths( + []table.ColumnSpec{ + table.Fixed(20), table.Fixed(13), table.Fixed(18), + table.Flex(28), table.Fixed(18), + }, + table.TerminalWidth()), + Rows: trows, + Wrap: true, + })) + return nil + }, +} + +func init() { + sisAssignmentsCmd.Flags().IntVar(&sisAssignmentsYear, "year", 0, "School year ID (default: latest from the year picker)") + sisAssignmentsCmd.Flags().Int64Var(&sisAssignmentsSection, "section", 0, "Limit to a single section DCID (default: every enrolled section)") + sisAssignmentsCmd.Flags().IntVar(&sisAssignmentsMaxCells, "max-cells", sisMaxCells, "Maximum per-standard API calls before aborting (0 disables the limit)") + sisCmd.AddCommand(sisAssignmentsCmd) +} diff --git a/cmd/sis_assignments_test.go b/cmd/sis_assignments_test.go new file mode 100644 index 0000000..11ea499 --- /dev/null +++ b/cmd/sis_assignments_test.go @@ -0,0 +1,158 @@ +package cmd + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/httpclient" + "github.com/IamCoder18/schooltools/internal/ps" +) + +// TestStemRowsSkipsSentinelCells asserts cells with no assignmentId are +// dropped: the legacy endpoint returns a trailing {} sentinel for every +// cell without a posted assignment. +func TestStemRowsSkipsSentinelCells(t *testing.T) { + rows := stemRows([]ps.StemAssignment{ + {AssignmentID: "", AssignmentName: ""}, + { + AssignmentID: "77", + SectionDCID: "96000001", + StandardID: "15400129", + AssignmentName: "Unit 1 quiz", + Category: "Quiz", + DueDate: "2026-10-01", + ActualScoreEntered: "EX1", + IsMissing: "1", + IsCollected: "0", + }, + }) + require.Len(t, rows, 1) + assert.Equal(t, int64(77), rows[0].AssignmentID) + assert.Equal(t, int64(96000001), rows[0].SectionDCID) + assert.Equal(t, "EX1", rows[0].Score) + assert.True(t, rows[0].IsMissing) + assert.False(t, rows[0].IsCollected) +} + +// TestStemRowsCoercesStringIDs asserts the legacy all-string payload is +// coerced to int64, and that unparseable values degrade to zero rather +// than panicking. +func TestStemRowsCoercesStringIDs(t *testing.T) { + rows := stemRows([]ps.StemAssignment{ + {AssignmentID: "notanumber", SectionDCID: "alsonot", StandardID: "nope"}, + }) + require.Len(t, rows, 1) + assert.Equal(t, int64(0), rows[0].AssignmentID) + assert.Equal(t, int64(0), rows[0].SectionDCID) +} + +// TestFetchStemCellsIsolatesFailures asserts one failing cell does not +// abort the run or discard the cells that succeeded — the behaviour the +// old serial loop got wrong when it returned on the first error. The +// handler blocks until two requests are provably in flight, so the +// concurrency assertion is deterministic rather than timing-dependent. +func TestFetchStemCellsIsolatesFailures(t *testing.T) { + const wantOverlap = 2 + release := make(chan struct{}) + arrived := make(chan struct{}, 8) + var timedOut atomic.Bool + + mux := http.NewServeMux() + mux.HandleFunc("/guardian/studentSectionStemAssignments.json", func(w http.ResponseWriter, r *http.Request) { + arrived <- struct{}{} + select { + case <-release: + case <-time.After(5 * time.Second): + timedOut.Store(true) + } + + if r.URL.Query().Get("standardId") == "2" { + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"assignmentId":"5","sectionDcid":"1","standardId":"1","assignmentName":"A"}]}`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + c.Base = srv.URL + + cells := []sisCell{ + {sectionDCID: 1, standardID: 1}, + {sectionDCID: 1, standardID: 2}, + {sectionDCID: 1, standardID: 3}, + {sectionDCID: 1, standardID: 4}, + } + done := make(chan struct{}) + var out []sisAssignment + var failures map[sisCell]error + go func() { + out, failures = fetchStemCells(c, 92000001, cells) + close(done) + }() + + for i := 0; i < wantOverlap; i++ { + select { + case <-arrived: + case <-time.After(5 * time.Second): + close(release) + <-done + t.Fatalf("only %d of %d requests overlapped; the fan-out is not concurrent", i, wantOverlap) + } + } + close(release) + <-done + + require.False(t, timedOut.Load(), "handler timed out waiting for release") + assert.Len(t, failures, 1) + assert.Contains(t, failures, cells[1]) + assert.Len(t, out, 3, "the three healthy cells should still be returned") +} + +// TestProficiencyFor asserts score tokens map to the published label and +// nominal percentage, and that unknown or empty tokens stay unlabelled. +func TestProficiencyFor(t *testing.T) { + label, percent := proficiencyFor("ex2") + assert.Equal(t, "Exemplary 2", label) + require.NotNil(t, percent) + assert.Equal(t, 100.0, *percent) + + label, percent = proficiencyFor(" PR1 ") + assert.Equal(t, "Proficient 1", label) + require.NotNil(t, percent) + assert.Equal(t, 75.0, *percent) + + label, percent = proficiencyFor("") + assert.Empty(t, label) + assert.Nil(t, percent) + + label, percent = proficiencyFor("ZZ9") + assert.Empty(t, label) + assert.Nil(t, percent) +} + +// TestFormatScore asserts the table cell falls back to the raw token when +// the level is unknown, and to a dash when there is no score yet. +func TestFormatScore(t *testing.T) { + assert.Equal(t, "—", formatScore("", "")) + assert.Equal(t, "EX1", formatScore("EX1", "")) + assert.Equal(t, "EX1 (Exemplary 1)", formatScore("EX1", "Exemplary 1")) +} + +// TestAssignmentFlags asserts only the set flags are listed, in a stable +// order, so the table can append them to the assignment name. +func TestAssignmentFlags(t *testing.T) { + assert.Empty(t, assignmentFlags(sisAssignment{})) + assert.Equal(t, "collected,missing", assignmentFlags(sisAssignment{IsCollected: true, IsMissing: true})) + assert.Equal(t, "late,exempt", assignmentFlags(sisAssignment{IsLate: true, IsExempt: true})) +} diff --git a/cmd/sis_grades.go b/cmd/sis_grades.go new file mode 100644 index 0000000..3ab2da2 --- /dev/null +++ b/cmd/sis_grades.go @@ -0,0 +1,179 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +var ( + sisGradesYear int + sisGradesMarks bool +) + +// sisSectionRow is the flattened JSON shape for one enrolled class. +// PowerSchool nests the course details under _coursesectioninfo; we +// flatten it so every sis JSON payload uses snake_case and one level of +// nesting. +type sisSectionRow struct { + SectionDCID int64 `json:"section_dcid"` + Status string `json:"status"` + EnrolledLate bool `json:"enrolled_late"` + SectionNum string `json:"section_num,omitempty"` + Expression string `json:"expression,omitempty"` + CourseName string `json:"course_name"` + CourseNum string `json:"course_num"` + Teacher string `json:"teacher"` + Term string `json:"term"` + TermAbbr string `json:"term_abbr"` +} + +func sisSectionRows(enrollments []ps.Enrollment) []sisSectionRow { + out := make([]sisSectionRow, 0, len(enrollments)) + for _, e := range enrollments { + out = append(out, sisSectionRow{ + SectionDCID: e.SectionDCID, + Status: e.Status, + EnrolledLate: e.EnrolledLate, + SectionNum: e.Section.SectionNum, + Expression: e.Section.Expression, + CourseName: e.Section.CourseName, + CourseNum: e.Section.CourseNum, + Teacher: e.Section.TeacherName, + Term: e.Section.TermName, + TermAbbr: e.Section.TermAbbreviation, + }) + } + return out +} + +var sisGradesCmd = &cobra.Command{ + Use: "grades", + Short: "List the student's enrolled classes, or their current course marks", + Long: "By default lists every class the student is enrolled in for the\n" + + "active school year. With --marks, reads the portal's\n" + + "\"Assignments & Grades\" page and prints the current T1/S1 mark\n" + + "for each course, matching what PowerSchool displays.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + + client, err := sisClient(cmd) + if err != nil { + return err + } + if sisGradesMarks { + return runSISGradesMarks(client, asJSON) + } + dcid, err := resolveStudentDCID(client) + if err != nil { + return err + } + yearID, err := resolveYearID(client, dcid, sisGradesYear) + if err != nil { + return err + } + + stu, err := client.GetEnrollments(dcid, yearID) + if err != nil { + return err + } + rows := sisSectionRows(stu.Enrollments) + + if asJSON { + out := map[string]any{ + "count": len(rows), + "year_id": yearID, + "student": stu.LastFirst, + "sections": rows, + } + b, _ := json.MarshalIndent(out, "", " ") + fmt.Println(string(b)) + return nil + } + fmt.Fprintf(os.Stderr, "Found %d section(s) for %s (year %d)\n", len(rows), stu.LastFirst, yearID) + tableRows := make([][]string, len(rows)) + for i, r := range rows { + tableRows[i] = []string{ + fmt.Sprintf("%d", r.SectionDCID), + r.TermAbbr, + r.CourseNum, + r.CourseName, + r.Teacher, + r.Term, + } + } + fmt.Print(table.Render(table.Options{ + Headers: []string{"Section", "Term", "Code", "Course", "Teacher", "Term Name"}, + Widths: table.Widths( + []table.ColumnSpec{ + table.Fixed(10), table.Fixed(6), table.Fixed(14), + table.Flex(16), table.Flex(16), table.Flex(12), + }, + table.TerminalWidth()), + Rows: tableRows, + Wrap: true, + })) + return nil + }, +} + +func runSISGradesMarks(client *ps.Client, asJSON bool) error { + marks, err := client.GetCourseMarks() + if err != nil { + return err + } + if marks == nil { + marks = []ps.CourseMark{} + } + if asJSON { + out := map[string]any{"count": len(marks), "courses": marks} + b, _ := json.MarshalIndent(out, "", " ") + fmt.Println(string(b)) + return nil + } + if len(marks) == 0 { + fmt.Fprintln(os.Stderr, "No course marks posted yet.") + return nil + } + terms := ps.MarkTerms() + headers := []string{"Course", "Teacher"} + headers = append(headers, terms...) + rows := make([][]string, len(marks)) + for i, m := range marks { + row := []string{m.Course, m.Teacher} + for _, term := range terms { + row = append(row, markOrDash(m.MarkFor(term))) + } + rows[i] = row + } + widths := []table.ColumnSpec{table.Flex(16), table.Flex(12)} + for range terms { + widths = append(widths, table.Fixed(6)) + } + fmt.Print(table.Render(table.Options{ + Headers: headers, + Widths: table.Widths(widths, table.TerminalWidth()), + Rows: rows, + Wrap: true, + })) + return nil +} + +func markOrDash(mark string) string { + if mark == "" { + return "—" + } + return mark +} + +func init() { + sisGradesCmd.Flags().IntVar(&sisGradesYear, "year", 0, "School year ID (default: latest from the year picker)") + sisGradesCmd.Flags().BoolVar(&sisGradesMarks, "marks", false, "Show current course marks (T1/S1) from the guardian grades page") + sisCmd.AddCommand(sisGradesCmd) +} diff --git a/cmd/sis_grades_test.go b/cmd/sis_grades_test.go new file mode 100644 index 0000000..eafb3fc --- /dev/null +++ b/cmd/sis_grades_test.go @@ -0,0 +1,45 @@ +package cmd + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/ps" +) + +func TestSISSectionRowsFlattens(t *testing.T) { + rows := sisSectionRows([]ps.Enrollment{ + { + SectionDCID: 1533424, + Status: "A", + EnrolledLate: true, + Section: ps.SectionInfo{ + SectionNum: "211", + Expression: "R1(A)", + CourseName: "Mathematics 20-1_cohort IB", + CourseNum: "MAT2791H", + TeacherName: "Weiss, Tannis R", + TermName: "Semester 2", + TermAbbreviation: "S2", + }, + }, + }) + require.Len(t, rows, 1) + assert.Equal(t, int64(1533424), rows[0].SectionDCID) + assert.Equal(t, "A", rows[0].Status) + assert.True(t, rows[0].EnrolledLate) + assert.Equal(t, "211", rows[0].SectionNum) + assert.Equal(t, "R1(A)", rows[0].Expression) + assert.Equal(t, "MAT2791H", rows[0].CourseNum) + assert.Equal(t, "Mathematics 20-1_cohort IB", rows[0].CourseName) + assert.Equal(t, "Weiss, Tannis R", rows[0].Teacher) + assert.Equal(t, "Semester 2", rows[0].Term) + assert.Equal(t, "S2", rows[0].TermAbbr) +} + +func TestMarkOrDash(t *testing.T) { + assert.Equal(t, "—", markOrDash("")) + assert.Equal(t, "97", markOrDash("97")) +} diff --git a/cmd/sis_login.go b/cmd/sis_login.go new file mode 100644 index 0000000..069aed7 --- /dev/null +++ b/cmd/sis_login.go @@ -0,0 +1,34 @@ +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" +) + +var sisLoginCmd = &cobra.Command{ + Use: "login", + Short: "Authenticate against PowerSchool MyCBE and persist the SIS session", + Long: "Sign in to sis.cbe.ab.ca using SIS_STUDENT_NUMBER (or CBE_EMAIL) +\n" + + "SIS_PASSWORD (or CBE_PASSWORD) from .env and persist the four\n" + + "session cookies (JSESSIONID, psaid, currentSchool, current_locale)\n" + + "to ~/.config/schooltools/sis-session.json.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + envFile, _ := cmd.Flags().GetString("env-file") + records, err := sisLoginRunner(envFile) + if err != nil { + return err + } + if err := ps.Save(records); err != nil { + return err + } + fmt.Fprintf(os.Stderr, "Saved %d PowerSchool cookie(s) to %s\n", len(records), ps.SessionPath()) + return nil + }, +} + +func init() { sisCmd.AddCommand(sisLoginCmd) } diff --git a/cmd/sis_logout.go b/cmd/sis_logout.go new file mode 100644 index 0000000..74648d4 --- /dev/null +++ b/cmd/sis_logout.go @@ -0,0 +1,31 @@ +package cmd + +import ( + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/authlog" + "github.com/IamCoder18/schooltools/internal/ps" +) + +var sisLogoutCmd = &cobra.Command{ + Use: "logout", + Short: "Delete the saved PowerSchool session", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + existed := false + if _, err := os.Stat(ps.SessionPath()); err == nil { + existed = true + } + if err := ps.Clear(); err != nil { + return err + } + fmt.Fprintln(os.Stderr, "PowerSchool session cleared.") + _ = authlog.Log("sis.logout", map[string]any{"saved_session_existed": existed}) + return nil + }, +} + +func init() { sisCmd.AddCommand(sisLogoutCmd) } diff --git a/cmd/sis_scale.go b/cmd/sis_scale.go new file mode 100644 index 0000000..560ade6 --- /dev/null +++ b/cmd/sis_scale.go @@ -0,0 +1,51 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +var sisScaleCmd = &cobra.Command{ + Use: "scale", + Short: "Show the CBE High School Proficiency Scale and nominal percentages", + Long: "CBE reports high-school achievement on an eight-level proficiency\n" + + "scale (EX2 → BG1). This prints every level with the nominal\n" + + "percentage CBE publishes for it. Levels whose percentage CBE does\n" + + "not publish are shown with a dash; the calculated percentage for\n" + + "a real outcome is on the `sis standard-grades` row.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + levels := ps.Scale() + + if asJSON { + out := map[string]any{"count": len(levels), "levels": levels} + b, _ := json.MarshalIndent(out, "", " ") + fmt.Println(string(b)) + return nil + } + rows := make([][]string, len(levels)) + for i, l := range levels { + percent := "—" + if l.Percent != nil { + percent = strconv.Itoa(*l.Percent) + "%" + } + rows[i] = []string{l.Code, l.Label, percent} + } + fmt.Printf("CBE High School Proficiency Scale (%d levels)\n", len(levels)) + fmt.Print(table.Render(table.Options{ + Headers: []string{"Code", "Level", "Nominal %"}, + Widths: table.Widths([]table.ColumnSpec{table.Fixed(8), table.Flex(24), table.Fixed(12)}, table.TerminalWidth()), + Rows: rows, + })) + return nil + }, +} + +func init() { sisCmd.AddCommand(sisScaleCmd) } diff --git a/cmd/sis_school.go b/cmd/sis_school.go new file mode 100644 index 0000000..aa52bc4 --- /dev/null +++ b/cmd/sis_school.go @@ -0,0 +1,107 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +var sisSchoolYear int + +// sisSchoolLimitRow is the flattened JSON shape for one school's +// comment-size configuration. +type sisSchoolLimitRow struct { + SchoolID int `json:"school_id"` + SchoolDCID int64 `json:"school_dcid"` + MaxFinalGradeCommentSize int `json:"max_final_grade_comment_size"` +} + +func sisSchoolLimitRows(limits []ps.SchoolCommentLimit) []sisSchoolLimitRow { + out := make([]sisSchoolLimitRow, 0, len(limits)) + for _, l := range limits { + out = append(out, sisSchoolLimitRow{ + SchoolID: l.SchoolID, + SchoolDCID: l.SchoolDCID, + MaxFinalGradeCommentSize: l.MaxFinalGradeCommentSize, + }) + } + return out +} + +var sisSchoolCmd = &cobra.Command{ + Use: "school", + Short: "Print PowerSchool school-level config (e.g. max comment size for the student's school)", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + + client, err := sisClient(cmd) + if err != nil { + return err + } + dcid, err := resolveStudentDCID(client) + if err != nil { + return err + } + yearID, err := resolveYearID(client, dcid, sisSchoolYear) + if err != nil { + return err + } + stu, err := client.GetEnrollments(dcid, yearID) + if err != nil { + return err + } + studentSchool := stu.SchoolID + + limits, err := client.GetSchoolCommentLimits() + if err != nil { + return err + } + schoolRows := sisSchoolLimitRows(limits) + + if asJSON { + out := map[string]any{ + "count": len(limits), + "student_school_id": studentSchool, + "year_id": yearID, + "limits": schoolRows, + } + b, _ := json.MarshalIndent(out, "", " ") + fmt.Println(string(b)) + return nil + } + fmt.Fprintf(os.Stderr, "Found %d school config(s); student is in school ID %d\n", len(limits), studentSchool) + rows := make([][]string, 0, len(limits)) + highlight := func(s int) string { + if s == studentSchool { + return "★ " + fmt.Sprintf("%d", s) + } + return fmt.Sprintf("%d", s) + } + for _, l := range limits { + rows = append(rows, []string{ + highlight(l.SchoolID), + fmt.Sprintf("%d", l.SchoolDCID), + fmt.Sprintf("%d", l.MaxFinalGradeCommentSize), + }) + } + fmt.Print(table.Render(table.Options{ + Headers: []string{"School ID", "School DCID", "Max comment chars"}, + Widths: table.Widths( + []table.ColumnSpec{table.Fixed(14), table.Fixed(14), table.Fixed(20)}, + table.TerminalWidth()), + Rows: rows, + })) + return nil + }, +} + +func init() { + sisSchoolCmd.Flags().IntVar(&sisSchoolYear, "year", 0, "School year ID (default: latest from the year picker)") + sisCmd.AddCommand(sisSchoolCmd) +} diff --git a/cmd/sis_standard_grades.go b/cmd/sis_standard_grades.go new file mode 100644 index 0000000..9b02e60 --- /dev/null +++ b/cmd/sis_standard_grades.go @@ -0,0 +1,199 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "strconv" + "strings" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +var ( + sisStandardGradesYear int + sisStandardGradesSection int64 +) + +// sisStandardGradeRow is the flattened JSON shape for one outcome grade. +type sisStandardGradeRow struct { + StandardGradeID int64 `json:"standard_grade_id"` + StudentDCID int64 `json:"student_dcid"` + StandardID int64 `json:"standard_id"` + SectionDCID int64 `json:"section_dcid"` + StoreCode string `json:"store_code"` + Course string `json:"course"` + Grade string `json:"grade"` + Percent *float64 `json:"percent"` + Flags []string `json:"flags,omitempty"` + LastUpdated string `json:"last_updated"` +} + +func sisStandardGradeRows(rows []ps.StandardGrade, sectionName map[int64]string) []sisStandardGradeRow { + out := make([]sisStandardGradeRow, 0, len(rows)) + for _, r := range rows { + out = append(out, sisStandardGradeRow{ + StandardGradeID: r.ID, + StudentDCID: r.StudentDCID, + StandardID: r.StandardID, + SectionDCID: r.SectionDCID, + StoreCode: r.StoreCode, + Course: sectionName[r.SectionDCID], + Grade: r.Grade, + Percent: r.Percent, + Flags: standardGradeFlags(r), + LastUpdated: r.LastUpdated, + }) + } + return out +} + +func standardGradeFlags(r ps.StandardGrade) []string { + var flags []string + if r.IsExempt { + flags = append(flags, "exempt") + } + if r.IsIncomplete { + flags = append(flags, "incomplete") + } + if r.IsLocked { + flags = append(flags, "locked") + } + if !r.IsEnrolled { + flags = append(flags, "not_enrolled") + } + if r.IsMigrated { + flags = append(flags, "migrated") + } + if r.IsAdminModified { + flags = append(flags, "admin_modified") + } + if r.IsReportsRollupExcluded { + flags = append(flags, "reports_rollup_excluded") + } + if r.IsManuallyOverridden { + flags = append(flags, "manually_overridden") + } + return flags +} + +func formatPercent(p *float64) string { + if p == nil { + return "—" + } + return strconv.FormatFloat(*p, 'f', -1, 64) +} + +var sisStandardGradesCmd = &cobra.Command{ + Use: "standard-grades", + Short: "Show (student, section, standard) grade rows posted by teachers", + Long: "Lists every standard-grade row PowerSchool has for the active\n" + + "school year, including the proficiency code and the calculated\n" + + "percentage. Each row also carries per-(student, section, standard)\n" + + "flags (isexempt, isincomplete, islocked, isenrolled, …); the\n" + + "per-assignment score behind the outcome is available from\n" + + "`sis assignments`.\n\n" + + "Often empty early in a term — PowerSchool doesn't create these\n" + + "rows until teachers post assignments against the standards.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + + client, err := sisClient(cmd) + if err != nil { + return err + } + dcid, err := resolveStudentDCID(client) + if err != nil { + return err + } + yearID, err := resolveYearID(client, dcid, sisStandardGradesYear) + if err != nil { + return err + } + stu, err := client.GetEnrollments(dcid, yearID) + if err != nil { + return err + } + sectionIDs := make([]int64, 0, len(stu.Enrollments)) + sectionName := map[int64]string{} + for _, e := range stu.Enrollments { + if sisStandardGradesSection == 0 || e.SectionDCID == sisStandardGradesSection { + sectionIDs = append(sectionIDs, e.SectionDCID) + sectionName[e.SectionDCID] = e.Section.CourseName + } + } + if len(sectionIDs) == 0 { + if sisStandardGradesSection != 0 { + return fmt.Errorf("section %d is not among this student's enrollments for year %d", sisStandardGradesSection, yearID) + } + return fmt.Errorf("no enrollments for school year %d; pass --year to select a different year", yearID) + } + rows, err := client.GetStandardGrades(dcid, sectionIDs, yearID) + if err != nil { + return err + } + out := sisStandardGradeRows(rows, sectionName) + + if asJSON { + j := map[string]any{ + "count": len(out), + "year_id": yearID, + "section_ids": sectionIDs, + "standard_grades": out, + } + b, _ := json.MarshalIndent(j, "", " ") + fmt.Println(string(b)) + return nil + } + if len(out) == 0 { + fmt.Fprintln(os.Stderr, "No standard-grade rows posted yet (PowerSchool returns [] before teachers post assignments).") + return nil + } + fmt.Fprintf(os.Stderr, "Found %d standard-grade row(s) across %d section(s) (year %d)\n", len(out), len(sectionIDs), yearID) + tableRows := make([][]string, len(out)) + for i, r := range out { + tableRows[i] = []string{ + r.Course, + r.StoreCode, + fmt.Sprintf("%d", r.StandardID), + fmt.Sprintf("%d", r.SectionDCID), + gradeOrDash(r.Grade), + formatPercent(r.Percent), + joinFlags(r.Flags), + } + } + fmt.Print(table.Render(table.Options{ + Headers: []string{"Course", "Store", "Standard", "Section", "Grade", "%", "Flags"}, + Widths: table.Widths( + []table.ColumnSpec{ + table.Flex(20), table.Fixed(6), table.Fixed(10), + table.Fixed(10), table.Fixed(6), table.Fixed(7), table.Flex(12), + }, + table.TerminalWidth()), + Rows: tableRows, + Wrap: true, + })) + return nil + }, +} + +func gradeOrDash(grade string) string { + if grade == "" { + return "—" + } + return grade +} + +func joinFlags(flags []string) string { + return strings.Join(flags, ",") +} + +func init() { + sisStandardGradesCmd.Flags().IntVar(&sisStandardGradesYear, "year", 0, "School year ID (default: latest from the year picker)") + sisStandardGradesCmd.Flags().Int64Var(&sisStandardGradesSection, "section", 0, "Limit to a single section DCID (default: every enrolled section)") + sisCmd.AddCommand(sisStandardGradesCmd) +} diff --git a/cmd/sis_standard_grades_test.go b/cmd/sis_standard_grades_test.go new file mode 100644 index 0000000..82b8799 --- /dev/null +++ b/cmd/sis_standard_grades_test.go @@ -0,0 +1,74 @@ +package cmd + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/ps" +) + +func TestSISStandardGradeRows(t *testing.T) { + percent := 97.5 + rows := sisStandardGradeRows([]ps.StandardGrade{ + { + ID: 1, + StudentDCID: 2, + StandardID: 3, + SectionDCID: 4, + StoreCode: "T1", + Grade: "EX1", + Percent: &percent, + IsIncomplete: true, + LastUpdated: "2026-11-01 10:00:00", + IsEnrolled: true, + }, + { + ID: 5, + StudentDCID: 2, + StandardID: 6, + SectionDCID: 4, + StoreCode: "S1", + IsEnrolled: true, + }, + }, map[int64]string{4: "Science 10"}) + + require.Len(t, rows, 2) + assert.Equal(t, "Science 10", rows[0].Course) + assert.Equal(t, "EX1", rows[0].Grade) + require.NotNil(t, rows[0].Percent) + assert.Equal(t, 97.5, *rows[0].Percent) + assert.Equal(t, []string{"incomplete"}, rows[0].Flags) + assert.Equal(t, "2026-11-01 10:00:00", rows[0].LastUpdated) + + assert.Empty(t, rows[1].Grade) + assert.Nil(t, rows[1].Percent) + assert.Empty(t, rows[1].Flags) +} + +func TestSISStandardGradeRowsFlags(t *testing.T) { + rows := sisStandardGradeRows([]ps.StandardGrade{ + {ID: 1, IsExempt: true, IsLocked: true, IsEnrolled: false}, + }, nil) + require.Len(t, rows, 1) + assert.Equal(t, []string{"exempt", "locked", "not_enrolled"}, rows[0].Flags) +} + +func TestFormatPercent(t *testing.T) { + assert.Equal(t, "—", formatPercent(nil)) + + whole := 100.0 + assert.Equal(t, "100", formatPercent(&whole)) + + fractional := 97.5 + assert.Equal(t, "97.5", formatPercent(&fractional)) + + precise := 98.33 + assert.Equal(t, "98.33", formatPercent(&precise)) +} + +func TestGradeOrDash(t *testing.T) { + assert.Equal(t, "—", gradeOrDash("")) + assert.Equal(t, "EX2", gradeOrDash("EX2")) +} diff --git a/cmd/sis_standards.go b/cmd/sis_standards.go new file mode 100644 index 0000000..c1d3c96 --- /dev/null +++ b/cmd/sis_standards.go @@ -0,0 +1,141 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +var ( + sisStandardsYear int +) + +// sisStandardRow is the flattened JSON shape for one rubric outcome. +type sisStandardRow struct { + StandardID int64 `json:"standard_id"` + SectionDCID int64 `json:"section_dcid"` + Name string `json:"name"` + Identifier string `json:"identifier,omitempty"` + Description string `json:"description,omitempty"` + SubjectArea string `json:"subject_area,omitempty"` + YearID int `json:"year_id"` + DisplayPosition int `json:"display_position"` + ExcludedFromReports bool `json:"excluded_from_reports"` + AssignmentAllowed bool `json:"assignment_allowed"` + MaxCommentLength int `json:"max_comment_length"` +} + +func sisStandardRows(stds []ps.Standard, sectionDCID int64) []sisStandardRow { + out := make([]sisStandardRow, 0, len(stds)) + for _, s := range stds { + out = append(out, sisStandardRow{ + StandardID: s.ID, + SectionDCID: sectionDCID, + Name: s.Name, + Identifier: s.Identifier, + Description: s.Description, + SubjectArea: s.SubjectArea, + YearID: s.YearID, + DisplayPosition: s.DisplayPos, + ExcludedFromReports: s.IsExcluded, + AssignmentAllowed: s.IsAssignmentAllowed, + MaxCommentLength: s.MaxCommentLength, + }) + } + return out +} + +var sisStandardsCmd = &cobra.Command{ + Use: "standards", + Short: "List standards (rubric items) for every section the student is enrolled in", + Long: "CBE rebrands PowerSchool's \"Standards / Outcomes\" as \"Stems /\n" + + "Outcomes / Classes\". Each section has its own set of rubric\n" + + "items; teachers grade against them.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + + client, err := sisClient(cmd) + if err != nil { + return err + } + dcid, err := resolveStudentDCID(client) + if err != nil { + return err + } + yearID, err := resolveYearID(client, dcid, sisStandardsYear) + if err != nil { + return err + } + stu, err := client.GetEnrollments(dcid, yearID) + if err != nil { + return err + } + if len(stu.Enrollments) == 0 { + return fmt.Errorf("no enrollments for school year %d; pass --year to select a different year", yearID) + } + + rows := make([]sisStandardRow, 0) + seen := map[string]bool{} + for _, e := range stu.Enrollments { + stds, err := client.GetStandards([]int64{e.SectionDCID}) + if err != nil { + return err + } + for _, r := range sisStandardRows(stds, e.SectionDCID) { + key := fmt.Sprintf("%d/%d", r.SectionDCID, r.StandardID) + if seen[key] { + continue + } + seen[key] = true + rows = append(rows, r) + } + } + + if asJSON { + out := map[string]any{ + "count": len(rows), + "year_id": yearID, + "section_count": len(stu.Enrollments), + "standards": rows, + } + b, _ := json.MarshalIndent(out, "", " ") + fmt.Println(string(b)) + return nil + } + fmt.Fprintf(os.Stderr, "Found %d standard(s) across %d section(s) (year %d)\n", len(rows), len(stu.Enrollments), yearID) + tableRows := make([][]string, len(rows)) + for i, s := range rows { + tableRows[i] = []string{ + fmt.Sprintf("%d", s.StandardID), + fmt.Sprintf("%d", s.SectionDCID), + s.SubjectArea, + s.Identifier, + s.Name, + fmt.Sprintf("%d", s.YearID), + } + } + fmt.Print(table.Render(table.Options{ + Headers: []string{"ID", "Section", "Subject", "Identifier", "Name", "Year"}, + Widths: table.Widths( + []table.ColumnSpec{ + table.Fixed(8), table.Fixed(10), table.Fixed(10), + table.Fixed(16), table.Flex(30), table.Fixed(6), + }, + table.TerminalWidth()), + Rows: tableRows, + Wrap: true, + })) + return nil + }, +} + +func init() { + sisStandardsCmd.Flags().IntVar(&sisStandardsYear, "year", 0, "School year ID (default: latest from the year picker)") + sisCmd.AddCommand(sisStandardsCmd) +} diff --git a/cmd/sis_test.go b/cmd/sis_test.go new file mode 100644 index 0000000..0ecd1f8 --- /dev/null +++ b/cmd/sis_test.go @@ -0,0 +1,140 @@ +package cmd + +import ( + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/httpclient" + "github.com/IamCoder18/schooltools/internal/ps" +) + +func newYearClient(t *testing.T) *ps.Client { + t.Helper() + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/standard_grade_section/student/years", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"abbr":"23-24","yearid":34},{"abbr":"25-26","yearid":35},{"abbr":"26-27","yearid":36}]`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + c.Base = srv.URL + return c +} + +func TestResolveYearIDPicksNewest(t *testing.T) { + c := newYearClient(t) + got, err := resolveYearID(c, 90000001, 0) + require.NoError(t, err) + assert.Equal(t, 36, got) +} + +func TestResolveYearIDOverride(t *testing.T) { + c := newYearClient(t) + got, err := resolveYearID(c, 90000001, 34) + require.NoError(t, err) + assert.Equal(t, 34, got) +} + +func TestResolveYearIDEmptyPicker(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/standard_grade_section/student/years", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[]`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + c.Base = srv.URL + + _, err = resolveYearID(c, 90000001, 0) + require.Error(t, err) + assert.Contains(t, err.Error(), "no entries") +} + +func TestResolveYearIDUnorderedPicker(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/standard_grade_section/student/years", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"abbr":"26-27","yearid":36},{"abbr":"23-24","yearid":34},{"abbr":"25-26","yearid":35}]`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + c.Base = srv.URL + + got, err := resolveYearID(c, 90000001, 0) + require.NoError(t, err) + assert.Equal(t, 36, got) +} + +func TestResolveStudentDCIDParsesDashboard(t *testing.T) { + t.Setenv("SIS_DCID", "") + mux := http.NewServeMux() + mux.HandleFunc("/guardian/home.html", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`me`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + c.Base = srv.URL + + got, err := resolveStudentDCID(c) + require.NoError(t, err) + assert.Equal(t, int64(90000001), got) +} + +func TestResolveStudentDCIDReportsStaleSession(t *testing.T) { + t.Setenv("SIS_DCID", "") + mux := http.NewServeMux() + mux.HandleFunc("/guardian/home.html", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`please sign in`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + c.Base = srv.URL + + _, err = resolveStudentDCID(c) + require.Error(t, err) + assert.Contains(t, err.Error(), "likely expired") + assert.Contains(t, err.Error(), "schooltools sis login") +} + +func TestResolveStudentDCIDEnvOverride(t *testing.T) { + t.Setenv("SIS_DCID", "90000001") + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + + got, err := resolveStudentDCID(c) + require.NoError(t, err) + assert.Equal(t, int64(90000001), got) +} + +func TestLoadEnvOptionalToleratesMissing(t *testing.T) { + err := loadEnvOptional(filepath.Join(t.TempDir(), "missing.env")) + require.NoError(t, err) +} + +func TestLoadEnvOptionalPropagatesRealErrors(t *testing.T) { + err := loadEnvOptional(t.TempDir()) + require.Error(t, err) +} diff --git a/cmd/sis_whoami.go b/cmd/sis_whoami.go new file mode 100644 index 0000000..60dbc4d --- /dev/null +++ b/cmd/sis_whoami.go @@ -0,0 +1,121 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + stderrors "github.com/IamCoder18/schooltools/internal/errors" + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +var sisWhoamiYear int + +var sisWhoamiCmd = &cobra.Command{ + Use: "whoami", + Short: "Verify the saved SIS session and print the student profile", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + + client, err := sisClient(cmd) + if err != nil { + return err + } + dcid, err := resolveStudentDCID(client) + if err != nil { + return fmt.Errorf("could not resolve student DCID: %w", err) + } + yearID, err := resolveYearID(client, dcid, sisWhoamiYear) + if err != nil { + return fmt.Errorf("/ws/xte/standard_grade_section/student/years failed: %w", err) + } + stu, err := client.GetEnrollments(dcid, yearID) + if err != nil { + return fmt.Errorf("/ws/xte/student/%d/enrollments failed: %w", dcid, err) + } + if stu.DCID == 0 { + return fmt.Errorf("PowerSchool returned an empty student record; run 'schooltools sis login'") + } + + if asJSON { + out := map[string]any{ + "count": 1, + "dcid": stu.DCID, + "id": stu.ID, + "person_id": stu.PersonID, + "student_no": stu.StudentNo, + "name": stu.LastFirst, + "first_name": stu.FirstName, + "last_name": stu.LastName, + "grade_level": stu.GradeLevel, + "school_id": stu.SchoolID, + "sections": len(stu.Enrollments), + "year_id": yearID, + } + b, _ := json.MarshalIndent(out, "", " ") + fmt.Println(string(b)) + return nil + } + + fmt.Fprintf(os.Stderr, "Verified: PowerSchool accepted the saved session.\n") + out := table.Render(table.Options{ + Headers: []string{"Field", "Value"}, + Widths: table.Widths([]table.ColumnSpec{table.Fixed(14), table.Flex(32)}, table.TerminalWidth()), + Rows: [][]string{ + {"DCID", fmt.Sprintf("%d", stu.DCID)}, + {"Student No", stu.StudentNo}, + {"Name", stu.LastFirst}, + {"Grade", fmt.Sprintf("%d", stu.GradeLevel)}, + {"School ID", fmt.Sprintf("%d", stu.SchoolID)}, + {"Year ID", fmt.Sprintf("%d", yearID)}, + {"Sections", fmt.Sprintf("%d", len(stu.Enrollments))}, + }, + }) + fmt.Print(out) + return nil + }, +} + +func init() { + sisWhoamiCmd.Flags().IntVar(&sisWhoamiYear, "year", 0, "School year ID (default: latest from the year picker)") + sisCmd.AddCommand(sisWhoamiCmd) +} + +// resolveStudentDCID returns the logged-in student's DCID. The +// PowerSchool year-picker endpoint needs it. +// +// Precedence: +// 1. SIS_DCID env var (skip the scrape). +// 2. Scrape /guardian/home.html — PowerSchool's Angular SPA embeds +// the student record inside an inline bootstrap script. +// +// The dashboard is part of the live PS HTML surface; it's the same +// authenticated path the SPA uses, so a successful GET implies a +// working session. +func resolveStudentDCID(client *ps.Client) (int64, error) { + if v := os.Getenv("SIS_DCID"); v != "" { + var d int64 + if _, err := fmt.Sscanf(v, "%d", &d); err == nil && d > 0 { + return d, nil + } + } + body, err := client.GetDashboardHTML() + if err != nil { + return 0, err + } + dcid := ps.ExtractDCIDFromDashboard(body) + if dcid == 0 { + if !strings.Contains(body, "credentials.html") { + return 0, stderrors.New("PS_SESSION_STALE", + fmt.Sprintf("PowerSchool returned %d bytes without the guardian dashboard; the saved SIS session is likely expired — run 'schooltools sis login'", len(body))) + } + return 0, stderrors.New("PS_DCID_PARSE", + fmt.Sprintf("could not find the student DCID in the guardian dashboard (%d bytes); set SIS_DCID in the env file or run 'schooltools sis login'", len(body))) + } + return dcid, nil +} diff --git a/cmd/sis_years.go b/cmd/sis_years.go new file mode 100644 index 0000000..397f328 --- /dev/null +++ b/cmd/sis_years.go @@ -0,0 +1,69 @@ +package cmd + +import ( + "encoding/json" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/IamCoder18/schooltools/internal/ps" + "github.com/IamCoder18/schooltools/internal/table" +) + +// sisYearRow is the flattened JSON shape for one academic year. +type sisYearRow struct { + Abbr string `json:"abbr"` + YearID int `json:"year_id"` +} + +func sisYearRows(years []ps.Year) []sisYearRow { + out := make([]sisYearRow, 0, len(years)) + for _, y := range years { + out = append(out, sisYearRow{Abbr: y.Abbr, YearID: y.YearID}) + } + return out +} + +var sisYearsCmd = &cobra.Command{ + Use: "years", + Short: "List academic years available for the logged-in student", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + asJSON, _ := cmd.Flags().GetBool("json") + + client, err := sisClient(cmd) + if err != nil { + return err + } + dcid, err := resolveStudentDCID(client) + if err != nil { + return err + } + years, err := client.GetYears(dcid) + if err != nil { + return err + } + yearRows := sisYearRows(years) + + if asJSON { + out := map[string]any{"count": len(yearRows), "years": yearRows} + b, _ := json.MarshalIndent(out, "", " ") + fmt.Println(string(b)) + return nil + } + rows := make([][]string, len(yearRows)) + for i, y := range yearRows { + rows[i] = []string{y.Abbr, fmt.Sprintf("%d", y.YearID)} + } + fmt.Fprintf(os.Stderr, "Found %d year(s)\n", len(years)) + fmt.Print(table.Render(table.Options{ + Headers: []string{"Year", "Year ID"}, + Widths: table.Widths([]table.ColumnSpec{table.Fixed(8), table.Fixed(10)}, table.TerminalWidth()), + Rows: rows, + })) + return nil + }, +} + +func init() { sisCmd.AddCommand(sisYearsCmd) } diff --git a/internal/env/env.go b/internal/env/env.go index b7c133d..0e9df46 100644 --- a/internal/env/env.go +++ b/internal/env/env.go @@ -13,6 +13,14 @@ type Creds struct { Password string } +// SISCreds holds PowerSchool MyCBE credentials. The account is a student +// number, not an email — the CBE portal uses the student ID for the +// parent/student login. +type SISCreds struct { + Account string + Password string +} + func LoadEnv(envFile string) error { path, err := filepath.Abs(envFile) if err != nil { @@ -21,7 +29,7 @@ func LoadEnv(envFile string) error { f, err := os.Open(path) if err != nil { if os.IsNotExist(err) { - return fmt.Errorf("env file not found: %s (create it with CBE_EMAIL and CBE_PASSWORD, or pass --env-file )", envFile) + return fmt.Errorf("env file not found: %s (create it with CBE_EMAIL and CBE_PASSWORD, or pass --env-file ): %w", envFile, err) } return err } @@ -52,4 +60,32 @@ func GetCreds() (Creds, error) { return Creds{}, fmt.Errorf("CBE_EMAIL and CBE_PASSWORD must be set in the env file; these are read from environment only and never logged") } return Creds{Email: email, Password: password}, nil -} \ No newline at end of file +} + +// GetSISCreds returns the PowerSchool SIS account + password. +// +// PowerSchool MyCBE uses the **student number**, not an email, so the +// obvious CBE_EMAIL fallback would silently try an email address as the +// username and fail. We prefer SIS_STUDENT_NUMBER, then +// CBE_STUDENT_NUMBER, then CBE_EMAIL — in that order — and we warn on +// stderr if the value still looks like an email. +func GetSISCreds() (SISCreds, error) { + account := os.Getenv("SIS_STUDENT_NUMBER") + if account == "" { + account = os.Getenv("CBE_STUDENT_NUMBER") + } + if account == "" { + account = os.Getenv("CBE_EMAIL") + } + password := os.Getenv("SIS_PASSWORD") + if password == "" { + password = os.Getenv("CBE_PASSWORD") + } + if account == "" || password == "" { + return SISCreds{}, fmt.Errorf("PowerSchool credentials missing: set SIS_STUDENT_NUMBER and SIS_PASSWORD (or CBE_STUDENT_NUMBER + CBE_PASSWORD) in the env file") + } + if strings.Contains(account, "@") { + fmt.Fprintf(os.Stderr, "Warning: SIS_STUDENT_NUMBER is unset, so '%s' from CBE_EMAIL was used as the PowerSchool username. MyCBE expects the student number and will reject an email address.\n", account) + } + return SISCreds{Account: account, Password: password}, nil +} diff --git a/internal/env/env_test.go b/internal/env/env_test.go new file mode 100644 index 0000000..20caf18 --- /dev/null +++ b/internal/env/env_test.go @@ -0,0 +1,161 @@ +package env_test + +import ( + "errors" + "io" + "io/fs" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/env" +) + +func writeEnv(t *testing.T, body string) string { + t.Helper() + p := filepath.Join(t.TempDir(), ".env") + require.NoError(t, os.WriteFile(p, []byte(body), 0o600)) + return p +} + +// clearSISEnv unsets every variable GetSISCreds consults. LoadEnv writes +// into the process environment, so without this a value set by one +// subtest leaks into the next. +func clearSISEnv(t *testing.T) { + t.Helper() + for _, k := range []string{"SIS_STUDENT_NUMBER", "CBE_STUDENT_NUMBER", "CBE_EMAIL", "SIS_PASSWORD", "CBE_PASSWORD"} { + t.Setenv(k, "") + require.NoError(t, os.Unsetenv(k)) + } +} + +// LoadEnv must export SIS_DCID into the process environment, not just the +// credentials the `sis` login path reads. resolveStudentDCID in +// cmd/sis_whoami.go reads SIS_DCID with os.Getenv, so a value written in +// .env was previously invisible on the valid-session path because nothing +// loaded the file before the lookup. +func TestLoadEnvExportsSISDCID(t *testing.T) { + p := writeEnv(t, "SIS_DCID=90000001\nSIS_STUDENT_NUMBER=1234567890\nSIS_PASSWORD=hunter2\n") + require.NoError(t, env.LoadEnv(p)) + assert.Equal(t, "90000001", os.Getenv("SIS_DCID")) +} + +// TestLoadEnvMissingWrapsNotExist asserts the missing-file error still +// satisfies errors.Is(err, fs.ErrNotExist). The sis command tree uses +// that to tolerate a missing .env when a saved session is already valid. +func TestLoadEnvMissingWrapsNotExist(t *testing.T) { + err := env.LoadEnv(filepath.Join(t.TempDir(), "missing.env")) + require.Error(t, err) + assert.True(t, errors.Is(err, fs.ErrNotExist)) + assert.Contains(t, err.Error(), "env file not found") +} + +func TestGetSISCredsPrecedence(t *testing.T) { + cases := []struct { + name string + body string + wantAccount string + }{ + { + name: "SIS_STUDENT_NUMBER wins", + body: "SIS_STUDENT_NUMBER=111\nCBE_STUDENT_NUMBER=222\nCBE_EMAIL=a@b.ca\n", + wantAccount: "111", + }, + { + name: "CBE_STUDENT_NUMBER is second", + body: "CBE_STUDENT_NUMBER=222\nCBE_EMAIL=a@b.ca\n", + wantAccount: "222", + }, + { + name: "CBE_EMAIL is the last resort", + body: "CBE_EMAIL=a@b.ca\n", + wantAccount: "a@b.ca", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + clearSISEnv(t) + require.NoError(t, env.LoadEnv(writeEnv(t, tc.body+"SIS_PASSWORD=hunter2\n"))) + creds, err := env.GetSISCreds() + require.NoError(t, err) + assert.Equal(t, tc.wantAccount, creds.Account) + assert.Equal(t, "hunter2", creds.Password) + }) + } +} + +func TestGetSISCredsPasswordFallback(t *testing.T) { + clearSISEnv(t) + require.NoError(t, env.LoadEnv(writeEnv(t, "SIS_STUDENT_NUMBER=111\nCBE_PASSWORD=fromcbe\n"))) + creds, err := env.GetSISCreds() + require.NoError(t, err) + assert.Equal(t, "fromcbe", creds.Password) +} + +func TestGetSISCredsMissing(t *testing.T) { + clearSISEnv(t) + _, err := env.GetSISCreds() + require.Error(t, err) + assert.Contains(t, err.Error(), "SIS_STUDENT_NUMBER") + // The message must not point at flags that do not exist. + assert.NotContains(t, err.Error(), "--password") +} + +func TestGetCredsUnchangedBySISHelper(t *testing.T) { + t.Setenv("CBE_EMAIL", "you@example.com") + t.Setenv("CBE_PASSWORD", "hunter2") + creds, err := env.GetCreds() + require.NoError(t, err) + assert.Equal(t, "you@example.com", creds.Email) + assert.Equal(t, "hunter2", creds.Password) +} + +// TestGetSISCredsWarnsOnEmailAccount asserts the documented stderr +// warning fires when the CBE_EMAIL fallback resolves the account, since +// MyCBE rejects an email address as the username. +func TestGetSISCredsWarnsOnEmailAccount(t *testing.T) { + clearSISEnv(t) + require.NoError(t, env.LoadEnv(writeEnv(t, "CBE_EMAIL=user@example.com\nCBE_PASSWORD=hunter2\n"))) + + r, w, err := os.Pipe() + require.NoError(t, err) + saved := os.Stderr + os.Stderr = w + + _, credsErr := env.GetSISCreds() + + os.Stderr = saved + require.NoError(t, w.Close()) + out, readErr := io.ReadAll(r) + require.NoError(t, readErr) + + require.NoError(t, credsErr) + got := string(out) + assert.Contains(t, got, "SIS_STUDENT_NUMBER") + assert.Contains(t, got, "user@example.com") +} + +// TestGetSISCredsNoWarnForStudentNumber asserts the warning is not +// emitted for a correctly configured student number. +func TestGetSISCredsNoWarnForStudentNumber(t *testing.T) { + clearSISEnv(t) + require.NoError(t, env.LoadEnv(writeEnv(t, "SIS_STUDENT_NUMBER=1234567890\nSIS_PASSWORD=hunter2\n"))) + + r, w, err := os.Pipe() + require.NoError(t, err) + saved := os.Stderr + os.Stderr = w + + _, credsErr := env.GetSISCreds() + + os.Stderr = saved + require.NoError(t, w.Close()) + out, readErr := io.ReadAll(r) + require.NoError(t, readErr) + + require.NoError(t, credsErr) + assert.Empty(t, string(out)) +} diff --git a/internal/errors/errors.go b/internal/errors/errors.go index b2711e0..41f7f3a 100644 --- a/internal/errors/errors.go +++ b/internal/errors/errors.go @@ -7,6 +7,11 @@ type AuthError struct { func (e *AuthError) Error() string { return e.Message } +// AuthCode lets callers use the same `interface{ AuthCode() string }` +// assertion against every auth failure type, so the machine-readable +// code always reaches the auth log instead of a per-call-site fallback. +func (e *AuthError) AuthCode() string { return e.Code } + func New(code, message string) *AuthError { return &AuthError{Code: code, Message: message} } @@ -46,4 +51,4 @@ func (e *AdfsRejectedError) Error() string { return "ADFS rejected the login: " + e.Reason } -func (e *AdfsRejectedError) AuthCode() string { return "ADFS_REJECTED" } \ No newline at end of file +func (e *AdfsRejectedError) AuthCode() string { return "ADFS_REJECTED" } diff --git a/internal/errors/errors_test.go b/internal/errors/errors_test.go index ad6e730..92727a2 100644 --- a/internal/errors/errors_test.go +++ b/internal/errors/errors_test.go @@ -11,6 +11,7 @@ func TestAuthError(t *testing.T) { e := stderrors.New("X", "msg") assert.Equal(t, "X", e.Code) assert.Equal(t, "msg", e.Error()) + assert.Equal(t, "X", e.AuthCode()) } func TestSamlConsumedError(t *testing.T) { @@ -35,4 +36,4 @@ func TestAdfsRejectedError(t *testing.T) { r := &stderrors.AdfsRejectedError{Reason: "bad password"} assert.Equal(t, "ADFS_REJECTED", r.AuthCode()) assert.Contains(t, r.Error(), "bad password") -} \ No newline at end of file +} diff --git a/internal/progress/progress_test.go b/internal/progress/progress_test.go index 8d20d56..69fef85 100644 --- a/internal/progress/progress_test.go +++ b/internal/progress/progress_test.go @@ -28,10 +28,10 @@ func homePage(token string) string { func TestFetchReturnsDefaultStateRow(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch { - case r.URL.Path == "/d2l/home": + switch r.URL.Path { + case "/d2l/home": _, _ = w.Write([]byte(homePage("tok"))) - case r.URL.Path == "/d2l/api/le/unstable/1522695/content/userprogress/7": + case "/d2l/api/le/unstable/1522695/content/userprogress/7": require.Equal(t, "42", r.URL.Query().Get("userId")) require.Equal(t, "tok", r.Header.Get("X-Csrf-Token")) require.Equal(t, "XMLHttpRequest", r.Header.Get("X-Requested-With")) @@ -52,10 +52,10 @@ func TestFetchReturnsDefaultStateRow(t *testing.T) { func TestUpdateSendsFullBodyWithoutIsExempt(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch { - case r.URL.Path == "/d2l/home": + switch r.URL.Path { + case "/d2l/home": _, _ = w.Write([]byte(homePage("tok"))) - case r.URL.Path == "/d2l/api/le/unstable/1522695/content/userprogress/": + case "/d2l/api/le/unstable/1522695/content/userprogress/": require.Equal(t, http.MethodPost, r.Method) require.Equal(t, "application/json", r.Header.Get("Content-Type")) var body map[string]any @@ -85,14 +85,14 @@ func TestUpdateSendsFullBodyWithoutIsExempt(t *testing.T) { func TestUpdateRetriesWithFreshTokenOn403(t *testing.T) { var homeHits atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch { - case r.URL.Path == "/d2l/home": + switch r.URL.Path { + case "/d2l/home": tok := "tok1" if homeHits.Add(1) >= 2 { tok = "tok2" } _, _ = w.Write([]byte(homePage(tok))) - case r.URL.Path == "/d2l/api/le/unstable/1522695/content/userprogress/": + case "/d2l/api/le/unstable/1522695/content/userprogress/": if r.Header.Get("X-Csrf-Token") != "tok2" { w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte(`{"Errors":[{"Message":"Forbidden"}]}`)) diff --git a/internal/ps/client.go b/internal/ps/client.go new file mode 100644 index 0000000..429a3f6 --- /dev/null +++ b/internal/ps/client.go @@ -0,0 +1,380 @@ +package ps + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/cookiejar" + "net/url" + "regexp" + "strconv" + "strings" + "sync" + + "github.com/IamCoder18/schooltools/internal/httpclient" +) + +// Client is the PowerSchool API client. It owns a cookie jar (set up +// by Login / EnsureSession) and applies the Origin header that the +// portal requires on POSTs. +type Client struct { + Jar *cookiejar.Jar + Base string // usually ps.BaseURL + + // reauth, when set, is invoked once when the portal answers 401 or + // 403 with a session that looked locally valid. PowerSchool issues + // psaid and JSESSIONID without an Expires, so a saved session never + // fails the local expiry check; only the server knows it is dead. + // Reauthenticating here is what keeps a revoked session from + // surfacing as a permanent opaque "HTTP 403" on every command. + reauth func() (*cookiejar.Jar, error) + + mu sync.Mutex + + // refreshMu collapses a concurrent burst of 401/403 into a single + // login. `sis assignments` fans out across workers, and without this + // an expired session would trigger one full re-login per in-flight + // request — a self-inflicted stampede on the very portal that just + // rejected us. + refreshMu sync.Mutex + refreshed bool + refreshJar *cookiejar.Jar + refreshErr error +} + +// NewClient wraps an existing jar. The base is fixed to BaseURL by +// default; tests can override. +func NewClient(jar *cookiejar.Jar) *Client { + return &Client{Jar: jar, Base: BaseURL} +} + +// SetReauth installs the hook used to recover from a server-side +// session expiry. It is safe to call concurrently with in-flight +// requests. +func (c *Client) SetReauth(fn func() (*cookiejar.Jar, error)) { + c.mu.Lock() + defer c.mu.Unlock() + c.reauth = fn +} + +func (c *Client) reauthFn() func() (*cookiejar.Jar, error) { + c.mu.Lock() + defer c.mu.Unlock() + return c.reauth +} + +// refreshOnce re-authenticates at most once for the lifetime of the +// Client. Concurrent callers that hit a 401/403 while a refresh is +// already in progress wait for that refresh and reuse its result rather +// than each starting their own login. The returned bool is false when no +// reauth hook is installed. +func (c *Client) refreshOnce() (*cookiejar.Jar, error, bool) { + hook := c.reauthFn() + if hook == nil { + return nil, nil, false + } + + c.refreshMu.Lock() + defer c.refreshMu.Unlock() + if c.refreshed { + return c.refreshJar, c.refreshErr, true + } + c.refreshed = true + jar, err := hook() + c.refreshJar, c.refreshErr = jar, err + return jar, err, true +} + +// Get issues an authenticated GET and decodes the JSON response. +func (c *Client) Get(path string, query url.Values, out any) error { + u := c.Base + path + if len(query) > 0 { + u += "?" + query.Encode() + } + return c.fetchJSON(http.MethodGet, u, nil, out) +} + +// Post issues an authenticated POST with a JSON body and decodes the +// response. Origin is automatically set to the base URL. +// +// Note: the cached ps.PostJSON variant from research-time differs from +// the GET by exactly one header (Origin) — we add it via the +// FetchOptions below. FetchOptions.Headers take precedence over the +// defaults set by browser.Headers(), so this is reliable. +func (c *Client) Post(path string, body any, out any) error { + u := c.Base + path + return c.fetchJSON(http.MethodPost, u, body, out) +} + +// fetchJSON performs the request and decodes into out. A 401 or 403 with +// a reauth hook installed is retried exactly once against a freshly +// authenticated jar. +// +// For non-2xx responses the error carries the status and a sanitized +// error-code hint. The response body is never embedded: PowerSchool +// error pages can echo the student record or other identifiers, and this +// error text reaches the terminal and the auth log. +func (c *Client) fetchJSON(method, rawURL string, body any, out any) error { + res, err := c.fetch(method, rawURL, body, jsonAccept, c.Base+"/guardian/grades.html") + if err != nil { + return err + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + if isSigninRedirect(res) { + _ = res.Body.Close() + return sessionStaleError(fmt.Sprintf("HTTP %d", res.StatusCode)) + } + _ = res.Body.Close() + return statusError(method, rawURL, res) + } + if out == nil { + _ = res.Body.Close() + return nil + } + defer func() { _ = res.Body.Close() }() + raw, err := io.ReadAll(res.Body) + if err != nil { + return fmt.Errorf("%s %s: read body: %v", method, redactedURL(rawURL), err) + } + trimmed := strings.TrimSpace(string(raw)) + if trimmed == "" { + return fmt.Errorf("%s %s: decode JSON: empty response", method, redactedURL(rawURL)) + } + if !json.Valid([]byte(trimmed)) { + if isLoginPage(trimmed) { + return sessionStaleError(fmt.Sprintf("%d-byte non-JSON response", len(raw))) + } + return fmt.Errorf("%s %s: decode JSON: invalid JSON response", method, redactedURL(rawURL)) + } + if err := json.Unmarshal(raw, out); err != nil { + return fmt.Errorf("%s %s: decode JSON: %v", method, redactedURL(rawURL), err) + } + return nil +} + +// fetch issues one request and, on a 401/403 with a reauth hook +// installed, retries exactly once against a fresh jar. It is shared by +// the JSON and HTML call paths so both recover from a server-side +// session revocation. +func (c *Client) fetch(method, rawURL string, body any, accept, referer string) (*http.Response, error) { + res, err := c.do(method, rawURL, body, accept, referer) + if err != nil { + return nil, err + } + if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { + if jar, rerr, ok := c.refreshOnce(); ok { + _ = res.Body.Close() + if rerr != nil { + return nil, fmt.Errorf("%s %s: HTTP %d and re-authentication failed: %w", method, redactedURL(rawURL), res.StatusCode, rerr) + } + c.mu.Lock() + c.Jar = jar + c.mu.Unlock() + res, err = c.do(method, rawURL, body, accept, referer) + if err != nil { + return nil, err + } + } + } + return res, nil +} + +func (c *Client) do(method, rawURL string, body any, accept, referer string) (*http.Response, error) { + var bodyReader io.Reader + if body != nil { + buf, err := json.Marshal(body) + if err != nil { + return nil, fmt.Errorf("marshal POST body: %w", err) + } + bodyReader = bytes.NewReader(buf) + } + + extra := map[string]string{ + "Accept": accept, + } + if method == http.MethodPost { + extra["Content-Type"] = "application/json;charset=UTF-8" + extra["Origin"] = c.Base + } + + c.mu.Lock() + jar := c.Jar + c.mu.Unlock() + + res, err := httpclient.Fetch(rawURL, jar, httpclient.FetchOptions{ + Method: method, + Body: bodyString(bodyReader), + Headers: extra, + Referer: referer, + }) + if err != nil { + return nil, fmt.Errorf("%s %s: %s", method, redactedURL(rawURL), sanitizeTransportError(err)) + } + return res, nil +} + +func bodyString(r io.Reader) string { + if r == nil { + return "" + } + b, err := io.ReadAll(r) + if err != nil { + return "" + } + return string(b) +} + +// statusError renders a non-2xx response without the body. PowerSchool +// error pages can echo student identifiers, so only the status line is +// included. +func statusError(method, rawURL string, res *http.Response) error { + return fmt.Errorf("%s %s: HTTP %s", method, redactedURL(rawURL), res.Status) +} + +// sanitizeTransportError strips the URL from a *url.Error so connection +// failures do not leak query parameters such as student_id. +func sanitizeTransportError(err error) string { + var ue *url.Error + if errors.As(err, &ue) { + return ue.Op + ": " + ue.Err.Error() + } + return err.Error() +} + +func isLoginPage(body string) bool { + lower := strings.ToLower(body) + return strings.Contains(lower, "login") || strings.Contains(lower, "sign in") || strings.Contains(lower, "dopcaslogin") +} + +var studentPathRE = regexp.MustCompile(`/student/\d+`) + +// redactedURL strips the query string and any student DCID from a URL +// before it is embedded in an error message. The PS API carries student +// DCIDs in query parameters and in the path for enrollment lookups. +func redactedURL(rawURL string) string { + u, err := url.Parse(rawURL) + if err != nil { + return rawURL + } + u.Path = studentPathRE.ReplaceAllString(u.Path, "/student/") + if u.RawQuery != "" { + return u.Scheme + "://" + u.Host + u.Path + "?" + } + return u.Scheme + "://" + u.Host + u.Path +} + +// GetEnrollments returns the student profile + every active section. +// +// Path: GET /ws/xte/student/{DCID}/enrollments?status=A,I,P&year_id=36 +// +// `status` filters enrollment codes: A=active, I=inactive, P=pre-registered. +// CBE uses A and P; we pass the full set. +func (c *Client) GetEnrollments(dcid int64, yearID int) (*Student, error) { + q := url.Values{} + q.Set("status", "A,I,P") + q.Set("year_id", strconv.Itoa(yearID)) + var out Student + if err := c.Get(fmt.Sprintf("/ws/xte/student/%d/enrollments", dcid), q, &out); err != nil { + return nil, err + } + return &out, nil +} + +// GetYears returns the school-year picker for a student. +// +// Path: GET /ws/xte/standard_grade_section/student/years?student_id={DCID} +func (c *Client) GetYears(dcid int64) ([]Year, error) { + q := url.Values{} + q.Set("student_id", strconv.FormatInt(dcid, 10)) + var out []Year + if err := c.Get("/ws/xte/standard_grade_section/student/years", q, &out); err != nil { + return nil, err + } + return out, nil +} + +// GetStandards returns the standards attached to the given sections. +// +// Path: GET /ws/xte/section/standard?include_comment_only=true&include_nonassignment=true§ion_ids={csv} +func (c *Client) GetStandards(sectionDCIDs []int64) ([]Standard, error) { + q := url.Values{} + q.Set("include_comment_only", "true") + q.Set("include_nonassignment", "true") + ids := make([]string, len(sectionDCIDs)) + for i, s := range sectionDCIDs { + ids[i] = strconv.FormatInt(s, 10) + } + q.Set("section_ids", JoinCSV(ids)) + var out []Standard + if err := c.Get("/ws/xte/section/standard", q, &out); err != nil { + return nil, err + } + return out, nil +} + +// GetStandardGrades returns one row per (student, section, standard) +// for the given scope. We pass `store_codes` in year_ids' place since +// PowerSchool's SPA does the same. +// +// Path: POST /ws/xte/standard_grade_section +// Body: {"section_ids":[…],"student_ids":[…],"year_ids":["36"]} +func (c *Client) GetStandardGrades(dcid int64, sectionDCIDs []int64, yearID int) ([]StandardGrade, error) { + body := map[string]any{ + "section_ids": sectionDCIDs, + "student_ids": []int64{dcid}, + "year_ids": []string{strconv.Itoa(yearID)}, + } + var out []StandardGrade + if err := c.Post("/ws/xte/standard_grade_section", body, &out); err != nil { + return nil, err + } + return out, nil +} + +// GetSchoolCommentLimits returns per-school max-comment-size config. +// +// Path: GET /ws/xte/school/comment +func (c *Client) GetSchoolCommentLimits() ([]SchoolCommentLimit, error) { + var out []SchoolCommentLimit + if err := c.Get("/ws/xte/school/comment", nil, &out); err != nil { + return nil, err + } + return out, nil +} + +// GetStemAssignment returns the per-cell score for one +// (student, section, standard). May return an empty StemAssignmentsResponse +// if no score has been posted. +// +// Path: GET /guardian/studentSectionStemAssignments.json +// +// Note: `studentId` must be the student's `id` field (e.g. the `id` field from the enrollments response), not +// the `dcid` — this is the only PowerSchool endpoint that uses `id`. +func (c *Client) GetStemAssignment(studentID, sectionDCID, standardID int64) (*StemAssignmentsResponse, error) { + q := url.Values{} + q.Set("studentId", strconv.FormatInt(studentID, 10)) + q.Set("sectionDcid", strconv.FormatInt(sectionDCID, 10)) + q.Set("standardId", strconv.FormatInt(standardID, 10)) + var out StemAssignmentsResponse + if err := c.Get("/guardian/studentSectionStemAssignments.json", q, &out); err != nil { + return nil, err + } + return &out, nil +} + +// JoinCSV joins a slice into a comma-separated string. The PS portal +// accepts both `section_ids=1,2,3` and `section_ids[]=1§ion_ids[]=2` +// — the CSV form is shorter and matches the live SPA traffic. +func JoinCSV(s []string) string { + out := "" + for i, v := range s { + if i > 0 { + out += "," + } + out += v + } + return out +} diff --git a/internal/ps/client_test.go b/internal/ps/client_test.go new file mode 100644 index 0000000..25a2427 --- /dev/null +++ b/internal/ps/client_test.go @@ -0,0 +1,438 @@ +package ps_test + +import ( + "encoding/json" + "errors" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "os" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/httpclient" + "github.com/IamCoder18/schooltools/internal/ps" +) + +func TestClientGetEnrollments(t *testing.T) { + requests := make(chan *http.Request, 64) + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/90000001/enrollments", func(w http.ResponseWriter, r *http.Request) { + select { + case requests <- r: + default: + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(loadFixture(t, "enrollments.json"))) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := ps.NewClient(jar) + c.Base = srv.URL + + stu, err := c.GetEnrollments(90000001, 36) + require.NoError(t, err) + assert.Equal(t, "Student, Sample", stu.LastFirst) + assert.Equal(t, int64(90000001), stu.DCID) + assert.Equal(t, 10, stu.GradeLevel) + assert.Equal(t, 13, len(stu.Enrollments)) + first := stu.Enrollments[0] + assert.Equal(t, int64(96000001), first.SectionDCID) + assert.Equal(t, "Mathematics 20-1_cohort IB", first.Section.CourseName) + assert.Equal(t, "Teacher, Sample", first.Section.TeacherName) + + // Last request should have had Origin + Accept headers. + var last *http.Request + for { + select { + case r := <-requests: + last = r + case <-time.After(50 * time.Millisecond): + goto done + } + } +done: + require.NotNil(t, last) + assert.Equal(t, "GET", last.Method) + assert.Equal(t, "A,I,P", last.URL.Query().Get("status")) + assert.Equal(t, "36", last.URL.Query().Get("year_id")) + assert.Contains(t, last.Header.Get("Accept"), "application/json") +} + +func TestClientGetYears(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/standard_grade_section/student/years", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]ps.Year{ + {Abbr: "22-23", YearID: 32}, + {Abbr: "26-27", YearID: 36}, + }) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + years, err := c.GetYears(90000001) + require.NoError(t, err) + require.Len(t, years, 2) + assert.Equal(t, "26-27", years[1].Abbr) + assert.Equal(t, 36, years[1].YearID) +} + +func TestClientGetStandards(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/section/standard", func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, "true", r.URL.Query().Get("include_comment_only")) + assert.Equal(t, "true", r.URL.Query().Get("include_nonassignment")) + assert.Equal(t, "1,2,3", r.URL.Query().Get("section_ids")) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"standardid":1,"name":"x","subjectarea":"Math"},{"standardid":2,"name":"y","subjectarea":"ELA"}]`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + stds, err := c.GetStandards([]int64{1, 2, 3}) + require.NoError(t, err) + require.Len(t, stds, 2) + assert.Equal(t, "Math", stds[0].SubjectArea) +} + +func TestClientPostAddsOrigin(t *testing.T) { + var captured *http.Request + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/standard_grade_section", func(w http.ResponseWriter, r *http.Request) { + captured = r + assert.Equal(t, "POST", r.Method) + assert.Contains(t, r.Header.Get("Origin"), "127.0.0.1") + assert.Equal(t, "application/json;charset=UTF-8", r.Header.Get("Content-Type")) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"standardgradesectionid":1,"studentsdcid":90000001,"standardid":99,"sectionsdcid":1,"storecode":"T1"}]`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + rows, err := c.GetStandardGrades(90000001, []int64{1}, 36) + require.NoError(t, err) + require.Len(t, rows, 1) + assert.Equal(t, int64(99), rows[0].StandardID) + require.NotNil(t, captured) +} + +func TestClientSurfacesNon2xx(t *testing.T) { + // A synthetic identifier stands in for the student number; the point + // is that nothing from the body reaches the error text. + const bodyID = "999999999" + + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte("No access to student_id " + bodyID)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + _, err := c.GetEnrollments(1, 36) + require.Error(t, err) + assert.Contains(t, err.Error(), "HTTP 403") + // The body can carry identifiers, so it is summarised, never inlined. + assert.NotContains(t, err.Error(), "No access to student_id") + assert.NotContains(t, err.Error(), bodyID) + // The query string carries the student DCID and is redacted too. + assert.NotContains(t, err.Error(), "?status=") + assert.NotContains(t, err.Error(), "year_id=") +} + +func TestClientNon2xxOmitsResponseBody(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + _, _ = w.Write([]byte(`{"code":"E_NO_ENROLLMENT","message":"student has no enrollments"}`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + _, err := c.GetEnrollments(1, 36) + require.Error(t, err) + assert.Contains(t, err.Error(), "HTTP 400") + assert.NotContains(t, err.Error(), "student has no enrollments") +} + +func TestClientRejectsBadJSON(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("not json")) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + _, err := c.GetEnrollments(1, 36) + require.Error(t, err) + assert.Contains(t, err.Error(), "decode JSON") +} + +func TestJoinCSV(t *testing.T) { + assert.Equal(t, "", ps.JoinCSV([]string{})) + assert.Equal(t, "a", ps.JoinCSV([]string{"a"})) + assert.Equal(t, "a,b,c", ps.JoinCSV([]string{"a", "b", "c"})) +} + +func TestStemAssignmentPath(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/guardian/studentSectionStemAssignments.json", func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + assert.Equal(t, "92000001", q.Get("studentId")) + assert.Equal(t, "96000001", q.Get("sectionDcid")) + assert.Equal(t, "15400129", q.Get("standardId")) + w.Header().Set("Content-Type", "application/json") + // Real CBE responses are all-string. Match that here. + _, _ = w.Write([]byte(`{"data": [{"sectionDcid":"96000001","standardId":"15400129","assignmentId":"3260086","assignmentName":"Unit 1 MC Exam","category":"OBA Tasks","dueDate":"Sep 22, 2026","actualScoreEntered":"EX1","isCollected":"0","isLate":"0","isMissing":"0","isExempt":"0","isAbsent":"0","isIncomplete":"0"}]}`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + resp, err := c.GetStemAssignment(92000001, 96000001, 15400129) + require.NoError(t, err) + require.Len(t, resp.Data, 1) + assert.Equal(t, "3260086", resp.Data[0].AssignmentID) + assert.Equal(t, "Unit 1 MC Exam", resp.Data[0].AssignmentName) + assert.Equal(t, "EX1", resp.Data[0].ActualScoreEntered) +} + +func TestSchoolCommentLimits(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/school/comment", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"schoolid":816,"schoolsdcid":235,"maxfinalgradecommentsize":2048}]`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + limits, err := c.GetSchoolCommentLimits() + require.NoError(t, err) + require.Len(t, limits, 1) + assert.Equal(t, 2048, limits[0].MaxFinalGradeCommentSize) + assert.Equal(t, 816, limits[0].SchoolID) +} + +// loadFixture reads a JSON fixture from internal/ps/testdata. Falls back +// to an inline empty object if the file is missing so a partial checkout +// still runs. +func loadFixture(t *testing.T, name string) string { + t.Helper() + paths := []string{ + "internal/ps/testdata/" + name, + "testdata/" + name, + "./testdata/" + name, + } + for _, p := range paths { + if b, err := os.ReadFile(p); err == nil { + return string(b) + } + } + return "{}" +} + +// TestClientRefreshesOn401 asserts a server-side session expiry is +// recovered from rather than surfacing as a permanent opaque 403. The +// psaid cookie PowerSchool issues has no Expires, so the local validity +// check cannot see the revocation — the reauth hook is the only path +// back. +func TestClientRefreshesOn401(t *testing.T) { + var calls int32 + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + if atomic.AddInt32(&calls, 1) == 1 { + w.WriteHeader(http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"dcid":1}`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + freshJar := jar + c.SetReauth(func() (*cookiejar.Jar, error) { + return freshJar, nil + }) + + stu, err := c.GetEnrollments(1, 36) + require.NoError(t, err) + assert.Equal(t, int64(1), stu.DCID) + assert.Equal(t, int32(2), atomic.LoadInt32(&calls)) +} + +// TestClientReportsFailureAfterRefresh asserts a 401 that survives a +// successful re-auth still reports the status instead of looping. +func TestClientReportsFailureAfterRefresh(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + c.SetReauth(func() (*cookiejar.Jar, error) { return jar, nil }) + + _, err := c.GetEnrollments(1, 36) + require.Error(t, err) + assert.Contains(t, err.Error(), "HTTP 403") +} + +// TestClientSurfacesReauthFailure asserts a failed refresh reports the +// underlying login problem rather than a bare status code. +func TestClientSurfacesReauthFailure(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + c.SetReauth(func() (*cookiejar.Jar, error) { return nil, errors.New("INVALID_CREDS") }) + + _, err := c.GetEnrollments(1, 36) + require.Error(t, err) + assert.Contains(t, err.Error(), "re-authentication failed") + assert.Contains(t, err.Error(), "INVALID_CREDS") +} + +// TestClientDoesNotRefreshWithoutHook asserts a 403 without a reauth hook +// is reported as-is. +func TestClientDoesNotRefreshWithoutHook(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + _, err := c.GetEnrollments(1, 36) + require.Error(t, err) + assert.Contains(t, err.Error(), "HTTP 403") +} + +// TestClientCollapsesConcurrentRefresh asserts a burst of 401s triggers +// exactly one re-authentication. Without the collapse, `sis assignments` +// fanning out across workers would issue one full login per in-flight +// request against the portal that just rejected the session. +func TestClientCollapsesConcurrentRefresh(t *testing.T) { + const callers = 8 + var refreshed atomic.Bool + var arrived atomic.Int32 + release := make(chan struct{}) + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/1/enrollments", func(w http.ResponseWriter, r *http.Request) { + if !refreshed.Load() { + if arrived.Add(1) == int32(callers) { + close(release) + } + <-release + w.WriteHeader(http.StatusUnauthorized) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"dcid":1}`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + var reauths int32 + c.SetReauth(func() (*cookiejar.Jar, error) { + atomic.AddInt32(&reauths, 1) + refreshed.Store(true) + return jar, nil + }) + + var wg sync.WaitGroup + errs := make([]error, callers) + for i := 0; i < callers; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + _, errs[i] = c.GetEnrollments(1, 36) + }(i) + } + wg.Wait() + + for i, err := range errs { + require.NoError(t, err, "caller %d", i) + } + assert.Equal(t, int32(1), atomic.LoadInt32(&reauths), + "a concurrent burst of 401s must trigger exactly one re-authentication") +} + +func TestClientErrorRedactsStudentDCID(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/student/90000001/enrollments", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, _ := httpclient.NewJar() + c := ps.NewClient(jar) + c.Base = srv.URL + + _, err := c.GetEnrollments(90000001, 36) + require.Error(t, err) + assert.NotContains(t, err.Error(), "90000001") + assert.Contains(t, err.Error(), "student//") +} diff --git a/internal/ps/dashboard.go b/internal/ps/dashboard.go new file mode 100644 index 0000000..d92d9f6 --- /dev/null +++ b/internal/ps/dashboard.go @@ -0,0 +1,82 @@ +package ps + +import ( + "fmt" + "net/http" + "regexp" + "strconv" + "strings" + + stderrors "github.com/IamCoder18/schooltools/internal/errors" + "github.com/IamCoder18/schooltools/internal/httpclient" +) + +func sessionStaleError(detail string) error { + return stderrors.New("PS_SESSION_STALE", + fmt.Sprintf("PowerSchool redirected to the sign-in page (%s); the saved SIS session is likely expired — run 'schooltools sis login'", detail)) +} + +func isSigninRedirect(res *http.Response) bool { + if res == nil || res.StatusCode < 300 || res.StatusCode >= 400 { + return false + } + loc := res.Header.Get("Location") + return strings.Contains(loc, "login") || strings.Contains(loc, "/public/") || strings.Contains(loc, "signin") +} + +// GetDashboardHTML returns the body of the PowerSchool guardian +// dashboard at /guardian/home.html. Used by `sis whoami` to discover +// the student's DCID when SIS_DCID isn't set. +// +// The dashboard is a 59 KB Angular SPA shell — the SPA then issues +// the actual /ws/xte/* data calls. We don't need to wait for those; +// the student record is embedded inside an inline bootstrap script. +func (c *Client) GetDashboardHTML() (string, error) { + rawURL := c.Base + "/guardian/home.html" + res, err := c.fetch(http.MethodGet, rawURL, nil, htmlAccept, c.Base+"/public/") + if err != nil { + return "", err + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + if isSigninRedirect(res) { + _ = res.Body.Close() + return "", sessionStaleError(fmt.Sprintf("HTTP %d", res.StatusCode)) + } + _ = res.Body.Close() + return "", statusError(http.MethodGet, rawURL, res) + } + body, err := httpclient.BodyString(res) + if err != nil { + return "", err + } + _ = res.Body.Close() + return body, nil +} + +var ( + dashboardStudentFRN = regexp.MustCompile(`/guardian/credentials\.html\?frn=00(\d+)`) +) + +// ExtractDCIDFromDashboard walks the dashboard HTML looking for the +// student DCID. Returns 0 when nothing matches — caller should treat +// that as "DCID unknown" and fail loudly rather than silently +// guessing. +// +// PowerSchool's FRN is a packed format ``. +// On CBE the student credentials link is `frn=00<1 digit><8-digit DCID>`, +// so the DCID is the trailing 8 digits of the FRN suffix. +func ExtractDCIDFromDashboard(html string) int64 { + m := dashboardStudentFRN.FindStringSubmatch(html) + if len(m) < 2 { + return 0 + } + frnSuffix := m[1] + if len(frnSuffix) < 8 { + return 0 + } + d, err := strconv.ParseInt(frnSuffix[len(frnSuffix)-8:], 10, 64) + if err != nil { + return 0 + } + return d +} diff --git a/internal/ps/dashboard_test.go b/internal/ps/dashboard_test.go new file mode 100644 index 0000000..6a602cf --- /dev/null +++ b/internal/ps/dashboard_test.go @@ -0,0 +1,58 @@ +package ps + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestExtractDCIDFromDashboard(t *testing.T) { + tests := []struct { + name string + html string + want int64 + }{ + { + name: "CBE dashboard with credentials link", + html: `My Profile`, + want: 90000001, + }, + { + name: "FRN with 2-digit table code (e.g. section-style)", + html: `X`, + want: 90000001, + }, + { + name: "no credentials link", + html: `no link here`, + want: 0, + }, + { + name: "credentials link with non-numeric FRN", + html: `X`, + want: 0, + }, + { + name: "credentials link with too-short FRN (< 8 digits)", + html: `X`, + want: 0, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, ExtractDCIDFromDashboard(tc.html)) + }) + } +} + +func TestExtractDCIDFromDashboardRealFixture(t *testing.T) { + // Read a dashboard body and confirm we extract the correct DCID. + body := strings.Builder{} + body.WriteString(`My Profile`) + body.WriteString(`Home`) + body.WriteString(`Grades`) + body.WriteString(`Attendance`) + got := ExtractDCIDFromDashboard(body.String()) + assert.Equal(t, int64(90000001), got) +} diff --git a/internal/ps/login.go b/internal/ps/login.go new file mode 100644 index 0000000..7a0dc6f --- /dev/null +++ b/internal/ps/login.go @@ -0,0 +1,303 @@ +package ps + +import ( + "fmt" + "net/http" + "net/http/cookiejar" + "net/url" + "strings" + + "github.com/IamCoder18/schooltools/internal/cookies" + stderrors "github.com/IamCoder18/schooltools/internal/errors" + "github.com/IamCoder18/schooltools/internal/httpclient" +) + +// LoginOptions configures a PowerSchool login. +type LoginOptions struct { + Account string + Password string +} + +// Login authenticates against the MyCBE portal and returns the cookies +// that should be persisted to the SIS session file. +// +// Flow: +// 1. GET /public/ to seed a JSESSIONID cookie +// 2. POST /guardian/home.html with form-urlencoded credentials — +// CBE's customised doPCASLogin (in /admin/javascript/md5.js) +// simply copies it into pw/dbpw/ldappassword; no HMAC-MD5 needed. +// 3. If the response is 302, follow it and verify we landed on a +// guardian/ page (not /public/home.html). +// 4. Return the resulting cookie set, which must include psaid. +func Login(opts LoginOptions) ([]cookies.Record, error) { + if opts.Account == "" || opts.Password == "" { + return nil, stderrors.New("MISSING_CREDS", "PowerSchool login requires SIS_STUDENT_NUMBER and SIS_PASSWORD (or CBE_STUDENT_NUMBER + CBE_PASSWORD) to be set in the .env file") + } + + jar, err := httpclient.NewJar() + if err != nil { + return nil, err + } + + if _, err := httpclient.Fetch(BaseURL+PublicPath, jar, httpclient.FetchOptions{ + Referer: BaseURL + PublicPath, + }); err != nil { + return nil, fmt.Errorf("GET %s failed: %w", PublicPath, err) + } + + form := url.Values{} + form.Set("account", opts.Account) + form.Set("pw", opts.Password) + form.Set("dbpw", opts.Password) + form.Set("ldappassword", opts.Password) + form.Set("serviceName", "PS Parent Portal") + form.Set("pcasServerUrl", "/") + form.Set("credentialType", "User Id and Password Credential") + form.Set("translator_username", "") + form.Set("translator_password", "") + form.Set("translator_ldappassword", "") + form.Set("returnUrl", "") + form.Set("serviceTicket", "") + form.Set("translatorpw", "") + + res, err := httpclient.Fetch(BaseURL+LoginPath, jar, httpclient.FetchOptions{ + Method: http.MethodPost, + Referer: BaseURL + PublicPath, + Body: form.Encode(), + Headers: map[string]string{ + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8", + "Origin": BaseURL, + }, + }) + if err != nil { + return nil, fmt.Errorf("POST %s failed: %w", LoginPath, err) + } + + switch res.StatusCode { + case http.StatusOK: + body, _ := httpclient.BodyString(res) + if isInvalidCreds(body) { + return nil, stderrors.New("INVALID_CREDS", "PowerSchool rejected the credentials (Invalid Username or Password!)") + } + if isPublicLoginPage(body) { + return nil, stderrors.New("UNEXPECTED_OK", "login POST returned 200 with the public login form instead of a guardian page; the portal did not accept the session") + } + case http.StatusFound, http.StatusMovedPermanently, http.StatusSeeOther, http.StatusTemporaryRedirect, http.StatusPermanentRedirect: + loc, err := res.Location() + if err != nil { + return nil, fmt.Errorf("302 had no usable Location: %w", err) + } + next, err := safeRedirectTarget(loc) + if err != nil { + return nil, err + } + res2, err := httpclient.Fetch(next, jar, httpclient.FetchOptions{ + Referer: BaseURL + LoginPath, + }) + if err != nil { + return nil, fmt.Errorf("follow-redirect GET %s failed: %w", redirectPath(loc), err) + } + if res2.StatusCode != http.StatusOK { + status := res2.Status + _ = res2.Body.Close() + return nil, stderrors.New("LOGIN_FOLLOW_FAILED", fmt.Sprintf("POST → %s, follow-up returned %d %s", redirectPath(loc), res2.StatusCode, status)) + } + body, _ := httpclient.BodyString(res2) + _ = res2.Body.Close() + if isInvalidCreds(body) { + return nil, stderrors.New("INVALID_CREDS", "PowerSchool rejected the credentials (Invalid Username or Password!)") + } + if isPublicLoginPage(body) { + return nil, stderrors.New("LOGIN_REDIRECTED_TO_LOGIN", fmt.Sprintf("login redirected back to the public login page (%s); the portal did not establish a session", redirectPath(loc))) + } + default: + return nil, stderrors.New("UNEXPECTED_STATUS", fmt.Sprintf("login POST returned %d %s", res.StatusCode, res.Status)) + } + + records := allPSCookies(jar) + if !HasValidSession(records) { + return nil, stderrors.New("NO_PSAID", fmt.Sprintf("PowerSchool login did not issue a psaid cookie — got %d cookies: %v", len(records), cookieNames(records))) + } + return records, nil +} + +// allPSCookies returns every cookie in the jar as Record values. +// Login always runs against a single host, so the jar holds only the +// PS cookies; we don't need to filter by hostname. +func allPSCookies(jar *cookiejar.Jar) []cookies.Record { + if jar == nil { + return nil + } + host := BaseURLHost() + if host == "" { + return nil + } + u, err := url.Parse("https://" + host) + if err != nil { + return nil + } + cs := jar.Cookies(u) + if len(cs) == 0 { + return nil + } + out := make([]cookies.Record, len(cs)) + for i, c := range cs { + out[i] = cookies.FromHTTP(c, host) + } + return out +} + +// BaseURLHost returns just the host part of BaseURL, including any port. +func BaseURLHost() string { + u, err := url.Parse(BaseURL) + if err != nil { + return "" + } + return u.Host +} + +func cookieNames(records []cookies.Record) []string { + out := make([]string, len(records)) + for i, r := range records { + out[i] = r.Name + } + return out +} + +// isInvalidCreds returns true when the response body carries the +// "Invalid Username or Password!" alert banner that PowerSchool renders +// on the public login page for rejected credentials. +func isInvalidCreds(body string) bool { + if body == "" { + return false + } + return strings.Contains(body, "Invalid Username or Password") +} + +// isPublicLoginPage returns true when a response body is the public +// sign-in form rather than an authenticated guardian page. PowerSchool +// re-renders the login form with HTTP 200 for a handful of challenges +// (MFA, account lockout, an exhausted session) that do not carry the +// invalid-creds banner, so a status check alone would treat them as a +// successful login. +func isPublicLoginPage(body string) bool { + if body == "" { + return false + } + lower := strings.ToLower(body) + if strings.Contains(lower, "/guardian/home") { + return false + } + return strings.Contains(lower, "signin") || strings.Contains(lower, "sign in") || + strings.Contains(lower, "public/home") || strings.Contains(lower, "id=\"username\"") +} + +// safeRedirectTarget validates a redirect Location before it is fetched. +// Anything that leaves the portal's own origin is rejected: the login +// flow has just posted a plaintext password, and following a +// server-supplied cross-host URL would send the seeded session cookies +// off-tenant. Only the path component is ever used in error messages, so +// a Location carrying a token in its query string is not persisted to the +// auth log. +// +// The scheme must match the scheme of BaseURL rather than being pinned to +// https, so the same check holds against the production portal and a +// plain-HTTP staging or test host. +func safeRedirectTarget(loc *url.URL) (string, error) { + if loc == nil { + return "", stderrors.New("LOGIN_FOLLOW_FAILED", "redirect had no usable Location") + } + want := "https" + if base, err := url.Parse(BaseURL); err == nil && base.Scheme != "" { + want = base.Scheme + } + if loc.Scheme != "" && loc.Scheme != want { + return "", stderrors.New("LOGIN_FOLLOW_FAILED", fmt.Sprintf("refusing to follow a redirect that downgrades %s to %s", want, loc.Scheme)) + } + if h := loc.Host; h != "" && normalizeHostPort(h, want) != normalizeHostPort(BaseURLHost(), want) { + return "", stderrors.New("LOGIN_FOLLOW_FAILED", fmt.Sprintf("refusing to follow a redirect off the PowerSchool origin (host %q)", h)) + } + return loc.String(), nil +} + +// normalizeHostPort strips an explicit default port for the scheme so +// "sis.cbe.ab.ca:443" and "sis.cbe.ab.ca" compare equal. +func normalizeHostPort(host, scheme string) string { + if host == "" { + return host + } + u, err := url.Parse("//" + host) + if err != nil { + return host + } + port := u.Port() + if port == "" { + return host + } + if (scheme == "http" && port == "80") || (scheme == "https" && port == "443") { + return u.Hostname() + } + return host +} + +// redirectPath renders the safe-to-log portion of a redirect URL: the +// path only, never the query string. +func redirectPath(loc *url.URL) string { + if loc == nil { + return "" + } + if loc.RawQuery != "" { + return loc.Path + "?" + } + return loc.Path +} + +// EnsureSessionOptions configures EnsureSession. +type EnsureSessionOptions struct { + AutoRefresh bool + LoginFn func() ([]cookies.Record, error) +} + +// EnsureSession loads the saved PS cookies, returning a ready jar. If +// the saved session is missing or invalid and AutoRefresh is set, it +// calls LoginFn to re-authenticate and persists the new cookies. +// +// The on-disk file is the single source of truth. +// +// Local expiry is not sufficient on its own: PowerSchool issues psaid +// and JSESSIONID as session cookies with no Expires, so a locally-saved +// session always looks valid even after the server has revoked it. The +// resulting 401/403 is caught by the Client's refresh hook, which calls +// Reauthenticate below. +func EnsureSession(opts EnsureSessionOptions) (*cookiejar.Jar, error) { + saved, err := Load() + if err != nil { + return nil, err + } + if !HasValidSession(saved) { + if !opts.AutoRefresh || opts.LoginFn == nil { + return nil, stderrors.New("NO_SESSION", "no valid PowerSchool session; run 'schooltools sis login' first") + } + if _, err := Reauthenticate(opts.LoginFn); err != nil { + return nil, err + } + } + return LoadJar() +} + +// Reauthenticate runs a fresh login, persists the resulting cookies, and +// returns a jar built from them. It backs both EnsureSession's initial +// login and the Client's 401/403 refresh hook. +func Reauthenticate(loginFn func() ([]cookies.Record, error)) (*cookiejar.Jar, error) { + if loginFn == nil { + return nil, stderrors.New("NO_SESSION", "no saved PowerSchool session; run 'schooltools sis login' first") + } + fresh, err := loginFn() + if err != nil { + return nil, err + } + if err := Save(fresh); err != nil { + return nil, err + } + return LoadJar() +} diff --git a/internal/ps/login_test.go b/internal/ps/login_test.go new file mode 100644 index 0000000..4922da1 --- /dev/null +++ b/internal/ps/login_test.go @@ -0,0 +1,272 @@ +package ps_test + +import ( + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/cookies" + stderrors "github.com/IamCoder18/schooltools/internal/errors" + "github.com/IamCoder18/schooltools/internal/ps" +) + +// TestLoginHappyPath exercises the full login flow against an httptest +// mock that mirrors PowerSchool's: GET /public/ seeds a JSESSIONID, +// POST /guardian/home.html sets psaid + JSESSIONID (rotated) + +// currentSchool + current_locale and 302s to /guardian/home.html. +func TestLoginHappyPath(t *testing.T) { + var postedForm url.Values + var srvLoopback string + mux := http.NewServeMux() + mux.HandleFunc("/public/", func(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{Name: "JSESSIONID", Value: "SEEDJS", Path: "/"}) + _, _ = w.Write([]byte("login page")) + }) + mux.HandleFunc("/guardian/home.html", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + // The 302 follow-up arrives here. Make sure the four + // required cookies are present. + for _, want := range []string{"JSESSIONID", "psaid", "currentSchool", "current_locale"} { + _, err := r.Cookie(want) + assert.NoError(t, err, "missing %s cookie on follow-up GET", want) + } + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("dashboard")) + return + } + // POST: capture the form body and issue the 302. + postedForm = r.URL.Query() + _ = r.ParseForm() + postedForm = r.PostForm + http.SetCookie(w, &http.Cookie{Name: "JSESSIONID", Value: "ROTATEDJS", Path: "/"}) + http.SetCookie(w, &http.Cookie{Name: "psaid", Value: "PSAIDVAL", Path: "/"}) + http.SetCookie(w, &http.Cookie{Name: "currentSchool", Value: "816", Path: "/"}) + http.SetCookie(w, &http.Cookie{Name: "current_locale", Value: "en_US", Path: "/"}) + w.Header().Set("Location", srvLoopback+"/guardian/home.html") + w.WriteHeader(http.StatusFound) + }) + // First GET on home.html (follow-up) — handled by the guard above. + + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + srvLoopback = srv.URL + + // Override BaseURL so the mock's redirect location matches. + prev := ps.BaseURL + ps.BaseURL = srv.URL + t.Cleanup(func() { ps.BaseURL = prev }) + + records, err := ps.Login(ps.LoginOptions{ + Account: "990000001", + Password: "hunter2", + }) + require.NoError(t, err) + require.NotEmpty(t, records) + assert.True(t, ps.HasValidSession(records)) + + // Validate the form body. + require.NotNil(t, postedForm) + assert.Equal(t, "990000001", postedForm.Get("account")) + assert.Equal(t, "hunter2", postedForm.Get("pw")) + assert.Equal(t, "hunter2", postedForm.Get("dbpw")) + assert.Equal(t, "hunter2", postedForm.Get("ldappassword")) + assert.Equal(t, "User Id and Password Credential", postedForm.Get("credentialType")) + + // Validate that the seeded cookie is overwritten by the rotated one. + var hasRotated, hasSeeded bool + for _, r := range records { + if r.Name == "JSESSIONID" && r.Value == "ROTATEDJS" { + hasRotated = true + } + if r.Name == "JSESSIONID" && r.Value == "SEEDJS" { + hasSeeded = true + } + } + assert.True(t, hasRotated, "rotated JSESSIONID missing from saved cookies") + assert.False(t, hasSeeded, "stale seeded JSESSIONID should be replaced by the rotated one") +} + +func TestLoginInvalidCreds(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/public/", func(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{Name: "JSESSIONID", Value: "x", Path: "/"}) + _, _ = w.Write([]byte("ok")) + }) + mux.HandleFunc("/guardian/home.html", func(w http.ResponseWriter, r *http.Request) { + // 200 with "Invalid Username or Password!" inline. + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(``)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + ps.BaseURL = srv.URL + t.Cleanup(func() { ps.BaseURL = "https://sis.cbe.ab.ca" }) + + _, err := ps.Login(ps.LoginOptions{Account: "bad", Password: "wrong"}) + require.Error(t, err) + var authErr *stderrors.AuthError + require.ErrorAs(t, err, &authErr) + assert.Equal(t, "INVALID_CREDS", authErr.Code) +} + +func TestLoginNoPSAID(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/public/", func(w http.ResponseWriter, r *http.Request) { + http.SetCookie(w, &http.Cookie{Name: "JSESSIONID", Value: "x", Path: "/"}) + _, _ = w.Write([]byte("ok")) + }) + mux.HandleFunc("/guardian/home.html", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + w.WriteHeader(http.StatusOK) + return + } + // 302 but only JSESSIONID set, no psaid. + http.SetCookie(w, &http.Cookie{Name: "JSESSIONID", Value: "y", Path: "/"}) + w.Header().Set("Location", "/guardian/home.html") + w.WriteHeader(http.StatusFound) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + ps.BaseURL = srv.URL + t.Cleanup(func() { ps.BaseURL = "https://sis.cbe.ab.ca" }) + + _, err := ps.Login(ps.LoginOptions{Account: "a", Password: "b"}) + require.Error(t, err) + var authErr *stderrors.AuthError + require.ErrorAs(t, err, &authErr) + assert.Equal(t, "NO_PSAID", authErr.Code) +} + +func TestLoginMissingCreds(t *testing.T) { + _, err := ps.Login(ps.LoginOptions{}) + require.Error(t, err) + var authErr *stderrors.AuthError + require.ErrorAs(t, err, &authErr) + assert.Equal(t, "MISSING_CREDS", authErr.Code) +} + +// Test that EnsureSession calls loginFn when the saved cookies are +// invalid/missing and persists whatever loginFn returns. +func TestEnsureSessionReauth(t *testing.T) { + withTempHome(t, func(string) { + calls := 0 + jar, err := ps.EnsureSession(ps.EnsureSessionOptions{ + AutoRefresh: true, + LoginFn: func() ([]cookies.Record, error) { + calls++ + return []cookies.Record{mkCookie("psaid", "fresh", "sis.cbe.ab.ca")}, nil + }, + }) + require.NoError(t, err) + assert.Equal(t, 1, calls) + require.NotNil(t, jar) + + // Saved file should now contain the fresh cookie. + loaded, err := ps.Load() + require.NoError(t, err) + require.Len(t, loaded, 1) + assert.Equal(t, "psaid", loaded[0].Name) + assert.Equal(t, "fresh", loaded[0].Value) + }) +} + +// TestInvalidCredsBannerVariants covers the bodies that must be treated +// as a credential rejection: the banner text itself, and the follow-up +// page PowerSchool serves when the POST is redirected back to the login +// form (MFA, lockout, exhausted session) with no banner. +func TestInvalidCredsBannerVariants(t *testing.T) { + cases := []struct { + name string + body string + code string + }{ + { + name: "explicit invalid banner", + body: ``, + code: "INVALID_CREDS", + }, + { + name: "login form re-rendered after redirect", + body: `
`, + code: "LOGIN_REDIRECTED_TO_LOGIN", + }, + { + name: "guardian page is a success", + body: `HomeGrades`, + code: "", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/public/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("ok")) + }) + mux.HandleFunc("/guardian/home.html", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + _, _ = w.Write([]byte(tc.body)) + return + } + for _, c := range []string{"psaid", "JSESSIONID"} { + http.SetCookie(w, &http.Cookie{Name: c, Value: "v", Path: "/"}) + } + w.Header().Set("Location", "/guardian/home.html") + w.WriteHeader(http.StatusFound) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + prev := ps.BaseURL + ps.BaseURL = srv.URL + t.Cleanup(func() { ps.BaseURL = prev }) + + _, err := ps.Login(ps.LoginOptions{Account: "a", Password: "b"}) + if tc.code == "" { + require.NoError(t, err) + return + } + require.Error(t, err) + var authErr *stderrors.AuthError + require.ErrorAs(t, err, &authErr) + assert.Equal(t, tc.code, authErr.Code) + }) + } +} + +// TestLoginRejectsOffHostRedirect asserts the credential POST will not +// follow a Location pointing at another origin. +func TestLoginRejectsOffHostRedirect(t *testing.T) { + evil := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("off-host redirect was followed to %s", r.URL) + })) + t.Cleanup(evil.Close) + + mux := http.NewServeMux() + mux.HandleFunc("/public/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("ok")) + }) + mux.HandleFunc("/guardian/home.html", func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + _, _ = w.Write([]byte(`Home`)) + return + } + w.Header().Set("Location", evil.URL+"/steal") + w.WriteHeader(http.StatusFound) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + prev := ps.BaseURL + ps.BaseURL = srv.URL + t.Cleanup(func() { ps.BaseURL = prev }) + + _, err := ps.Login(ps.LoginOptions{Account: "a", Password: "b"}) + require.Error(t, err) + var authErr *stderrors.AuthError + require.ErrorAs(t, err, &authErr) + assert.Equal(t, "LOGIN_FOLLOW_FAILED", authErr.Code) + assert.NotContains(t, authErr.Message, "steal") +} diff --git a/internal/ps/marks.go b/internal/ps/marks.go new file mode 100644 index 0000000..4553c17 --- /dev/null +++ b/internal/ps/marks.go @@ -0,0 +1,146 @@ +package ps + +import ( + "fmt" + "html" + "io" + "net/http" + "strings" + + "github.com/PuerkitoBio/goquery" + + stderrors "github.com/IamCoder18/schooltools/internal/errors" + "github.com/IamCoder18/schooltools/internal/httpclient" +) + +// markTerms are the reporting-term columns on /guardian/grades.html, in +// page order. +var markTerms = []string{"T1", "T2", "S1", "T3", "T4", "S2", "Y1"} + +// MarkTerms returns the reporting-term codes in page order, as a copy +// callers may iterate without mutating the package-level table. +func MarkTerms() []string { + return append([]string(nil), markTerms...) +} + +// TermMark is one reporting-term grade for a course. Mark is empty when +// PowerSchool has not posted a grade for that term. +type TermMark struct { + Term string `json:"term"` + Mark string `json:"mark"` +} + +// CourseMark is one row of the guardian "Assignments & Grades" table: +// the course, its teacher, and one mark per reporting term. +type CourseMark struct { + Expression string `json:"expression,omitempty"` + Course string `json:"course"` + Teacher string `json:"teacher,omitempty"` + Marks []TermMark `json:"marks"` +} + +// MarkFor returns the mark for term, or "" when it is not present. +func (c CourseMark) MarkFor(term string) string { + for _, m := range c.Marks { + if m.Term == term { + return m.Mark + } + } + return "" +} + +// GetCourseMarks fetches /guardian/grades.html and returns one row per +// course with a mark for every reporting term. It is the server-rendered +// page behind the portal's "Assignments & Grades" view, so the values +// match what the portal displays. +func (c *Client) GetCourseMarks() ([]CourseMark, error) { + rawURL := c.Base + "/guardian/grades.html" + res, err := c.fetch(http.MethodGet, rawURL, nil, htmlAccept, c.Base+"/guardian/home.html") + if err != nil { + return nil, err + } + if res.StatusCode < 200 || res.StatusCode >= 300 { + if isSigninRedirect(res) { + _ = res.Body.Close() + return nil, sessionStaleError(fmt.Sprintf("HTTP %d", res.StatusCode)) + } + _ = res.Body.Close() + return nil, statusError(http.MethodGet, rawURL, res) + } + defer func() { _ = res.Body.Close() }() + body, err := httpclient.BodyString(res) + if err != nil { + return nil, err + } + marks, err := ParseCourseMarks(strings.NewReader(body)) + if err != nil { + return nil, err + } + if len(marks) == 0 && !strings.Contains(body, "Assignments") { + return nil, stderrors.New("PS_SESSION_STALE", + fmt.Sprintf("PowerSchool returned %d bytes without any course rows; the saved SIS session is likely expired — run 'schooltools sis login'", len(body))) + } + return marks, nil +} + +// ParseCourseMarks extracts the course-mark rows from the guardian +// grades page. The page is a legacy server-rendered HTML table; rows are +// identified by their ccid_ id and cells are read by position because +// the second cell is a hidden attendance placeholder. +func ParseCourseMarks(r io.Reader) ([]CourseMark, error) { + doc, err := goquery.NewDocumentFromReader(r) + if err != nil { + return nil, err + } + var out []CourseMark + doc.Find("tr[id^='ccid_']").Each(func(_ int, row *goquery.Selection) { + cells := row.ChildrenFiltered("td") + if cells.Length() < len(markTerms)+3 { + return + } + course := courseName(cells.Eq(2)) + if course == "" { + return + } + cm := CourseMark{ + Expression: strings.TrimSpace(cells.Eq(0).Text()), + Course: course, + Teacher: teacherName(cells.Eq(2)), + Marks: make([]TermMark, 0, len(markTerms)), + } + for i, term := range markTerms { + cm.Marks = append(cm.Marks, TermMark{ + Term: term, + Mark: normalizeMark(cells.Eq(3 + i).Text()), + }) + } + out = append(out, cm) + }) + return out, nil +} + +// courseName reads the course title from the cell, dropping the teacher +// link, email link, room span, and the
that follows the title. +func courseName(sel *goquery.Selection) string { + clone := sel.Clone() + clone.Find("a, span, img, em, div, br").Remove() + return strings.TrimSpace(clone.Text()) +} + +func teacherName(sel *goquery.Selection) string { + title, ok := sel.Find("a[title^='Details about']").First().Attr("title") + if !ok { + return "" + } + return strings.TrimSpace(strings.TrimPrefix(title, "Details about")) +} + +func normalizeMark(s string) string { + s = html.UnescapeString(s) + s = strings.Join(strings.Fields(s), " ") + switch s { + case "", "-", "Not available": + return "" + } + return s +} diff --git a/internal/ps/marks_test.go b/internal/ps/marks_test.go new file mode 100644 index 0000000..f5956a7 --- /dev/null +++ b/internal/ps/marks_test.go @@ -0,0 +1,147 @@ +package ps + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/httpclient" +) + +const marksPage = ` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ExpCourseT1T2S1T3T4S2Y1AbsencesLates
R1(A)[LastWeekThisWeekDays]Science 10_cohort IB OB 
E Email Graham, Debbie M - Rm: 278 Scienc
 Not available Not available Not available Not available Not available00
R2(A)[LastWeekThisWeekDays]Mathematics 10C Email Hor, Janice-Not availableNot availableNot availableNot availableNot available00
` + +func TestParseCourseMarks(t *testing.T) { + got, err := ParseCourseMarks(strings.NewReader(marksPage)) + require.NoError(t, err) + require.Len(t, got, 2) + + first := got[0] + assert.Equal(t, "R1(A)", first.Expression) + assert.Equal(t, "Science 10_cohort IB OB", first.Course) + assert.Equal(t, "Graham, Debbie M", first.Teacher) + assert.Equal(t, "94", first.MarkFor("T1")) + assert.Equal(t, "", first.MarkFor("T2")) + assert.Equal(t, "97", first.MarkFor("S1")) + assert.Equal(t, "", first.MarkFor("Y1")) + + second := got[1] + assert.Equal(t, "Mathematics 10C", second.Course) + assert.Equal(t, "", second.MarkFor("T1")) + assert.Equal(t, "[ i ]", second.MarkFor("S1")) +} + +func TestMarkForMissingTerm(t *testing.T) { + cm := CourseMark{Course: "X", Marks: []TermMark{{Term: "T1", Mark: "90"}}} + assert.Equal(t, "", cm.MarkFor("S1")) + assert.Equal(t, "90", cm.MarkFor("T1")) +} + +func TestClientGetCourseMarks(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/guardian/grades.html", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + _, _ = w.Write([]byte(marksPage)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := NewClient(jar) + c.Base = srv.URL + + got, err := c.GetCourseMarks() + require.NoError(t, err) + require.Len(t, got, 2) + assert.Equal(t, "94", got[0].MarkFor("T1")) +} + +func TestClientGetCourseMarksNon2xx(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/guardian/grades.html", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := NewClient(jar) + c.Base = srv.URL + + _, err = c.GetCourseMarks() + require.Error(t, err) + assert.Contains(t, err.Error(), "HTTP 403") +} + +func TestClientGetCourseMarksStaleSession(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/guardian/grades.html", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`please sign in`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := NewClient(jar) + c.Base = srv.URL + + _, err = c.GetCourseMarks() + require.Error(t, err) + assert.Contains(t, err.Error(), "likely expired") + assert.Contains(t, err.Error(), "schooltools sis login") +} + +func TestClientGetCourseMarksRedirectToSignin(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/guardian/grades.html", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "/public/", http.StatusFound) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := NewClient(jar) + c.Base = srv.URL + + _, err = c.GetCourseMarks() + require.Error(t, err) + assert.Contains(t, err.Error(), "likely expired") + assert.Contains(t, err.Error(), "schooltools sis login") +} diff --git a/internal/ps/ps.go b/internal/ps/ps.go new file mode 100644 index 0000000..a7a1cca --- /dev/null +++ b/internal/ps/ps.go @@ -0,0 +1,31 @@ +// Package ps is the client for the Calgary Board of Education's +// PowerSchool SIS parent/student portal at https://sis.cbe.ab.ca. +// +// The portal is a modern Angular SPA (PowerSchool 21.06.339 / PDS 31.0.3, +// "Neon" UI) that talks to internal REST endpoints under /ws/xte/…. +// Authentication is session-cookie based: a successful login sets +// JSESSIONID, psaid, currentSchool and current_locale; subsequent API +// calls just need those four cookies plus an Origin header for POSTs. +// +// We do not use the public Pearson REST plugin +// (/pearson-rest/services/PublicPortalServiceJSON) — CBE rotated the +// default digest credentials and that endpoint returns 401. We also do +// not use /ws/v1/ (the OAuth2 SIS REST API) — student accounts don't +// have admin OAuth tokens. +package ps + +// BaseURL is the CBE PowerSchool SIS portal. It's a var (not a const) +// so tests can swap it for an httptest server. +var BaseURL = "https://sis.cbe.ab.ca" + +const ( + jsonAccept = "application/json, text/plain, */*" + htmlAccept = "text/html,application/xhtml+xml" +) + +// LoginPath is the form-post endpoint CBE customised to send plaintext +// passwords (no HMAC-MD5 with pskey, unlike vanilla PowerSchool). +const LoginPath = "/guardian/home.html" + +// PublicPath seeds the JSESSIONID cookie. +const PublicPath = "/public/" diff --git a/internal/ps/scale.go b/internal/ps/scale.go new file mode 100644 index 0000000..cc37181 --- /dev/null +++ b/internal/ps/scale.go @@ -0,0 +1,61 @@ +package ps + +import "strings" + +// Proficiency is one level of the CBE High School Proficiency Scale. +// Percent is the nominal percentage CBE publishes for the level. It is +// nil for levels whose percentage CBE does not publish, so callers can +// distinguish "unknown" from a genuine zero. +type Proficiency struct { + Code string `json:"code"` + Label string `json:"label"` + Percent *int `json:"percent,omitempty"` +} + +func intPtr(v int) *int { return &v } + +var proficiencyScale = []Proficiency{ + {Code: "EX2", Label: "Exemplary 2", Percent: intPtr(100)}, + {Code: "EX1", Label: "Exemplary 1", Percent: intPtr(95)}, + {Code: "PR2", Label: "Proficient 2", Percent: intPtr(85)}, + {Code: "PR1", Label: "Proficient 1", Percent: intPtr(75)}, + {Code: "DV2", Label: "Developing 2"}, + {Code: "DV1", Label: "Developing 1"}, + {Code: "BG2", Label: "Beginning 2"}, + {Code: "BG1", Label: "Beginning 1"}, +} + +// Scale returns a copy of the CBE High School Proficiency Scale, +// ordered from highest to lowest. Callers may mutate the result without +// affecting the package-level table. +func Scale() []Proficiency { + out := make([]Proficiency, len(proficiencyScale)) + for i, p := range proficiencyScale { + out[i] = p + if p.Percent != nil { + v := *p.Percent + out[i].Percent = &v + } + } + return out +} + +// LookupProficiency resolves a PowerSchool score token such as "EX1" to +// its scale entry. Matching is case-insensitive and ignores surrounding +// whitespace. The second result is false for unknown or empty tokens. +func LookupProficiency(code string) (Proficiency, bool) { + needle := strings.ToUpper(strings.TrimSpace(code)) + if needle == "" { + return Proficiency{}, false + } + for _, p := range proficiencyScale { + if p.Code == needle { + if p.Percent != nil { + v := *p.Percent + p.Percent = &v + } + return p, true + } + } + return Proficiency{}, false +} diff --git a/internal/ps/scale_test.go b/internal/ps/scale_test.go new file mode 100644 index 0000000..72f281f --- /dev/null +++ b/internal/ps/scale_test.go @@ -0,0 +1,51 @@ +package ps + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLookupProficiency(t *testing.T) { + p, ok := LookupProficiency("ex1") + require.True(t, ok) + assert.Equal(t, "EX1", p.Code) + assert.Equal(t, "Exemplary 1", p.Label) + require.NotNil(t, p.Percent) + assert.Equal(t, 95, *p.Percent) + + p, ok = LookupProficiency(" PR2 ") + require.True(t, ok) + require.NotNil(t, p.Percent) + assert.Equal(t, 85, *p.Percent) +} + +func TestLookupProficiencyUnknown(t *testing.T) { + for _, code := range []string{"", " ", "ZZ9", "EX"} { + _, ok := LookupProficiency(code) + assert.False(t, ok, code) + } +} + +func TestScaleIsCopy(t *testing.T) { + first := Scale() + require.Len(t, first, 8) + require.NotNil(t, first[0].Percent) + *first[0].Percent = 1 + + second := Scale() + require.NotNil(t, second[0].Percent) + assert.Equal(t, 100, *second[0].Percent) +} + +func TestScalePercentKnownOnlyForPublishedLevels(t *testing.T) { + for _, p := range Scale() { + switch p.Code { + case "EX2", "EX1", "PR2", "PR1": + assert.NotNil(t, p.Percent, p.Code) + default: + assert.Nil(t, p.Percent, p.Code) + } + } +} diff --git a/internal/ps/session.go b/internal/ps/session.go new file mode 100644 index 0000000..23de5db --- /dev/null +++ b/internal/ps/session.go @@ -0,0 +1,181 @@ +package ps + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/cookiejar" + "net/url" + "os" + "path/filepath" + "strings" + "time" + + "github.com/IamCoder18/schooltools/internal/cookies" + "golang.org/x/net/publicsuffix" +) + +// SessionPath returns the canonical SIS session file path. +// +// We deliberately keep this separate from the D2L session.json: the +// PS portal uses a different cookie set (psaid, currentSchool, …) and +// the expiry semantics are independent. +func SessionPath() string { + home, _ := os.UserHomeDir() + return filepath.Join(home, ".config", "schooltools", "sis-session.json") +} + +// Save persists the four PowerSchool session cookies to disk at +// SessionPath(). The file is 0600 and the directory is 0700, matching +// the D2L session.json rules in SECURITY.md. +func Save(records []cookies.Record) error { + fresh := make([]cookies.Record, 0, len(records)) + for _, r := range records { + if !r.IsExpired(time.Now()) { + fresh = append(fresh, r) + } + } + dir := filepath.Dir(SessionPath()) + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + data, err := json.MarshalIndent(fresh, "", " ") + if err != nil { + return err + } + path := SessionPath() + if err := os.WriteFile(path, data, 0o600); err != nil { + return err + } + return os.Chmod(path, 0o600) +} + +// Load returns the persisted PowerSchool cookies. Session cookies +// (Expires == zero) are returned as-is; expired cookies are dropped. +func Load() ([]cookies.Record, error) { + records, err := loadFileRaw() + if err != nil { + return nil, err + } + out := records[:0] + for _, r := range records { + if !r.IsExpired(time.Now()) { + out = append(out, r) + } + } + return out, nil +} + +func loadFileRaw() ([]cookies.Record, error) { + raw, err := os.ReadFile(SessionPath()) + if err != nil { + if os.IsNotExist(err) { + return nil, nil + } + return nil, fmt.Errorf("could not read SIS session file %s: %v", SessionPath(), err) + } + var arr []json.RawMessage + if err := json.Unmarshal(raw, &arr); err != nil { + return nil, fmt.Errorf("SIS session file %s is corrupt (%v); delete it and run 'schooltools sis login' again", SessionPath(), err) + } + records := make([]cookies.Record, 0, len(arr)) + for _, m := range arr { + var r cookies.Record + if err := json.Unmarshal(m, &r); err != nil { + continue + } + records = append(records, r) + } + return records, nil +} + +// Clear removes the saved SIS session file. A missing file is not an +// error. +func Clear() error { + err := os.Remove(SessionPath()) + if err != nil && !os.IsNotExist(err) { + return err + } + return nil +} + +// HasValidSession reports whether the saved cookie set includes a +// non-expired psaid cookie — the PowerSchool equivalent of +// session.HasValidSession() for D2L. JSESSIONID alone is not enough: +// PowerSchool also issues a `psaid` cookie on login and subsequent +// requests will 401/403 without it. +// +// A psaid cookie is considered valid when: +// - its domain ends with "cbe.ab.ca", OR +// - its domain matches BaseURL's host (covers test environments +// against 127.0.0.1 or any other staging host). +func HasValidSession(records []cookies.Record) bool { + if len(records) == 0 { + return false + } + now := time.Now() + baseHost := strings.TrimPrefix(strings.Split(BaseURLHost(), ":")[0], ".") + for _, r := range records { + if r.Name != "psaid" { + continue + } + if r.IsExpired(now) { + continue + } + if r.Domain == "" { + continue + } + d := strings.TrimPrefix(strings.Split(r.Domain, ":")[0], ".") + if endsWithCBEDomain(d) { + return true + } + if baseHost != "" && d == baseHost { + return true + } + } + return false +} + +func endsWithCBEDomain(domain string) bool { + const suffix = "cbe.ab.ca" + if len(domain) < len(suffix) { + return false + } + return domain[len(domain)-len(suffix):] == suffix +} + +// LoadJar builds a fresh cookie jar from the persisted records. The +// cookie domain in PowerSchool responses is host-only (no leading dot) +// so the jar handles per-host storage automatically. +func LoadJar() (*cookiejar.Jar, error) { + jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List}) + if err != nil { + return nil, err + } + records, err := Load() + if err != nil { + return nil, err + } + for _, r := range records { + if r.IsExpired(time.Now()) { + continue + } + host := strings.TrimPrefix(r.Domain, ".") + u := &url.URL{Scheme: "https", Host: host, Path: r.Path} + jar.SetCookies(u, []*http.Cookie{recordToCookie(r)}) + } + return jar, nil +} + +func recordToCookie(r cookies.Record) *http.Cookie { + return &http.Cookie{ + Name: r.Name, + Value: r.Value, + Domain: r.Domain, + Path: r.Path, + Expires: r.Expires, + Secure: r.Secure, + HttpOnly: r.HttpOnly, + SameSite: http.SameSite(r.SameSite), + } +} diff --git a/internal/ps/session_test.go b/internal/ps/session_test.go new file mode 100644 index 0000000..97b7e88 --- /dev/null +++ b/internal/ps/session_test.go @@ -0,0 +1,245 @@ +package ps_test + +import ( + "net/http" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/cookies" + stderrors "github.com/IamCoder18/schooltools/internal/errors" + "github.com/IamCoder18/schooltools/internal/ps" +) + +func withTempHome(t *testing.T, fn func(home string)) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("XDG_CONFIG_HOME", "") + fn(home) +} + +func mkCookie(name, value, domain string, opts ...func(*cookies.Record)) cookies.Record { + r := cookies.Record{ + Name: name, + Value: value, + Domain: domain, + Path: "/", + } + for _, o := range opts { + o(&r) + } + return r +} + +func pastExpires(r *cookies.Record) { r.Expires = time.Now().Add(-time.Minute) } + +func TestSessionPath(t *testing.T) { + withTempHome(t, func(home string) { + got := ps.SessionPath() + want := filepath.Join(home, ".config", "schooltools", "sis-session.json") + assert.Equal(t, want, got) + }) +} + +func TestSaveLoadRoundTrip(t *testing.T) { + withTempHome(t, func(string) { + records := []cookies.Record{ + mkCookie("JSESSIONID", "AAAA", "sis.cbe.ab.ca"), + mkCookie("psaid", "BBBB", "sis.cbe.ab.ca"), + mkCookie("currentSchool", "816", "sis.cbe.ab.ca"), + mkCookie("current_locale", "en_US", "sis.cbe.ab.ca"), + } + require.NoError(t, ps.Save(records)) + got, err := ps.Load() + require.NoError(t, err) + require.Len(t, got, 4) + assert.Equal(t, "AAAA", got[0].Value) + assert.Equal(t, "BBBB", got[1].Value) + assert.Equal(t, "816", got[2].Value) + }) +} + +func TestSaveDropsExpired(t *testing.T) { + withTempHome(t, func(string) { + records := []cookies.Record{ + mkCookie("psaid", "BBBB", "sis.cbe.ab.ca"), + mkCookie("JSESSIONID", "AAAA", "sis.cbe.ab.ca", pastExpires), + } + require.NoError(t, ps.Save(records)) + got, err := ps.Load() + require.NoError(t, err) + // Expired cookie dropped on save. + require.Len(t, got, 1) + assert.Equal(t, "psaid", got[0].Name) + }) +} + +func TestLoadMissing(t *testing.T) { + withTempHome(t, func(string) { + got, err := ps.Load() + require.NoError(t, err) + assert.Empty(t, got) + }) +} + +func TestLoadCorrupt(t *testing.T) { + withTempHome(t, func(string) { + require.NoError(t, os.MkdirAll(filepath.Dir(ps.SessionPath()), 0o700)) + require.NoError(t, os.WriteFile(ps.SessionPath(), []byte("not json"), 0o600)) + _, err := ps.Load() + require.Error(t, err) + assert.Contains(t, err.Error(), "corrupt") + }) +} + +func TestClear(t *testing.T) { + withTempHome(t, func(string) { + require.NoError(t, os.MkdirAll(filepath.Dir(ps.SessionPath()), 0o700)) + require.NoError(t, os.WriteFile(ps.SessionPath(), []byte("[]"), 0o600)) + require.NoError(t, ps.Clear()) + _, err := os.Stat(ps.SessionPath()) + assert.True(t, os.IsNotExist(err)) + // Idempotent. + require.NoError(t, ps.Clear()) + }) +} + +func TestHasValidSession(t *testing.T) { + tests := []struct { + name string + recs []cookies.Record + want bool + }{ + {"empty", nil, false}, + {"only-jsessionid", []cookies.Record{mkCookie("JSESSIONID", "x", "sis.cbe.ab.ca")}, false}, + {"psaid-but-expired", []cookies.Record{mkCookie("psaid", "x", "sis.cbe.ab.ca", pastExpires)}, false}, + {"psaid-but-wrong-domain", []cookies.Record{mkCookie("psaid", "x", "evil.com")}, false}, + {"psaid-good", []cookies.Record{mkCookie("psaid", "x", "sis.cbe.ab.ca")}, true}, + {"psaid-with-leading-dot-domain", []cookies.Record{mkCookie("psaid", "x", ".cbe.ab.ca")}, true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.want, ps.HasValidSession(tc.recs)) + }) + } +} + +func TestLoadJar(t *testing.T) { + withTempHome(t, func(string) { + records := []cookies.Record{ + mkCookie("JSESSIONID", "AAAA", "sis.cbe.ab.ca"), + mkCookie("psaid", "BBBB", "sis.cbe.ab.ca"), + mkCookie("currentSchool", "816", "sis.cbe.ab.ca"), + mkCookie("current_locale", "en_US", "sis.cbe.ab.ca"), + } + require.NoError(t, ps.Save(records)) + jar, err := ps.LoadJar() + require.NoError(t, err) + require.NotNil(t, jar) + // All four cookies should now be in the jar, retrievable for the + // sis.cbe.ab.ca host. + req, _ := http.NewRequest("GET", "https://sis.cbe.ab.ca/ws/xte/test", nil) + var found int + for _, c := range jar.Cookies(req.URL) { + if c.Name == "JSESSIONID" || c.Name == "psaid" || c.Name == "currentSchool" || c.Name == "current_locale" { + found++ + } + } + assert.Equal(t, 4, found) + }) +} + +func TestEnsureSessionReloadsWhenMissing(t *testing.T) { + withTempHome(t, func(string) { + called := false + jar, err := ps.EnsureSession(ps.EnsureSessionOptions{ + AutoRefresh: true, + LoginFn: func() ([]cookies.Record, error) { + called = true + return []cookies.Record{mkCookie("psaid", "x", "sis.cbe.ab.ca")}, nil + }, + }) + require.NoError(t, err) + assert.True(t, called) + require.NotNil(t, jar) + }) +} + +func TestEnsureSessionLoadsWhenValid(t *testing.T) { + withTempHome(t, func(string) { + require.NoError(t, ps.Save([]cookies.Record{ + mkCookie("psaid", "x", "sis.cbe.ab.ca"), + })) + // Verify it's saved properly. + loaded, err := ps.Load() + require.NoError(t, err) + require.Len(t, loaded, 1) + require.True(t, ps.HasValidSession(loaded)) + + called := false + jar, err := ps.EnsureSession(ps.EnsureSessionOptions{ + AutoRefresh: true, + LoginFn: func() ([]cookies.Record, error) { + called = true + return nil, nil + }, + }) + require.NoError(t, err) + assert.False(t, called) + require.NotNil(t, jar) + // sanity: jar returns the loaded cookie + req, _ := http.NewRequest("GET", "https://sis.cbe.ab.ca/test", nil) + var found bool + for _, c := range jar.Cookies(req.URL) { + t.Logf("jar cookie: %s=%s domain=%q", c.Name, c.Value, c.Domain) + if c.Name == "psaid" { + found = true + } + } + assert.True(t, found) + }) +} + +// TestEnsureSessionRespectsAutoRefreshOff asserts `sis logout` is sticky +// when --auto-refresh=false: the missing session is an error rather than +// a silent re-login. +func TestEnsureSessionRespectsAutoRefreshOff(t *testing.T) { + withTempHome(t, func(string) { + called := false + _, err := ps.EnsureSession(ps.EnsureSessionOptions{ + AutoRefresh: false, + LoginFn: func() ([]cookies.Record, error) { + called = true + return []cookies.Record{mkCookie("psaid", "x", "sis.cbe.ab.ca")}, nil + }, + }) + require.Error(t, err) + assert.False(t, called) + var authErr *stderrors.AuthError + require.ErrorAs(t, err, &authErr) + assert.Equal(t, "NO_SESSION", authErr.Code) + }) +} + +// TestReauthenticatePersists asserts the 401 refresh path writes the new +// cookies to disk, not just returns a jar. +func TestReauthenticatePersists(t *testing.T) { + withTempHome(t, func(string) { + jar, err := ps.Reauthenticate(func() ([]cookies.Record, error) { + return []cookies.Record{mkCookie("psaid", "renewed", "sis.cbe.ab.ca")}, nil + }) + require.NoError(t, err) + require.NotNil(t, jar) + + loaded, err := ps.Load() + require.NoError(t, err) + require.Len(t, loaded, 1) + assert.Equal(t, "renewed", loaded[0].Value) + }) +} diff --git a/internal/ps/standard_grades_test.go b/internal/ps/standard_grades_test.go new file mode 100644 index 0000000..f9a4469 --- /dev/null +++ b/internal/ps/standard_grades_test.go @@ -0,0 +1,44 @@ +package ps + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/IamCoder18/schooltools/internal/httpclient" +) + +func TestGetStandardGradesParsesGradeAndPercent(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/ws/xte/standard_grade_section", func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + _ = json.NewDecoder(r.Body).Decode(&body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[ + {"standardgradesectionid":1,"studentsdcid":90000001,"standardid":11,"sectionsdcid":96000001,"storecode":"T1","standardgrade":"EX2","standardpercent":100.0}, + {"standardgradesectionid":2,"studentsdcid":90000001,"standardid":12,"sectionsdcid":96000001,"storecode":"T1"} + ]`)) + }) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + + jar, err := httpclient.NewJar() + require.NoError(t, err) + c := NewClient(jar) + c.Base = srv.URL + + rows, err := c.GetStandardGrades(90000001, []int64{96000001}, 36) + require.NoError(t, err) + require.Len(t, rows, 2) + + assert.Equal(t, "EX2", rows[0].Grade) + require.NotNil(t, rows[0].Percent) + assert.Equal(t, 100.0, *rows[0].Percent) + + assert.Empty(t, rows[1].Grade) + assert.Nil(t, rows[1].Percent) +} diff --git a/internal/ps/testdata/enrollments.json b/internal/ps/testdata/enrollments.json new file mode 100644 index 0000000..caae3c9 --- /dev/null +++ b/internal/ps/testdata/enrollments.json @@ -0,0 +1 @@ +{"_alerts":[],"firstname":"Sample","photoflag":true,"minpref":false,"_name":"students","lastfirst":"Student, Sample","gender":"M","@extensions":"s_stu_crdc_x,s_ab_stu_x,u_students,s_stu_x,activities,c_studentlocator,s_stu_crosslea_x,s_stu_directadmit_x,integration_students,s_stu_ncea_x,s_stu_edfi_x,studentcorefields","lastname":"Student","gradelevel":10,"enrollmentschoolid":94000001,"dcid":90000001,"schoolid":94000001,"studentnumber":"990000001","personid":91000001,"_id":90000001,"id":92000001,"_enrollments":[{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"211","expression":"R1(A)","termabbreviation":"S2","_name":"coursesectioninfo","coursename":"Mathematics 20-1_cohort IB","_termbinwrappers":[{"enddate":"2027-04-11","_name":"termbins","level":2,"parentstorecode":"S2","_childtermbins":[],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"T3","endtimestamp":1807423200000},{"enddate":"2027-06-25","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T3"}],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"S2","endtimestamp":1813903200000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000001,"schoolname":"Sample High School","termname":"Semester 2","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000001,"_name":"teachers"},"_name":"sections"},"coursenum":"MAT2791H","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000001},{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"111","expression":"R1(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Science 10_cohort IB OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000002,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000002,"_name":"teachers"},"_name":"sections"},"coursenum":"SCN1270HOB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000002},{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"121","expression":"R2(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Mathematics 10C_cohort IB OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000003,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000003,"_name":"teachers"},"_name":"sections"},"coursenum":"MAT1791HOB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000003},{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"221","expression":"R2(A)","termabbreviation":"S2","_name":"coursesectioninfo","coursename":"Physics 20_cohort IB","_termbinwrappers":[{"enddate":"2027-04-11","_name":"termbins","level":2,"parentstorecode":"S2","_childtermbins":[],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"T3","endtimestamp":1807423200000},{"enddate":"2027-06-25","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T3"}],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"S2","endtimestamp":1813903200000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000004,"schoolname":"Sample High School","termname":"Semester 2","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000004,"_name":"teachers"},"_name":"sections"},"coursenum":"SCN2797H","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000004},{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"131","expression":"R3(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Business Intro IB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000005,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000005,"_name":"teachers"},"_name":"sections"},"coursenum":"BUS10XXH","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000005},{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"231","expression":"R3(A)","termabbreviation":"S2","_name":"coursesectioninfo","coursename":"French 10 3Y_cohort IB OB","_termbinwrappers":[{"enddate":"2027-04-11","_name":"termbins","level":2,"parentstorecode":"S2","_childtermbins":[],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"T3","endtimestamp":1807423200000},{"enddate":"2027-06-25","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T3"}],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"S2","endtimestamp":1813903200000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000006,"schoolname":"Sample High School","termname":"Semester 2","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000006,"_name":"teachers"},"_name":"sections"},"coursenum":"FSL1093HOB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000006},{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"241","expression":"R4(A)","termabbreviation":"S2","_name":"coursesectioninfo","coursename":"English Language Arts 10-1_cohort IB OB","_termbinwrappers":[{"enddate":"2027-04-11","_name":"termbins","level":2,"parentstorecode":"S2","_childtermbins":[],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"T3","endtimestamp":1807423200000},{"enddate":"2027-06-25","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T3"}],"startdate":"2027-02-01","starttimestamp":1801465200000,"storecode":"S2","endtimestamp":1813903200000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000007,"schoolname":"Sample High School","termname":"Semester 2","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000007,"_name":"teachers"},"_name":"sections"},"coursenum":"ELA1105HOB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000007},{"statuscode":"A","enrolledlate":false,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"141","expression":"R4(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Social Studies 10-1_cohort IB OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000008,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000008,"_name":"teachers"},"_name":"sections"},"coursenum":"SST1771HOB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000008},{"statuscode":"A","enrolledlate":true,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"131IB","expression":"M3(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Challenge & Opportunity OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000009,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000009,"_name":"teachers"},"_name":"sections"},"coursenum":"ENT1010OB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000009},{"statuscode":"A","enrolledlate":true,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"131IB","expression":"M3(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"MAM Project A OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000010,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000010,"_name":"teachers"},"_name":"sections"},"coursenum":"MAM1910OB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000010},{"statuscode":"A","enrolledlate":true,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"131IB","expression":"M3(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Marketing & Management OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000011,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000011,"_name":"teachers"},"_name":"sections"},"coursenum":"MAM1010OB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000011},{"statuscode":"A","enrolledlate":true,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"131IB","expression":"M3(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Spreadsheet 1 OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000012,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000012,"_name":"teachers"},"_name":"sections"},"coursenum":"INF1060OB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000012},{"statuscode":"A","enrolledlate":true,"_name":"enrollment","_coursesectioninfo":{"sectionnum":"13IB","expression":"M3(A)","termabbreviation":"S1","_name":"coursesectioninfo","coursename":"Spreadsheet 2 OB","_termbinwrappers":[{"enddate":"2026-11-01","_name":"termbins","level":2,"parentstorecode":"S1","_childtermbins":[],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"T1","endtimestamp":1793512800000},{"enddate":"2027-01-31","_name":"termbins","level":1,"parentstorecode":"","_childtermbins":[{"_name":"termbins","storecode":"T1"}],"startdate":"2026-08-31","starttimestamp":1788156000000,"storecode":"S1","endtimestamp":1801378800000}],"completed":false,"schoolsdcid":93000001,"coursesdcid":95000013,"schoolname":"Sample High School","termname":"Semester 1","schoolabbreviation":"Sample","_coresection":{"_coreteacher":{"users_dcid":97000013,"_name":"teachers"},"_name":"sections"},"coursenum":"INF2080OB","teachername":"Teacher, Sample","_section":{"_name":"SectionWrapper","gradebooktype":2}},"sectiondcid":96000013}]} \ No newline at end of file diff --git a/internal/ps/types.go b/internal/ps/types.go new file mode 100644 index 0000000..ab820c7 --- /dev/null +++ b/internal/ps/types.go @@ -0,0 +1,137 @@ +package ps + +// Student is the parsed /ws/xte/student/{DCID}/enrollments response. +// The shape is roughly PowerSchool's "students" PowerPlug record. +// +// PowerSchool emits a number of arbitrary record-level fields +// (photoflag, gradelevel, …) and an array of _enrollments where each +// entry mirrors the "enrollment" + "coursesectioninfo" structure. We +// only model the fields this CLI surfaces. +type Student struct { + DCID int64 `json:"dcid"` + ID int64 `json:"id"` + PersonID int64 `json:"personid"` + StudentNo string `json:"studentnumber"` + LastFirst string `json:"lastfirst"` + FirstName string `json:"firstname"` + LastName string `json:"lastname"` + Gender string `json:"gender"` + GradeLevel int `json:"gradelevel"` + SchoolID int `json:"schoolid"` + SchoolDCID int64 `json:"schoolsdcid"` + Enrollments []Enrollment `json:"_enrollments"` +} + +// Enrollment is one active class section for a student, lifted from +// /ws/xte/student/{DCID}/enrollments. +type Enrollment struct { + SectionDCID int64 `json:"sectiondcid"` + Status string `json:"statuscode"` + EnrolledLate bool `json:"enrolledlate"` + Section SectionInfo `json:"_coursesectioninfo"` +} + +// SectionInfo is the joined course+section+teacher+term info that +// PowerSchool returns inline with each enrollment. +type SectionInfo struct { + SectionNum string `json:"sectionnum"` + Expression string `json:"expression"` + CourseName string `json:"coursename"` + CourseNum string `json:"coursenum"` + CourseDCID int64 `json:"coursesdcid"` + SchoolName string `json:"schoolname"` + SchoolDCID int64 `json:"schoolsdcid"` + TermName string `json:"termname"` + TermAbbreviation string `json:"termabbreviation"` + TeacherName string `json:"teachername"` + Completed bool `json:"completed"` +} + +// Year is one academic year for the year picker, e.g. {"abbr":"26-27","yearid":36}. +type Year struct { + Abbr string `json:"abbr"` + YearID int `json:"yearid"` +} + +// Standard is one standards-grading rubric definition attached to a +// section. Returned by /ws/xte/section/standard. +type Standard struct { + ID int64 `json:"standardid"` + Name string `json:"name"` + Identifier string `json:"identifier"` + Description string `json:"description"` + SubjectArea string `json:"subjectarea"` + YearID int `json:"yearid"` + DisplayPos int `json:"displayposition"` + IsExcluded bool `json:"isexcludedfromreports"` + IsAssignmentAllowed bool `json:"isassignmentallowed"` + MaxCommentLength int `json:"maxcommentlength"` + SectionDCID int64 `json:"sectiondcid"` +} + +// StandardGrade is one (student × section × standard) row, returned +// by POST /ws/xte/standard_grade_section. It carries the proficiency +// code (Grade) and the percentage PowerSchool calculated for that +// outcome (Percent), plus per-row flags (isexempt, isincomplete, +// islocked, isenrolled, …). +type StandardGrade struct { + ID int64 `json:"standardgradesectionid"` + StudentDCID int64 `json:"studentsdcid"` + StandardID int64 `json:"standardid"` + SectionDCID int64 `json:"sectionsdcid"` + SchoolDCID int64 `json:"schoolsdcid"` + YearID int `json:"yearid"` + GradeLevel int `json:"gradelevel"` + StoreCode string `json:"storecode"` + SchoolName string `json:"schoolname"` + IsExempt bool `json:"isexempt"` + IsIncomplete bool `json:"isincomplete"` + IsLocked bool `json:"islocked"` + IsEnrolled bool `json:"isenrolled"` + IsMigrated bool `json:"ismigrated"` + IsAdminModified bool `json:"isadminmodified"` + IsReportsRollupExcluded bool `json:"isreportsrollupexcluded"` + IsManuallyOverridden bool `json:"ismanuallyoverridden"` + LastUpdated string `json:"lastupdated"` + Grade string `json:"standardgrade"` + Percent *float64 `json:"standardpercent"` +} + +// SchoolCommentLimit is one entry from /ws/xte/school/comment. We use +// this to surface "max 2048 characters" per school so any future +// grade-comment command can validate. +type SchoolCommentLimit struct { + SchoolID int `json:"schoolid"` + SchoolDCID int64 `json:"schoolsdcid"` + MaxFinalGradeCommentSize int `json:"maxfinalgradecommentsize"` +} + +// StemAssignment is one row from /guardian/studentSectionStemAssignments.json +// (the legacy per-cell assignment + score drill-down). The endpoint +// returns `{"data": [ {…} ]}`. The fields are strings (not numbers) +// because PowerSchool's legacy JSON emits everything as string — +// coerce to int at the consumer. +type StemAssignment struct { + DCID string `json:"dcid"` + StudentID string `json:"studentid"` + SectionDCID string `json:"sectionDcid"` + StandardID string `json:"standardId"` + AssignmentID string `json:"assignmentId"` + AssignmentName string `json:"assignmentName"` + Category string `json:"category"` + DueDate string `json:"dueDate"` + ActualScoreEntered string `json:"actualScoreEntered"` + IsCollected string `json:"isCollected"` + IsLate string `json:"isLate"` + IsMissing string `json:"isMissing"` + IsExempt string `json:"isExempt"` + IsAbsent string `json:"isAbsent"` + IsIncomplete string `json:"isIncomplete"` +} + +// StemAssignmentsResponse is the wrapper around the array of per-cell +// scores. PowerSchool's legacy endpoint returns {"data": [...]} even +// for a single row. +type StemAssignmentsResponse struct { + Data []StemAssignment `json:"data"` +} diff --git a/internal/render/render.go b/internal/render/render.go index b5167a1..19bbbbc 100644 --- a/internal/render/render.go +++ b/internal/render/render.go @@ -432,7 +432,7 @@ func Window(startISO, endISO string) string { end, hasEnd := Parse(endISO) switch { case hasStart && hasEnd: - state := "open" + var state string switch { case now.Before(start): state = Warn("opens " + RelAt(start, now)) diff --git a/internal/table/table.go b/internal/table/table.go index 603e0b8..39f4aa5 100644 --- a/internal/table/table.go +++ b/internal/table/table.go @@ -14,7 +14,7 @@ type ColumnSpec struct { Flex int } -func Fixed(n int) ColumnSpec { return ColumnSpec{Fixed: n} } +func Fixed(n int) ColumnSpec { return ColumnSpec{Fixed: n} } func Flex(min int) ColumnSpec { return ColumnSpec{Flex: min, IsFlex: true} } // Widths computes column widths matching the old cli-table3 semantics: @@ -88,6 +88,7 @@ type Options struct { Rows [][]string Widths []int Style string // "dark" (default for TTY), "light", "notty" (default for pipes) + Wrap bool // wrap cell content to the computed widths instead of truncating } // Render produces a styled table using lipgloss/table directly. This avoids @@ -144,6 +145,9 @@ func Render(opts Options) string { opts.Widths[i] = 20 } } + if opts.Wrap { + t.Wrap(true) + } if total := sumWidths(opts.Widths); total > 0 { t.Width(total) } @@ -170,4 +174,4 @@ func Truncate(s string, width int) string { return s } return s[:width-1] + "…" -} \ No newline at end of file +}