Files
restic-manager/internal/api/messages.go
T
steve c275f4ff4c phase 1 foundations: api types, store, crypto, auth
Lands the bottom three layers of Phase 1:

P1-08 internal/api: protocol_version + envelope + every WS message
  shape from spec.md §6.2 (Hello, Heartbeat, Job*, Schedule*, etc).
  Wire-format tests pin the JSON shape so a rename here breaks
  tests instead of silently breaking the agent.

P1-02 + P1-03 internal/store: SQLite via modernc.org/sqlite,
  embed.FS + a tiny version table for hand-rolled migrations.
  0001_initial.sql covers every table from spec.md §5 plus
  enrollment_tokens and host_schedule_version. Typed accessors
  for users / sessions / enrollment / audit. WAL + foreign_keys
  + busy_timeout on by default.

P1-06 internal/crypto: XChaCha20-Poly1305 AEAD wrapper with
  per-message random nonce. Key file lifecycle (generate +
  refuse-to-overwrite, load with size validation). Optional
  additionalData binds ciphertext to the row that owns it.

P1-04 internal/auth (partial — passwords + tokens; sessions
  middleware lands with the HTTP handlers): argon2id following
  RFC 9106 (64 MiB / t=3 / p=4 / 32B), constant-time verify.
  HashToken stores SHA-256 of session/agent/enrollment tokens
  so a stolen DB doesn't hand over credentials.

Build floor moves to Go 1.25 (modernc.org/sqlite v1.50+ requires
it); CI + Dockerfile + README updated. Markdown lint diagnostics
on tasks.md cleared.

All packages tested. ~70 new tests pass in <1s.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 00:24:40 +01:00

214 lines
7.3 KiB
Go

package api
import (
"encoding/json"
"time"
)
// HostOS / HostArch are constrained string types. The store stores them
// raw, but agent metadata collection should populate them from these
// constants so we don't end up with both "linux" and "Linux" rows.
type HostOS string
const (
OSLinux HostOS = "linux"
OSWindows HostOS = "windows"
)
type HostArch string
const (
ArchAmd64 HostArch = "amd64"
ArchArm64 HostArch = "arm64"
)
// HelloPayload is the agent's first message after WS auth. The server
// upserts a Host row, marks it online, and (if protocol_version is
// acceptable) responds with a config.update + schedule.set burst.
type HelloPayload struct {
ProtocolVersion int `json:"protocol_version"`
AgentVersion string `json:"agent_version"`
ResticVersion string `json:"restic_version"`
Hostname string `json:"hostname"`
OS HostOS `json:"os"`
Arch HostArch `json:"arch"`
BootTime time.Time `json:"boot_time,omitempty"`
}
// HeartbeatPayload is sent by the agent every 30s. It carries no data
// today; presence is the signal. Future fields (load, free disk) can
// land here without bumping protocol_version.
type HeartbeatPayload struct {
SentAt time.Time `json:"sent_at"`
}
// JobKind is the operation an agent is being asked to run, or just ran.
type JobKind string
const (
JobBackup JobKind = "backup"
JobForget JobKind = "forget"
JobPrune JobKind = "prune"
JobCheck JobKind = "check"
JobUnlock JobKind = "unlock"
)
// JobStatus is the lifecycle state of a job.
type JobStatus string
const (
JobQueued JobStatus = "queued"
JobRunning JobStatus = "running"
JobSucceeded JobStatus = "succeeded"
JobFailed JobStatus = "failed"
JobCancelled JobStatus = "cancelled"
)
// CommandRunPayload is the server → agent dispatch for a run-now job.
type CommandRunPayload struct {
JobID string `json:"job_id"`
Kind JobKind `json:"kind"`
Args []string `json:"args,omitempty"`
}
// CommandCancelPayload is the server → agent cancel signal.
type CommandCancelPayload struct {
JobID string `json:"job_id"`
}
// CommandResultPayload acks a command.run dispatch (the agent has
// accepted the job and persisted it locally) — this is *not* the job
// completion. job.finished signals that.
type CommandResultPayload struct {
JobID string `json:"job_id"`
Accepted bool `json:"accepted"`
Error string `json:"error,omitempty"`
}
// JobStartedPayload — agent has begun execution.
type JobStartedPayload struct {
JobID string `json:"job_id"`
Kind JobKind `json:"kind"`
StartedAt time.Time `json:"started_at"`
}
// JobProgressPayload — agent's periodic status while a job is running.
// Field set chosen to match what restic --json emits for `backup`;
// other kinds populate the subset that makes sense.
type JobProgressPayload struct {
JobID string `json:"job_id"`
PercentDone float64 `json:"percent_done"`
FilesDone int64 `json:"files_done"`
TotalFiles int64 `json:"total_files"`
BytesDone int64 `json:"bytes_done"`
TotalBytes int64 `json:"total_bytes"`
ETASeconds int64 `json:"eta_seconds"`
ThroughputBps int64 `json:"throughput_bps"`
}
// JobFinishedPayload — agent reports terminal state.
type JobFinishedPayload struct {
JobID string `json:"job_id"`
Status JobStatus `json:"status"`
ExitCode int `json:"exit_code"`
FinishedAt time.Time `json:"finished_at"`
Stats json.RawMessage `json:"stats,omitempty"` // restic summary blob
Error string `json:"error,omitempty"`
}
// LogStreamLine is one entry of the live job log.
type LogStreamLine struct {
JobID string `json:"job_id"`
Seq int64 `json:"seq"`
TS time.Time `json:"ts"`
Stream LogStream `json:"stream"`
Payload string `json:"payload"`
}
// LogStream identifies which channel a log line came from.
type LogStream string
const (
LogStdout LogStream = "stdout"
LogStderr LogStream = "stderr"
LogEvent LogStream = "event" // parsed restic --json event
)
// SnapshotsReportPayload — agent dumps its full snapshot list after
// each successful backup, so the server can refresh its projection.
type SnapshotsReportPayload struct {
Snapshots []Snapshot `json:"snapshots"`
}
// Snapshot is the projection mirrored from `restic snapshots --json`.
type Snapshot struct {
ID string `json:"id"` // restic snapshot ID
Time time.Time `json:"time"`
Hostname string `json:"hostname"`
Paths []string `json:"paths"`
Tags []string `json:"tags,omitempty"`
SizeBytes int64 `json:"size_bytes,omitempty"`
FileCount int64 `json:"file_count,omitempty"`
}
// RepoStatsPayload — agent reports periodic repo health facts derived
// from `restic stats` and lock-file inspection.
type RepoStatsPayload struct {
SizeBytes int64 `json:"size_bytes"`
SnapshotCount int `json:"snapshot_count"`
DedupRatio float64 `json:"dedup_ratio"`
LastCheckAt time.Time `json:"last_check_at,omitempty"`
LastCheckStatus string `json:"last_check_status,omitempty"`
LockState string `json:"lock_state"` // locked|unlocked
}
// Schedule is the agent-facing view of a Schedule row. (Server-side
// CRUD shapes live in the http handlers; this is what gets pushed.)
type Schedule struct {
ID string `json:"id"`
Kind JobKind `json:"kind"`
CronExpr string `json:"cron_expr"`
Paths []string `json:"paths,omitempty"`
Excludes []string `json:"excludes,omitempty"`
Tags []string `json:"tags,omitempty"`
RetentionPolicy json.RawMessage `json:"retention_policy,omitempty"`
Options json.RawMessage `json:"options,omitempty"`
PreHook string `json:"pre_hook,omitempty"`
PostHook string `json:"post_hook,omitempty"`
Enabled bool `json:"enabled"`
}
// ScheduleSetPayload — server pushes the full canonical schedule list
// for a host. Agent reconciles its local cron and replies with
// ScheduleAckPayload carrying the same Version.
type ScheduleSetPayload struct {
Version int64 `json:"version"`
Schedules []Schedule `json:"schedules"`
}
// ScheduleAckPayload — agent confirms it has applied a given version.
type ScheduleAckPayload struct {
Version int64 `json:"version"`
AppliedAt time.Time `json:"applied_at"`
}
// ConfigUpdatePayload — server pushes per-host config (currently just
// repo connection details). Empty fields mean "leave existing alone";
// to clear something, send an explicit zero value.
type ConfigUpdatePayload struct {
RepoURL string `json:"repo_url,omitempty"`
RepoPassword string `json:"repo_password,omitempty"` // sensitive
RepoUsername string `json:"repo_username,omitempty"`
RepoCredential string `json:"repo_credential,omitempty"` // sensitive (for rest server basic auth)
HookShell string `json:"hook_shell,omitempty"`
}
// AgentUpdateAvailablePayload — informational only; the agent does
// NOT self-update. See spec.md §4.2 for the package-manager-based
// update model.
type AgentUpdateAvailablePayload struct {
LatestVersion string `json:"latest_version"`
PackageURL string `json:"package_url"` // apt repo / choco source
Changelog string `json:"changelog,omitempty"`
}