SPB Git

Repository Public

ops_maintenance_test.go 24.2 KB 535 lines go

1package api_test23import (4	"bytes"5	"context"6	"fmt"7	"net/url"8	"strings"9	"testing"10	"time"11	"unicode/utf8"1213	"github.com/google/uuid"1415	mt "clustr.spboucher.ai/mcc/internal/maintenance"16)1718type winBody struct {19	ID        string   `json:"id"`20	Title     string   `json:"title"`21	Status    string   `json:"status"`22	Timezone  string   `json:"timezone"`23	Recur     string   `json:"recurrence"`24	Activated string   `json:"activated_occurrence"`25	Creator   string   `json:"created_by_display_name"`26	Warnings  []string `json:"warnings"`27	SetMode   bool     `json:"set_maintenance_mode"`28	Silence   bool     `json:"silence_alerts"`29}3031func ts(t time.Time) string { return t.UTC().Format(time.RFC3339) }3233func (e *opsEnv) mtick(now time.Time) {34	e.t.Helper()35	if err := (&mt.Scheduler{Pool: e.Pool, Now: func() time.Time { return now }}).Tick(context.Background()); err != nil {36		e.t.Fatal(err)37	}38}3940func TestMaintenanceWindowsAPI(t *testing.T) {41	e := newOpsEnv(t)42	loc, _ := time.LoadLocation("America/Toronto")43	first := time.Date(2027, 3, 7, 1, 0, 0, 0, loc) // Sunday 01:00 local, one week before the spring DST change44	base := map[string]any{"title": "Weekly macOS updates - studios", "category": "update", "starts_at": ts(first), "ends_at": ts(first.Add(2 * time.Hour)),45		"timezone": "America/Toronto", "recurrence": "weekly", "scope": map[string]any{"node_ids": []string{e.node.String()}}}46	with := func(kv ...any) map[string]any {47		m := map[string]any{}48		for k, v := range base {49			m[k] = v50		}51		for i := 0; i+1 < len(kv); i += 2 {52			m[kv[i].(string)] = kv[i+1]53		}54		return m55	}56	// Permissions and validation.57	if r := e.viewer.do("POST", "/maintenance/windows", base); r.Status != 403 {58		t.Fatalf("viewer create: %d", r.Status)59	}60	for name, body := range map[string]map[string]any{61		"end before start":   with("ends_at", ts(first.Add(-time.Hour))),62		"longer than 14 d":   with("ends_at", ts(first.Add(15*24*time.Hour)), "recurrence", "none"),63		"bad time zone":      with("timezone", "Mars/Olympus"),64		"bad recurrence":     with("recurrence", "hourly"),65		"weekly of 8 days":   with("ends_at", ts(first.Add(8*24*time.Hour))),66		"until before start": with("recurrence_until", ts(first.Add(-24*time.Hour))),67		"empty title":        with("title", "  "),68	} {69		if r := e.oper.do("POST", "/maintenance/windows", body); r.Status != 400 {70			t.Errorf("%s: %d %s", name, r.Status, r.Raw)71		}72	}73	if r := e.oper.do("POST", "/maintenance/windows", with("scope", map[string]any{"node_ids": []string{uuid.NewString()}})); r.Status != 404 {74		t.Fatalf("unknown node: %d %s", r.Status, r.Raw)75	}76	if e.count(`select count(*) from maintenance_windows`) != 0 {77		t.Fatal("refused windows were stored")78	}79	var w winBody80	e.oper.must("POST", "/maintenance/windows", base, 201).json(t, &w)81	if w.Status != "scheduled" || w.Recur != "weekly" || !w.SetMode || !w.Silence || w.Creator != "User oscar" || len(w.Warnings) != 0 {82		t.Fatalf("%+v", w)83	}84	// Overlap on the same node: a warning, not an error. Another node: no warning.85	var w2 winBody86	e.oper.must("POST", "/maintenance/windows", with("title", "Disk swap", "recurrence", "none", "starts_at", ts(first.Add(7*24*time.Hour).Add(-30*time.Minute)),87		"ends_at", ts(first.Add(7*24*time.Hour).Add(30*time.Minute))), 201).json(t, &w2)88	if len(w2.Warnings) != 1 || !strings.Contains(w2.Warnings[0], "Weekly macOS updates") || !strings.Contains(w2.Warnings[0], "T-ALPHA") {89		t.Fatalf("overlap warning: %+v", w2.Warnings)90	}91	var w3 winBody92	e.oper.must("POST", "/maintenance/windows", with("title", "Other node", "scope", map[string]any{"node_ids": []string{e.node2.String()}}), 201).json(t, &w3)93	if len(w3.Warnings) != 0 {94		t.Fatalf("unexpected warning: %+v", w3.Warnings)95	}9697	// Range query: occurrences expanded in the window's zone, local time kept across DST (2027-03-14).98	var occ struct {99		Truncated bool100		Items     []struct {101			Start     time.Time `json:"occurrence_start"`102			End       time.Time `json:"occurrence_end"`103			NoteCount int       `json:"note_count"`104			Active    bool      `json:"active"`105			Window    winBody106		}107	}108	q := "/maintenance/windows?from=" + url.QueryEscape(ts(first)) + "&to=" + url.QueryEscape(ts(first.Add(22*24*time.Hour))) + "&node_id=" + e.node.String()109	e.viewer.must("GET", q, nil, 200).json(t, &occ)110	var weekly []time.Time111	for _, it := range occ.Items {112		if it.Window.ID == w.ID {113			weekly = append(weekly, it.Start)114			if it.Start.In(loc).Hour() != 1 || it.End.In(loc).Hour() != 3 {115				t.Errorf("occurrence %s does not keep 01:00-03:00 local", it.Start)116			}117		}118	}119	// 2027-03-07 06:00Z (EST), 03-14 06:00Z (EST, the change is at 02:00 that night), 03-21 05:00Z (EDT), 03-28 05:00Z.120	want := []string{"2027-03-07T06:00:00Z", "2027-03-14T06:00:00Z", "2027-03-21T05:00:00Z", "2027-03-28T05:00:00Z"}121	if len(weekly) != 4 || len(occ.Items) != 5 || occ.Truncated {122		t.Fatalf("occurrences: %v (%d items)", weekly, len(occ.Items))123	}124	for i, s := range want {125		if ts(weekly[i]) != s {126			t.Errorf("occurrence %d = %s, want %s", i, ts(weekly[i]), s)127		}128	}129	for i := 1; i < len(occ.Items); i++ {130		if occ.Items[i].Start.Before(occ.Items[i-1].Start) {131			t.Fatal("occurrences not ordered")132		}133	}134	// Cap at 1000 occurrences.135	e.oper.must("POST", "/maintenance/windows", with("title", "Daily check", "recurrence", "daily", "ends_at", ts(first.Add(time.Hour)), "scope", map[string]any{"node_ids": []string{}},136		"starts_at", ts(first)), 201)137	e.oper.must("POST", "/maintenance/windows", with("title", "Daily check 2", "recurrence", "daily", "ends_at", ts(first.Add(time.Hour)), "scope", map[string]any{"node_ids": []string{}}), 201)138	e.oper.must("POST", "/maintenance/windows", with("title", "Daily check 3", "recurrence", "daily", "ends_at", ts(first.Add(time.Hour)), "scope", map[string]any{"node_ids": []string{}}), 201)139	e.viewer.must("GET", "/maintenance/windows?from="+url.QueryEscape(ts(first))+"&to="+url.QueryEscape(ts(first.Add(399*24*time.Hour))), nil, 200).json(t, &occ)140	if len(occ.Items) != 1000 || !occ.Truncated {141		t.Fatalf("cap: %d truncated=%v", len(occ.Items), occ.Truncated)142	}143	if r := e.viewer.do("GET", "/maintenance/windows?from="+url.QueryEscape(ts(first))+"&to="+url.QueryEscape(ts(first.Add(500*24*time.Hour))), nil); r.Status != 400 {144		t.Fatalf("range above 400 days: %d", r.Status)145	}146	e.Pool.Exec(context.Background(), `delete from maintenance_windows where title like 'Daily check%'`)147148	// Update.149	e.oper.must("PATCH", "/maintenance/windows/"+w.ID, map[string]any{"title": "Weekly updates", "recurrence_until": ts(first.Add(60 * 24 * time.Hour))}, 200).json(t, &w)150	if w.Title != "Weekly updates" {151		t.Fatalf("%+v", w)152	}153	if r := e.oper.do("PATCH", "/maintenance/windows/"+w.ID, map[string]any{"timezone": "Nowhere/None"}); r.Status != 400 {154		t.Fatalf("patch bad zone: %d", r.Status)155	}156157	// Scheduler + complete: the current occurrence ends early and is not re-applied; the series goes on.158	at := first.Add(7 * 24 * time.Hour).Add(10 * time.Minute)159	// (the handlers use the real clock: move the series so that an occurrence is in progress now)160	now := time.Now().UTC()161	e.oper.must("PATCH", "/maintenance/windows/"+w.ID, map[string]any{"starts_at": ts(now.Add(-10 * time.Minute)), "ends_at": ts(now.Add(50 * time.Minute)), "recurrence_until": ts(now.Add(30 * 24 * time.Hour))}, 200)162	_ = at163	e.mtick(now)164	e.viewer.must("GET", "/maintenance/windows/"+w.ID, nil, 200).json(t, &w)165	if w.Status != "in_progress" || w.Activated == "" || e.count(`select count(*) from nodes where id=$1 and maintenance`, e.node) != 1 {166		t.Fatalf("not applied: %+v", w)167	}168	if r := e.oper.do("PATCH", "/maintenance/windows/"+w.ID, map[string]any{"ends_at": ts(now.Add(5 * time.Hour))}); r.Status != 409 {169		t.Fatalf("reschedule while in progress: %d", r.Status)170	}171	e.oper.must("PATCH", "/maintenance/windows/"+w.ID, map[string]any{"description": "running late"}, 200)172	e.viewer.must("GET", "/maintenance/windows", nil, 200).json(t, &occ)173	if len(occ.Items) == 0 || !occ.Items[0].Active {174		t.Fatalf("active occurrence not flagged: %+v", occ.Items)175	}176	e.oper.must("POST", "/maintenance/windows/"+w.ID+"/complete", map[string]any{"note": "All studios updated to 27.1."}, 200).json(t, &w)177	if w.Status != "scheduled" || e.count(`select count(*) from nodes where id=$1 and maintenance`, e.node) != 0 {178		t.Fatalf("complete: %+v", w)179	}180	if e.count(`select count(*) from silences where maintenance_window_id=$1 and ends_at > now()`, w.ID) != 0 {181		t.Fatal("silence not lifted")182	}183	if e.count(`select count(*) from maintenance_notes where window_id=$1 and occurrence is not null and body like 'All studios%'`, w.ID) != 1 {184		t.Fatal("closing note not stored on the occurrence")185	}186	e.mtick(time.Now().UTC())187	if e.count(`select count(*) from nodes where id=$1 and maintenance`, e.node) != 0 {188		t.Fatal("the scheduler re-applied an occurrence completed by hand")189	}190	if r := e.oper.do("POST", "/maintenance/windows/"+w.ID+"/complete", nil); r.Status != 409 {191		t.Fatalf("complete twice: %d %s", r.Status, r.Raw)192	}193	e.mtick(now.Add(7 * 24 * time.Hour).Add(time.Minute)) // next week: applied again194	if e.count(`select count(*) from nodes where id=$1 and maintenance`, e.node) != 1 {195		t.Fatal("next occurrence not applied")196	}197	// Cancel while in progress: effects lifted, window kept.198	e.oper.must("DELETE", "/maintenance/windows/"+w.ID, nil, 204)199	e.viewer.must("GET", "/maintenance/windows/"+w.ID, nil, 200).json(t, &w)200	if w.Status != "cancelled" || e.count(`select count(*) from nodes where id=$1 and maintenance`, e.node) != 0 {201		t.Fatalf("cancel: %+v", w)202	}203	for _, r := range []resp{e.oper.do("DELETE", "/maintenance/windows/"+w.ID, nil), e.oper.do("PATCH", "/maintenance/windows/"+w.ID, map[string]any{"title": "x"})} {204		if r.Status != 409 {205			t.Fatalf("change of a cancelled window: %d", r.Status)206		}207	}208	// A one-off window completed by hand becomes completed.209	var once winBody210	e.oper.must("POST", "/maintenance/windows", with("title", "RAM swap", "recurrence", "none", "starts_at", ts(now.Add(-time.Minute)), "ends_at", ts(now.Add(time.Hour))), 201).json(t, &once)211	e.oper.must("POST", "/maintenance/windows/"+once.ID+"/complete", nil, 200).json(t, &once)212	if once.Status != "completed" {213		t.Fatalf("%+v", once)214	}215	e.mtick(time.Now().UTC())216	if e.count(`select count(*) from nodes where id=$1 and maintenance`, e.node) != 0 {217		t.Fatal("completed one-off window applied")218	}219	for _, a := range []string{"create", "update", "complete", "cancel"} {220		if e.count(`select count(*) from audit_log where action=$1 and outcome='success'`, "maintenance.window."+a) == 0 {221			t.Errorf("maintenance.window.%s not audited", a)222		}223	}224	if e.count(`select count(*) from events_outbox where topic='maintenance.changed'`) < 8 {225		t.Fatal("maintenance.changed events missing")226	}227}228229func TestMaintenanceNotesAPI(t *testing.T) {230	e := newOpsEnv(t)231	type note struct {232		ID       string `json:"id"`233		Body     string `json:"body"`234		Pinned   bool   `json:"pinned"`235		Author   string `json:"author_display_name"`236		Node     string `json:"node_alias"`237		EditedAt string `json:"edited_at"`238		WindowID string `json:"window_id"`239	}240	now := time.Now().UTC().Truncate(time.Second)241	var w winBody242	e.oper.must("POST", "/maintenance/windows", map[string]any{"title": "Daily backup check", "starts_at": ts(now.Add(time.Hour)), "ends_at": ts(now.Add(2 * time.Hour)),243		"timezone": "UTC", "recurrence": "daily", "scope": map[string]any{"node_ids": []string{e.node.String()}}}, 201).json(t, &w)244	// Validation and permissions.245	if r := e.viewer.do("POST", "/maintenance/notes", map[string]any{"node_id": e.node, "body": "x"}); r.Status != 403 {246		t.Fatalf("viewer note: %d", r.Status)247	}248	for name, body := range map[string]map[string]any{249		"no anchor":                 {"body": "x"},250		"empty body":                {"node_id": e.node, "body": "   "},251		"occurrence without window": {"node_id": e.node, "occurrence": ts(now), "body": "x"},252		"not an occurrence":         {"window_id": w.ID, "occurrence": ts(now.Add(90 * time.Minute)), "body": "x"},253		"too long":                  {"node_id": e.node, "body": strings.Repeat("x", 20001)},254	} {255		if r := e.oper.do("POST", "/maintenance/notes", body); r.Status != 400 {256			t.Errorf("%s: %d %s", name, r.Status, r.Raw)257		}258	}259	if r := e.oper.do("POST", "/maintenance/notes", map[string]any{"node_id": uuid.New(), "body": "x"}); r.Status != 404 {260		t.Fatalf("unknown node: %d", r.Status)261	}262	if r := e.oper.do("POST", "/maintenance/notes", map[string]any{"window_id": uuid.New(), "body": "x"}); r.Status != 404 {263		t.Fatalf("unknown window: %d", r.Status)264	}265	var n1, n2, n3, n4 note266	e.oper.must("POST", "/maintenance/notes", map[string]any{"node_id": e.node, "body": "Internal disk at 3 GB free out of 926; cleanup planned on Sunday.", "pinned": true}, 201).json(t, &n1)267	e.admin.must("POST", "/maintenance/notes", map[string]any{"window_id": w.ID, "occurrence": ts(now.Add(25 * time.Hour)), "body": "Second occurrence: backup of 100% of volumes verified_ok."}, 201).json(t, &n2)268	e.oper.must("POST", "/maintenance/notes", map[string]any{"window_id": w.ID, "node_id": e.node2, "body": "Fan noise on T-BETA"}, 201).json(t, &n3)269	e.oper.must("POST", "/maintenance/notes", map[string]any{"node_id": e.node, "body": "Replaced the UPS battery."}, 201).json(t, &n4)270	if n1.Author != "User oscar" || !n1.Pinned || n1.Node != "T-ALPHA" || n2.WindowID != w.ID || n1.EditedAt != "" {271		t.Fatalf("%+v %+v", n1, n2)272	}273	list := func(c *client, q string) []note {274		var l struct {275			Items      []note276			NextCursor string `json:"next_cursor"`277		}278		c.must("GET", "/maintenance/notes"+q, nil, 200).json(t, &l)279		return l.Items280	}281	// Pinned first, then most recent first.282	all := list(e.viewer, "")283	if len(all) != 4 || all[0].ID != n1.ID || all[1].ID != n4.ID || all[3].ID != n2.ID {284		t.Fatalf("order: %+v", all)285	}286	if got := list(e.viewer, "?node_id="+e.node.String()); len(got) != 2 {287		t.Fatalf("by node: %d", len(got))288	}289	if got := list(e.viewer, "?window_id="+w.ID); len(got) != 2 {290		t.Fatalf("by window: %d", len(got))291	}292	if got := list(e.viewer, "?window_id="+w.ID+"&occurrence="+url.QueryEscape(ts(now.Add(25*time.Hour)))); len(got) != 1 || got[0].ID != n2.ID {293		t.Fatalf("by occurrence: %+v", got)294	}295	// Search: case-insensitive substring; wildcards and quotes are literal text, never SQL.296	for q, want := range map[string]int{"ups BATTERY": 1, "disk": 1, "100%": 1, "%": 1, "verified_ok": 1, "verifiedXok": 0, "_": 1, "' or 1=1 --": 0, "nothing-like-this": 0} {297		if got := list(e.viewer, "?q="+url.QueryEscape(q)); len(got) != want {298			t.Errorf("q=%q: %d results, want %d", q, len(got), want)299		}300	}301	if r := e.viewer.do("GET", "/maintenance/notes?q="+strings.Repeat("a", 121), nil); r.Status != 400 {302		t.Fatalf("q too long: %d", r.Status)303	}304	// Pagination follows the same order.305	var page struct {306		Items      []note307		NextCursor string `json:"next_cursor"`308	}309	e.viewer.must("GET", "/maintenance/notes?limit=3", nil, 200).json(t, &page)310	if len(page.Items) != 3 || page.NextCursor == "" {311		t.Fatalf("page 1: %+v", page)312	}313	cursor := page.NextCursor314	page.NextCursor = ""315	e.viewer.must("GET", "/maintenance/notes?limit=3&cursor="+url.QueryEscape(cursor), nil, 200).json(t, &page)316	if len(page.Items) != 1 || page.Items[0].ID != n2.ID || page.NextCursor != "" {317		t.Fatalf("page 2: %+v", page)318	}319	if r := e.viewer.do("GET", "/maintenance/notes?cursor=garbage", nil); r.Status != 400 {320		t.Fatalf("bad cursor: %d", r.Status)321	}322	// The calendar counts notes per occurrence.323	var occ struct {324		Items []struct {325			Start     time.Time `json:"occurrence_start"`326			NoteCount int       `json:"note_count"`327		}328	}329	e.viewer.must("GET", "/maintenance/windows?from="+url.QueryEscape(ts(now))+"&to="+url.QueryEscape(ts(now.Add(49*time.Hour))), nil, 200).json(t, &occ)330	if len(occ.Items) != 2 || occ.Items[0].NoteCount != 0 || occ.Items[1].NoteCount != 1 {331		t.Fatalf("note counts: %+v", occ.Items)332	}333334	// Editing: only the author changes the text; anyone with maintenance.write pins.335	if r := e.admin.do("PATCH", "/maintenance/notes/"+n1.ID, map[string]any{"body": "rewritten by someone else"}); r.Status != 403 {336		t.Fatalf("edit of another author's note: %d", r.Status)337	}338	if r := e.root.do("PATCH", "/maintenance/notes/"+n1.ID, map[string]any{"body": "even the owner does not rewrite others"}); r.Status != 403 {339		t.Fatalf("owner edit of another author's note: %d", r.Status)340	}341	if r := e.viewer.do("PATCH", "/maintenance/notes/"+n1.ID, map[string]any{"pinned": false}); r.Status != 403 {342		t.Fatalf("viewer pin: %d", r.Status)343	}344	var got note345	e.admin.must("PATCH", "/maintenance/notes/"+n1.ID, map[string]any{"pinned": false}, 200).json(t, &got)346	if got.Pinned || got.EditedAt != "" || got.Body != n1.Body {347		t.Fatalf("pin by another user: %+v", got)348	}349	e.oper.must("PATCH", "/maintenance/notes/"+n1.ID, map[string]any{"body": "Internal disk cleaned: 210 GB free."}, 200).json(t, &got)350	if got.Body != "Internal disk cleaned: 210 GB free." || got.EditedAt == "" {351		t.Fatalf("author edit: %+v", got)352	}353	if e.count(`select count(*) from audit_log where action='maintenance.note.update' and outcome='denied'`) != 2 {354		t.Fatal("refused edits not audited")355	}356	// Deleting: the author, or a holder of alerts.manage; soft delete.357	if r := e.oper.do("DELETE", "/maintenance/notes/"+n2.ID, nil); r.Status != 403 { // n2 was written by alice358		t.Fatalf("operator delete of another author's note: %d", r.Status)359	}360	e.oper.must("DELETE", "/maintenance/notes/"+n4.ID, nil, 204)  // own note361	e.admin.must("DELETE", "/maintenance/notes/"+n3.ID, nil, 204) // admin holds alerts.manage362	if r := e.admin.do("DELETE", "/maintenance/notes/"+n3.ID, nil); r.Status != 404 {363		t.Fatalf("delete twice: %d", r.Status)364	}365	if r := e.oper.do("PATCH", "/maintenance/notes/"+n4.ID, map[string]any{"body": "zombie"}); r.Status != 404 {366		t.Fatalf("edit of a deleted note: %d", r.Status)367	}368	if left := list(e.viewer, ""); len(left) != 2 {369		t.Fatalf("%d notes listed after deletion", len(left))370	}371	if list(e.viewer, "?q=UPS") != nil && len(list(e.viewer, "?q=UPS")) != 0 {372		t.Fatal("a deleted note is still found by search")373	}374	if e.count(`select count(*) from maintenance_notes`) != 4 || e.count(`select count(*) from maintenance_notes where deleted_at is not null`) != 2 {375		t.Fatal("notes must be soft-deleted, not removed")376	}377	if e.count(`select count(*) from audit_log where action like 'maintenance.note.%' and outcome='success'`) != 8 { // 4 create, 2 update, 2 delete378		t.Fatalf("note audit entries: %d", e.count(`select count(*) from audit_log where action like 'maintenance.note.%' and outcome='success'`))379	}380	if e.count(`select count(*) from audit_log where action like 'maintenance.note.%' and params::text like '%UPS battery%'`) != 0 {381		t.Fatal("note text copied into the audit log")382	}383	if e.count(`select count(*) from events_outbox where topic='maintenance.changed' and payload->>'change' like 'note_%'`) != 8 {384		t.Fatal("note events missing")385	}386}387388// checkICS is a strict line-level check of an iCalendar document: CRLF only,389// physical lines of at most 75 octets, valid UTF-8 after unfolding, balanced390// components, and the required properties of each VEVENT.391func checkICS(t *testing.T, data []byte) (events []map[string]string) {392	t.Helper()393	if !bytes.HasSuffix(data, []byte("\r\n")) {394		t.Fatal("ICS must end with CRLF")395	}396	raw := strings.Split(strings.TrimSuffix(string(data), "\r\n"), "\r\n")397	var lines []string398	for i, l := range raw {399		if strings.ContainsAny(l, "\r\n") {400			t.Fatalf("line %d contains a bare CR or LF", i+1)401		}402		if len(l) > 75 {403			t.Fatalf("line %d is %d octets long", i+1, len(l))404		}405		if strings.HasPrefix(l, " ") || strings.HasPrefix(l, "\t") {406			if len(lines) == 0 {407				t.Fatal("continuation without a first line")408			}409			lines[len(lines)-1] += l[1:]410			continue411		}412		lines = append(lines, l)413	}414	var stack []string415	var cur map[string]string416	tzids := map[string]bool{}417	for i, l := range lines {418		if !utf8.ValidString(l) {419			t.Fatalf("logical line %d is not valid UTF-8 (a fold split a character)", i+1)420		}421		name, value, ok := strings.Cut(l, ":")422		if !ok || name == "" {423			t.Fatalf("logical line %d has no property name: %q", i+1, l)424		}425		prop, _, _ := strings.Cut(name, ";")426		switch prop {427		case "BEGIN":428			stack = append(stack, value)429			if value == "VEVENT" {430				cur = map[string]string{}431			}432		case "END":433			if len(stack) == 0 || stack[len(stack)-1] != value {434				t.Fatalf("END:%s does not match the open component", value)435			}436			stack = stack[:len(stack)-1]437			if value == "VEVENT" {438				for _, req := range []string{"UID", "DTSTAMP", "DTSTART", "DTEND", "SUMMARY"} {439					if cur[req] == "" {440						t.Fatalf("VEVENT without %s", req)441					}442				}443				events = append(events, cur)444				cur = nil445			}446		default:447			if len(stack) > 0 && stack[len(stack)-1] == "VTIMEZONE" && prop == "TZID" {448				tzids[value] = true449			}450			if cur != nil {451				cur[prop] = value452				if strings.Contains(name, "TZID=") {453					cur[prop+";TZID"] = name[strings.Index(name, "TZID=")+5:]454				}455			}456		}457	}458	if len(stack) != 0 || lines[0] != "BEGIN:VCALENDAR" || lines[len(lines)-1] != "END:VCALENDAR" {459		t.Fatal("unbalanced calendar")460	}461	if !strings.Contains(string(data), "\r\nVERSION:2.0\r\n") || !strings.Contains(string(data), "\r\nPRODID:") {462		t.Fatal("VERSION or PRODID missing")463	}464	for _, ev := range events {465		if z := ev["DTSTART;TZID"]; z != "" && !tzids[z] {466			t.Fatalf("TZID %s used without a VTIMEZONE", z)467		}468	}469	return events470}471472func TestMaintenanceCalendarICS(t *testing.T) {473	e := newOpsEnv(t)474	now := time.Now().UTC().Truncate(time.Second)475	mk := func(title, desc, rec string, start time.Time) winBody {476		var w winBody477		e.oper.must("POST", "/maintenance/windows", map[string]any{"title": title, "description": desc, "starts_at": ts(start), "ends_at": ts(start.Add(time.Hour)),478			"timezone": "America/Toronto", "recurrence": rec, "scope": map[string]any{"node_ids": []string{e.node.String()}}}, 201).json(t, &w)479		return w480	}481	long := "Mise à jour mensuelle des studios — vérification, redémarrage; sauvegarde, contrôle 🙂 " + strings.Repeat("é", 40)482	w1 := mk(long, "Étapes:\n1) sauvegarde, 2) mise à jour; 3) contrôle \\ fin", "monthly", time.Date(2027, 1, 31, 15, 0, 0, 0, time.UTC))483	w2 := mk("One-off", "", "none", now.Add(48*time.Hour))484	w3 := mk("Cancelled weekly", "", "weekly", now.Add(72*time.Hour))485	e.oper.must("DELETE", "/maintenance/windows/"+w3.ID, nil, 204)486	mk("Far away", "", "none", now.Add(600*24*time.Hour)) // outside the default range487488	if r := e.browser().do("GET", "/maintenance/calendar.ics", nil); r.Status != 401 {489		t.Fatalf("anonymous calendar: %d", r.Status)490	}491	r := e.viewer.must("GET", "/maintenance/calendar.ics", nil, 200)492	if ct := r.Header.Get("Content-Type"); !strings.HasPrefix(ct, "text/calendar") {493		t.Fatalf("content type %q", ct)494	}495	if cd := r.Header.Get("Content-Disposition"); cd != `attachment; filename="mcc-maintenance.ics"` {496		t.Fatalf("content disposition %q", cd)497	}498	evs := checkICS(t, r.Raw)499	if len(evs) != 3 {500		t.Fatalf("%d events, want 3", len(evs))501	}502	by := map[string]map[string]string{}503	for _, ev := range evs {504		by[ev["UID"]] = ev505	}506	ev1, ev2, ev3 := by[w1.ID+"@localhost"], by[w2.ID+"@localhost"], by[w3.ID+"@localhost"]507	if ev1 == nil || ev2 == nil || ev3 == nil {508		t.Fatalf("stable UIDs missing: %v", by)509	}510	// Monthly on the 31st: last day of shorter months, expressed in the RRULE; local time with TZID.511	if ev1["RRULE"] != "FREQ=MONTHLY;BYMONTHDAY=-1" || ev1["DTSTART;TZID"] != "America/Toronto" || ev1["DTSTART"] != "20270131T100000" {512		t.Fatalf("monthly event: %+v", ev1)513	}514	if !strings.Contains(ev1["SUMMARY"], `redémarrage\; sauvegarde\, contrôle 🙂`) || !strings.Contains(ev1["DESCRIPTION"], `Étapes:\n1) sauvegarde\, 2) mise à jour\; 3) contrôle \\ fin`) {515		t.Fatalf("escaping: %q / %q", ev1["SUMMARY"], ev1["DESCRIPTION"])516	}517	if ev2["RRULE"] != "" || !strings.HasSuffix(ev2["DTSTART"], "Z") || ev2["STATUS"] != "CONFIRMED" {518		t.Fatalf("one-off event: %+v", ev2)519	}520	if ev3["STATUS"] != "CANCELLED" || ev3["RRULE"] != "FREQ=WEEKLY" {521		t.Fatalf("cancelled event: %+v", ev3)522	}523	// Stable across calls; node filter; range validation.524	r2 := e.viewer.must("GET", "/maintenance/calendar.ics", nil, 200)525	if fmt.Sprint(len(checkICS(t, r2.Raw))) != "3" {526		t.Fatal("second export differs")527	}528	if n := len(checkICS(t, e.viewer.must("GET", "/maintenance/calendar.ics?node_id="+e.node2.String(), nil, 200).Raw)); n != 0 {529		t.Fatalf("node filter: %d events", n)530	}531	if r := e.viewer.do("GET", "/maintenance/calendar.ics?from=2027-01-01T00:00:00Z&to=2026-01-01T00:00:00Z", nil); r.Status != 400 {532		t.Fatalf("inverted range: %d", r.Status)533	}534}535
Files main
Menu

Theme