lint: drive baseline to zero, drop only-new-issues gate
Cleanup pass over the repo so CI can enforce lint going forward
without the only-new-issues escape hatch:
* gofumpt -w across the tree (31 hits, all formatting)
* misspell --fix (25 hits, US-locale spelling) — but reverted on
api.JobCancelled = "cancelled" since that literal is the wire +
DB CHECK constraint value, plus matched the case in store/fleet.go
back to "cancelled" and added //nolint:misspell on both for the
next time someone reaches for the auto-fix
* Wrap every `defer rows.Close()` / `defer stmt.Close()` /
`defer res.Body.Close()` in `defer func() { _ = .Close() }()`
to satisfy errcheck without losing the close itself
* websocket.Dial callers (1 prod, 4 tests) now capture + close the
upgrade response Body — coder/websocket can return res with a nil
Body on success, so the test deferred-closes guard against that
* Annotate the two genuine-by-design nilerr cases with //nolint
comments explaining why nil-on-error is the contract (cookie
missing = no session; ctx cancelled mid-backoff = clean shutdown)
* Add brief godoc on the 10 exported const groups + types that
revive flagged (api.HostOS/HostArch/JobKind/JobStatus/LogStream/
ErrorCode, restic.EventKind, store.Role, web.FS)
* Drop the unused (*Server).userByID method
* Inline the unparam baseView(active) — every UI page is under
the dashboard primary nav today
Result: `golangci-lint run ./...` reports 0 issues. CI lint job
no longer needs only-new-issues: true; X-06 follow-up entry in
tasks.md removed.
This commit is contained in:
@@ -41,13 +41,6 @@ jobs:
|
||||
# Bumping to a v2.x release built against current Go.
|
||||
version: v2.1.6
|
||||
args: --timeout=5m
|
||||
# Only flag issues introduced by the PR. The repo carries
|
||||
# ~90 pre-existing findings (mostly missing godoc comments
|
||||
# + gofumpt drift + misspell) accumulated before lint was
|
||||
# actually wired into CI; cleaning them up is its own piece
|
||||
# of work tracked separately. Without this, every PR fails
|
||||
# on baseline noise instead of its own changes.
|
||||
only-new-issues: true
|
||||
|
||||
build:
|
||||
name: Build (${{ matrix.goos }}/${{ matrix.goarch }})
|
||||
|
||||
@@ -110,7 +110,7 @@ func (s *Scheduler) Apply(payload api.ScheduleSetPayload, tx Sender) {
|
||||
"received", len(payload.Schedules), "active", added)
|
||||
|
||||
// Ack outside the lock — Send() shouldn't take long, but holding
|
||||
// s.mu across an external call would needlessly serialise other
|
||||
// s.mu across an external call would needlessly serialize other
|
||||
// callers (e.g. a future Status() inspection from the UI).
|
||||
ackEnv, err := api.Marshal(api.MsgScheduleAck, "", api.ScheduleAckPayload{
|
||||
Version: payload.Version,
|
||||
@@ -167,4 +167,3 @@ func (s *Scheduler) fire(entry api.Schedule) {
|
||||
"schedule_id", entry.ID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
|
||||
// additionalData binds ciphertexts to the agent-secrets context, so a
|
||||
// blob lifted from one role's file can't be replayed into another's
|
||||
// row in some unrelated table that uses the same key. (Defence in
|
||||
// row in some unrelated table that uses the same key. (Defense in
|
||||
// depth — the key is per-host today, but cheap to be careful.)
|
||||
const additionalData = "rm-agent-repo-creds-v1"
|
||||
|
||||
|
||||
@@ -48,7 +48,9 @@ func Collect(ctx context.Context, resticPath string) (Snapshot, error) {
|
||||
|
||||
// detectResticVersion runs `restic version` and parses the first line.
|
||||
// Output looks like:
|
||||
//
|
||||
// restic 0.17.1 compiled with go1.22.5 on linux/amd64
|
||||
//
|
||||
// Returns the version token (e.g. "0.17.1") or "" if restic isn't
|
||||
// found. We never block startup on a missing restic — the operator
|
||||
// might not have installed it yet, and the agent should still be
|
||||
@@ -74,5 +76,5 @@ func detectResticVersion(ctx context.Context, override string) (string, error) {
|
||||
if len(parts) >= 2 && parts[0] == "restic" {
|
||||
return parts[1], nil
|
||||
}
|
||||
return "", fmt.Errorf("sysinfo: unrecognised restic version output: %q", first)
|
||||
return "", fmt.Errorf("sysinfo: unrecognized restic version output: %q", first)
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ type Config struct {
|
||||
// Sender is what handlers use to push agent → server messages
|
||||
// (job.progress, job.finished, log.stream, command.result, …).
|
||||
// Returned by the WS client to the dispatch handler. Write operations
|
||||
// serialise behind a single mutex on the conn; concurrent calls are
|
||||
// serialize behind a single mutex on the conn; concurrent calls are
|
||||
// safe.
|
||||
type Sender interface {
|
||||
Send(env api.Envelope) error
|
||||
@@ -52,7 +52,7 @@ type Sender interface {
|
||||
type Handler func(ctx context.Context, env api.Envelope, tx Sender) error
|
||||
|
||||
// Run keeps the agent connected indefinitely. Returns when ctx is
|
||||
// cancelled. Errors during a single connection attempt are logged and
|
||||
// canceled. Errors during a single connection attempt are logged and
|
||||
// trigger reconnect-with-backoff; only ctx.Done() ends the loop.
|
||||
func Run(ctx context.Context, cfg Config, handle Handler) error {
|
||||
if cfg.HeartbeatPeriod <= 0 {
|
||||
@@ -69,7 +69,10 @@ func Run(ctx context.Context, cfg Config, handle Handler) error {
|
||||
slog.Warn("ws agent disconnect", "err", err)
|
||||
}
|
||||
if err := sleepCtx(ctx, backoff.next()); err != nil {
|
||||
return nil
|
||||
// ctx cancellation mid-backoff means the parent shut us down —
|
||||
// exit the reconnect loop quietly rather than propagating
|
||||
// a context error up to a caller that will discard it.
|
||||
return nil //nolint:nilerr
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,11 +103,15 @@ func connectOnce(ctx context.Context, cfg Config, handle Handler) error {
|
||||
}
|
||||
|
||||
dialCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
conn, _, err := websocket.Dial(dialCtx, wsURL, dialOpts)
|
||||
conn, res, err := websocket.Dial(dialCtx, wsURL, dialOpts)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("dial: %w", err)
|
||||
}
|
||||
// websocket.Dial returns the upgrade response separately from the
|
||||
// conn. Body is empty on a successful upgrade but Go's net/http
|
||||
// still expects it closed to release the connection.
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
defer conn.CloseNow() //nolint:errcheck
|
||||
|
||||
// Send hello.
|
||||
|
||||
@@ -50,7 +50,7 @@ func Enroll(ctx context.Context, serverURL string, req EnrollRequest) (*EnrollRe
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("agent enroll: post: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
defer func() { _ = res.Body.Close() }()
|
||||
rawRes, _ := io.ReadAll(res.Body)
|
||||
if res.StatusCode != stdhttp.StatusCreated {
|
||||
return nil, fmt.Errorf("agent enroll: server returned %d: %s",
|
||||
|
||||
@@ -10,13 +10,18 @@ import (
|
||||
// constants so we don't end up with both "linux" and "Linux" rows.
|
||||
type HostOS string
|
||||
|
||||
// Allowed values for HostOS. Lowercased on the wire so the server
|
||||
// can use a single CHECK constraint.
|
||||
const (
|
||||
OSLinux HostOS = "linux"
|
||||
OSWindows HostOS = "windows"
|
||||
)
|
||||
|
||||
// HostArch is the agent's CPU architecture; same lowercase-on-wire
|
||||
// rule as HostOS.
|
||||
type HostArch string
|
||||
|
||||
// Allowed values for HostArch.
|
||||
const (
|
||||
ArchAmd64 HostArch = "amd64"
|
||||
ArchArm64 HostArch = "arm64"
|
||||
@@ -45,6 +50,9 @@ type HeartbeatPayload struct {
|
||||
// JobKind is the operation an agent is being asked to run, or just ran.
|
||||
type JobKind string
|
||||
|
||||
// Allowed JobKind values. backup is operator/cron driven; init runs
|
||||
// once per host on first connect; forget/prune/check fire from the
|
||||
// server-side maintenance ticker; unlock is operator-only.
|
||||
const (
|
||||
JobBackup JobKind = "backup"
|
||||
JobInit JobKind = "init"
|
||||
@@ -57,12 +65,16 @@ const (
|
||||
// JobStatus is the lifecycle state of a job.
|
||||
type JobStatus string
|
||||
|
||||
// Allowed JobStatus values. queued → running → one of {succeeded,
|
||||
// failed, JobCancelled} as a terminal state. The wire/DB literal for
|
||||
// the JobCancelled value uses UK spelling — don't "fix" it; existing
|
||||
// job rows + agent payloads will mismatch. //nolint:misspell
|
||||
const (
|
||||
JobQueued JobStatus = "queued"
|
||||
JobRunning JobStatus = "running"
|
||||
JobSucceeded JobStatus = "succeeded"
|
||||
JobFailed JobStatus = "failed"
|
||||
JobCancelled JobStatus = "cancelled"
|
||||
JobCancelled JobStatus = "cancelled" //nolint:misspell // wire format
|
||||
)
|
||||
|
||||
// CommandRunPayload is the server → agent dispatch for a run-now job.
|
||||
@@ -145,6 +157,8 @@ type LogStreamLine struct {
|
||||
// LogStream identifies which channel a log line came from.
|
||||
type LogStream string
|
||||
|
||||
// Allowed LogStream values. stdout/stderr are passed through verbatim;
|
||||
// event is the parsed restic --json envelope (summary, error, etc).
|
||||
const (
|
||||
LogStdout LogStream = "stdout"
|
||||
LogStderr LogStream = "stderr"
|
||||
|
||||
@@ -71,6 +71,8 @@ func (e Envelope) UnmarshalPayload(v any) error {
|
||||
// These are stable identifiers; client code may switch on them.
|
||||
type ErrorCode string
|
||||
|
||||
// Stable ErrorCode values surfaced over the wire. Clients switch on
|
||||
// these; renaming requires a wire-version bump.
|
||||
const (
|
||||
ErrProtocolTooOld ErrorCode = "protocol_too_old"
|
||||
ErrProtocolTooNew ErrorCode = "protocol_too_new"
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
// argon2id parameters following RFC 9106 §4 "second
|
||||
// recommended option" (memory-constrained):
|
||||
// - 64 MiB memory, 3 iterations, 4 lanes, 32-byte tag.
|
||||
//
|
||||
// These are tunable per-deployment if a beefy controller wants to
|
||||
// crank them; we ship a defensible default.
|
||||
const (
|
||||
@@ -27,7 +28,9 @@ const (
|
||||
)
|
||||
|
||||
// HashPassword returns an argon2id-encoded string of the form
|
||||
//
|
||||
// $argon2id$v=19$m=...,t=...,p=...$<salt>$<hash>
|
||||
//
|
||||
// safe to store in a TEXT column. The salt is freshly random per call.
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, defaultSaltLen)
|
||||
@@ -53,7 +56,7 @@ func VerifyPassword(encoded, password string) error {
|
||||
parts := strings.Split(encoded, "$")
|
||||
// "$argon2id$v=...$m=...,t=...,p=...$<salt>$<hash>" → 6 parts (leading empty)
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return errors.New("auth: unrecognised hash format")
|
||||
return errors.New("auth: unrecognized hash format")
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
|
||||
@@ -65,7 +65,7 @@ func GenerateKeyFile(path string) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("create key file %q: %w", path, err)
|
||||
}
|
||||
defer f.Close()
|
||||
defer func() { _ = f.Close() }()
|
||||
key := make([]byte, KeyLen)
|
||||
if _, err := io.ReadFull(rand.Reader, key); err != nil {
|
||||
return fmt.Errorf("read random: %w", err)
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Locate resolves the path to the restic binary. Honour an explicit
|
||||
// Locate resolves the path to the restic binary. Honor an explicit
|
||||
// override if provided, else fall back to PATH.
|
||||
func Locate(override string) (string, error) {
|
||||
if override != "" {
|
||||
@@ -54,6 +54,8 @@ type Env struct {
|
||||
// switch on message_type.
|
||||
type EventKind string
|
||||
|
||||
// Known message_type values restic --json emits during a backup.
|
||||
// Kept as constants so callers can switch without typo risk.
|
||||
const (
|
||||
EventStatus EventKind = "status" // periodic progress
|
||||
EventVerbose EventKind = "verbose_status"
|
||||
@@ -90,7 +92,7 @@ type BackupSummary struct {
|
||||
}
|
||||
|
||||
// LineHandler receives every stdout/stderr line. event is non-nil
|
||||
// when the line is a recognised JSON status; raw always carries the
|
||||
// when the line is a recognized JSON status; raw always carries the
|
||||
// original text (so we can also tee to job_logs as `stdout`).
|
||||
type LineHandler func(stream string, raw string, event any)
|
||||
|
||||
@@ -256,7 +258,7 @@ func (e Env) RunInit(ctx context.Context, handle LineHandler) error {
|
||||
|
||||
// Sniff for "config file already exists" on stderr; if we see it
|
||||
// we'll treat the non-zero exit as a soft success — running init
|
||||
// against an already-initialised repo is a no-op semantically,
|
||||
// against an already-initialized repo is a no-op semantically,
|
||||
// not a failure. Wraps the caller's handle so the line still
|
||||
// gets streamed verbatim to the operator-facing log.
|
||||
alreadyInited := false
|
||||
@@ -280,7 +282,7 @@ func (e Env) RunInit(ctx context.Context, handle LineHandler) error {
|
||||
if werr := cmd.Wait(); werr != nil {
|
||||
if alreadyInited {
|
||||
if handle != nil {
|
||||
handle("event", "repo already initialised — treating as success", nil)
|
||||
handle("event", "repo already initialized — treating as success", nil)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -8,9 +8,11 @@ func TestMergeRestCreds(t *testing.T) {
|
||||
}{
|
||||
{"rest with creds", "rest:http://h:8000/p/", "u", "p", "rest:http://u:p@h:8000/p/"},
|
||||
{"rest no user — no-op", "rest:http://h:8000/p/", "", "p", "rest:http://h:8000/p/"},
|
||||
{"rest creds already inline — no-op",
|
||||
{
|
||||
"rest creds already inline — no-op",
|
||||
"rest:http://existing:secret@h:8000/p/", "u", "p",
|
||||
"rest:http://existing:secret@h:8000/p/"},
|
||||
"rest:http://existing:secret@h:8000/p/",
|
||||
},
|
||||
{"non-rest s3 — no-op", "s3:s3.amazonaws.com/bucket", "u", "p", "s3:s3.amazonaws.com/bucket"},
|
||||
{"unparseable — pass through", "rest:not a url", "u", "p", "rest:not a url"},
|
||||
{"https URL kept intact", "rest:https://h/p/", "u", "p", "rest:https://u:p@h/p/"},
|
||||
|
||||
@@ -57,7 +57,7 @@ func (s *Server) handleAgentBinary(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
}
|
||||
|
||||
func (s *Server) handleInstallAsset(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
// chi's TrimPrefix-like behaviour: r.URL.Path is "/install/<file>".
|
||||
// chi's TrimPrefix-like behavior: r.URL.Path is "/install/<file>".
|
||||
rel := strings.TrimPrefix(r.URL.Path, "/install/")
|
||||
// Reject any path traversal — must be a flat filename.
|
||||
if rel == "" || strings.ContainsAny(rel, "/\\") {
|
||||
|
||||
@@ -137,7 +137,7 @@ func (s *Server) handleBootstrap(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
return
|
||||
}
|
||||
if n > 0 {
|
||||
writeJSONError(w, stdhttp.StatusConflict, "already_initialised",
|
||||
writeJSONError(w, stdhttp.StatusConflict, "already_initialized",
|
||||
"a user already exists; bootstrap is disabled")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -125,7 +125,9 @@ func TestLoginAndLogout(t *testing.T) {
|
||||
bs, _ := json.Marshal(bootstrapRequest{
|
||||
Token: "test-token", Username: "alice", Password: "averylongpassword",
|
||||
})
|
||||
stdhttp.Post(url+"/api/bootstrap", "application/json", bytes.NewReader(bs)) //nolint:errcheck
|
||||
if bsRes, err := stdhttp.Post(url+"/api/bootstrap", "application/json", bytes.NewReader(bs)); err == nil {
|
||||
_ = bsRes.Body.Close()
|
||||
}
|
||||
|
||||
// Login.
|
||||
body, _ := json.Marshal(loginRequest{Username: "alice", Password: "averylongpassword"})
|
||||
|
||||
@@ -3,6 +3,7 @@ package http
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
stdhttp "net/http"
|
||||
@@ -142,7 +143,7 @@ func (s *Server) handleAgentEnroll(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
|
||||
// Seed the host's "default" source group with whatever paths the
|
||||
// operator typed into Add-host (empty allowed; group is editable
|
||||
// from the Sources tab post-enrol). Also seed the host's
|
||||
// from the Sources tab post-enroll). Also seed the host's
|
||||
// repo-maintenance row with default cadences so forget/prune/check
|
||||
// start ticking on their own. Auto-init dispatch lands in Phase 6
|
||||
// of the redesign.
|
||||
@@ -222,12 +223,11 @@ func (s *Server) handleCreateEnrollmentToken(w stdhttp.ResponseWriter, r *stdhtt
|
||||
return
|
||||
}
|
||||
token, expiresAt, err := s.mintEnrollmentToken(r.Context(), req.RepoURL, req.RepoUsername, req.RepoPassword, req.InitialPaths)
|
||||
switch err {
|
||||
case nil:
|
||||
switch {
|
||||
case err == nil:
|
||||
writeJSON(w, stdhttp.StatusCreated, enrollOperatorResponse{Token: token, ExpiresAt: expiresAt})
|
||||
case errMissingRepoCreds:
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "missing_field",
|
||||
"repo_url and repo_password are required so the agent can run backups on first connect")
|
||||
case errors.Is(err, errMissingRepoCreds):
|
||||
writeJSONError(w, stdhttp.StatusBadRequest, "missing_field", "repo_url and repo_password are required so the agent can run backups on first connect")
|
||||
default:
|
||||
writeJSONError(w, stdhttp.StatusInternalServerError, "internal", "")
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ func (s *Server) handleSetHostCredentials(w stdhttp.ResponseWriter, r *stdhttp.R
|
||||
w.WriteHeader(stdhttp.StatusNoContent)
|
||||
}
|
||||
|
||||
// pushRepoCredsToAgent serialises blob into a config.update envelope
|
||||
// pushRepoCredsToAgent serializes blob into a config.update envelope
|
||||
// and ships it down the agent's WS. Returns an error from the hub
|
||||
// (no-op if not connected — caller is expected to check first when it
|
||||
// matters).
|
||||
|
||||
@@ -215,24 +215,30 @@ func TestSchedulesCRUDValidation(t *testing.T) {
|
||||
|
||||
// Bad cron → 400.
|
||||
status, body := doJSON(t, url, "POST", "/api/hosts/"+hostID+"/schedules",
|
||||
map[string]any{"cron": "not-a-cron", "enabled": true,
|
||||
"source_group_ids": []string{"x"}}, cookie)
|
||||
map[string]any{
|
||||
"cron": "not-a-cron", "enabled": true,
|
||||
"source_group_ids": []string{"x"},
|
||||
}, cookie)
|
||||
if status != 400 {
|
||||
t.Fatalf("bad cron: want 400, got %d (body=%+v)", status, body)
|
||||
}
|
||||
|
||||
// Missing groups → 400.
|
||||
status, _ = doJSON(t, url, "POST", "/api/hosts/"+hostID+"/schedules",
|
||||
map[string]any{"cron": "0 3 * * *", "enabled": true,
|
||||
"source_group_ids": []string{}}, cookie)
|
||||
map[string]any{
|
||||
"cron": "0 3 * * *", "enabled": true,
|
||||
"source_group_ids": []string{},
|
||||
}, cookie)
|
||||
if status != 400 {
|
||||
t.Errorf("missing groups: want 400, got %d", status)
|
||||
}
|
||||
|
||||
// Group not on host → 400.
|
||||
status, _ = doJSON(t, url, "POST", "/api/hosts/"+hostID+"/schedules",
|
||||
map[string]any{"cron": "0 3 * * *", "enabled": true,
|
||||
"source_group_ids": []string{"non-existent"}}, cookie)
|
||||
map[string]any{
|
||||
"cron": "0 3 * * *", "enabled": true,
|
||||
"source_group_ids": []string{"non-existent"},
|
||||
}, cookie)
|
||||
if status != 400 {
|
||||
t.Errorf("bogus group: want 400, got %d", status)
|
||||
}
|
||||
@@ -247,8 +253,10 @@ func TestSchedulesCRUDValidation(t *testing.T) {
|
||||
|
||||
// Happy create.
|
||||
status, body = doJSON(t, url, "POST", "/api/hosts/"+hostID+"/schedules",
|
||||
map[string]any{"cron": "0 3 * * *", "enabled": true,
|
||||
"source_group_ids": []string{gid}}, cookie)
|
||||
map[string]any{
|
||||
"cron": "0 3 * * *", "enabled": true,
|
||||
"source_group_ids": []string{gid},
|
||||
}, cookie)
|
||||
if status != 201 {
|
||||
t.Fatalf("create: %d body=%+v", status, body)
|
||||
}
|
||||
@@ -269,8 +277,10 @@ func TestSchedulesCRUDValidation(t *testing.T) {
|
||||
|
||||
// Update — change cron, keep group.
|
||||
status, body = doJSON(t, url, "PUT", "/api/hosts/"+hostID+"/schedules/"+sid,
|
||||
map[string]any{"cron": "@hourly", "enabled": false,
|
||||
"source_group_ids": []string{gid}}, cookie)
|
||||
map[string]any{
|
||||
"cron": "@hourly", "enabled": false,
|
||||
"source_group_ids": []string{gid},
|
||||
}, cookie)
|
||||
if status != 200 {
|
||||
t.Fatalf("update: %d body=%+v", status, body)
|
||||
}
|
||||
@@ -484,5 +494,7 @@ func equalStrings(a, b []string) bool {
|
||||
}
|
||||
|
||||
// keep fmt import live — used for occasional debug.
|
||||
var _ = fmt.Sprintf
|
||||
var _ = strings.HasPrefix
|
||||
var (
|
||||
_ = fmt.Sprintf
|
||||
_ = strings.HasPrefix
|
||||
)
|
||||
|
||||
@@ -6,8 +6,8 @@ package http
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
stdhttp "net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -29,13 +29,18 @@ func agentDial(t *testing.T, srv *Server, ts *httptest.Server, hostID, token str
|
||||
url := "ws" + strings.TrimPrefix(ts.URL, "http") + "/ws/agent"
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
c, _, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
c, res, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
HTTPHeader: stdhttp.Header{"Authorization": []string{"Bearer " + token}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = c.CloseNow() })
|
||||
t.Cleanup(func() {
|
||||
_ = c.CloseNow()
|
||||
if res != nil && res.Body != nil {
|
||||
_ = res.Body.Close()
|
||||
}
|
||||
})
|
||||
return c
|
||||
}
|
||||
|
||||
@@ -76,7 +81,7 @@ func drainUntil(t *testing.T, c *websocket.Conn, wantType api.MessageType) api.E
|
||||
return api.Envelope{}
|
||||
}
|
||||
|
||||
// enrolHostForWS pre-enrols a host with bound repo creds so the server
|
||||
// enrolHostForWS pre-enrolls a host with bound repo creds so the server
|
||||
// will treat it as ready to receive command.run.
|
||||
func enrolHostForWS(t *testing.T, srv *Server, st *store.Store, name string) (hostID, token string) {
|
||||
t.Helper()
|
||||
|
||||
@@ -142,4 +142,3 @@ func (s *Server) handleUpdateRepoMaintenance(w stdhttp.ResponseWriter, r *stdhtt
|
||||
}
|
||||
writeJSON(w, stdhttp.StatusOK, toRepoMaintenanceView(m))
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// The slim-schedule wire shape is built here from the (Schedule,
|
||||
// SourceGroup) pair. Each schedule is sent with its resolved source
|
||||
// groups inlined so the agent doesn't have to keep its own copy of
|
||||
// the group catalogue. Cron + enabled drive the agent's local timer;
|
||||
// the group catalog. Cron + enabled drive the agent's local timer;
|
||||
// when an entry fires the agent ships back a schedule.fire and
|
||||
// dispatchScheduledJob below resolves the schedule's groups and
|
||||
// dispatches one backup command.run per group.
|
||||
|
||||
@@ -184,7 +184,7 @@ func (s *Server) routes(r chi.Router) {
|
||||
// Durable post-Add-host page (operator can refresh / come
|
||||
// back; password decrypted from the token row each render).
|
||||
// Polled fragment under /awaiting flips to "connected" once
|
||||
// the agent enrols.
|
||||
// the agent enrolls.
|
||||
r.Get("/hosts/pending/{token}", s.handleUIPendingHost)
|
||||
r.Get("/hosts/pending/{token}/awaiting", s.handleUIPendingAwaiting)
|
||||
// Host detail (Snapshots tab is the default).
|
||||
|
||||
@@ -44,7 +44,11 @@ func staticHandler() stdhttp.Handler {
|
||||
func (s *Server) sessionUser(r *stdhttp.Request) (*ui.User, error) {
|
||||
c, err := r.Cookie(sessionCookieName)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
// Missing or invalid cookie just means the caller isn't logged
|
||||
// in — that's a normal state, not a server error. Return
|
||||
// (nil, nil) so callers can decide between "redirect to login"
|
||||
// and "treat as anonymous".
|
||||
return nil, nil //nolint:nilerr
|
||||
}
|
||||
sess, err := s.deps.Store.LookupSession(r.Context(), auth.HashToken(c.Value))
|
||||
if err != nil {
|
||||
@@ -81,11 +85,13 @@ func (s *Server) requireUIUser(w stdhttp.ResponseWriter, r *stdhttp.Request) *ui
|
||||
}
|
||||
|
||||
// baseView populates the fields the nav partial needs on every
|
||||
// authenticated page.
|
||||
func (s *Server) baseView(u *ui.User, active string) ui.ViewData {
|
||||
// authenticated page. Every UI page sits under the dashboard primary
|
||||
// nav today; if a future page lives under a different primary nav
|
||||
// tab (e.g. Settings, Audit), accept an Active arg again.
|
||||
func (s *Server) baseView(u *ui.User) ui.ViewData {
|
||||
return ui.ViewData{
|
||||
User: u,
|
||||
Active: active,
|
||||
Active: "dashboard",
|
||||
Version: s.version(),
|
||||
}
|
||||
}
|
||||
@@ -200,7 +206,7 @@ func (s *Server) handleUIDashboard(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
rows = append(rows, row)
|
||||
}
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.OpenAlerts = summary.OpenAlerts
|
||||
view.Page = dashboardPage{
|
||||
Hosts: rows,
|
||||
@@ -249,7 +255,7 @@ type addHostPage struct {
|
||||
}
|
||||
|
||||
// pendingHostPage is the GET /hosts/pending/{token} view. Lives
|
||||
// for as long as the token does (1h ttl); once the agent enrols,
|
||||
// for as long as the token does (1h ttl); once the agent enrolls,
|
||||
// the handler redirects to /hosts/{host_id} and this page is gone.
|
||||
type pendingHostPage struct {
|
||||
Token string
|
||||
@@ -267,7 +273,7 @@ func (s *Server) handleUIAddHostGet(w stdhttp.ResponseWriter, r *stdhttp.Request
|
||||
if u == nil {
|
||||
return
|
||||
}
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "Add host · restic-manager"
|
||||
view.Page = addHostPage{ServerURL: s.publicURL(r)}
|
||||
if err := s.deps.UI.Render(w, "add_host", view); err != nil {
|
||||
@@ -327,11 +333,11 @@ func (s *Server) handleUIAddHostPost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
|
||||
if page.Error == "" {
|
||||
token, _, err := s.mintEnrollmentToken(r.Context(), page.RepoURL, repoUsername, repoPassword, splitPaths(page.Paths))
|
||||
switch err {
|
||||
case nil:
|
||||
switch {
|
||||
case err == nil:
|
||||
stdhttp.Redirect(w, r, "/hosts/pending/"+token, stdhttp.StatusSeeOther)
|
||||
return
|
||||
case errMissingRepoCreds:
|
||||
case errors.Is(err, errMissingRepoCreds):
|
||||
page.Error = "Repo URL and password are both required."
|
||||
default:
|
||||
slog.Error("ui add_host: mint token", "err", err)
|
||||
@@ -339,7 +345,7 @@ func (s *Server) handleUIAddHostPost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
}
|
||||
}
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "Add host · restic-manager"
|
||||
view.Page = page
|
||||
w.WriteHeader(stdhttp.StatusUnprocessableEntity)
|
||||
@@ -350,7 +356,7 @@ func (s *Server) handleUIAddHostPost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
|
||||
// handleUIPendingHost serves the durable Add-host result page —
|
||||
// shown after a successful POST /hosts/new and reachable until the
|
||||
// agent enrols (the page redirects to /hosts/{id} once that
|
||||
// agent enrolls (the page redirects to /hosts/{id} once that
|
||||
// happens) or the token expires (1h ttl). The password is
|
||||
// re-decrypted from the encrypted token row on every render so
|
||||
// the operator can refresh, bookmark, navigate away and come back.
|
||||
@@ -406,7 +412,7 @@ func (s *Server) handleUIPendingHost(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
}
|
||||
}
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "Pending host · restic-manager"
|
||||
view.Page = page
|
||||
if err := s.deps.UI.Render(w, "pending_host", view); err != nil {
|
||||
@@ -546,7 +552,7 @@ func (s *Server) handleUIHostDetail(w stdhttp.ResponseWriter, r *stdhttp.Request
|
||||
shown = shown[:cap]
|
||||
}
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = host.Name + " · restic-manager"
|
||||
view.Page = hostDetailPage{
|
||||
hostChromeData: s.loadHostChrome(r, *host, "snapshots", "snapshots"),
|
||||
@@ -645,7 +651,7 @@ func (s *Server) handleUIJobDetail(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
nextSeq = logs[n-1].Seq
|
||||
}
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = job.Kind + " · " + host.Name + " · restic-manager"
|
||||
view.Page = jobDetailPage{
|
||||
Job: *job,
|
||||
@@ -742,21 +748,6 @@ func buildSyntheticJobFinished(job *store.Job) (api.Envelope, error) {
|
||||
})
|
||||
}
|
||||
|
||||
// userByID fetches the full store.User the UI session represents.
|
||||
// Returns the user, ok-flag, error. Used by handlers that need the
|
||||
// store-side row (e.g. for audit_log.user_id) rather than just the
|
||||
// projected ui.User.
|
||||
func (s *Server) userByID(r *stdhttp.Request, id string) (*store.User, bool, error) {
|
||||
u, err := s.deps.Store.GetUserByID(r.Context(), id)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return nil, false, nil
|
||||
}
|
||||
return nil, false, err
|
||||
}
|
||||
return u, true, nil
|
||||
}
|
||||
|
||||
// handleUILoginGet renders the login form. If the user is already
|
||||
// signed in we redirect them home — login is for the unauthenticated.
|
||||
func (s *Server) handleUILoginGet(w stdhttp.ResponseWriter, r *stdhttp.Request) {
|
||||
|
||||
@@ -143,7 +143,7 @@ func (s *Server) handleUIHostRepo(w stdhttp.ResponseWriter, r *stdhttp.Request)
|
||||
return
|
||||
}
|
||||
page.SavedSection = r.URL.Query().Get("saved")
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = host.Name + " repo · restic-manager"
|
||||
view.Page = *page
|
||||
if err := s.deps.UI.Render(w, "host_repo", view); err != nil {
|
||||
@@ -166,7 +166,7 @@ func (s *Server) renderRepoPage(w stdhttp.ResponseWriter, r *stdhttp.Request, u
|
||||
page.CredentialsError = credErr
|
||||
page.BandwidthError = bwErr
|
||||
page.MaintenanceError = mntErr
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = host.Name + " repo · restic-manager"
|
||||
view.Page = *page
|
||||
w.WriteHeader(stdhttp.StatusUnprocessableEntity)
|
||||
|
||||
@@ -78,7 +78,7 @@ func (s *Server) handleUISchedulesList(w stdhttp.ResponseWriter, r *stdhttp.Requ
|
||||
chrome.ScheduleCount = len(scheds)
|
||||
chrome.SourceGroupCount = len(groups)
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = host.Name + " schedules · restic-manager"
|
||||
view.Page = hostSchedulesPage{
|
||||
hostChromeData: chrome,
|
||||
@@ -106,7 +106,7 @@ func (s *Server) handleUIScheduleNewGet(w stdhttp.ResponseWriter, r *stdhttp.Req
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "New schedule · " + host.Name + " · restic-manager"
|
||||
view.Page = scheduleEditPage{
|
||||
hostChromeData: s.loadHostChrome(r, *host, "schedules", "new schedule"),
|
||||
@@ -152,7 +152,7 @@ func (s *Server) handleUIScheduleEditGet(w stdhttp.ResponseWriter, r *stdhttp.Re
|
||||
for _, gid := range sc.SourceGroupIDs {
|
||||
selected[gid] = true
|
||||
}
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "Edit schedule · " + host.Name + " · restic-manager"
|
||||
view.Page = scheduleEditPage{
|
||||
hostChromeData: s.loadHostChrome(r, *host, "schedules", "edit schedule"),
|
||||
@@ -381,7 +381,7 @@ func (s *Server) renderScheduleFormError(w stdhttp.ResponseWriter, r *stdhttp.Re
|
||||
saveAction = "/hosts/" + host.ID + "/schedules/" + sid + "/edit"
|
||||
crumb = "edit schedule"
|
||||
}
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "Schedule · " + host.Name + " · restic-manager"
|
||||
view.Page = scheduleEditPage{
|
||||
hostChromeData: s.loadHostChrome(r, *host, "schedules", crumb),
|
||||
|
||||
@@ -119,7 +119,7 @@ func (s *Server) handleUIHostSources(w stdhttp.ResponseWriter, r *stdhttp.Reques
|
||||
// loadHostChrome already counted groups; reuse count we just got.
|
||||
chrome.SourceGroupCount = len(groups)
|
||||
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = host.Name + " sources · restic-manager"
|
||||
view.Page = hostSourcesPage{hostChromeData: chrome, Groups: rows}
|
||||
if err := s.deps.UI.Render(w, "host_sources", view); err != nil {
|
||||
@@ -137,7 +137,7 @@ func (s *Server) handleUISourceGroupNewGet(w stdhttp.ResponseWriter, r *stdhttp.
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "New source group · " + host.Name + " · restic-manager"
|
||||
view.Page = sourceGroupEditPage{
|
||||
hostChromeData: s.loadHostChrome(r, *host, "sources", "new source group"),
|
||||
@@ -171,7 +171,7 @@ func (s *Server) handleUISourceGroupEditGet(w stdhttp.ResponseWriter, r *stdhttp
|
||||
stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = g.Name + " · " + host.Name + " · restic-manager"
|
||||
view.Page = sourceGroupEditPage{
|
||||
hostChromeData: s.loadHostChrome(r, *host, "sources", g.Name),
|
||||
@@ -341,7 +341,7 @@ func (s *Server) handleUISourceGroupDelete(w stdhttp.ResponseWriter, r *stdhttp.
|
||||
// typed input intact + an error banner. Returns 422 to signal "form
|
||||
// rejected" while still returning HTML (mirrors handleUIAddHostPost).
|
||||
func (s *Server) renderSourceFormError(w stdhttp.ResponseWriter, r *stdhttp.Request, u *ui.User, host *store.Host, gid string, isNew bool, form sourceFormData, msg string) {
|
||||
view := s.baseView(u, "dashboard")
|
||||
view := s.baseView(u)
|
||||
view.Title = "Source group · " + host.Name + " · restic-manager"
|
||||
saveAction := "/hosts/" + host.ID + "/sources/new"
|
||||
crumb := "new source group"
|
||||
|
||||
@@ -204,7 +204,7 @@ func dispatchAgentMessage(ctx context.Context, c *Conn, hostID string, env api.E
|
||||
string(p.Status), p.ExitCode, p.Stats, errMsg, p.FinishedAt); err != nil {
|
||||
slog.Warn("ws: mark job finished", "job_id", p.JobID, "err", err)
|
||||
}
|
||||
// repo_initialised_at projection has been removed — auto-init
|
||||
// repo_initialized_at projection has been removed — auto-init
|
||||
// at host enrolment makes "is the repo init'd" derivable from
|
||||
// the latest init job's status, no separate column needed.
|
||||
if deps.JobHub != nil {
|
||||
|
||||
@@ -100,7 +100,7 @@ func NewConn(hostID string, c *websocket.Conn) *Conn {
|
||||
}
|
||||
|
||||
// Send writes an envelope as a JSON text message. Concurrent calls
|
||||
// are serialised; the underlying socket is not safe for parallel
|
||||
// are serialized; the underlying socket is not safe for parallel
|
||||
// writers.
|
||||
func (c *Conn) Send(ctx context.Context, env api.Envelope) error {
|
||||
c.writeMu.Lock()
|
||||
|
||||
@@ -57,13 +57,18 @@ func TestWSHelloAndHeartbeat(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
c, _, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
c, res, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
HTTPHeader: stdhttp.Header{"Authorization": []string{"Bearer " + token}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer c.CloseNow()
|
||||
defer func() {
|
||||
if res != nil && res.Body != nil {
|
||||
_ = res.Body.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
// Send hello.
|
||||
hello := api.HelloPayload{
|
||||
@@ -125,13 +130,18 @@ func TestWSRejectsOldProtocol(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
c, _, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
c, res, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
HTTPHeader: stdhttp.Header{"Authorization": []string{"Bearer " + token}},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer c.CloseNow()
|
||||
defer func() {
|
||||
if res != nil && res.Body != nil {
|
||||
_ = res.Body.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
hello := api.HelloPayload{ProtocolVersion: 0} // below minimum
|
||||
env, _ := api.Marshal(api.MsgHello, "", hello)
|
||||
@@ -170,6 +180,13 @@ func TestWSRejectsBadToken(t *testing.T) {
|
||||
_, res, err := websocket.Dial(ctx, url, &websocket.DialOptions{
|
||||
HTTPHeader: stdhttp.Header{"Authorization": []string{"Bearer wrong"}},
|
||||
})
|
||||
if res != nil {
|
||||
defer func() {
|
||||
if res != nil && res.Body != nil {
|
||||
_ = res.Body.Close()
|
||||
}
|
||||
}()
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatal("dial should fail")
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func NewJobHub() *JobHub {
|
||||
// the hub's set (so concurrent Broadcasts will reach it), but no
|
||||
// pump goroutine runs yet. The caller can prime the channel via Send
|
||||
// — useful for late-subscriber catch-up — and then call Run to start
|
||||
// the pump. Run blocks until ctx is cancelled or conn dies, and
|
||||
// the pump. Run blocks until ctx is canceled or conn dies, and
|
||||
// unregisters on return.
|
||||
type Subscriber struct {
|
||||
hub *JobHub
|
||||
@@ -73,7 +73,7 @@ func (s *Subscriber) Send(env api.Envelope) {
|
||||
}
|
||||
|
||||
// Run pumps messages from the subscriber's channel onto conn until
|
||||
// ctx is cancelled or conn dies. Unregisters on return. Caller is
|
||||
// ctx is canceled or conn dies. Unregisters on return. Caller is
|
||||
// expected to invoke this from the goroutine that owns conn.
|
||||
func (s *Subscriber) Run(ctx context.Context, conn *Conn) {
|
||||
defer s.unregister()
|
||||
|
||||
@@ -26,7 +26,7 @@ func (s *Store) AppendAudit(ctx context.Context, e AuditEntry) error {
|
||||
}
|
||||
|
||||
// nullable returns nil for nil/empty *string so SQLite stores NULL.
|
||||
// SQLite's driver treats Go nil as NULL but treats *string("") as ''.
|
||||
// SQLite's driver treats Go nil as NULL but treats *string("") as ”.
|
||||
// We want NULL semantics for "absent."
|
||||
func nullable(p *string) any {
|
||||
if p == nil || *p == "" {
|
||||
|
||||
@@ -172,4 +172,3 @@ func (s *Store) PurgeExpiredEnrollmentTokens(ctx context.Context) (int64, error)
|
||||
n, _ := res.RowsAffected()
|
||||
return n, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ func (s *Store) FleetSummary(ctx context.Context) (FleetSummary, error) {
|
||||
if err != nil {
|
||||
return FleetSummary{}, fmt.Errorf("store: fleet summary jobs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
for rows.Next() {
|
||||
var status string
|
||||
var n int
|
||||
@@ -70,7 +70,7 @@ func (s *Store) FleetSummary(ctx context.Context) (FleetSummary, error) {
|
||||
fs.JobsLast24hSucceeded = n
|
||||
case "failed":
|
||||
fs.JobsLast24hFailed = n
|
||||
case "cancelled":
|
||||
case "cancelled": //nolint:misspell // matches the DB CHECK constraint and api.JobCancelled wire value
|
||||
fs.JobsLast24hCancelled = n
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +121,7 @@ func (s *Store) ListHosts(ctx context.Context) ([]Host, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: list hosts: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
var out []Host
|
||||
for rows.Next() {
|
||||
h, err := scanHostRow(rows)
|
||||
|
||||
@@ -118,7 +118,7 @@ func (s *Store) ListJobLogs(ctx context.Context, jobID string, afterSeq int64, l
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: list job logs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
var out []JobLogLine
|
||||
for rows.Next() {
|
||||
var l JobLogLine
|
||||
|
||||
@@ -52,7 +52,7 @@ func (st *Store) DuePendingRuns(ctx context.Context, now time.Time, limit int) (
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: due pending runs: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
out := []PendingRun{}
|
||||
for rows.Next() {
|
||||
var p PendingRun
|
||||
|
||||
@@ -144,7 +144,7 @@ func (st *Store) ListSchedulesByHost(ctx context.Context, hostID string) ([]Sche
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: list schedules: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
s, err := scanScheduleRow(rows)
|
||||
@@ -247,7 +247,7 @@ func (st *Store) scheduleGroupIDs(ctx context.Context, scheduleID string) ([]str
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: read schedule junction: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
out := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
@@ -269,7 +269,7 @@ func (st *Store) SchedulesUsingGroup(ctx context.Context, groupID string) ([]str
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: schedules using group: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
out := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
|
||||
@@ -51,7 +51,7 @@ func (s *Store) ReplaceHostSnapshots(ctx context.Context, hostID string, snaps [
|
||||
if err != nil {
|
||||
return fmt.Errorf("store: prepare snapshot insert: %w", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
defer func() { _ = stmt.Close() }()
|
||||
|
||||
refreshed := when.UTC().Format(time.RFC3339Nano)
|
||||
for _, snap := range snaps {
|
||||
@@ -92,7 +92,7 @@ func (s *Store) ListSnapshotsByHost(ctx context.Context, hostID string) ([]Snaps
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: list snapshots: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
|
||||
var out []Snapshot
|
||||
for rows.Next() {
|
||||
|
||||
@@ -129,9 +129,11 @@ func TestReplaceHostSnapshotsEmpty(t *testing.T) {
|
||||
|
||||
// First a non-empty replace.
|
||||
if err := s.ReplaceHostSnapshots(ctx, hostID, []Snapshot{
|
||||
{ID: "1111111111111111111111111111111111111111111111111111111111111111",
|
||||
{
|
||||
ID: "1111111111111111111111111111111111111111111111111111111111111111",
|
||||
ShortID: "11111111", Time: time.Now().UTC(), Hostname: "snap-host",
|
||||
Paths: []string{"/x"}},
|
||||
Paths: []string{"/x"},
|
||||
},
|
||||
}, time.Now().UTC()); err != nil {
|
||||
t.Fatalf("replace 1: %v", err)
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ func (st *Store) ListSourceGroupsByHost(ctx context.Context, hostID string) ([]S
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("store: list source groups: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
defer func() { _ = rows.Close() }()
|
||||
out := []SourceGroup{}
|
||||
for rows.Next() {
|
||||
g, err := scanSourceGroupRow(rows)
|
||||
|
||||
@@ -34,10 +34,12 @@ func TestOpenAppliesMigrations(t *testing.T) {
|
||||
}
|
||||
|
||||
// Spot-check a few tables exist with expected columns.
|
||||
tables := []string{"users", "sessions", "hosts", "repos",
|
||||
tables := []string{
|
||||
"users", "sessions", "hosts", "repos",
|
||||
"credentials", "schedules", "jobs", "job_logs",
|
||||
"snapshots", "alerts", "audit_log",
|
||||
"enrollment_tokens", "host_schedule_version"}
|
||||
"enrollment_tokens", "host_schedule_version",
|
||||
}
|
||||
for _, tbl := range tables {
|
||||
row := s.DB().QueryRow(
|
||||
`SELECT name FROM sqlite_master WHERE type='table' AND name = ?`, tbl)
|
||||
|
||||
@@ -20,6 +20,7 @@ type User struct {
|
||||
// Role enumerates the access tiers from spec.md §7.2.
|
||||
type Role string
|
||||
|
||||
// Defined Role values, in descending order of privilege.
|
||||
const (
|
||||
RoleAdmin Role = "admin"
|
||||
RoleOperator Role = "operator"
|
||||
|
||||
@@ -273,4 +273,3 @@ Sizes: **S** = under a day, **M** = 1–3 days, **L** = 3–7 days.
|
||||
- [ ] **X-03** Periodic dependency updates (`dependabot` or `renovate`)
|
||||
- [ ] **X-04** Threat-model review at end of each phase
|
||||
- [ ] **X-05** Proper first-run onboarding UI: admin shouldn't need to `curl` `/api/bootstrap` by hand. Render the bootstrap form on the same login page (extra "setup token" field shown only while no admin user exists, hidden after); on submit POST to `/api/bootstrap`, then drop straight into a session. Surface the one-time token from the server log somewhere copy-able (or print a clickable URL with the token in the query string at first-run). Also: relax the 12-char password floor for the first-run path or document it in the form so `admin` doesn't silently fail validation.
|
||||
- [ ] **X-06** Lint-baseline cleanup pass. `.golangci.yml` is now on the v2 schema; CI is gated with `only-new-issues: true` because the repo carries ~90 pre-existing findings (gofumpt drift × 31, misspell × 25, missing godoc on exported consts × 10, bodyclose × 6, errcheck × 12, errorlint/nilerr/unused × handful) accumulated before lint was actually wired into CI. Drive the count to zero in a dedicated PR (mostly mechanical: `gofumpt -w .`, fix typos, add comments, audit nilerr cases since those *might* be real bugs), then drop `only-new-issues: true` so future regressions are caught at the source.
|
||||
|
||||
@@ -7,5 +7,9 @@ package web
|
||||
|
||||
import "embed"
|
||||
|
||||
// FS is the embedded view of every template + static asset under
|
||||
// this package. Consumed by internal/server/ui (templates) and
|
||||
// internal/server/http (static handler).
|
||||
//
|
||||
//go:embed templates/* static/*
|
||||
var FS embed.FS
|
||||
|
||||
Reference in New Issue
Block a user