diff --git a/cmd/clawctl-hub/operator_admin_scope_test.go b/cmd/clawctl-hub/operator_admin_scope_test.go index 426db45f..68eab192 100644 --- a/cmd/clawctl-hub/operator_admin_scope_test.go +++ b/cmd/clawctl-hub/operator_admin_scope_test.go @@ -27,7 +27,7 @@ func TestOperatorAdminScopeCentralAuthorization(t *testing.T) { allowed = append(allowed, route) } } - if len(allowed) != 12 { + if len(allowed) != 13 { t.Fatalf("operator-admin routes=%d", len(allowed)) } forbidden := []string{ @@ -91,7 +91,7 @@ func TestOperatorAdminScheduleAPI(t *testing.T) { if err != nil { t.Fatal(err) } - routes := []string{"POST /v1/operator/schedules/{operation}/{phase}", "POST /v1/operator/schedules/{id}/run-now"} + routes := []string{"POST /v1/operator/schedules/{operation}/{phase}", "POST /v1/operator/schedules/{id}/run-now", "POST /v1/operator/schedule-jobs/{id}/cancel"} _, secret, err := f.store.CreateServiceToken(store.ServiceToken{Name: "scheduler", Scope: "operator-admin", ExpiresAt: time.Now().Add(time.Hour), Allowlist: routes}, actor.AccountID) if err != nil { t.Fatal(err) @@ -146,4 +146,32 @@ func TestOperatorAdminScheduleAPI(t *testing.T) { if run.Code != 200 { t.Fatalf("run %d %s", run.Code, run.Body.String()) } + var ran store.ScheduleRunNowResponse + if err := json.Unmarshal(run.Body.Bytes(), &ran); err != nil || len(ran.JobIDs) != 1 { + t.Fatalf("run receipt %s", run.Body.String()) + } + if rec := call("/v1/operator/schedule-jobs/"+ran.JobIDs[0]+"/cancel", store.ScheduleJobCancelRequest{}, "cancel-empty"); rec.Code != 400 { + t.Fatalf("cancel without reason %d %s", rec.Code, rec.Body.String()) + } + if rec := call("/v1/operator/schedule-jobs/"+ran.JobIDs[0]+"/cancel", store.ScheduleJobCancelRequest{Reason: "machine offline"}, ""); rec.Code == 200 { + t.Fatal("cancel without idempotency key succeeded") + } + cancel := call("/v1/operator/schedule-jobs/"+ran.JobIDs[0]+"/cancel", store.ScheduleJobCancelRequest{Reason: "machine offline"}, "cancel") + if cancel.Code != 200 { + t.Fatalf("cancel %d %s", cancel.Code, cancel.Body.String()) + } + var cancelled store.ScheduleJobCancelResponse + if err := json.Unmarshal(cancel.Body.Bytes(), &cancelled); err != nil || cancelled.State != "rejected" || cancelled.ScheduleID != v.ID || cancelled.Replayed { + t.Fatalf("cancel receipt %s", cancel.Body.String()) + } + again := call("/v1/operator/schedule-jobs/"+ran.JobIDs[0]+"/cancel", store.ScheduleJobCancelRequest{Reason: "machine offline"}, "cancel") + if again.Code != 200 || again.Header().Get("Idempotency-Replayed") != "true" { + t.Fatalf("cancel replay %d %s", again.Code, again.Body.String()) + } + if rec := call("/v1/operator/schedule-jobs/"+ran.JobIDs[0]+"/cancel", store.ScheduleJobCancelRequest{Reason: "machine offline"}, "cancel-twice"); rec.Code != 412 || !strings.Contains(rec.Body.String(), "PRECONDITION_FAILED") { + t.Fatalf("cancel of a finished job %d %s", rec.Code, rec.Body.String()) + } + if rec := call("/v1/operator/schedule-jobs/no-such-job/cancel", store.ScheduleJobCancelRequest{Reason: "machine offline"}, "cancel-missing"); rec.Code != 404 { + t.Fatalf("cancel missing %d %s", rec.Code, rec.Body.String()) + } } diff --git a/cmd/clawctl-hub/operator_api.go b/cmd/clawctl-hub/operator_api.go index 30e2dc41..879d4a6b 100644 --- a/cmd/clawctl-hub/operator_api.go +++ b/cmd/clawctl-hub/operator_api.go @@ -314,12 +314,13 @@ func (h *hub) operatorRoutes(mux *http.ServeMux) []string { } { mux.HandleFunc(patterns[diskClean+i], handler) } - patterns = append(patterns, "GET /v1/operator/schedules", "GET /v1/operator/schedules/{id}", "POST /v1/operator/schedules/{operation}/{phase}", "POST /v1/operator/schedules/{id}/run-now", "GET /v1/operator/script-catalog", "POST /v1/operator/script-runs/preview", "POST /v1/operator/script-runs") + patterns = append(patterns, "GET /v1/operator/schedules", "GET /v1/operator/schedules/{id}", "POST /v1/operator/schedules/{operation}/{phase}", "POST /v1/operator/schedules/{id}/run-now", "POST /v1/operator/schedule-jobs/{id}/cancel", "GET /v1/operator/script-catalog", "POST /v1/operator/script-runs/preview", "POST /v1/operator/script-runs") mux.HandleFunc("GET /v1/operator/script-catalog", h.handleScriptCatalog) mux.HandleFunc("GET /v1/operator/schedules", h.handleScheduleList) mux.HandleFunc("GET /v1/operator/schedules/{id}", h.handleScheduleGet) mux.HandleFunc("POST /v1/operator/schedules/{operation}/{phase}", h.handleScheduleManage) mux.HandleFunc("POST /v1/operator/schedules/{id}/run-now", h.handleScheduleRunNow) + mux.HandleFunc("POST /v1/operator/schedule-jobs/{id}/cancel", h.handleScheduleJobCancel) mux.HandleFunc("POST /v1/operator/script-runs/preview", h.handleScriptPreview) mux.HandleFunc("POST /v1/operator/script-runs", h.handleScriptApply) for _, pattern := range []string{"POST /v1/operator/disk-ops/actions/preview", "POST /v1/operator/disk-ops/actions/decide", "GET /v1/operator/disk-ops/quarantine/{machine_id}", "POST /v1/operator/disk-ops/restores/preview", "POST /v1/operator/disk-ops/restores"} { diff --git a/cmd/clawctl-hub/operator_boundary.go b/cmd/clawctl-hub/operator_boundary.go index 1cce4808..bd83c75f 100644 --- a/cmd/clawctl-hub/operator_boundary.go +++ b/cmd/clawctl-hub/operator_boundary.go @@ -482,6 +482,7 @@ var operatorRoutePolicies = map[string]operatorRoutePolicy{ "GET /v1/operator/schedules/{id}": {operatorauth.View, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligible}, "POST /v1/operator/schedules/{operation}/{phase}": {operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleOperatorAdmin}, "POST /v1/operator/schedules/{id}/run-now": {operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleOperatorAdmin}, + "POST /v1/operator/schedule-jobs/{id}/cancel": {operatorauth.Admin, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleOperatorAdmin}, "GET /v1/operator/script-catalog": {operatorauth.View, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceIneligible}, "POST /v1/operator/script-runs/preview": {operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleReadScriptsOnly}, "POST /v1/operator/script-runs": {operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleReadScriptsOnly}, diff --git a/cmd/clawctl-hub/operator_boundary_test.go b/cmd/clawctl-hub/operator_boundary_test.go index 55d3ec92..ec7e16f9 100644 --- a/cmd/clawctl-hub/operator_boundary_test.go +++ b/cmd/clawctl-hub/operator_boundary_test.go @@ -131,12 +131,12 @@ func TestOperatorRouteManifestMatchesAllRegisteredRoutes(t *testing.T) { t.Fatalf("non-operator registered=%d policies=%d, want 39/39", len(nonOperatorRegistered), len(nonOperatorRoutePolicies)) } - if len(operatorRegistered) != 325 || len(operatorRoutePolicies) != 325 { - t.Fatalf("operator registered=%d policies=%d, want 325/325", + if len(operatorRegistered) != 326 || len(operatorRoutePolicies) != 326 { + t.Fatalf("operator registered=%d policies=%d, want 326/326", len(operatorRegistered), len(operatorRoutePolicies)) } - if len(nonOperatorRegistered)+len(operatorRegistered) != 364 { - t.Fatalf("all registered routes=%d, 預期 364", len(nonOperatorRegistered)+len(operatorRegistered)) + if len(nonOperatorRegistered)+len(operatorRegistered) != 365 { + t.Fatalf("all registered routes=%d, 預期 365", len(nonOperatorRegistered)+len(operatorRegistered)) } counts := map[operatorauth.Permission]int{} representations := map[operatorRepresentation]int{} @@ -146,14 +146,14 @@ func TestOperatorRouteManifestMatchesAllRegisteredRoutes(t *testing.T) { representations[policy.Representation]++ profiles[policy.SecurityProfile]++ } - if counts[operatorauth.View] != 128 || counts[operatorauth.Operate] != 34 || counts[operatorauth.Admin] != 163 { - t.Fatalf("permission counts=%v, want view=128 operate=34 admin=163", counts) + if counts[operatorauth.View] != 128 || counts[operatorauth.Operate] != 34 || counts[operatorauth.Admin] != 164 { + t.Fatalf("permission counts=%v, want view=128 operate=34 admin=164", counts) } - if representations[operatorJSON] != 159 || representations[operatorHTML] != 165 || representations[operatorPlain] != 1 { - t.Fatalf("representation counts=%v, want JSON=159 HTML=165 plain=1", representations) + if representations[operatorJSON] != 160 || representations[operatorHTML] != 165 || representations[operatorPlain] != 1 { + t.Fatalf("representation counts=%v, want JSON=160 HTML=165 plain=1", representations) } - if profiles[operatorSecurityLocked] != 324 || profiles[operatorSecurityTerminal] != 1 { - t.Fatalf("security profiles=%v, want locked=324 terminal=1", profiles) + if profiles[operatorSecurityLocked] != 325 || profiles[operatorSecurityTerminal] != 1 { + t.Fatalf("security profiles=%v, want locked=325 terminal=1", profiles) } } @@ -580,6 +580,7 @@ func TestEveryOperatorRouteRequestsItsExactPermission(t *testing.T) { {"GET /v1/operator/schedules/{id}", "/v1/operator/schedules/s-1", operatorRoutePolicy{operatorauth.View, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligible}}, {"POST /v1/operator/schedules/{operation}/{phase}", "/v1/operator/schedules/upsert/preview", operatorRoutePolicy{operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleOperatorAdmin}}, {"POST /v1/operator/schedules/{id}/run-now", "/v1/operator/schedules/s-1/run-now", operatorRoutePolicy{operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleOperatorAdmin}}, + {"POST /v1/operator/schedule-jobs/{id}/cancel", "/v1/operator/schedule-jobs/j-1/cancel", operatorRoutePolicy{operatorauth.Admin, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleOperatorAdmin}}, {"GET /v1/operator/script-catalog", "/v1/operator/script-catalog", operatorRoutePolicy{operatorauth.View, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceIneligible}}, {"POST /v1/operator/script-runs/preview", "/v1/operator/script-runs/preview", operatorRoutePolicy{operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleReadScriptsOnly}}, {"POST /v1/operator/script-runs", "/v1/operator/script-runs", operatorRoutePolicy{operatorauth.Operate, operatorJSON, operator.SourceKindOperatorAPI, operatorSecurityLocked, serviceEligibleReadScriptsOnly}}, diff --git a/cmd/clawctl-hub/operator_schedule_api.go b/cmd/clawctl-hub/operator_schedule_api.go index 9346dfae..d6f156c9 100644 --- a/cmd/clawctl-hub/operator_schedule_api.go +++ b/cmd/clawctl-hub/operator_schedule_api.go @@ -150,6 +150,47 @@ func (h *hub) handleScheduleRunNow(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, result) } +// handleScheduleJobCancel cancels one scheduled job that is still not_started +// and was never claimed, so a stale job on an offline machine can be cleared +// without a raw database edit. Admin only; reason and Idempotency-Key required. +func (h *hub) handleScheduleJobCancel(w http.ResponseWriter, r *http.Request) { + if !h.admitScheduleMutation(w, r) { + return + } + actor := operatorActor(r) + action := store.AuditScheduleJobCancel + if !h.requireAuditedJSON(w, r, actor, action) { + return + } + p, ok := operatorauth.PrincipalFromContext(r.Context()) + if !ok || !p.Has(operatorauth.Admin) { + h.rejectOperatorPolicyTransport(w, r, actor, action, 403, "SCRIPT_SCOPE_REQUIRED", "cancelling a scheduled job requires admin") + return + } + if !h.requireDiskJSONFreshHuman(w, r, action) { + return + } + actor.AuthCapability = p.GrantedCapabilities.Admin + if p.ServiceScope == operatorauth.ServiceScopeOperatorAdmin { + actor.AuthCapability = operatorauth.ServiceScopeOperatorAdmin + } + var body store.ScheduleJobCancelRequest + if rejection := decodeOperatorBody(w, r, &body); rejection != nil { + h.rejectOperatorPolicyTransport(w, r, actor, action, rejection.Status, rejection.Code, rejection.Detail) + return + } + result, e := operator.New(h.store).ScheduleJobCancel(r.PathValue("id"), r.Header.Get("Idempotency-Key"), body, actor) + if e != nil { + writeSettingErr(w, "schedule job cancel", e) + return + } + w.Header().Set("Cache-Control", "no-store") + if result.Replayed { + w.Header().Set("Idempotency-Replayed", "true") + } + writeJSON(w, 200, result) +} + // The registry and stored schedule select the boundary scope, never a caller mode. func scheduleRequestPermission(r *http.Request, st *store.Store) operatorauth.Permission { var id, script string diff --git a/docs/API-SURFACE.md b/docs/API-SURFACE.md index ae3c9467..00e14004 100644 --- a/docs/API-SURFACE.md +++ b/docs/API-SURFACE.md @@ -3,7 +3,7 @@ > 這是控制面 parity 的帳本,不是行銷功能表。只要正常操作仍只有 CLI, > 就留在「缺口」欄;高風險不是把入口藏起來,而是補 RBAC、preview、確認、 > 冪等與 audit。共同成功語意見 [CONTROL-PLANE-CONTRACT.md](CONTROL-PLANE-CONTRACT.md)。 -> 逐一對照 364 個 HTTP operations(39 non-operator+325 operator;159 條 operator JSON)、 +> 逐一對照 365 個 HTTP operations(39 non-operator+326 operator;160 條 operator JSON)、 > native Store、UI/CLI 與 Intune-style submenu 的完整清單, > 見 [FEATURE-INVENTORY.md](FEATURE-INVENTORY.md)。 @@ -12,7 +12,7 @@ is off by default and uses its own signature/secret boundary. See [CHANNELS.md]( ## Public local-account routes (Autopilot) -These six operations are included in the 364-operation tally above (39 non-operator + 325 operator). The inventory/contract excludes these six public account operations and totals 358. Account routes return 404 in `tailscale` mode. In `local` / `both`, they pin Host to `CLAWCTL_PUBLIC_URL`, use locked security headers and Go CrossOriginProtection, and do not require an existing operator session. +These six operations are included in the 365-operation tally above (39 non-operator + 326 operator). The inventory/contract excludes these six public account operations and totals 359. Account routes return 404 in `tailscale` mode. In `local` / `both`, they pin Host to `CLAWCTL_PUBLIC_URL`, use locked security headers and Go CrossOriginProtection, and do not require an existing operator session. | Method | Route | Authority / behavior | |---|---|---| @@ -599,6 +599,16 @@ Both require view. `targets`, `cron`, and `enabled`. `catch_up` must be false. Preview and apply return a `ScheduleResult` object with `schedule`, `preview_digest`, and `replayed`. +`POST /v1/operator/schedule-jobs/{id}/cancel` requires admin (or an allowlisted +`operator-admin` service token), `Idempotency-Key`, and `{"reason":"..."}`. It +cancels one scheduled job only while it is `not_started` and has never been +claimed (no lease); the job becomes `rejected` with an audit row +(`schedule-job-cancel`). It returns `{"job_id","schedule_id","machine_id","state","replayed"}`; +an unknown job is `404 SCHEDULE_JOB_NOT_FOUND`, a claimed or finished job is +`412 PRECONDITION_FAILED`. The scheduler also stops counting such a job as an +overlap once it is older than one cron interval of its schedule (plus a +two-minute grace); that target is left out of the run, recorded in audit, and +the other targets still run. `POST /v1/operator/schedules/{id}/run-now` requires `Idempotency-Key`, accepts `{}`, and returns `{"job_ids":[...],"replayed":false}` (an empty array when no jobs are enqueued). Replays return the saved job IDs, `replayed:true`, and `Idempotency-Replayed: true`, without enqueueing. Manual @@ -828,7 +838,8 @@ that service identity. Existing bounded rate-limit denial auditing still applies Schedule list/get accepts explicitly allowlisted `view`, `operate`, and `operator-admin` tokens. Schedule upsert and set-enabled preview/apply (`POST /v1/operator/schedules/{operation}/{phase}`), and run-now -(`POST /v1/operator/schedules/{id}/run-now`) accept explicitly allowlisted +(`POST /v1/operator/schedules/{id}/run-now`), and scheduled-job cancel +(`POST /v1/operator/schedule-jobs/{id}/cancel`) accept explicitly allowlisted `operator-admin` tokens. `view` and `operate` tokens cannot manage schedules. Catalog approval, revision, preview digest, idempotency and rate-limit checks still apply to delegated actions. diff --git a/docs/CONTROL-PLANE-CONTRACT.md b/docs/CONTROL-PLANE-CONTRACT.md index 5e33f2d7..6f21b610 100644 --- a/docs/CONTROL-PLANE-CONTRACT.md +++ b/docs/CONTROL-PLANE-CONTRACT.md @@ -479,8 +479,8 @@ Web、operator JSON、strict Go client 與 HTTP CLI 共用同一套 preview/dige 在 mutation 前建立 private canonical recovery receipt,ambiguous response 以原 request 精確重放。 目前 production surface 固定為 -358(33 non-operator+325 operator;159 operator JSON+166 HTML/BFF/CSV/download),exact auth tally 是 -`view=128`/`operate=34`/`admin=163`。這是由 manifest 測試固定的 contract;實機紀錄是私人工作筆記,不在這個公開倉庫。 +359(33 non-operator+326 operator;160 operator JSON+166 HTML/BFF/CSV/download),exact auth tally 是 +`view=128`/`operate=34`/`admin=164`。這是由 manifest 測試固定的 contract;實機紀錄是私人工作筆記,不在這個公開倉庫。 管理中心導覽語言是 browser presentation preference,不是 fleet state。右上角是同源 form `POST /preferences/navigation-language`,只接受 `zh-Hant`/`en`,以 HttpOnly、SameSite=Lax、 diff --git a/docs/FEATURE-INVENTORY.md b/docs/FEATURE-INVENTORY.md index 2136d347..3ffc1877 100644 --- a/docs/FEATURE-INVENTORY.md +++ b/docs/FEATURE-INVENTORY.md @@ -47,12 +47,12 @@ manifest 位於 `cmd/clawctl-hub/operator_boundary.go`,Web routes 位於 Hub schema 已平台中立:`internal/store/schema.sql` 的 `machine_registry.os`/`arch` 是 TEXT、無 CHECK;`internal/catalog/catalog.go` 的 `Platform{OS,Arch}` 無 enum,同一個檔的 `validPlatform` 只做識別字規則,`"darwin"` 與 `"windows"` 字串都過得了。過得了字串 ≠ 有 adapter 或 installer。 -## 358 個 production operations 基線 +## 359 個 production operations 基線 -此數字按 HTTP method + route 計數:33 個 non-operator operations、325 個 operator -operations;其中 159 個為 operator JSON、166 個為 HTML/BFF/CSV/download。Operator 另按 exact -capability 分成 `view=128`、`operate=34`、`admin=163`。這組數字由 route/API/service/Web/CLI -合約測試固定;358-operation surface 包含受 operator view 保護的 Agent bootstrap download、Tailnet Settings、Maintenance、Ticket usage、資料揭露面、註冊報告、每日早報預覽、註冊上限、軟體清查、每機安裝狀態、發佈與指派對照、Hub 名冊重新命名及名冊備註、管理中心導覽語言偏好, +此數字按 HTTP method + route 計數:33 個 non-operator operations、326 個 operator +operations;其中 160 個為 operator JSON、166 個為 HTML/BFF/CSV/download。Operator 另按 exact +capability 分成 `view=128`、`operate=34`、`admin=164`。這組數字由 route/API/service/Web/CLI +合約測試固定;359-operation surface 包含受 operator view 保護的 Agent bootstrap download、Tailnet Settings、Maintenance、Ticket usage、資料揭露面、註冊報告、每日早報預覽、註冊上限、軟體清查、每機安裝狀態、發佈與指派對照、Hub 名冊重新命名及名冊備註、管理中心導覽語言偏好, 以及只開兩條 route 的 verifier transport; 這是 repo 的 route manifest 基線,live binary 的實機紀錄是私人工作筆記,不在這個公開倉庫,兩者在部署前本來就可能不同。 新增、移除或改 method 時,須同步更新本節與 route manifest 測試。 @@ -104,7 +104,7 @@ resolver 在 `cmd/clawctl-hub/verifier_api.go`。 | 32 | `GET /api/v1/errors` | `cmd/clawctl-hub/errors_api.go` | No | Scoped errors:read token; filtered error records; opt-in ingest | | 33 | `GET /api/v1/errors/top` | `cmd/clawctl-hub/errors_api.go` | No | Scoped errors:read token; error aggregates; opt-in ingest | -### Operator HTML/BFF 與 JSON(325) +### Operator HTML/BFF 與 JSON(326) | # | Method / route | 類型 | 人工 action | 備註 | |---:|---|---|---|---| @@ -458,6 +458,7 @@ domain service 見 `internal/operator/`。 | 356 | `POST /tenant/offline-alerts/apply` | HTML form | Yes | `admin`; Canonical confirmed apply | | 357 | `POST /machines/{id}/execution-policy/preview` | HTML form | Yes, preview | Human admin; audited profile preview | | 358 | `POST /machines/{id}/execution-policy/apply` | HTML form | Yes | Human admin + fresh MFA; exact preview, revision, reason, confirmation and request key | +| 359 | `POST /v1/operator/schedule-jobs/{id}/cancel` | JSON | Yes | `admin` (or operator-admin service token); cancels one scheduled job that is still `not_started` and never claimed; required reason and Idempotency-Key, receipt replay and audit | ## Workload / submenu parity matrix diff --git a/docs/OPERATOR-AGENT.md b/docs/OPERATOR-AGENT.md index 33fdbf24..7e5263ee 100644 --- a/docs/OPERATOR-AGENT.md +++ b/docs/OPERATOR-AGENT.md @@ -350,8 +350,14 @@ GET /v1/operator/schedules GET /v1/operator/schedules/{id} POST /v1/operator/schedules/{operation}/{phase} POST /v1/operator/schedules/{id}/run-now +POST /v1/operator/schedule-jobs/{id}/cancel ``` +`schedule_job_cancel` (`job_id`, `reason`, `idempotency_key`) cancels one +scheduled job that is still `not_started` and was never claimed, for example a +stale job left on an offline machine. It needs admin or an `operator-admin` +token and is refused for a claimed or finished job. + Use the registered route patterns literally in the allowlist; substitute IDs and operations in actual requests. Supply a normal audit reason such as `rotate disk on sampleagent1, per ticket #42`; never include credentials. Keep diff --git a/docs/OPERATOR-AUTH.md b/docs/OPERATOR-AUTH.md index 7be7ec90..fab9472f 100644 --- a/docs/OPERATOR-AUTH.md +++ b/docs/OPERATOR-AUTH.md @@ -173,11 +173,11 @@ example.com/cap/clawctl-admin 另外一條 non-operator route 是 opt-in signed chat webhook `POST /v1/channels/{id}/inbound`,有獨立 provider authentication;見 [CHANNELS.md](CHANNELS.md)。 -目前 code route manifest 固定為 358 operations:33 條 non-operator,加上 325 條 operator -routes;operator manifest 的 exact capability tally 是 `view=128`、`operate=34`、`admin=163`, -其中 `/v1/operator/*` JSON routes 共 159 條、HTML/BFF/CSV/download 共 166 條。這些數字由 route manifest 測試固定,不能靠 +目前 code route manifest 固定為 359 operations:33 條 non-operator,加上 326 條 operator +routes;operator manifest 的 exact capability tally 是 `view=128`、`operate=34`、`admin=164`, +其中 `/v1/operator/*` JSON routes 共 160 條、HTML/BFF/CSV/download 共 166 條。這些數字由 route manifest 測試固定,不能靠 較高 capability 的隱含繼承湊數。 -358-operation boundary 包含 machine-bearer bootstrap readiness receipt、operator-only bundle download、Tailnet Settings、Retention Maintenance、資料揭露面、註冊報告、每日早報預覽、註冊上限、軟體清查、每機安裝狀態、發佈與指派對照、Hub 名冊重新命名/備註、verifier registry 與派工、disk-clean 摘要與發布;完整 route 與 ledger 證據的實機紀錄是私人工作筆記,不在這個公開倉庫。 +359-operation boundary 包含 machine-bearer bootstrap readiness receipt、operator-only bundle download、Tailnet Settings、Retention Maintenance、資料揭露面、註冊報告、每日早報預覽、註冊上限、軟體清查、每機安裝狀態、發佈與指派對照、Hub 名冊重新命名/備註、verifier registry 與派工、disk-clean 摘要與發布;完整 route 與 ledger 證據的實機紀錄是私人工作筆記,不在這個公開倉庫。 Disk policy and approval-decision JSON applies accept boundary-authorized human Tailscale admins or local admins with a current session MFA proof, checked before diff --git a/internal/operator/http.go b/internal/operator/http.go index 101e2d92..0830d29c 100644 --- a/internal/operator/http.go +++ b/internal/operator/http.go @@ -32,7 +32,8 @@ func HTTPError(err error) (status int, code, detail string) { store.OperatorCodeVerificationAssignmentJobNotFound, store.OperatorCodeSettingPolicyNotFound, store.OperatorCodeCompliancePolicyNotFound, - store.OperatorCodeMaintenanceNotFound: + store.OperatorCodeMaintenanceNotFound, + store.OperatorCodeScheduleJobNotFound: status = http.StatusNotFound case "REVISION_CONFLICT", store.OperatorCodeIdempotencyConflict, store.OperatorCodeNeverObserved, store.OperatorCodeMachinePlatformUnknown, store.OperatorCodeMachinePlatformUnsupported, diff --git a/internal/operator/script.go b/internal/operator/script.go index bab11c56..919787d1 100644 --- a/internal/operator/script.go +++ b/internal/operator/script.go @@ -13,6 +13,11 @@ func (s *Service) ScheduleRunNow(id, key string, actor Actor) (store.ScheduleRun return s.store.ScheduleRunNow(id, key, auditFromActor(actor)) } +// ScheduleJobCancel cancels a scheduled job that no agent has claimed. +func (s *Service) ScheduleJobCancel(jobID, key string, req store.ScheduleJobCancelRequest, actor Actor) (store.ScheduleJobCancelResponse, error) { + return s.store.ScheduleJobCancel(jobID, key, req, auditFromActor(actor)) +} + func (s *Service) RejectScheduleRunNow(id, key string, actor Actor) error { a := auditFromActor(actor) a.Action = store.AuditScheduleRunNow diff --git a/internal/operatoragent/schedules.go b/internal/operatoragent/schedules.go index a7ec8e57..5be0ce80 100644 --- a/internal/operatoragent/schedules.go +++ b/internal/operatoragent/schedules.go @@ -11,11 +11,12 @@ type scheduleHub interface { ScheduleRead(context.Context, string) (any, error) ScheduleManage(context.Context, store.ScheduleRequest, string, bool, string) (store.ScheduleResult, error) ScheduleRunNow(context.Context, string, string) (any, error) + ScheduleJobCancel(context.Context, string, string, string) (any, error) } func scheduleTools() []Tool { props := map[string]any{"id": strField(1, 128, idPattern, "Schedule ID"), "name": strField(1, 63, "^[a-z0-9][a-z0-9-]*$", "Unique name"), "script_id": strField(1, 128, idPattern, "Catalog ID"), "script_sha256": strField(64, 64, "^[a-f0-9]{64}$", "Approved hash"), "args": map[string]any{"type": "object"}, "targets": map[string]any{"type": "array", "minItems": 1, "maxItems": 50, "uniqueItems": true, "items": strField(1, 128, idPattern, "")}, "cron": strField(1, 128, "", "Five numeric fields in tz (default UTC); minimum five minutes"), "tz": strField(1, 128, "", "IANA timezone; optional, default UTC"), "enabled": map[string]any{"type": "boolean"}, "catch_up": map[string]any{"type": "boolean", "enum": []bool{false}}, "expected_revision": intBound(0, 2147483647, "Current revision; zero for create"), "reason": strField(1, 500, "", "Reason without credentials")} - out := []Tool{{Name: "schedule_list", Description: "List schedules. Requires view.", InputSchema: obj(map[string]any{}), Annotations: readAnn("schedule_list")}, {Name: "schedule_get", Description: "Get a schedule. Requires view.", InputSchema: obj(map[string]any{"id": props["id"]}, "id"), Annotations: readAnn("schedule_get")}, {Name: "schedule_run_now", Description: "Run an approved schedule now, with overlap protection. Requires operate for read scripts, admin for write scripts.", InputSchema: obj(map[string]any{"id": props["id"], "idempotency_key": strField(1, 200, "", "Durable manual run key")}, "id", "idempotency_key"), Annotations: writeAnn("schedule_run_now", false)}} + out := []Tool{{Name: "schedule_list", Description: "List schedules. Requires view.", InputSchema: obj(map[string]any{}), Annotations: readAnn("schedule_list")}, {Name: "schedule_get", Description: "Get a schedule. Requires view.", InputSchema: obj(map[string]any{"id": props["id"]}, "id"), Annotations: readAnn("schedule_get")}, {Name: "schedule_run_now", Description: "Run an approved schedule now, with overlap protection. Requires operate for read scripts, admin for write scripts.", InputSchema: obj(map[string]any{"id": props["id"], "idempotency_key": strField(1, 200, "", "Durable manual run key")}, "id", "idempotency_key"), Annotations: writeAnn("schedule_run_now", false)}, {Name: "schedule_job_cancel", Description: "Cancel one scheduled job that is still not_started and was never claimed by its agent, such as a stale job on an offline machine. Requires admin.", InputSchema: obj(map[string]any{"job_id": strField(1, 128, idPattern, "Scheduled job ID"), "reason": props["reason"], "idempotency_key": strField(1, 200, "", "Idempotency key")}, "job_id", "reason", "idempotency_key"), Annotations: writeAnn("schedule_job_cancel", false)}} for _, op := range []string{"upsert", "set_enabled"} { for _, phase := range []string{"preview", "apply"} { p := map[string]any{} @@ -55,6 +56,24 @@ func (s *Service) scheduleCall(ctx context.Context, name string, raw json.RawMes v, e := h.ScheduleRead(ctx, "") return v, hubErr(e) } + if name == "schedule_job_cancel" { + var req struct { + JobID string `json:"job_id"` + Reason string `json:"reason"` + IdempotencyKey string `json:"idempotency_key"` + } + if e := decodeArgs(raw, &req); e != nil { + return nil, e + } + if req.JobID == "" || strings.TrimSpace(req.Reason) == "" { + return nil, &CallError{Code: "invalid_arguments", Message: "job_id and reason required"} + } + if e := requireIdempotency(req.IdempotencyKey); e != nil { + return nil, e + } + v, e := h.ScheduleJobCancel(ctx, req.JobID, req.Reason, req.IdempotencyKey) + return v, hubErr(e) + } if name == "schedule_get" || name == "schedule_run_now" { var req struct { ID string `json:"id"` diff --git a/internal/operatoragent/schedules_test.go b/internal/operatoragent/schedules_test.go index 74170a46..731bc870 100644 --- a/internal/operatoragent/schedules_test.go +++ b/internal/operatoragent/schedules_test.go @@ -24,6 +24,10 @@ func (f *fakeScheduleHub) ScheduleRunNow(context.Context, string, string) (any, f.callsSchedule++ return nil, nil } +func (f *fakeScheduleHub) ScheduleJobCancel(context.Context, string, string, string) (any, error) { + f.callsSchedule++ + return nil, nil +} func TestScheduleTools(t *testing.T) { f := &fakeScheduleHub{} s := &Service{Hub: f} @@ -36,6 +40,12 @@ func TestScheduleTools(t *testing.T) { if _, e := s.Call(context.Background(), "schedule_run_now", json.RawMessage(`{"id":"s-1"}`)); e == nil || f.callsSchedule != 0 { t.Fatal("manual run missing key called Hub") } + if _, e := s.Call(context.Background(), "schedule_job_cancel", json.RawMessage(`{"job_id":"j-1","reason":"machine offline"}`)); e == nil || f.callsSchedule != 0 { + t.Fatal("cancel missing key called Hub") + } + if _, e := s.Call(context.Background(), "schedule_job_cancel", json.RawMessage(`{"job_id":"j-1","reason":" ","idempotency_key":"cancel-key"}`)); e == nil || f.callsSchedule != 0 { + t.Fatal("cancel without reason called Hub") + } for _, tool := range scheduleTools() { if tool.InputSchema["additionalProperties"] != false { t.Fatal(tool.Name) @@ -44,6 +54,9 @@ func TestScheduleTools(t *testing.T) { if _, e := s.Call(context.Background(), "schedule_list", json.RawMessage(`{}`)); e != nil || f.callsSchedule != 1 { t.Fatal(e) } + if _, e := s.Call(context.Background(), "schedule_job_cancel", json.RawMessage(`{"job_id":"j-1","reason":"machine offline","idempotency_key":"cancel-key"}`)); e != nil || f.callsSchedule != 2 { + t.Fatal(e) + } if _, e := s.Call(context.Background(), "schedule_get", json.RawMessage(`{"id":"s-1","unknown":true}`)); e == nil { t.Fatal("unknown field") } diff --git a/internal/operatoragent/tools.go b/internal/operatoragent/tools.go index c8703d43..ea22546e 100644 --- a/internal/operatoragent/tools.go +++ b/internal/operatoragent/tools.go @@ -80,7 +80,7 @@ func (s *Service) Call(ctx context.Context, name string, raw json.RawMessage) (a return s.diskApprovalCall(ctx, name, raw) case "disk_alerts_list", "disk_ownership_get", "disk_report_get", "disk_ops_status", "disk_policy_list", "disk_policy_get", "disk_policy_upsert_preview", "disk_policy_upsert_apply": return s.diskPolicyCall(ctx, name, raw) - case "schedule_list", "schedule_get", "schedule_upsert_preview", "schedule_upsert_apply", "schedule_set_enabled_preview", "schedule_set_enabled_apply", "schedule_run_now": + case "schedule_list", "schedule_get", "schedule_upsert_preview", "schedule_upsert_apply", "schedule_set_enabled_preview", "schedule_set_enabled_apply", "schedule_run_now", "schedule_job_cancel": return s.scheduleCall(ctx, name, raw) case "script_catalog_list", "script_run_preview", "script_run_apply": return s.scriptCall(ctx, name, raw) diff --git a/internal/operatorauth/service_scope.go b/internal/operatorauth/service_scope.go index 344c569c..7e79b2d0 100644 --- a/internal/operatorauth/service_scope.go +++ b/internal/operatorauth/service_scope.go @@ -10,6 +10,7 @@ func OperatorAdminRoute(route string) bool { switch route { case "POST /v1/operator/enrollment-tokens/preview", "POST /v1/operator/enrollment-tokens", "POST /v1/operator/schedules/{operation}/{phase}", "POST /v1/operator/schedules/{id}/run-now", + "POST /v1/operator/schedule-jobs/{id}/cancel", "POST /v1/operator/machines/{id}/profile-assignment-preview", "POST /v1/operator/machines/{id}/profile-assignments", "POST /v1/operator/deployments/preview", "POST /v1/operator/deployments", "POST /v1/operator/deployments/{id}/continuation-preview", "POST /v1/operator/deployments/{id}/continuations", diff --git a/internal/operatorauth/service_scope_test.go b/internal/operatorauth/service_scope_test.go index 801f861a..3a1f4505 100644 --- a/internal/operatorauth/service_scope_test.go +++ b/internal/operatorauth/service_scope_test.go @@ -22,7 +22,7 @@ func TestScheduleReadScopes(t *testing.T) { t.Fatalf("read denied: %s %s", scope, route) } } - for _, route := range []string{"POST /v1/operator/schedules/{operation}/{phase}", "POST /v1/operator/schedules/{id}/run-now"} { + for _, route := range []string{"POST /v1/operator/schedules/{operation}/{phase}", "POST /v1/operator/schedules/{id}/run-now", "POST /v1/operator/schedule-jobs/{id}/cancel"} { if ServiceScopeAllows(scope, "operate", route) != (scope == ServiceScopeOperatorAdmin) { t.Fatalf("mutation scope: %s %s", scope, route) } diff --git a/internal/operatorclient/schedules.go b/internal/operatorclient/schedules.go index 68dfbea4..3006b80f 100644 --- a/internal/operatorclient/schedules.go +++ b/internal/operatorclient/schedules.go @@ -70,6 +70,31 @@ func (c *Client) ScheduleManage(ctx context.Context, body store.ScheduleRequest, } return out, e } +func (c *Client) ScheduleJobCancel(ctx context.Context, jobID, reason, key string) (any, error) { + if !validSettingIdempotencyKey(key) { + return nil, errors.New("idempotency key required") + } + r, e := c.postSettingJSON(ctx, "/v1/operator/schedule-jobs/"+url.PathEscape(jobID)+"/cancel", key, store.ScheduleJobCancelRequest{Reason: reason}) + if e != nil { + return nil, e + } + if r.status != 200 { + return nil, errors.New("schedule job cancel failed") + } + if e = validateJSONNoStoreResponse(r.header); e != nil { + return nil, e + } + replayed, e := responseReplayEvidenceFromHeader(r.header) + if e != nil { + return nil, e + } + var out store.ScheduleJobCancelResponse + e = decodeStrictJSONDocument(r.body, "schedule job cancel", &out) + if e == nil && out.Replayed != replayed { + e = errors.New("schedule job cancel replay receipt mismatch") + } + return out, e +} func (c *Client) ScheduleRunNow(ctx context.Context, id, key string) (any, error) { if !validSettingIdempotencyKey(key) { return nil, errors.New("idempotency key required") diff --git a/internal/store/audit.go b/internal/store/audit.go index f9e0f964..7edf8434 100644 --- a/internal/store/audit.go +++ b/internal/store/audit.go @@ -52,6 +52,7 @@ const ( AuditScheduleEnabledApply AuditAction = "schedule-set-enabled-apply" AuditScheduleRun AuditAction = "schedule-run" AuditScheduleRunNow AuditAction = "schedule-run-now" + AuditScheduleJobCancel AuditAction = "schedule-job-cancel" AuditScriptPreview AuditAction = "script-run-preview" AuditScriptApply AuditAction = "script-run-apply" AuditScriptComplete AuditAction = "script-run-complete" @@ -188,7 +189,7 @@ func IsCanonicalOperatorAction(action AuditAction) bool { action == AuditDeploymentCreate || action == AuditDeploymentRetry || action == AuditDeploymentContinue || action == AuditDeploymentSkipFailedBatch || action == AuditDeploymentAbandon || action == AuditArtifactFetch || action == AuditCatalogManifest || action == AuditMachineProfile || - action == AuditScheduleUpsertPreview || action == AuditScheduleUpsertApply || action == AuditScheduleEnabledPreview || action == AuditScheduleEnabledApply || action == AuditScheduleRun || action == AuditScheduleRunNow || + action == AuditScheduleUpsertPreview || action == AuditScheduleUpsertApply || action == AuditScheduleEnabledPreview || action == AuditScheduleEnabledApply || action == AuditScheduleRun || action == AuditScheduleRunNow || action == AuditScheduleJobCancel || action == AuditScriptPreview || action == AuditScriptApply || action == AuditScriptComplete || action == AuditMachineProfileAssign || action == AuditDiagnosticNoop || action == AuditDeviceSync || action == AuditTailnetPeerIgnore || action == AuditRetentionPrune || action == AuditRestoreDrill || action == AuditVerifierRegister || action == AuditVerifierRevoke || diff --git a/internal/store/audit_read.go b/internal/store/audit_read.go index 599ea4f6..619aac1d 100644 --- a/internal/store/audit_read.go +++ b/internal/store/audit_read.go @@ -57,7 +57,7 @@ var allAuditActions = [...]AuditAction{ AuditMachineLifecycle, AuditMachineRename, AuditMachineNotes, - AuditScheduleUpsertPreview, AuditScheduleUpsertApply, AuditScheduleEnabledPreview, AuditScheduleEnabledApply, AuditScheduleRun, AuditScheduleRunNow, + AuditScheduleUpsertPreview, AuditScheduleUpsertApply, AuditScheduleEnabledPreview, AuditScheduleEnabledApply, AuditScheduleRun, AuditScheduleRunNow, AuditScheduleJobCancel, AuditScriptPreview, AuditScriptApply, AuditScriptComplete, diff --git a/internal/store/schedules.go b/internal/store/schedules.go index 9184d485..4f8707ec 100644 --- a/internal/store/schedules.go +++ b/internal/store/schedules.go @@ -5,6 +5,7 @@ import ( "database/sql" "encoding/json" "errors" + "fmt" "github.com/teddashh/AI-Intune/internal/boundedtext" "github.com/teddashh/AI-Intune/internal/operatorauth" "regexp" @@ -554,13 +555,36 @@ func (s *Store) runSchedule(id string, now time.Time, manual bool, a AuditEntry, // must still be a target of this schedule and must not be retired. A job // left on a machine that was dropped from the schedule or retired is never // claimed again, and counting it would skip every later slot forever. + // + // A job that was never claimed and is older than one cron interval is + // stale too: its machine has already missed the next run as well, and + // holding further slots for it only turns one offline machine into a + // fleet-wide gap. var active int - err = tx.QueryRow(`SELECT COUNT(*) FROM schedule_jobs sj JOIN jobs j ON j.job_id=sj.job_id JOIN machine_registry m ON m.machine_id=j.machine_id WHERE sj.schedule_id=? AND j.state NOT IN (?,?,?,?,?) AND m.retired_at IS NULL AND j.machine_id IN (SELECT value FROM json_each(?))`, id, deploy.Succeeded, deploy.Failed, deploy.Rejected, deploy.LeaseExpired, deploy.ManualIntervention, string(mustScriptJSON(v.Targets))).Scan(&active) + staleBefore := fmtTime(scheduleStaleNotStartedCutoff(v, now)) + err = tx.QueryRow(`SELECT COUNT(*) FROM schedule_jobs sj JOIN jobs j ON j.job_id=sj.job_id JOIN machine_registry m ON m.machine_id=j.machine_id WHERE sj.schedule_id=? AND j.state NOT IN (?,?,?,?,?) AND m.retired_at IS NULL AND j.machine_id IN (SELECT value FROM json_each(?)) AND NOT (j.state=? AND j.lease_token IS NULL AND j.created_at<=?)`, id, deploy.Succeeded, deploy.Failed, deploy.Rejected, deploy.LeaseExpired, deploy.ManualIntervention, string(mustScriptJSON(v.Targets)), deploy.NotStarted, staleBefore).Scan(&active) if err != nil { return } outcome := "enqueued" - req := ScriptRunRequest{ScriptID: v.ScriptID, ScriptSHA256: v.ScriptSHA256, Args: v.Args, Targets: v.Targets, TimeoutSeconds: entry.DefaultTimeout, Reason: "scheduled catalog run"} + // A target still holding a stale unclaimed job of this schedule would fail + // target validation (it has an active job) and skip the run for everyone. + // Leave that target out of this run instead; its old job stays visible + // and can be cancelled by an operator. + runTargets := v.Targets + staleTargets, err := scheduleStaleTargetsTx(tx, id, v.Targets, staleBefore) + if err != nil { + return + } + if len(staleTargets) > 0 { + runTargets = make([]string, 0, len(v.Targets)) + for _, target := range v.Targets { + if !staleTargets[target] { + runTargets = append(runTargets, target) + } + } + } + req := ScriptRunRequest{ScriptID: v.ScriptID, ScriptSHA256: v.ScriptSHA256, Args: v.Args, Targets: runTargets, TimeoutSeconds: entry.DefaultTimeout, Reason: "scheduled catalog run"} if entry.ID == "disk-deep-report-v1" { for _, target := range v.Targets { available, e := deepAvailableTx(tx, target, now) @@ -577,6 +601,9 @@ func (s *Store) runSchedule(id string, now time.Time, manual bool, a AuditEntry, } if active > 0 { outcome = "skipped_overlap" + } else if len(req.Targets) == 0 { + outcome = "skipped_unavailable" + a.Detail = "every target still holds a stale unclaimed job" } else if err = s.diskSafeGateTx(tx, req, entry); err != nil { if manual { return nil, err @@ -593,7 +620,7 @@ func (s *Store) runSchedule(id string, now time.Time, manual bool, a AuditEntry, return nil, e } raw := mustScriptJSON(scriptcatalog.Spec{Policy: policy, ExecutionMode: v.ExecutionMode, Kind: scriptcatalog.Kind, ScriptID: v.ScriptID, ScriptSHA256: v.ScriptSHA256, Args: v.Args}) - for _, target := range v.Targets { + for _, target := range req.Targets { if entry.ID == "disk-quarantine-expire-v1" { var args struct { ID string `json:"policy_id"` @@ -635,6 +662,13 @@ func (s *Store) runSchedule(id string, now time.Time, manual bool, a AuditEntry, } } } + if outcome == "enqueued" && len(staleTargets) > 0 { + note := a + note.Detail = fmt.Sprintf("left out %d target(s) still holding a stale unclaimed job: %s", len(staleTargets), strings.Join(sortedKeys(staleTargets), ",")) + if err = s.recordAuditTx(tx, note); err != nil { + return + } + } if outcome == "enqueued" && len(jobs) == 0 { outcome = "skipped_unavailable" a.Detail = "no approved expiry items are due" @@ -709,6 +743,53 @@ func (s *Store) recordScheduleSkipTx(tx dbTx, v Schedule, now time.Time, outcome return e } +// OperatorCodeScheduleJobNotFound reports a cancel for a job that is not a +// scheduled job. +const OperatorCodeScheduleJobNotFound = "SCHEDULE_JOB_NOT_FOUND" + +// scheduleStaleTargetsTx returns the targets that hold an unclaimed +// not_started job of this schedule created at or before staleBefore. +func scheduleStaleTargetsTx(tx dbTx, scheduleID string, targets []string, staleBefore string) (map[string]bool, error) { + rows, err := tx.Query(`SELECT DISTINCT j.machine_id FROM schedule_jobs sj JOIN jobs j ON j.job_id=sj.job_id WHERE sj.schedule_id=? AND j.state=? AND j.lease_token IS NULL AND j.created_at<=? AND j.machine_id IN (SELECT value FROM json_each(?))`, scheduleID, deploy.NotStarted, staleBefore, string(mustScriptJSON(targets))) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]bool{} + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + out[id] = true + } + return out, rows.Err() +} + +// scheduleStaleGrace absorbs scheduler tick jitter: a slot runs up to a minute +// after it is due, so a job made by the previous slot can be slightly older +// than one interval when the next slot is evaluated. The grace keeps that job +// counting as overlap for exactly one more slot. +const scheduleStaleGrace = 2 * time.Minute + +// scheduleStaleNotStartedCutoff returns the creation time at or before which a +// never-claimed job of v no longer counts as overlap: more than one cron +// interval (measured from the upcoming slot) plus scheduleStaleGrace before +// now. The job still blocks the slot right after its own, as overlap always +// did, and stops blocking from the slot after that. +func scheduleStaleNotStartedCutoff(v Schedule, now time.Time) time.Time { + c, err := schedulecron.Parse(v.Cron) + if err != nil { + return time.Time{} + } + first := scheduleNext(c, now, v.TZ) + interval := scheduleNext(c, first, v.TZ).Sub(first) + if interval <= 0 { + return time.Time{} + } + return now.Add(-interval - scheduleStaleGrace) +} + func scheduleNext(c *schedulecron.Cron, after time.Time, tz string) time.Time { loc, err := time.LoadLocation(tz) if err != nil { @@ -734,3 +815,106 @@ func (s *Store) ScheduleJobIDs(id string) ([]string, error) { } return ids, rows.Err() } + +// ScheduleJobCancelRequest names an unclaimed scheduled job to cancel. +type ScheduleJobCancelRequest struct { + Reason string `json:"reason"` +} + +// ScheduleJobCancelResponse is the durable receipt of a cancellation. +type ScheduleJobCancelResponse struct { + JobID string `json:"job_id"` + ScheduleID string `json:"schedule_id"` + MachineID string `json:"machine_id"` + State string `json:"state"` + Replayed bool `json:"replayed"` +} + +// ScheduleJobCancel ends a scheduled job that no machine has claimed. Only a +// not_started job with no lease is eligible: once an agent holds a lease the +// job may be executing, and the Hub must not invent a terminal state for it. +// The job becomes rejected, which also stops it counting as overlap. +func (s *Store) ScheduleJobCancel(jobID, key string, req ScheduleJobCancelRequest, a AuditEntry) (out ScheduleJobCancelResponse, err error) { + a.Action = AuditScheduleJobCancel + a.Subject = jobID + a.Reason = req.Reason + a.IdempotencyKey = key + defer func() { + if err != nil { + a.OK = false + a.Detail = "schedule job cancel rejected" + _ = s.RecordAudit(a) + } + }() + if key == "" || len(key) > 200 { + return out, scriptBad("idempotency key required") + } + reason, reasonErr := boundedtext.Reason(req.Reason) + if reasonErr != nil { + return out, scriptBad(reasonErr.Error()) + } + tx, err := s.beginWrite(context.Background(), "schedule_job_cancel") + if err != nil { + return + } + defer tx.Rollback() + now := s.now().UTC() + a.At = now + requestDigest := "sha256:" + scriptcatalog.Digest(mustScriptJSON(struct{ JobID, Reason, Principal string }{jobID, reason, a.AuthSubject})) + a.RequestDigest = requestDigest + var op, digest, raw string + e := tx.QueryRow(`SELECT operation,request_digest,COALESCE(response_json,'') FROM operator_idempotency WHERE idempotency_key=?`, key).Scan(&op, &digest, &raw) + if e == nil { + if op != string(AuditScheduleJobCancel) || digest != requestDigest { + return out, scriptBad("idempotency conflict") + } + if err = json.Unmarshal([]byte(raw), &out); err != nil { + return + } + out.Replayed = true + a.OK = true + a.Detail = OperatorIdempotencyReplayPrefix + "schedule job cancel receipt" + if err = s.recordAuditTx(tx, a); err != nil { + return + } + err = tx.Commit() + return + } + if !errors.Is(e, sql.ErrNoRows) { + return out, e + } + var scheduleID, scheduleName, machineID, state string + var lease sql.NullString + e = tx.QueryRow(`SELECT sj.schedule_id,sj.schedule_name,j.machine_id,j.state,j.lease_token FROM schedule_jobs sj JOIN jobs j ON j.job_id=sj.job_id WHERE sj.job_id=?`, jobID).Scan(&scheduleID, &scheduleName, &machineID, &state, &lease) + if errors.Is(e, sql.ErrNoRows) { + return out, operatorError(OperatorCodeScheduleJobNotFound, "scheduled job not found") + } + if e != nil { + return out, e + } + if state != string(deploy.NotStarted) || (lease.Valid && lease.String != "") { + return out, operatorError("PRECONDITION_FAILED", "only an unclaimed not_started scheduled job can be cancelled; state is "+state) + } + res, e := tx.Exec(`UPDATE jobs SET state=?,terminal_at=?,lease_token=NULL,lease_expires_at=NULL WHERE job_id=? AND state=? AND lease_token IS NULL`, deploy.Rejected, fmtTime(now), jobID, deploy.NotStarted) + if e != nil { + return out, e + } + if n, e := res.RowsAffected(); e != nil { + return out, e + } else if n != 1 { + return out, operatorError("REVISION_CONFLICT", "scheduled job changed during cancel") + } + out = ScheduleJobCancelResponse{JobID: jobID, ScheduleID: scheduleID, MachineID: machineID, State: string(deploy.Rejected)} + if _, err = tx.Exec(`INSERT INTO operator_idempotency (idempotency_key,operation,request_digest,outcome,response_json,created_at) VALUES (?,?,?,'ok',?,?)`, key, string(AuditScheduleJobCancel), requestDigest, string(mustScriptJSON(out)), fmtTime(now)); err != nil { + return + } + a.OK = true + a.Subject = scheduleName + a.MachineID = machineID + a.Detail = "cancelled unclaimed scheduled job " + jobID + "; reason=" + reason + if err = s.recordAuditTx(tx, a); err != nil { + return + } + err = tx.Commit() + return +} diff --git a/internal/store/schedules_test.go b/internal/store/schedules_test.go index bbfd3fe3..cf129f0e 100644 --- a/internal/store/schedules_test.go +++ b/internal/store/schedules_test.go @@ -777,3 +777,203 @@ func TestScheduleOverlapIgnoresDroppedTarget(t *testing.T) { t.Fatalf("%s %v", outcome, e) } } + +// A never-claimed job on a live target stops counting as overlap once it is +// older than one cron interval, and its machine is left out of that run, so +// one offline machine cannot stall the rest of the fleet. +func TestScheduleOverlapIgnoresStaleNotStartedJob(t *testing.T) { + s, r, a, now := scriptFixture(t) + offline := mustEnroll(t, s, "offline-node", now) + c := healthyCheckin(now) + c.ScriptV1 = true + if err := s.RecordCheckin(offline, c, now); err != nil { + t.Fatal(err) + } + online := r.Targets[0] + req := ScheduleRequest{Name: "probe-check", ScriptID: r.ScriptID, ScriptSHA256: r.ScriptSHA256, Args: r.Args, Targets: []string{online, offline}, Cron: "*/5 * * * *", Enabled: true, Reason: r.Reason} + p, e := s.ScheduleManage(req, "upsert", false, "", a) + if e != nil { + t.Fatal(e) + } + req.PreviewDigest = p.PreviewDigest + out, e := s.ScheduleManage(req, "upsert", true, "schedule-stale", a) + if e != nil { + t.Fatal(e) + } + v := out.Schedule + if e = s.TickSchedules(v.NextRunAt); e != nil { + t.Fatal(e) + } + got, _ := s.ScheduleGet(v.ID) + if len(got.LastJobIDs) != 2 { + t.Fatalf("%+v", got) + } + var stuck string + for _, id := range got.LastJobIDs { + j, _ := s.Job(id) + if j.MachineID == online { + s.DB().Exec(`UPDATE jobs SET state='succeeded',terminal_at=? WHERE job_id=?`, fmtTime(now), id) + } else { + stuck = id + } + } + var created string + s.rdb.QueryRow(`SELECT created_at FROM jobs WHERE job_id=?`, stuck).Scan(&created) + createdAt, _ := time.Parse(time.RFC3339, created) + outcomeAt := func(slot time.Time) string { + t.Helper() + if _, e := s.DB().Exec(`UPDATE schedules SET next_run_at=? WHERE id=?`, fmtTime(slot), v.ID); e != nil { + t.Fatal(e) + } + if e := s.TickSchedules(slot); e != nil { + t.Fatal(e) + } + var o string + if e := s.rdb.QueryRow(`SELECT outcome FROM schedule_slots WHERE schedule_id=? AND slot=?`, v.ID, fmtTime(slot)).Scan(&o); e != nil { + t.Fatal(e) + } + return o + } + // Unclaimed for one interval: the next slot is still overlap, as before. + if o := outcomeAt(createdAt.Add(5 * time.Minute).Truncate(time.Minute)); o != "skipped_overlap" { + t.Fatalf("one-interval job outcome %s", o) + } + // A leased job never goes stale, however old. + s.DB().Exec(`UPDATE jobs SET lease_token='lease' WHERE job_id=?`, stuck) + if o := outcomeAt(createdAt.Add(10 * time.Minute).Truncate(time.Minute)); o != "skipped_overlap" { + t.Fatalf("leased job outcome %s", o) + } + s.DB().Exec(`UPDATE jobs SET lease_token=NULL WHERE job_id=?`, stuck) + // Older than one interval plus grace: the run goes ahead without the offline machine. + if o := outcomeAt(createdAt.Add(15 * time.Minute).Truncate(time.Minute)); o != "enqueued" { + var d string + s.rdb.QueryRow(`SELECT detail FROM audit_log WHERE subject=? ORDER BY rowid DESC LIMIT 1`, v.Name).Scan(&d) + t.Fatalf("stale job outcome %s (%s)", o, d) + } + after, _ := s.ScheduleGet(v.ID) + if len(after.LastJobIDs) != 1 { + t.Fatalf("want one new job, got %v", after.LastJobIDs) + } + if j, _ := s.Job(after.LastJobIDs[0]); j.MachineID != online { + t.Fatalf("new job on %s", j.MachineID) + } + var notes int + s.rdb.QueryRow(`SELECT COUNT(*) FROM audit_log WHERE subject=? AND detail LIKE 'left out 1 target(s)%'`, v.Name).Scan(¬es) + if notes != 1 { + t.Fatalf("left-out audit rows %d", notes) + } +} + +// When every target holds a stale job the run is skipped as unavailable. +func TestScheduleAllTargetsStaleIsUnavailable(t *testing.T) { + s, v, _, _ := createTestSchedule(t) + if e := s.TickSchedules(v.NextRunAt); e != nil { + t.Fatal(e) + } + got, _ := s.ScheduleGet(v.ID) + var created string + s.rdb.QueryRow(`SELECT created_at FROM jobs WHERE job_id=?`, got.LastJobIDs[0]).Scan(&created) + createdAt, _ := time.Parse(time.RFC3339, created) + slot := createdAt.Add(15 * time.Minute).Truncate(time.Minute) + s.DB().Exec(`UPDATE schedules SET next_run_at=? WHERE id=?`, fmtTime(slot), v.ID) + if e := s.TickSchedules(slot); e != nil { + t.Fatal(e) + } + var o string + s.rdb.QueryRow(`SELECT outcome FROM schedule_slots WHERE schedule_id=? AND slot=?`, v.ID, fmtTime(slot)).Scan(&o) + if o != "skipped_unavailable" { + t.Fatalf("outcome %s", o) + } +} + +func TestScheduleStaleCutoffTracksInterval(t *testing.T) { + now := time.Date(2026, 11, 20, 17, 0, 30, 0, time.UTC) + daily := scheduleStaleNotStartedCutoff(Schedule{Cron: "0 12 * * *", TZ: "America/New_York"}, now) + if want := now.Add(-24*time.Hour - scheduleStaleGrace); !daily.Equal(want) { + t.Fatalf("daily cutoff %s want %s", daily, want) + } + // A job made by yesterday's slot still blocks today's slot... + if made := time.Date(2026, 11, 19, 17, 0, 12, 0, time.UTC); !made.After(daily) { + t.Fatalf("yesterday's job %s already stale at cutoff %s", made, daily) + } + // ...and a job made two slots ago no longer does. + if made := time.Date(2026, 11, 18, 17, 0, 12, 0, time.UTC); made.After(daily) { + t.Fatalf("two-day-old job %s not stale at cutoff %s", made, daily) + } + if bad := scheduleStaleNotStartedCutoff(Schedule{Cron: "nonsense"}, now); !bad.IsZero() { + t.Fatal("invalid cron must disable staleness") + } +} + +func TestScheduleJobCancel(t *testing.T) { + s, v, a, _ := createTestSchedule(t) + if e := s.TickSchedules(v.NextRunAt); e != nil { + t.Fatal(e) + } + got, _ := s.ScheduleGet(v.ID) + job := got.LastJobIDs[0] + a.AuthCapability = "admin" + if _, e := s.ScheduleJobCancel(job, "", ScheduleJobCancelRequest{Reason: "machine offline"}, a); e == nil { + t.Fatal("missing idempotency key accepted") + } + if _, e := s.ScheduleJobCancel(job, "k0", ScheduleJobCancelRequest{Reason: " "}, a); e == nil { + t.Fatal("empty reason accepted") + } + if _, e := s.ScheduleJobCancel("nope", "k1", ScheduleJobCancelRequest{Reason: "machine offline"}, a); e == nil { + t.Fatal("unknown job accepted") + } + out, e := s.ScheduleJobCancel(job, "k2", ScheduleJobCancelRequest{Reason: "machine offline"}, a) + if e != nil || out.State != "rejected" || out.ScheduleID != v.ID || out.Replayed { + t.Fatalf("%+v %v", out, e) + } + j, _ := s.Job(job) + if j.State != "rejected" || j.TerminalAt == nil { + t.Fatalf("job not terminal: %+v", j) + } + again, e := s.ScheduleJobCancel(job, "k2", ScheduleJobCancelRequest{Reason: "machine offline"}, a) + if e != nil || !again.Replayed || again.JobID != job { + t.Fatalf("replay %+v %v", again, e) + } + if _, e := s.ScheduleJobCancel(job, "k2", ScheduleJobCancelRequest{Reason: "different"}, a); e == nil { + t.Fatal("idempotency conflict accepted") + } + if _, e := s.ScheduleJobCancel(job, "k3", ScheduleJobCancelRequest{Reason: "machine offline"}, a); e == nil { + t.Fatal("cancelled a terminal job twice") + } + var n int + s.rdb.QueryRow(`SELECT COUNT(*) FROM audit_log WHERE action=? AND outcome='ok'`, string(AuditScheduleJobCancel)).Scan(&n) + if n < 1 { + t.Fatal("no audit row") + } + // After cancel, the next slot is free. + next, _ := s.ScheduleGet(v.ID) + if e = s.TickSchedules(next.NextRunAt); e != nil { + t.Fatal(e) + } + var o string + s.rdb.QueryRow(`SELECT outcome FROM schedule_slots WHERE schedule_id=? AND slot=?`, v.ID, fmtTime(next.NextRunAt)).Scan(&o) + if o != "enqueued" { + t.Fatalf("after cancel outcome %s", o) + } +} + +func TestScheduleJobCancelRefusesClaimedJob(t *testing.T) { + s, v, a, _ := createTestSchedule(t) + if e := s.TickSchedules(v.NextRunAt); e != nil { + t.Fatal(e) + } + got, _ := s.ScheduleGet(v.ID) + job := got.LastJobIDs[0] + if _, e := s.DB().Exec(`UPDATE jobs SET state='claimed',lease_token='lease' WHERE job_id=?`, job); e != nil { + t.Fatal(e) + } + if _, e := s.ScheduleJobCancel(job, "k", ScheduleJobCancelRequest{Reason: "machine offline"}, a); e == nil { + t.Fatal("claimed job cancelled") + } + if _, e := s.DB().Exec(`UPDATE jobs SET state='not_started' WHERE job_id=?`, job); e != nil { + t.Fatal(e) + } + if _, e := s.ScheduleJobCancel(job, "k4", ScheduleJobCancelRequest{Reason: "machine offline"}, a); e == nil { + t.Fatal("leased not_started job cancelled") + } +}