Files
archie/internal/app/controlplane/schedules.go
T
sam f33a33d854 feat(scheduling): refuse a job payload that names a dangerous command
A scheduled job runs unattended, so a payload that restarts the daemon,
formats a disk or powers the machine down is refused when the job is
created rather than when it fires. scheduling.RefuseDangerousJob is the
one rule every creation path reaches: the dashboard, any control-plane
client and the config seed all replace the schedules document through the
same validator, so a new token is added in one place.
2026-10-08 22:45:28 +11:00

83 lines
2.1 KiB
Go

package controlplane
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
const SchedulesKind = "schedules"
func scheduleDefinition() Definition {
return Definition{
Kind: SchedulesKind,
Title: "Schedules",
Document: []scheduling.JobSpec{},
ApplyMode: "live",
Seed: func(config.Config) any { return []scheduling.JobSpec{} },
Validate: func(input []byte) error {
return validateAs(input, validateSchedules)
},
Normalize: normalizeSchedules,
}
}
func validateSchedules(jobs []scheduling.JobSpec) error {
seen := make(map[string]struct{}, len(jobs))
for _, job := range jobs {
if err := scheduling.RefuseDangerousJob(job); err != nil {
return err
}
if strings.TrimSpace(job.ID) == "" {
return fmt.Errorf("schedule ID is required")
}
if _, exists := seen[job.ID]; exists {
return fmt.Errorf("duplicate schedule %q", job.ID)
}
seen[job.ID] = struct{}{}
switch job.Kind {
case scheduling.KindWorkflow:
case scheduling.KindChat:
if job.Target.Channel == "" || job.Target.ChatID == "" || strings.TrimSpace(job.Payload.Text) == "" {
return fmt.Errorf("chat schedule %q needs a channel, chat ID and message", job.ID)
}
default:
return fmt.Errorf("schedule %q has unsupported kind %q", job.ID, job.Kind)
}
if err := job.Schedule.Validate(); err != nil {
return err
}
if err := scheduling.Pool(job.Pool).Validate(); err != nil {
return err
}
}
return nil
}
func normalizeSchedules(input []byte) ([]byte, error) {
var jobs []scheduling.JobSpec
if err := json.Unmarshal(input, &jobs); err != nil {
return nil, err
}
now := time.Now().UTC()
for i := range jobs {
jobs[i].Schedule = jobs[i].Schedule.Resolved()
if jobs[i].NextRun.IsZero() {
next, err := jobs[i].Schedule.FirstRun(now)
if err != nil {
return nil, err
}
jobs[i].NextRun = next.UTC()
}
if jobs[i].Created.IsZero() {
jobs[i].Created = now
}
jobs[i].Updated = now
}
return json.Marshal(jobs)
}