Skip to content

Modern Docker Management, Designed for Everyone

chore: fix code with new linter style

Kyle Mendell47a560566c96
diff --git a/.depot/workflows/ci.yml b/.depot/workflows/ci.yml
index 8723b0863..af314dbb9 100644
--- a/.depot/workflows/ci.yml
+++ b/.depot/workflows/ci.yml
@@ -89,11 +89,11 @@ jobs:
matrix:
module:
- name: backend
- args: --build-tags=exclude_frontend --config=../.github/.golangci.yml
+ args: --build-tags=exclude_frontend --config=../.golangci.yml
- name: cli
- args: --config=../.github/.golangci.yml
+ args: --config=../.golangci.yml
- name: types
- args: --config=../.github/.golangci.yml
+ args: --config=../.golangci.yml
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
diff --git a/.github/.golangci.yml b/.github/.golangci.yml
deleted file mode 100644
index e860247a0..000000000
--- a/.github/.golangci.yml
+++ /dev/null
@@ -1,130 +0,0 @@
-version: "2"
-run:
- tests: false
- timeout: 5m
-linters:
- default: none
- enable:
- - shimbad
- - arangolint
- - asasalint
- - asciicheck
- - bidichk
- - bodyclose
- - clickhouselint
- - contextcheck
- - copyloopvar
- - decorder
- - dupl
- - dupword
- - durationcheck
- - embeddedstructfieldcheck
- - errcheck
- - errchkjson
- - errname
- - errorlint
- - exhaustive
- - exptostd
- - fatcontext
- - forcetypeassert
- - ginkgolinter
- - gocheckcompilerdirectives
- - gochecksumtype
- - gocognit
- - gocritic
- - gocyclo
- - godoclint
- - goheader
- - gomoddirectives
- - gomodguard_v2
- - goprintffuncname
- - gosec
- - gosmopolitan
- - govet
- - grouper
- - iface
- - inamedparam
- - ineffassign
- - interfacebloat
- - intrange
- - iotamixing
- - loggercheck
- - maintidx
- - makezero
- - mirror
- - misspell
- - modernize
- - musttag
- - nakedret
- - nilerr
- - nilnesserr
- - noctx
- - nolintlint
- - nosprintfhostport
- - perfsprint
- - prealloc
- - predeclared
- - promlinter
- - protogetter
- - reassign
- - recvcheck
- - revive
- - rowserrcheck
- - sloglint
- - spancheck
- - sqlclosecheck
- - staticcheck
- - testableexamples
- - testifylint
- - unconvert
- - unparam
- - unqueryvet
- - unused
- - usestdlibvars
- - usetesting
- - wastedassign
- - whitespace
- - zerologlint
- settings:
- grouper:
- const-require-single-const: true
- custom:
- shimbad:
- type: module
- description: Detects suspicious Go function implementations.
- original-url: https://go.ofkm.dev/shimbad
- gomoddirectives:
- replace-local: true
- replace-allow-list:
- # Copacetic v0.14.2 only compiles against the buildx v0.32 imagetools
- # API; drop once copa supports buildx >= 0.35 and the pin is removed.
- - github.com/docker/buildx
- exclusions:
- generated: lax
- presets:
- - comments
- - common-false-positives
- - legacy
- - std-error-handling
- rules:
- - linters:
- - revive
- text: "var-naming:"
- - linters:
- - revive
- text: "unused-parameter:"
- - linters:
- - revive
- text: "exported:"
- # Endpoint path builders are intentional one-line functions.
- - linters:
- - shimbad
- path: internal/types/endpoints\.go
-issues:
- max-issues-per-linter: 0
- max-same-issues: 0
-formatters:
- enable:
- - gofumpt
- exclusions:
- generated: lax
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index daf8cba6e..74fe471ef 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -92,11 +92,11 @@ jobs:
matrix:
module:
- name: backend
- args: --build-tags=exclude_frontend --config=../.github/.golangci.yml
+ args: --build-tags=exclude_frontend --config=../.golangci.yml
- name: cli
- args: --config=../.github/.golangci.yml
+ args: --config=../.golangci.yml
- name: types
- args: --config=../.github/.golangci.yml
+ args: --config=../.golangci.yml
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
diff --git a/.golangci.yml b/.golangci.yml
index fad6f7578..0eb5c7870 100644
--- a/.golangci.yml
+++ b/.golangci.yml
@@ -1,4 +1,4 @@
-# Slightly Modified Version docker's golangci lint configuration to fit my project standards
+# Slightly Modified Version of docker's golangci lint configuration to fit arcanes standards
version: "2"
run:
@@ -25,7 +25,6 @@ formatters:
settings:
gci:
sections:
- # Include Go 1.27 packages missing from gci's built-in standard-library list.
- prefix(arena,archive/,bufio,bytes,cmp,compress/,container/,context,crypto,database/,debug/,embed,encoding,errors,expvar,flag,fmt,go/,hash,html,image,index/,io,iter,log,maps,math,mime,net,os,path,plugin,reflect,regexp,runtime,slices,sort,strconv,strings,structs,sync,syscall,testing,text/,time,unicode,unique,unsafe,uuid,weak)
- default
- localmodule
@@ -81,12 +80,6 @@ linters:
desc: Use stdlib uuid instead.
- pkg: "gopkg.in/yaml.v3"
desc: Use go.yaml.in/yaml/v4 instead.
- - pkg: github.com/stretchr/testify/assert
- desc: Use "gotest.tools/v3/assert" instead
- - pkg: github.com/stretchr/testify/require
- desc: Use "gotest.tools/v3/assert" instead
- - pkg: github.com/stretchr/testify/suite
- desc: Do not use
forbidigo:
analyze-types: true
diff --git a/Justfile b/Justfile
index 2d92caf64..22004ce3a 100644
--- a/Justfile
+++ b/Justfile
@@ -224,6 +224,7 @@ _format_go:
#!/usr/bin/env bash
set -euo pipefail
for module in {{ modules }}; do
+ echo "Formatting Go module: ${module} (gci + gofumpt)"
(cd "$module" && gci write --skip-generated --skip-vendor --custom-order -s "{{ go_stdlib_section }}" -s default -s localmodule .)
gofumpt -w -extra "$module"
done
diff --git a/backend/api/api.go b/backend/api/api.go
index 9b337f5aa..faeb32b02 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -128,7 +128,7 @@ func customSchemaNamer(t reflect.Type, hint string) string {
if pkgName, ok := arcanePackageName(pkgPath); ok {
name = pkgName + name
- } else if dockerPrefix, ok := dockerSchemaPrefix(pkgPath, shortPkg); ok {
+ } else if dockerPrefix, localOk := dockerSchemaPrefix(pkgPath, shortPkg); localOk {
name = dockerPrefix + name
}
return qualifyGenericArcaneArgumentsInternal(pkgPath, typeStr, name)
@@ -397,7 +397,7 @@ func SetupAPIForSpec() huma.API {
// Register handlers with zero-value dependencies for schema discovery only.
registerNormalizationInternal(api)
- registerHandlersInternal(api, HandlerDeps{}, handlerutil.NewActivityAppContext(context.Background()), nil)
+ registerHandlersInternal(api, HandlerDeps{}, handlerutil.NewActivityAppContext(context.Background()), nil) //nolint:forbidigo // Schema discovery has no running request or application lifecycle.
return api
}
diff --git a/backend/api/api_test.go b/backend/api/api_test.go
index c3bfdcc22..202c61f23 100644
--- a/backend/api/api_test.go
+++ b/backend/api/api_test.go
@@ -2,7 +2,6 @@ package api
import (
"bytes"
- "context"
"net/http"
"reflect"
"sort"
@@ -341,7 +340,7 @@ func TestVariableMaterializationRoutesAreAgentOnly(t *testing.T) {
agentAPI := SetupAPI(
router,
router.Group("/api"),
- handlerutil.NewActivityAppContext(context.Background()),
+ handlerutil.NewActivityAppContext(t.Context()),
&config.Config{AgentMode: true},
HandlerDeps{},
)
diff --git a/backend/api/json_serializer.go b/backend/api/json_serializer.go
index af2f72bf8..721a537d9 100644
--- a/backend/api/json_serializer.go
+++ b/backend/api/json_serializer.go
@@ -28,8 +28,8 @@ func (jsonV2Serializer) Serialize(c *echo.Context, value any, indent string) err
func (jsonV2Serializer) Deserialize(c *echo.Context, value any) error {
err := json.UnmarshalRead(c.Request().Body, value, jsonV2APIOptions)
if err == nil {
- if err := normalization.Normalize(value); err != nil {
- return echo.NewHTTPError(http.StatusUnprocessableEntity, err.Error()).Wrap(err)
+ if normalizeErr := normalization.Normalize(value); normalizeErr != nil {
+ return echo.NewHTTPError(http.StatusUnprocessableEntity, normalizeErr.Error()).Wrap(normalizeErr)
}
return nil
}
diff --git a/backend/api/json_serializer_benchmark_test.go b/backend/api/json_serializer_benchmark_test.go
index f707f8c40..2b6047090 100644
--- a/backend/api/json_serializer_benchmark_test.go
+++ b/backend/api/json_serializer_benchmark_test.go
@@ -72,8 +72,8 @@ func BenchmarkJSONRequestDecoding(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
var output jsonBenchmarkResponse
- if err := jsonv1.NewDecoder(bytes.NewReader(data)).Decode(&output); err != nil {
- require.FailNowf(b, "benchmark JSON decoding failed", "%v", err)
+ if decodeErr := jsonv1.NewDecoder(bytes.NewReader(data)).Decode(&output); decodeErr != nil {
+ require.FailNowf(b, "benchmark JSON decoding failed", "%v", decodeErr)
}
}
})
@@ -82,8 +82,8 @@ func BenchmarkJSONRequestDecoding(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
var output jsonBenchmarkResponse
- if err := jsonv2.UnmarshalRead(bytes.NewReader(data), &output, jsonV2APIOptions); err != nil {
- require.FailNowf(b, "benchmark JSON decoding failed", "%v", err)
+ if unmarshalReadErr := jsonv2.UnmarshalRead(bytes.NewReader(data), &output, jsonV2APIOptions); unmarshalReadErr != nil {
+ require.FailNowf(b, "benchmark JSON decoding failed", "%v", unmarshalReadErr)
}
}
})
diff --git a/backend/api/json_serializer_test.go b/backend/api/json_serializer_test.go
index fb2bc7382..c0747b5e7 100644
--- a/backend/api/json_serializer_test.go
+++ b/backend/api/json_serializer_test.go
@@ -20,7 +20,7 @@ func TestJSONV2SerializerUsesV2ResponseSemantics(t *testing.T) {
e := echo.New()
recorder := httptest.NewRecorder()
- context := e.NewContext(httptest.NewRequest("GET", "/", nil), recorder)
+ context := e.NewContext(httptest.NewRequest("GET", "/", http.NoBody), recorder)
err := (jsonV2Serializer{}).Serialize(context, response{}, "")
@@ -41,7 +41,7 @@ func TestJSONV2SerializerPreservesDurationNanoseconds(t *testing.T) {
e := echo.New()
recorder := httptest.NewRecorder()
- context := e.NewContext(httptest.NewRequest("GET", "/", nil), recorder)
+ context := e.NewContext(httptest.NewRequest("GET", "/", http.NoBody), recorder)
err := (jsonV2Serializer{}).Serialize(context, response{HeartbeatPeriod: 5 * time.Second}, "")
diff --git a/backend/api/normalization.go b/backend/api/normalization.go
index d77c10a62..f3ef0c3d0 100644
--- a/backend/api/normalization.go
+++ b/backend/api/normalization.go
@@ -120,8 +120,8 @@ func readNormalizationBodyInternal(ctx huma.Context) ([]byte, error) {
}
} else if op.BodyReadTimeout > 0 {
defer func() {
- if err := controller.SetReadDeadline(time.Time{}); err != nil {
- slog.WarnContext(ctx.Context(), "failed to clear request body read deadline", "error", err)
+ if setReadDeadlineErr := controller.SetReadDeadline(time.Time{}); setReadDeadlineErr != nil {
+ slog.WarnContext(ctx.Context(), "failed to clear request body read deadline", "error", setReadDeadlineErr)
}
}()
}
diff --git a/backend/api/normalization_test.go b/backend/api/normalization_test.go
index fe46f1140..5d322b405 100644
--- a/backend/api/normalization_test.go
+++ b/backend/api/normalization_test.go
@@ -52,7 +52,11 @@ func TestNormalizationBeforeHumaValidation(t *testing.T) {
registerNormalizationInternal(api)
called := false
var received normalizationTestBody
- huma.Register(api, huma.Operation{OperationID: "normalize", Method: http.MethodPost, Path: "/normalize"}, func(_ context.Context, input *struct{ Body normalizationTestBody }) (*struct{ Body normalizationTestBody }, error) {
+ huma.Register(api, huma.Operation{
+ OperationID: "normalize",
+ Method: http.MethodPost,
+ Path: "/normalize",
+ }, func(_ context.Context, input *struct{ Body normalizationTestBody }) (*struct{ Body normalizationTestBody }, error) {
called = true
received = input.Body
return &struct{ Body normalizationTestBody }{Body: input.Body}, nil
@@ -86,12 +90,21 @@ func TestNormalizationBeforeHumaValidation(t *testing.T) {
api := humaecho.New(router, huma.DefaultConfig("test", "1"))
registerNormalizationInternal(api)
var received usertypes.CreateUser
- huma.Register(api, huma.Operation{OperationID: "create", Method: http.MethodPost, Path: "/create"}, func(_ context.Context, input *struct{ Body usertypes.CreateUser }) (*struct{}, error) {
+ huma.Register(api, huma.Operation{
+ OperationID: "create",
+ Method: http.MethodPost,
+ Path: "/create",
+ }, func(_ context.Context, input *struct{ Body usertypes.CreateUser }) (*struct{}, error) {
received = input.Body
return &struct{}{}, nil
})
recorder := httptest.NewRecorder()
- request := httptest.NewRequest(http.MethodPost, "/create", strings.NewReader(`{"username":" Jose\u0301 ","email":" Jose\[email protected] ","displayName":" Jose\u0301 ","password":" password "}`))
+ request := httptest.NewRequest(
+ http.MethodPost,
+ "/create",
+ strings.NewReader("{\"username\":\" Jose\\u0301 \",\"email\":\" Jose\\[email protected] \",\"displayName\":\" Jose\\u0301 \",\"password"+
+ "\":\" password \"}"),
+ )
router.ServeHTTP(recorder, request)
require.Equal(t, http.StatusNoContent, recorder.Code, recorder.Body.String())
require.Equal(t, " Jose\u0301 ", received.Username)
@@ -100,7 +113,11 @@ func TestNormalizationBeforeHumaValidation(t *testing.T) {
require.Equal(t, " password ", received.Password)
var login authtypes.Login
- huma.Register(api, huma.Operation{OperationID: "login", Method: http.MethodPost, Path: "/login"}, func(_ context.Context, input *struct{ Body authtypes.Login }) (*struct{}, error) {
+ huma.Register(api, huma.Operation{
+ OperationID: "login",
+ Method: http.MethodPost,
+ Path: "/login",
+ }, func(_ context.Context, input *struct{ Body authtypes.Login }) (*struct{}, error) {
login = input.Body
return &struct{}{}, nil
})
@@ -117,7 +134,12 @@ func TestNormalizationBodyLimits(t *testing.T) {
router := echo.New()
api := humaecho.New(router, huma.DefaultConfig("test", "1"))
registerNormalizationInternal(api)
- huma.Register(api, huma.Operation{OperationID: "limit", Method: http.MethodPost, Path: "/limit", MaxBodyBytes: 32}, func(_ context.Context, _ *struct{ Body normalizationTestBody }) (*struct{}, error) {
+ huma.Register(api, huma.Operation{
+ OperationID: "limit",
+ Method: http.MethodPost,
+ Path: "/limit",
+ MaxBodyBytes: 32,
+ }, func(_ context.Context, _ *struct{ Body normalizationTestBody }) (*struct{}, error) {
t.Fatal("oversized body must not reach application code")
return nil, nil
})
@@ -198,7 +220,12 @@ func TestNormalizationReadTimeout(t *testing.T) {
api := humaecho.New(router, huma.DefaultConfig("test", "1"))
registerNormalizationInternal(api)
called := false
- huma.Register(api, huma.Operation{OperationID: "timeout", Method: http.MethodPost, Path: "/timeout", BodyReadTimeout: tc.timeout}, func(_ context.Context, _ *struct{ Body normalizationTestBody }) (*struct{}, error) {
+ huma.Register(api, huma.Operation{
+ OperationID: "timeout",
+ Method: http.MethodPost,
+ Path: "/timeout",
+ BodyReadTimeout: tc.timeout,
+ }, func(_ context.Context, _ *struct{ Body normalizationTestBody }) (*struct{}, error) {
called = true
return &struct{}{}, nil
})
@@ -207,7 +234,7 @@ func TestNormalizationReadTimeout(t *testing.T) {
if !tc.readTimeout {
body.body = strings.NewReader(`{"name":"x"}`)
}
- request := httptest.NewRequest(http.MethodPost, "/timeout", nil)
+ request := httptest.NewRequest(http.MethodPost, "/timeout", http.NoBody)
request.Body = body
router.ServeHTTP(recorder, request)
require.Equal(t, tc.status, recorder.Code, recorder.Body.String())
diff --git a/backend/api/ws/container_stats.go b/backend/api/ws/container_stats.go
index f4dfc5191..154a9ba46 100644
--- a/backend/api/ws/container_stats.go
+++ b/backend/api/ws/container_stats.go
@@ -42,11 +42,10 @@ func (h *WebSocketHandler) ContainerStats(c *echo.Context) error {
// A reconnect can land exactly on the 5s idle-teardown boundary and load a
// hub whose Run has already exited. Drop that hub and retry once so the
// client gets a live producer instead of a silent socket.
- // WebSocket connections use context.Background() because they are long-lived and should not
- // be tied to the HTTP request context. Cleanup is handled by the shared hub when it idles.
+ // The hub owns connection cleanup; preserve request values without request cancellation.
for attempt := range 2 {
hub := h.getOrCreateContainerStatsHubInternal(containerID)
- if wshub.ServeClientWithOnRemove(context.Background(), hub, conn, onRemove) {
+ if wshub.ServeClientWithOnRemove(context.WithoutCancel(c.Request().Context()), hub, conn, onRemove) {
return nil
}
h.containerStatsHubs.CompareAndDelete(containerID, hub)
@@ -62,7 +61,7 @@ func (h *WebSocketHandler) ContainerStats(c *echo.Context) error {
func (h *WebSocketHandler) getOrCreateContainerStatsHubInternal(containerID string) *wshub.Hub {
if existing, ok := h.containerStatsHubs.Load(containerID); ok {
- if hub, ok := existing.(*wshub.Hub); ok {
+ if hub, localOk := existing.(*wshub.Hub); localOk {
return hub
}
}
@@ -87,7 +86,7 @@ func (h *WebSocketHandler) getOrCreateContainerStatsHubInternal(containerID stri
const containerStatsErrorDrainGrace = 2 * time.Second
func (h *WebSocketHandler) runContainerStatsHubInternal(containerID string, hub *wshub.Hub) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(context.Background()) //nolint:forbidigo // Shared stats hubs own their lifecycle and idle cancellation across requests.
var cleanupTimer *time.Timer
var cleanupTimerMu sync.Mutex
diff --git a/backend/api/ws/diagnostics.go b/backend/api/ws/diagnostics.go
index 0453dfa09..51bd1e5d9 100644
--- a/backend/api/ws/diagnostics.go
+++ b/backend/api/ws/diagnostics.go
@@ -85,8 +85,8 @@ func (h *WebSocketHandler) DiagnosticsStream(c *echo.Context) error {
return nil
}
defer func() {
- if err := conn.CloseNow(); err != nil {
- slog.Debug("Failed to close diagnostics websocket connection", "error", err)
+ if closeNowErr := conn.CloseNow(); closeNowErr != nil {
+ slog.Debug("Failed to close diagnostics websocket connection", "error", closeNowErr)
}
}()
@@ -132,8 +132,8 @@ func (h *WebSocketHandler) ServerLogsStream(c *echo.Context) error {
return nil
}
defer func() {
- if err := conn.CloseNow(); err != nil {
- slog.Debug("Failed to close server logs websocket connection", "error", err)
+ if closeNowErr := conn.CloseNow(); closeNowErr != nil {
+ slog.Debug("Failed to close server logs websocket connection", "error", closeNowErr)
}
}()
diff --git a/backend/api/ws/exec.go b/backend/api/ws/exec.go
index d84559215..05ca5a7d4 100644
--- a/backend/api/ws/exec.go
+++ b/backend/api/ws/exec.go
@@ -81,10 +81,10 @@ func (h *WebSocketHandler) runContainerExecInternal(ctx context.Context, cancel
// the session is what unblocks it.
cleanup := sync.OnceFunc(func() {
slog.Debug("Cleaning up exec session", "execID", execID, "containerID", containerID, "contextErr", ctx.Err())
- cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cleanupCancel()
- if err := execSession.Close(cleanupCtx); err != nil { //nolint:contextcheck
- slog.Warn("Failed to clean up exec session", "execID", execID, "error", err)
+ if closeErr := execSession.Close(cleanupCtx); closeErr != nil { //nolint:contextcheck
+ slog.Warn("Failed to clean up exec session", "execID", execID, "error", closeErr)
}
})
defer cleanup()
@@ -159,8 +159,8 @@ func (h *WebSocketHandler) pipeExecOutputInternal(ctx context.Context, conn *web
return
}
if n > 0 {
- if err := conn.Write(ctx, websocket.MessageBinary, buf[:n]); err != nil {
- done <- fmt.Errorf("websocket write: %w", err)
+ if writeErr := conn.Write(ctx, websocket.MessageBinary, buf[:n]); writeErr != nil {
+ done <- fmt.Errorf("websocket write: %w", writeErr)
return
}
}
@@ -174,8 +174,8 @@ func (h *WebSocketHandler) pipeExecInputInternal(ctx context.Context, cancel con
cancel(fmt.Errorf("websocket read: %w", err))
return
}
- if _, err := stdin.Write(data); err != nil {
- cancel(fmt.Errorf("exec input write: %w", err))
+ if _, writeErr := stdin.Write(data); writeErr != nil {
+ cancel(fmt.Errorf("exec input write: %w", writeErr))
return
}
}
diff --git a/backend/api/ws/log_streams.go b/backend/api/ws/log_streams.go
index 48946b35a..a47b09018 100644
--- a/backend/api/ws/log_streams.go
+++ b/backend/api/ws/log_streams.go
@@ -155,10 +155,8 @@ func (h *WebSocketHandler) serveLogStreamInternal(
unregister()
h.releaseLogStreamInternal(streamKey, stream)
}
- // WebSocket connections use context.Background() because they are long-lived and should not
- // be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
- // which triggers when all clients disconnect.
- if !wshub.ServeClientWithOnRemove(context.Background(), stream.hub, conn, release) {
+ // The hub owns connection cleanup; preserve request values without request cancellation.
+ if !wshub.ServeClientWithOnRemove(context.WithoutCancel(c.Request().Context()), stream.hub, conn, release) {
// The stream refcount normally keeps this hub alive, so a stopped hub
// here means it was torn down out from under us; drop our reference
// rather than leaking the connection and the metrics entry.
@@ -247,7 +245,7 @@ func newWSLogStreamInternal(key, format string) (*wsLogStream, context.Context)
close(ls.firstSubscriber)
})
- ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec // cancel is intentionally retained and invoked by the hub OnEmpty callback.
+ ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec,forbidigo // Shared log hubs own their lifecycle and idle cancellation across requests.
ls.cancel = cancel
go ls.hub.Run(ctx)
diff --git a/backend/api/ws/system_stats.go b/backend/api/ws/system_stats.go
index 3ef229a8c..cf29e772c 100644
--- a/backend/api/ws/system_stats.go
+++ b/backend/api/ws/system_stats.go
@@ -468,8 +468,8 @@ func (h *WebSocketHandler) SystemStats(c *echo.Context) error {
if err != nil {
return err
}
- wctx, cancel := context.WithTimeout(ctx, 10*time.Second)
- defer cancel()
+ wctx, localCancel := context.WithTimeout(ctx, 10*time.Second)
+ defer localCancel()
return conn.Write(wctx, websocket.MessageText, b)
}
diff --git a/backend/api/ws/system_stats_test.go b/backend/api/ws/system_stats_test.go
index 7d16040d1..e03dabc3e 100644
--- a/backend/api/ws/system_stats_test.go
+++ b/backend/api/ws/system_stats_test.go
@@ -79,7 +79,7 @@ func TestSystemStatsSamplerRearmsOnFasterSubscriber(t *testing.T) {
},
}
- ctx := context.Background()
+ ctx := t.Context()
slow := time.Hour
require.True(t, h.acquireSystemStatsSamplerInternal(ctx, slow))
defer h.releaseSystemStatsSamplerInternal(slow)
diff --git a/backend/cli/admin/reset_mfa.go b/backend/cli/admin/reset_mfa.go
index e54a886cf..5152b6d4c 100644
--- a/backend/cli/admin/reset_mfa.go
+++ b/backend/cli/admin/reset_mfa.go
@@ -58,7 +58,7 @@ func runResetMFACommandInternal(cmd *cobra.Command, _ []string) error {
}()
userService := user.NewUserService(db, nil)
- user, err := userService.GetUserByUsername(cmd.Context(), username)
+ localUser, err := userService.GetUserByUsername(cmd.Context(), username)
if err != nil {
if errors.Is(err, common.ErrUserNotFound) {
return fmt.Errorf("user %q not found", username)
@@ -67,12 +67,12 @@ func runResetMFACommandInternal(cmd *cobra.Command, _ []string) error {
}
passkeyService := passkey.NewPasskeyService(db, cfg)
- if err := passkeyService.ResetMFAForUser(cmd.Context(), user.ID); err != nil {
- return fmt.Errorf("failed to reset passkey MFA: %w", err)
+ if resetMFAForUserErr := passkeyService.ResetMFAForUser(cmd.Context(), localUser.ID); resetMFAForUserErr != nil {
+ return fmt.Errorf("failed to reset passkey MFA: %w", resetMFAForUserErr)
}
- if _, err := fmt.Fprintf(cmd.OutOrStdout(), "Passkey MFA reset successfully for %q\n", username); err != nil {
- return fmt.Errorf("failed to write MFA reset result: %w", err)
+ if _, fprintfErr := fmt.Fprintf(cmd.OutOrStdout(), "Passkey MFA reset successfully for %q\n", username); fprintfErr != nil {
+ return fmt.Errorf("failed to write MFA reset result: %w", fprintfErr)
}
return nil
}
diff --git a/backend/cli/admin/reset_mfa_test.go b/backend/cli/admin/reset_mfa_test.go
index bee43bfc1..d67250b03 100644
--- a/backend/cli/admin/reset_mfa_test.go
+++ b/backend/cli/admin/reset_mfa_test.go
@@ -2,7 +2,6 @@ package admin
import (
"bytes"
- "context"
"testing"
"time"
@@ -54,7 +53,7 @@ func TestConfirmMFAResetInternal(t *testing.T) {
func TestResetMFACommandServiceStatePreservesPasskey(t *testing.T) {
db := newResetMFATestDBInternal(t)
- ctx := context.Background()
+ ctx := t.Context()
user := &common.User{
ID: "mfa-reset-user",
Username: "alice",
diff --git a/backend/cli/admin/reset_password.go b/backend/cli/admin/reset_password.go
index 62a146a10..3ffd4d2db 100644
--- a/backend/cli/admin/reset_password.go
+++ b/backend/cli/admin/reset_password.go
@@ -77,12 +77,12 @@ func runResetPasswordCommandInternal(cmd *cobra.Command, _ []string) error {
return err
}
- if err := resetPasswordInternal(cmd.Context(), db, username, password, policy); err != nil {
- return err
+ if resetPasswordErr := resetPasswordInternal(cmd.Context(), db, username, password, policy); resetPasswordErr != nil {
+ return resetPasswordErr
}
- if _, err := fmt.Fprintf(cmd.OutOrStdout(), "Password reset successfully for global administrator %q\n", username); err != nil {
- return fmt.Errorf("failed to write password reset result: %w", err)
+ if _, fprintfErr := fmt.Fprintf(cmd.OutOrStdout(), "Password reset successfully for global administrator %q\n", username); fprintfErr != nil {
+ return fmt.Errorf("failed to write password reset result: %w", fprintfErr)
}
return nil
}
@@ -108,8 +108,8 @@ func readNewPasswordInternal(out io.Writer, policy string) (string, error) {
return "", fmt.Errorf("failed to read password confirmation: %w", err)
}
- if err := validatePasswordPairInternal(password, confirmation, policy); err != nil {
- return "", err
+ if validatePasswordPairErr := validatePasswordPairInternal(password, confirmation, policy); validatePasswordPairErr != nil {
+ return "", validatePasswordPairErr
}
return password, nil
}
@@ -175,8 +175,8 @@ func resetPasswordInternal(ctx context.Context, db *database.DB, username, passw
return fmt.Errorf("user %q does not have effective global administrator permissions", username)
}
- if _, err := userService.SetPasswordAndRevokeSessionsExcept(ctx, target, password, ""); err != nil {
- return fmt.Errorf("failed to reset password: %w", err)
+ if _, setPasswordAndRevokeSessionsExceptErr := userService.SetPasswordAndRevokeSessionsExcept(ctx, target, password, ""); setPasswordAndRevokeSessionsExceptErr != nil {
+ return fmt.Errorf("failed to reset password: %w", setPasswordAndRevokeSessionsExceptErr)
}
return nil
diff --git a/backend/cli/admin/reset_password_test.go b/backend/cli/admin/reset_password_test.go
index df5aad004..bd266c837 100644
--- a/backend/cli/admin/reset_password_test.go
+++ b/backend/cli/admin/reset_password_test.go
@@ -1,7 +1,6 @@
package admin
import (
- "context"
"testing"
"time"
@@ -39,9 +38,9 @@ func newResetPasswordTestDBInternal(t *testing.T) *database.DB {
return db
}
-func createGlobalAdminInternal(t *testing.T, db *database.DB) (*common.User, *role.RoleService, *user.UserService) {
+func createGlobalAdminInternal(t *testing.T, db *database.DB) (*common.User, *user.UserService) {
t.Helper()
- ctx := context.Background()
+ ctx := t.Context()
roleService := role.NewRoleService(db)
require.NoError(t, roleService.EnsureBuiltInRoles(ctx))
userService := user.NewUserService(db, roleService)
@@ -58,13 +57,13 @@ func createGlobalAdminInternal(t *testing.T, db *database.DB) (*common.User, *ro
{RoleID: authz.BuiltInRoleAdmin},
}))
- return adminUser, roleService, userService
+ return adminUser, userService
}
func TestResetPasswordInternalResetsPasswordAndRevokesSessions(t *testing.T) {
db := newResetPasswordTestDBInternal(t)
- ctx := context.Background()
- adminUser, _, userService := createGlobalAdminInternal(t, db)
+ ctx := t.Context()
+ adminUser, userService := createGlobalAdminInternal(t, db)
sessionService := session.NewSessionService(db)
firstSession, _, err := sessionService.CreateSession(ctx, adminUser.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
require.NoError(t, err)
@@ -89,10 +88,10 @@ func TestResetPasswordInternalResetsPasswordAndRevokesSessions(t *testing.T) {
func TestResetPasswordInternalRollsBackWhenSessionRevocationFails(t *testing.T) {
db := newResetPasswordTestDBInternal(t)
- ctx := context.Background()
- adminUser, _, userService := createGlobalAdminInternal(t, db)
+ ctx := t.Context()
+ adminUser, userService := createGlobalAdminInternal(t, db)
sessionService := session.NewSessionService(db)
- session, _, err := sessionService.CreateSession(ctx, adminUser.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
+ localSession, _, err := sessionService.CreateSession(ctx, adminUser.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
require.NoError(t, err)
require.NoError(t, db.Exec(`
CREATE TRIGGER fail_user_session_revocation
@@ -111,15 +110,15 @@ func TestResetPasswordInternalRollsBackWhenSessionRevocationFails(t *testing.T)
require.NoError(t, err)
require.NoError(t, userService.ValidatePassword(unchangedUser.PasswordHash, "old-password"))
require.True(t, unchangedUser.RequiresPasswordChange)
- unchangedSession, err := sessionService.GetSessionByID(ctx, session.ID)
+ unchangedSession, err := sessionService.GetSessionByID(ctx, localSession.ID)
require.NoError(t, err)
require.Nil(t, unchangedSession.RevokedAt)
}
func TestResetPasswordInternalRejectsNonAdmin(t *testing.T) {
db := newResetPasswordTestDBInternal(t)
- ctx := context.Background()
- _, _, userService := createGlobalAdminInternal(t, db)
+ ctx := t.Context()
+ _, userService := createGlobalAdminInternal(t, db)
passwordHash, err := userService.HashPassword("old-password")
require.NoError(t, err)
nonAdmin, err := userService.CreateUser(ctx, &common.User{
diff --git a/backend/cli/config_schema.go b/backend/cli/config_schema.go
index 00e50f640..dcdfcf62c 100644
--- a/backend/cli/config_schema.go
+++ b/backend/cli/config_schema.go
@@ -39,8 +39,8 @@ var configSchemaCmd = &cobra.Command{
}
if outputFile != "" {
- if err := atomic.WriteFile(outputFile, output, 0o600); err != nil {
- cmd.PrintErrf("Error writing file: %v\n", err)
+ if writeFileErr := atomic.WriteFile(outputFile, output, 0o600); writeFileErr != nil {
+ cmd.PrintErrf("Error writing file: %v\n", writeFileErr)
os.Exit(1)
}
cmd.PrintErrf("Config schema written to %s\n", outputFile)
diff --git a/backend/cli/generate/secret_test.go b/backend/cli/generate/secret_test.go
index 28943875c..821d44c2f 100644
--- a/backend/cli/generate/secret_test.go
+++ b/backend/cli/generate/secret_test.go
@@ -69,8 +69,8 @@ func TestSecretDefaultBase64(t *testing.T) {
require.NotContains(t, out, "JWT_SECRET",
"JWT_SECRET is no longer emitted, got: %q", out)
- if b, err := base64.StdEncoding.DecodeString(encVal); err != nil {
- require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY is not valid base64: %v (value=%q)", err, encVal)
+ if b, decodeStringErr := base64.StdEncoding.DecodeString(encVal); decodeStringErr != nil {
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY is not valid base64: %v (value=%q)", decodeStringErr, encVal)
} else if len(b) != 32 {
require.Len(t, b, 32,
"ENCRYPTION_KEY decoded length != 32 bytes: %d", len(b))
@@ -121,8 +121,8 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
require.NotContains(t, out, "JWT_SECRET",
"JWT_SECRET is no longer emitted, got: %q", out)
- if b, err := hex.DecodeString(strings.TrimSpace(hexEnc)); err != nil {
- require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY hex decode failed: %v", err)
+ if b, decodeStringErr := hex.DecodeString(strings.TrimSpace(hexEnc)); decodeStringErr != nil {
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY hex decode failed: %v", decodeStringErr)
} else if len(b) != 32 {
require.Len(t, b, 32,
"ENCRYPTION_KEY hex decoded length != 32: %d", len(b))
diff --git a/backend/cli/health.go b/backend/cli/health.go
index 5e869220d..fb55e855a 100644
--- a/backend/cli/health.go
+++ b/backend/cli/health.go
@@ -75,7 +75,7 @@ func runHealthCommandInternal(ctx context.Context, cfg *config.Config, timeout t
return err
}
- request, err := http.NewRequestWithContext(ctx, http.MethodHead, healthURL, nil)
+ request, err := http.NewRequestWithContext(ctx, http.MethodHead, healthURL, http.NoBody)
if err != nil {
return fmt.Errorf("health check request creation failed: %w", err)
}
diff --git a/backend/cli/health_test.go b/backend/cli/health_test.go
index 12b67c6ce..131512737 100644
--- a/backend/cli/health_test.go
+++ b/backend/cli/health_test.go
@@ -1,8 +1,6 @@
package cli
import (
- "context"
- "fmt"
"net/http"
"net/http/httptest"
"strconv"
@@ -82,7 +80,7 @@ func TestRunHealthCommandInternal(t *testing.T) {
cfg := &config.Config{Port: port}
{
- err := runHealthCommandInternal(context.Background(), cfg, 2*time.Second)
+ err := runHealthCommandInternal(t.Context(), cfg, 2*time.Second)
require.NoError(t, err,
"health command failed: %v", err)
}
@@ -104,7 +102,7 @@ func TestRunHealthCommandInternalNon2xx(t *testing.T) {
}
cfg := &config.Config{Port: port}
- err := runHealthCommandInternal(context.Background(), cfg, 2*time.Second)
+ err := runHealthCommandInternal(t.Context(), cfg, 2*time.Second)
require.Error(t, err,
"expected non-2xx response to fail")
@@ -114,14 +112,14 @@ func TestRunHealthCommandInternalNon2xx(t *testing.T) {
}
func TestRunHealthCommandInternalConnectionFailure(t *testing.T) {
- err := runHealthCommandInternal(context.Background(), &config.Config{Port: "1"}, 200*time.Millisecond)
+ err := runHealthCommandInternal(t.Context(), &config.Config{Port: "1"}, 200*time.Millisecond)
require.Error(t, err,
"expected connection failure")
}
func TestRunHealthCommandInternalDefaultTimeoutFallback(t *testing.T) {
- err := runHealthCommandInternal(context.Background(), &config.Config{Port: "1"}, 0)
+ err := runHealthCommandInternal(t.Context(), &config.Config{Port: "1"}, 0)
require.Error(t, err,
"expected connection failure")
@@ -131,6 +129,6 @@ func TestRunHealthCommandInternalDefaultTimeoutFallback(t *testing.T) {
// Ensure timeout path is exercised by checking the string formatting path.
- require.Contains(t, fmt.Sprint(defaultHealthTimeout), "5s",
+ require.Contains(t, defaultHealthTimeout.String(), "5s",
"unexpected default timeout: %s", defaultHealthTimeout)
}
diff --git a/backend/cli/openapi.go b/backend/cli/openapi.go
index 1b35be80c..5ce0f92fe 100644
--- a/backend/cli/openapi.go
+++ b/backend/cli/openapi.go
@@ -42,8 +42,8 @@ var openapiCmd = &cobra.Command{
// Write to file or stdout
if outputFile != "" {
- if err := atomic.WriteFile(outputFile, output, 0o600); err != nil {
- cmd.PrintErrf("Error writing file: %v\n", err)
+ if writeFileErr := atomic.WriteFile(outputFile, output, 0o600); writeFileErr != nil {
+ cmd.PrintErrf("Error writing file: %v\n", writeFileErr)
os.Exit(1)
}
cmd.PrintErrf("OpenAPI spec written to %s\n", outputFile)
diff --git a/backend/cli/recovery/recovery.go b/backend/cli/recovery/recovery.go
index c4ddb8065..7848aaf3e 100644
--- a/backend/cli/recovery/recovery.go
+++ b/backend/cli/recovery/recovery.go
@@ -49,15 +49,15 @@ func init() {
RestoreCmd.Flags().StringVar(&requestPath, "request", "/app/data/.arcane-recovery-request.json", "Prepared recovery request")
}
-func runRestoreInternal(_ *cobra.Command, _ []string) error {
- ctx := context.Background()
+func runRestoreInternal(cmd *cobra.Command, _ []string) error {
+ ctx := cmd.Context()
data, err := os.ReadFile(requestPath)
if err != nil {
return fmt.Errorf("read recovery request: %w", err)
}
var request recoverytypes.RestoreRequest
- if err := json.Unmarshal(data, &request); err != nil {
- return fmt.Errorf("decode recovery request: %w", err)
+ if unmarshalErr := json.Unmarshal(data, &request); unmarshalErr != nil {
+ return fmt.Errorf("decode recovery request: %w", unmarshalErr)
}
_ = os.Remove(requestPath)
if len(request.Stages) == 0 {
@@ -72,7 +72,7 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {
if err != nil {
return fmt.Errorf("inspect Arcane container: %w", err)
}
- if _, err := dockerClient.ImageInspect(ctx, rusticImage); err != nil {
+ if _, imageInspectErr := dockerClient.ImageInspect(ctx, rusticImage); imageInspectErr != nil {
reader, pullErr := dockerClient.ImagePull(ctx, rusticImage, client.ImagePullOptions{})
if pullErr != nil {
return fmt.Errorf("pull Arcane tools image for Rustic: %w", pullErr)
@@ -83,19 +83,19 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {
}
_ = reader.Close()
}
- if _, err := dockerClient.ContainerStop(ctx, request.ContainerID, client.ContainerStopOptions{Timeout: new(30)}); err != nil {
- return fmt.Errorf("stop Arcane container: %w", err)
+ if _, containerStopErr := dockerClient.ContainerStop(ctx, request.ContainerID, client.ContainerStopOptions{Timeout: new(30)}); containerStopErr != nil {
+ return fmt.Errorf("stop Arcane container: %w", containerStopErr)
}
restart := func() { _, _ = dockerClient.ContainerStart(ctx, request.ContainerID, client.ContainerStartOptions{}) }
- if err := runStagesInternal(ctx, dockerClient, request, request.Stages); err != nil {
+ if runStagesErr := runStagesInternal(ctx, dockerClient, request, request.Stages); runStagesErr != nil {
// Arcane restarts only when the rollback succeeds; otherwise it stays
// stopped rather than running with mismatched data and projects.
- err = fmt.Errorf("rustic system restore failed: %w", err)
+ runStagesErr = fmt.Errorf("rustic system restore failed: %w", runStagesErr)
if len(request.RollbackStages) == 0 {
- return errors.Join(err, errors.New("no pre-restore system backup is available for rollback; Arcane was left stopped"))
+ return errors.Join(runStagesErr, errors.New("no pre-restore system backup is available for rollback; Arcane was left stopped"))
}
if rollbackErr := runStagesInternal(context.WithoutCancel(ctx), dockerClient, request, request.RollbackStages); rollbackErr != nil {
- return errors.Join(err, fmt.Errorf("restoring the pre-restore system backup failed; Arcane was left stopped: %w", rollbackErr))
+ return errors.Join(runStagesErr, fmt.Errorf("restoring the pre-restore system backup failed; Arcane was left stopped: %w", rollbackErr))
}
rollbackManifest, readErr := os.ReadFile("/app/data/.arcane-recovery.json")
var rollback recoverytypes.Manifest
@@ -106,10 +106,10 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {
readErr = francis.ClearRestoredHosts(context.WithoutCancel(ctx), rollback.Environment["DATABASE_URL"])
}
if readErr != nil {
- return errors.Join(err, fmt.Errorf("clear restored actor ownership; Arcane was left stopped: %w", readErr))
+ return errors.Join(runStagesErr, fmt.Errorf("clear restored actor ownership; Arcane was left stopped: %w", readErr))
}
restart()
- return fmt.Errorf("%w; the pre-restore system backup was restored", err)
+ return fmt.Errorf("%w; the pre-restore system backup was restored", runStagesErr)
}
if !request.ProjectsIncluded {
slog.Warn("the restored system backup did not include the projects directory; the current projects directory was left untouched")
@@ -120,9 +120,9 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {
return fmt.Errorf("read restored recovery manifest: %w", err)
}
var manifest recoverytypes.Manifest
- if err := json.Unmarshal(manifestData, &manifest); err != nil {
+ if unmarshalErr2 := json.Unmarshal(manifestData, &manifest); unmarshalErr2 != nil {
restart()
- return fmt.Errorf("decode restored recovery manifest: %w", err)
+ return fmt.Errorf("decode restored recovery manifest: %w", unmarshalErr2)
}
_ = os.Remove("/app/data/.arcane-recovery.json")
if (manifest.FormatVersion != 1 && manifest.FormatVersion != recoverytypes.ManifestFormatVersion) || len(manifest.Environment) == 0 {
@@ -132,11 +132,11 @@ func runRestoreInternal(_ *cobra.Command, _ []string) error {
// Projects were restored into the current directory, so the recovered
// configuration must keep pointing there rather than at the backup-time path.
manifest.Environment["PROJECTS_DIRECTORY"] = cmp.Or(request.ProjectsSetting, manifest.Environment["PROJECTS_DIRECTORY"])
- if err := finalizeRestoredBackupInternal(ctx, manifest.Environment["DATABASE_URL"], manifest.BackupID, manifest.ActivityID, request); err != nil {
- return fmt.Errorf("finalize restored system backup: %w", err)
+ if finalizeRestoredBackupErr := finalizeRestoredBackupInternal(ctx, manifest.Environment["DATABASE_URL"], manifest.BackupID, manifest.ActivityID, request); finalizeRestoredBackupErr != nil {
+ return fmt.Errorf("finalize restored system backup: %w", finalizeRestoredBackupErr)
}
- if err := upgrade.UpgradeContainer(ctx, dockerClient, inspect.Container, request.ContainerImage, manifest.Environment); err != nil {
- return fmt.Errorf("recreate Arcane container with recovered configuration: %w", err)
+ if upgradeContainerErr := upgrade.UpgradeContainer(ctx, dockerClient, inspect.Container, request.ContainerImage, manifest.Environment); upgradeContainerErr != nil {
+ return fmt.Errorf("recreate Arcane container with recovered configuration: %w", upgradeContainerErr)
}
return nil
}
@@ -159,23 +159,23 @@ func finalizeRestoredBackupInternal(ctx context.Context, databaseURL, manifestBa
}
}()
db = db.WithContext(ctx)
- if err := finalizeRestoredRunInternal(db, manifestBackupID, request); err != nil {
- return err
+ if finalizeRestoredRunErr := finalizeRestoredRunInternal(db, manifestBackupID, request); finalizeRestoredRunErr != nil {
+ return finalizeRestoredRunErr
}
- if err := preserveSafetyBackupInternal(db, request.SafetyBackup); err != nil {
- return err
+ if preserveSafetyBackupErr := preserveSafetyBackupInternal(db, request.SafetyBackup); preserveSafetyBackupErr != nil {
+ return preserveSafetyBackupErr
}
// Keep the restored database pointing at the directory projects were restored into.
if value := strings.TrimSpace(request.ProjectsSetting); value != "" {
- err := db.Model(&settings.SettingVariable{}).
+ operationErr := db.Model(&settings.SettingVariable{}).
Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "key"}}, DoUpdates: clause.Assignments(map[string]any{"value": value})}).
Create(map[string]any{"key": "projectsDirectory", "value": value}).Error
- if err != nil {
- return err
+ if operationErr != nil {
+ return operationErr
}
}
- if err := finalizeRestoredActivityInternal(db, manifestActivityID); err != nil {
- return err
+ if finalizeRestoredActivityErr := finalizeRestoredActivityInternal(db, manifestActivityID); finalizeRestoredActivityErr != nil {
+ return finalizeRestoredActivityErr
}
return francis.ClearRestoredHosts(ctx, databaseURL)
}
diff --git a/backend/cli/recovery/recovery_test.go b/backend/cli/recovery/recovery_test.go
index e64cf1b4d..e3d281b04 100644
--- a/backend/cli/recovery/recovery_test.go
+++ b/backend/cli/recovery/recovery_test.go
@@ -1,7 +1,6 @@
package recovery
import (
- "context"
"path/filepath"
"testing"
"time"
@@ -49,7 +48,7 @@ func newRestoredDatabaseForTestInternal(t *testing.T, runIDs ...string) (string,
func TestFinalizeRestoredBackupInternal(t *testing.T) {
databaseURL, dsn := newRestoredDatabaseForTestInternal(t, "older", "selected")
- require.NoError(t, finalizeRestoredBackupInternal(context.Background(), databaseURL, "selected", "activity-1", recoverytypes.RestoreRequest{
+ require.NoError(t, finalizeRestoredBackupInternal(t.Context(), databaseURL, "selected", "activity-1", recoverytypes.RestoreRequest{
BackupID: "request-id", RemoteSnapshotID: "snapshot-1", S3DestinationID: "destination-1", Size: 1234,
ProjectsSetting: "/srv/projects",
SafetyBackup: &recoverytypes.SafetyBackup{
@@ -84,7 +83,7 @@ func TestFinalizeRestoredBackupInternal(t *testing.T) {
func TestFinalizeRestoredBackupInternalFallsBackForLegacyManifest(t *testing.T) {
databaseURL, dsn := newRestoredDatabaseForTestInternal(t, "older", "newest")
- require.NoError(t, finalizeRestoredBackupInternal(context.Background(), databaseURL, "", "", recoverytypes.RestoreRequest{BackupID: "missing-discovery-id"}))
+ require.NoError(t, finalizeRestoredBackupInternal(t.Context(), databaseURL, "", "", recoverytypes.RestoreRequest{BackupID: "missing-discovery-id"}))
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
require.NoError(t, err)
@@ -97,6 +96,6 @@ func TestFinalizeRestoredBackupInternalFallsBackForLegacyManifest(t *testing.T)
}
func TestRunStagesInternalRejectsStagesWithoutDestination(t *testing.T) {
- err := runStagesInternal(context.Background(), nil, recoverytypes.RestoreRequest{}, []recoverytypes.RestoreStage{{SourcePath: "/data"}})
+ err := runStagesInternal(t.Context(), nil, recoverytypes.RestoreRequest{}, []recoverytypes.RestoreStage{{SourcePath: "/data"}})
require.ErrorContains(t, err, "restore stage for /data has no destination")
}
diff --git a/backend/cli/root.go b/backend/cli/root.go
index 634388653..5073fb200 100644
--- a/backend/cli/root.go
+++ b/backend/cli/root.go
@@ -31,7 +31,7 @@ var rootCmd = &cobra.Command{
}
func Execute() {
- ctx := signals.SignalContext(context.Background())
+ ctx := signals.SignalContext(context.Background()) //nolint:forbidigo // Process entry point creates the signal-controlled application context.
err := rootCmd.ExecuteContext(ctx)
if err != nil {
diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.go
index 25ba15c59..6eb9bc4a7 100644
--- a/backend/cli/upgrade/upgrade.go
+++ b/backend/cli/upgrade/upgrade.go
@@ -60,7 +60,7 @@ func init() {
func runUpgrade(cmd *cobra.Command, args []string) error {
// Use background context instead of command context to ignore signals
// This prevents interruption when stopping the target container
- ctx := context.Background()
+ ctx := context.WithoutCancel(cmd.Context())
logFile, err := SetupMessageOnlyLogFile(libarcane.UpgradeLogDirectory, "arcane-upgrade", slog.LevelInfo)
if err != nil {
@@ -103,8 +103,8 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
// Pull the new image
slog.Info("Pulling new image", "image", imageToPull)
- if err := pullImage(ctx, dockerClient, imageToPull); err != nil {
- return fmt.Errorf("failed to pull image: %w", err)
+ if pullImageErr := pullImage(ctx, dockerClient, imageToPull); pullImageErr != nil {
+ return fmt.Errorf("failed to pull image: %w", pullImageErr)
}
// The pull always runs so a mutable tag gets re-resolved, but when it lands on
@@ -118,8 +118,8 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
// Perform the upgrade
slog.Info("Starting container upgrade", "container", containerName)
- if err := UpgradeContainer(ctx, dockerClient, targetContainer, imageToPull, nil); err != nil {
- return fmt.Errorf("failed to upgrade container: %w", err)
+ if upgradeContainerErr := UpgradeContainer(ctx, dockerClient, targetContainer, imageToPull, nil); upgradeContainerErr != nil {
+ return fmt.Errorf("failed to upgrade container: %w", upgradeContainerErr)
}
slog.Info("Upgrade completed successfully", "container", containerName, "image", imageToPull)
@@ -146,8 +146,8 @@ func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (cont
continue
}
- inspectResult, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})
- if err != nil {
+ inspectResult, containerInspectWithCompatibilityErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, c.ID, client.ContainerInspectOptions{})
+ if containerInspectWithCompatibilityErr != nil {
continue
}
inspect := inspectResult.Container
@@ -539,15 +539,15 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta
fmt.Println("PROGRESS:65:Renaming old container")
slog.Info("Renaming old container", "from", originalName, "to", oldName)
- if _, err := dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: oldName}); err != nil {
- return fmt.Errorf("rename old container: %w", err)
+ if _, containerRenameErr := dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: oldName}); containerRenameErr != nil {
+ return fmt.Errorf("rename old container: %w", containerRenameErr)
}
fmt.Println("PROGRESS:70:Stopping old container")
slog.Info("Stopping old container", "name", oldName)
- if _, err := dockerClient.ContainerStop(ctx, oldContainer.ID, client.ContainerStopOptions{Timeout: new(10)}); err != nil {
+ if _, containerStopErr := dockerClient.ContainerStop(ctx, oldContainer.ID, client.ContainerStopOptions{Timeout: new(10)}); containerStopErr != nil {
_, _ = dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: originalName})
- return fmt.Errorf("stop old container: %w", err)
+ return fmt.Errorf("stop old container: %w", containerStopErr)
}
fmt.Println("PROGRESS:75:Creating new container")
@@ -567,12 +567,12 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta
fmt.Println("PROGRESS:80:Starting new container")
slog.Info("Starting new container", "id", resp.ID[:12])
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
// Cleanup new container and restart old one
_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})
_, _ = dockerClient.ContainerStart(ctx, oldContainer.ID, client.ContainerStartOptions{})
_, _ = dockerClient.ContainerRename(ctx, oldContainer.ID, client.ContainerRenameOptions{NewName: originalName})
- return fmt.Errorf("start new container: %w", err)
+ return fmt.Errorf("start new container: %w", containerStartErr)
}
// Wait a moment for the new container to initialize
@@ -582,8 +582,8 @@ func UpgradeContainer(ctx context.Context, dockerClient *client.Client, oldConta
fmt.Println("PROGRESS:90:Removing old container")
slog.Info("Removing old container", "id", oldContainer.ID[:12])
- if _, err := dockerClient.ContainerRemove(ctx, oldContainer.ID, client.ContainerRemoveOptions{}); err != nil {
- slog.Warn("Failed to remove old container", "error", err)
+ if _, containerRemoveErr := dockerClient.ContainerRemove(ctx, oldContainer.ID, client.ContainerRemoveOptions{}); containerRemoveErr != nil {
+ slog.Warn("Failed to remove old container", "error", containerRemoveErr)
}
fmt.Println("PROGRESS:95:Upgrade complete")
@@ -601,12 +601,12 @@ func applyRecoveredEnvironmentInternal(current []string, recovered map[string]st
continue
}
if baseName, ok := strings.CutSuffix(name, "__FILE"); ok {
- if _, ok := recovered[baseName]; ok {
+ if _, localOk := recovered[baseName]; localOk {
continue
}
}
if baseName, ok := strings.CutSuffix(name, "_FILE"); ok {
- if _, ok := recovered[baseName]; ok {
+ if _, localOk2 := recovered[baseName]; localOk2 {
continue
}
}
diff --git a/backend/cli/upgrade/upgrade_test.go b/backend/cli/upgrade/upgrade_test.go
index 17f35b6b1..abdfccfa2 100644
--- a/backend/cli/upgrade/upgrade_test.go
+++ b/backend/cli/upgrade/upgrade_test.go
@@ -1,7 +1,6 @@
package upgrade
import (
- "context"
"net/http"
"net/http/httptest"
"strings"
@@ -153,7 +152,7 @@ func TestRefreshRecreatedContainerLabelsInternalPreservesLabelsWhenTargetInspect
}
got := refreshRecreatedContainerLabelsInternal(
- context.Background(),
+ t.Context(),
dockerClient,
containerLabels,
"sha256:old-image",
@@ -194,7 +193,7 @@ func TestRefreshRecreatedContainerLabelsInternalPreservesOverridesWhenPreviousIn
}
got := refreshRecreatedContainerLabelsInternal(
- context.Background(),
+ t.Context(),
dockerClient,
containerLabels,
"sha256:old-image",
diff --git a/backend/internal/activity/handler.go b/backend/internal/activity/handler.go
index 9f298ecf0..ac780049c 100644
--- a/backend/internal/activity/handler.go
+++ b/backend/internal/activity/handler.go
@@ -82,10 +82,10 @@ type CancelActivityInput struct {
RequestedBy string `query:"requestedBy" doc:"Display name to attribute the cancellation to (used when proxying to a remote environment)"`
}
-func NewHandler(activityService *ActivityService, environment EnvironmentDependencies) *ActivityHandler {
+func NewHandler(activityService *ActivityService, localEnvironment EnvironmentDependencies) *ActivityHandler {
return &ActivityHandler{
activityService: activityService,
- environment: environment,
+ environment: localEnvironment,
remoteStreamHub: agg.NewHub[activitytypes.StreamEvent](),
}
}
@@ -189,9 +189,9 @@ func (h *ActivityHandler) ClearHistory(ctx context.Context, input *ClearActivity
}
if input.EnvironmentID != "0" {
- out, err := h.proxyClearHistoryInternal(ctx, input)
- if err != nil {
- return nil, err
+ out, proxyClearHistoryErr := h.proxyClearHistoryInternal(ctx, input)
+ if proxyClearHistoryErr != nil {
+ return nil, proxyClearHistoryErr
}
out.Body.Data.Deleted += deleted
return out, nil
@@ -360,20 +360,20 @@ func (h *ActivityHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz.
})
}
-func activityStreamEnvironmentVersionInternal(environment environment.Environment) string {
- if environment.UpdatedAt == nil {
- return environment.ID
+func activityStreamEnvironmentVersionInternal(localEnvironment environment.Environment) string {
+ if localEnvironment.UpdatedAt == nil {
+ return localEnvironment.ID
}
- return environment.ID + ":" + environment.UpdatedAt.UTC().Format(time.RFC3339Nano)
+ return localEnvironment.ID + ":" + localEnvironment.UpdatedAt.UTC().Format(time.RFC3339Nano)
}
-func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Context, environment environment.Environment, limit int, publish func(activitytypes.StreamEvent)) {
- environmentID := environment.ID
+func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Context, localEnvironment environment.Environment, limit int, publish func(activitytypes.StreamEvent)) {
+ environmentID := localEnvironment.ID
lastError := ""
lastFingerprint := ""
poll := func() {
- currentEnvironment := environment
+ currentEnvironment := localEnvironment
if h.environment.GetActiveRemoteEnvironment != nil {
var ok bool
currentEnvironment, ok = h.environment.GetActiveRemoteEnvironment(environmentID).Get()
@@ -591,23 +591,46 @@ func (h *ActivityHandler) proxyListActivitiesInternal(ctx context.Context, input
return out, nil
}
-func (h *ActivityHandler) proxyListActivitiesForEnvironmentInternal(ctx context.Context, environment environment.Environment, input *ListActivitiesInput) (*handlerutil.Page[activitytypes.Activity], error) {
+func (
+ h *ActivityHandler,
+) proxyListActivitiesForEnvironmentInternal(
+ ctx context.Context,
+ localEnvironment environment.Environment,
+ input *ListActivitiesInput,
+) (
+ *handlerutil.Page[activitytypes.Activity],
+ error,
+) {
out, err := h.listRemoteActivitiesInternal(ctx, input, func(path string) (*base.Paginated[activitytypes.Activity], error) {
pollCtx, cancelPoll := context.WithTimeout(ctx, activityStreamRemotePollTimeout)
defer cancelPoll()
var out base.Paginated[activitytypes.Activity]
- if err := h.environment.ProxyJSONRequestForEnvironment(pollCtx, environment, http.MethodGet, path, nil, &out); err != nil {
+ if err := h.environment.ProxyJSONRequestForEnvironment(pollCtx, localEnvironment, http.MethodGet, path, nil, &out); err != nil {
return nil, handlerutil.TranslateRemoteProxyError(err)
}
return &out, nil
})
if out != nil {
- applyActivitySourceLabelsForEnvironmentInternal(environment, out.Body.Data)
+ applyActivitySourceLabelsForEnvironmentInternal(localEnvironment, out.Body.Data)
}
return out, err
}
-func (h *ActivityHandler) listRemoteActivitiesInternal(ctx context.Context, input *ListActivitiesInput, fetch func(string) (*base.Paginated[activitytypes.Activity], error)) (*handlerutil.Page[activitytypes.Activity], error) {
+func (
+ h *ActivityHandler,
+) listRemoteActivitiesInternal(
+ ctx context.Context,
+ input *ListActivitiesInput,
+ fetch func(
+ string,
+ ) (
+ *base.Paginated[activitytypes.Activity],
+ error,
+ ),
+) (
+ *handlerutil.Page[activitytypes.Activity],
+ error,
+) {
params := normalizeRemoteActivityParamsInternal(activityListParamsInternal(input))
// The agent only ships the newest window the merged page can use, not its
// whole history; the stream poller repeats this every few seconds.
diff --git a/backend/internal/activity/limiter.go b/backend/internal/activity/limiter.go
index 782f0b117..66a2f02bd 100644
--- a/backend/internal/activity/limiter.go
+++ b/backend/internal/activity/limiter.go
@@ -39,9 +39,9 @@ type activityEnvironmentSlots struct {
wake chan struct{}
}
-func newActivitySlotLimiterInternal(settings *settings.SettingsService) *activitySlotLimiter {
+func newActivitySlotLimiterInternal(localSettings *settings.SettingsService) *activitySlotLimiter {
return &activitySlotLimiter{
- settings: settings,
+ settings: localSettings,
state: map[string]*activityEnvironmentSlots{},
}
}
diff --git a/backend/internal/activity/remote.go b/backend/internal/activity/remote.go
index 5fb78cb92..097740284 100644
--- a/backend/internal/activity/remote.go
+++ b/backend/internal/activity/remote.go
@@ -54,7 +54,19 @@ func collectActivityWindowInternal(window int, fetchPage func(start, limit int)
// ListRemoteActivities combines manager-owned summaries with agent-owned work
// before slicing the page. The remote records must already match the filters
// and be the agent's newest window; remoteTotal is the agent's filtered count.
-func (s *ActivityService) ListRemoteActivities(ctx context.Context, environmentID string, remote []activitytypes.Activity, remoteTotal int64, params pagination.QueryParams) ([]activitytypes.Activity, pagination.Response, error) {
+func (
+ s *ActivityService,
+) ListRemoteActivities(
+ ctx context.Context,
+ environmentID string,
+ remote []activitytypes.Activity,
+ remoteTotal int64,
+ params pagination.QueryParams,
+) (
+ []activitytypes.Activity,
+ pagination.Response,
+ error,
+) {
params = normalizeRemoteActivityParamsInternal(params)
window := kit.Ternary(params.Limit == -1, -1, params.Start+params.Limit)
activities, localTotal, err := collectActivityWindowInternal(window, func(start, limit int) ([]activitytypes.Activity, int64, error) {
diff --git a/backend/internal/activity/service.go b/backend/internal/activity/service.go
index 563cbe48d..78d6a51ff 100644
--- a/backend/internal/activity/service.go
+++ b/backend/internal/activity/service.go
@@ -161,13 +161,14 @@ func (sub *activitySubscriber) enqueue(event activitytypes.StreamEvent) {
func (sub *activitySubscriber) dropOldestMessageLockedInternal() {
for i, entry := range sub.queue {
- if !isCoalescableEventInternal(entry.event) {
- sub.queue = append(sub.queue[:i], sub.queue[i+1:]...)
- sub.messageCount--
- sub.missed = true
- slog.Warn("activity subscriber message buffer full; snapshot will be sent on next heartbeat", "environmentId", sub.environmentID)
- return
+ if isCoalescableEventInternal(entry.event) {
+ continue
}
+ sub.queue = append(sub.queue[:i], sub.queue[i+1:]...)
+ sub.messageCount--
+ sub.missed = true
+ slog.Warn("activity subscriber message buffer full; snapshot will be sent on next heartbeat", "environmentId", sub.environmentID)
+ return
}
}
@@ -686,7 +687,19 @@ func (s *ActivityService) appendBatchWithRetryInternal(ctx context.Context, acti
return nil, writeErr
}
-func (s *ActivityService) CompleteActivity(ctx context.Context, activityID string, status activitytypes.Status, finalMessage string, errMessage *string, finalStep ...string) (*activitytypes.Activity, error) {
+func (
+ s *ActivityService,
+) CompleteActivity(
+ ctx context.Context,
+ activityID string,
+ status activitytypes.Status,
+ finalMessage string,
+ errMessage *string,
+ finalStep ...string,
+) (
+ *activitytypes.Activity,
+ error,
+) {
if err := s.checkInitInternal(); err != nil {
return nil, err
}
@@ -1122,7 +1135,9 @@ func (s *ActivityService) ListActivitiesPaginated(ctx context.Context, environme
escaped := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(term)
searchPattern := "%" + escaped + "%"
q = q.Where(
- "type LIKE ? ESCAPE '\\' OR COALESCE(resource_name, '') LIKE ? ESCAPE '\\' OR COALESCE(latest_message, '') LIKE ? ESCAPE '\\' OR COALESCE(step, '') LIKE ? ESCAPE '\\' OR COALESCE(error, '') LIKE ? ESCAPE '\\'",
+ "type LIKE ? ESCAPE '\\' OR COALESCE(resource_name, '') LIKE ? ESCAPE '\\' OR COALESCE(latest_message, "+
+ "'') LIKE ? ESCAPE '\\' OR COALESCE(step, '') LIKE ? ESCAPE '\\' OR COALESCE(error, '') LIKE ? ESCAPE "+
+ "'\\'",
searchPattern, searchPattern, searchPattern, searchPattern, searchPattern,
)
}
@@ -1278,31 +1293,31 @@ func (s *ActivityService) Subscribe(environmentID string) (<-chan activitytypes.
missedEvents := func() bool {
s.subscribersMu.RLock()
- sub, ok := s.subscribers[id]
+ localSub, ok := s.subscribers[id]
s.subscribersMu.RUnlock()
if !ok {
return false
}
- sub.mu.Lock()
- defer sub.mu.Unlock()
- if !sub.missed {
+ localSub.mu.Lock()
+ defer localSub.mu.Unlock()
+ if !localSub.missed {
return false
}
- sub.missed = false
+ localSub.missed = false
return true
}
unsubscribe := func() {
s.subscribersMu.Lock()
- sub, ok := s.subscribers[id]
+ localSub, ok := s.subscribers[id]
if ok {
delete(s.subscribers, id)
}
s.subscribersMu.Unlock()
if ok {
// The pump goroutine owns ch and closes it on shutdown.
- close(sub.done)
+ close(localSub.done)
}
}
@@ -1554,7 +1569,23 @@ func activityStartedByDTOInternal(model *Activity) *activitytypes.StartedBy {
// FailInterruptedBackups finalizes backup activities before startup admits work.
func (s *ActivityService) FailInterruptedBackups(ctx context.Context, protectedIDs ...string) error {
var pending []Activity
- if err := s.db.WithContext(ctx).Where("status IN ?", []activitytypes.Status{activitytypes.StatusQueued, activitytypes.StatusRunning}).Where("id NOT IN ?", append(protectedIDs, "")).Find(&pending).Error; err != nil {
+ if err := s.db.WithContext(
+ ctx,
+ ).Where(
+ "status IN ?",
+ []activitytypes.Status{
+ activitytypes.StatusQueued,
+ activitytypes.StatusRunning,
+ },
+ ).Where(
+ "id NOT IN ?",
+ append(
+ protectedIDs,
+ "",
+ ),
+ ).Find(
+ &pending,
+ ).Error; err != nil {
return fmt.Errorf("find interrupted backup activities: %w", err)
}
const message = "Backup interrupted by Arcane restart"
diff --git a/backend/internal/activity/service_test.go b/backend/internal/activity/service_test.go
index 7f09bddcb..6ff2192b1 100644
--- a/backend/internal/activity/service_test.go
+++ b/backend/internal/activity/service_test.go
@@ -28,7 +28,7 @@ func setupActivityServiceTestDBInternal(t *testing.T) *database.DB {
}
func TestActivityServiceLifecycleInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -94,7 +94,7 @@ func TestActivityServiceLifecycleInternal(t *testing.T) {
}
func TestActivityServiceStreamFanoutInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -137,7 +137,7 @@ func TestActivityServiceStreamFanoutInternal(t *testing.T) {
}
func TestActivityServiceRetentionCleanupInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -171,7 +171,7 @@ func TestActivityServiceRetentionCleanupInternal(t *testing.T) {
}
func TestActivityServicePruneHistoryZeroRetentionDisablesAgeCleanupInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -214,7 +214,7 @@ func TestActivityServiceSubscribeMarksMissedEventsWhenBufferFullInternal(t *test
}
func TestActivityServiceDeleteHistoryPreservesActiveActivitiesInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -244,7 +244,7 @@ func TestActivityServiceDeleteHistoryPreservesActiveActivitiesInternal(t *testin
}
func TestActivityServicePruneHistoryByAgeAndCountInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -331,7 +331,7 @@ func TestActivitySubscriberCoalescesProgressEventsInternal(t *testing.T) {
}
func TestActivityServiceListOrderStableUnderProgressUpdatesInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -370,7 +370,7 @@ func TestActivityServiceListOrderStableUnderProgressUpdatesInternal(t *testing.T
func setupQueuedActivityServiceInternal(t *testing.T) (*ActivityService, context.Context) {
t.Helper()
- ctx := context.Background()
+ ctx := t.Context()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
@@ -383,17 +383,17 @@ func setupQueuedActivityServiceInternal(t *testing.T) (*ActivityService, context
require.NoError(t, err)
sqlDB.SetMaxOpenConns(1)
- settings, err := newSettingsServiceForTestInternal(t, ctx, wrapped)
+ localSettings, err := newSettingsServiceForTestInternal(t, ctx, wrapped)
require.NoError(t, err)
- require.NoError(t, settings.SetIntSetting(ctx, maxConcurrentActivitiesSettingKey, 1))
- return NewActivityService(wrapped, settings), ctx
+ require.NoError(t, localSettings.SetIntSetting(ctx, maxConcurrentActivitiesSettingKey, 1))
+ return NewActivityService(wrapped, localSettings), ctx
}
func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *database.DB) (*settings.SettingsService, error) {
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -500,7 +500,7 @@ func TestActivityServiceCancelWhileQueuedUnblocksAwaitInternal(t *testing.T) {
func TestActivityServiceCompleteActivityRejectsUninitializedServiceInternal(t *testing.T) {
service := NewActivityService(nil, nil)
- _, err := service.CompleteActivity(context.Background(), "any-id", activitytypes.StatusSuccess, "done", nil)
+ _, err := service.CompleteActivity(t.Context(), "any-id", activitytypes.StatusSuccess, "done", nil)
require.Error(t, err)
}
@@ -509,8 +509,8 @@ func TestActivityServiceTrackAndRequestCancelInternal(t *testing.T) {
service := NewActivityService(db, nil)
// Mirror the handler flow: work runs under an app-lifecycle runtime context.
- appCtx := utils.WithAppLifecycleContext(context.Background())
- runtimeCtx := utils.ActivityRuntimeContext(context.Background(), appCtx)
+ appCtx := utils.WithAppLifecycleContext(t.Context())
+ runtimeCtx := utils.ActivityRuntimeContext(t.Context(), appCtx)
created, err := service.StartActivity(runtimeCtx, StartActivityRequest{
EnvironmentID: "0",
@@ -540,7 +540,7 @@ func TestActivityServiceTrackAndRequestCancelInternal(t *testing.T) {
}
func TestActivityServiceCancelActivityInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -567,7 +567,7 @@ func TestActivityServiceCancelActivityInternal(t *testing.T) {
}
func TestActivityServiceFailStaleImageUpdateChecksInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -635,7 +635,7 @@ func TestActivityServiceFailStaleImageUpdateChecksInternal(t *testing.T) {
}
func TestActivityServiceFailAbandonedActivitiesInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -684,7 +684,7 @@ func TestActivityServiceFailAbandonedActivitiesInternal(t *testing.T) {
}
func TestActivityServiceResolveStaleAutoUpdateActivitiesInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -747,7 +747,7 @@ func receiveActivityEventInternal(t *testing.T, events <-chan activitytypes.Stre
// messages in order and coalesces the activity update to the batch's last
// message, last progress, and last step.
func TestActivityServiceAppendMessagesBatchInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -796,7 +796,7 @@ func TestActivityServiceAppendMessagesBatchInternal(t *testing.T) {
// publishes after it — is dropped instead of reverting subscribers to a
// running state no later event would correct.
func TestActivityServiceDropsStaleSnapshotAfterTerminalPublishInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
@@ -824,8 +824,8 @@ func TestActivityServiceDropsStaleSnapshotAfterTerminalPublishInternal(t *testin
service.publishActivityInternal(stale)
select {
- case event := <-events:
- t.Fatalf("stale non-terminal snapshot reached subscriber: %+v", event)
+ case localEvent := <-events:
+ t.Fatalf("stale non-terminal snapshot reached subscriber: %+v", localEvent)
case <-time.After(100 * time.Millisecond):
}
}
diff --git a/backend/internal/activity/visibility_test.go b/backend/internal/activity/visibility_test.go
index 042540732..6f3dd7949 100644
--- a/backend/internal/activity/visibility_test.go
+++ b/backend/internal/activity/visibility_test.go
@@ -18,8 +18,27 @@ func TestJobActivityVisibilityFiltersBeforePagination(t *testing.T) {
db := setupActivityServiceTestDBInternal(t)
service := NewActivityService(db, nil)
for _, environmentID := range []string{"0", "private"} {
- require.NoError(t, db.Create(&Activity{ID: environmentID + "-job", EnvironmentID: environmentID, Type: activitytypes.TypeJobRun, Status: activitytypes.StatusSuccess, StartedAt: time.Now(), Metadata: database.JSON{"environmentId": environmentID}}).Error)
- require.NoError(t, db.Create(&Activity{ID: environmentID + "-pull", EnvironmentID: environmentID, Type: activitytypes.TypeImagePull, Status: activitytypes.StatusSuccess, StartedAt: time.Now()}).Error)
+ require.NoError(
+ t,
+ db.Create(&Activity{
+ ID: environmentID + "-job",
+ EnvironmentID: environmentID,
+ Type: activitytypes.TypeJobRun,
+ Status: activitytypes.StatusSuccess,
+ StartedAt: time.Now(),
+ Metadata: database.JSON{"environmentId": environmentID},
+ }).Error,
+ )
+ require.NoError(
+ t,
+ db.Create(&Activity{
+ ID: environmentID + "-pull",
+ EnvironmentID: environmentID,
+ Type: activitytypes.TypeImagePull,
+ Status: activitytypes.StatusSuccess,
+ StartedAt: time.Now(),
+ }).Error,
+ )
}
permissions := authz.NewPermissionSet()
permissions.PerEnv["0"] = map[string]struct{}{authz.PermActivitiesRead: {}}
@@ -40,7 +59,17 @@ func TestJobActivityVisibilityFiltersBeforePagination(t *testing.T) {
require.EqualValues(t, 1, response.TotalItems)
require.Len(t, activities, 1)
require.Equal(t, "private-pull", activities[0].ID)
- require.False(t, canReadJobActivityInternal(ctx, activitytypes.Activity{Type: activitytypes.TypeJobRun, EnvironmentID: "private", Metadata: map[string]any{"environmentId": "allowed"}}))
+ require.False(
+ t,
+ canReadJobActivityInternal(
+ ctx,
+ activitytypes.Activity{
+ Type: activitytypes.TypeJobRun,
+ EnvironmentID: "private",
+ Metadata: map[string]any{"environmentId": "allowed"},
+ },
+ ),
+ )
require.True(t, canReadJobActivityInternal(ctx, activitytypes.Activity{Type: activitytypes.TypeJobRun, Metadata: map[string]any{"environmentId": "allowed"}}))
privileged := context.WithValue(t.Context(), middleware.ContextKeyUserPermissions, authz.SudoPermissionSet())
activities, response, err = service.ListActivitiesPaginated(privileged, "private", pagination.QueryParams{Limit: 10})
diff --git a/backend/internal/apikey/handler.go b/backend/internal/apikey/handler.go
index 803ec1508..8e7d8f327 100644
--- a/backend/internal/apikey/handler.go
+++ b/backend/internal/apikey/handler.go
@@ -334,11 +334,11 @@ func (h *ApiKeyHandler) DeleteMyApiKey(ctx context.Context, input *DeleteApiKeyI
return nil, huma.Error404NotFound("API key not found")
}
- if err := h.apiKeyService.DeleteApiKey(ctx, input.ID); err != nil {
- if errors.Is(err, ErrApiKeyNotFound) {
+ if deleteApiKeyErr := h.apiKeyService.DeleteApiKey(ctx, input.ID); deleteApiKeyErr != nil {
+ if errors.Is(deleteApiKeyErr, ErrApiKeyNotFound) {
return nil, huma.Error404NotFound("API key not found")
}
- if errors.Is(err, ErrApiKeyProtected) {
+ if errors.Is(deleteApiKeyErr, ErrApiKeyProtected) {
return nil, huma.Error403Forbidden("this API key cannot be deleted")
}
return nil, huma.Error500InternalServerError("Failed to delete API key")
diff --git a/backend/internal/apikey/service.go b/backend/internal/apikey/service.go
index b5b7a7dbe..db6ad61bf 100644
--- a/backend/internal/apikey/service.go
+++ b/backend/internal/apikey/service.go
@@ -156,12 +156,12 @@ func (s *ApiKeyService) BackfillApiKeyPermissions(ctx context.Context) error {
return err
}
for _, p := range perms {
- if err := tx.Create(&role.ApiKeyPermission{
+ if createKeyPermissionErr := tx.Create(&role.ApiKeyPermission{
ApiKeyID: key.ID,
Permission: p,
EnvironmentID: key.EnvironmentID,
- }).Error; err != nil {
- return fmt.Errorf("failed to seed api key permission: %w", err)
+ }).Error; createKeyPermissionErr != nil {
+ return fmt.Errorf("failed to seed api key permission: %w", createKeyPermissionErr)
}
}
slog.InfoContext(ctx, "Backfilled missing permissions for bootstrap api key", "api_key_id", key.ID, "perm_count", len(perms), "env_id", key.EnvironmentID)
@@ -355,8 +355,8 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerP
}
if s.roleService != nil {
grants := toApiKeyPermissionRowsInternal(created.ID, req.Permissions)
- if err := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); err != nil {
- return nil, fmt.Errorf("failed to persist api key permissions: %w", err)
+ if setApiKeyPermissionsErr := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); setApiKeyPermissionsErr != nil {
+ return nil, fmt.Errorf("failed to persist api key permissions: %w", setApiKeyPermissionsErr)
}
// Re-load the just-persisted grants into the response DTO so the
// frontend doesn't see `"permissions": null` on a successful create.
@@ -375,16 +375,16 @@ func (s *ApiKeyService) validateGrantsAgainstOwnerInternal(ctx context.Context,
if s.roleService == nil || len(grants) == 0 {
return nil
}
- user, err := s.userService.GetUserByID(ctx, ownerID)
+ localUser, err := s.userService.GetUserByID(ctx, ownerID)
if err != nil {
return fmt.Errorf("load owner for permission validation: %w", err)
}
- ps, err := s.roleService.ResolvePermissions(ctx, user)
+ ps, err := s.roleService.ResolvePermissions(ctx, localUser)
if err != nil {
return fmt.Errorf("resolve owner permissions: %w", err)
}
- if err := validateGrantsAgainstPermissionSetInternal(ps, grants); err != nil {
- return fmt.Errorf("owner's roles do not allow this grant: %w", err)
+ if validateGrantsAgainstPermissionSetErr := validateGrantsAgainstPermissionSetInternal(ps, grants); validateGrantsAgainstPermissionSetErr != nil {
+ return fmt.Errorf("owner's roles do not allow this grant: %w", validateGrantsAgainstPermissionSetErr)
}
return nil
}
@@ -473,8 +473,8 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(
EnvironmentID: environmentID,
ExpiresAt: req.ExpiresAt,
}
- if err := s.db.WithContext(ctx).Create(ak).Error; err != nil {
- return nil, fmt.Errorf("failed to create API key: %w", err)
+ if createAPIKeyErr := s.db.WithContext(ctx).Create(ak).Error; createAPIKeyErr != nil {
+ return nil, fmt.Errorf("failed to create API key: %w", createAPIKeyErr)
}
// A just-minted environment key is about to be linked as the
// environment's pairing key, so present it as bootstrap already.
@@ -570,9 +570,9 @@ func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*common.User,
// The username is mutable and not proof of provenance — never mint the
// managed full-permission key onto an account that isn't a global admin.
if s.roleService != nil {
- perms, err := s.roleService.ResolvePermissions(ctx, adminUser)
- if err != nil {
- return nil, fmt.Errorf("failed to resolve default admin permissions: %w", err)
+ perms, resolvePermissionsErr := s.roleService.ResolvePermissions(ctx, adminUser)
+ if resolvePermissionsErr != nil {
+ return nil, fmt.Errorf("failed to resolve default admin permissions: %w", resolvePermissionsErr)
}
if !perms.IsGlobalAdmin() {
slog.WarnContext(ctx, "User is not a global admin, skipping default admin API key reconciliation", "username", defaultAdminUsername)
@@ -655,8 +655,8 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, raw
ManagedBy: new(managedByAdminBootstrap),
UserID: &userID,
}
- if err := tx.Create(ak).Error; err != nil {
- return fmt.Errorf("failed to create managed API key: %w", err)
+ if createManagedKeyErr := tx.Create(ak).Error; createManagedKeyErr != nil {
+ return fmt.Errorf("failed to create managed API key: %w", createManagedKeyErr)
}
return nil
}
@@ -679,20 +679,20 @@ func (s *ApiKeyService) reconcileManagedAPIKeys(tx *gorm.DB, userID, rawKey stri
matchingIndex := s.findMatchingManagedAPIKey(rawKey, managedKeys)
if matchingIndex >= 0 {
- if err := s.updateMatchingManagedAPIKey(tx, managedKeys[matchingIndex].ID); err != nil {
- return nil, err
+ if updateMatchingManagedAPIKeyErr := s.updateMatchingManagedAPIKey(tx, managedKeys[matchingIndex].ID); updateMatchingManagedAPIKeyErr != nil {
+ return nil, updateMatchingManagedAPIKeyErr
}
deleteIDs := managedAPIKeyDeleteIDsInternal(managedKeys, matchingIndex)
- if err := s.deleteManagedAPIKeysByIDs(tx, deleteIDs); err != nil {
- return nil, err
+ if deleteManagedAPIKeysByIDsErr := s.deleteManagedAPIKeysByIDs(tx, deleteIDs); deleteManagedAPIKeysByIDsErr != nil {
+ return nil, deleteManagedAPIKeysByIDsErr
}
// The kept key's metadata changed too; its cached copy is stale.
return append(deleteIDs, managedKeys[matchingIndex].ID), nil
}
deleteIDs := managedAPIKeyDeleteIDsInternal(managedKeys, -1)
- if err := s.deleteManagedAPIKeysByIDs(tx, deleteIDs); err != nil {
- return nil, err
+ if deleteRemovedManagedKeysErr := s.deleteManagedAPIKeysByIDs(tx, deleteIDs); deleteRemovedManagedKeysErr != nil {
+ return nil, deleteRemovedManagedKeysErr
}
return deleteIDs, s.createManagedDefaultAdminAPIKey(tx, userID, rawKey)
@@ -707,12 +707,12 @@ func (s *ApiKeyService) ReconcileDefaultAdminAPIKey(ctx context.Context, rawKey
}
var affectedIDs []string
- if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if transactionErr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
affectedIDs, err = s.reconcileManagedAPIKeys(tx, adminUser.ID, rawKey)
return err
- }); err != nil {
+ }); transactionErr != nil {
// Rolled back: the DB is unchanged, so cached entries are still valid.
- return err
+ return transactionErr
}
s.invalidateValidatedKeysInternal(affectedIDs...)
return nil
@@ -751,8 +751,8 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environment
EnvironmentID: &environmentID,
}
}
- if err := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); err != nil {
- return nil, fmt.Errorf("failed to persist environment bootstrap key permissions: %w", err)
+ if setApiKeyPermissionsErr := s.roleService.SetApiKeyPermissions(ctx, created.ID, grants); setApiKeyPermissionsErr != nil {
+ return nil, fmt.Errorf("failed to persist environment bootstrap key permissions: %w", setApiKeyPermissionsErr)
}
// Re-load grants into the response DTO so callers see the seeded
// permissions immediately, not null.
@@ -991,8 +991,8 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {
}
func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*common.User, error) {
- user, _, err := s.ValidateApiKeyWithID(ctx, rawKey)
- return user, err
+ localUser, _, err := s.ValidateApiKeyWithID(ctx, rawKey)
+ return localUser, err
}
// ValidateApiKeyWithID is like ValidateApiKey but additionally returns the
@@ -1007,12 +1007,12 @@ func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string)
return nil, nil, ErrApiKeyInvalid
}
- user, err := s.userService.GetUserByID(ctx, *apiKey.UserID)
+ localUser, err := s.userService.GetUserByID(ctx, *apiKey.UserID)
if err != nil {
return nil, nil, fmt.Errorf("failed to get user for API key: %w", err)
}
- return user, apiKey, nil
+ return localUser, apiKey, nil
}
func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey string) (*string, error) {
@@ -1047,12 +1047,12 @@ func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey st
// publish below, the generation will have moved and the publish is dropped.
gen := s.cacheGen.Load()
var apiKeys []ApiKey
- if err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {
- return nil, fmt.Errorf("failed to find API keys: %w", err)
+ if findAPIKeysErr := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; findAPIKeysErr != nil {
+ return nil, fmt.Errorf("failed to find API keys: %w", findAPIKeysErr)
}
for _, apiKey := range apiKeys {
- if err := s.validateApiKeyHash(apiKey.KeyHash, rawKey); err == nil {
+ if validateApiKeyHashErr := s.validateApiKeyHash(apiKey.KeyHash, rawKey); validateApiKeyHashErr == nil {
if apiKey.ExpiresAt != nil && apiKey.ExpiresAt.Before(time.Now()) {
return nil, ErrApiKeyExpired
}
diff --git a/backend/internal/apikey/service_test.go b/backend/internal/apikey/service_test.go
index c909bba9c..5fce0c0da 100644
--- a/backend/internal/apikey/service_test.go
+++ b/backend/internal/apikey/service_test.go
@@ -60,17 +60,17 @@ func setupAPIKeyService(t *testing.T) (*ApiKeyService, *database.DB, *user.UserS
func createTestAPIKeyUser(t *testing.T, ctx context.Context, userService *user.UserService, id string, usernames ...string) *common.User {
t.Helper()
- username := fmt.Sprintf("user-%s", id)
+ username := "user-" + id
if len(usernames) > 0 {
username = usernames[0]
}
- user := &common.User{
+ localUser := &common.User{
ID: id,
Username: username,
}
- created, err := userService.CreateUser(ctx, user)
+ created, err := userService.CreateUser(ctx, localUser)
require.NoError(t, err)
return created
}
@@ -79,7 +79,7 @@ func fetchAPIKey(t *testing.T, db *database.DB, keyID string) ApiKey {
t.Helper()
var apiKey ApiKey
- err := db.WithContext(context.Background()).Where("id = ?", keyID).First(&apiKey).Error
+ err := db.WithContext(t.Context()).Where("id = ?", keyID).First(&apiKey).Error
require.NoError(t, err)
return apiKey
}
@@ -88,7 +88,7 @@ func listAPIKeysForUser(t *testing.T, db *database.DB, userID string) []ApiKey {
t.Helper()
var apiKeys []ApiKey
- err := db.WithContext(context.Background()).Where("user_id = ?", userID).Order("created_at asc").Find(&apiKeys).Error
+ err := db.WithContext(t.Context()).Where("user_id = ?", userID).Order("created_at asc").Find(&apiKeys).Error
require.NoError(t, err)
return apiKeys
}
@@ -108,12 +108,12 @@ func invalidateAPIKey(rawKey string) string {
func createDefaultAdminUser(t *testing.T, ctx context.Context, userService *user.UserService) *common.User {
t.Helper()
- user := &common.User{
+ localUser := &common.User{
ID: "default-admin-user",
Username: defaultAdminUsername,
}
- created, err := userService.CreateUser(ctx, user)
+ created, err := userService.CreateUser(ctx, localUser)
require.NoError(t, err)
return created
}
@@ -154,7 +154,7 @@ func TestListApiKeysPermissionQueryCountIsConstant(t *testing.T) {
queryCount.Add(1)
}))
- result, _, err := service.ListApiKeys(context.Background(), pagination.QueryParams{
+ result, _, err := service.ListApiKeys(t.Context(), pagination.QueryParams{
Limit: 100,
})
require.NoError(t, err)
@@ -165,7 +165,7 @@ func TestListApiKeysPermissionQueryCountIsConstant(t *testing.T) {
queryCounts[keyCount] = queryCount.Load()
queryCount.Store(0)
- result, err = service.ListApiKeysByUser(context.Background(), userID)
+ result, err = service.ListApiKeysByUser(t.Context(), userID)
require.NoError(t, err)
require.Len(t, result, keyCount)
for _, apiKey := range result {
@@ -184,12 +184,12 @@ func TestListApiKeysPermissionQueryCountIsConstant(t *testing.T) {
}
func TestCreateDefaultAdminAPIKeyUsesProvidedRawKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-default-admin")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-default-admin")
rawKey := "arc_bootstrapprovidedkey1234567890"
- created, err := service.CreateDefaultAdminAPIKey(ctx, user.ID, rawKey)
+ created, err := service.CreateDefaultAdminAPIKey(ctx, localUser.ID, rawKey)
require.NoError(t, err)
require.Equal(t, rawKey, created.Key)
require.Equal(t, defaultAdminAPIKeyName, created.Name)
@@ -203,7 +203,7 @@ func TestCreateDefaultAdminAPIKeyUsesProvidedRawKey(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeyCreatesManagedKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -225,7 +225,7 @@ func TestReconcileDefaultAdminAPIKeyCreatesManagedKey(t *testing.T) {
}
func TestDeleteApiKeyRejectsStaticKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -241,7 +241,7 @@ func TestDeleteApiKeyRejectsStaticKey(t *testing.T) {
}
func TestUpdateApiKeyRejectsStaticKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -263,7 +263,7 @@ func TestUpdateApiKeyRejectsStaticKey(t *testing.T) {
}
func TestUpdateApiKeyRollsBackMetadataWhenPermissionUpdateFails(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAPIKeyServiceTestDB(t)
require.NoError(t, db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''))").Error)
@@ -294,22 +294,22 @@ func TestUpdateApiKeyRollsBackMetadataWhenPermissionUpdateFails(t *testing.T) {
}
func TestCreateApiKeyRejectsGrantsBeyondCallerPermissions(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, _, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-escalation")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-escalation")
callerPerms := authz.NewPermissionSet()
callerPerms.AddGlobal(authz.PermContainersList)
// A grant the caller does not hold must be rejected.
- _, err := service.CreateApiKey(ctx, user.ID, callerPerms, apikey.CreateApiKey{
+ _, err := service.CreateApiKey(ctx, localUser.ID, callerPerms, apikey.CreateApiKey{
Name: "escalated",
Permissions: []apikey.PermissionGrant{{Permission: authz.PermApiKeysCreate}},
})
require.ErrorIs(t, err, ErrApiKeyPermissionEscalation)
// A grant within the caller's set succeeds.
- created, err := service.CreateApiKey(ctx, user.ID, callerPerms, apikey.CreateApiKey{
+ created, err := service.CreateApiKey(ctx, localUser.ID, callerPerms, apikey.CreateApiKey{
Name: "allowed",
Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},
})
@@ -318,7 +318,7 @@ func TestCreateApiKeyRejectsGrantsBeyondCallerPermissions(t *testing.T) {
}
func TestApiKeyGrantsAreCappedByOwnerRoles(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAPIKeyServiceTestDB(t)
roleSvc := role.NewRoleService(db)
@@ -359,13 +359,13 @@ func TestApiKeyGrantsAreCappedByOwnerRoles(t *testing.T) {
}
func TestCreatePersonalApiKeyHasNoGrantsAndCannotGainAny(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-personal")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-personal")
- _, err := service.CreatePersonalApiKey(ctx, user.ID, apikey.CreateUserApiKey{Name: " \t "})
+ _, err := service.CreatePersonalApiKey(ctx, localUser.ID, apikey.CreateUserApiKey{Name: " \t "})
require.EqualError(t, err, "name: must contain at least 1 characters after normalization")
- created, err := service.CreatePersonalApiKey(ctx, user.ID, apikey.CreateUserApiKey{Name: " cafe\u0301 personal "})
+ created, err := service.CreatePersonalApiKey(ctx, localUser.ID, apikey.CreateUserApiKey{Name: " cafe\u0301 personal "})
require.NoError(t, err)
require.Equal(t, "café personal", created.Name)
require.Equal(t, ApiKeyKindPersonal, created.Kind)
@@ -380,7 +380,7 @@ func TestCreatePersonalApiKeyHasNoGrantsAndCannotGainAny(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeyNoOpWhenUnchanged(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -396,7 +396,7 @@ func TestReconcileDefaultAdminAPIKeyNoOpWhenUnchanged(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeyReplacesManagedKeyOnRotation(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -420,7 +420,7 @@ func TestReconcileDefaultAdminAPIKeyReplacesManagedKeyOnRotation(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeyRotationEvictsRacingCacheFill(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -455,7 +455,7 @@ func TestReconcileDefaultAdminAPIKeyRotationEvictsRacingCacheFill(t *testing.T)
}
func TestReconcileDefaultAdminAPIKeyDeletesManagedKeyWhenUnset(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -467,7 +467,7 @@ func TestReconcileDefaultAdminAPIKeyDeletesManagedKeyWhenUnset(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeyPreservesUserManagedKeys(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -497,7 +497,7 @@ func TestReconcileDefaultAdminAPIKeyPreservesUserManagedKeys(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeyDeletesDuplicateManagedKeys(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -515,7 +515,7 @@ func TestReconcileDefaultAdminAPIKeyDeletesDuplicateManagedKeys(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeySkipsWhenDefaultAdminMissing(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, _ := setupAPIKeyService(t)
err := service.ReconcileDefaultAdminAPIKey(ctx, "arc_bootstrapmissing1234567890")
@@ -528,7 +528,7 @@ func TestReconcileDefaultAdminAPIKeySkipsWhenDefaultAdminMissing(t *testing.T) {
}
func TestReconcileDefaultAdminAPIKeyRejectsInvalidKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
adminUser := createDefaultAdminUser(t, ctx, userService)
@@ -538,28 +538,28 @@ func TestReconcileDefaultAdminAPIKeyRejectsInvalidKey(t *testing.T) {
}
func TestValidateAPIKeyUpdatesLastUsedAt(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-validate")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-validate")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "validate-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "validate-key"})
require.NoError(t, err)
require.Nil(t, fetchAPIKey(t, db, created.ID).LastUsedAt)
validatedUser, err := service.ValidateApiKey(ctx, created.Key)
require.NoError(t, err)
- require.Equal(t, user.ID, validatedUser.ID)
+ require.Equal(t, localUser.ID, validatedUser.ID)
apiKey := fetchAPIKey(t, db, created.ID)
require.NotNil(t, apiKey.LastUsedAt)
}
func TestValidateAPIKeyCacheSkipsHashValidationAndInvalidatesOnRevoke(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-cached")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-cached")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "cached-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "cached-key"})
require.NoError(t, err)
_, err = service.ValidateApiKey(ctx, created.Key)
@@ -571,7 +571,7 @@ func TestValidateAPIKeyCacheSkipsHashValidationAndInvalidatesOnRevoke(t *testing
validatedUser, err := service.ValidateApiKey(ctx, created.Key)
require.NoError(t, err)
- require.Equal(t, user.ID, validatedUser.ID)
+ require.Equal(t, localUser.ID, validatedUser.ID)
// Revocation must reject immediately despite the cache.
require.NoError(t, service.DeleteApiKey(ctx, created.ID))
@@ -580,11 +580,11 @@ func TestValidateAPIKeyCacheSkipsHashValidationAndInvalidatesOnRevoke(t *testing
}
func TestValidateAPIKeyCacheFillDroppedWhenRevocationRacesValidation(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-fill-race")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-fill-race")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "fill-race-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "fill-race-key"})
require.NoError(t, err)
// Simulate a validation whose DB read happened before the revocation:
@@ -600,11 +600,11 @@ func TestValidateAPIKeyCacheFillDroppedWhenRevocationRacesValidation(t *testing.
}
func TestValidateAPIKeyDebouncesLastUsedWrites(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-debounce")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-debounce")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "debounce-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "debounce-key"})
require.NoError(t, err)
_, err = service.ValidateApiKey(ctx, created.Key)
@@ -621,11 +621,11 @@ func TestValidateAPIKeyDebouncesLastUsedWrites(t *testing.T) {
}
func TestValidateAPIKeyDebounceReleasedOnWriteFailure(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-debounce-retry")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-debounce-retry")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "debounce-retry-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "debounce-retry-key"})
require.NoError(t, err)
canceledCtx, cancel := context.WithCancel(ctx)
@@ -640,11 +640,11 @@ func TestValidateAPIKeyDebounceReleasedOnWriteFailure(t *testing.T) {
}
func TestValidateAPIKeyLastUsedUpdateIsRequestScoped(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-request-scoped")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-request-scoped")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "request-scoped-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "request-scoped-key"})
require.NoError(t, err)
updateStarted := make(chan struct{})
@@ -656,8 +656,8 @@ func TestValidateAPIKeyLastUsedUpdateIsRequestScoped(t *testing.T) {
validationDone := make(chan error, 1)
go func() {
- _, err := service.ValidateApiKey(ctx, created.Key)
- validationDone <- err
+ _, validateApiKeyErr := service.ValidateApiKey(ctx, created.Key)
+ validationDone <- validateApiKeyErr
}()
select {
@@ -668,9 +668,9 @@ func TestValidateAPIKeyLastUsedUpdateIsRequestScoped(t *testing.T) {
}
select {
- case err := <-validationDone:
+ case operationErr := <-validationDone:
close(releaseUpdate)
- require.NoError(t, err)
+ require.NoError(t, operationErr)
require.FailNow(t, "validation returned before its last-used update completed")
case <-time.After(50 * time.Millisecond):
}
@@ -680,11 +680,11 @@ func TestValidateAPIKeyLastUsedUpdateIsRequestScoped(t *testing.T) {
}
func TestMarkAPIKeyUsedHonorsRequestCancellation(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-canceled-usage")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-canceled-usage")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "canceled-usage-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "canceled-usage-key"})
require.NoError(t, err)
canceledCtx, cancel := context.WithCancel(ctx)
@@ -695,11 +695,11 @@ func TestMarkAPIKeyUsedHonorsRequestCancellation(t *testing.T) {
}
func TestMarkAPIKeyUsedReturnsDatabaseErrors(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-usage-error")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-usage-error")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "usage-error-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "usage-error-key"})
require.NoError(t, err)
sqlDB, err := db.DB.DB()
@@ -712,18 +712,18 @@ func TestMarkAPIKeyUsedReturnsDatabaseErrors(t *testing.T) {
}
func TestValidateAPIKeyRepeatedAuthenticationDoesNotGrowGoroutines(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, _, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-repeated-auth")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-repeated-auth")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "repeated-auth-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "repeated-auth-key"})
require.NoError(t, err)
before := runtime.NumGoroutine()
for range 20 {
- validatedUser, err := service.ValidateApiKey(ctx, created.Key)
- require.NoError(t, err)
- require.Equal(t, user.ID, validatedUser.ID)
+ validatedUser, validateApiKeyErr := service.ValidateApiKey(ctx, created.Key)
+ require.NoError(t, validateApiKeyErr)
+ require.Equal(t, localUser.ID, validatedUser.ID)
}
runtime.Gosched()
after := runtime.NumGoroutine()
@@ -732,7 +732,7 @@ func TestValidateAPIKeyRepeatedAuthenticationDoesNotGrowGoroutines(t *testing.T)
}
func TestGetEnvironmentByAPIKeyUpdatesLastUsedAt(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, _ := setupAPIKeyService(t)
created, err := service.CreateEnvironmentApiKey(ctx, "env-123")
@@ -749,7 +749,7 @@ func TestGetEnvironmentByAPIKeyUpdatesLastUsedAt(t *testing.T) {
}
func TestApiKeyProtectedWhileEnvironmentReferenced(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, _ := setupAPIKeyService(t)
created, err := service.CreateEnvironmentApiKey(ctx, "env-referenced")
@@ -791,11 +791,11 @@ func TestApiKeyProtectedWhileEnvironmentReferenced(t *testing.T) {
}
func TestValidateAPIKeyInvalidDoesNotUpdateLastUsedAt(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, userService := setupAPIKeyService(t)
- user := createTestAPIKeyUser(t, ctx, userService, "user-invalid")
+ localUser := createTestAPIKeyUser(t, ctx, userService, "user-invalid")
- created, err := service.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "invalid-key"})
+ created, err := service.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), apikey.CreateApiKey{Name: "invalid-key"})
require.NoError(t, err)
_, err = service.ValidateApiKey(ctx, invalidateAPIKey(created.Key))
@@ -806,7 +806,7 @@ func TestValidateAPIKeyInvalidDoesNotUpdateLastUsedAt(t *testing.T) {
}
func TestValidateAPIKeyRejectsShortPrefixedInput(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, _, _ := setupAPIKeyService(t)
_, err := service.ValidateApiKey(ctx, "arc_123")
@@ -814,7 +814,7 @@ func TestValidateAPIKeyRejectsShortPrefixedInput(t *testing.T) {
}
func TestGetEnvironmentByAPIKeyExpiredDoesNotUpdateLastUsedAt(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, _ := setupAPIKeyService(t)
created, err := service.CreateEnvironmentApiKey(ctx, "env-expired")
@@ -832,7 +832,7 @@ func TestGetEnvironmentByAPIKeyExpiredDoesNotUpdateLastUsedAt(t *testing.T) {
}
func TestCreateEnvironmentApiKeySeedsAllPermissionsScopedToEnv(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAPIKeyServiceTestDB(t)
require.NoError(t, db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''))").Error)
@@ -863,7 +863,7 @@ func TestCreateEnvironmentApiKeySeedsAllPermissionsScopedToEnv(t *testing.T) {
}
func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAPIKeyServiceTestDB(t)
require.NoError(t, db.Exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_akp_uniq ON api_key_permissions(api_key_id, permission, COALESCE(environment_id, ''))").Error)
@@ -917,7 +917,7 @@ func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {
}
func TestBackfillPermsForKeyDeduplicatesGlobalAndEnvironmentPermissions(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAPIKeyServiceTestDB(t)
roleSvc := role.NewRoleService(db)
@@ -961,7 +961,7 @@ func TestBackfillPermsForKeyDeduplicatesGlobalAndEnvironmentPermissions(t *testi
}
func TestGetEnvironmentByAPIKeyRecentLastUsedAtDoesNotRewriteImmediately(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
service, db, _ := setupAPIKeyService(t)
created, err := service.CreateEnvironmentApiKey(ctx, "env-456")
diff --git a/backend/internal/apns/handler.go b/backend/internal/apns/handler.go
index 01464636c..6cea8d307 100644
--- a/backend/internal/apns/handler.go
+++ b/backend/internal/apns/handler.go
@@ -33,8 +33,28 @@ type DeviceIDInput struct {
func RegisterApns(api huma.API, service *ApnsService) {
h := &ApnsHandler{service: service}
- huma.Register(api, securedApnsOperationInternal("get-apns-status", http.MethodGet, "/apns/status", "Get mobile push status", "Whether mobile push is enabled and the caller's registered devices"), h.Status)
- huma.Register(api, securedApnsOperationInternal("create-apns-pairing-token", http.MethodPost, "/apns/pairing-token", "Issue a pairing token", "Issue a short-lived signed token the mobile app presents to the push relay"), h.PairingToken)
+ huma.Register(
+ api,
+ securedApnsOperationInternal(
+ "get-apns-status",
+ http.MethodGet,
+ "/apns/status",
+ "Get mobile push status",
+ "Whether mobile push is enabled and the caller's registered devices",
+ ),
+ h.Status,
+ )
+ huma.Register(
+ api,
+ securedApnsOperationInternal(
+ "create-apns-pairing-token",
+ http.MethodPost,
+ "/apns/pairing-token",
+ "Issue a pairing token",
+ "Issue a short-lived signed token the mobile app presents to the push relay",
+ ),
+ h.PairingToken,
+ )
huma.Register(api, securedApnsOperationInternal("register-apns-device", http.MethodPost, "/apns/devices", "Register a mobile device", ""), h.RegisterDevice)
huma.Register(api, securedApnsOperationInternal("update-apns-device", http.MethodPatch, "/apns/devices/{id}", "Update a mobile device", ""), h.UpdateDevice)
huma.Register(api, securedApnsOperationInternal("delete-apns-device", http.MethodDelete, "/apns/devices/{id}", "Remove a mobile device", ""), h.DeleteDevice)
@@ -114,8 +134,8 @@ func (h *ApnsHandler) DeleteDevice(ctx context.Context, input *DeviceIDInput) (*
if err != nil {
return nil, err
}
- if err := h.service.DeleteDevice(ctx, user.ID, input.ID); err != nil {
- return nil, apnsHTTPErrorInternal(err)
+ if deleteDeviceErr := h.service.DeleteDevice(ctx, user.ID, input.ID); deleteDeviceErr != nil {
+ return nil, apnsHTTPErrorInternal(deleteDeviceErr)
}
return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Device removed"}}}, nil
}
@@ -125,8 +145,8 @@ func (h *ApnsHandler) TestDevice(ctx context.Context, input *DeviceIDInput) (*ha
if err != nil {
return nil, err
}
- if err := h.service.TestDevice(ctx, user.ID, input.ID); err != nil {
- return nil, apnsHTTPErrorInternal(err)
+ if testDeviceErr := h.service.TestDevice(ctx, user.ID, input.ID); testDeviceErr != nil {
+ return nil, apnsHTTPErrorInternal(testDeviceErr)
}
return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Test notification queued"}}}, nil
}
diff --git a/backend/internal/apns/service.go b/backend/internal/apns/service.go
index 1c668855d..b280ab935 100644
--- a/backend/internal/apns/service.go
+++ b/backend/internal/apns/service.go
@@ -59,7 +59,14 @@ type ApnsService struct {
drainPending atomic.Bool
}
-func NewApnsService(db *database.DB, cfg *config.Config, settingsService *settings.SettingsService, roleService *role.RoleService, eventService *event.EventService, httpClient *http.Client) *ApnsService {
+func NewApnsService(
+ db *database.DB,
+ cfg *config.Config,
+ settingsService *settings.SettingsService,
+ roleService *role.RoleService,
+ eventService *event.EventService,
+ httpClient *http.Client,
+) *ApnsService {
return &ApnsService{db: db, config: cfg, settings: settingsService, roles: roleService, events: eventService, httpClient: httpClient}
}
@@ -100,8 +107,8 @@ func (s *ApnsService) signerInternal(ctx context.Context) (*signerInternal, erro
if err != nil {
return nil, fmt.Errorf("failed to encrypt push signing key: %w", err)
}
- if err := s.settings.UpdateSetting(ctx, "apnsSigningKey", encrypted); err != nil {
- return nil, err
+ if updateSettingErr := s.settings.UpdateSetting(ctx, "apnsSigningKey", encrypted); updateSettingErr != nil {
+ return nil, updateSettingErr
}
}
@@ -135,9 +142,9 @@ func (s *ApnsService) relayRequestInternal(ctx context.Context, method, path str
}
req.Header.Set("Content-Type", "application/json")
if signer != nil {
- sig, err := signer.sign(body)
- if err != nil {
- return 0, nil, fmt.Errorf("failed to sign push relay request: %w", err)
+ sig, signErr := signer.sign(body)
+ if signErr != nil {
+ return 0, nil, fmt.Errorf("failed to sign push relay request: %w", signErr)
}
req.Header.Set(signatureHeader, base64.StdEncoding.EncodeToString(sig))
}
@@ -178,11 +185,11 @@ func (s *ApnsService) EnsureChannel(ctx context.Context) (string, error) {
var parsed struct {
ChannelID string `json:"channelId"`
}
- if err := json.Unmarshal(respBody, &parsed); err != nil || parsed.ChannelID == "" {
+ if unmarshalErr := json.Unmarshal(respBody, &parsed); unmarshalErr != nil || parsed.ChannelID == "" {
return "", fmt.Errorf("channel registration returned no channel id: %w", common.ErrApnsRelay)
}
- if err := s.settings.UpdateSetting(ctx, "apnsChannelId", parsed.ChannelID); err != nil {
- return "", err
+ if updateSettingErr := s.settings.UpdateSetting(ctx, "apnsChannelId", parsed.ChannelID); updateSettingErr != nil {
+ return "", updateSettingErr
}
slog.InfoContext(ctx, "Registered push relay channel", "channelId", parsed.ChannelID, "algorithm", signer.algorithm)
return parsed.ChannelID, nil
@@ -226,8 +233,8 @@ func (s *ApnsService) RevokeChannel(ctx context.Context) error {
if status != http.StatusNoContent && status != http.StatusNotFound && status != http.StatusGone {
return fmt.Errorf("channel revocation returned %d: %s: %w", status, strings.TrimSpace(string(respBody)), common.ErrApnsRelay)
}
- if err := s.settings.UpdateSetting(ctx, "apnsChannelId", ""); err != nil {
- return err
+ if updateSettingErr := s.settings.UpdateSetting(ctx, "apnsChannelId", ""); updateSettingErr != nil {
+ return updateSettingErr
}
slog.InfoContext(ctx, "Revoked push relay channel", "channelId", channelID)
}
@@ -306,7 +313,13 @@ func (s *ApnsService) RegisterDevice(ctx context.Context, userID string, req apn
events := req.Events
if events == nil {
events = map[string]bool{}
- for _, t := range []notifications.NotificationEventType{notifications.NotificationEventImageUpdate, notifications.NotificationEventContainerUpdate, notifications.NotificationEventVulnerabilityFound, notifications.NotificationEventPruneReport, notifications.NotificationEventAutoHeal} {
+ for _, t := range []notifications.NotificationEventType{
+ notifications.NotificationEventImageUpdate,
+ notifications.NotificationEventContainerUpdate,
+ notifications.NotificationEventVulnerabilityFound,
+ notifications.NotificationEventPruneReport,
+ notifications.NotificationEventAutoHeal,
+ } {
events[string(t)] = true
}
}
@@ -325,16 +338,16 @@ func (s *ApnsService) RegisterDevice(ctx context.Context, userID string, req apn
existing.Events = events
existing.EnvironmentIDs = environmentIDs
existing.LastSeenAt = &now
- if err := s.db.WithContext(ctx).Save(&existing).Error; err != nil {
- return apnstypes.Device{}, fmt.Errorf("failed to update push device: %w", err)
+ if updateDeviceErr := s.db.WithContext(ctx).Save(&existing).Error; updateDeviceErr != nil {
+ return apnstypes.Device{}, fmt.Errorf("failed to update push device: %w", updateDeviceErr)
}
return deviceDTOInternal(existing), nil
case !errors.Is(err, gorm.ErrRecordNotFound):
return apnstypes.Device{}, fmt.Errorf("failed to load push device: %w", err)
}
device := Device{UserID: userID, RecipientID: req.RecipientID, Label: req.Label, Events: events, EnvironmentIDs: environmentIDs, LastSeenAt: &now}
- if err := s.db.WithContext(ctx).Create(&device).Error; err != nil {
- return apnstypes.Device{}, fmt.Errorf("failed to register push device: %w", err)
+ if createDeviceErr := s.db.WithContext(ctx).Create(&device).Error; createDeviceErr != nil {
+ return apnstypes.Device{}, fmt.Errorf("failed to register push device: %w", createDeviceErr)
}
return deviceDTOInternal(device), nil
}
@@ -371,8 +384,8 @@ func (s *ApnsService) UpdateDevice(ctx context.Context, userID, id string, req a
}
}
device.LastSeenAt = new(time.Now())
- if err := s.db.WithContext(ctx).Save(device).Error; err != nil {
- return apnstypes.Device{}, fmt.Errorf("failed to update push device: %w", err)
+ if saveDeviceErr := s.db.WithContext(ctx).Save(device).Error; saveDeviceErr != nil {
+ return apnstypes.Device{}, fmt.Errorf("failed to update push device: %w", saveDeviceErr)
}
return deviceDTOInternal(*device), nil
}
@@ -382,8 +395,8 @@ func (s *ApnsService) DeleteDevice(ctx context.Context, userID, id string) error
if err != nil {
return err
}
- if err := s.db.WithContext(ctx).Delete(device).Error; err != nil {
- return fmt.Errorf("failed to delete push device: %w", err)
+ if deleteDeviceErr := s.db.WithContext(ctx).Delete(device).Error; deleteDeviceErr != nil {
+ return fmt.Errorf("failed to delete push device: %w", deleteDeviceErr)
}
return nil
}
@@ -489,13 +502,13 @@ func (s *ApnsService) Enqueue(ctx context.Context, environmentID, environmentNam
return fmt.Errorf("failed to marshal push envelope: %w", err)
}
entry := OutboxEntry{EventID: envelope.EventID, Envelope: string(raw), NextAttemptAt: time.Now()}
- if err := s.db.WithContext(ctx).Create(&entry).Error; err != nil {
- return fmt.Errorf("failed to enqueue push notification: %w", err)
+ if enqueueNotificationErr := s.db.WithContext(ctx).Create(&entry).Error; enqueueNotificationErr != nil {
+ return fmt.Errorf("failed to enqueue push notification: %w", enqueueNotificationErr)
}
go func() {
drainCtx := context.WithoutCancel(ctx)
- if err := s.DrainOutbox(drainCtx); err != nil {
- slog.WarnContext(drainCtx, "Push outbox drain failed", "error", err)
+ if drainOutboxErr := s.DrainOutbox(drainCtx); drainOutboxErr != nil {
+ slog.WarnContext(drainCtx, "Push outbox drain failed", "error", drainOutboxErr)
}
}()
return nil
@@ -597,17 +610,17 @@ func (s *ApnsService) sendOutboxEntryInternal(ctx context.Context, entry OutboxE
UnknownRecipientIDs []string `json:"unknownRecipientIds"`
}
if json.Unmarshal(respBody, &parsed) == nil && len(parsed.UnknownRecipientIDs) > 0 {
- if err := s.db.WithContext(ctx).Where("recipient_id IN ?", parsed.UnknownRecipientIDs).Delete(&Device{}).Error; err != nil {
- slog.WarnContext(ctx, "Failed to prune stale push devices", "error", err)
+ if deleteUnknownDevicesErr := s.db.WithContext(ctx).Where("recipient_id IN ?", parsed.UnknownRecipientIDs).Delete(&Device{}).Error; deleteUnknownDevicesErr != nil {
+ slog.WarnContext(ctx, "Failed to prune stale push devices", "error", deleteUnknownDevicesErr)
}
}
s.finishOutboxInternal(ctx, entry, envelope, "")
case err == nil && status == http.StatusGone:
- if err := s.settings.UpdateSetting(ctx, "apnsChannelId", ""); err != nil {
- slog.WarnContext(ctx, "Failed to clear revoked push channel", "error", err)
+ if updateSettingErr := s.settings.UpdateSetting(ctx, "apnsChannelId", ""); updateSettingErr != nil {
+ slog.WarnContext(ctx, "Failed to clear revoked push channel", "error", updateSettingErr)
}
- if err := s.db.WithContext(ctx).Where("1 = 1").Delete(&Device{}).Error; err != nil {
- slog.WarnContext(ctx, "Failed to remove push devices after channel revocation", "error", err)
+ if deleteInvalidDevicesErr := s.db.WithContext(ctx).Where("1 = 1").Delete(&Device{}).Error; deleteInvalidDevicesErr != nil {
+ slog.WarnContext(ctx, "Failed to remove push devices after channel revocation", "error", deleteInvalidDevicesErr)
}
s.finishOutboxInternal(ctx, entry, envelope, "relay channel revoked; devices must pair again")
return true
diff --git a/backend/internal/appimages/service.go b/backend/internal/appimages/service.go
index 7863a7489..8c2605cd7 100644
--- a/backend/internal/appimages/service.go
+++ b/backend/internal/appimages/service.go
@@ -43,8 +43,8 @@ func NewApplicationImagesService(embeddedFS embed.FS, settingsService *settings.
ext := strings.ToLower(filepath.Ext(filename))
nameWithoutExt := strings.TrimSuffix(filename, ext)
- data, err := embeddedFS.ReadFile(filepath.Join(imageDir, filename))
- if err != nil {
+ data, readFileErr := embeddedFS.ReadFile(filepath.Join(imageDir, filename))
+ if readFileErr != nil {
continue
}
diff --git a/backend/internal/auth/buildables_test.go b/backend/internal/auth/buildables_test.go
index 4f058fd6d..2e9ec7321 100644
--- a/backend/internal/auth/buildables_test.go
+++ b/backend/internal/auth/buildables_test.go
@@ -3,7 +3,6 @@
package auth
import (
- "context"
"testing"
"github.com/stretchr/testify/require"
@@ -23,7 +22,7 @@ func enableAutoLoginFeature(t *testing.T) {
func TestGetAutoLoginConfig_Enabled(t *testing.T) {
enableAutoLoginFeature(t)
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthServiceTestDB(t)
settingsSvc, err := newSettingsServiceForAuthTestInternal(t, ctx, db)
@@ -49,7 +48,7 @@ func TestGetAutoLoginConfig_Enabled(t *testing.T) {
func TestGetAutoLoginConfig_DisabledWhenLocalAuthDisabled(t *testing.T) {
enableAutoLoginFeature(t)
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthServiceTestDB(t)
settingsSvc, err := newSettingsServiceForAuthTestInternal(t, ctx, db)
diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.go
index 2dba4aa32..b890cae2b 100644
--- a/backend/internal/auth/handler.go
+++ b/backend/internal/auth/handler.go
@@ -90,7 +90,21 @@ type UploadMyAvatarInput struct {
}
// RegisterAuth registers authentication routes using Huma.
-func RegisterAuth(api huma.API, userService *user.UserService, authService *AuthService, settingsService *settings.SettingsService, beginMFAAuthentication func(context.Context, string, authtypes.SessionMeta, string) (*authtypes.MFAChallenge, error)) {
+func RegisterAuth(
+ api huma.API,
+ userService *user.UserService,
+ authService *AuthService,
+ settingsService *settings.SettingsService,
+ beginMFAAuthentication func(
+ context.Context,
+ string,
+ authtypes.SessionMeta,
+ string,
+ ) (
+ *authtypes.MFAChallenge,
+ error,
+ ),
+) {
h := &AuthHandler{
userService: userService,
authService: authService,
@@ -226,8 +240,8 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpu
}
if userModel.PasskeyMFAEnabled {
- challenge, err := h.beginMFAAuthentication(ctx, userModel.ID, meta, session.UserSessionSourceLocal)
- if err != nil {
+ challenge, beginMFAAuthenticationErr := h.beginMFAAuthentication(ctx, userModel.ID, meta, session.UserSessionSourceLocal)
+ if beginMFAAuthenticationErr != nil {
return nil, huma.Error500InternalServerError("Authentication failed")
}
return &LoginOutput{
@@ -398,8 +412,8 @@ func (h *AuthHandler) LogoutAllOtherSessions(ctx context.Context, input *struct{
}
currentSessionID, _ := middleware.GetCurrentSessionIDFromContext(ctx)
- if err := h.authService.LogoutAllOtherSessions(ctx, userModel.ID, currentSessionID); err != nil {
- return nil, huma.Error500InternalServerError("failed to revoke sessions: " + err.Error())
+ if logoutAllOtherSessionsErr := h.authService.LogoutAllOtherSessions(ctx, userModel.ID, currentSessionID); logoutAllOtherSessionsErr != nil {
+ return nil, huma.Error500InternalServerError("failed to revoke sessions: " + logoutAllOtherSessionsErr.Error())
}
return &handlerutil.Out[base.MessageResponse]{
@@ -468,9 +482,9 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfil
userModel.DisplayName = input.Body.DisplayName
}
if input.Body.Email != nil {
- normalized, err := user.NormalizeOptionalEmail(input.Body.Email)
- if err != nil {
- return nil, huma.Error400BadRequest(err.Error())
+ normalized, normalizeOptionalEmailErr := user.NormalizeOptionalEmail(input.Body.Email)
+ if normalizeOptionalEmailErr != nil {
+ return nil, huma.Error400BadRequest(normalizeOptionalEmailErr.Error())
}
userModel.Email = normalized
}
@@ -484,8 +498,8 @@ func (h *AuthHandler) UpdateMyProfile(ctx context.Context, input *UpdateMyProfil
userModel.FontSize = input.Body.FontSize
}
if p := input.Body.Preferences; p != nil {
- if err := validatePreferencesInternal(p); err != nil {
- return nil, err
+ if validatePreferencesErr := validatePreferencesInternal(p); validatePreferencesErr != nil {
+ return nil, validatePreferencesErr
}
mergePreferencesInternal(&userModel.Preferences, p)
}
@@ -537,8 +551,8 @@ func (h *AuthHandler) UploadMyAvatar(ctx context.Context, input *UploadMyAvatarI
// Read one byte past the configured ceiling so oversized files are rejected
// without buffering the full multipart payload.
buf := new(bytes.Buffer)
- if _, err := buf.ReadFrom(io.LimitReader(f, maxSizeBytes+1)); err != nil {
- return nil, huma.Error500InternalServerError("failed to read file data: " + err.Error())
+ if _, readFromErr := buf.ReadFrom(io.LimitReader(f, maxSizeBytes+1)); readFromErr != nil {
+ return nil, huma.Error500InternalServerError("failed to read file data: " + readFromErr.Error())
}
if int64(buf.Len()) > maxSizeBytes {
@@ -553,8 +567,8 @@ func (h *AuthHandler) UploadMyAvatar(ctx context.Context, input *UploadMyAvatarI
}
data, mimeType = normalizeAvatarImageInternal(data, mimeType)
- if err := h.userService.UploadAvatar(ctx, currentUser.ID, data, mimeType); err != nil {
- slog.ErrorContext(ctx, "Failed to save avatar", "user_id", currentUser.ID, "error", err)
+ if uploadAvatarErr := h.userService.UploadAvatar(ctx, currentUser.ID, data, mimeType); uploadAvatarErr != nil {
+ slog.ErrorContext(ctx, "Failed to save avatar", "user_id", currentUser.ID, "error", uploadAvatarErr)
return nil, huma.Error500InternalServerError("failed to save avatar")
}
h.authService.InvalidateUserTokenCache(currentUser.ID)
@@ -594,8 +608,8 @@ func (h *AuthHandler) DeleteMyAvatar(ctx context.Context, input *struct{}) (*han
return nil, err
}
- if err := h.userService.DeleteAvatar(ctx, currentUser.ID); err != nil {
- slog.ErrorContext(ctx, "Failed to delete avatar", "user_id", currentUser.ID, "error", err)
+ if deleteAvatarErr := h.userService.DeleteAvatar(ctx, currentUser.ID); deleteAvatarErr != nil {
+ slog.ErrorContext(ctx, "Failed to delete avatar", "user_id", currentUser.ID, "error", deleteAvatarErr)
return nil, huma.Error500InternalServerError("failed to delete avatar")
}
h.authService.InvalidateUserTokenCache(currentUser.ID)
@@ -650,7 +664,7 @@ func normalizeAvatarImageInternal(data []byte, mimeType string) ([]byte, string)
}
var out bytes.Buffer
- if err := jpeg.Encode(&out, img, &jpeg.Options{Quality: 92}); err != nil {
+ if encodeErr := jpeg.Encode(&out, img, &jpeg.Options{Quality: 92}); encodeErr != nil {
return data, mimeType
}
if out.Len() == 0 || out.Len() >= len(data) {
diff --git a/backend/internal/auth/huma_middleware.go b/backend/internal/auth/huma_middleware.go
index e67a9c9d2..339556cfe 100644
--- a/backend/internal/auth/huma_middleware.go
+++ b/backend/internal/auth/huma_middleware.go
@@ -187,7 +187,19 @@ func createEnvironmentUserInternal(env *environment.Environment) *common.User {
// enforces security requirements defined on operations. It also resolves the
// caller's effective PermissionSet via permResolver and stashes it on the
// request context for downstream middleware.RequirePermission checks.
-func NewHumaMiddleware(api huma.API, authService *AuthService, apiKeyService *apikey.ApiKeyService, permResolver PermissionResolver, envTokenResolver EnvironmentAccessTokenResolver, cfg *config.Config) func(ctx huma.Context, next func(huma.Context)) {
+func NewHumaMiddleware(
+ api huma.API,
+ authService *AuthService,
+ apiKeyService *apikey.ApiKeyService,
+ permResolver PermissionResolver,
+ envTokenResolver EnvironmentAccessTokenResolver,
+ cfg *config.Config,
+) func(
+ ctx huma.Context,
+ next func(
+ huma.Context,
+ ),
+) {
return func(ctx huma.Context, next func(huma.Context)) {
ctx = huma.WithContext(ctx, context.WithValue(ctx.Context(), middleware.ContextKeyRemoteAddr, ctx.RemoteAddr()))
if authService == nil {
@@ -277,7 +289,18 @@ func opportunisticBearerAuthInternal(ctx huma.Context, authService *AuthService,
// handleApiKeyAuthInternal handles the API-key-present branch. Invalid user
// keys fail closed; only recognized environment tokens defer to bearer auth
// when both credentials are present on a bearer-capable operation.
-func handleApiKeyAuthInternal(api huma.API, ctx huma.Context, authService *AuthService, apiKeyService *apikey.ApiKeyService, permResolver PermissionResolver, envTokenResolver EnvironmentAccessTokenResolver, allowBearerFallback bool, next func(huma.Context)) {
+func handleApiKeyAuthInternal(
+ api huma.API,
+ ctx huma.Context,
+ authService *AuthService,
+ apiKeyService *apikey.ApiKeyService,
+ permResolver PermissionResolver,
+ envTokenResolver EnvironmentAccessTokenResolver,
+ allowBearerFallback bool,
+ next func(
+ huma.Context,
+ ),
+) {
if user, key, ok := tryApiKeyAuthInternal(ctx, apiKeyService); ok {
// Personal keys inherit the owner's role permissions (same resolution
// as session auth); scoped keys are limited to their own grants.
diff --git a/backend/internal/auth/huma_middleware_test.go b/backend/internal/auth/huma_middleware_test.go
index ecfc53b91..40672b68d 100644
--- a/backend/internal/auth/huma_middleware_test.go
+++ b/backend/internal/auth/huma_middleware_test.go
@@ -72,10 +72,10 @@ func TestNewHumaMiddleware_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T)
Path: "/secure",
Security: []map[string][]string{{"ApiKeyAuth": {}}},
}, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {
- user, ok := common.CurrentUserFromContext(ctx)
+ localUser, ok := common.CurrentUserFromContext(ctx)
require.True(t, ok)
- require.Equal(t, "environment:env-self", user.ID)
- require.Equal(t, "Self Target", user.Username)
+ require.Equal(t, "environment:env-self", localUser.ID)
+ require.Equal(t, "Self Target", localUser.Username)
ps, ok := middleware.PermissionsFromContext(ctx)
require.True(t, ok)
@@ -85,11 +85,11 @@ func TestNewHumaMiddleware_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T)
require.False(t, ps.IsGlobalAdmin())
resp := &secureOutput{}
- resp.Body.UserID = user.ID
+ resp.Body.UserID = localUser.ID
return resp, nil
})
- req := httptest.NewRequest(http.MethodGet, "/api/secure", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/secure", http.NoBody)
req.Header.Set("X-API-Key", token)
rec := httptest.NewRecorder()
@@ -144,16 +144,16 @@ func TestNewHumaMiddleware_UsesBearerWhenLoopbackProxySendsEnvironmentAccessToke
CID string `path:"cid"`
},
) (*secureOutput, error) {
- user, ok := common.CurrentUserFromContext(ctx)
+ localUser, ok := common.CurrentUserFromContext(ctx)
require.True(t, ok)
- require.Equal(t, "u-loopback", user.ID)
+ require.Equal(t, "u-loopback", localUser.ID)
resp := &secureOutput{}
- resp.Body.UserID = user.ID
+ resp.Body.UserID = localUser.ID
return resp, nil
})
- req := httptest.NewRequest(http.MethodPost, "/api/environments/0/containers/c/start", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/0/containers/c/start", http.NoBody)
req.Header.Set("Authorization", "Bearer "+bearerToken)
req.Header.Set("X-API-Key", envToken)
req.Header.Set("X-Arcane-Agent-Token", envToken)
@@ -191,7 +191,7 @@ func TestNewHumaMiddleware_RejectsApiKeyOnBearerOnlyOperation(t *testing.T) {
return &secureOutput{}, nil
})
- req := httptest.NewRequest(http.MethodPost, "/api/bearer-only", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/bearer-only", http.NoBody)
req.Header.Set("X-API-Key", "arc_whatever-valid-or-not-never-consulted")
rec := httptest.NewRecorder()
@@ -271,14 +271,14 @@ func TestNewHumaMiddleware_OpportunisticAuthOnPublicRoute(t *testing.T) {
cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}
authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, cfg).WithSigningKey(signingKey)
- _, err := userSvc.CreateUser(context.Background(), &common.User{
+ _, err := userSvc.CreateUser(t.Context(), &common.User{
ID: "u-logout",
Username: "logouttest",
})
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, _, err := sessionSvc.CreateSession(context.Background(), "u-logout", exp, authtypes.SessionMeta{})
+ localSession, _, err := sessionSvc.CreateSession(t.Context(), "u-logout", exp, authtypes.SessionMeta{})
require.NoError(t, err)
claims := map[string]any{
@@ -286,7 +286,7 @@ func TestNewHumaMiddleware_OpportunisticAuthOnPublicRoute(t *testing.T) {
"sub": "access",
"iat": time.Now().Unix(),
"exp": exp.Unix(),
- "sid": session.ID,
+ "sid": localSession.ID,
"user_id": "u-logout",
"username": "logouttest",
"roles": []string{"user"},
@@ -317,17 +317,17 @@ func TestNewHumaMiddleware_OpportunisticAuthOnPublicRoute(t *testing.T) {
t.Run("populates session ID when valid token presented", func(t *testing.T) {
sawSessionID = ""
- req := httptest.NewRequest(http.MethodPost, "/api/public", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/public", http.NoBody)
req.AddCookie(&http.Cookie{Name: cookie.InsecureTokenCookieName, Value: token})
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
- require.Equal(t, session.ID, sawSessionID)
+ require.Equal(t, localSession.ID, sawSessionID)
})
t.Run("succeeds with no token", func(t *testing.T) {
sawSessionID = ""
- req := httptest.NewRequest(http.MethodPost, "/api/public", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/public", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
@@ -336,7 +336,7 @@ func TestNewHumaMiddleware_OpportunisticAuthOnPublicRoute(t *testing.T) {
t.Run("succeeds with invalid token (does not block)", func(t *testing.T) {
sawSessionID = ""
- req := httptest.NewRequest(http.MethodPost, "/api/public", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/public", http.NoBody)
req.Header.Set("Authorization", "Bearer not-a-valid-token")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -360,14 +360,14 @@ func TestNewHumaMiddleware_VersionMismatchIsRecoverable(t *testing.T) {
authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, cfg).WithSigningKey(signingKey)
authSvc.browserSigningKey = browserSigningKey
- _, err := userSvc.CreateUser(context.Background(), &common.User{
+ _, err := userSvc.CreateUser(t.Context(), &common.User{
ID: "u-ver",
Username: "vertest",
})
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, _, err := sessionSvc.CreateSession(context.Background(), "u-ver", exp, authtypes.SessionMeta{})
+ localSession, _, err := sessionSvc.CreateSession(t.Context(), "u-ver", exp, authtypes.SessionMeta{})
require.NoError(t, err)
// An empty appVersion omits the claim, which passes the version check (no pin).
@@ -377,15 +377,15 @@ func TestNewHumaMiddleware_VersionMismatchIsRecoverable(t *testing.T) {
Subject(browserTokenSubject).
IssuedAt(time.Now()).
Expiration(exp).
- Claim(claimSessionID, session.ID).
+ Claim(claimSessionID, localSession.ID).
Claim(claimUserID, "u-ver")
if appVersion != "" {
builder.Claim(claimAppVersion, appVersion)
}
- token, err := builder.Build()
- require.NoError(t, err)
- signed, err := jwt.Sign(token, jwt.WithKey(jwa.HS512(), browserSigningKey))
- require.NoError(t, err)
+ token, buildErr := builder.Build()
+ require.NoError(t, buildErr)
+ signed, buildErr := jwt.Sign(token, jwt.WithKey(jwa.HS512(), browserSigningKey))
+ require.NoError(t, buildErr)
return string(signed)
}
@@ -408,7 +408,7 @@ func TestNewHumaMiddleware_VersionMismatchIsRecoverable(t *testing.T) {
})
t.Run("version mismatch returns a recoverable 401 without clearing cookies", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodGet, "/api/protected", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/protected", http.NoBody)
req.AddCookie(&http.Cookie{Name: cookie.InsecureTokenCookieName, Value: mintToken("v0.0.0-stale")})
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -422,13 +422,13 @@ func TestNewHumaMiddleware_VersionMismatchIsRecoverable(t *testing.T) {
t.Run("token without a version pin still authenticates", func(t *testing.T) {
token := mintToken("")
- req := httptest.NewRequest(http.MethodGet, "/api/protected", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/protected", http.NoBody)
req.AddCookie(&http.Cookie{Name: cookie.InsecureTokenCookieName, Value: token})
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
- req = httptest.NewRequest(http.MethodGet, "/api/protected", nil)
+ req = httptest.NewRequest(http.MethodGet, "/api/protected", http.NoBody)
req.Header.Set("Authorization", "Bearer "+token)
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -458,17 +458,17 @@ func TestNewHumaMiddleware_AgentAuthAppliesForwardedIconCatalog(t *testing.T) {
Path: "/secure-agent-icon-catalog",
Security: []map[string][]string{{"ApiKeyAuth": {}}},
}, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {
- user, ok := common.CurrentUserFromContext(ctx)
+ localUser, ok := common.CurrentUserFromContext(ctx)
require.True(t, ok)
- require.NotNil(t, user.Preferences.IconCatalog)
- require.Equal(t, "dashboard-icons", *user.Preferences.IconCatalog)
+ require.NotNil(t, localUser.Preferences.IconCatalog)
+ require.Equal(t, "dashboard-icons", *localUser.Preferences.IconCatalog)
resp := &secureOutput{}
- resp.Body.UserID = user.ID
+ resp.Body.UserID = localUser.ID
return resp, nil
})
- req := httptest.NewRequest(http.MethodGet, "/api/secure-agent-icon-catalog", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/secure-agent-icon-catalog", http.NoBody)
req.Header.Set(middleware.HeaderAgentToken, agentToken)
req.Header.Set(middleware.HeaderIconCatalog, "dashboard-icons")
rec := httptest.NewRecorder()
@@ -496,14 +496,14 @@ func setupAuthMiddlewareTestDBInternal(t *testing.T) *database.DB {
func mintHumaMiddlewareTestTokenInternal(t *testing.T, userSvc *user.UserService, sessionSvc *session.SessionService, signingKey *mldsa.PrivateKey, userID string) string {
t.Helper()
- _, err := userSvc.CreateUser(context.Background(), &common.User{
+ _, err := userSvc.CreateUser(t.Context(), &common.User{
ID: userID,
Username: userID,
})
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, _, err := sessionSvc.CreateSession(context.Background(), userID, exp, authtypes.SessionMeta{})
+ localSession, _, err := sessionSvc.CreateSession(t.Context(), userID, exp, authtypes.SessionMeta{})
require.NoError(t, err)
claims := map[string]any{
@@ -511,13 +511,17 @@ func mintHumaMiddlewareTestTokenInternal(t *testing.T, userSvc *user.UserService
"sub": "access",
"iat": time.Now().Unix(),
"exp": exp.Unix(),
- "sid": session.ID,
+ "sid": localSession.ID,
"user_id": userID,
"username": userID,
}
return signJWXTokenInternal(t, signingKey, claims)
}
+type staticPermissionResolverInternal struct {
+ ps *authz.PermissionSet
+}
+
func (r staticPermissionResolverInternal) ResolvePermissions(_ context.Context, _ *common.User) (*authz.PermissionSet, error) {
return r.ps, nil
}
@@ -526,10 +530,6 @@ func (r staticPermissionResolverInternal) ResolveApiKeyPermissions(_ context.Con
return r.ps, nil
}
-type staticPermissionResolverInternal struct {
- ps *authz.PermissionSet
-}
-
type testOperationProvider struct {
operation *huma.Operation
}
diff --git a/backend/internal/auth/middleware_test.go b/backend/internal/auth/middleware_test.go
index 1e5673483..1b0af5168 100644
--- a/backend/internal/auth/middleware_test.go
+++ b/backend/internal/auth/middleware_test.go
@@ -96,7 +96,7 @@ func TestAuthMiddleware_ManagerAuthResolvesPermissionsByKeyKind(t *testing.T) {
return c.JSON(http.StatusOK, map[string]any{"ok": true})
})
- req := httptest.NewRequest(http.MethodGet, "/secure", nil)
+ req := httptest.NewRequest(http.MethodGet, "/secure", http.NoBody)
req.Header.Set("X-API-Key", "valid-key")
rec := httptest.NewRecorder()
@@ -106,7 +106,7 @@ func TestAuthMiddleware_ManagerAuthResolvesPermissionsByKeyKind(t *testing.T) {
}
t.Run("browser cookie uses owner role permissions", func(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthMiddlewareTestDBInternal(t)
userSvc := usersvc.NewUserService(db, nil)
sessionSvc := session.NewSessionService(db)
@@ -139,13 +139,13 @@ func TestAuthMiddleware_ManagerAuthResolvesPermissionsByKeyKind(t *testing.T) {
return c.NoContent(http.StatusOK)
})
- req := httptest.NewRequest(http.MethodGet, "/secure", nil)
+ req := httptest.NewRequest(http.MethodGet, "/secure", http.NoBody)
req.Header.Set("Authorization", "Bearer "+tokenPair.BrowserToken)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusUnauthorized, rec.Code)
- req = httptest.NewRequest(http.MethodGet, "/secure", nil)
+ req = httptest.NewRequest(http.MethodGet, "/secure", http.NoBody)
req.AddCookie(&http.Cookie{Name: cookie.InsecureTokenCookieName, Value: tokenPair.BrowserToken})
rec = httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -203,7 +203,7 @@ func TestAuthMiddleware_ManagerAuthEnvironmentAccessToken(t *testing.T) {
return c.JSON(http.StatusOK, map[string]any{"userId": user.ID})
})
- req := httptest.NewRequest(http.MethodGet, "/secure", nil)
+ req := httptest.NewRequest(http.MethodGet, "/secure", http.NoBody)
req.Header.Set(tc.header, token)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
diff --git a/backend/internal/auth/module.go b/backend/internal/auth/module.go
index 0073eb41d..1e256e904 100644
--- a/backend/internal/auth/module.go
+++ b/backend/internal/auth/module.go
@@ -19,7 +19,20 @@ type Module struct {
beginMFAAuthentication func(context.Context, string, authtypes.SessionMeta, string) (*authtypes.MFAChallenge, error)
}
-func New(service *AuthService, userService *user.UserService, settingsService *settings.SettingsService, beginMFAAuthentication func(context.Context, string, authtypes.SessionMeta, string) (*authtypes.MFAChallenge, error)) *Module {
+func New(
+ service *AuthService,
+ userService *user.UserService,
+ settingsService *settings.SettingsService,
+ beginMFAAuthentication func(
+ context.Context,
+ string,
+ authtypes.SessionMeta,
+ string,
+ ) (
+ *authtypes.MFAChallenge,
+ error,
+ ),
+) *Module {
return &Module{service: service, user: userService, settings: settingsService, beginMFAAuthentication: beginMFAAuthentication}
}
diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.go
index 1d857c4b4..e8f35cc0a 100644
--- a/backend/internal/auth/service.go
+++ b/backend/internal/auth/service.go
@@ -82,7 +82,14 @@ type AuthService struct {
cacheFillMu sync.Mutex
}
-func NewAuthService(userService *user.UserService, settingsService *settings.SettingsService, eventService *event.EventService, sessionService *session.SessionService, roleService *role.RoleService, cfg *config.Config) *AuthService {
+func NewAuthService(
+ userService *user.UserService,
+ settingsService *settings.SettingsService,
+ eventService *event.EventService,
+ sessionService *session.SessionService,
+ roleService *role.RoleService,
+ cfg *config.Config,
+) *AuthService {
return &AuthService{
userService: userService,
settingsService: settingsService,
@@ -147,10 +154,10 @@ func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*auth.Oid
// In tests, a zero-valued settings.SettingsService may panic; treat as merge disabled
_ = recover()
}()
- if settings, err := s.settingsService.GetSettings(ctx); err == nil {
- mergeAccounts = settings.OidcMergeAccounts.IsTrue()
- providerName = settings.OidcProviderName.Value
- providerLogoUrl = settings.OidcProviderLogoUrl.Value
+ if localSettings, err := s.settingsService.GetSettings(ctx); err == nil {
+ mergeAccounts = localSettings.OidcMergeAccounts.IsTrue()
+ providerName = localSettings.OidcProviderName.Value
+ providerLogoUrl = localSettings.OidcProviderLogoUrl.Value
}
}()
}
@@ -174,12 +181,12 @@ func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*auth.Oid
}
func (s *AuthService) GetSessionTimeout(ctx context.Context) (int, error) {
- settings, err := s.settingsService.GetSettings(ctx)
+ localSettings, err := s.settingsService.GetSettings(ctx)
if err != nil {
return 60, err
}
- minutes := settings.AuthSessionTimeout.AsInt()
+ minutes := localSettings.AuthSessionTimeout.AsInt()
if minutes <= 0 {
minutes = 60
}
@@ -194,19 +201,19 @@ func (s *AuthService) GetSessionTimeout(ctx context.Context) (int, error) {
}
func (s *AuthService) IsLocalAuthEnabled(ctx context.Context) (bool, error) {
- settings, err := s.settingsService.GetSettings(ctx)
+ localSettings, err := s.settingsService.GetSettings(ctx)
if err != nil {
return true, err
}
- return settings.AuthLocalEnabled.IsTrue(), nil
+ return localSettings.AuthLocalEnabled.IsTrue(), nil
}
func (s *AuthService) IsOidcEnabled(ctx context.Context) (bool, error) {
- settings, err := s.settingsService.GetSettings(ctx)
+ localSettings, err := s.settingsService.GetSettings(ctx)
if err != nil {
return false, err
}
- return settings.OidcEnabled.IsTrue(), nil
+ return localSettings.OidcEnabled.IsTrue(), nil
}
func (s *AuthService) GetOidcConfig(ctx context.Context) (*settings.OidcConfig, error) {
@@ -234,7 +241,7 @@ func (s *AuthService) AuthenticateLocalPrimary(ctx context.Context, username, pa
return nil, ErrLocalAuthDisabled
}
- user, err := s.userService.GetUserByUsername(ctx, username)
+ localUser, err := s.userService.GetUserByUsername(ctx, username)
if err != nil && !errors.Is(err, common.ErrUserNotFound) {
return nil, err
}
@@ -250,30 +257,30 @@ func (s *AuthService) AuthenticateLocalPrimary(ctx context.Context, username, pa
return nil, ErrInvalidCredentials
case emailErr != nil && !errors.Is(emailErr, common.ErrUserNotFound):
return nil, emailErr
- case emailErr == nil && user != nil && emailUser.ID != user.ID:
+ case emailErr == nil && localUser != nil && emailUser.ID != localUser.ID:
slog.WarnContext(ctx, "Rejecting login: identifier matches one account's username and a different account's email", "identifier", username)
return nil, ErrInvalidCredentials
- case emailErr == nil && user == nil:
- user = emailUser
+ case emailErr == nil && localUser == nil:
+ localUser = emailUser
}
}
- if user == nil {
+ if localUser == nil {
return nil, ErrInvalidCredentials
}
- if err := s.userService.ValidatePassword(user.PasswordHash, password); err != nil {
+ if validatePasswordErr := s.userService.ValidatePassword(localUser.PasswordHash, password); validatePasswordErr != nil {
return nil, ErrInvalidCredentials
}
- user.LastLogin = new(time.Now())
- userCopy := new(*user)
+ localUser.LastLogin = new(time.Now())
+ userCopy := new(*localUser)
s.runInBackground(ctx, "update_last_login", func(ctx context.Context) error {
- if _, err := s.userService.UpdateUser(ctx, userCopy, nil); err != nil {
- return fmt.Errorf("failed to update user's last login time: %w", err)
+ if _, updateUserErr := s.userService.UpdateUser(ctx, userCopy, nil); updateUserErr != nil {
+ return fmt.Errorf("failed to update user's last login time: %w", updateUserErr)
}
return nil
})
- return user, nil
+ return localUser, nil
}
// PrepareOidcLogin reconciles the provider identity without creating a
@@ -288,15 +295,15 @@ func (s *AuthService) PrepareOidcLogin(ctx context.Context, userInfo auth.OidcUs
// CompleteLogin creates the authenticated session after all required factors
// have succeeded. Source is server-selected and is persisted with the session.
-func (s *AuthService) CompleteLogin(ctx context.Context, user *common.User, meta auth.SessionMeta, source, mfaMethod string, eventMetadata ...database.JSON) (*TokenPair, error) {
- if user == nil {
+func (s *AuthService) CompleteLogin(ctx context.Context, localUser *common.User, meta auth.SessionMeta, source, mfaMethod string, eventMetadata ...database.JSON) (*TokenPair, error) {
+ if localUser == nil {
return nil, common.ErrUserNotFound
}
if strings.TrimSpace(source) == "" {
source = session.UserSessionSourceLocal
}
mfaMethod = strings.TrimSpace(mfaMethod)
- if user.PasskeyMFAEnabled && source != session.UserSessionSourcePasskey && mfaMethod != session.PasskeyMFAMethod && mfaMethod != session.RecoveryCodeMFAMethod {
+ if localUser.PasskeyMFAEnabled && source != session.UserSessionSourcePasskey && mfaMethod != session.PasskeyMFAMethod && mfaMethod != session.RecoveryCodeMFAMethod {
return nil, ErrMFARequired
}
meta.Source = source
@@ -306,7 +313,7 @@ func (s *AuthService) CompleteLogin(ctx context.Context, user *common.User, meta
meta.MFAVerifiedAt = &now
}
- tokenPair, err := s.createSessionAndTokensInternal(ctx, user, meta)
+ tokenPair, err := s.createSessionAndTokensInternal(ctx, localUser, meta)
if err != nil {
return nil, err
}
@@ -319,8 +326,8 @@ func (s *AuthService) CompleteLogin(ctx context.Context, user *common.User, meta
metadata["mfa"] = meta.MFAMethod
}
if s.eventService != nil {
- logUserID := user.ID
- logUsername := user.Username
+ logUserID := localUser.ID
+ logUsername := localUser.Username
s.runInBackground(ctx, "log_user_login", func(ctx context.Context) error {
return s.eventService.LogUserEvent(ctx, event.EventTypeUserLogin, logUserID, logUsername, metadata)
})
@@ -330,40 +337,40 @@ func (s *AuthService) CompleteLogin(ctx context.Context, user *common.User, meta
}
func (s *AuthService) Login(ctx context.Context, username, password string, meta auth.SessionMeta) (*common.User, *TokenPair, error) {
- user, err := s.AuthenticateLocalPrimary(ctx, username, password)
+ localUser, err := s.AuthenticateLocalPrimary(ctx, username, password)
if err != nil {
return nil, nil, err
}
- if user.PasskeyMFAEnabled {
+ if localUser.PasskeyMFAEnabled {
return nil, nil, ErrMFARequired
}
- tokenPair, err := s.CompleteLogin(ctx, user, meta, session.UserSessionSourceLocal, "")
+ tokenPair, err := s.CompleteLogin(ctx, localUser, meta, session.UserSessionSourceLocal, "")
if err != nil {
return nil, nil, err
}
- return user, tokenPair, nil
+ return localUser, tokenPair, nil
}
func (s *AuthService) OidcLogin(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse, meta auth.SessionMeta) (*common.User, *TokenPair, error) {
- user, isNewUser, err := s.PrepareOidcLogin(ctx, userInfo, tokenResp)
+ localUser, isNewUser, err := s.PrepareOidcLogin(ctx, userInfo, tokenResp)
if err != nil {
return nil, nil, err
}
- if user.PasskeyMFAEnabled {
+ if localUser.PasskeyMFAEnabled {
return nil, nil, ErrMFARequired
}
- tokenPair, err := s.CompleteLogin(ctx, user, meta, session.UserSessionSourceOidc, "", database.JSON{
+ tokenPair, err := s.CompleteLogin(ctx, localUser, meta, session.UserSessionSourceOidc, "", database.JSON{
"newUser": isNewUser,
"subject": userInfo.Subject,
})
if err != nil {
return nil, nil, err
}
- return user, tokenPair, nil
+ return localUser, tokenPair, nil
}
-func (s *AuthService) LogLogout(ctx context.Context, user *common.User) {
- if s.eventService == nil || user == nil {
+func (s *AuthService) LogLogout(ctx context.Context, localUser *common.User) {
+ if s.eventService == nil || localUser == nil {
return
}
@@ -371,8 +378,8 @@ func (s *AuthService) LogLogout(ctx context.Context, user *common.User) {
"action": "logout",
}
- userID := user.ID
- username := user.Username
+ userID := localUser.ID
+ username := localUser.Username
s.runInBackground(ctx, "log_user_logout", func(ctx context.Context) error {
return s.eventService.LogUserEvent(ctx, event.EventTypeUserLogout, userID, username, metadata)
})
@@ -382,13 +389,13 @@ func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.Oi
if err := normalization.Normalize(&userInfo); err != nil {
return nil, false, err
}
- user, err := s.userService.GetUserByOidcSubjectId(ctx, userInfo.Subject)
+ localUser, err := s.userService.GetUserByOidcSubjectId(ctx, userInfo.Subject)
if err != nil && !errors.Is(err, common.ErrUserNotFound) {
return nil, false, err
}
- if user != nil {
- return s.updateExistingOidcUser(ctx, user, userInfo, tokenResp)
+ if localUser != nil {
+ return s.updateExistingOidcUser(ctx, localUser, userInfo, tokenResp)
}
mergedUser, merged, err := s.tryMergeOidcUser(ctx, userInfo, tokenResp)
@@ -412,11 +419,11 @@ func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.Oi
return created, true, nil
}
-func (s *AuthService) updateExistingOidcUser(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {
- if err := s.updateOidcUser(ctx, user, userInfo, tokenResp); err != nil {
+func (s *AuthService) updateExistingOidcUser(ctx context.Context, localUser *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {
+ if err := s.updateOidcUser(ctx, localUser, userInfo, tokenResp); err != nil {
return nil, false, err
}
- return user, false, nil
+ return localUser, false, nil
}
func (s *AuthService) tryMergeOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {
@@ -444,8 +451,8 @@ func (s *AuthService) tryMergeOidcUser(ctx context.Context, userInfo auth.OidcUs
}
func (s *AuthService) isOidcMergeEnabled(ctx context.Context) bool {
- settings, settingsErr := s.settingsService.GetSettings(ctx)
- return settingsErr == nil && settings.OidcMergeAccounts.IsTrue()
+ localSettings, settingsErr := s.settingsService.GetSettings(ctx)
+ return settingsErr == nil && localSettings.OidcMergeAccounts.IsTrue()
}
func (s *AuthService) validateMergeEmailVerification(userInfo auth.OidcUserInfo) error {
@@ -480,7 +487,7 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUser
displayName = new(username)
}
- user := &common.User{
+ localUser := &common.User{
ID: uuid.New().String(),
Username: username,
DisplayName: displayName,
@@ -489,7 +496,7 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUser
LastLogin: new(time.Now()),
}
- s.persistOidcTokens(user, tokenResp)
+ s.persistOidcTokens(localUser, tokenResp)
// The username probe is not atomic with the insert: a concurrent
// first-time login can claim the candidate in between, failing the
@@ -497,21 +504,21 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUser
var createErr error
for attempt := range 3 {
if attempt > 0 {
- if user.Username, err = s.resolveOidcUsernameInternal(ctx, userInfo); err != nil {
+ if localUser.Username, err = s.resolveOidcUsernameInternal(ctx, userInfo); err != nil {
return nil, err
}
}
- if _, createErr = s.userService.CreateUser(ctx, user); createErr == nil {
+ if _, createErr = s.userService.CreateUser(ctx, localUser); createErr == nil {
break
}
}
if createErr != nil {
return nil, createErr
}
- if err := s.syncOidcRoleAssignments(ctx, user, userInfo, tokenResp); err != nil {
- slog.WarnContext(ctx, "failed to sync OIDC role assignments on user create", "error", err, "user_id", user.ID)
+ if syncOidcRoleAssignmentsErr := s.syncOidcRoleAssignments(ctx, localUser, userInfo, tokenResp); syncOidcRoleAssignmentsErr != nil {
+ slog.WarnContext(ctx, "failed to sync OIDC role assignments on user create", "error", syncOidcRoleAssignmentsErr, "user_id", localUser.ID)
}
- return user, nil
+ return localUser, nil
}
// resolveOidcUsernameInternal returns the preferred username for a new OIDC
@@ -550,29 +557,29 @@ func (s *AuthService) resolveOidcUsernameInternal(ctx context.Context, userInfo
}
}
-func (s *AuthService) updateOidcUser(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
- if userInfo.Name != "" && user.DisplayName == nil {
- user.DisplayName = new(userInfo.Name)
+func (s *AuthService) updateOidcUser(ctx context.Context, localUser *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
+ if userInfo.Name != "" && localUser.DisplayName == nil {
+ localUser.DisplayName = new(userInfo.Name)
}
- if userInfo.Email != "" && user.Email == nil {
- user.Email = new(userInfo.Email)
+ if userInfo.Email != "" && localUser.Email == nil {
+ localUser.Email = new(userInfo.Email)
}
- s.persistOidcTokens(user, tokenResp)
+ s.persistOidcTokens(localUser, tokenResp)
- user.LastLogin = new(time.Now())
- if _, err := s.userService.UpdateUser(ctx, user, nil); err != nil {
+ localUser.LastLogin = new(time.Now())
+ if _, err := s.userService.UpdateUser(ctx, localUser, nil); err != nil {
return err
}
- if err := s.syncOidcRoleAssignments(ctx, user, userInfo, tokenResp); err != nil {
- slog.WarnContext(ctx, "failed to sync OIDC role assignments on user update", "error", err, "user_id", user.ID)
+ if err := s.syncOidcRoleAssignments(ctx, localUser, userInfo, tokenResp); err != nil {
+ slog.WarnContext(ctx, "failed to sync OIDC role assignments on user update", "error", err, "user_id", localUser.ID)
}
return nil
}
-func (s *AuthService) mergeOidcWithExistingUser(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
+func (s *AuthService) mergeOidcWithExistingUser(ctx context.Context, localUser *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
// Perform the merge atomically to avoid races when multiple OIDC subjects share the same email
- merged, err := s.userService.AttachOidcSubjectTransactional(ctx, user.ID, userInfo.Subject, func(u *common.User) {
+ merged, err := s.userService.AttachOidcSubjectTransactional(ctx, localUser.ID, userInfo.Subject, func(u *common.User) {
if userInfo.Name != "" && u.DisplayName == nil {
u.DisplayName = new(userInfo.Name)
}
@@ -593,8 +600,8 @@ func (s *AuthService) mergeOidcWithExistingUser(ctx context.Context, user *commo
// syncOidcRoleAssignments rebuilds the user's `source='oidc'` role assignments
// based on the OIDC group claim and the configured OidcRoleMapping rows.
// Manual assignments are untouched.
-func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
- if s.roleService == nil || user == nil {
+func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, localUser *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {
+ if s.roleService == nil || localUser == nil {
return nil
}
@@ -629,7 +636,7 @@ func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *common.
})
}
- return s.roleService.ReplaceOidcAssignments(ctx, user.ID, desired)
+ return s.roleService.ReplaceOidcAssignments(ctx, localUser.ID, desired)
}
// extractOidcGroups reads the user's group memberships from the OIDC userinfo
@@ -660,26 +667,26 @@ func (s *AuthService) extractOidcGroups(ctx context.Context, userInfo auth.OidcU
}
func (s *AuthService) oidcGroupsClaim(ctx context.Context) string {
- settings, err := s.settingsService.GetSettings(ctx)
+ localSettings, err := s.settingsService.GetSettings(ctx)
if err != nil {
return "groups"
}
- v := strings.TrimSpace(settings.OidcGroupsClaim.Value)
+ v := strings.TrimSpace(localSettings.OidcGroupsClaim.Value)
return kit.Ternary(v == "", "groups", v)
}
-func (s *AuthService) persistOidcTokens(user *common.User, tokenResp *auth.OidcTokenResponse) {
+func (s *AuthService) persistOidcTokens(localUser *common.User, tokenResp *auth.OidcTokenResponse) {
if tokenResp == nil {
return
}
if tokenResp.AccessToken != "" {
- user.OidcAccessToken = new(tokenResp.AccessToken)
+ localUser.OidcAccessToken = new(tokenResp.AccessToken)
}
if tokenResp.RefreshToken != "" {
- user.OidcRefreshToken = new(tokenResp.RefreshToken)
+ localUser.OidcRefreshToken = new(tokenResp.RefreshToken)
}
if tokenResp.ExpiresIn > 0 {
- user.OidcAccessTokenExpiresAt = new(time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second))
+ localUser.OidcAccessTokenExpiresAt = new(time.Now().Add(time.Duration(tokenResp.ExpiresIn) * time.Second))
}
}
@@ -750,8 +757,8 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, met
if userSession.UserID != claims.UserID {
return nil, common.ErrInvalidToken
}
- if err := session.ValidateActive(userSession); err != nil {
- return nil, err
+ if validateActiveErr := session.ValidateActive(userSession); validateActiveErr != nil {
+ return nil, validateActiveErr
}
rotatedSession, refreshJTI, err := s.sessionService.RotateRefreshToken(ctx, claims.SessionID, claims.ID, meta)
@@ -759,18 +766,18 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, met
return nil, err
}
- user, err := s.userService.GetUserByID(ctx, claims.UserID)
+ localUser, err := s.userService.GetUserByID(ctx, claims.UserID)
if err != nil {
return nil, err
}
- return s.buildTokenPairInternal(ctx, user, rotatedSession, refreshJTI)
+ return s.buildTokenPairInternal(ctx, localUser, rotatedSession, refreshJTI)
}
func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*common.User, string, error) {
tokenHash := kit.SHA256Hex(accessToken)
- if user, sessionID, ok := s.cachedVerificationInternal(tokenHash); ok {
- return user, sessionID, nil
+ if localUser, sessionID, ok := s.cachedVerificationInternal(tokenHash); ok {
+ return localUser, sessionID, nil
}
signingKey, err := s.signingKeyInternal(ctx)
if err != nil {
@@ -785,8 +792,8 @@ func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*com
func (s *AuthService) VerifyBrowserToken(ctx context.Context, browserToken string) (*common.User, string, error) {
tokenHash := "browser:" + kit.SHA256Hex(browserToken)
- if user, sessionID, ok := s.cachedVerificationInternal(tokenHash); ok {
- return user, sessionID, nil
+ if localUser, sessionID, ok := s.cachedVerificationInternal(tokenHash); ok {
+ return localUser, sessionID, nil
}
algorithm, ok := signedTokenAlgorithmInternal(browserToken)
if !ok {
@@ -848,8 +855,8 @@ func (s *AuthService) verifyTokenClaimsInternal(ctx context.Context, tokenHash s
if userSession.UserID != dbUser.ID {
return nil, "", common.ErrInvalidToken
}
- if err := session.ValidateActive(userSession); err != nil {
- return nil, "", err
+ if validateActiveErr := session.ValidateActive(userSession); validateActiveErr != nil {
+ return nil, "", validateActiveErr
}
s.cacheFillMu.Lock()
@@ -866,23 +873,23 @@ func (s *AuthService) ChangePassword(ctx context.Context, userID, currentPasswor
return common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.
}
- user, err := s.userService.GetUserByID(ctx, userID)
+ localUser, err := s.userService.GetUserByID(ctx, userID)
if err != nil {
return err
}
- if user.PasswordHash != "" {
- if err := s.userService.ValidatePassword(user.PasswordHash, currentPassword); err != nil {
+ if localUser.PasswordHash != "" {
+ if validatePasswordErr := s.userService.ValidatePassword(localUser.PasswordHash, currentPassword); validatePasswordErr != nil {
return ErrInvalidCredentials
}
}
policy := s.passwordPolicyInternal(ctx)
- if err := validation.ValidatePasswordPolicy(newPassword, policy); err != nil {
- return common.Classify(common.ErrValidation, err)
+ if validatePasswordPolicyErr := validation.ValidatePasswordPolicy(newPassword, policy); validatePasswordPolicyErr != nil {
+ return common.Classify(common.ErrValidation, validatePasswordPolicyErr)
}
- if _, err = s.userService.SetPasswordAndRevokeSessionsExcept(ctx, user, newPassword, currentSessionID); err != nil {
+ if _, err = s.userService.SetPasswordAndRevokeSessionsExcept(ctx, localUser, newPassword, currentSessionID); err != nil {
return err
}
// The current session's cached user still carries the old password flags.
@@ -947,19 +954,19 @@ func (s *AuthService) LogoutAllOtherSessions(ctx context.Context, userID, curren
return nil
}
-func (s *AuthService) createSessionAndTokensInternal(ctx context.Context, user *common.User, meta auth.SessionMeta) (*TokenPair, error) {
+func (s *AuthService) createSessionAndTokensInternal(ctx context.Context, localUser *common.User, meta auth.SessionMeta) (*TokenPair, error) {
if s.sessionService == nil {
return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.
}
refreshExpiry := time.Now().Add(s.refreshExpiry)
- session, refreshJTI, err := s.sessionService.CreateSession(ctx, user.ID, refreshExpiry, meta)
+ localSession, refreshJTI, err := s.sessionService.CreateSession(ctx, localUser.ID, refreshExpiry, meta)
if err != nil {
return nil, err
}
- return s.buildTokenPairInternal(ctx, user, session, refreshJTI)
+ return s.buildTokenPairInternal(ctx, localUser, localSession, refreshJTI)
}
-func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *common.User, session *session.UserSession, refreshJTI string) (*TokenPair, error) {
+func (s *AuthService) buildTokenPairInternal(ctx context.Context, localUser *common.User, localSession *session.UserSession, refreshJTI string) (*TokenPair, error) {
sessionTimeout, _ := s.GetSessionTimeout(ctx)
now := time.Now()
accessTokenExpiry := now.Add(time.Duration(sessionTimeout) * time.Minute)
@@ -970,20 +977,20 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *common.U
}
accessBuilder := jwt.NewBuilder().
- JwtID(user.ID).
+ JwtID(localUser.ID).
Subject(accessTokenSubject).
IssuedAt(now).
Expiration(accessTokenExpiry).
- Claim(claimSessionID, session.ID).
- Claim(claimUserID, user.ID)
- if user.Username != "" {
- accessBuilder.Claim(claimUsername, user.Username)
+ Claim(claimSessionID, localSession.ID).
+ Claim(claimUserID, localUser.ID)
+ if localUser.Username != "" {
+ accessBuilder.Claim(claimUsername, localUser.Username)
}
- if user.Email != nil && *user.Email != "" {
- accessBuilder.Claim(claimEmail, *user.Email)
+ if localUser.Email != nil && *localUser.Email != "" {
+ accessBuilder.Claim(claimEmail, *localUser.Email)
}
- if user.DisplayName != nil && *user.DisplayName != "" {
- accessBuilder.Claim(claimDisplayName, *user.DisplayName)
+ if localUser.DisplayName != nil && *localUser.DisplayName != "" {
+ accessBuilder.Claim(claimDisplayName, *localUser.DisplayName)
}
if config.Version != "" {
accessBuilder.Claim(claimAppVersion, config.Version)
@@ -1001,9 +1008,9 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *common.U
JwtID(refreshJTI).
Subject(refreshTokenSubject).
IssuedAt(now).
- Expiration(session.ExpiresAt).
- Claim(claimUserID, user.ID).
- Claim(claimSessionID, session.ID)
+ Expiration(localSession.ExpiresAt).
+ Claim(claimUserID, localUser.ID).
+ Claim(claimSessionID, localSession.ID)
if config.Version != "" {
refreshBuilder.Claim(claimAppVersion, config.Version)
}
@@ -1025,8 +1032,8 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *common.U
Subject(browserTokenSubject).
IssuedAt(now).
Expiration(accessTokenExpiry).
- Claim(claimSessionID, session.ID).
- Claim(claimUserID, user.ID)
+ Claim(claimSessionID, localSession.ID).
+ Claim(claimUserID, localUser.ID)
if config.Version != "" {
browserBuilder.Claim(claimAppVersion, config.Version)
}
@@ -1047,11 +1054,11 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *common.U
}, nil
}
-func (s *AuthService) IssueFederatedToken(ctx context.Context, user *common.User, credentialID string, ttlSeconds int) (*TokenPair, error) {
+func (s *AuthService) IssueFederatedToken(ctx context.Context, localUser *common.User, credentialID string, ttlSeconds int) (*TokenPair, error) {
if s.sessionService == nil {
return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured")) //nolint:staticcheck // Preserve the existing error message.
}
- if user == nil {
+ if localUser == nil {
return nil, common.ErrUserNotFound
}
@@ -1059,7 +1066,7 @@ func (s *AuthService) IssueFederatedToken(ctx context.Context, user *common.User
now := time.Now()
accessTokenExpiry := now.Add(time.Duration(ttlSeconds) * time.Second)
- federatedSession, err := s.sessionService.CreateFederatedSession(ctx, user.ID, accessTokenExpiry, credentialID)
+ federatedSession, err := s.sessionService.CreateFederatedSession(ctx, localUser.ID, accessTokenExpiry, credentialID)
if err != nil {
return nil, err
}
@@ -1069,22 +1076,22 @@ func (s *AuthService) IssueFederatedToken(ctx context.Context, user *common.User
return nil, err
}
builder := jwt.NewBuilder().
- JwtID(user.ID).
+ JwtID(localUser.ID).
Subject(accessTokenSubject).
IssuedAt(now).
Expiration(accessTokenExpiry).
Claim(claimSessionID, federatedSession.ID).
- Claim(claimUserID, user.ID).
+ Claim(claimUserID, localUser.ID).
Claim(claimTokenType, session.UserSessionSourceFederated).
Claim(claimFederatedCredentialID, credentialID)
- if user.Username != "" {
- builder.Claim(claimUsername, user.Username)
+ if localUser.Username != "" {
+ builder.Claim(claimUsername, localUser.Username)
}
- if user.Email != nil && *user.Email != "" {
- builder.Claim(claimEmail, *user.Email)
+ if localUser.Email != nil && *localUser.Email != "" {
+ builder.Claim(claimEmail, *localUser.Email)
}
- if user.DisplayName != nil && *user.DisplayName != "" {
- builder.Claim(claimDisplayName, *user.DisplayName)
+ if localUser.DisplayName != nil && *localUser.DisplayName != "" {
+ builder.Claim(claimDisplayName, *localUser.DisplayName)
}
if config.Version != "" {
builder.Claim(claimAppVersion, config.Version)
diff --git a/backend/internal/auth/service_test.go b/backend/internal/auth/service_test.go
index 3ef5cf5ef..540bcde3d 100644
--- a/backend/internal/auth/service_test.go
+++ b/backend/internal/auth/service_test.go
@@ -56,7 +56,7 @@ func newSettingsServiceForAuthTestInternal(t testing.TB, ctx context.Context, db
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -137,7 +137,7 @@ func makeAccessToken(t *testing.T, key *mldsa.PrivateKey, subject, id, username
return signLegacyTokenInternal(t, key, claims)
}
-func makeRefreshToken(t *testing.T, key *mldsa.PrivateKey, subject, id string, exp time.Time, userIDAndSessionID ...string) string {
+func makeRefreshTokenInternal(t *testing.T, key *mldsa.PrivateKey, id string, exp time.Time, userIDAndSessionID ...string) string {
t.Helper()
userID := id
sessionID := ""
@@ -149,7 +149,7 @@ func makeRefreshToken(t *testing.T, key *mldsa.PrivateKey, subject, id string, e
}
claims := map[string]any{
"jti": id,
- "sub": subject,
+ "sub": "refresh",
"iat": time.Now().Unix(),
"exp": exp.Unix(),
"user_id": userID,
@@ -162,12 +162,12 @@ func makeRefreshToken(t *testing.T, key *mldsa.PrivateKey, subject, id string, e
func createTestSession(t *testing.T, db *database.DB, userID string, expiresAt time.Time) (*session.UserSession, string) {
t.Helper()
sessionSvc := session.NewSessionService(db)
- session, refreshJTI, err := sessionSvc.CreateSession(context.Background(), userID, expiresAt, auth.SessionMeta{
+ localSession, refreshJTI, err := sessionSvc.CreateSession(t.Context(), userID, expiresAt, auth.SessionMeta{
UserAgent: "test-agent",
IPAddress: "127.0.0.1",
})
require.NoError(t, err)
- return session, refreshJTI
+ return localSession, refreshJTI
}
func makeUnsignedToken(t *testing.T, claims map[string]any) string {
@@ -183,20 +183,20 @@ func TestVerifyToken_ValidClaims(t *testing.T) {
s.sessionService = session.NewSessionService(db)
// Create user in DB
- user := &common.User{
+ localUser := &common.User{
ID: "u123",
Username: "alice",
Email: new("[email protected]"),
DisplayName: new("Alice"),
}
- _, err := userSvc.CreateUser(context.Background(), user)
+ _, err := userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, _ := createTestSession(t, db, "u123", exp)
- token := makeAccessToken(t, s.signingKey, "access", "u123", "alice", []string{"user", "admin"}, "[email protected]", "Alice", exp, session.ID)
+ localSession, _ := createTestSession(t, db, "u123", exp)
+ token := makeAccessToken(t, s.signingKey, "access", "u123", "alice", []string{"user", "admin"}, "[email protected]", "Alice", exp, localSession.ID)
- verifiedUser, _, err := s.VerifyToken(context.Background(), token)
+ verifiedUser, _, err := s.VerifyToken(t.Context(), token)
require.NoError(t, err,
"VerifyToken error: %v", err)
@@ -232,7 +232,7 @@ func TestVerifyToken_RejectsNonMLDSAAlg(t *testing.T) {
token, err := jwt.Sign(parsed, jwt.WithKey(jwa.HS512(), s.browserSigningKey))
require.NoError(t, err)
- _, _, err = s.VerifyToken(context.Background(), string(token))
+ _, _, err = s.VerifyToken(t.Context(), string(token))
assert.ErrorIs(t, err, common.ErrInvalidToken,
"want common.ErrInvalidToken, got %v", err)
@@ -246,17 +246,17 @@ func TestVerifyToken_Expired(t *testing.T) {
s.sessionService = session.NewSessionService(db)
// Create user in DB
- user := &common.User{
+ localUser := &common.User{
ID: "u1",
Username: "bob",
}
- _, err := userSvc.CreateUser(context.Background(), user)
+ _, err := userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(-1 * time.Minute)
token := makeAccessToken(t, s.signingKey, "access", "u1", "bob", []string{"user"}, "", "", exp)
- _, _, err = s.VerifyToken(context.Background(), token)
+ _, _, err = s.VerifyToken(t.Context(), token)
assert.ErrorIs(t, err, common.ErrExpiredToken,
"want ErrExpiredToken, got %v", err)
@@ -267,7 +267,7 @@ func TestVerifyToken_InvalidSubject(t *testing.T) {
exp := time.Now().Add(5 * time.Minute)
token := makeAccessToken(t, s.signingKey, "refresh", "u1", "bob", []string{"user"}, "", "", exp)
- _, _, err := s.VerifyToken(context.Background(), token)
+ _, _, err := s.VerifyToken(t.Context(), token)
require.ErrorIs(t, err, common.ErrTokenValidation)
}
@@ -278,7 +278,7 @@ func TestVerifyToken_InvalidSignature(t *testing.T) {
token := makeAccessToken(t, otherKey, "access", "u1", "bob", []string{"user"}, "", "", exp)
- _, _, err := s.VerifyToken(context.Background(), token)
+ _, _, err := s.VerifyToken(t.Context(), token)
assert.ErrorIs(t, err, common.ErrInvalidToken,
"want common.ErrInvalidToken, got %v", err)
@@ -289,7 +289,7 @@ func TestVerifyToken_MissingUserID(t *testing.T) {
exp := time.Now().Add(5 * time.Minute)
token := makeAccessToken(t, s.signingKey, "access", "", "bob", []string{"user"}, "", "", exp)
- _, _, err := s.VerifyToken(context.Background(), token)
+ _, _, err := s.VerifyToken(t.Context(), token)
require.ErrorIs(t, err, common.ErrTokenValidation)
}
@@ -324,7 +324,7 @@ func TestUniqueOidcUsernameInternal(t *testing.T) {
func TestPersistOidcTokens_SetsFields(t *testing.T) {
s := newTestAuthService()
- user := &common.User{}
+ localUser := &common.User{}
start := time.Now()
resp := &auth.OidcTokenResponse{
AccessToken: "at-123",
@@ -332,23 +332,23 @@ func TestPersistOidcTokens_SetsFields(t *testing.T) {
ExpiresIn: 7,
IDToken: "",
}
- s.persistOidcTokens(user, resp)
+ s.persistOidcTokens(localUser, resp)
- assert.False(t, user.OidcAccessToken == nil || *user.OidcAccessToken != "at-123",
- "access token %v", user.OidcAccessToken)
+ assert.False(t, localUser.OidcAccessToken == nil || *localUser.OidcAccessToken != "at-123",
+ "access token %v", localUser.OidcAccessToken)
- assert.False(t, user.OidcRefreshToken == nil || *user.OidcRefreshToken != "rt-456",
- "refresh token %v", user.OidcRefreshToken)
+ assert.False(t, localUser.OidcRefreshToken == nil || *localUser.OidcRefreshToken != "rt-456",
+ "refresh token %v", localUser.OidcRefreshToken)
- assert.NotNil(t, user.OidcAccessTokenExpiresAt,
+ assert.NotNil(t, localUser.OidcAccessTokenExpiresAt,
"expiresAt nil")
// Check approx expiry within [start+7s, start+12s] to allow CI slop
earliest := start.Add(7 * time.Second)
latest := start.Add(12 * time.Second)
- assert.False(t, user.OidcAccessTokenExpiresAt.Before(earliest) || user.OidcAccessTokenExpiresAt.After(latest),
- "expiresAt %v not in [%v,%v]", user.OidcAccessTokenExpiresAt, earliest, latest)
+ assert.False(t, localUser.OidcAccessTokenExpiresAt.Before(earliest) || localUser.OidcAccessTokenExpiresAt.After(latest),
+ "expiresAt %v not in [%v,%v]", localUser.OidcAccessTokenExpiresAt, earliest, latest)
}
func TestVerifyToken_VersionMismatch(t *testing.T) {
@@ -360,7 +360,7 @@ func TestVerifyToken_VersionMismatch(t *testing.T) {
token := makeAccessToken(t, s.signingKey, "access", "u1", "bob", []string{"user"}, "", "", exp, "session-version-mismatch")
config.Version = "2.0.0"
- _, _, err := s.VerifyToken(context.Background(), token)
+ _, _, err := s.VerifyToken(t.Context(), token)
assert.ErrorIs(t, err, common.ErrTokenVersionMismatch,
"want ErrTokenVersionMismatch, got %v", err)
@@ -371,25 +371,25 @@ func TestVerifyToken_VersionMismatch(t *testing.T) {
func TestRefreshToken_Valid(t *testing.T) {
db := setupAuthServiceTestDB(t)
userSvc := user.NewUserService(db, nil)
- settingsSvc, err := newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err := newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s := newTestAuthService()
s.userService = userSvc
s.settingsService = settingsSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-refresh",
Username: "refresh-user",
}
- _, err = userSvc.CreateUser(context.Background(), user)
+ _, err = userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, refreshJTI := createTestSession(t, db, "u-refresh", exp)
- token := makeRefreshToken(t, s.signingKey, "refresh", refreshJTI, exp, "u-refresh", session.ID)
+ localSession, refreshJTI := createTestSession(t, db, "u-refresh", exp)
+ token := makeRefreshTokenInternal(t, s.signingKey, refreshJTI, exp, "u-refresh", localSession.ID)
- tokenPair, err := s.RefreshToken(context.Background(), token, auth.SessionMeta{})
+ tokenPair, err := s.RefreshToken(t.Context(), token, auth.SessionMeta{})
require.NoError(t, err)
require.NotNil(t, tokenPair)
require.NotEmpty(t, tokenPair.AccessToken)
@@ -414,30 +414,30 @@ func TestRefreshToken_Valid(t *testing.T) {
func TestRefreshToken_VersionMismatchRotates(t *testing.T) {
db := setupAuthServiceTestDB(t)
userSvc := user.NewUserService(db, nil)
- settingsSvc, err := newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err := newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s := newTestAuthService()
s.userService = userSvc
s.settingsService = settingsSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-versionmismatch",
Username: "versionmismatch-user",
}
- _, err = userSvc.CreateUser(context.Background(), user)
+ _, err = userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, refreshJTI := createTestSession(t, db, user.ID, exp)
+ localSession, refreshJTI := createTestSession(t, db, localUser.ID, exp)
oldVersion := config.Version
t.Cleanup(func() { config.Version = oldVersion })
config.Version = "1.0.0"
- token := makeRefreshToken(t, s.signingKey, "refresh", refreshJTI, exp, user.ID, session.ID)
+ token := makeRefreshTokenInternal(t, s.signingKey, refreshJTI, exp, localUser.ID, localSession.ID)
config.Version = "2.0.0"
- tokenPair, err := s.RefreshToken(context.Background(), token, auth.SessionMeta{})
+ tokenPair, err := s.RefreshToken(t.Context(), token, auth.SessionMeta{})
require.NoError(t, err)
require.NotNil(t, tokenPair)
require.NotEmpty(t, tokenPair.AccessToken)
@@ -456,10 +456,10 @@ func TestRefreshToken_VersionMismatchRotates(t *testing.T) {
require.Equal(t, browserTokenSubject, browserSubject)
browserSessionID, err := jwt.Get[string](parsedBrowser, claimSessionID)
require.NoError(t, err)
- require.Equal(t, session.ID, browserSessionID)
+ require.Equal(t, localSession.ID, browserSessionID)
browserUserID, err := jwt.Get[string](parsedBrowser, claimUserID)
require.NoError(t, err)
- require.Equal(t, user.ID, browserUserID)
+ require.Equal(t, localUser.ID, browserUserID)
browserVersion, err := jwt.Get[string](parsedBrowser, claimAppVersion)
require.NoError(t, err)
require.Equal(t, "2.0.0", browserVersion)
@@ -478,32 +478,32 @@ func TestVerifyToken_RejectsRevokedSession(t *testing.T) {
s.userService = userSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-revoked",
Username: "revoked-user",
}
- _, err := userSvc.CreateUser(context.Background(), user)
+ _, err := userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, _ := createTestSession(t, db, user.ID, exp)
- token := makeAccessToken(t, s.signingKey, "access", user.ID, user.Username, []string{"user"}, "", "", exp, session.ID)
+ localSession, _ := createTestSession(t, db, localUser.ID, exp)
+ token := makeAccessToken(t, s.signingKey, "access", localUser.ID, localUser.Username, []string{"user"}, "", "", exp, localSession.ID)
browser, err := jwt.NewBuilder().
JwtID("revoked-browser-token").
Subject(browserTokenSubject).
IssuedAt(time.Now()).
Expiration(exp).
- Claim(claimSessionID, session.ID).
- Claim(claimUserID, user.ID).
+ Claim(claimSessionID, localSession.ID).
+ Claim(claimUserID, localUser.ID).
Build()
require.NoError(t, err)
browserToken, err := jwt.Sign(browser, jwt.WithKey(jwa.HS512(), s.browserSigningKey))
require.NoError(t, err)
- require.NoError(t, s.RevokeSession(context.Background(), session.ID))
+ require.NoError(t, s.RevokeSession(t.Context(), localSession.ID))
- _, _, err = s.VerifyToken(context.Background(), token)
+ _, _, err = s.VerifyToken(t.Context(), token)
require.ErrorIs(t, err, common.ErrSessionRevoked)
- _, _, err = s.VerifyBrowserToken(context.Background(), string(browserToken))
+ _, _, err = s.VerifyBrowserToken(t.Context(), string(browserToken))
require.ErrorIs(t, err, common.ErrSessionRevoked)
}
@@ -514,16 +514,16 @@ func TestVerifyToken_RejectsMissingSessionID(t *testing.T) {
s.userService = userSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-no-sid",
Username: "no-sid-user",
}
- _, err := userSvc.CreateUser(context.Background(), user)
+ _, err := userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
- token := makeAccessToken(t, s.signingKey, "access", user.ID, user.Username, []string{"user"}, "", "", time.Now().Add(5*time.Minute))
+ token := makeAccessToken(t, s.signingKey, "access", localUser.ID, localUser.Username, []string{"user"}, "", "", time.Now().Add(5*time.Minute))
- _, _, err = s.VerifyToken(context.Background(), token)
+ _, _, err = s.VerifyToken(t.Context(), token)
require.ErrorIs(t, err, common.ErrTokenValidation)
}
@@ -534,19 +534,19 @@ func TestRevokeSessionThenVerifyTokenFails(t *testing.T) {
s.userService = userSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-logout",
Username: "logout-user",
}
- _, err := userSvc.CreateUser(context.Background(), user)
+ _, err := userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, _ := createTestSession(t, db, user.ID, exp)
- token := makeAccessToken(t, s.signingKey, "access", user.ID, user.Username, []string{"user"}, "", "", exp, session.ID)
- require.NoError(t, s.RevokeSession(context.Background(), session.ID))
+ localSession, _ := createTestSession(t, db, localUser.ID, exp)
+ token := makeAccessToken(t, s.signingKey, "access", localUser.ID, localUser.Username, []string{"user"}, "", "", exp, localSession.ID)
+ require.NoError(t, s.RevokeSession(t.Context(), localSession.ID))
- _, _, err = s.VerifyToken(context.Background(), token)
+ _, _, err = s.VerifyToken(t.Context(), token)
require.ErrorIs(t, err, common.ErrSessionRevoked)
}
@@ -557,77 +557,77 @@ func TestVerifyToken_RejectsRevokedCachedSession(t *testing.T) {
s.userService = userSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-cached-revoked",
Username: "cached-revoked-user",
}
- _, err := userSvc.CreateUser(context.Background(), user)
+ _, err := userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- sessionRecord, _ := createTestSession(t, db, user.ID, exp)
- token := makeAccessToken(t, s.signingKey, "access", user.ID, user.Username, []string{"user"}, "", "", exp, sessionRecord.ID)
+ sessionRecord, _ := createTestSession(t, db, localUser.ID, exp)
+ token := makeAccessToken(t, s.signingKey, "access", localUser.ID, localUser.Username, []string{"user"}, "", "", exp, sessionRecord.ID)
- _, _, err = s.VerifyToken(context.Background(), token)
+ _, _, err = s.VerifyToken(t.Context(), token)
require.NoError(t, err)
- require.NoError(t, s.RevokeSession(context.Background(), sessionRecord.ID))
+ require.NoError(t, s.RevokeSession(t.Context(), sessionRecord.ID))
- _, _, err = s.VerifyToken(context.Background(), token)
+ _, _, err = s.VerifyToken(t.Context(), token)
require.ErrorIs(t, err, common.ErrSessionRevoked, "expected cached access token to be rejected after revocation, got %v", err)
}
func TestRefreshToken_RotatesJTI(t *testing.T) {
db := setupAuthServiceTestDB(t)
userSvc := user.NewUserService(db, nil)
- settingsSvc, err := newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err := newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s := newTestAuthService()
s.userService = userSvc
s.settingsService = settingsSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-rotate",
Username: "rotate-user",
}
- _, err = userSvc.CreateUser(context.Background(), user)
+ _, err = userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, refreshJTI := createTestSession(t, db, user.ID, exp)
- token := makeRefreshToken(t, s.signingKey, "refresh", refreshJTI, exp, user.ID, session.ID)
+ localSession, refreshJTI := createTestSession(t, db, localUser.ID, exp)
+ token := makeRefreshTokenInternal(t, s.signingKey, refreshJTI, exp, localUser.ID, localSession.ID)
- tokenPair, err := s.RefreshToken(context.Background(), token, auth.SessionMeta{})
+ tokenPair, err := s.RefreshToken(t.Context(), token, auth.SessionMeta{})
require.NoError(t, err)
require.NotEmpty(t, tokenPair.RefreshToken)
- _, err = s.RefreshToken(context.Background(), token, auth.SessionMeta{})
+ _, err = s.RefreshToken(t.Context(), token, auth.SessionMeta{})
require.ErrorIs(t, err, common.ErrInvalidToken)
}
func TestRefreshToken_RejectsRevokedSession(t *testing.T) {
db := setupAuthServiceTestDB(t)
userSvc := user.NewUserService(db, nil)
- settingsSvc, err := newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err := newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s := newTestAuthService()
s.userService = userSvc
s.settingsService = settingsSvc
s.sessionService = session.NewSessionService(db)
- user := &common.User{
+ localUser := &common.User{
ID: "u-refresh-revoked",
Username: "refresh-revoked-user",
}
- _, err = userSvc.CreateUser(context.Background(), user)
+ _, err = userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
exp := time.Now().Add(5 * time.Minute)
- session, refreshJTI := createTestSession(t, db, user.ID, exp)
- require.NoError(t, s.RevokeSession(context.Background(), session.ID))
- token := makeRefreshToken(t, s.signingKey, "refresh", refreshJTI, exp, user.ID, session.ID)
+ localSession, refreshJTI := createTestSession(t, db, localUser.ID, exp)
+ require.NoError(t, s.RevokeSession(t.Context(), localSession.ID))
+ token := makeRefreshTokenInternal(t, s.signingKey, refreshJTI, exp, localUser.ID, localSession.ID)
- _, err = s.RefreshToken(context.Background(), token, auth.SessionMeta{})
+ _, err = s.RefreshToken(t.Context(), token, auth.SessionMeta{})
require.ErrorIs(t, err, common.ErrSessionRevoked)
}
@@ -640,22 +640,22 @@ func TestChangePassword_RevokesAllSessions(t *testing.T) {
passwordHash, err := userSvc.HashPassword("old-password")
require.NoError(t, err)
- user := &common.User{
+ localUser := &common.User{
ID: "u-password",
Username: "password-user",
PasswordHash: passwordHash,
}
- _, err = userSvc.CreateUser(context.Background(), user)
+ _, err = userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
- sessionA, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
- sessionB, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
+ sessionA, _ := createTestSession(t, db, localUser.ID, time.Now().Add(time.Hour))
+ sessionB, _ := createTestSession(t, db, localUser.ID, time.Now().Add(time.Hour))
- require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "New-password1!", ""))
+ require.NoError(t, s.ChangePassword(t.Context(), localUser.ID, "old-password", "New-password1!", ""))
- sessionA, err = s.sessionService.GetSessionByID(context.Background(), sessionA.ID)
+ sessionA, err = s.sessionService.GetSessionByID(t.Context(), sessionA.ID)
require.NoError(t, err)
- sessionB, err = s.sessionService.GetSessionByID(context.Background(), sessionB.ID)
+ sessionB, err = s.sessionService.GetSessionByID(t.Context(), sessionB.ID)
require.NoError(t, err)
require.NotNil(t, sessionA.RevokedAt)
require.NotNil(t, sessionB.RevokedAt)
@@ -670,22 +670,22 @@ func TestChangePassword_KeepsCurrentSessionAlive(t *testing.T) {
passwordHash, err := userSvc.HashPassword("old-password")
require.NoError(t, err)
- user := &common.User{
+ localUser := &common.User{
ID: "u-keep",
Username: "keep-user",
PasswordHash: passwordHash,
}
- _, err = userSvc.CreateUser(context.Background(), user)
+ _, err = userSvc.CreateUser(t.Context(), localUser)
require.NoError(t, err)
- current, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
- other, _ := createTestSession(t, db, user.ID, time.Now().Add(time.Hour))
+ current, _ := createTestSession(t, db, localUser.ID, time.Now().Add(time.Hour))
+ other, _ := createTestSession(t, db, localUser.ID, time.Now().Add(time.Hour))
- require.NoError(t, s.ChangePassword(context.Background(), user.ID, "old-password", "New-password1!", current.ID))
+ require.NoError(t, s.ChangePassword(t.Context(), localUser.ID, "old-password", "New-password1!", current.ID))
- current, err = s.sessionService.GetSessionByID(context.Background(), current.ID)
+ current, err = s.sessionService.GetSessionByID(t.Context(), current.ID)
require.NoError(t, err)
- other, err = s.sessionService.GetSessionByID(context.Background(), other.ID)
+ other, err = s.sessionService.GetSessionByID(t.Context(), other.ID)
require.NoError(t, err)
require.Nil(t, current.RevokedAt, "current session should remain active")
require.NotNil(t, other.RevokedAt, "other sessions should be revoked")
@@ -701,7 +701,7 @@ func TestRefreshToken_RejectsNonHMACAlg(t *testing.T) {
"exp": exp.Unix(),
})
- _, err := s.RefreshToken(context.Background(), token, auth.SessionMeta{})
+ _, err := s.RefreshToken(t.Context(), token, auth.SessionMeta{})
assert.ErrorIs(t, err, common.ErrInvalidToken,
"want common.ErrInvalidToken, got %v", err)
@@ -712,11 +712,11 @@ func TestGetOidcConfigurationStatus(t *testing.T) {
// Disabled
s := newTestAuthService()
s.config = &config.Config{}
- settingsSvc, err := newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err := newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s.settingsService = settingsSvc
- status, err := s.GetOidcConfigurationStatus(context.Background())
+ status, err := s.GetOidcConfigurationStatus(t.Context())
require.NoError(t, err,
"GetOidcConfigurationStatus error: %v", err)
@@ -731,11 +731,11 @@ func TestGetOidcConfigurationStatus(t *testing.T) {
// Explicit env override to false should still be treated as forced
t.Setenv("OIDC_ENABLED", "false")
- settingsSvc, err = newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err = newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s.settingsService = settingsSvc
s.config.OidcEnabled = false
- status, err = s.GetOidcConfigurationStatus(context.Background())
+ status, err = s.GetOidcConfigurationStatus(t.Context())
require.NoError(t, err,
"GetOidcConfigurationStatus error: %v", err)
@@ -745,11 +745,11 @@ func TestGetOidcConfigurationStatus(t *testing.T) {
// Enabled but missing fields
t.Setenv("OIDC_ENABLED", "true")
- settingsSvc, err = newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err = newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s.settingsService = settingsSvc
s.config.OidcEnabled = true
- status, err = s.GetOidcConfigurationStatus(context.Background())
+ status, err = s.GetOidcConfigurationStatus(t.Context())
require.NoError(t, err,
"GetOidcConfigurationStatus error: %v", err)
@@ -760,7 +760,7 @@ func TestGetOidcConfigurationStatus(t *testing.T) {
// Enabled and configured
s.config.OidcClientID = "client-id"
s.config.OidcIssuerURL = "https://example.com"
- status, err = s.GetOidcConfigurationStatus(context.Background())
+ status, err = s.GetOidcConfigurationStatus(t.Context())
require.NoError(t, err,
"GetOidcConfigurationStatus error: %v", err)
@@ -770,7 +770,7 @@ func TestGetOidcConfigurationStatus(t *testing.T) {
}
func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_NoExistingUser_CreatesNewUser(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthServiceTestDB(t)
settingsSvc, err := newSettingsServiceForAuthTestInternal(t, ctx, db)
@@ -824,7 +824,7 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_NoExistingUser_Creat
}
func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_WithExistingUser_ReturnsError(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthServiceTestDB(t)
settingsSvc, err := newSettingsServiceForAuthTestInternal(t, ctx, db)
@@ -866,7 +866,7 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_WithExistingUser_Ret
}
func TestFindOrCreateOidcUser_MergeEnabled_EmailVerificationMissing_WithExistingUser_Merges(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthServiceTestDB(t)
settingsSvc, err := newSettingsServiceForAuthTestInternal(t, ctx, db)
@@ -912,7 +912,7 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailVerificationMissing_WithExisting
func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {
db := setupAuthServiceTestDB(t)
userSvc := user.NewUserService(db, nil)
- settingsSvc, err := newSettingsServiceForAuthTestInternal(t, context.Background(), db)
+ settingsSvc, err := newSettingsServiceForAuthTestInternal(t, t.Context(), db)
require.NoError(t, err)
s := newTestAuthService()
s.userService = userSvc
@@ -932,7 +932,7 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {
{ID: "u-col-a", Username: "[email protected]", PasswordHash: hash},
{ID: "u-col-b", Username: "colb", Email: new("[email protected]"), PasswordHash: dupHash},
} {
- _, err = userSvc.CreateUser(context.Background(), u)
+ _, err = userSvc.CreateUser(t.Context(), u)
require.NoError(t, err)
}
@@ -964,12 +964,12 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
- got, err := s.AuthenticateLocalPrimary(context.Background(), tc.login, tc.password)
+ got, authenticateLocalPrimaryErr := s.AuthenticateLocalPrimary(t.Context(), tc.login, tc.password)
if tc.wantErr != nil {
- require.ErrorIs(t, err, tc.wantErr)
+ require.ErrorIs(t, authenticateLocalPrimaryErr, tc.wantErr)
return
}
- require.NoError(t, err)
+ require.NoError(t, authenticateLocalPrimaryErr)
require.Equal(t, tc.wantID, got.ID)
})
}
diff --git a/backend/internal/backup/engine.go b/backend/internal/backup/engine.go
index 4a2f2c392..b25e5f348 100644
--- a/backend/internal/backup/engine.go
+++ b/backend/internal/backup/engine.go
@@ -136,7 +136,34 @@ type Engine struct {
func NewEngine(ctx context.Context, admission *runs.Admission, imageService *image.ImageService) *Engine {
runCtx, cancel := context.WithCancel(ctx)
- return &Engine{cancel: cancel, imageService: imageService, admission: admission, lifecycleCtx: runCtx, repositories: make(map[string]*sync.Mutex), handlers: make(map[string]func(context.Context, string, []byte, bool) error), failures: make(map[string]func(context.Context, string, []byte, error) error), leases: make(map[string]*runs.Lease)}
+ return &Engine{
+ cancel: cancel,
+ imageService: imageService,
+ admission: admission,
+ lifecycleCtx: runCtx,
+ repositories: make(
+ map[string]*sync.Mutex,
+ ),
+ handlers: make(
+ map[string]func(
+ context.Context,
+ string,
+ []byte,
+ bool,
+ ) error,
+ ),
+ failures: make(
+ map[string]func(
+ context.Context,
+ string,
+ []byte,
+ error,
+ ) error,
+ ),
+ leases: make(
+ map[string]*runs.Lease,
+ ),
+ }
}
func (e *Engine) TryAcquireRun(ctx context.Context, scope, id string) (*runs.Lease, bool, error) {
@@ -186,8 +213,8 @@ func (e *Engine) CreateSnapshot(ctx context.Context, dockerClient *client.Client
return Snapshot{}, err
}
var decoded rusticSnapshotOutputInternal
- if err := json.Unmarshal([]byte(output), &decoded); err != nil {
- return Snapshot{}, fmt.Errorf("failed to decode Rustic snapshot: %w", err)
+ if unmarshalErr := json.Unmarshal([]byte(output), &decoded); unmarshalErr != nil {
+ return Snapshot{}, fmt.Errorf("failed to decode Rustic snapshot: %w", unmarshalErr)
}
if decoded.ID == "" {
return Snapshot{}, errors.New("rustic did not return a snapshot ID")
@@ -230,20 +257,20 @@ func (e *Engine) ListSnapshotFiles(ctx context.Context, dockerClient *client.Cli
return nil, fmt.Errorf("failed to list Rustic snapshot: %w", err)
}
var files []string
- if err := json.Unmarshal([]byte(output), &files); err != nil {
- return nil, fmt.Errorf("failed to decode Rustic file list: %w", err)
+ if unmarshalErr := json.Unmarshal([]byte(output), &files); unmarshalErr != nil {
+ return nil, fmt.Errorf("failed to decode Rustic file list: %w", unmarshalErr)
}
if !recursive && len(files) > 0 {
// Rustic's JSON listing omits node types; the stable long listing restores them.
longCommand := slices.Clone(command)
longCommand[1] = "--long"
- longOutput, err := e.runInternal(ctx, dockerClient, repository, password, longCommand)
- if err != nil {
- return nil, fmt.Errorf("failed to list Rustic snapshot metadata: %w", err)
+ longOutput, runErr := e.runInternal(ctx, dockerClient, repository, password, longCommand)
+ if runErr != nil {
+ return nil, fmt.Errorf("failed to list Rustic snapshot metadata: %w", runErr)
}
- files, err = markSnapshotDirectoriesInternal(files, longOutput)
- if err != nil {
- return nil, err
+ files, runErr = markSnapshotDirectoriesInternal(files, longOutput)
+ if runErr != nil {
+ return nil, runErr
}
}
return qualifySnapshotListingInternal(files, cleanedPath), nil
@@ -371,7 +398,7 @@ func (e *Engine) ListSnapshots(ctx context.Context, dockerClient *client.Client,
func decodeSnapshotsInternal(output string) ([]DiscoveredSnapshot, error) {
trimmedOutput := strings.TrimSpace(output)
- if len(trimmedOutput) == 0 || trimmedOutput[0] != '[' {
+ if trimmedOutput == "" || trimmedOutput[0] != '[' {
return nil, errors.New("invalid Rustic snapshot listing: expected an array")
}
var entries []jsontext.Value
@@ -666,8 +693,8 @@ func (s *RecoveryKeyStore) Set(ctx context.Context, recoveryKey string) error {
return fmt.Errorf("failed to encrypt recovery key: %w", err)
}
config := SystemBackupRecoveryConfig{ID: RecoveryKeyConfigID, EncryptedRecoveryKey: encrypted}
- if err := s.db.WithContext(ctx).Save(&config).Error; err != nil {
- return fmt.Errorf("failed to save recovery key: %w", err)
+ if saveRecoveryKeyErr := s.db.WithContext(ctx).Save(&config).Error; saveRecoveryKeyErr != nil {
+ return fmt.Errorf("failed to save recovery key: %w", saveRecoveryKeyErr)
}
return nil
}
diff --git a/backend/internal/backup/engine_test.go b/backend/internal/backup/engine_test.go
index b343bd7e3..5f184d558 100644
--- a/backend/internal/backup/engine_test.go
+++ b/backend/internal/backup/engine_test.go
@@ -14,7 +14,9 @@ import (
func TestMarkSnapshotDirectoriesInternal(t *testing.T) {
files := []string{"/volume", "/volume/folder", "/volume/file.txt", "/volume/link"}
- longOutput := "drwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume\"\r\ndrwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume/folder\"\r\n-rw-r--r-- root root 5 1 Jan 2026 00:00 \"/volume/file.txt\"\r\nlrwxrwxrwx root root 4 1 Jan 2026 00:00 \"/volume/link\" -> \"file.txt\""
+ longOutput := "drwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume\"\r\ndrwxr-xr-x root root 0 1 Jan 2026 00:00 \"/volume/" +
+ "folder\"\r\n-rw-r--r-- root root 5 1 Jan 2026 00:00 \"/volume/file.txt\"\r\nlrwxrwxrwx root root 4 1 Jan 20" +
+ "26 00:00 \"/volume/link\" -> \"file.txt\""
marked, err := markSnapshotDirectoriesInternal(files, longOutput)
require.NoError(t, err)
@@ -115,7 +117,24 @@ func TestSnapshotCommandInternal(t *testing.T) {
multi, err := snapshotCommandInternal("arcane-system-recovery", CreateSnapshotInput{Sources: []string{"/data", "/projects"}, Globs: []string{"!/data/arcane.db-wal"}})
require.NoError(t, err)
- require.Equal(t, []string{"backup", "--init", "--json", "--host", "arcane", "--label", "arcane-system-recovery", "--glob", "!/data/arcane.db-wal", "--", "/data", "/projects"}, multi)
+ require.Equal(
+ t,
+ []string{
+ "backup",
+ "--init",
+ "--json",
+ "--host",
+ "arcane",
+ "--label",
+ "arcane-system-recovery",
+ "--glob",
+ "!/data/arcane.db-wal",
+ "--",
+ "/data",
+ "/projects",
+ },
+ multi,
+ )
_, err = snapshotCommandInternal("x", CreateSnapshotInput{Sources: []string{"/data", "/projects"}, AsPath: "/"})
require.ErrorContains(t, err, "single source")
diff --git a/backend/internal/backup/policies.go b/backend/internal/backup/policies.go
index 0e22993aa..10e1ac4ab 100644
--- a/backend/internal/backup/policies.go
+++ b/backend/internal/backup/policies.go
@@ -40,8 +40,8 @@ func (r PolicyReconciliation[P, U]) Run(ctx context.Context, updates []U) error
if err != nil {
return err
}
- if err := r.persistInternal(ctx, policies, kept); err != nil {
- return fmt.Errorf("failed to save %s backup policies: %w", r.Domain, err)
+ if persistErr := r.persistInternal(ctx, policies, kept); persistErr != nil {
+ return fmt.Errorf("failed to save %s backup policies: %w", r.Domain, persistErr)
}
for i := range r.Existing {
if _, ok := kept[r.ID(&r.Existing[i])]; !ok {
@@ -98,7 +98,7 @@ func ValidatePolicyUpdate(ctx context.Context, domain string, update backuptypes
if s3 == nil {
return update, errors.New("S3 backup destinations are unavailable")
}
- if _, err := s3.Configuration(ctx, update.S3DestinationID); err != nil {
+ if _, configurationErr := s3.Configuration(ctx, update.S3DestinationID); configurationErr != nil {
return update, fmt.Errorf("select a valid S3 destination for %s backups", domain)
}
} else {
diff --git a/backend/internal/backup/remote.go b/backend/internal/backup/remote.go
index 0885adc9d..c813fad4c 100644
--- a/backend/internal/backup/remote.go
+++ b/backend/internal/backup/remote.go
@@ -67,8 +67,10 @@ func CheckScheduledRemote(ctx context.Context, db *database.DB, destinations *s3
}
if result.Reason == s3util.RepositoryReasonMissingRepository {
var retained int64
- if err := db.WithContext(ctx).Table(table).Where("s3_destination_id = ? AND COALESCE(remote_snapshot_id, '') <> ''", destinationID).Count(&retained).Error; err != nil {
- return err
+ if countRetainedSnapshotsErr := db.WithContext(ctx).Table(table).
+ Where("s3_destination_id = ? AND COALESCE(remote_snapshot_id, '') <> ''", destinationID).
+ Count(&retained).Error; countRetainedSnapshotsErr != nil {
+ return countRetainedSnapshotsErr
}
if retained == 0 {
return nil
diff --git a/backend/internal/backup/runs.go b/backend/internal/backup/runs.go
index 0d1102f97..6e65bb94e 100644
--- a/backend/internal/backup/runs.go
+++ b/backend/internal/backup/runs.go
@@ -98,8 +98,8 @@ func (a *backupRunActorInternal) Invoke(ctx context.Context, _ string, data acto
err := a.service.GetState(ctx, backupRunTypeInternal, a.id, &state)
if errors.Is(err, actor.ErrStateNotFound) {
state = backuptypes.DurableRunState{Command: command, Status: st.Queued}
- if err := a.service.SetState(ctx, backupRunTypeInternal, a.id, state, nil); err != nil {
- return nil, err
+ if setStateErr := a.service.SetState(ctx, backupRunTypeInternal, a.id, state, nil); setStateErr != nil {
+ return nil, setStateErr
}
} else if err != nil {
return nil, err
@@ -194,16 +194,16 @@ func (a *backupRunActorInternal) executeInternal(ctx context.Context, command ba
return errors.New("backup run kind is unavailable")
}
if a.engine.authorize != nil {
- if err := a.engine.authorize(ctx, command); err != nil {
+ if authorizeErr := a.engine.authorize(ctx, command); authorizeErr != nil {
a.engine.mu.Lock()
lease := a.engine.leases[a.id]
delete(a.engine.leases, a.id)
a.engine.mu.Unlock()
defer lease.Release(ctx)
if failure != nil {
- err = errors.Join(err, failure(ctx, a.id, command.Payload, err))
+ authorizeErr = errors.Join(authorizeErr, failure(ctx, a.id, command.Payload, authorizeErr))
}
- return err
+ return authorizeErr
}
}
return handler(ctx, a.id, command.Payload, interrupted)
@@ -221,8 +221,8 @@ func (e *Engine) activeRunsInternal(ctx context.Context) ([]backuptypes.DurableR
continue
}
var state backuptypes.DurableRunState
- if err := item.Data.Decode(&state); err != nil {
- return nil, err
+ if decodeErr := item.Data.Decode(&state); decodeErr != nil {
+ return nil, decodeErr
}
if state.Status == st.Queued || state.Status == st.Running || state.Status == st.NeedsAttention {
result = append(result, state)
@@ -280,9 +280,9 @@ func (e *Engine) ReconcileDispatches(ctx context.Context) error {
if state.Status == st.NeedsAttention {
continue
}
- jobs, err := e.service.ListJobs(ctx, backupRunTypeInternal, state.Command.RunID)
- if err != nil {
- return err
+ jobs, listJobsErr := e.service.ListJobs(ctx, backupRunTypeInternal, state.Command.RunID)
+ if listJobsErr != nil {
+ return listJobsErr
}
live := false
for _, job := range jobs {
@@ -291,21 +291,21 @@ func (e *Engine) ReconcileDispatches(ctx context.Context) error {
break
}
if job.Status == actor.JobStatusDeadLettered {
- if _, err := e.service.RetryJob(ctx, job.JobID); err != nil {
- return err
+ if _, retryJobErr := e.service.RetryJob(ctx, job.JobID); retryJobErr != nil {
+ return retryJobErr
}
live = true
break
}
- if err := e.service.DeleteJob(ctx, backupRunTypeInternal, state.Command.RunID, job.JobID); err != nil && !errors.Is(err, actor.ErrJobNotFound) {
- return err
+ if deleteJobErr := e.service.DeleteJob(ctx, backupRunTypeInternal, state.Command.RunID, job.JobID); deleteJobErr != nil && !errors.Is(deleteJobErr, actor.ErrJobNotFound) {
+ return deleteJobErr
}
}
if live {
continue
}
- if _, _, err := e.service.Dispatch(ctx, backupRunTypeInternal, state.Command.RunID, "execute", nil, actor.WithIdempotencyKey(state.Command.RunID)); err != nil {
- return err
+ if _, _, dispatchErr := e.service.Dispatch(ctx, backupRunTypeInternal, state.Command.RunID, "execute", nil, actor.WithIdempotencyKey(state.Command.RunID)); dispatchErr != nil {
+ return dispatchErr
}
}
return nil
diff --git a/backend/internal/backup/runs_test.go b/backend/internal/backup/runs_test.go
index c14b2b390..5c5726eb8 100644
--- a/backend/internal/backup/runs_test.go
+++ b/backend/internal/backup/runs_test.go
@@ -105,7 +105,7 @@ func TestDurableBackupShutdownKeepsInterruptedEvidenceInternal(t *testing.T) {
previous, ok := jobcontext.Run(ctx)
require.True(t, ok)
require.Len(t, previous.Outcome.Targets, 1)
- require.Equal(t, `{"backupId":"frozen"}`, string(previous.Outcome.Targets[0].RecoveryData))
+ require.JSONEq(t, `{"backupId":"frozen"}`, string(previous.Outcome.Targets[0].RecoveryData))
close(resumed)
return nil
})
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 87a394ac3..ead916c70 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -78,8 +78,8 @@ func Bootstrap(ctx context.Context) error {
}
defer func() {
cancelApp()
- if err := db.Close(); err != nil {
- slog.Error("Error closing database", "error", err)
+ if closeErr := db.Close(); closeErr != nil {
+ slog.Error("Error closing database", "error", closeErr)
}
}()
@@ -87,8 +87,8 @@ func Bootstrap(ctx context.Context) error {
startCtx, cancelStart := context.WithTimeout(ctx, 5*time.Minute)
defer cancelStart()
- if err := app.Start(startCtx); err != nil {
- return fmt.Errorf("start application: %w", err)
+ if startErr := app.Start(startCtx); startErr != nil {
+ return fmt.Errorf("start application: %w", startErr)
}
select {
@@ -100,8 +100,8 @@ func Bootstrap(ctx context.Context) error {
stopCtx, cancelStop := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancelStop()
- if err := app.Stop(stopCtx); err != nil {
- return fmt.Errorf("stop application: %w", err)
+ if stopErr := app.Stop(stopCtx); stopErr != nil {
+ return fmt.Errorf("stop application: %w", stopErr)
}
slog.InfoContext(context.WithoutCancel(appCtx), "Arcane shutdown complete")
@@ -139,8 +139,8 @@ func applicationOptions(appCtx context.Context, cfg *config.Config, db *database
// ENCRYPTION_KEY is an unprefixed passphrase shorter than 32 characters in
// production. crypto derives a key from any non-empty passphrase, so this
// preserves the historical fail-fast rejection of low-entropy production keys.
-func isWeakProductionEncryptionKeyInternal(encryptionKey, environment string, agentMode bool) bool {
- if environment != "production" || agentMode {
+func isWeakProductionEncryptionKeyInternal(encryptionKey, localEnvironment string, agentMode bool) bool {
+ if localEnvironment != "production" || agentMode {
return false
}
key := strings.TrimSpace(encryptionKey)
@@ -439,7 +439,7 @@ func handleAgentBootstrapPairing(ctx context.Context, cfg *config.Config, httpCl
reqCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
- req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pairURL, nil)
+ req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, pairURL, http.NoBody)
if err != nil {
return fmt.Errorf("failed to create pairing request: %w", err)
}
diff --git a/backend/internal/bootstrap/bootstrap_test.go b/backend/internal/bootstrap/bootstrap_test.go
index 389fde4e1..15f1279e8 100644
--- a/backend/internal/bootstrap/bootstrap_test.go
+++ b/backend/internal/bootstrap/bootstrap_test.go
@@ -2,7 +2,6 @@ package bootstrap
import (
"context"
- "crypto/tls"
"io"
"net"
"net/http"
@@ -19,7 +18,6 @@ import (
libcrypto "go.getarcane.app/sys/crypto"
"go.uber.org/fx"
"go.uber.org/fx/fxtest"
- "golang.org/x/net/http2"
"gorm.io/gorm"
"github.com/getarcaneapp/arcane/backend/v2/api"
@@ -65,7 +63,7 @@ func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {
})
t.Run("path without prefix remains unchanged", func(t *testing.T) {
- req := httptest.NewRequest("POST", fullMethodPath, nil)
+ req := httptest.NewRequest("POST", fullMethodPath, http.NoBody)
normalized := normalizeTunnelGRPCRequestPathInternal(req)
assert.Same(t, req, normalized)
@@ -73,7 +71,7 @@ func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {
})
t.Run("api prefix is removed", func(t *testing.T) {
- req := httptest.NewRequest("POST", "/api"+fullMethodPath, nil)
+ req := httptest.NewRequest("POST", "/api"+fullMethodPath, http.NoBody)
normalized := normalizeTunnelGRPCRequestPathInternal(req)
assert.NotSame(t, req, normalized)
@@ -82,7 +80,7 @@ func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {
})
t.Run("nested proxy prefix is removed up to method path", func(t *testing.T) {
- req := httptest.NewRequest("POST", "/edge/proxy/api"+fullMethodPath, nil)
+ req := httptest.NewRequest("POST", "/edge/proxy/api"+fullMethodPath, http.NoBody)
normalized := normalizeTunnelGRPCRequestPathInternal(req)
assert.NotSame(t, req, normalized)
@@ -95,7 +93,7 @@ func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {
// gRPC transport. The agent client uses /api/tunnel/connect as its
// gRPC method path so reverse proxies can route tunnel traffic with
// a stable URL instead of the proto-generated gRPC service name.
- req := httptest.NewRequest("POST", "/api/tunnel/connect", nil)
+ req := httptest.NewRequest("POST", "/api/tunnel/connect", http.NoBody)
normalized := normalizeTunnelGRPCRequestPathInternal(req)
assert.NotSame(t, req, normalized)
@@ -104,7 +102,7 @@ func TestNormalizeTunnelGRPCRequestPathInternal(t *testing.T) {
})
t.Run("nested proxy with legacy /api/tunnel/connect is rewritten", func(t *testing.T) {
- req := httptest.NewRequest("POST", "/edge/proxy/api/tunnel/connect", nil)
+ req := httptest.NewRequest("POST", "/edge/proxy/api/tunnel/connect", http.NoBody)
normalized := normalizeTunnelGRPCRequestPathInternal(req)
assert.NotSame(t, req, normalized)
@@ -117,36 +115,36 @@ func TestIsTunnelGRPCRequestInternal(t *testing.T) {
fullMethodPath := tunnelpb.TunnelService_Connect_FullMethodName
t.Run("detects by grpc content-type", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPost, "/any/path", nil)
+ req := httptest.NewRequest(http.MethodPost, "/any/path", http.NoBody)
req.Header.Set("Content-Type", "application/grpc")
assert.True(t, isTunnelGRPCRequestInternal(req))
})
t.Run("detects by grpc-web content-type", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPost, "/any/path", nil)
+ req := httptest.NewRequest(http.MethodPost, "/any/path", http.NoBody)
req.Header.Set("Content-Type", "application/grpc-web+proto")
assert.True(t, isTunnelGRPCRequestInternal(req))
})
t.Run("detects by method path without grpc content-type", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPost, fullMethodPath, nil)
+ req := httptest.NewRequest(http.MethodPost, fullMethodPath, http.NoBody)
assert.True(t, isTunnelGRPCRequestInternal(req))
})
t.Run("does not match regular api requests", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPost, "/api/environments/pair", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/pair", http.NoBody)
req.Header.Set("Content-Type", "application/json")
assert.False(t, isTunnelGRPCRequestInternal(req))
})
t.Run("requires post", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodGet, fullMethodPath, nil)
+ req := httptest.NewRequest(http.MethodGet, fullMethodPath, http.NoBody)
req.Header.Set("Content-Type", "application/grpc")
assert.False(t, isTunnelGRPCRequestInternal(req))
})
t.Run("does not match http2 post with te trailers and json content-type", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPost, "/api/auth/login", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/auth/login", http.NoBody)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Te", "trailers")
req.ProtoMajor = 2
@@ -154,7 +152,7 @@ func TestIsTunnelGRPCRequestInternal(t *testing.T) {
})
t.Run("does not match http2 post with te trailers and form content-type", func(t *testing.T) {
- req := httptest.NewRequest(http.MethodPost, "/logout", nil)
+ req := httptest.NewRequest(http.MethodPost, "/logout", http.NoBody)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Te", "trailers")
req.ProtoMajor = 2
@@ -195,7 +193,7 @@ func TestHTTP2APIResponsesDoNotUseAPIGzipInternal(t *testing.T) {
Environment: config.AppEnvironmentTest,
}
router, _ := newRouter(RouterParams{
- Context: context.Background(),
+ Context: t.Context(),
Config: cfg,
HandlerDeps: api.HandlerDeps{
Project: project.New(&project.ProjectService{}, nil),
@@ -221,31 +219,27 @@ func TestHTTP2APIResponsesDoNotUseAPIGzipInternal(t *testing.T) {
errCh <- server.Serve(listener)
}()
t.Cleanup(func() {
- require.NoError(t, server.Shutdown(context.Background()))
+ require.NoError(t, server.Shutdown(context.WithoutCancel(t.Context())))
require.ErrorIs(t, <-errCh, http.ErrServerClosed)
})
- transport := &http2.Transport{
- AllowHTTP: true,
- DisableCompression: true,
- DialTLSContext: func(ctx context.Context, network, addr string, _ *tls.Config) (net.Conn, error) {
- return (&net.Dialer{}).DialContext(ctx, network, addr)
- },
- }
+ clientProtocols := &http.Protocols{}
+ clientProtocols.SetUnencryptedHTTP2(true)
+ transport := &http.Transport{Protocols: clientProtocols, DisableCompression: true}
client := &http.Client{Transport: transport}
for _, path := range []string{"/api/health", "/api/openapi.json"} {
t.Run(path, func(t *testing.T) {
- req, err := http.NewRequest(http.MethodGet, "http://"+listener.Addr().String()+path, nil)
- require.NoError(t, err)
+ req, requestErr := http.NewRequest(http.MethodGet, "http://"+listener.Addr().String()+path, http.NoBody)
+ require.NoError(t, requestErr)
req.Header.Set("Accept-Encoding", "gzip")
- resp, err := client.Do(req)
- require.NoError(t, err)
+ resp, responseErr := client.Do(req)
+ require.NoError(t, responseErr)
defer func() { _ = resp.Body.Close() }()
- body, err := io.ReadAll(resp.Body)
- require.NoError(t, err)
+ body, readErr := io.ReadAll(resp.Body)
+ require.NoError(t, readErr)
require.Equal(t, "HTTP/2.0", resp.Proto)
require.Equal(t, http.StatusOK, resp.StatusCode)
@@ -291,16 +285,13 @@ func TestH2CStreamSurvivesPastReadHeaderTimeoutInternal(t *testing.T) {
errCh <- server.Serve(listener)
}()
t.Cleanup(func() {
- require.NoError(t, server.Shutdown(context.Background()))
+ require.NoError(t, server.Shutdown(context.WithoutCancel(t.Context())))
require.ErrorIs(t, <-errCh, http.ErrServerClosed)
})
- transport := &http2.Transport{
- AllowHTTP: true,
- DialTLSContext: func(ctx context.Context, network, addr string, _ *tls.Config) (net.Conn, error) {
- return (&net.Dialer{}).DialContext(ctx, network, addr)
- },
- }
+ clientProtocols := &http.Protocols{}
+ clientProtocols.SetUnencryptedHTTP2(true)
+ transport := &http.Transport{Protocols: clientProtocols}
client := &http.Client{Transport: transport}
resp, err := client.Get("http://" + listener.Addr().String() + "/stream")
@@ -345,14 +336,14 @@ func TestHTTPServerStopCancelsStreamingRequestContextsInternal(t *testing.T) {
Router: router,
})
require.NoError(t, err)
- require.NoError(t, lifecycle.Start(context.Background()))
+ require.NoError(t, lifecycle.Start(t.Context()))
resp, err := http.Get("http://" + srv.Addr + "/stream")
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
<-handlerEntered
- shutdownCtx, cancelShutdown := context.WithTimeout(context.Background(), 2*time.Second)
+ shutdownCtx, cancelShutdown := context.WithTimeout(t.Context(), 2*time.Second)
defer cancelShutdown()
start := time.Now()
require.NoError(t, lifecycle.Stop(shutdownCtx))
@@ -368,7 +359,7 @@ func TestNewHTTPServerRejectsInvalidTLSCertificateInternal(t *testing.T) {
}
_, err := NewHTTPServer(fxtest.NewLifecycle(t), HTTPServerParams{
- AppCtx: context.Background(),
+ AppCtx: t.Context(),
Config: cfg,
Router: echo.New(),
})
@@ -376,7 +367,7 @@ func TestNewHTTPServerRejectsInvalidTLSCertificateInternal(t *testing.T) {
}
func TestRegisterAppCancelHookRunsAfterLaterStopHooks(t *testing.T) {
- appCtx, cancelApp := context.WithCancel(context.Background())
+ appCtx, cancelApp := context.WithCancel(t.Context())
lifecycle := fxtest.NewLifecycle(t)
registerAppCancelHook(lifecycle, cancelApp)
appActiveDuringDependencyStop := false
@@ -462,7 +453,7 @@ func TestJobSchedulerStopCancelsItsPrivateContextInternal(t *testing.T) {
}
func TestApplicationOptionsValidate(t *testing.T) {
- appCtx, cancelApp := context.WithCancel(context.Background())
+ appCtx, cancelApp := context.WithCancel(t.Context())
defer cancelApp()
err := fx.ValidateApp(applicationOptions(
@@ -481,7 +472,7 @@ func TestPrepareServerTLSInternal_AgentModeSkipsManagerMTLSValidation(t *testing
ManagerApiUrl: "https://127.0.0.1:3552",
}
- useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(context.Background(), cfg)
+ useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(t.Context(), cfg)
require.NoError(t, err)
assert.False(t, useTLS)
assert.Empty(t, tlsCertFile)
@@ -504,7 +495,7 @@ func TestPrepareServerTLSInternal_AllowsExternalMTLSTermination(t *testing.T) {
EncryptionKey: "test-encryption-key-for-edge-mtls-32bytes-min",
}
- useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(context.Background(), cfg)
+ useTLS, tlsCertFile, tlsKeyFile, edgeCfg, err := prepareServerTLSInternal(t.Context(), cfg)
require.NoError(t, err)
assert.False(t, useTLS)
assert.Empty(t, tlsCertFile)
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 4e766a503..cf104b952 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -32,7 +32,25 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs"
)
-func newJobScheduler(appCtx context.Context, lc fx.Lifecycle, cfg *config.Config, runtime *runs.Coordinator, _ *runs.Admission, imageUpdateWatcher *scheduler.ImageUpdateWatcher, analytics *scheduler.AnalyticsJob, systemUpgrade *system.SystemUpgradeService, jobService *job.JobService, backupEngine *backup.Engine, updaterService *updater.UpdaterService, volumes *volume.VolumeService, systemBackups *systembackup.SystemBackupService, gitopsSync *gitops.GitOpsSyncService) (schedulertypes.JobScheduler, error) {
+func newJobScheduler(
+ appCtx context.Context,
+ lc fx.Lifecycle,
+ cfg *config.Config,
+ runtime *runs.Coordinator,
+ _ *runs.Admission,
+ imageUpdateWatcher *scheduler.ImageUpdateWatcher,
+ analytics *scheduler.AnalyticsJob,
+ systemUpgrade *system.SystemUpgradeService,
+ jobService *job.JobService,
+ backupEngine *backup.Engine,
+ updaterService *updater.UpdaterService,
+ volumes *volume.VolumeService,
+ systemBackups *systembackup.SystemBackupService,
+ gitopsSync *gitops.GitOpsSyncService,
+) (
+ schedulertypes.JobScheduler,
+ error,
+) {
schedulerCtx, cancelScheduler := context.WithCancel(appCtx)
jobScheduler, err := scheduler.NewJobScheduler(schedulerCtx, jobService.Coordinator(), cfg.GetLocation())
if err != nil {
@@ -51,11 +69,11 @@ func newJobScheduler(appCtx context.Context, lc fx.Lifecycle, cfg *config.Config
}
}()
slog.InfoContext(appCtx, "Starting scheduler")
- if err := jobService.Coordinator().Start(ctx, schedulerCtx); err != nil {
- return fmt.Errorf("initialize scheduler: %w", err)
+ if startErr := jobService.Coordinator().Start(ctx, schedulerCtx); startErr != nil {
+ return fmt.Errorf("initialize scheduler: %w", startErr)
}
- if err := reconcileCoordinatorStartupInternal(ctx, jobService, backupEngine, updaterService, volumes, systemBackups, gitopsSync); err != nil {
- return fmt.Errorf("reconcile scheduler startup: %w", err)
+ if reconcileCoordinatorStartupErr := reconcileCoordinatorStartupInternal(ctx, jobService, backupEngine, updaterService, volumes, systemBackups, gitopsSync); reconcileCoordinatorStartupErr != nil {
+ return fmt.Errorf("reconcile scheduler startup: %w", reconcileCoordinatorStartupErr)
}
if gitopsSync != nil {
gitopsSync.RegisterAutoSyncJobsOnStartup(ctx)
@@ -63,12 +81,12 @@ func newJobScheduler(appCtx context.Context, lc fx.Lifecycle, cfg *config.Config
}
if imageUpdateWatcher != nil {
imageUpdateWatcher.SetCoordinator(jobService.Coordinator())
- if err := jobScheduler.RegisterBusWatcher(imageUpdateWatcher, true); err != nil {
- return err
+ if registerBusWatcherErr := jobScheduler.RegisterBusWatcher(imageUpdateWatcher, true); registerBusWatcherErr != nil {
+ return registerBusWatcherErr
}
}
- if err := jobScheduler.StartScheduler(ctx); err != nil {
- return fmt.Errorf("start scheduler: %w", err)
+ if startSchedulerErr := jobScheduler.StartScheduler(ctx); startSchedulerErr != nil {
+ return fmt.Errorf("start scheduler: %w", startSchedulerErr)
}
jobService.Coordinator().Activate()
if backupEngine != nil {
@@ -79,16 +97,16 @@ func newJobScheduler(appCtx context.Context, lc fx.Lifecycle, cfg *config.Config
}()
}
if analytics != nil {
- if _, err := jobService.Coordinator().Submit(ctx, schedulertypes.Request{JobID: analytics.Name(), EnvironmentID: "0", Trigger: "startup"}); err != nil {
- return fmt.Errorf("submit startup job %q: %w", analytics.Name(), err)
+ if _, submitErr := jobService.Coordinator().Submit(ctx, schedulertypes.Request{JobID: analytics.Name(), EnvironmentID: "0", Trigger: "startup"}); submitErr != nil {
+ return fmt.Errorf("submit startup job %q: %w", analytics.Name(), submitErr)
}
}
if !cfg.AgentMode && systemUpgrade != nil {
resumeDone = make(chan struct{})
go func() { defer close(resumeDone); systemUpgrade.ResumeUpdateAllOnStartup(schedulerCtx) }()
}
- if err := ctx.Err(); err != nil {
- return fmt.Errorf("complete scheduler startup: %w", err)
+ if startupCancellationErr := ctx.Err(); startupCancellationErr != nil {
+ return fmt.Errorf("complete scheduler startup: %w", startupCancellationErr)
}
started = true
return nil
@@ -120,24 +138,32 @@ func stopJobSchedulerInternal(ctx context.Context, cancelScheduler context.Cance
return nil
}
-func reconcileCoordinatorStartupInternal(ctx context.Context, jobs *job.JobService, engine *backup.Engine, updates *updater.UpdaterService, volumes *volume.VolumeService, systemBackups *systembackup.SystemBackupService, syncService *gitops.GitOpsSyncService) error {
+func reconcileCoordinatorStartupInternal(
+ ctx context.Context,
+ jobs *job.JobService,
+ engine *backup.Engine,
+ updates *updater.UpdaterService,
+ volumes *volume.VolumeService,
+ systemBackups *systembackup.SystemBackupService,
+ syncService *gitops.GitOpsSyncService,
+) error {
activities, backups, err := startupProtectionInternal(ctx, jobs, engine, updates)
if err != nil {
return err
}
if volumes != nil {
- if err := volumes.ReconcileInterruptedBackups(ctx, backups...); err != nil {
- return err
+ if reconcileInterruptedBackupsErr := volumes.ReconcileInterruptedBackups(ctx, backups...); reconcileInterruptedBackupsErr != nil {
+ return reconcileInterruptedBackupsErr
}
}
if systemBackups != nil {
- if err := systemBackups.ReconcileInterruptedBackups(ctx, backups...); err != nil {
- return err
+ if reconcileSystemBackupsErr := systemBackups.ReconcileInterruptedBackups(ctx, backups...); reconcileSystemBackupsErr != nil {
+ return reconcileSystemBackupsErr
}
}
if syncService != nil {
- if err := syncService.ReconcileInterruptedBackupsOnStartup(ctx, backups...); err != nil {
- return err
+ if reconcileInterruptedBackupsOnStartupErr := syncService.ReconcileInterruptedBackupsOnStartup(ctx, backups...); reconcileInterruptedBackupsOnStartupErr != nil {
+ return reconcileInterruptedBackupsOnStartupErr
}
}
return jobs.ReconcileStartupActivities(ctx, activities...)
@@ -156,23 +182,23 @@ func startupProtectionInternal(ctx context.Context, jobs *job.JobService, engine
activities := []string{}
backups := make([]string, 0, len(scheduled))
if engine != nil {
- var err error
- activities, err = engine.ActiveActivityIDs(ctx)
- if err != nil {
- return nil, nil, err
+ var loadActivityIDsErr error
+ activities, loadActivityIDsErr = engine.ActiveActivityIDs(ctx)
+ if loadActivityIDsErr != nil {
+ return nil, nil, loadActivityIDsErr
}
- backups, err = engine.ActiveRunIDs(ctx)
- if err != nil {
- return nil, nil, err
+ backups, loadActivityIDsErr = engine.ActiveRunIDs(ctx)
+ if loadActivityIDsErr != nil {
+ return nil, nil, loadActivityIDsErr
}
- if err := engine.ReconcileDispatches(ctx); err != nil {
- return nil, nil, err
+ if reconcileDispatchesErr := engine.ReconcileDispatches(ctx); reconcileDispatchesErr != nil {
+ return nil, nil, reconcileDispatchesErr
}
}
if updates != nil {
- ids, err := updates.ActiveUpdateActivityIDs(ctx)
- if err != nil {
- return nil, nil, err
+ ids, activeUpdateActivityIDsErr := updates.ActiveUpdateActivityIDs(ctx)
+ if activeUpdateActivityIDsErr != nil {
+ return nil, nil, activeUpdateActivityIDsErr
}
activities = append(activities, ids...)
}
@@ -556,8 +582,8 @@ func setupTimeoutSettingsSubscriptionInternal(params settingsSubscriptionsParams
}
// syncTimeoutSettingsToAgentsInternal syncs timeout settings to all connected remote environments
-func syncTimeoutSettingsToAgentsInternal(ctx context.Context, environment timeoutSettingsEnvironmentInternal, timeoutSettings []libarcane.SettingUpdate) {
- envs, err := environment.ListRemoteEnvironments(ctx)
+func syncTimeoutSettingsToAgentsInternal(ctx context.Context, localEnvironment timeoutSettingsEnvironmentInternal, timeoutSettings []libarcane.SettingUpdate) {
+ envs, err := localEnvironment.ListRemoteEnvironments(ctx)
if err != nil {
slog.WarnContext(ctx, "Failed to list remote environments for timeout sync", "error", err)
return
@@ -583,9 +609,9 @@ func syncTimeoutSettingsToAgentsInternal(ctx context.Context, environment timeou
slog.InfoContext(ctx, "Syncing environment settings to remote environments", "count", len(envs), "keys", keys)
for _, env := range envs {
- responseBody, statusCode, err := environment.ProxyRequest(ctx, env.ID, http.MethodPut, "/api/environments/0/settings", body)
- if err != nil {
- slog.WarnContext(ctx, "Failed to sync timeout settings to environment", "environmentID", env.ID, "environmentName", env.Name, "error", err)
+ responseBody, statusCode, proxyRequestErr := localEnvironment.ProxyRequest(ctx, env.ID, http.MethodPut, "/api/environments/0/settings", body)
+ if proxyRequestErr != nil {
+ slog.WarnContext(ctx, "Failed to sync timeout settings to environment", "environmentID", env.ID, "environmentName", env.Name, "error", proxyRequestErr)
continue
}
if statusCode < http.StatusOK || statusCode >= http.StatusMultipleChoices {
diff --git a/backend/internal/bootstrap/jobs_bootstrap_test.go b/backend/internal/bootstrap/jobs_bootstrap_test.go
index 7bb26ec82..b1a7db187 100644
--- a/backend/internal/bootstrap/jobs_bootstrap_test.go
+++ b/backend/internal/bootstrap/jobs_bootstrap_test.go
@@ -78,15 +78,15 @@ func TestSettingsTimeoutSyncDoesNotBlockOtherEffectsInternal(t *testing.T) {
lifecycle := fxtest.NewLifecycle(t)
settings := &settingsSubscriptionStubInternal{}
- scheduler := &settingsSubscriptionSchedulerStubInternal{rescheduled: make(chan struct{})}
- environment := &timeoutSyncEnvironmentStubInternal{started: make(chan struct{})}
+ localScheduler := &settingsSubscriptionSchedulerStubInternal{rescheduled: make(chan struct{})}
+ localEnvironment := &timeoutSyncEnvironmentStubInternal{started: make(chan struct{})}
require.NoError(t, setupSettingsSubscriptionsInternal(settingsSubscriptionsParams{
Lifecycle: lifecycle,
- LifecycleCtx: context.Background(),
+ LifecycleCtx: t.Context(),
Config: &config.Config{},
- Scheduler: scheduler,
+ Scheduler: localScheduler,
Settings: settings,
- Environment: environment,
+ Environment: localEnvironment,
}))
timeoutCallbackDone := make(chan struct{})
@@ -96,7 +96,7 @@ func TestSettingsTimeoutSyncDoesNotBlockOtherEffectsInternal(t *testing.T) {
}()
select {
- case <-environment.started:
+ case <-localEnvironment.started:
case <-time.After(time.Second):
require.FailNow(t, "timeout sync did not start")
}
@@ -108,12 +108,12 @@ func TestSettingsTimeoutSyncDoesNotBlockOtherEffectsInternal(t *testing.T) {
settings.pollingCallback([]libarcane.SettingUpdate{{Key: "pollingEnabled", Value: "true"}})
select {
- case <-scheduler.rescheduled:
+ case <-localScheduler.rescheduled:
case <-time.After(time.Second):
require.FailNow(t, "local settings effect was blocked by remote timeout sync")
}
- stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
require.NoError(t, lifecycle.Stop(stopCtx))
}
@@ -137,7 +137,7 @@ func TestFeatureChangeReschedulesScanAndPatchJobsInternal(t *testing.T) {
callback([]libarcane.SettingUpdate{{Key: features.VulnerabilityManagementSettingKey, Value: "false"}})
}
require.ElementsMatch(t, []string{scheduler.VulnerabilityScanJobName, scheduler.VulnerabilityRiskJobName, scheduler.AutoPatchJobName}, schedulerStub.jobs)
- stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
require.NoError(t, lifecycle.Stop(stopCtx))
}
diff --git a/backend/internal/bootstrap/router_bootstrap_test.go b/backend/internal/bootstrap/router_bootstrap_test.go
index afe8318cd..092882afa 100644
--- a/backend/internal/bootstrap/router_bootstrap_test.go
+++ b/backend/internal/bootstrap/router_bootstrap_test.go
@@ -37,7 +37,7 @@ func TestNewEchoInternal_DecodesPathParams(t *testing.T) {
// RFC 3986 §6.2.2.2: these are all the same URI and must resolve identically.
for _, segment := range []string{"sha256:abc", "sha256%3Aabc", "%73ha256:abc"} {
got = ""
- req := httptest.NewRequest(http.MethodGet, "/api/environments/0/images/"+segment, nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/0/images/"+segment, http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -57,7 +57,7 @@ func TestSecureCookieContextMiddleware_TrustGating(t *testing.T) {
runRequest := func(t *testing.T, nets []*net.IPNet, remoteAddr, forwardedProto string) bool {
t.Helper()
e := echo.New()
- req := httptest.NewRequest("GET", "/", nil)
+ req := httptest.NewRequest("GET", "/", http.NoBody)
req.RemoteAddr = remoteAddr
if forwardedProto != "" {
req.Header.Set("X-Forwarded-Proto", forwardedProto)
@@ -71,9 +71,9 @@ func TestSecureCookieContextMiddleware_TrustGating(t *testing.T) {
return nil
})
{
- err := handler(c)
- require.NoError(t, err,
- "handler: %v", err)
+ handlerErr := handler(c)
+ require.NoError(t, handlerErr,
+ "handler: %v", handlerErr)
}
return observed
diff --git a/backend/internal/bootstrap/server_bootstrap.go b/backend/internal/bootstrap/server_bootstrap.go
index 703d9bbdb..f93016bef 100644
--- a/backend/internal/bootstrap/server_bootstrap.go
+++ b/backend/internal/bootstrap/server_bootstrap.go
@@ -54,17 +54,17 @@ func NewHTTPServer(lc fx.Lifecycle, p HTTPServerParams) (*http.Server, error) {
httpHandler, protocols := configureHTTPProtocolsInternal(useTLS, httpHandler)
// Request contexts deliberately do not inherit the app lifecycle marker.
- baseCtx, cancelBase := context.WithCancel(context.Background())
+ baseCtx, cancelBase := context.WithCancel(context.Background()) //nolint:forbidigo // HTTP requests need a root without the application lifecycle marker.
srv, err := newHTTPServerInternal(baseCtx, listenAddr, httpHandler, protocols, useTLS, edgeCfg)
if err != nil {
cancelBase()
return nil, err
}
if useTLS {
- certificate, err := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile)
- if err != nil {
+ certificate, loadX509KeyPairErr := tls.LoadX509KeyPair(tlsCertFile, tlsKeyFile)
+ if loadX509KeyPairErr != nil {
cancelBase()
- return nil, err
+ return nil, loadX509KeyPairErr
}
if srv.TLSConfig == nil {
srv.TLSConfig = &tls.Config{}
@@ -76,10 +76,10 @@ func NewHTTPServer(lc fx.Lifecycle, p HTTPServerParams) (*http.Server, error) {
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
- listener, err := new(net.ListenConfig).Listen(ctx, "tcp", listenAddr)
- if err != nil {
+ listener, listenErr := new(net.ListenConfig).Listen(ctx, "tcp", listenAddr)
+ if listenErr != nil {
cancelBase()
- return err
+ return listenErr
}
srv.Addr = listener.Addr().String()
diff --git a/backend/internal/build/service.go b/backend/internal/build/service.go
index 892ce1ce8..171b2f1ad 100644
--- a/backend/internal/build/service.go
+++ b/backend/internal/build/service.go
@@ -51,7 +51,7 @@ const buildHistoryOutputLimitBytes = 2 * 1024 * 1024
func NewBuildService(
db *database.DB,
- settings *settings.SettingsService,
+ localSettings *settings.SettingsService,
dockerService *docker.DockerClientService,
registryService *registry.ContainerRegistryService,
gitRepository *gitrepo.GitRepositoryService,
@@ -59,7 +59,7 @@ func NewBuildService(
) *BuildService {
svc := &BuildService{
db: db,
- settings: settings,
+ settings: localSettings,
dockerService: dockerService,
registryService: registryService,
gitRepository: gitRepository,
@@ -85,16 +85,28 @@ func (s *BuildService) BuildSettings() buildtypes.BuildSettings {
if s.settings == nil {
return buildtypes.BuildSettings{}
}
- settings := s.settings.GetSettingsConfig()
+ localSettings := s.settings.GetSettingsConfig()
return buildtypes.BuildSettings{
- DepotProjectID: settings.DepotProjectId.Value,
- DepotToken: settings.DepotToken.Value,
- BuildProvider: settings.BuildProvider.Value,
- BuildTimeoutSecs: settings.BuildTimeout.AsInt(),
+ DepotProjectID: localSettings.DepotProjectId.Value,
+ DepotToken: localSettings.DepotToken.Value,
+ BuildProvider: localSettings.BuildProvider.Value,
+ BuildTimeoutSecs: localSettings.BuildTimeout.AsInt(),
}
}
-func (s *BuildService) BuildImage(ctx context.Context, environmentID string, req buildtypes.BuildRequest, progressWriter io.Writer, serviceName string, user *common.User) (*buildtypes.BuildResult, error) {
+func (
+ s *BuildService,
+) BuildImage(
+ ctx context.Context,
+ environmentID string,
+ req buildtypes.BuildRequest,
+ progressWriter io.Writer,
+ serviceName string,
+ user *common.User,
+) (
+ *buildtypes.BuildResult,
+ error,
+) {
if s.builder == nil {
return nil, errors.New("build service not available")
}
@@ -167,7 +179,22 @@ func (s *BuildService) BuildImage(ctx context.Context, environmentID string, req
errMsg = new(err.Error())
}
- if updateErr := s.completeBuildRecord(ctx, buildRecordID, status, outputPtr, logCapture.Truncated(), errMsg, digest, provider, completedAt, new(completedAt.Sub(startedAt).Milliseconds())); updateErr != nil {
+ if updateErr := s.completeBuildRecord(
+ ctx,
+ buildRecordID,
+ status,
+ outputPtr,
+ logCapture.Truncated(),
+ errMsg,
+ digest,
+ provider,
+ completedAt,
+ new(
+ completedAt.Sub(
+ startedAt,
+ ).Milliseconds(),
+ ),
+ ); updateErr != nil {
slog.WarnContext(ctx, "failed to update build history record", "error", updateErr)
}
}
@@ -278,8 +305,8 @@ func (s *BuildService) resolveBuildRequestInternal(
}
if gitkit.RequiresRemoteProbe(source.RepositoryURL) {
writeBuildProgressStatusInternal(progressWriter, serviceName, "verifying remote git repository "+source.RepositoryURL)
- if err := s.probeGitContextInternal(ctx, source.RepositoryURL, authConfig); err != nil {
- return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("failed to verify remote git repository %q: %w", source.RepositoryURL, err)
+ if probeGitContextErr := s.probeGitContextInternal(ctx, source.RepositoryURL, authConfig); probeGitContextErr != nil {
+ return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("failed to verify remote git repository %q: %w", source.RepositoryURL, probeGitContextErr)
}
}
@@ -290,9 +317,9 @@ func (s *BuildService) resolveBuildRequestInternal(
contextDir := repoPath
if source.Subdir != "" {
- if err := buildgit.ValidatePath(repoPath, filepath.FromSlash(source.Subdir)); err != nil {
+ if validatePathErr := buildgit.ValidatePath(repoPath, filepath.FromSlash(source.Subdir)); validatePathErr != nil {
_ = s.cleanupGitContextInternal(repoPath)
- return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("invalid git build context subdir: %w", err)
+ return buildtypes.BuildRequest{}, func() error { return nil }, fmt.Errorf("invalid git build context subdir: %w", validatePathErr)
}
contextDir = filepath.Join(repoPath, filepath.FromSlash(source.Subdir))
}
diff --git a/backend/internal/build/service_test.go b/backend/internal/build/service_test.go
index 26e50c983..6b198db81 100644
--- a/backend/internal/build/service_test.go
+++ b/backend/internal/build/service_test.go
@@ -42,7 +42,7 @@ func TestBuildService_ResolveBuildRequest_PassesThroughLocalContext(t *testing.T
Dockerfile: "Dockerfile",
}
- resolvedReq, cleanup, err := svc.resolveBuildRequestInternal(context.Background(), req, nil, "")
+ resolvedReq, cleanup, err := svc.resolveBuildRequestInternal(t.Context(), req, nil, "")
require.NoError(t, err)
require.NotNil(t, cleanup)
assert.Equal(t, req, resolvedReq)
@@ -89,7 +89,7 @@ func TestBuildService_ResolveBuildRequest_ClonesRemoteGitContext(t *testing.T) {
Dockerfile: "Dockerfile",
}
- resolvedReq, cleanup, err := svc.resolveBuildRequestInternal(context.Background(), req, nil, "manual")
+ resolvedReq, cleanup, err := svc.resolveBuildRequestInternal(t.Context(), req, nil, "manual")
require.NoError(t, err)
assert.Equal(t, filepath.Join(repoPath, "docker", "app"), resolvedReq.ContextDir)
require.NoError(t, cleanup())
@@ -121,7 +121,7 @@ func TestBuildService_ResolveBuildRequest_ProbesAndClonesRemoteGitContextWithout
}
resolvedReq, cleanup, err := svc.resolveBuildRequestInternal(
- context.Background(),
+ t.Context(),
buildtypes.BuildRequest{ContextDir: "https://git.sr.ht/~jordanreger/nws-alerts#main:docker/app"},
nil,
"",
@@ -137,7 +137,7 @@ func TestBuildService_ResolveBuildRequest_RequiresGitRepositoryServiceForRemoteC
svc := &BuildService{}
_, cleanup, err := svc.resolveBuildRequestInternal(
- context.Background(),
+ t.Context(),
buildtypes.BuildRequest{ContextDir: "https://github.com/getarcaneapp/arcane.git#main"},
nil,
"",
@@ -161,7 +161,7 @@ func TestBuildService_ResolveBuildRequest_RejectsNonGitHTTPContextViaProbeFailur
}
_, cleanup, err := svc.resolveBuildRequestInternal(
- context.Background(),
+ t.Context(),
buildtypes.BuildRequest{ContextDir: "https://example.com/archive.tar.gz"},
nil,
"",
@@ -222,13 +222,13 @@ func TestBuildService_ResolveBuildRequest_UsesSavedGitCredentials(t *testing.T)
gitCleanupFn: func(string) error { return nil },
}
- _, cleanup, err := svc.resolveBuildRequestInternal(
- context.Background(),
+ _, cleanup, resolveBuildRequestErr := svc.resolveBuildRequestInternal(
+ t.Context(),
buildtypes.BuildRequest{ContextDir: "https://github.com/getarcaneapp/private-build#main"},
nil,
"",
)
- require.NoError(t, err)
+ require.NoError(t, resolveBuildRequestErr)
require.NoError(t, cleanup())
})
@@ -248,13 +248,13 @@ func TestBuildService_ResolveBuildRequest_UsesSavedGitCredentials(t *testing.T)
gitCleanupFn: func(string) error { return nil },
}
- _, cleanup, err := svc.resolveBuildRequestInternal(
- context.Background(),
+ _, cleanup, resolveBuildRequestErr := svc.resolveBuildRequestInternal(
+ t.Context(),
buildtypes.BuildRequest{ContextDir: "[email protected]:getarcaneapp/private-ssh.git#main"},
nil,
"",
)
- require.NoError(t, err)
+ require.NoError(t, resolveBuildRequestErr)
require.NoError(t, cleanup())
})
}
@@ -287,12 +287,12 @@ func TestBuildService_BuildImage_PreservesRemoteSourceInHistory(t *testing.T) {
Load: true,
}
- _, err = svc.BuildImage(context.Background(), "0", req, nil, "manual", nil)
+ _, err = svc.BuildImage(t.Context(), "0", req, nil, "manual", nil)
require.NoError(t, err)
assert.Equal(t, repoPath, captured.ContextDir)
var record ImageBuild
- require.NoError(t, db.WithContext(context.Background()).First(&record).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&record).Error)
assert.Equal(t, req.ContextDir, record.ContextDir)
}
@@ -321,17 +321,17 @@ func TestBuildService_BuildImage_FailureRecordsHistoryAndEvent(t *testing.T) {
Load: true,
}
- _, err = svc.BuildImage(context.Background(), "0", req, nil, "web", user)
+ _, err = svc.BuildImage(t.Context(), "0", req, nil, "web", user)
require.ErrorIs(t, err, buildErr)
var record ImageBuild
- require.NoError(t, db.WithContext(context.Background()).First(&record).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&record).Error)
assert.Equal(t, ImageBuildStatusFailed, record.Status)
require.NotNil(t, record.ErrorMessage)
assert.Contains(t, *record.ErrorMessage, "docker exporter")
var evt event.Event
- require.NoError(t, db.WithContext(context.Background()).First(&evt, "type = ?", event.EventTypeImageError).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&evt, "type = ?", event.EventTypeImageError).Error)
assert.Equal(t, event.EventSeverityError, evt.Severity)
require.NotNil(t, evt.ResourceName)
assert.Equal(t, "arcane.local/demo:test", *evt.ResourceName)
@@ -377,11 +377,11 @@ func TestBuildService_BuildImage_FailureExporterErrorsAppearInOutputHistoryAndEv
Load: true,
}
- _, err = svc.BuildImage(context.Background(), "0", req, progress, "web", user)
+ _, err = svc.BuildImage(t.Context(), "0", req, progress, "web", user)
require.ErrorIs(t, err, buildErr)
var record ImageBuild
- require.NoError(t, db.WithContext(context.Background()).First(&record).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&record).Error)
assert.Equal(t, ImageBuildStatusFailed, record.Status)
require.NotNil(t, record.Output)
assert.Contains(t, *record.Output, buildErr.Error())
@@ -389,7 +389,7 @@ func TestBuildService_BuildImage_FailureExporterErrorsAppearInOutputHistoryAndEv
assert.Contains(t, *record.ErrorMessage, "exporter \"image\"")
var evt event.Event
- require.NoError(t, db.WithContext(context.Background()).First(&evt, "type = ?", event.EventTypeImageError).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&evt, "type = ?", event.EventTypeImageError).Error)
assert.Equal(t, event.EventSeverityError, evt.Severity)
require.NotNil(t, evt.ResourceName)
assert.Equal(t, "ghcr.io/getarcaneapp/arcane:test", *evt.ResourceName)
@@ -446,7 +446,7 @@ func TestBuildService_ListImageBuilds_OmitsOutputColumn(t *testing.T) {
svc := &BuildService{db: db}
output := "large build output"
- require.NoError(t, db.WithContext(context.Background()).Create(&ImageBuild{
+ require.NoError(t, db.WithContext(t.Context()).Create(&ImageBuild{
ID: "build-omit-output",
EnvironmentID: "0",
Status: ImageBuildStatusSuccess,
@@ -454,7 +454,7 @@ func TestBuildService_ListImageBuilds_OmitsOutputColumn(t *testing.T) {
Output: &output,
}).Error)
- records, _, err := svc.ListImageBuildsByEnvironmentPaginated(context.Background(), "0", pagination.QueryParams{
+ records, _, err := svc.ListImageBuildsByEnvironmentPaginated(t.Context(), "0", pagination.QueryParams{
Limit: 10,
})
require.NoError(t, err)
@@ -462,7 +462,7 @@ func TestBuildService_ListImageBuilds_OmitsOutputColumn(t *testing.T) {
assert.Nil(t, records[0].Output)
// The detail endpoint must still return the stored output.
- detail, err := svc.GetImageBuildByID(context.Background(), "0", "build-omit-output")
+ detail, err := svc.GetImageBuildByID(t.Context(), "0", "build-omit-output")
require.NoError(t, err)
require.NotNil(t, detail.Output)
assert.Equal(t, output, *detail.Output)
@@ -473,15 +473,15 @@ func setupBuildHistoryTestDB() (*database.DB, error) {
if err != nil {
return nil, err
}
- if err := db.AutoMigrate(&ImageBuild{}, &event.Event{}); err != nil {
- return nil, err
+ if autoMigrateErr := db.AutoMigrate(&ImageBuild{}, &event.Event{}); autoMigrateErr != nil {
+ return nil, autoMigrateErr
}
return &database.DB{DB: db}, nil
}
func createTestGitRepository(t *testing.T, db *database.DB, repository gitrepo.GitRepository) {
t.Helper()
- require.NoError(t, db.WithContext(context.Background()).Create(&repository).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(&repository).Error)
}
func encryptSecretForTest(t *testing.T, value string) string {
diff --git a/backend/internal/build/workspace_handler.go b/backend/internal/build/workspace_handler.go
index e84347b01..246942026 100644
--- a/backend/internal/build/workspace_handler.go
+++ b/backend/internal/build/workspace_handler.go
@@ -61,7 +61,9 @@ func RegisterBuildWorkspaces(api huma.API, workspaceService *BuildWorkspaceServi
Method: "POST",
Path: "/environments/{id}/builds/browse/upload",
Summary: "Upload build workspace file",
- Description: "Copy a complete chunked upload session into the builds workspace root. multipart/form-data bodies are still accepted for backward compatibility; that form is deprecated and will be removed in a future release.",
+ Description: "Copy a complete chunked upload session into the builds workspace root. multipart/form-data bodies " +
+ "are still accepted for backward compatibility; that form is deprecated and will be removed in a " +
+ "future release.",
Tags: []string{"Builds"},
Security: handlerutil.DefaultOperationSecurity(),
Middlewares: upload.LegacyMultipartMiddleware(api, uploadService, uploadtypes.KindBuildWorkspace),
@@ -174,8 +176,8 @@ func (h *BuildWorkspaceHandler) UploadFile(ctx context.Context, input *UploadBui
}
defer cleanup()
- if err := h.service.UploadFile(ctx, input.Path, file, session.Filename, session.Size); err != nil {
- return nil, huma.Error500InternalServerError(err.Error())
+ if uploadFileErr := h.service.UploadFile(ctx, input.Path, file, session.Filename, session.Size); uploadFileErr != nil {
+ return nil, huma.Error500InternalServerError(uploadFileErr.Error())
}
return &base.ApiResponse[base.MessageResponse]{
Success: true,
diff --git a/backend/internal/build/workspace_service.go b/backend/internal/build/workspace_service.go
index 079dddebb..454587a06 100644
--- a/backend/internal/build/workspace_service.go
+++ b/backend/internal/build/workspace_service.go
@@ -28,8 +28,8 @@ type BuildWorkspaceService struct {
settings *settings.SettingsService
}
-func NewBuildWorkspaceService(settings *settings.SettingsService) *BuildWorkspaceService {
- return &BuildWorkspaceService{settings: settings}
+func NewBuildWorkspaceService(localSettings *settings.SettingsService) *BuildWorkspaceService {
+ return &BuildWorkspaceService{settings: localSettings}
}
func (s *BuildWorkspaceService) ListDirectory(ctx context.Context, dirPath string) ([]workspacetypes.FileEntry, error) {
@@ -125,13 +125,13 @@ func (s *BuildWorkspaceService) UploadFile(ctx context.Context, destPath string,
return fmt.Errorf("invalid path: %w", err)
}
- if err := acfs.MkdirAll(ctx, root, cleaned, 0o755); err != nil {
- return fmt.Errorf("failed to create directory: %w", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, root, cleaned, 0o755); mkdirAllErr != nil {
+ return fmt.Errorf("failed to create directory: %w", mkdirAllErr)
}
targetFile := path.Join(cleaned, safeFilename)
- if _, err := acfs.WriteFrom(ctx, root, targetFile, content, size, 0o644); err != nil {
- return fmt.Errorf("failed to write file: %w", err)
+ if _, writeFromErr := acfs.WriteFrom(ctx, root, targetFile, content, size, 0o644); writeFromErr != nil {
+ return fmt.Errorf("failed to write file: %w", writeFromErr)
}
return nil
@@ -153,8 +153,8 @@ func (s *BuildWorkspaceService) CreateDirectory(ctx context.Context, dirPath str
return nil
}
- if err := acfs.MkdirAll(ctx, root, cleaned, 0o755); err != nil {
- return fmt.Errorf("failed to create directory: %w", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, root, cleaned, 0o755); mkdirAllErr != nil {
+ return fmt.Errorf("failed to create directory: %w", mkdirAllErr)
}
return nil
@@ -176,8 +176,8 @@ func (s *BuildWorkspaceService) DeleteFile(ctx context.Context, filePath string)
return errors.New("cannot delete root directory")
}
- if err := acfs.RemoveAll(ctx, root, cleaned); err != nil {
- return fmt.Errorf("failed to delete path: %w", err)
+ if removeAllErr := acfs.RemoveAll(ctx, root, cleaned); removeAllErr != nil {
+ return fmt.Errorf("failed to delete path: %w", removeAllErr)
}
return nil
diff --git a/backend/internal/build/workspace_service_test.go b/backend/internal/build/workspace_service_test.go
index 59b5e1a68..45a0f024c 100644
--- a/backend/internal/build/workspace_service_test.go
+++ b/backend/internal/build/workspace_service_test.go
@@ -15,7 +15,7 @@ import (
)
func TestBuildWorkspaceServiceDeleteFileRejectsCurrentDirectoryInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -44,7 +44,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 123f8c2ef..1df34e4d4 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -41,30 +41,35 @@ var (
ErrTimeout = errors.New("kind: timeout")
ErrUnavailable = errors.New("kind: service unavailable")
- ErrFeatureDisabled = Classify(ErrForbidden, errors.New("feature disabled"))
- ErrInvalidToken = errors.New("invalid token")
- ErrExpiredToken = errors.New("token expired")
- ErrTokenVersionMismatch = errors.New("token version mismatch")
- ErrUserNotFound = errors.New("user not found")
- ErrAmbiguousUserEmail = Classify(ErrConflict, errors.New("multiple accounts share this email"))
- ErrTokenValidation = Classify(ErrUnauthorized, errors.New("Invalid token claims"))
- ErrSessionRevoked = Classify(ErrUnauthorized, errors.New("Session has been revoked"))
- ErrUpgradeInProgress = Classify(ErrConflict, errors.New("an upgrade is already in progress"))
- ErrUpdateAllInProgress = Classify(ErrConflict, errors.New("an update-all job is already in progress"))
- ErrUpdaterNoContainersMatched = Classify(ErrBadRequest, errors.New("no compose-managed containers matched the requested resources"))
- ErrTemplateNotFound = Classify(ErrNotFound, errors.New("Template not found"))
- ErrInvalidEnvKey = Classify(ErrValidation, errors.New("Invalid environment key"))
- ErrGlobalVariableNotFound = Classify(ErrNotFound, errors.New("Global variable not found"))
- ErrApnsDisabled = Classify(ErrForbidden, errors.New("Mobile push notifications are disabled"))
- ErrApnsDeviceNotFound = Classify(ErrNotFound, errors.New("Mobile push device not found"))
- ErrApnsDeviceConflict = Classify(ErrConflict, errors.New("Mobile push device is already registered"))
- ErrApnsRelay = Classify(ErrUnavailable, errors.New("Push relay request failed"))
- ErrGlobalVariableConflict = Classify(ErrConflict, errors.New("Global variable already exists"))
- ErrGlobalVariableScopeRequired = Classify(ErrValidation, errors.New("At least one environment is required when a variable is not scoped to all environments"))
- ErrGlobalVariableSecretValueRequired = Classify(ErrValidation, errors.New("A new value is required when making a secret variable readable"))
- ErrImageUntagged = Classify(ErrBadRequest, errors.New("image has no tag; only tagged images can be patched"))
- ErrImageLocalOnly = Classify(ErrBadRequest, errors.New("locally built image has no registry source to patch from; rebuild it to update its packages"))
- ErrPatchRequiresContainerdImageStore = Classify(ErrBadRequest, errors.New("image patching requires Docker's containerd image store; enable the containerd-snapshotter feature in daemon.json and restart Docker"))
+ ErrFeatureDisabled = Classify(ErrForbidden, errors.New("feature disabled"))
+ ErrInvalidToken = errors.New("invalid token")
+ ErrExpiredToken = errors.New("token expired")
+ ErrTokenVersionMismatch = errors.New("token version mismatch")
+ ErrUserNotFound = errors.New("user not found")
+ ErrAmbiguousUserEmail = Classify(ErrConflict, errors.New("multiple accounts share this email"))
+ ErrTokenValidation = Classify(ErrUnauthorized, errors.New("Invalid token claims"))
+ ErrSessionRevoked = Classify(ErrUnauthorized, errors.New("Session has been revoked"))
+ ErrUpgradeInProgress = Classify(ErrConflict, errors.New("an upgrade is already in progress"))
+ ErrUpdateAllInProgress = Classify(ErrConflict, errors.New("an update-all job is already in progress"))
+ ErrUpdaterNoContainersMatched = Classify(ErrBadRequest, errors.New("no compose-managed containers matched the requested resources"))
+ ErrTemplateNotFound = Classify(ErrNotFound, errors.New("Template not found"))
+ ErrInvalidEnvKey = Classify(ErrValidation, errors.New("Invalid environment key"))
+ ErrGlobalVariableNotFound = Classify(ErrNotFound, errors.New("Global variable not found"))
+ ErrApnsDisabled = Classify(ErrForbidden, errors.New("Mobile push notifications are disabled"))
+ ErrApnsDeviceNotFound = Classify(ErrNotFound, errors.New("Mobile push device not found"))
+ ErrApnsDeviceConflict = Classify(ErrConflict, errors.New("Mobile push device is already registered"))
+ ErrApnsRelay = Classify(ErrUnavailable, errors.New("Push relay request failed"))
+ ErrGlobalVariableConflict = Classify(ErrConflict, errors.New("Global variable already exists"))
+ ErrGlobalVariableScopeRequired = Classify(ErrValidation, errors.New("At least one environment is required when a variable is not scoped to all environments"))
+ ErrGlobalVariableSecretValueRequired = Classify(ErrValidation, errors.New("A new value is required when making a secret variable readable"))
+ ErrImageUntagged = Classify(ErrBadRequest, errors.New("image has no tag; only tagged images can be patched"))
+ ErrImageLocalOnly = Classify(ErrBadRequest, errors.New("locally built image has no registry source to patch from; rebuild it to update its packages"))
+ ErrPatchRequiresContainerdImageStore = Classify(
+ ErrBadRequest,
+ errors.New(
+ "image patching requires Docker's containerd image store; enable the containerd-snapshotter feature in daemon.json and restart Docker",
+ ),
+ )
ErrPatchScanReportUnavailable = Classify(ErrNotFound, errors.New("no stored scan report is available for this scan; re-scan the image or patch without a report"))
ErrPatchScanImageMismatch = Classify(ErrBadRequest, errors.New("the selected scan does not belong to this image"))
ErrContainerComposeManaged = Classify(ErrConflict, errors.New("container is managed by a compose project; edit it via the project editor"))
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index 6f1f610dc..f2cee8638 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -464,7 +464,7 @@ func (c *Config) MaskSensitive() map[string]any {
if isSensitive {
// Mask sensitive values
strVal := fmt.Sprintf("%v", field.Interface())
- result[envTag] = kit.Ternary(len(strVal) > 0, "****", "(empty)")
+ result[envTag] = kit.Ternary(strVal != "", "****", "(empty)")
} else {
result[envTag] = field.Interface()
}
diff --git a/backend/internal/config/schema/schema.go b/backend/internal/config/schema/schema.go
index ced593e03..50a13340c 100644
--- a/backend/internal/config/schema/schema.go
+++ b/backend/internal/config/schema/schema.go
@@ -195,7 +195,7 @@ func collectEnvConfigInternal(sourceRoot string) ([]ConfigEntry, error) {
}
configEntries, err := parseStructEnvFieldsInternal(
- filepath.Join(root, "internal/config/config.go"),
+ filepath.Join(root, "internal", "config", "config.go"),
"Config",
envFieldOptions{
sourceFile: sourceFileConfig,
@@ -207,7 +207,7 @@ func collectEnvConfigInternal(sourceRoot string) ([]ConfigEntry, error) {
}
buildablesEntries, err := parseStructEnvFieldsInternal(
- filepath.Join(root, "internal/config/buildables_config.go"),
+ filepath.Join(root, "internal", "config", "buildables_config.go"),
"BuildablesConfig",
envFieldOptions{
conditional: true,
@@ -246,9 +246,9 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOpti
continue
}
- tagValue, err := strconv.Unquote(field.Tag.Value)
- if err != nil {
- return nil, fmt.Errorf("unquote struct tag for %s: %w", structName, err)
+ tagValue, unquoteErr := strconv.Unquote(field.Tag.Value)
+ if unquoteErr != nil {
+ return nil, fmt.Errorf("unquote struct tag for %s: %w", structName, unquoteErr)
}
structTag := reflect.StructTag(tagValue)
@@ -258,9 +258,9 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOpti
}
options := kit.TrimNonEmpty(strings.Split(structTag.Get("options"), ","))
- typeName, err := exprStringInternal(field.Type)
- if err != nil {
- return nil, fmt.Errorf("render type for %s.%s: %w", structName, field.Names[0].Name, err)
+ typeName, unquoteErr := exprStringInternal(field.Type)
+ if unquoteErr != nil {
+ return nil, fmt.Errorf("render type for %s.%s: %w", structName, field.Names[0].Name, unquoteErr)
}
description := cmp.Or(strings.Join(strings.Fields(field.Doc.Text()), " "), strings.Join(strings.Fields(field.Comment.Text()), " "))
@@ -362,13 +362,13 @@ func findStructTypeInternal(file *ast.File, structName string) (*ast.StructType,
}
for _, spec := range genDecl.Specs {
- typeSpec, ok := spec.(*ast.TypeSpec)
- if !ok || typeSpec.Name.Name != structName {
+ typeSpec, localOk := spec.(*ast.TypeSpec)
+ if !localOk || typeSpec.Name.Name != structName {
continue
}
- structType, ok := typeSpec.Type.(*ast.StructType)
- if !ok {
+ structType, localOk := typeSpec.Type.(*ast.StructType)
+ if !localOk {
return nil, fmt.Errorf("%s is not a struct", structName)
}
@@ -440,8 +440,8 @@ func resolveSourceRootCandidateInternal(candidate string) (string, error) {
func hasSchemaSourceFilesInternal(root string) bool {
required := []string{
- filepath.Join(root, "internal/config/config.go"),
- filepath.Join(root, "internal/config/buildables_config.go"),
+ filepath.Join(root, "internal", "config", "config.go"),
+ filepath.Join(root, "internal", "config", "buildables_config.go"),
}
// os.* rather than acfs: this probes repo source files while walking up
diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.go
index df7bac478..d173fce32 100644
--- a/backend/internal/container/handler.go
+++ b/backend/internal/container/handler.go
@@ -137,7 +137,14 @@ type GenerateComposeInput struct {
Body containertypes.GenerateComposeRequest
}
-func RegisterContainers(api huma.API, containerSvc *ContainerService, dockerSvc *docker.DockerClientService, settingsSvc *settings.SettingsService, activitySvc *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
+func RegisterContainers(
+ api huma.API,
+ containerSvc *ContainerService,
+ dockerSvc *docker.DockerClientService,
+ settingsSvc *settings.SettingsService,
+ activitySvc *activity.ActivityService,
+ appCtx handlerutil.ActivityAppContext,
+) {
h := &ContainerHandler{
containerService: containerSvc,
dockerService: dockerSvc,
@@ -476,9 +483,9 @@ func applyHostConfigPortBindings(config *dockercontainer.Config, portBindings ne
for _, binding := range bindingList {
pb := network.PortBinding{HostPort: binding.HostPort}
if hostIP := strings.TrimSpace(binding.HostIP); hostIP != "" {
- parsedIP, err := netip.ParseAddr(hostIP)
- if err != nil {
- return err
+ parsedIP, parseAddrErr := netip.ParseAddr(hostIP)
+ if parseAddrErr != nil {
+ return parseAddrErr
}
pb.HostIP = parsedIP
}
@@ -598,16 +605,16 @@ func (h *ContainerHandler) CreateContainer(ctx context.Context, input *CreateCon
config := buildContainerConfig(input.Body)
portBindings := network.PortMap{}
- if err := applyLegacyPortBindings(input.Body, config, portBindings); err != nil {
- return nil, huma.Error400BadRequest("Invalid port format: " + err.Error())
+ if applyLegacyPortBindingsErr := applyLegacyPortBindings(input.Body, config, portBindings); applyLegacyPortBindingsErr != nil {
+ return nil, huma.Error400BadRequest("Invalid port format: " + applyLegacyPortBindingsErr.Error())
}
- if err := applyExposedPorts(input.Body.ExposedPorts, config); err != nil {
- return nil, huma.Error400BadRequest("Invalid port format: " + err.Error())
+ if applyExposedPortsErr := applyExposedPorts(input.Body.ExposedPorts, config); applyExposedPortsErr != nil {
+ return nil, huma.Error400BadRequest("Invalid port format: " + applyExposedPortsErr.Error())
}
hostConfig := buildHostConfigBase(input.Body, portBindings)
- if err := applyHostConfigOverrides(input.Body, config, hostConfig, portBindings); err != nil {
- return nil, huma.Error400BadRequest("Invalid port format: " + err.Error())
+ if applyHostConfigOverridesErr := applyHostConfigOverrides(input.Body, config, hostConfig, portBindings); applyHostConfigOverridesErr != nil {
+ return nil, huma.Error400BadRequest("Invalid port format: " + applyHostConfigOverridesErr.Error())
}
applyLegacyResourceLimits(input.Body, hostConfig)
@@ -823,10 +830,28 @@ func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input
}
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, cfg.ActivityType, "container", input.ContainerID, h.containerActivityNameInternal(runtimeCtx, input.ContainerID), user, cfg.Step, cfg.StartMessage, database.JSON{"containerID": input.ContainerID}, false)
- if err := cfg.Action(runtimeCtx, input.ContainerID, *user); err != nil {
- activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.CompleteMessage, err)
- return nil, cfg.Error(err)
+ activityID, runtimeCtx := activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ input.EnvironmentID,
+ cfg.ActivityType,
+ "container",
+ input.ContainerID,
+ h.containerActivityNameInternal(
+ runtimeCtx,
+ input.ContainerID,
+ ),
+ user,
+ cfg.Step,
+ cfg.StartMessage,
+ database.JSON{
+ "containerID": input.ContainerID,
+ },
+ false,
+ )
+ if actionErr := cfg.Action(runtimeCtx, input.ContainerID, *user); actionErr != nil {
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.CompleteMessage, actionErr)
+ return nil, cfg.Error(actionErr)
}
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.CompleteMessage, nil)
@@ -868,7 +893,25 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain
}
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeContainerRedeploy, "container", input.ContainerID, h.containerActivityNameInternal(runtimeCtx, input.ContainerID), user, "Starting redeploy", "Container redeploy requested", database.JSON{"containerID": input.ContainerID}, true)
+ activityID, runtimeCtx := activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ input.EnvironmentID,
+ activitytypes.TypeContainerRedeploy,
+ "container",
+ input.ContainerID,
+ h.containerActivityNameInternal(
+ runtimeCtx,
+ input.ContainerID,
+ ),
+ user,
+ "Starting redeploy",
+ "Container redeploy requested",
+ database.JSON{
+ "containerID": input.ContainerID,
+ },
+ true,
+ )
activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, input.EnvironmentID)
activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Redeploying container")
redeployCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)
@@ -939,7 +982,25 @@ func (h *ContainerHandler) EditContainer(ctx context.Context, input *EditContain
}
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeContainerEdit, "container", input.ContainerID, h.containerActivityNameInternal(runtimeCtx, input.ContainerID), user, "Starting edit", "Container edit requested", database.JSON{"containerID": input.ContainerID}, true)
+ activityID, runtimeCtx := activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ input.EnvironmentID,
+ activitytypes.TypeContainerEdit,
+ "container",
+ input.ContainerID,
+ h.containerActivityNameInternal(
+ runtimeCtx,
+ input.ContainerID,
+ ),
+ user,
+ "Starting edit",
+ "Container edit requested",
+ database.JSON{
+ "containerID": input.ContainerID,
+ },
+ true,
+ )
activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, input.EnvironmentID)
activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Editing container")
editCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)
@@ -985,10 +1046,30 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon
}
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeContainerDelete, "container", input.ContainerID, h.containerActivityNameInternal(runtimeCtx, input.ContainerID), user, "Deleting container", "Container delete requested", database.JSON{"containerID": input.ContainerID, "force": input.Force, "removeVolumes": input.RemoveVolumes}, false)
- if err := h.containerService.DeleteContainer(runtimeCtx, input.ContainerID, input.Force, input.RemoveVolumes, *user); err != nil {
- activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", err)
- return nil, huma.Error500InternalServerError("Failed to delete container: " + err.Error())
+ activityID, runtimeCtx := activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ input.EnvironmentID,
+ activitytypes.TypeContainerDelete,
+ "container",
+ input.ContainerID,
+ h.containerActivityNameInternal(
+ runtimeCtx,
+ input.ContainerID,
+ ),
+ user,
+ "Deleting container",
+ "Container delete requested",
+ database.JSON{
+ "containerID": input.ContainerID,
+ "force": input.Force,
+ "removeVolumes": input.RemoveVolumes,
+ },
+ false,
+ )
+ if deleteContainerErr := h.containerService.DeleteContainer(runtimeCtx, input.ContainerID, input.Force, input.RemoveVolumes, *user); deleteContainerErr != nil {
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", deleteContainerErr)
+ return nil, huma.Error500InternalServerError("Failed to delete container: " + deleteContainerErr.Error())
}
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", nil)
@@ -1008,7 +1089,7 @@ func (h *ContainerHandler) SetAutoUpdate(ctx context.Context, input *SetAutoUpda
}
excluded := !input.Body.Enabled
- if err := h.settingsService.SetContainerAutoUpdateExclusionInternal(ctx, containerName, excluded); err != nil {
+ if setContainerAutoUpdateExclusionErr := h.settingsService.SetContainerAutoUpdateExclusionInternal(ctx, containerName, excluded); setContainerAutoUpdateExclusionErr != nil {
return nil, huma.Error500InternalServerError("failed to update auto-update setting")
}
diff --git a/backend/internal/container/logs_test.go b/backend/internal/container/logs_test.go
index e3a5cdd25..a6c413b77 100644
--- a/backend/internal/container/logs_test.go
+++ b/backend/internal/container/logs_test.go
@@ -2,7 +2,6 @@ package container
import (
"bytes"
- "context"
"encoding/binary"
"io"
"net/http"
@@ -66,7 +65,7 @@ func TestContainerServiceDownloadLogsDemultiplexesNonTTYInternal(t *testing.T) {
var gotQuery url.Values
svc := newLogsTestServiceInternal(t, false, frames.Bytes(), &gotQuery)
- reader, filename, err := svc.DownloadLogs(context.Background(), "container-1")
+ reader, filename, err := svc.DownloadLogs(t.Context(), "container-1")
require.NoError(t, err)
t.Cleanup(func() { _ = reader.Close() })
@@ -88,7 +87,7 @@ func TestContainerServiceDownloadLogsPassesTTYOutputThroughInternal(t *testing.T
var gotQuery url.Values
svc := newLogsTestServiceInternal(t, true, []byte("raw tty line\r\nno trailing newline"), &gotQuery)
- reader, filename, err := svc.DownloadLogs(context.Background(), "container-1")
+ reader, filename, err := svc.DownloadLogs(t.Context(), "container-1")
require.NoError(t, err)
content, err := io.ReadAll(reader)
diff --git a/backend/internal/container/resource_stats.go b/backend/internal/container/resource_stats.go
index 81225f983..5a64aec4f 100644
--- a/backend/internal/container/resource_stats.go
+++ b/backend/internal/container/resource_stats.go
@@ -184,8 +184,8 @@ func (s *ContainerService) collectResourceSampleInternal(ctx context.Context, co
defer func() { _ = stats.Body.Close() }()
var statsData container.StatsResponse
- if err := json.UnmarshalDecode(jsontext.NewDecoder(stats.Body), &statsData); err != nil {
- return nil, fmt.Errorf("failed to decode container stats: %w", err)
+ if unmarshalDecodeErr := json.UnmarshalDecode(jsontext.NewDecoder(stats.Body), &statsData); unmarshalDecodeErr != nil {
+ return nil, fmt.Errorf("failed to decode container stats: %w", unmarshalDecodeErr)
}
built := containerstats.BuildSample(statsData)
diff --git a/backend/internal/container/resource_stats_test.go b/backend/internal/container/resource_stats_test.go
index 103bdebc4..44faea2cd 100644
--- a/backend/internal/container/resource_stats_test.go
+++ b/backend/internal/container/resource_stats_test.go
@@ -96,7 +96,16 @@ func (f *resourceStatsServerInternal) handler() http.Handler {
defer f.mu.Unlock()
for _, summary := range f.containers {
if summary.ID == id {
- inspect := container.InspectResponse{ID: summary.ID, Name: summary.Names[0], Image: summary.ImageID, Config: &container.Config{Image: summary.Image, Labels: summary.Labels}, State: &container.State{Status: summary.State}}
+ inspect := container.InspectResponse{
+ ID: summary.ID,
+ Name: summary.Names[0],
+ Image: summary.ImageID,
+ Config: &container.Config{
+ Image: summary.Image,
+ Labels: summary.Labels,
+ },
+ State: &container.State{Status: summary.State},
+ }
if err := json.NewEncoder(w).Encode(inspect); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
diff --git a/backend/internal/container/service.go b/backend/internal/container/service.go
index 7358d503e..f48df6274 100644
--- a/backend/internal/container/service.go
+++ b/backend/internal/container/service.go
@@ -75,7 +75,13 @@ type ContainerListResult struct {
Counts containertypes.StatusCounts
}
-func NewContainerService(eventService *event.EventService, dockerService *docker.DockerClientService, imageService *image.ImageService, settingsService *settings.SettingsService, projectService *project.ProjectService) *ContainerService {
+func NewContainerService(
+ eventService *event.EventService,
+ dockerService *docker.DockerClientService,
+ imageService *image.ImageService,
+ settingsService *settings.SettingsService,
+ projectService *project.ProjectService,
+) *ContainerService {
return &ContainerService{
eventService: eventService,
dockerService: dockerService,
@@ -145,9 +151,17 @@ func shouldStartRedeployedContainerInternal(containerInfo container.InspectRespo
return shouldStart
}
-func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerClient *client.Client, imageName, containerID, containerName, action string, credentials []containerregistry.Credential, user common.User) error {
- settings := s.settingsService.GetSettingsConfig()
- pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))
+func (
+ s *ContainerService,
+) pullRedeployImageInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ imageName, containerID, containerName, action string,
+ credentials []containerregistry.Credential,
+ user common.User,
+) error {
+ localSettings := s.settingsService.GetSettingsConfig()
+ pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(localSettings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))
defer pullCancel()
pullOptions, authErr := s.imageService.PullOptionsWithAuth(ctx, imageName, credentials)
@@ -207,7 +221,15 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker
return nil
}
-func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName string, wasRunning bool, user common.User) error {
+func (
+ s *ContainerService,
+) prepareContainerForRedeployInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerID, containerName, backupName string,
+ wasRunning bool,
+ user common.User,
+) error {
s.eventService.MarkDockerExpectation("container", containerID, containerName)
if containerName != "" {
if _, err := dockerClient.ContainerRename(ctx, containerID, client.ContainerRenameOptions{NewName: backupName}); err != nil {
@@ -245,7 +267,15 @@ func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Conte
return fmt.Errorf("failed to stop container: %w", err)
}
-func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName, failedStep string, wasRunning bool, user common.User) {
+func (
+ s *ContainerService,
+) restoreContainerAfterRedeployFailureInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerID, containerName, backupName, failedStep string,
+ wasRunning bool,
+ user common.User,
+) {
s.eventService.MarkDockerExpectation("container", containerID, containerName)
if wasRunning {
if _, startErr := dockerClient.ContainerStart(ctx, containerID, client.ContainerStartOptions{}); startErr != nil {
@@ -277,7 +307,15 @@ func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx cont
// failed replacement must be removed first so the original name is free again.
// A returned error means the original container is gone and could not be
// restored; the caller must surface it alongside the replacement failure.
-func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(ctx context.Context, dockerClient *client.Client, containerInfo container.InspectResponse, apiVersion string, user common.User) error {
+func (
+ s *ContainerService,
+) restoreAutoRemoveContainerAfterStartFailureInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerInfo container.InspectResponse,
+ apiVersion string,
+ user common.User,
+) error {
containerID := containerInfo.ID
containerName := strings.TrimPrefix(containerInfo.Name, "/")
@@ -302,12 +340,12 @@ func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(c
}
defer s.eventService.BeginDockerResourceSuppressionWindow("container", createResp.ID, containerName)()
- if _, err := dockerClient.ContainerStart(ctx, createResp.ID, client.ContainerStartOptions{}); err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, createResp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", containerStartErr, database.JSON{
"action": "redeploy",
"step": "restore_start_original",
})
- return fmt.Errorf("failed to restart original auto-remove container: %w", err)
+ return fmt.Errorf("failed to restart original auto-remove container: %w", containerStartErr)
}
slog.InfoContext(
@@ -324,7 +362,18 @@ func (s *ContainerService) restoreAutoRemoveContainerAfterStartFailureInternal(c
// auto-remove original the rollback rebuilds it from the inspected
// configuration; a failed restore is combined into the start error so the
// caller learns the workload is down, not just that the replacement failed.
-func (s *ContainerService) rollbackFailedReplacementStartInternal(ctx context.Context, dockerClient *client.Client, containerInfo container.InspectResponse, replacementID, action, backupName string, stopAfterCreate, wasRunning bool, apiVersion string, startErr error, user common.User) error {
+func (
+ s *ContainerService,
+) rollbackFailedReplacementStartInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerInfo container.InspectResponse,
+ replacementID, action, backupName string,
+ stopAfterCreate, wasRunning bool,
+ apiVersion string,
+ startErr error,
+ user common.User,
+) error {
containerName := strings.TrimPrefix(containerInfo.Name, "/")
s.eventService.MarkDockerExpectation("container", replacementID, containerName)
@@ -520,7 +569,18 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stri
// - handled=true, err!=nil: compose path was attempted and failed. The
// caller MUST surface the error and MUST NOT fall back to the standalone
// path, which would clobber whatever partial state ComposeUp left behind.
-func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Context, containerInfo container.InspectResponse, containerID, containerName string, user common.User) (string, bool, error) {
+func (
+ s *ContainerService,
+) tryRedeployViaComposeProjectInternal(
+ ctx context.Context,
+ containerInfo container.InspectResponse,
+ containerID, containerName string,
+ user common.User,
+) (
+ string,
+ bool,
+ error,
+) {
if s.projectService == nil || containerInfo.Config == nil {
return "", false, nil
}
@@ -564,8 +624,8 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont
"service", serviceName,
)
- if err := s.projectService.UpdateProjectServices(ctx, proj.ID, []string{serviceName}, user, false); err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{
+ if updateProjectServicesErr := s.projectService.UpdateProjectServices(ctx, proj.ID, []string{serviceName}, user, false); updateProjectServicesErr != nil {
+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", updateProjectServicesErr, database.JSON{
"action": "redeploy",
"step": "compose_update_services",
"project": projectName,
@@ -573,7 +633,7 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont
"projectId": proj.ID,
"projectName": proj.Name,
})
- return "", true, fmt.Errorf("compose redeploy failed for %s/%s: %w", projectName, serviceName, err)
+ return "", true, fmt.Errorf("compose redeploy failed for %s/%s: %w", projectName, serviceName, updateProjectServicesErr)
}
newID, lookupErr := projects.FindComposeServiceContainerID(ctx, s.dockerService.DockerHost(), projectName, serviceName)
@@ -657,21 +717,49 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st
}
if imageName != "" {
- if err := s.pullRedeployImageInternal(ctx, dockerClient, imageName, containerID, containerName, "redeploy", nil, user); err != nil {
- return "", err
+ if pullRedeployImageErr := s.pullRedeployImageInternal(ctx, dockerClient, imageName, containerID, containerName, "redeploy", nil, user); pullRedeployImageErr != nil {
+ return "", pullRedeployImageErr
}
}
networkingConfig := buildCleanNetworkingConfigInternal(containerInfo, apiVersion)
newConfig := *containerInfo.Config
- return s.recreateContainerInternal(ctx, dockerClient, containerInfo, "redeploy", containerName, &newConfig, containerInfo.HostConfig, networkingConfig, apiVersion, event.EventTypeContainerDeploy, user)
+ return s.recreateContainerInternal(
+ ctx,
+ dockerClient,
+ containerInfo,
+ "redeploy",
+ containerName,
+ &newConfig,
+ containerInfo.HostConfig,
+ networkingConfig,
+ apiVersion,
+ event.EventTypeContainerDeploy,
+ user,
+ )
}
// recreateContainerInternal replaces an existing container with one created
// from the supplied config, using rename-as-backup so the original can be
// restored when create or start fails. Shared by redeploy and edit.
-func (s *ContainerService) recreateContainerInternal(ctx context.Context, dockerClient *client.Client, containerInfo container.InspectResponse, action, newName string, newConfig *container.Config, newHostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, apiVersion string, eventType event.EventType, user common.User) (string, error) {
+func (
+ s *ContainerService,
+) recreateContainerInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerInfo container.InspectResponse,
+ action, newName string,
+ newConfig *container.Config,
+ newHostConfig *container.HostConfig,
+ networkingConfig *network.NetworkingConfig,
+ apiVersion string,
+ eventType event.EventType,
+ user common.User,
+) (
+ string,
+ error,
+) {
containerID := containerInfo.ID
containerName := strings.TrimPrefix(containerInfo.Name, "/")
wasRunning := containerInfo.State != nil && containerInfo.State.Running
@@ -714,7 +802,7 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker
defer s.eventService.BeginDockerResourceSuppressionWindow("container", createResp.ID, newName)()
if stopAfterCreate {
- if _, err := dockerClient.ContainerStop(ctx, containerID, client.ContainerStopOptions{Timeout: new(30)}); err != nil {
+ if _, containerStopErr := dockerClient.ContainerStop(ctx, containerID, client.ContainerStopOptions{Timeout: new(30)}); containerStopErr != nil {
if _, removeErr := dockerClient.ContainerRemove(ctx, createResp.ID, client.ContainerRemoveOptions{Force: true}); removeErr != nil {
s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", removeErr, database.JSON{
"action": action,
@@ -722,11 +810,11 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker
})
}
s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerID, containerName, backupName, "stop", false, user)
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{
+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", containerStopErr, database.JSON{
"action": action,
"step": "stop",
})
- return "", fmt.Errorf("failed to stop container: %w", err)
+ return "", fmt.Errorf("failed to stop container: %w", containerStopErr)
}
}
@@ -754,16 +842,16 @@ func (s *ContainerService) recreateContainerInternal(ctx context.Context, docker
// After a deferred stop the daemon has already auto-removed the original.
if !stopAfterCreate {
- if _, err := dockerClient.ContainerRemove(ctx, containerID, client.ContainerRemoveOptions{
+ if _, containerRemoveErr := dockerClient.ContainerRemove(ctx, containerID, client.ContainerRemoveOptions{
Force: true,
RemoveVolumes: false,
RemoveLinks: false,
- }); err != nil {
+ }); containerRemoveErr != nil {
slog.WarnContext(
ctx, "failed to remove old container after successful recreate",
"containerId", containerID,
"backupName", backupName,
- "error", err,
+ "error", containerRemoveErr,
)
}
}
@@ -848,9 +936,9 @@ func portMapFromCreateInternal(bindings map[string][]containertypes.PortBindingC
for _, binding := range bindingList {
pb := network.PortBinding{HostPort: binding.HostPort}
if hostIP := strings.TrimSpace(binding.HostIP); hostIP != "" {
- parsedIP, err := netip.ParseAddr(hostIP)
- if err != nil {
- return nil, fmt.Errorf("invalid host IP %s: %w", hostIP, err)
+ parsedIP, parseAddrErr := netip.ParseAddr(hostIP)
+ if parseAddrErr != nil {
+ return nil, fmt.Errorf("invalid host IP %s: %w", hostIP, parseAddrErr)
}
pb.HostIP = parsedIP
}
@@ -1100,8 +1188,8 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID string
containerName := strings.TrimPrefix(containerInfo.Name, "/")
- if project := dockerutils.ComposeProjectLabel(containerInfo.Config.Labels); project != "" {
- return "", fmt.Errorf("compose project %s: %w", project, common.ErrContainerComposeManaged)
+ if localProject := dockerutils.ComposeProjectLabel(containerInfo.Config.Labels); localProject != "" {
+ return "", fmt.Errorf("compose project %s: %w", localProject, common.ErrContainerComposeManaged)
}
currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
@@ -1134,11 +1222,11 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID string
newHostConfig = *containerInfo.HostConfig
}
- if err := applyEditToContainerConfigInternal(&newConfig, newHostConfig.PortBindings, req); err != nil {
- return "", common.Classify(common.ErrValidation, err)
+ if applyEditToContainerConfigErr := applyEditToContainerConfigInternal(&newConfig, newHostConfig.PortBindings, req); applyEditToContainerConfigErr != nil {
+ return "", common.Classify(common.ErrValidation, applyEditToContainerConfigErr)
}
- if err := applyEditToHostConfigInternal(&newHostConfig, req); err != nil {
- return "", common.Classify(common.ErrValidation, err)
+ if applyEditToHostConfigErr := applyEditToHostConfigInternal(&newHostConfig, req); applyEditToHostConfigErr != nil {
+ return "", common.Classify(common.ErrValidation, applyEditToHostConfigErr)
}
networkingConfig, err := buildEditNetworkingConfigInternal(containerInfo, req.NetworkingConfig, apiVersion)
if err != nil {
@@ -1150,8 +1238,8 @@ func (s *ContainerService) EditContainer(ctx context.Context, containerID string
imageName := newConfig.Image
if imageName != "" {
if _, inspectErr := dockerClient.ImageInspect(ctx, imageName); inspectErr != nil {
- if err := s.pullRedeployImageInternal(ctx, dockerClient, imageName, containerID, containerName, "edit", req.Credentials, user); err != nil {
- return "", err
+ if pullRedeployImageErr := s.pullRedeployImageInternal(ctx, dockerClient, imageName, containerID, containerName, "edit", req.Credentials, user); pullRedeployImageErr != nil {
+ return "", pullRedeployImageErr
}
}
}
@@ -1256,7 +1344,22 @@ func (s *ContainerService) GetContainerNameByID(ctx context.Context, id string)
func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force, removeVolumes bool, user common.User) error {
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ containerID,
+ "",
+ user.ID,
+ user.Username,
+ "0",
+ err,
+ database.JSON{
+ "action": "delete",
+ "force": force,
+ "removeVolumes": removeVolumes,
+ },
+ )
return fmt.Errorf("failed to connect to Docker: %w", err)
}
@@ -1275,8 +1378,14 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri
}
defer s.eventService.BeginDockerResourceSuppressionWindow("container", containerID, "")()
+ volumeReleases := make([]func(), 0, len(volumesToRemove))
+ defer func() {
+ for i := len(volumeReleases) - 1; i >= 0; i-- {
+ volumeReleases[i]()
+ }
+ }()
for _, volumeName := range volumesToRemove {
- defer s.eventService.BeginDockerResourceSuppressionWindow("volume", volumeName, volumeName)()
+ volumeReleases = append(volumeReleases, s.eventService.BeginDockerResourceSuppressionWindow("volume", volumeName, volumeName))
}
_, err = dockerClient.ContainerRemove(ctx, containerID, client.ContainerRemoveOptions{
Force: force,
@@ -1284,7 +1393,22 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri
RemoveLinks: false,
})
if err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ containerID,
+ "",
+ user.ID,
+ user.Username,
+ "0",
+ err,
+ database.JSON{
+ "action": "delete",
+ "force": force,
+ "removeVolumes": removeVolumes,
+ },
+ )
return fmt.Errorf("failed to delete container: %w", err)
}
@@ -1311,7 +1435,20 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID stri
return nil
}
-func (s *ContainerService) CreateContainer(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string, user common.User, credentials []containerregistry.Credential) (*container.InspectResponse, error) {
+func (
+ s *ContainerService,
+) CreateContainer(
+ ctx context.Context,
+ config *container.Config,
+ hostConfig *container.HostConfig,
+ networkingConfig *network.NetworkingConfig,
+ containerName string,
+ user common.User,
+ credentials []containerregistry.Credential,
+) (
+ *container.InspectResponse,
+ error,
+) {
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image})
@@ -1329,18 +1466,48 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe
pullOptions = client.ImagePullOptions{}
}
- settings := s.settingsService.GetSettingsConfig()
- pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))
+ localSettings := s.settingsService.GetSettingsConfig()
+ pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(localSettings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))
defer pullCancel()
defer s.eventService.BeginDockerResourceSuppressionWindow("image", "", config.Image)()
reader, pullErr := dockerClient.ImagePull(pullCtx, config.Image, pullOptions)
if pullErr != nil {
if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "create", "image": config.Image, "step": "pull_image_timeout"})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ "",
+ containerName,
+ user.ID,
+ user.Username,
+ "0",
+ pullErr,
+ database.JSON{
+ "action": "create",
+ "image": config.Image,
+ "step": "pull_image_timeout",
+ },
+ )
return nil, fmt.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", config.Image)
}
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "create", "image": config.Image, "step": "pull_image"})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ "",
+ containerName,
+ user.ID,
+ user.Username,
+ "0",
+ pullErr,
+ database.JSON{
+ "action": "create",
+ "image": config.Image,
+ "step": "pull_image",
+ },
+ )
return nil, fmt.Errorf("failed to pull image %s: %w", config.Image, pullErr)
}
defer func() { _ = reader.Close() }()
@@ -1350,7 +1517,22 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe
streamErr := dockerutils.RenderJSONMessageStream(reader, logWriter)
_ = logWriter.Close()
if streamErr != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "create", "image": config.Image, "step": "complete_pull"})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ "",
+ containerName,
+ user.ID,
+ user.Username,
+ "0",
+ streamErr,
+ database.JSON{
+ "action": "create",
+ "image": config.Image,
+ "step": "complete_pull",
+ },
+ )
return nil, fmt.Errorf("failed to complete image pull: %w", streamErr)
}
}
@@ -1363,7 +1545,22 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe
Name: containerName,
})
if err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "create"})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ "",
+ containerName,
+ user.ID,
+ user.Username,
+ "0",
+ err,
+ database.JSON{
+ "action": "create",
+ "image": config.Image,
+ "step": "create",
+ },
+ )
return nil, fmt.Errorf("failed to create container: %w", err)
}
@@ -1377,15 +1574,45 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containe
slog.WarnContext(ctx, "could not log container stop action", "error", logErr)
}
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "start"})
- return nil, fmt.Errorf("failed to start container: %w", err)
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ resp.ID,
+ containerName,
+ user.ID,
+ user.Username,
+ "0",
+ containerStartErr,
+ database.JSON{
+ "action": "create",
+ "image": config.Image,
+ "step": "start",
+ },
+ )
+ return nil, fmt.Errorf("failed to start container: %w", containerStartErr)
}
containerJSON, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, resp.ID, client.ContainerInspectOptions{})
if err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "inspect"})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeContainerError,
+ "container",
+ resp.ID,
+ containerName,
+ user.ID,
+ user.Username,
+ "0",
+ err,
+ database.JSON{
+ "action": "create",
+ "image": config.Image,
+ "step": "inspect",
+ },
+ )
return nil, fmt.Errorf("failed to inspect created container: %w", err)
}
@@ -1408,19 +1635,19 @@ func (s *ContainerService) StreamStats(ctx context.Context, containerID string,
historySent := false
for {
- if err := ctx.Err(); err != nil {
- return err
+ if cancellationErr := ctx.Err(); cancellationErr != nil {
+ return cancellationErr
}
var statsData container.StatsResponse
- if err := json.UnmarshalDecode(decoder, &statsData); err != nil {
+ if unmarshalDecodeErr := json.UnmarshalDecode(decoder, &statsData); unmarshalDecodeErr != nil {
if ctx.Err() != nil {
return ctx.Err()
}
- if errors.Is(err, io.EOF) {
+ if errors.Is(unmarshalDecodeErr, io.EOF) {
return nil
}
- return fmt.Errorf("failed to decode stats: %w", err)
+ return fmt.Errorf("failed to decode stats: %w", unmarshalDecodeErr)
}
recordedAt := statsData.Read
@@ -1598,12 +1825,12 @@ func flattenContainerProjectGroupsInternal(groups []containertypes.SummaryGroup)
return flattened
}
-func getContainerProjectNameInternal(container containertypes.Summary) string {
- if container.Labels == nil {
+func getContainerProjectNameInternal(localContainer containertypes.Summary) string {
+ if localContainer.Labels == nil {
return containerNoProjectGroup
}
- projectName := dockerutils.ComposeProjectLabel(container.Labels)
+ projectName := dockerutils.ComposeProjectLabel(localContainer.Labels)
return kit.Ternary(projectName == "", containerNoProjectGroup, projectName)
}
@@ -1639,7 +1866,15 @@ func (s *ContainerService) lookupContainerUpdateInfoInternal(ctx context.Context
return updates
}
-func (s *ContainerService) BuildSummaries(ctx context.Context, containers []container.Summary, updateInfoMap map[string]*imagetypes.UpdateInfo, currentContainerID string, currentContainerErr error) []containertypes.Summary {
+func (
+ s *ContainerService,
+) BuildSummaries(
+ ctx context.Context,
+ containers []container.Summary,
+ updateInfoMap map[string]*imagetypes.UpdateInfo,
+ currentContainerID string,
+ currentContainerErr error,
+) []containertypes.Summary {
items := make([]containertypes.Summary, 0, len(containers))
var excluded map[string]bool
if s.settingsService != nil {
@@ -1692,20 +1927,20 @@ func (s *ContainerService) applyContainerDetailsIconInternal(ctx context.Context
details.IconDarkURL = resolvedIcon.IconDarkURL
}
-func (s *ContainerService) resolveContainerIconInternal(ctx context.Context, labels map[string]string, metadataByProject map[string]projects.ArcaneComposeMetadata) iconcatalog.ResolvedIconSet {
- explicitIcon := projects.FindArcaneIconSet(labels)
+func (s *ContainerService) resolveContainerIconInternal(ctx context.Context, localLabels map[string]string, metadataByProject map[string]projects.ArcaneComposeMetadata) iconcatalog.ResolvedIconSet {
+ explicitIcon := projects.FindArcaneIconSet(localLabels)
if !explicitIcon.IsEmpty() {
return iconcatalog.Resolve(project.IconCatalogForContext(ctx), explicitIcon)
}
- projectName := dockerutils.ComposeProjectLabel(labels)
+ projectName := dockerutils.ComposeProjectLabel(localLabels)
if projectName == "" || s == nil || s.projectService == nil {
return iconcatalog.Resolve(project.IconCatalogForContext(ctx), explicitIcon)
}
meta := s.getCachedProjectIconMetadataInternal(ctx, projectName, metadataByProject)
- serviceName := dockerutils.ComposeServiceLabel(labels)
+ serviceName := dockerutils.ComposeServiceLabel(localLabels)
return iconcatalog.Resolve(project.IconCatalogForContext(ctx), cmp.Or(
explicitIcon,
meta.ServiceIconSets[serviceName],
diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.go
index 4a1b5713b..c57ee048f 100644
--- a/backend/internal/container/service_test.go
+++ b/backend/internal/container/service_test.go
@@ -292,7 +292,7 @@ func TestContainerServiceCommitContainerCallsDockerAPIInternal(t *testing.T) {
nil,
)
- out, err := svc.CommitContainer(context.Background(), "container-1", containertypes.CommitRequest{
+ out, err := svc.CommitContainer(t.Context(), "container-1", containertypes.CommitRequest{
Repository: "registry.example.com/team/app",
Tag: "snapshot",
Comment: "manual snapshot",
@@ -310,7 +310,7 @@ func TestContainerServiceCommitContainerCallsDockerAPIInternal(t *testing.T) {
}, gotRequest)
var evt event.Event
- require.NoError(t, db.WithContext(context.Background()).Where("type = ?", event.EventTypeImageCommit).First(&evt).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("type = ?", event.EventTypeImageCommit).First(&evt).Error)
require.Equal(t, "container-1", *evt.ResourceID)
}
@@ -339,7 +339,7 @@ func TestContainerServiceCommitContainerOmitsReferenceWhenRepositoryEmptyInterna
nil,
)
- out, err := svc.CommitContainer(context.Background(), "container-1", containertypes.CommitRequest{
+ out, err := svc.CommitContainer(t.Context(), "container-1", containertypes.CommitRequest{
Tag: "latest",
}, common.SystemUser)
require.NoError(t, err)
@@ -352,9 +352,9 @@ func TestContainerServiceCommitContainerOmitsReferenceWhenRepositoryEmptyInterna
}, gotRequest)
}
-func newGroupedContainerSummary(name, project string) containertypes.Summary {
+func newGroupedContainerSummary(name, localProject string) containertypes.Summary {
labels := map[string]string{}
- labels["com.docker.compose.project"] = cmp.Or(project, labels["com.docker.compose.project"])
+ labels["com.docker.compose.project"] = cmp.Or(localProject, labels["com.docker.compose.project"])
return containertypes.Summary{
ID: name,
@@ -400,7 +400,7 @@ func setupProjectTestDBInternal(t *testing.T) *database.DB {
return &database.DB{DB: db}
}
-var dockerAPIVersionPrefixInternal = regexp.MustCompile(`^/v[0-9]+\.[0-9]+`)
+var dockerAPIVersionPrefixInternal = regexp.MustCompile(`^/v\d+\.\d+`)
func TestApplyEditPreservesUnmanagedSettingsInternal(t *testing.T) {
cfg := container.Config{
@@ -582,12 +582,46 @@ func TestRecreateContainerDaemonCorrelationInternal(t *testing.T) {
t.Cleanup(server.Close)
dockerClient := newTestDockerClientInternal(t, server)
svc := NewContainerService(events, nil, nil, nil, nil)
- info := container.InspectResponse{ID: "old-id", Name: "/web", State: &container.State{Running: true}, Config: &container.Config{Image: "app:latest"}, HostConfig: &container.HostConfig{}}
- id, err := svc.recreateContainerInternal(t.Context(), dockerClient, info, "redeploy", "web", info.Config, info.HostConfig, nil, "1.41", event.EventTypeContainerDeploy, common.SystemUser)
+ info := container.InspectResponse{
+ ID: "old-id",
+ Name: "/web",
+ State: &container.State{Running: true},
+ Config: &container.Config{Image: "app:latest"},
+ HostConfig: &container.HostConfig{},
+ }
+ id, err := svc.recreateContainerInternal(
+ t.Context(),
+ dockerClient,
+ info,
+ "redeploy",
+ "web",
+ info.Config,
+ info.HostConfig,
+ nil,
+ "1.41",
+ event.EventTypeContainerDeploy,
+ common.SystemUser,
+ )
require.NoError(t, err)
require.Equal(t, "new-id", id)
require.Len(t, observed, 5)
- require.Equal(t, []string{"/containers/old-id/rename", "/containers/old-id/stop", "/containers/create", "/containers/new-id/start", "/containers/old-id"}, []string{<-observed, <-observed, <-observed, <-observed, <-observed})
+ require.Equal(
+ t,
+ []string{
+ "/containers/old-id/rename",
+ "/containers/old-id/stop",
+ "/containers/create",
+ "/containers/new-id/start",
+ "/containers/old-id",
+ },
+ []string{
+ <-observed,
+ <-observed,
+ <-observed,
+ <-observed,
+ <-observed,
+ },
+ )
require.True(t, events.ShouldSuppressDaemonEvent("container", "old-id", "", ""))
require.True(t, events.ShouldSuppressDaemonEvent("container", "new-id", "", ""))
}
@@ -643,11 +677,30 @@ func TestContainerServiceGetContainerProcessesInternal(t *testing.T) {
wantErr func(error) bool
}{
{
- name: "docker snapshot",
- status: http.StatusOK,
- body: `{"Titles":["PID","USER","%CPU","%MEM","ELAPSED","CMD"],"Processes":[["1","root","0.0","0.1","01:02:03","nginx: master process nginx -g daemon off;"],["29","nginx","0.0","0.1","01:02:03","nginx: worker process"]]}`,
+ name: "docker snapshot",
+ status: http.StatusOK,
+ body: "{\"Titles\":[\"PID\",\"USER\",\"%CPU\",\"%MEM\",\"ELAPSED\",\"CMD\"],\"Processes\":[[\"1\",\"root\",\"0.0\",\"0.1\",\"01:02:0" +
+ "3\",\"nginx: master process nginx -g daemon off;\"],[\"29\",\"nginx\",\"0.0\",\"0.1\",\"01:02:03\",\"nginx: worker" +
+ " process\"]]}",
wantTitles: []string{"PID", "USER", "%CPU", "%MEM", "ELAPSED", "CMD"},
- wantRows: [][]string{{"1", "root", "0.0", "0.1", "01:02:03", "nginx: master process nginx -g daemon off;"}, {"29", "nginx", "0.0", "0.1", "01:02:03", "nginx: worker process"}},
+ wantRows: [][]string{
+ {
+ "1",
+ "root",
+ "0.0",
+ "0.1",
+ "01:02:03",
+ "nginx: master process nginx -g daemon off;",
+ },
+ {
+ "29",
+ "nginx",
+ "0.0",
+ "0.1",
+ "01:02:03",
+ "nginx: worker process",
+ },
+ },
},
{name: "empty", status: http.StatusOK, body: `{}`, wantTitles: []string{}, wantRows: [][]string{}},
{name: "not found", status: http.StatusNotFound, body: `{"message":"No such container: container-1"}`, wantErr: errdefs.IsNotFound},
@@ -686,7 +739,7 @@ func TestContainerServiceGetContainerProcessesInternal(t *testing.T) {
t.Cleanup(server.Close)
svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClientInternal(t, server)), nil, nil, nil)
- processes, err := svc.GetContainerProcesses(context.Background(), "container-1")
+ processes, err := svc.GetContainerProcesses(t.Context(), "container-1")
wantArgs := []string{strings.Join(containerProcessesPsArgs[0], " ")}
if tt.fallback != nil {
wantArgs = append(wantArgs, strings.Join(containerProcessesPsArgs[1], " "))
@@ -712,7 +765,7 @@ func TestContainerServiceGetContainerProcessesPropagatesContextInternal(t *testi
t.Cleanup(server.Close)
svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClientInternal(t, server)), nil, nil, nil)
- ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
_, err := svc.GetContainerProcesses(ctx, "container-1")
require.ErrorIs(t, err, context.DeadlineExceeded)
diff --git a/backend/internal/dashboard/handler.go b/backend/internal/dashboard/handler.go
index 417de4929..cad9414a1 100644
--- a/backend/internal/dashboard/handler.go
+++ b/backend/internal/dashboard/handler.go
@@ -204,15 +204,15 @@ func (h *DashboardHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz
})
}
-func dashboardStreamEnvironmentVersionInternal(environment environment.Environment) string {
- if environment.UpdatedAt == nil {
- return environment.ID
+func dashboardStreamEnvironmentVersionInternal(localEnvironment environment.Environment) string {
+ if localEnvironment.UpdatedAt == nil {
+ return localEnvironment.ID
}
- return environment.ID + ":" + environment.UpdatedAt.UTC().Format(time.RFC3339Nano)
+ return localEnvironment.ID + ":" + localEnvironment.UpdatedAt.UTC().Format(time.RFC3339Nano)
}
-func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Context, environment environment.Environment, debugAllGood bool, publish func(dashboardtypes.StreamEvent)) {
- environmentID := environment.ID
+func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Context, localEnvironment environment.Environment, debugAllGood bool, publish func(dashboardtypes.StreamEvent)) {
+ environmentID := localEnvironment.ID
// Tell the client this environment is covered before the first poll
// completes so it can hold skeletons instead of assuming no data exists.
publish(dashboardtypes.StreamEvent{
@@ -227,7 +227,7 @@ func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Co
pollCtx, cancelPoll := context.WithTimeout(ctx, dashboardStreamRemotePollTimeout)
defer cancelPoll()
- currentEnvironment := environment
+ currentEnvironment := localEnvironment
if h.environmentService != nil {
var ok bool
currentEnvironment, ok = h.environmentService.GetActiveRemoteEnvironmentSnapshot(environmentID).Get()
@@ -290,7 +290,7 @@ func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Co
// endpoint directly through the environment service so the raw remenv error
// survives for classification (proxyRemoteJSONInternal would translate it
// into a huma error first).
-func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Context, environment environment.Environment, debugAllGood bool) (*dashboardtypes.Snapshot, error) {
+func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Context, localEnvironment environment.Environment, debugAllGood bool) (*dashboardtypes.Snapshot, error) {
// The all-environments dashboard only reads the aggregate counters, so the
// agent is asked to leave the container/image tables out of the payload.
query := url.Values{"includeTables": {"false"}}
@@ -300,7 +300,7 @@ func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Cont
path := "/api/environments/0/dashboard?" + query.Encode()
var out base.ApiResponse[dashboardtypes.Snapshot]
- if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, path, nil, &out); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, localEnvironment, http.MethodGet, path, nil, &out); err != nil {
return nil, err
}
if !out.Success {
@@ -314,7 +314,7 @@ func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Cont
// agents have exposed for far longer than the aggregate dashboard endpoint.
// Each piece is fetched independently so a partially compatible agent still
// yields partial data; only when every piece fails is an error returned.
-func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Context, environment environment.Environment) (*dashboardtypes.Snapshot, error) {
+func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Context, localEnvironment environment.Environment) (*dashboardtypes.Snapshot, error) {
snapshot := &dashboardtypes.Snapshot{
ActionItems: dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}},
}
@@ -323,7 +323,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont
attempted++
var containerCounts base.ApiResponse[containertypes.StatusCounts]
- if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, "/api/environments/0/containers/counts", nil, &containerCounts); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, localEnvironment, http.MethodGet, "/api/environments/0/containers/counts", nil, &containerCounts); err != nil {
errs = append(errs, err)
} else {
snapshot.Containers.Counts = containerCounts.Data
@@ -338,7 +338,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont
attempted++
var imageCounts base.ApiResponse[imagetypes.UsageCounts]
- if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, "/api/environments/0/images/counts", nil, &imageCounts); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, localEnvironment, http.MethodGet, "/api/environments/0/images/counts", nil, &imageCounts); err != nil {
errs = append(errs, err)
} else {
snapshot.ImageUsageCounts = imageCounts.Data
@@ -346,7 +346,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont
attempted++
var volumeCounts base.ApiResponse[volumetypes.UsageCounts]
- if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, "/api/environments/0/volumes/counts", nil, &volumeCounts); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, localEnvironment, http.MethodGet, "/api/environments/0/volumes/counts", nil, &volumeCounts); err != nil {
errs = append(errs, err)
} else {
snapshot.VolumeUsageCounts = &volumeCounts.Data
@@ -354,7 +354,7 @@ func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Cont
attempted++
var versionInfo versiontypes.Info
- if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, "/api/app-version", nil, &versionInfo); err != nil {
+ if err := h.environmentService.ProxyJSONRequestForEnvironment(ctx, localEnvironment, http.MethodGet, "/api/app-version", nil, &versionInfo); err != nil {
errs = append(errs, err)
} else {
snapshot.VersionInfo = &versionInfo
diff --git a/backend/internal/dashboard/service_test.go b/backend/internal/dashboard/service_test.go
index c5caa6dec..a4356dd46 100644
--- a/backend/internal/dashboard/service_test.go
+++ b/backend/internal/dashboard/service_test.go
@@ -48,7 +48,7 @@ func setupDashboardServiceTestDB(t *testing.T) (*database.DB, *settings.Settings
require.NoError(t, db.AutoMigrate(&apikey.ApiKey{}, &environment.Environment{}, &imageupdate.ImageUpdateRecord{}, &project.Project{}, &settings.SettingVariable{}))
databaseDB := &database.DB{DB: db}
- settingsSvc, err := newSettingsServiceForTestInternal(context.Background(), t, databaseDB)
+ settingsSvc, err := newSettingsServiceForTestInternal(t.Context(), t, databaseDB)
require.NoError(t, err)
return databaseDB, settingsSvc
@@ -56,12 +56,12 @@ func setupDashboardServiceTestDB(t *testing.T) (*database.DB, *settings.Settings
func createDashboardTestAPIKey(t *testing.T, db *database.DB, key apikey.ApiKey) {
t.Helper()
- require.NoError(t, db.WithContext(context.Background()).Create(&key).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(&key).Error)
}
func createDashboardTestImageUpdateRecord(t *testing.T, db *database.DB, record imageupdate.ImageUpdateRecord) {
t.Helper()
- require.NoError(t, db.WithContext(context.Background()).Create(&record).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(&record).Error)
}
func newDashboardTestDockerService(
@@ -184,12 +184,12 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, volumes)
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
- require.NoError(t, settingsSvc.SetStringSetting(context.Background(), "projectsDirectory", projectsDir))
- require.NoError(t, settingsSvc.SetStringSetting(context.Background(), "autoUpdateExcludedContainers", "stopped-app"))
+ require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "projectsDirectory", projectsDir))
+ require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "autoUpdateExcludedContainers", "stopped-app"))
projectPath := createComposeProjectDirInternal(t, projectsDir, "project-with-update")
require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: repo/worker:latest\n"), 0o644))
dirName := "project-with-update"
- require.NoError(t, db.WithContext(context.Background()).Create(&project.Project{
+ require.NoError(t, db.WithContext(t.Context()).Create(&project.Project{
ID: "project-with-update",
Name: "project-with-update",
DirName: &dirName,
@@ -200,7 +200,7 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
projectSvc := project.NewProjectService(db, settingsSvc, nil, imageSvc, nil, nil, nil, nil, config.Load(), nil, nil)
svc := NewDashboardService(db, dockerSvc, nil, projectSvc, imageSvc, settingsSvc, nil, nil, nil, volume.NewVolumeService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil))
- snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, true)
+ snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)
require.NoError(t, err)
require.NotNil(t, snapshot)
@@ -255,7 +255,7 @@ func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testi
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)
svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil)
- snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{DebugAllGood: true}, true)
+ snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{DebugAllGood: true}, true)
require.NoError(t, err)
require.NotNil(t, snapshot)
@@ -296,7 +296,7 @@ func TestDashboardService_GetSnapshot_EnrichesPinnedReferencesInternal(t *testin
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)
svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil)
- snapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, true)
+ snapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)
require.NoError(t, err)
require.NotNil(t, snapshot)
@@ -321,29 +321,13 @@ func createComposeProjectDirInternal(t *testing.T, root, name string) string {
return projectPath
}
-// createTestRemoteEnvironmentInternal inserts an enabled, online remote environment.
-func createTestRemoteEnvironmentInternal(t *testing.T, db *database.DB, environmentID, name, apiURL, token string) {
- t.Helper()
- now := time.Now()
- require.NoError(t, db.Create(&environment.Environment{
- ID: environmentID,
- CreatedAt: now,
- UpdatedAt: &now,
- Name: name,
- ApiUrl: apiURL,
- Status: string(environment.EnvironmentStatusOnline),
- Enabled: true,
- AccessToken: &token,
- }).Error)
-}
-
// newSettingsServiceForTestInternal builds a SettingsService backed by its own actor runtime,
// stopped when the test ends.
func newSettingsServiceForTestInternal(ctx context.Context, t testing.TB, db *database.DB) (*settings.SettingsService, error) {
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -352,8 +336,26 @@ func TestDashboardService_GetSnapshot_TrimmedOmitsTablesAndSharesBuilds(t *testi
db, settingsSvc := setupDashboardServiceTestDB(t)
containers := []dockercontainer.Summary{
- {ID: "container-running", Names: []string{"/running-app"}, Image: "repo/app:stable", ImageID: "sha256:image-a", Created: 1700000000, State: "running", Status: "Up 2 hours", Labels: map[string]string{}},
- {ID: "container-stopped", Names: []string{"/stopped-app"}, Image: "repo/worker:latest", ImageID: "sha256:image-b", Created: 1800000000, State: "exited", Status: "Exited (0) 1 hour ago", Labels: map[string]string{}},
+ {
+ ID: "container-running",
+ Names: []string{"/running-app"},
+ Image: "repo/app:stable",
+ ImageID: "sha256:image-a",
+ Created: 1700000000,
+ State: "running",
+ Status: "Up 2 hours",
+ Labels: map[string]string{},
+ },
+ {
+ ID: "container-stopped",
+ Names: []string{"/stopped-app"},
+ Image: "repo/worker:latest",
+ ImageID: "sha256:image-b",
+ Created: 1800000000,
+ State: "exited",
+ Status: "Exited (0) 1 hour ago",
+ Labels: map[string]string{},
+ },
}
images := []dockerimage.Summary{
{ID: "sha256:image-a", RepoTags: []string{"repo/app:stable"}, Created: 1710000000, Size: 100},
@@ -363,7 +365,7 @@ func TestDashboardService_GetSnapshot_TrimmedOmitsTablesAndSharesBuilds(t *testi
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)
svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil)
- trimmed, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, false)
+ trimmed, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, false)
require.NoError(t, err)
require.NotNil(t, trimmed)
@@ -378,12 +380,12 @@ func TestDashboardService_GetSnapshot_TrimmedOmitsTablesAndSharesBuilds(t *testi
require.Equal(t, 2, trimmed.ImageUsageCounts.Total)
// Within the TTL every subscriber shares the same build.
- again, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, false)
+ again, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, false)
require.NoError(t, err)
require.Same(t, trimmed, again)
// The full variant is cached separately and still carries the tables.
- full, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, true)
+ full, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)
require.NoError(t, err)
require.NotNil(t, full)
require.Len(t, full.Containers.Data, 2)
@@ -394,18 +396,27 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testi
db, settingsSvc := setupDashboardServiceTestDB(t)
containers := []dockercontainer.Summary{
- {ID: "container-running", Names: []string{"/running-app"}, Image: "repo/app:stable", ImageID: "sha256:image-a", Created: 1700000000, State: "running", Status: "Up 2 hours", Labels: map[string]string{"arcane.icon": "myapp"}},
+ {
+ ID: "container-running",
+ Names: []string{"/running-app"},
+ Image: "repo/app:stable",
+ ImageID: "sha256:image-a",
+ Created: 1700000000,
+ State: "running",
+ Status: "Up 2 hours",
+ Labels: map[string]string{"arcane.icon": "myapp"},
+ },
}
images := []dockerimage.Summary{
{ID: "sha256:image-a", RepoTags: []string{"repo/app:stable"}, Created: 1710000000, Size: 100},
}
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)
- require.NoError(t, settingsSvc.SetStringSetting(context.Background(), "autoUpdateExcludedContainers", "running-app"))
+ require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "autoUpdateExcludedContainers", "running-app"))
containerSvc := container.NewContainerService(nil, dockerSvc, nil, settingsSvc, nil)
svc := NewDashboardService(db, dockerSvc, containerSvc, nil, nil, settingsSvc, nil, nil, nil, nil)
- defaultSnapshot, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, true)
+ defaultSnapshot, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)
require.NoError(t, err)
require.Len(t, defaultSnapshot.Containers.Data, 1)
require.Contains(t, defaultSnapshot.Containers.Data[0].IconLightURL, "selfhst")
@@ -414,7 +425,7 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testi
// A user preferring another catalog must not be served the default-catalog
// snapshot from the cache.
dashboardIconsUser := &common.User{Preferences: usertypes.Preferences{IconCatalog: new("dashboard-icons")}}
- userCtx := context.WithValue(context.Background(), common.CurrentUserContextKey{}, dashboardIconsUser)
+ userCtx := context.WithValue(t.Context(), common.CurrentUserContextKey{}, dashboardIconsUser)
userSnapshot, err := svc.GetSnapshot(userCtx, DashboardActionItemsOptions{}, true)
require.NoError(t, err)
require.NotSame(t, defaultSnapshot, userSnapshot)
@@ -422,7 +433,7 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testi
require.Contains(t, userSnapshot.Containers.Data[0].IconLightURL, "dashboard-icons")
// Both catalog variants stay cached side by side within the TTL.
- defaultAgain, err := svc.GetSnapshot(context.Background(), DashboardActionItemsOptions{}, true)
+ defaultAgain, err := svc.GetSnapshot(t.Context(), DashboardActionItemsOptions{}, true)
require.NoError(t, err)
require.Same(t, defaultSnapshot, defaultAgain)
userAgain, err := svc.GetSnapshot(userCtx, DashboardActionItemsOptions{}, true)
@@ -437,7 +448,17 @@ func TestPendingContainerCountUsesScopedTagRecords(t *testing.T) {
// A digest record recorded under another local tag of the shared image.
{ID: "shared", Repository: "docker.io/library/app", Tag: "stable", HasUpdate: true, UpdateType: "digest"},
{ID: "container::first", PolicyKey: imageref.UpdatePolicyKey("app:1.2.3", tagLabels), ContainerID: "first", ImageID: "shared", HasUpdate: true, UpdateType: "tag"},
- {ID: "container::other-project", PolicyKey: imageref.UpdatePolicyKey("app:1.2.3", tagLabels), ContainerID: "other-project", ImageID: "shared", HasUpdate: true, UpdateType: "tag"},
+ {
+ ID: "container::other-project",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "app:1.2.3",
+ tagLabels,
+ ),
+ ContainerID: "other-project",
+ ImageID: "shared",
+ HasUpdate: true,
+ UpdateType: "tag",
+ },
}
require.NoError(t, db.Create(&records).Error)
service := &DashboardService{db: db, imageService: image.NewImageService(db, nil, nil, nil, nil, nil)}
diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go
index 2d3074e74..9d83409ad 100644
--- a/backend/internal/database/database.go
+++ b/backend/internal/database/database.go
@@ -76,8 +76,8 @@ func Initialize(ctx context.Context, databaseURL string, options MigrationOption
}
}()
- if err := ctx.Err(); err != nil {
- return nil, err
+ if cancellationErr := ctx.Err(); cancellationErr != nil {
+ return nil, cancellationErr
}
// Get underlying sql.DB for migrations
@@ -96,9 +96,9 @@ func Initialize(ctx context.Context, databaseURL string, options MigrationOption
return nil, fmt.Errorf("unsupported database type in URL: %s", databaseURL)
}
- if err := migrateDatabaseInternal(ctx, sqlDB, dbProvider, options); err != nil {
- slog.Error("Failed to run migrations", "error", err)
- return nil, fmt.Errorf("failed to run migrations: %w", err)
+ if migrateDatabaseErr := migrateDatabaseInternal(ctx, sqlDB, dbProvider, options); migrateDatabaseErr != nil {
+ slog.Error("Failed to run migrations", "error", migrateDatabaseErr)
+ return nil, fmt.Errorf("failed to run migrations: %w", migrateDatabaseErr)
}
// Set connection pool settings
@@ -127,8 +127,8 @@ func connectDatabaseInternal(ctx context.Context, databaseURL string) (*DB, erro
if err != nil {
return nil, fmt.Errorf("failed to parse SQLite connection string: %w", err)
}
- if err := ensureSQLiteDirectoryInternal(connString); err != nil {
- return nil, fmt.Errorf("failed to prepare SQLite directory: %w", err)
+ if ensureSQLiteDirectoryErr := ensureSQLiteDirectoryInternal(connString); ensureSQLiteDirectoryErr != nil {
+ return nil, fmt.Errorf("failed to prepare SQLite directory: %w", ensureSQLiteDirectoryErr)
}
dialector = sqlite.Open(connString)
case strings.HasPrefix(databaseURL, "postgres"):
@@ -141,8 +141,8 @@ func connectDatabaseInternal(ctx context.Context, databaseURL string) (*DB, erro
var db *gorm.DB
var err error
for i := 1; i <= 3; i++ {
- if err := ctx.Err(); err != nil {
- return nil, err
+ if retryCancellationErr := ctx.Err(); retryCancellationErr != nil {
+ return nil, retryCancellationErr
}
db, err = gorm.Open(dialector, &gorm.Config{
Logger: customGormLogger,
@@ -199,19 +199,33 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvide
if currentVersion > requiredVersion {
if !options.AllowDowngrade {
- return fmt.Errorf("database schema version %d is newer than this Arcane binary supports (target %d for %s); downgrade requires ALLOW_DOWNGRADE=true and a database backup before startup", currentVersion, requiredVersion, dbProvider)
+ return fmt.Errorf(
+ "database schema version %d is newer than this Arcane binary supports (target %d for %s); downgrade "+
+ "requires ALLOW_DOWNGRADE=true and a database backup before startup",
+ currentVersion,
+ requiredVersion,
+ dbProvider,
+ )
}
- missingVersions, err := missingEmbeddedDowngradeMigrationsInternal(ctx, db, dbProvider, requiredVersion)
- if err != nil {
- return err
+ missingVersions, missingEmbeddedDowngradeMigrationsErr := missingEmbeddedDowngradeMigrationsInternal(ctx, db, dbProvider, requiredVersion)
+ if missingEmbeddedDowngradeMigrationsErr != nil {
+ return missingEmbeddedDowngradeMigrationsErr
}
if len(missingVersions) > 0 {
- return fmt.Errorf("cannot downgrade database from version %d to %d for %s: embedded Goose migrations are missing for applied version(s) %v, so the rollback SQL is unavailable in this Arcane binary; ALLOW_DOWNGRADE=true is not sufficient, restore the database from a backup taken before the newer schema was applied", currentVersion, requiredVersion, dbProvider, missingVersions)
+ return fmt.Errorf("cannot downgrade database from version %d to %d for %s: embedded Goose migrations are missing for "+
+ "applied version(s) %v, so the rollback SQL is unavailable in this Arcane binary; "+
+ "ALLOW_DOWNGRADE=true is not sufficient, restore the database from a backup taken before the newer "+
+ "schema was applied",
+ currentVersion,
+ requiredVersion,
+ dbProvider,
+ missingVersions,
+ )
}
- if _, err := provider.DownTo(ctx, requiredVersion); err != nil {
- return fmt.Errorf("failed to downgrade database from version %d to %d for %s using embedded Goose migrations: %w", currentVersion, requiredVersion, dbProvider, err)
+ if _, downToErr := provider.DownTo(ctx, requiredVersion); downToErr != nil {
+ return fmt.Errorf("failed to downgrade database from version %d to %d for %s using embedded Goose migrations: %w", currentVersion, requiredVersion, dbProvider, downToErr)
}
slog.Info("Database downgrade completed successfully", "provider", dbProvider, "fromVersion", currentVersion, "toVersion", requiredVersion)
@@ -223,8 +237,8 @@ func migrateDatabaseToVersionInternal(ctx context.Context, db *sql.DB, dbProvide
return nil
}
- if _, err := provider.UpTo(ctx, requiredVersion); err != nil {
- return fmt.Errorf("failed to apply embedded Goose migrations for %s: %w", dbProvider, err)
+ if _, upToErr := provider.UpTo(ctx, requiredVersion); upToErr != nil {
+ return fmt.Errorf("failed to apply embedded Goose migrations for %s: %w", dbProvider, upToErr)
}
slog.Info("Database migrations completed successfully", "provider", dbProvider, "targetVersion", requiredVersion)
@@ -248,9 +262,9 @@ func newGooseProviderInternal(db *sql.DB, dbProvider string) (*goose.Provider, e
// equivalent because it is single-writer by construction.
var options []goose.ProviderOption
if dialect == goose.DialectPostgres {
- sessionLocker, err := lock.NewPostgresSessionLocker()
- if err != nil {
- return nil, fmt.Errorf("failed to create Postgres migration session locker: %w", err)
+ sessionLocker, newPostgresSessionLockerErr := lock.NewPostgresSessionLocker()
+ if newPostgresSessionLockerErr != nil {
+ return nil, fmt.Errorf("failed to create Postgres migration session locker: %w", newPostgresSessionLockerErr)
}
options = append(options, goose.WithSessionLocker(sessionLocker))
}
@@ -289,11 +303,16 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvid
if legacyState.dirty {
if !options.AllowDowngrade {
- return fmt.Errorf("database schema version %d is dirty in legacy %s table; resolve it manually or set ALLOW_DOWNGRADE=true after verifying the database state", legacyState.version, legacyVersionTable)
+ return fmt.Errorf(
+ "database schema version %d is dirty in legacy %s table; resolve it manually or set "+
+ "ALLOW_DOWNGRADE=true after verifying the database state",
+ legacyState.version,
+ legacyVersionTable,
+ )
}
- if err := clearLegacyMigrationDirtyInternal(ctx, db, dbProvider, legacyState.version); err != nil {
- return err
+ if clearLegacyMigrationDirtyErr := clearLegacyMigrationDirtyInternal(ctx, db, dbProvider, legacyState.version); clearLegacyMigrationDirtyErr != nil {
+ return clearLegacyMigrationDirtyErr
}
slog.Warn("Cleared dirty legacy migration state because ALLOW_DOWNGRADE=true", "provider", dbProvider, "version", legacyState.version)
}
@@ -319,37 +338,37 @@ func adoptLegacyMigrationStateInternal(ctx context.Context, db *sql.DB, dbProvid
_ = tx.Rollback()
}()
- if err := createGooseVersionTableInternal(ctx, tx, dbProvider); err != nil {
- return err
+ if createGooseVersionTableErr := createGooseVersionTableInternal(ctx, tx, dbProvider); createGooseVersionTableErr != nil {
+ return createGooseVersionTableErr
}
- if err := clearGooseVersionTableInternal(ctx, tx, dbProvider); err != nil {
- return err
+ if clearGooseVersionTableErr := clearGooseVersionTableInternal(ctx, tx, dbProvider); clearGooseVersionTableErr != nil {
+ return clearGooseVersionTableErr
}
- if err := insertGooseMigrationVersionInternal(ctx, tx, dbProvider, 0); err != nil {
- return err
+ if insertGooseMigrationVersionErr := insertGooseMigrationVersionInternal(ctx, tx, dbProvider, 0); insertGooseMigrationVersionErr != nil {
+ return insertGooseMigrationVersionErr
}
versionApplied := legacyState.version == 0
for _, version := range versions {
if version > legacyState.version {
break
}
- if err := insertGooseMigrationVersionInternal(ctx, tx, dbProvider, version); err != nil {
- return err
+ if insertMigrationVersionErr := insertGooseMigrationVersionInternal(ctx, tx, dbProvider, version); insertMigrationVersionErr != nil {
+ return insertMigrationVersionErr
}
if version == legacyState.version {
versionApplied = true
}
}
if !versionApplied {
- if err := insertGooseMigrationVersionInternal(ctx, tx, dbProvider, legacyState.version); err != nil {
- return err
+ if insertLegacyVersionErr := insertGooseMigrationVersionInternal(ctx, tx, dbProvider, legacyState.version); insertLegacyVersionErr != nil {
+ return insertLegacyVersionErr
}
}
- if err := tx.Commit(); err != nil {
- return fmt.Errorf("failed to commit legacy migration adoption for %s: %w", dbProvider, err)
+ if commitErr := tx.Commit(); commitErr != nil {
+ return fmt.Errorf("failed to commit legacy migration adoption for %s: %w", dbProvider, commitErr)
}
slog.Info("Adopted legacy migration state into Goose", "provider", dbProvider, "legacyVersion", legacyState.version)
@@ -407,8 +426,8 @@ func clearLegacyMigrationDirtyInternal(ctx context.Context, db *sql.DB, dbProvid
if err != nil {
return err
}
- if _, err := db.ExecContext(ctx, query, args...); err != nil {
- return fmt.Errorf("failed to clear legacy dirty migration state for %s version %d: %w", dbProvider, version, err)
+ if _, execContextErr := db.ExecContext(ctx, query, args...); execContextErr != nil {
+ return fmt.Errorf("failed to clear legacy dirty migration state for %s version %d: %w", dbProvider, version, execContextErr)
}
return nil
}
@@ -421,8 +440,8 @@ func gooseVersionTableHasAppliedMigrationsInternal(ctx context.Context, db *sql.
var version int64
applied := kit.Ternary(dbProvider == dbProviderPostgres, "true", "1")
- if err := db.QueryRowContext(ctx, fmt.Sprintf("SELECT COALESCE(MAX(version_id), 0) FROM %s WHERE is_applied = %s", gooseVersionTable, applied)).Scan(&version); err != nil {
- return false, fmt.Errorf("failed to read Goose migration state for %s: %w", dbProvider, err)
+ if scanErr := db.QueryRowContext(ctx, fmt.Sprintf("SELECT COALESCE(MAX(version_id), 0) FROM %s WHERE is_applied = %s", gooseVersionTable, applied)).Scan(&version); scanErr != nil {
+ return false, fmt.Errorf("failed to read Goose migration state for %s: %w", dbProvider, scanErr)
}
return version > 0, nil
}
@@ -591,15 +610,15 @@ func missingEmbeddedDowngradeMigrationsInternal(ctx context.Context, db *sql.DB,
var missing []int64
for rows.Next() {
var version int64
- if err := rows.Scan(&version); err != nil {
- return nil, fmt.Errorf("failed to scan applied migration version for %s: %w", dbProvider, err)
+ if scanErr := rows.Scan(&version); scanErr != nil {
+ return nil, fmt.Errorf("failed to scan applied migration version for %s: %w", dbProvider, scanErr)
}
if _, ok := embeddedSet[version]; !ok {
missing = append(missing, version)
}
}
- if err := rows.Err(); err != nil {
- return nil, fmt.Errorf("failed to iterate applied migration versions for %s: %w", dbProvider, err)
+ if iterateVersionsErr := rows.Err(); iterateVersionsErr != nil {
+ return nil, fmt.Errorf("failed to iterate applied migration versions for %s: %w", dbProvider, iterateVersionsErr)
}
return missing, nil
diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.go
index 7a66e95d3..131bd33d3 100644
--- a/backend/internal/database/database_test.go
+++ b/backend/internal/database/database_test.go
@@ -1,7 +1,6 @@
package database
import (
- "context"
stdsql "database/sql"
"fmt"
"io/fs"
@@ -45,7 +44,7 @@ func TestEnsureSQLiteDirectoryPreservesAbsoluteFilePath(t *testing.T) {
}
func TestMigrateDatabase_BlocksDowngradeWithoutFlag(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-test.db")
require.NoError(t, migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}))
targetVersion := downgradeTargetVersionInternal(t)
@@ -61,7 +60,7 @@ func TestMigrateDatabase_BlocksDowngradeWithoutFlag(t *testing.T) {
}
func TestMigrateDatabase_DowngradesWhenAllowed(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-test.db")
require.NoError(t, migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}))
targetVersion := downgradeTargetVersionInternal(t)
@@ -71,7 +70,7 @@ func TestMigrateDatabase_DowngradesWhenAllowed(t *testing.T) {
}
func TestMigration065_ProjectBuildImageRefs_UpAndDown(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-project-build-refs.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 64))
@@ -81,7 +80,14 @@ func TestMigration065_ProjectBuildImageRefs_UpAndDown(t *testing.T) {
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 65))
var notNull int
- require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*), COALESCE(MAX("notnull"), 0) FROM pragma_table_info('projects') WHERE name = 'build_image_refs_json'`).Scan(&columnCount, &notNull))
+ require.NoError(
+ t,
+ rawDB.QueryRow("SELECT COUNT(*), COALESCE(MAX(\"notnull\"), 0) FROM pragma_table_info('projects') WHERE name = 'build_"+
+ "image_refs_json'").Scan(
+ &columnCount,
+ &notNull,
+ ),
+ )
assert.Equal(t, 1, columnCount)
assert.Zero(t, notNull)
@@ -91,7 +97,7 @@ func TestMigration065_ProjectBuildImageRefs_UpAndDown(t *testing.T) {
}
func TestMigration066_GlobalVariables_UpAndDown(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-global-variables.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 65))
@@ -105,7 +111,8 @@ func TestMigration066_GlobalVariables_UpAndDown(t *testing.T) {
_, err := rawDB.Exec(`INSERT INTO environments (id, api_url, status, enabled) VALUES ('env-1', 'http://localhost', 'online', TRUE)`)
require.NoError(t, err)
- _, err = rawDB.Exec(`INSERT INTO global_variables (id, created_at, key, value, is_secret, all_environments) VALUES ('var-1', CURRENT_TIMESTAMP, 'API_URL', 'https://example.test', FALSE, FALSE)`)
+ _, err = rawDB.Exec("INSERT INTO global_variables (id, created_at, key, value, is_secret, all_environments) VALUES ('var-" +
+ "1', CURRENT_TIMESTAMP, 'API_URL', 'https://example.test', FALSE, FALSE)")
require.NoError(t, err)
_, err = rawDB.Exec(`INSERT INTO global_variable_environments (global_variable_id, environment_id) VALUES ('var-1', 'env-1')`)
require.NoError(t, err)
@@ -121,7 +128,7 @@ func TestMigration066_GlobalVariables_UpAndDown(t *testing.T) {
}
func TestMigration088_VulnerabilityRisk_BackfillsCVSSAndDowngrades(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-vulnerability-risk.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 87))
@@ -150,16 +157,24 @@ func TestMigration088_VulnerabilityRisk_BackfillsCVSSAndDowngrades(t *testing.T)
assert.False(t, scores["CVE-NONE"].Valid)
var tableCount int
- require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('vulnerability_threat_intel', 'vulnerability_risk_snapshots')`).Scan(&tableCount))
+ require.NoError(
+ t,
+ rawDB.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('vulnerability_threat_intel', '"+
+ "vulnerability_risk_snapshots')").Scan(&tableCount),
+ )
assert.Equal(t, 2, tableCount)
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}, 87))
- require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('vulnerability_threat_intel', 'vulnerability_risk_snapshots')`).Scan(&tableCount))
+ require.NoError(
+ t,
+ rawDB.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('vulnerability_threat_intel', '"+
+ "vulnerability_risk_snapshots')").Scan(&tableCount),
+ )
assert.Zero(t, tableCount)
}
func TestMigration067_ActivityBatchID_UpAndDown(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-activity-batch-id.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 66))
@@ -185,7 +200,7 @@ func TestMigration067_ActivityBatchID_UpAndDown(t *testing.T) {
}
func TestMigration068_UserPreferences_UpAndDown(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-user-preferences.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 67))
@@ -207,7 +222,15 @@ func TestMigration068_UserPreferences_UpAndDown(t *testing.T) {
var theme string
var oled bool
var iconCatalog stdsql.NullString
- require.NoError(t, rawDB.QueryRow(`SELECT json_extract(preferences, '$.applicationTheme'), json_extract(preferences, '$.oledMode'), json_extract(preferences, '$.iconCatalog') FROM users WHERE id = 'u-1'`).Scan(&theme, &oled, &iconCatalog))
+ require.NoError(
+ t,
+ rawDB.QueryRow("SELECT json_extract(preferences, '$.applicationTheme'), json_extract(preferences, '$.oledMode'), jso"+
+ "n_extract(preferences, '$.iconCatalog') FROM users WHERE id = 'u-1'").Scan(
+ &theme,
+ &oled,
+ &iconCatalog,
+ ),
+ )
assert.Equal(t, "nord", theme)
assert.True(t, oled)
assert.False(t, iconCatalog.Valid)
@@ -218,12 +241,16 @@ func TestMigration068_UserPreferences_UpAndDown(t *testing.T) {
}
func TestMigration070_PasskeysAndMFA_UpAndDown(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-passkeys-mfa.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 69))
var tableCount int
- require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('passkeys', 'auth_transactions', 'passkey_ceremonies', 'passkey_recovery_codes')`).Scan(&tableCount))
+ require.NoError(
+ t,
+ rawDB.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('passkeys', 'auth_transactions'"+
+ ", 'passkey_ceremonies', 'passkey_recovery_codes')").Scan(&tableCount),
+ )
assert.Zero(t, tableCount)
var columnCount int
@@ -231,7 +258,11 @@ func TestMigration070_PasskeysAndMFA_UpAndDown(t *testing.T) {
assert.Zero(t, columnCount)
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 70))
- require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('passkeys', 'auth_transactions', 'passkey_ceremonies', 'passkey_recovery_codes')`).Scan(&tableCount))
+ require.NoError(
+ t,
+ rawDB.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('passkeys', 'auth_transactions'"+
+ ", 'passkey_ceremonies', 'passkey_recovery_codes')").Scan(&tableCount),
+ )
assert.Equal(t, 4, tableCount)
require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'passkey_mfa_enabled'`).Scan(&columnCount))
assert.Equal(t, 1, columnCount)
@@ -239,7 +270,11 @@ func TestMigration070_PasskeysAndMFA_UpAndDown(t *testing.T) {
assert.Equal(t, 2, columnCount)
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}, 69))
- require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('passkeys', 'auth_transactions', 'passkey_ceremonies', 'passkey_recovery_codes')`).Scan(&tableCount))
+ require.NoError(
+ t,
+ rawDB.QueryRow("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('passkeys', 'auth_transactions'"+
+ ", 'passkey_ceremonies', 'passkey_recovery_codes')").Scan(&tableCount),
+ )
assert.Zero(t, tableCount)
require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'passkey_mfa_enabled'`).Scan(&columnCount))
assert.Zero(t, columnCount)
@@ -251,7 +286,7 @@ func TestMigration070_PasskeysAndMFA_UpAndDown(t *testing.T) {
// pre-existing volume backup rows survive the backup-support migration as
// format=archive, and that downgrading is refused while Rustic rows exist.
func TestMigration073_BackupSupport_PreservesExistingBackups(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-backup-support.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 72))
@@ -268,7 +303,11 @@ func TestMigration073_BackupSupport_PreservesExistingBackups(t *testing.T) {
assert.EqualValues(t, 42, size)
// Downgrade is refused while a Rustic-format row exists.
- _, err = rawDB.ExecContext(ctx, `INSERT INTO volume_backups (id, volume_name, size, created_at, format, local_snapshot_id) VALUES ('rustic-1', 'app-data', 7, CURRENT_TIMESTAMP, 'rustic', 'snap-1')`)
+ _, err = rawDB.ExecContext(
+ ctx,
+ "INSERT INTO volume_backups (id, volume_name, size, created_at, format, local_snapshot_id) VALUES ('r"+
+ "ustic-1', 'app-data', 7, CURRENT_TIMESTAMP, 'rustic', 'snap-1')",
+ )
require.NoError(t, err)
err = migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}, 72)
require.Error(t, err)
@@ -283,7 +322,7 @@ func TestMigration073_BackupSupport_PreservesExistingBackups(t *testing.T) {
}
func TestMigration072_ProjectTags_UpDownAndCascade(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-project-tags.db")
rawDB.SetMaxOpenConns(1)
@@ -301,7 +340,8 @@ func TestMigration072_ProjectTags_UpDownAndCascade(t *testing.T) {
_, err := rawDB.Exec(`PRAGMA foreign_keys=ON`)
require.NoError(t, err)
- _, err = rawDB.Exec(`INSERT INTO projects (id, name, path, status, service_count, running_count, created_at) VALUES ('project-1', 'demo', '/tmp/demo', 'stopped', 0, 0, CURRENT_TIMESTAMP)`)
+ _, err = rawDB.Exec("INSERT INTO projects (id, name, path, status, service_count, running_count, created_at) VALUES ('pro" +
+ "ject-1', 'demo', '/tmp/demo', 'stopped', 0, 0, CURRENT_TIMESTAMP)")
require.NoError(t, err)
_, err = rawDB.Exec(`INSERT INTO project_tags (project_id, name, source) VALUES ('project-1', 'database', 'ui'), ('project-1', 'database', 'compose')`)
require.NoError(t, err)
@@ -321,7 +361,7 @@ func TestMigration072_ProjectTags_UpDownAndCascade(t *testing.T) {
}
func TestMigration071_RenamesVolumeWorkspaceLegacyKeys(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-volume-workspace-keys.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 70))
@@ -333,7 +373,8 @@ func TestMigration071_RenamesVolumeWorkspaceLegacyKeys(t *testing.T) {
require.NoError(t, err)
_, err = rawDB.Exec(`INSERT INTO api_keys (id, name, key_hash, key_prefix) VALUES ('key-workspace', 'Workspace key', 'hash', 'arc_')`)
require.NoError(t, err)
- _, err = rawDB.Exec(`INSERT INTO api_key_permissions (id, api_key_id, permission) VALUES ('grant-browse', 'key-workspace', 'volumes:browse'), ('grant-read', 'key-workspace', 'volumes:read')`)
+ _, err = rawDB.Exec("INSERT INTO api_key_permissions (id, api_key_id, permission) VALUES ('grant-browse', 'key-workspace'" +
+ ", 'volumes:browse'), ('grant-read', 'key-workspace', 'volumes:read')")
require.NoError(t, err)
require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 71))
@@ -358,7 +399,7 @@ func TestMigration071_RenamesVolumeWorkspaceLegacyKeys(t *testing.T) {
}
func TestMigrateDatabase_BlocksFutureGooseVersionWithoutFlag(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-future.db")
highestVersion, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -373,7 +414,7 @@ func TestMigrateDatabase_BlocksFutureGooseVersionWithoutFlag(t *testing.T) {
}
func TestMigrateDatabase_BlocksDowngradeWhenEmbeddedMigrationMissing(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-missing-down.db")
highestVersion, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -390,7 +431,7 @@ func TestMigrateDatabase_BlocksDowngradeWhenEmbeddedMigrationMissing(t *testing.
}
func TestMigrateDatabase_BlocksDirtyLegacyCurrentVersion(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-legacy-current-dirty.db")
highestVersion, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -403,11 +444,11 @@ func TestMigrateDatabase_BlocksDirtyLegacyCurrentVersion(t *testing.T) {
require.NoError(t, migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}))
assert.Equal(t, highestVersion, readGooseSQLiteVersionInternal(t, dsn))
- assertLegacyMigrationDirtyInternal(t, dsn, false)
+ assertLegacyMigrationCleanInternal(t, dsn)
}
func TestMigrateDatabase_BlocksDirtyLegacyOlderVersion(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-legacy-older-dirty.db")
targetVersion := downgradeTargetVersionInternal(t)
require.NoError(t, migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}))
@@ -424,7 +465,7 @@ func TestMigrateDatabase_BlocksDirtyLegacyOlderVersion(t *testing.T) {
highestVersion, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
assert.Equal(t, highestVersion, readGooseSQLiteVersionInternal(t, dsn))
- assertLegacyMigrationDirtyInternal(t, dsn, false)
+ assertLegacyMigrationCleanInternal(t, dsn)
}
func downgradeTargetVersionInternal(t *testing.T) int64 {
@@ -452,7 +493,7 @@ func newSQLiteSQLDBInternal(t *testing.T, dirPath, fileName string) (*stdsql.DB,
}
func TestInitialize_AllowsMigrationOptions(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
dsn := "file:" + filepath.Join(t.TempDir(), "arcane-init.db")
db, err := Initialize(ctx, dsn, MigrationOptions{})
@@ -466,7 +507,7 @@ func TestInitialize_AllowsMigrationOptions(t *testing.T) {
}
func TestInitialize_RecordsGooseVersionOnFreshSQLite(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
dsn := "file:" + filepath.Join(t.TempDir(), "arcane-goose-fresh.db")
db, err := Initialize(ctx, dsn, MigrationOptions{})
@@ -482,7 +523,7 @@ func TestInitialize_RecordsGooseVersionOnFreshSQLite(t *testing.T) {
}
func TestInitialize_AdoptsCleanLegacyMigrationState(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
dsn := "file:" + filepath.Join(t.TempDir(), "arcane-legacy-clean.db")
highest, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -496,11 +537,11 @@ func TestInitialize_AdoptsCleanLegacyMigrationState(t *testing.T) {
})
assert.Equal(t, highest, readGooseSQLiteVersionInternal(t, dsn))
- assertLegacyMigrationDirtyInternal(t, dsn, false)
+ assertLegacyMigrationCleanInternal(t, dsn)
}
func TestInitialize_RollsBackFailedLegacyMigrationAdoption(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-legacy-rollback.db")
highest, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -528,7 +569,7 @@ CREATE TABLE goose_db_version (
}
func TestInitialize_BlocksDirtyLegacyMigrationState(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
dsn := "file:" + filepath.Join(t.TempDir(), "arcane-legacy-dirty.db")
highest, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -542,7 +583,7 @@ func TestInitialize_BlocksDirtyLegacyMigrationState(t *testing.T) {
}
func TestInitialize_ClearsDirtyLegacyMigrationStateWhenAllowed(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
dsn := "file:" + filepath.Join(t.TempDir(), "arcane-legacy-dirty-allowed.db")
highest, err := getHighestEmbeddedMigrationVersionInternal("sqlite")
require.NoError(t, err)
@@ -556,11 +597,11 @@ func TestInitialize_ClearsDirtyLegacyMigrationStateWhenAllowed(t *testing.T) {
})
assert.Equal(t, highest, readGooseSQLiteVersionInternal(t, dsn))
- assertLegacyMigrationDirtyInternal(t, dsn, false)
+ assertLegacyMigrationCleanInternal(t, dsn)
}
func TestInitialize_CreatesQueryPerformanceIndexes(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
dsn := "file:" + filepath.Join(t.TempDir(), "arcane-indexes.db")
db, err := Initialize(ctx, dsn, MigrationOptions{})
@@ -678,7 +719,7 @@ func readGooseSQLiteVersionInternal(t *testing.T, dsn string) int64 {
return version
}
-func assertLegacyMigrationDirtyInternal(t *testing.T, dsn string, expected bool) {
+func assertLegacyMigrationCleanInternal(t *testing.T, dsn string) {
t.Helper()
rawDB, err := stdsql.Open("sqlite", dsn)
@@ -690,7 +731,7 @@ func assertLegacyMigrationDirtyInternal(t *testing.T, dsn string, expected bool)
var dirty bool
err = rawDB.QueryRow(`SELECT dirty FROM schema_migrations ORDER BY version DESC LIMIT 1`).Scan(&dirty)
require.NoError(t, err)
- assert.Equal(t, expected, dirty)
+ assert.False(t, dirty)
}
// TestSQLiteMigrations_ColumnAddsAreReversible guards against the historical footgun
@@ -711,15 +752,22 @@ func TestSQLiteMigrations_ColumnAddsAreReversible(t *testing.T) {
continue
}
- content, err := fs.ReadFile(migrationsFS, entry.Name())
- require.NoError(t, err)
+ content, readFileErr := fs.ReadFile(migrationsFS, entry.Name())
+ require.NoError(t, readFileErr)
up, down := gooseUpDownSectionsInternal(string(content))
if !strings.Contains(strings.ToUpper(up), "ADD COLUMN") {
continue
}
- assert.True(t, sectionHasSQLInternal(down), "migration %s adds a column but its '-- +goose Down' has no SQL; add the reversing ALTER TABLE ... DROP COLUMN (modernc SQLite supports it). A no-op Down breaks down/up round-trips with a duplicate-column error.", entry.Name())
+ assert.True(
+ t,
+ sectionHasSQLInternal(down),
+ "migration %s adds a column but its '-- +goose Down' has no SQL; add the reversing ALTER TABLE ... DR"+
+ "OP COLUMN (modernc SQLite supports it). A no-op Down breaks down/up round-trips with a duplicate-col"+
+ "umn error.",
+ entry.Name(),
+ )
}
}
@@ -733,7 +781,7 @@ func TestSQLiteMigrations_ColumnAddsAreReversible(t *testing.T) {
// foreign key still references it, which SQLite rejects. That is unrelated to the no-op
// Down fixes here and is tracked separately.
func TestSQLiteMigrations_DownUpRoundTrip(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-roundtrip.db")
require.NoError(t, migrateDatabaseInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}))
@@ -787,11 +835,22 @@ func TestIdentityNormalizationMigration(t *testing.T) {
{name: "existing duplicate emails preserved", first: "one", second: "two", emailFirst: "[email protected]", emailSecond: "[email protected]"},
} {
t.Run(tc.name, func(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "identities.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, db, dbProviderSQLite, MigrationOptions{}, 80))
const displayName = "\t\n\v\f\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000Jose\u0301\u3000"
- _, err := db.Exec("INSERT INTO users (id, username, email, display_name, password_hash) VALUES (?, ?, ?, ?, 'unchanged'), (?, ?, ?, ?, 'unchanged')", "first", tc.first, tc.emailFirst, displayName, "second", tc.second, tc.emailSecond, nil)
+ _, err := db.Exec(
+ "INSERT INTO users (id, username, email, display_name, password_hash) VALUES (?, ?, ?, ?, 'unchanged'"+
+ "), (?, ?, ?, ?, 'unchanged')",
+ "first",
+ tc.first,
+ tc.emailFirst,
+ displayName,
+ "second",
+ tc.second,
+ tc.emailSecond,
+ nil,
+ )
require.NoError(t, err)
require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderSQLite, MigrationOptions{}))
require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderSQLite, MigrationOptions{}))
@@ -804,7 +863,19 @@ func TestIdentityNormalizationMigration(t *testing.T) {
} {
var id, username, email, password string
var displayName stdsql.NullString
- require.NoError(t, db.QueryRow("SELECT id, username, email, display_name, password_hash FROM users WHERE id = ?", expected.id).Scan(&id, &username, &email, &displayName, &password))
+ require.NoError(
+ t,
+ db.QueryRow(
+ "SELECT id, username, email, display_name, password_hash FROM users WHERE id = ?",
+ expected.id,
+ ).Scan(
+ &id,
+ &username,
+ &email,
+ &displayName,
+ &password,
+ ),
+ )
require.Equal(t, expected.id, id)
require.Equal(t, expected.username, username)
require.Equal(t, expected.email, email)
@@ -821,10 +892,20 @@ func TestIdentityNormalizationMigration(t *testing.T) {
}
func TestIdentityNormalizationGooseUpgrade(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "upgrade.db")
require.NoError(t, migrateDatabaseToVersionInternal(ctx, db, dbProviderSQLite, MigrationOptions{}, 80))
- _, err := db.Exec("INSERT INTO users (id, username, display_name, password_hash) VALUES (?, ?, ?, ?), (?, ?, ?, ?)", "first", " Jose\u0301 ", " Jose\u0301 ", "unchanged", "second", "José", nil, "unchanged")
+ _, err := db.Exec(
+ "INSERT INTO users (id, username, display_name, password_hash) VALUES (?, ?, ?, ?), (?, ?, ?, ?)",
+ "first",
+ " Jose\u0301 ",
+ " Jose\u0301 ",
+ "unchanged",
+ "second",
+ "José",
+ nil,
+ "unchanged",
+ )
require.NoError(t, err)
initialized, err := Initialize(ctx, dsn, MigrationOptions{})
require.NoError(t, err)
@@ -852,7 +933,7 @@ func TestIdentityNormalizationPostgresUpgrade(t *testing.T) {
if dsn == "" {
t.Skip("ARCANE_TEST_POSTGRES_DSN is not set")
}
- ctx := context.Background()
+ ctx := t.Context()
admin, err := stdsql.Open("pgx", dsn)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, admin.Close()) })
@@ -860,8 +941,8 @@ func TestIdentityNormalizationPostgresUpgrade(t *testing.T) {
_, err = admin.ExecContext(ctx, "CREATE SCHEMA "+schema)
require.NoError(t, err)
t.Cleanup(func() {
- _, err := admin.ExecContext(ctx, "DROP SCHEMA "+schema+" CASCADE")
- require.NoError(t, err)
+ _, execContextErr := admin.ExecContext(ctx, "DROP SCHEMA "+schema+" CASCADE")
+ require.NoError(t, execContextErr)
})
parsed, err := url.Parse(dsn)
require.NoError(t, err)
@@ -874,7 +955,21 @@ func TestIdentityNormalizationPostgresUpgrade(t *testing.T) {
t.Cleanup(func() { require.NoError(t, db.Close()) })
require.NoError(t, migrateDatabaseToVersionInternal(ctx, db, dbProviderPostgres, MigrationOptions{}, 80))
const whitespace = "\t\n\v\f\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000"
- _, err = db.ExecContext(ctx, "INSERT INTO users (id, username, email, display_name, password_hash) VALUES ($1, $2, $3, $4, $5), ($6, $7, $8, $9, $10)", "first", " Jose\u0301 ", " [email protected] ", whitespace+"Jose\u0301"+whitespace, "unchanged", "second", "José", nil, nil, "unchanged")
+ _, err = db.ExecContext(
+ ctx,
+ "INSERT INTO users (id, username, email, display_name, password_hash) VALUES ($1, $2, $3, $4, $5), ($"+
+ "6, $7, $8, $9, $10)",
+ "first",
+ " Jose\u0301 ",
+ whitespace+"Jose\u0301"+whitespace,
+ "unchanged",
+ "second",
+ "José",
+ nil,
+ nil,
+ "unchanged",
+ )
require.NoError(t, err)
require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderPostgres, MigrationOptions{}))
require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderPostgres, MigrationOptions{}))
@@ -887,7 +982,20 @@ func TestIdentityNormalizationPostgresUpgrade(t *testing.T) {
} {
var id, username, password string
var email, displayName stdsql.NullString
- require.NoError(t, db.QueryRowContext(ctx, "SELECT id, username, email, display_name, password_hash FROM users WHERE id = $1", expected.id).Scan(&id, &username, &email, &displayName, &password))
+ require.NoError(
+ t,
+ db.QueryRowContext(
+ ctx,
+ "SELECT id, username, email, display_name, password_hash FROM users WHERE id = $1",
+ expected.id,
+ ).Scan(
+ &id,
+ &username,
+ &email,
+ &displayName,
+ &password,
+ ),
+ )
require.Equal(t, expected.id, id)
require.Equal(t, expected.username, username)
require.Equal(t, expected.email, email)
diff --git a/backend/internal/di/di_test.go b/backend/internal/di/di_test.go
index eac14a41f..ad8da9066 100644
--- a/backend/internal/di/di_test.go
+++ b/backend/internal/di/di_test.go
@@ -137,7 +137,7 @@ func TestOptionsValidate(t *testing.T) {
(*database.DB)(nil),
&http.Client{},
),
- fx.Provide(func() context.Context { return context.Background() }),
+ fx.Provide(func() context.Context { return t.Context() }),
ActorOptions,
ServiceOptions,
JobOptions,
@@ -161,7 +161,17 @@ func TestDockerEventLifecycleInternal(t *testing.T) {
return
}
w.Header().Set("Content-Type", "application/json")
- err := json.MarshalWrite(w, events.Message{Type: events.ContainerEventType, Action: events.ActionStart, Actor: events.Actor{ID: "daemon-container", Attributes: map[string]string{"name": "external"}}})
+ err := json.MarshalWrite(
+ w,
+ events.Message{
+ Type: events.ContainerEventType,
+ Action: events.ActionStart,
+ Actor: events.Actor{
+ ID: "daemon-container",
+ Attributes: map[string]string{"name": "external"},
+ },
+ },
+ )
if err != nil {
return
}
@@ -183,7 +193,7 @@ func TestDockerEventLifecycleInternal(t *testing.T) {
eventService := event.NewEventService(databaseDB, cfg, nil)
provideDockerClientServiceInternal(t.Context(), lifecycle, databaseDB, cfg, nil, eventService)
t.Cleanup(func() {
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), 3*time.Second)
defer cancel()
require.NoError(t, lifecycle.Stop(ctx))
})
@@ -198,7 +208,7 @@ func TestDockerEventLifecycleInternal(t *testing.T) {
require.Equal(t, "System", *record.Username)
require.Equal(t, "0", *record.EnvironmentID)
require.Equal(t, "docker", record.Metadata["source"])
- stopCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ stopCtx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
require.NoError(t, lifecycle.Stop(stopCtx))
select {
diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.go
index 222f313f0..154c0936f 100644
--- a/backend/internal/di/providers.go
+++ b/backend/internal/di/providers.go
@@ -48,13 +48,13 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/oidcjwk"
)
-func provideActivityModuleInternal(service *activity.ActivityService, environment *environment.EnvironmentService) *activity.Module {
+func provideActivityModuleInternal(service *activity.ActivityService, localEnvironment *environment.EnvironmentService) *activity.Module {
return activity.New(service, activity.EnvironmentDependencies{
- ProxyJSONRequest: environment.ProxyJSONRequest,
- ListActiveRemoteEnvironments: environment.ListActiveRemoteEnvironments,
- GetActiveRemoteEnvironment: environment.GetActiveRemoteEnvironmentSnapshot,
- ProxyJSONRequestForEnvironment: environment.ProxyJSONRequestForEnvironment,
- ResolveEnvironmentName: environment.ResolveEnvironmentName,
+ ProxyJSONRequest: localEnvironment.ProxyJSONRequest,
+ ListActiveRemoteEnvironments: localEnvironment.ListActiveRemoteEnvironments,
+ GetActiveRemoteEnvironment: localEnvironment.GetActiveRemoteEnvironmentSnapshot,
+ ProxyJSONRequestForEnvironment: localEnvironment.ProxyJSONRequestForEnvironment,
+ ResolveEnvironmentName: localEnvironment.ResolveEnvironmentName,
})
}
@@ -62,11 +62,23 @@ func provideImageUpdateModuleInternal(service *imageupdate.ImageUpdateService, i
return imageupdate.New(service, imageService.GetUpdateInfoByImageRefs)
}
-func provideSettingsModuleInternal(service *settings.SettingsService, search *settings.SettingsSearchService, environment *environment.EnvironmentService, cfg *config.Config) *settings.Module {
- return settings.New(service, search, environment.ProxyJSONRequest, cfg)
+func provideSettingsModuleInternal(service *settings.SettingsService, search *settings.SettingsSearchService, localEnvironment *environment.EnvironmentService, cfg *config.Config) *settings.Module {
+ return settings.New(service, search, localEnvironment.ProxyJSONRequest, cfg)
}
-func provideBackupEngineInternal(ctx context.Context, lc fx.Lifecycle, admission *runs.Admission, imageService *image.ImageService, runtime *francis.Runtime, coordinator *runs.Coordinator, roles *role.RoleService, cfg *config.Config) (*backup.Engine, error) {
+func provideBackupEngineInternal(
+ ctx context.Context,
+ lc fx.Lifecycle,
+ admission *runs.Admission,
+ imageService *image.ImageService,
+ runtime *francis.Runtime,
+ coordinator *runs.Coordinator,
+ roles *role.RoleService,
+ cfg *config.Config,
+) (
+ *backup.Engine,
+ error,
+) {
engine := backup.NewEngine(ctx, admission, imageService)
if err := engine.Register(runtime); err != nil {
return nil, err
@@ -101,8 +113,8 @@ func provideActorRuntimeInternal(appCtx context.Context, cfg *config.Config, set
return nil, err
}
lc.Append(fx.Hook{OnStart: func(ctx context.Context) error {
- if err := runtime.ConfigureIdentity(cfg.EncryptionKey, settingsService.GetSettingsConfig().InstanceID.Value); err != nil {
- return err
+ if configureIdentityErr := runtime.ConfigureIdentity(cfg.EncryptionKey, settingsService.GetSettingsConfig().InstanceID.Value); configureIdentityErr != nil {
+ return configureIdentityErr
}
return runtime.Start(ctx, appCtx, func(err error) { slog.ErrorContext(appCtx, "Francis host failed", "error", err); cancelApp() })
}, OnStop: runtime.Stop})
@@ -119,18 +131,31 @@ func provideRunCoordinatorInternal(runtime *francis.Runtime, store *kv.KVService
func provideAdmissionGateInternal(runtime *francis.Runtime) (*runs.Admission, error) {
admission := runs.NewAdmission(runtime.Service(), uuid.New().String())
- return admission, admission.Register(runtime)
+ if err := admission.Register(runtime); err != nil {
+ return nil, err
+ }
+ return admission, nil
}
func provideTunnelRegistryInternal(lc fx.Lifecycle) *edge.TunnelRegistry {
- registry := edge.NewTunnelRegistry()
- edge.SetDefaultRegistry(registry)
- lc.Append(fx.Hook{OnStop: func(ctx context.Context) error { defer edge.ClearDefaultRegistry(registry); return registry.Stop(ctx) }})
- return registry
+ localRegistry := edge.NewTunnelRegistry()
+ edge.SetDefaultRegistry(localRegistry)
+ lc.Append(fx.Hook{OnStop: func(ctx context.Context) error {
+ defer edge.ClearDefaultRegistry(localRegistry)
+ return localRegistry.Stop(ctx)
+ }})
+ return localRegistry
}
-func provideDockerClientServiceInternal(ctx context.Context, lc fx.Lifecycle, db *database.DB, cfg *config.Config, settings *settings.SettingsService, eventService *event.EventService) *docker.DockerClientService {
- service := docker.NewDockerClientService(ctx, db, cfg, settings, bus.WithDroppedEventCallback(func(message events.Message) {
+func provideDockerClientServiceInternal(
+ ctx context.Context,
+ lc fx.Lifecycle,
+ db *database.DB,
+ cfg *config.Config,
+ localSettings *settings.SettingsService,
+ eventService *event.EventService,
+) *docker.DockerClientService {
+ service := docker.NewDockerClientService(ctx, db, cfg, localSettings, bus.WithDroppedEventCallback(func(message events.Message) {
// Overflow is recovered synchronously, applying backpressure instead of losing log entries.
eventService.RecordDockerEvent(ctx, message)
}))
@@ -174,36 +199,60 @@ func provideDockerClientServiceInternal(ctx context.Context, lc fx.Lifecycle, db
return service
}
-func provideVersionServiceInternal(httpClient *http.Client, cfg *config.Config, registry *registry.ContainerRegistryService, docker *docker.DockerClientService, imageUpdate *imageupdate.ImageUpdateService, settingsService *settings.SettingsService) *version.VersionService {
- return version.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, registry, docker, imageUpdate, settingsService)
+func provideVersionServiceInternal(
+ httpClient *http.Client,
+ cfg *config.Config,
+ localRegistry *registry.ContainerRegistryService,
+ localDocker *docker.DockerClientService,
+ imageUpdate *imageupdate.ImageUpdateService,
+ settingsService *settings.SettingsService,
+) *version.VersionService {
+ return version.NewVersionService(httpClient, cfg.UpdateCheckDisabled, config.Version, config.Revision, localRegistry, localDocker, imageUpdate, settingsService)
}
func provideGitRepositoryServiceInternal(db *database.DB, cfg *config.Config, eventService *event.EventService, settingsService *settings.SettingsService) *gitrepo.GitRepositoryService {
return gitrepo.NewGitRepositoryService(db, cfg.GitWorkDir, eventService, settingsService)
}
-func provideS3ModuleInternal(service *s3domain.S3DestinationService, environment *environment.EnvironmentService) *s3domain.Module {
- return s3domain.New(service, environment.SyncS3DestinationsToRemoteEnvironments)
+func provideS3ModuleInternal(service *s3domain.S3DestinationService, localEnvironment *environment.EnvironmentService) *s3domain.Module {
+ return s3domain.New(service, localEnvironment.SyncS3DestinationsToRemoteEnvironments)
}
-func provideS3ServiceInternal(db *database.DB, environment *environment.EnvironmentService) *s3domain.S3DestinationService {
- return s3domain.NewS3DestinationService(db, environment.CheckS3DestinationReferences)
+func provideS3ServiceInternal(db *database.DB, localEnvironment *environment.EnvironmentService) *s3domain.S3DestinationService {
+ return s3domain.NewS3DestinationService(db, localEnvironment.CheckS3DestinationReferences)
}
func provideAuthModuleInternal(service *auth.AuthService, userService *user.UserService, settingsService *settings.SettingsService, passkeyService *passkey.PasskeyService) *auth.Module {
return auth.New(service, userService, settingsService, passkeyService.BeginMFAAuthentication)
}
-func provideContainerRegistryServiceInternal(db *database.DB, docker *docker.DockerClientService, kv *kv.KVService, settings *settings.SettingsService) *registry.ContainerRegistryService {
- return registry.NewContainerRegistryService(db, func(ctx context.Context) (registry.RegistryDaemonClient, error) { return docker.GetClient(ctx) }, kv, settings)
+func provideContainerRegistryServiceInternal(
+ db *database.DB,
+ localDocker *docker.DockerClientService,
+ kvService *kv.KVService,
+ settingsService *settings.SettingsService,
+) *registry.ContainerRegistryService {
+ return registry.NewContainerRegistryService(db, func(ctx context.Context) (registry.RegistryDaemonClient, error) { return localDocker.GetClient(ctx) }, kvService, settingsService)
}
-func provideContainerRegistryModuleInternal(service *registry.ContainerRegistryService, environment *environment.EnvironmentService) *registry.Module {
- return registry.New(service, environment.SyncRegistriesToRemoteEnvironments)
+func provideContainerRegistryModuleInternal(service *registry.ContainerRegistryService, localEnvironment *environment.EnvironmentService) *registry.Module {
+ return registry.New(service, localEnvironment.SyncRegistriesToRemoteEnvironments)
}
-func provideProjectServiceInternal(db *database.DB, settings *settings.SettingsService, event *event.EventService, image *image.ImageService, docker *docker.DockerClientService, build *build.BuildService, lifecycleService *project.LifecycleService, kv *kv.KVService, registry *registry.ContainerRegistryService, environment *environment.EnvironmentService, cfg *config.Config) *project.ProjectService {
- return project.NewProjectService(db, settings, event, image, docker, build, lifecycleService, registry, cfg, kv, environment.GetEnabledRegistryCredentials)
+func provideProjectServiceInternal(
+ db *database.DB,
+ localSettings *settings.SettingsService,
+ localEvent *event.EventService,
+ localImage *image.ImageService,
+ localDocker *docker.DockerClientService,
+ localBuild *build.BuildService,
+ lifecycleService *project.LifecycleService,
+ localKv *kv.KVService,
+ localRegistry *registry.ContainerRegistryService,
+ localEnvironment *environment.EnvironmentService,
+ cfg *config.Config,
+) *project.ProjectService {
+ return project.NewProjectService(db, localSettings, localEvent, localImage, localDocker, localBuild, lifecycleService, localRegistry, cfg, localKv, localEnvironment.GetEnabledRegistryCredentials)
}
// updaterServiceParams includes actor registration and worker lifecycle dependencies.
@@ -231,19 +280,46 @@ type updaterServiceParams struct {
}
func provideUpdaterServiceInternal(p updaterServiceParams) (*updater.UpdaterService, error) {
- service, err := updater.NewUpdaterService(p.DB, p.Settings, p.Docker, p.Project, p.ImageUpdate, p.Registry, p.Event, p.Image, p.Notification, p.SystemUpgrade, p.Activity, p.Config, p.Coordinator, p.Admission, p.Roles)
+ service, err := updater.NewUpdaterService(
+ p.DB,
+ p.Settings,
+ p.Docker,
+ p.Project,
+ p.ImageUpdate,
+ p.Registry,
+ p.Event,
+ p.Image,
+ p.Notification,
+ p.SystemUpgrade,
+ p.Activity,
+ p.Config,
+ p.Coordinator,
+ p.Admission,
+ p.Roles,
+ )
if err != nil {
return nil, err
}
- if err := service.RegisterActors(p.ActorRuntime); err != nil {
- return nil, err
+ if registerActorsErr := service.RegisterActors(p.ActorRuntime); registerActorsErr != nil {
+ return nil, registerActorsErr
}
- p.Lifecycle.Append(fx.Hook{OnStart: func(context.Context) error { return service.Start(p.Context) }, OnStop: service.Stop}) //nolint:contextcheck // Workers inherit the application lifetime after startup returns.
+ p.Lifecycle.Append(
+ fx.Hook{
+ OnStart: func(
+ context.Context,
+ ) error {
+ return service.Start(
+ p.Context,
+ )
+ },
+ OnStop: service.Stop,
+ },
+ ) //nolint:contextcheck // Workers inherit the application lifetime after startup returns.
return service, nil
}
-func provideUserModuleInternal(service *user.UserService, auth *auth.AuthService, settingsService *settings.SettingsService) *user.Module {
- return user.New(service, auth.InvalidateUserTokenCache, settingsService)
+func provideUserModuleInternal(service *user.UserService, localAuth *auth.AuthService, settingsService *settings.SettingsService) *user.Module {
+ return user.New(service, localAuth.InvalidateUserTokenCache, settingsService)
}
func provideJWKSetManagerInternal(ctx context.Context, lc fx.Lifecycle) *oidcjwk.KeySetManager {
@@ -252,15 +328,31 @@ func provideJWKSetManagerInternal(ctx context.Context, lc fx.Lifecycle) *oidcjwk
return manager
}
-func provideAuthMiddlewareInternal(authService *auth.AuthService, apiKey *apikey.ApiKeyService, env *environment.EnvironmentService, role *role.RoleService, cfg *config.Config) *auth.AuthMiddleware {
+func provideAuthMiddlewareInternal(
+ authService *auth.AuthService,
+ apiKey *apikey.ApiKeyService,
+ env *environment.EnvironmentService,
+ localRole *role.RoleService,
+ cfg *config.Config,
+) *auth.AuthMiddleware {
return auth.NewAuthMiddleware(authService, cfg).
WithApiKeyValidator(apiKey).
WithEnvironmentAccessTokenResolver(env).
- WithPermissionResolver(role)
+ WithPermissionResolver(localRole)
}
-func provideFilesystemWatcherJobInternal(ctx context.Context, lc fx.Lifecycle, project *project.ProjectService, template *template.TemplateService, settings *settings.SettingsService, cfg *config.Config) (*scheduler.FilesystemWatcherJob, error) {
- job, err := scheduler.NewFilesystemWatcherJob(ctx, project, template, settings, cfg.ProjectScanMaxDepth)
+func provideFilesystemWatcherJobInternal(
+ ctx context.Context,
+ lc fx.Lifecycle,
+ localProject *project.ProjectService,
+ localTemplate *template.TemplateService,
+ localSettings *settings.SettingsService,
+ cfg *config.Config,
+) (
+ *scheduler.FilesystemWatcherJob,
+ error,
+) {
+ job, err := scheduler.NewFilesystemWatcherJob(ctx, localProject, localTemplate, localSettings, cfg.ProjectScanMaxDepth)
if err != nil {
return nil, err
}
@@ -295,11 +387,11 @@ func provideFilesystemWatcherJobInternal(ctx context.Context, lc fx.Lifecycle, p
return nil
},
OnStop: func(stopCtx context.Context) error {
- var err error
+ var stopWorkerErr error
if stop != nil {
- err = stop(stopCtx)
+ stopWorkerErr = stop(stopCtx)
}
- return errors.Join(err, job.Stop(stopCtx))
+ return errors.Join(stopWorkerErr, job.Stop(stopCtx))
},
})
return job, nil
diff --git a/backend/internal/docker/service_test.go b/backend/internal/docker/service_test.go
index b3319872c..894b9e5a4 100644
--- a/backend/internal/docker/service_test.go
+++ b/backend/internal/docker/service_test.go
@@ -47,7 +47,7 @@ func TestNewDockerClient_PinsEffectiveAPIVersion(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
server := newDockerPingTestServerInternal(t, tt.pingAPIVersion)
- cli, err := newDockerClientInternal(context.Background(), server.URL)
+ cli, err := newDockerClientInternal(t.Context(), server.URL)
require.NoError(t, err)
t.Cleanup(func() {
_ = cli.Close()
@@ -62,15 +62,15 @@ func TestNewDockerClient_PinsEffectiveAPIVersion(t *testing.T) {
func TestDockerClientService_GetClientReturnsCachedClientUntilRefresh(t *testing.T) {
server := newDockerPingTestServerInternal(t, "1.41")
- svc := newDockerClientServiceForTestInternal(server.URL)
+ svc := newDockerClientServiceForTestInternal(t, server.URL)
- firstClient, err := svc.GetClient(context.Background())
+ firstClient, err := svc.GetClient(t.Context())
require.NoError(t, err)
t.Cleanup(func() {
_ = firstClient.Close()
})
- secondClient, err := svc.GetClient(context.Background())
+ secondClient, err := svc.GetClient(t.Context())
require.NoError(t, err)
assert.Same(t, firstClient, secondClient)
@@ -83,9 +83,9 @@ func TestDockerClientService_RefreshClientRecreatesCachedClientAfterAPIVersionCh
server := newDockerPingTestServerWithVersionInternal(t, func() string {
return apiVersion.Load().(string)
})
- svc := newDockerClientServiceForTestInternal(server.URL)
+ svc := newDockerClientServiceForTestInternal(t, server.URL)
- firstClient, err := svc.GetClient(context.Background())
+ firstClient, err := svc.GetClient(t.Context())
require.NoError(t, err)
t.Cleanup(func() {
_ = firstClient.Close()
@@ -94,7 +94,7 @@ func TestDockerClientService_RefreshClientRecreatesCachedClientAfterAPIVersionCh
apiVersion.Store("1.42")
- err = svc.RefreshClient(context.Background())
+ err = svc.RefreshClient(t.Context())
require.NoError(t, err)
secondClient := svc.Client
t.Cleanup(func() {
@@ -113,21 +113,21 @@ func TestDockerClientService_RefreshClientClosesOldCachedClientWhenReplaced(t *t
}
})
newServer := newDockerPingTestServerInternal(t, "1.42")
- svc := newDockerClientServiceForTestInternal(oldServer.URL)
+ svc := newDockerClientServiceForTestInternal(t, oldServer.URL)
- firstClient, err := svc.GetClient(context.Background())
+ firstClient, err := svc.GetClient(t.Context())
require.NoError(t, err)
t.Cleanup(func() {
_ = firstClient.Close()
})
- _, err = firstClient.Ping(context.Background(), client.PingOptions{})
+ _, err = firstClient.Ping(t.Context(), client.PingOptions{})
require.NoError(t, err)
closedBeforeReplace := oldServerClosedConnections.Load()
svc.config.DockerHost = newServer.URL
- err = svc.RefreshClient(context.Background())
+ err = svc.RefreshClient(t.Context())
require.NoError(t, err)
secondClient := svc.Client
t.Cleanup(func() {
@@ -155,9 +155,9 @@ func TestDockerClientService_RefreshClientProbeFailureKeepsCachedClient(t *testi
w.Header().Set("Api-Version", "1.41")
w.WriteHeader(http.StatusOK)
})
- svc := newDockerClientServiceForTestInternal(server.URL)
+ svc := newDockerClientServiceForTestInternal(t, server.URL)
- firstClient, err := svc.GetClient(context.Background())
+ firstClient, err := svc.GetClient(t.Context())
require.NoError(t, err)
t.Cleanup(func() {
_ = firstClient.Close()
@@ -165,7 +165,7 @@ func TestDockerClientService_RefreshClientProbeFailureKeepsCachedClient(t *testi
failProbe.Store(true)
- err = svc.RefreshClient(context.Background())
+ err = svc.RefreshClient(t.Context())
require.Error(t, err)
assert.Same(t, firstClient, svc.Client)
assert.Equal(t, "1.41", svc.clientVersion)
@@ -212,7 +212,7 @@ func TestDockerClientService_EventActorStopCancelsAndJoinsStreamInternal(t *test
}
})
- service := newDockerClientServiceForTestInternal(server.URL)
+ service := newDockerClientServiceForTestInternal(t, server.URL)
t.Cleanup(service.Close)
eventsCh, unsubscribe := service.EventBus().Subscribe(events.ImageEventType)
@@ -234,7 +234,7 @@ func TestDockerClientService_EventActorStopCancelsAndJoinsStreamInternal(t *test
default:
}
- stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
require.NoError(t, stop(stopCtx))
require.Eventually(t, func() bool {
@@ -275,12 +275,12 @@ func TestCountImageUsage_NoImages(t *testing.T) {
assert.Equal(t, imagetypes.UsageCounts{}, counts)
}
-func newDockerClientServiceForTestInternal(host string) *DockerClientService {
- return NewDockerClientService(context.Background(), nil, &config.Config{DockerHost: host}, nil)
+func newDockerClientServiceForTestInternal(t *testing.T, host string) *DockerClientService {
+ return NewDockerClientService(t.Context(), nil, &config.Config{DockerHost: host}, nil)
}
func dockerTestPathInternal(path string) string {
- return regexp.MustCompile(`^/v[0-9]+\.[0-9]+`).ReplaceAllString(path, "")
+ return regexp.MustCompile(`^/v\d+\.\d+`).ReplaceAllString(path, "")
}
func newDockerPingTestServerInternal(t *testing.T, apiVersion string) *httptest.Server {
diff --git a/backend/internal/environment/edge_mtls_handler.go b/backend/internal/environment/edge_mtls_handler.go
index 61b4870b8..33b427604 100644
--- a/backend/internal/environment/edge_mtls_handler.go
+++ b/backend/internal/environment/edge_mtls_handler.go
@@ -36,8 +36,8 @@ func generatedEdgeMTLSClientCertPathInternal(cfg *config.Config, envID string) (
}
// os.* rather than acfs: the assets dir may be user-configured to anywhere
// on the host, so no confinement root exists for this path.
- if _, err := os.Stat(certPath); err != nil {
- return "", fmt.Errorf("stat generated edge mTLS client certificate: %w", err)
+ if _, statErr := os.Stat(certPath); statErr != nil {
+ return "", fmt.Errorf("stat generated edge mTLS client certificate: %w", statErr)
}
return certPath, nil
diff --git a/backend/internal/environment/environment.go b/backend/internal/environment/environment.go
index e537f78e7..1796833ab 100644
--- a/backend/internal/environment/environment.go
+++ b/backend/internal/environment/environment.go
@@ -97,7 +97,14 @@ func (s *EnvironmentService) ForgetSyncState(environmentID string) {
}
}
-func NewEnvironmentService(db *database.DB, httpClient *http.Client, dockerService *docker.DockerClientService, eventService *event.EventService, settingsService *settings.SettingsService, apiKeyService *apikey.ApiKeyService) *EnvironmentService {
+func NewEnvironmentService(
+ db *database.DB,
+ httpClient *http.Client,
+ dockerService *docker.DockerClientService,
+ eventService *event.EventService,
+ settingsService *settings.SettingsService,
+ apiKeyService *apikey.ApiKeyService,
+) *EnvironmentService {
if httpClient == nil {
httpClient = http.DefaultClient
}
@@ -213,8 +220,8 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl
if err == nil {
// Local environment already exists, ensure ApiUrl matches current appUrl
if existingEnv.ApiUrl != appUrl {
- if err := s.db.WithContext(ctx).Model(&existingEnv).Update("api_url", appUrl).Error; err != nil {
- return fmt.Errorf("failed to update local environment api url: %w", err)
+ if updateLocalURLErr := s.db.WithContext(ctx).Model(&existingEnv).Update("api_url", appUrl).Error; updateLocalURLErr != nil {
+ return fmt.Errorf("failed to update local environment api url: %w", updateLocalURLErr)
}
s.invalidateEnvironmentCacheInternal(LocalEnvironmentID)
slog.InfoContext(ctx, "updated local environment api url", "id", LocalEnvironmentID, "url", appUrl)
@@ -238,8 +245,8 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl
Enabled: true,
}
- if err := s.db.WithContext(ctx).Create(localEnv).Error; err != nil {
- return fmt.Errorf("failed to create local environment: %w", err)
+ if createLocalEnvironmentErr := s.db.WithContext(ctx).Create(localEnv).Error; createLocalEnvironmentErr != nil {
+ return fmt.Errorf("failed to create local environment: %w", createLocalEnvironmentErr)
}
slog.InfoContext(ctx, "created local environment record", "id", LocalEnvironmentID)
@@ -266,7 +273,22 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment
}
// Create event in background
- go s.createEnvironmentEvent(context.WithoutCancel(ctx), environment.ID, environment.Name, event.EventTypeEnvironmentCreate, "Environment Created", fmt.Sprintf("Environment '%s' was created", environment.Name), event.EventSeveritySuccess, userID, username)
+ go s.createEnvironmentEvent(
+ context.WithoutCancel(
+ ctx,
+ ),
+ environment.ID,
+ environment.Name,
+ event.EventTypeEnvironmentCreate,
+ "Environment Created",
+ fmt.Sprintf(
+ "Environment '%s' was created",
+ environment.Name,
+ ),
+ event.EventSeveritySuccess,
+ userID,
+ username,
+ )
if environment.Enabled {
s.registerHealthJobInternal(ctx, environment.ID)
@@ -305,7 +327,7 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, u
}
}
_, accessTokenUpdated := updates["access_token"]
- if err := validation.ValidateCredentialTargetChange(
+ if validateCredentialTargetChangeErr := validation.ValidateCredentialTargetChange(
"environment API URL",
current.ApiUrl,
nextAPIURL,
@@ -318,14 +340,14 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, u
},
map[string]bool{"accessToken": current.AccessToken != nil && *current.AccessToken != ""},
map[string]bool{"accessToken": accessTokenUpdated},
- ); err != nil {
- return nil, err
+ ); validateCredentialTargetChangeErr != nil {
+ return nil, validateCredentialTargetChangeErr
}
updates["updated_at"] = new(time.Now())
- if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {
- return nil, fmt.Errorf("failed to update environment: %w", err)
+ if updateEnvironmentErr := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; updateEnvironmentErr != nil {
+ return nil, fmt.Errorf("failed to update environment: %w", updateEnvironmentErr)
}
s.invalidateEnvironmentCacheInternal(id)
s.NotifyRuntimeStateChanged()
@@ -354,7 +376,22 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, u
// Create event in background (skip for local environment)
if id != "0" {
- go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, updated.Name, event.EventTypeEnvironmentUpdate, "Environment Updated", fmt.Sprintf("Environment '%s' was updated", updated.Name), event.EventSeverityInfo, userID, username)
+ go s.createEnvironmentEvent(
+ context.WithoutCancel(
+ ctx,
+ ),
+ id,
+ updated.Name,
+ event.EventTypeEnvironmentUpdate,
+ "Environment Updated",
+ fmt.Sprintf(
+ "Environment '%s' was updated",
+ updated.Name,
+ ),
+ event.EventSeverityInfo,
+ userID,
+ username,
+ )
}
return updated, nil
@@ -371,32 +408,32 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, u
s.removeHealthJobInternal(ctx, id)
var syncIDs []string
- if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := tx.Table("gitops_syncs").
+ if transactionErr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if loadSyncIDsErr := tx.Table("gitops_syncs").
Where("environment_id = ?", id).
- Pluck("id", &syncIDs).Error; err != nil {
- return fmt.Errorf("failed to list environment gitops syncs: %w", err)
+ Pluck("id", &syncIDs).Error; loadSyncIDsErr != nil {
+ return fmt.Errorf("failed to list environment gitops syncs: %w", loadSyncIDsErr)
}
if len(syncIDs) > 0 {
- if err := tx.Table("projects").
+ if clearProjectLinksErr := tx.Table("projects").
Where("gitops_managed_by IN ?", syncIDs).
- Update("gitops_managed_by", nil).Error; err != nil {
- return fmt.Errorf("failed to clear environment gitops project references: %w", err)
+ Update("gitops_managed_by", nil).Error; clearProjectLinksErr != nil {
+ return fmt.Errorf("failed to clear environment gitops project references: %w", clearProjectLinksErr)
}
- if err := tx.Exec("DELETE FROM gitops_syncs WHERE environment_id = ?", id).Error; err != nil {
- return fmt.Errorf("failed to delete environment gitops syncs: %w", err)
+ if deleteSyncsErr := tx.Exec("DELETE FROM gitops_syncs WHERE environment_id = ?", id).Error; deleteSyncsErr != nil {
+ return fmt.Errorf("failed to delete environment gitops syncs: %w", deleteSyncsErr)
}
}
- if err := tx.Delete(&Environment{}, "id = ?", id).Error; err != nil {
- return fmt.Errorf("failed to delete environment: %w", err)
+ if deleteEnvironmentErr := tx.Delete(&Environment{}, "id = ?", id).Error; deleteEnvironmentErr != nil {
+ return fmt.Errorf("failed to delete environment: %w", deleteEnvironmentErr)
}
return nil
- }); err != nil {
+ }); transactionErr != nil {
if env.Enabled {
s.registerHealthJobInternal(ctx, env.ID)
}
- return err
+ return transactionErr
}
// Deleting an environment orphans its GitOps syncs, whose jobs belong to
@@ -415,12 +452,36 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, u
s.NotifyRuntimeStateChanged()
// Create event in background
- go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, env.Name, event.EventTypeEnvironmentDelete, "Environment Deleted", fmt.Sprintf("Environment '%s' was deleted", env.Name), event.EventSeverityWarning, userID, username)
+ go s.createEnvironmentEvent(
+ context.WithoutCancel(
+ ctx,
+ ),
+ id,
+ env.Name,
+ event.EventTypeEnvironmentDelete,
+ "Environment Deleted",
+ fmt.Sprintf(
+ "Environment '%s' was deleted",
+ env.Name,
+ ),
+ event.EventSeverityWarning,
+ userID,
+ username,
+ )
return nil
}
-func (s *EnvironmentService) createEnvironmentEvent(ctx context.Context, envID, envName string, eventType event.EventType, title, description string, severity event.EventSeverity, userID, username *string) {
+func (
+ s *EnvironmentService,
+) createEnvironmentEvent(
+ ctx context.Context,
+ envID, envName string,
+ eventType event.EventType,
+ title, description string,
+ severity event.EventSeverity,
+ userID, username *string,
+) {
if s == nil || s.eventService == nil {
return
}
@@ -476,7 +537,23 @@ func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, en
})
// Create event log in background
- go s.createEnvironmentEvent(context.WithoutCancel(ctx), envID, envName, event.EventTypeEnvironmentApiKeyRegenerated, "API Key Regenerated", "Environment API key was regenerated and status set to pending", event.EventSeverityInfo, new(userID), new(username))
+ go s.createEnvironmentEvent(
+ context.WithoutCancel(
+ ctx,
+ ),
+ envID,
+ envName,
+ event.EventTypeEnvironmentApiKeyRegenerated,
+ "API Key Regenerated",
+ "Environment API key was regenerated and status set to pending",
+ event.EventSeverityInfo,
+ new(
+ userID,
+ ),
+ new(
+ username,
+ ),
+ )
return nil
}
diff --git a/backend/internal/environment/environment_health.go b/backend/internal/environment/environment_health.go
index 57e67177a..46159faab 100644
--- a/backend/internal/environment/environment_health.go
+++ b/backend/internal/environment/environment_health.go
@@ -114,8 +114,8 @@ func (s *EnvironmentService) RunHealthChecksNow(ctx context.Context) error {
}
for _, id := range ids {
request.JobID = s.jobs.JobName(id)
- if _, err := s.jobs.Scheduler().Submit(ctx, request); err != nil {
- return err
+ if _, submitErr := s.jobs.Scheduler().Submit(ctx, request); submitErr != nil {
+ return submitErr
}
}
return nil
@@ -135,14 +135,14 @@ func (s *EnvironmentService) runHealthCheckInternal(ctx context.Context, envID s
}
defer lease.Release(ctx)
- environment, err := s.GetEnvironmentByID(ctx, envID)
+ localEnvironment, err := s.GetEnvironmentByID(ctx, envID)
if err != nil {
return schedulertypes.Outcome{}, err
}
- if !environment.Enabled {
+ if !localEnvironment.Enabled {
return schedulertypes.Outcome{Status: schedulertypes.Canceled, Message: "Environment disabled"}, nil
}
- wasOnline := environment.Status == string(EnvironmentStatusOnline)
+ wasOnline := localEnvironment.Status == string(EnvironmentStatusOnline)
status, err := s.TestConnection(ctx, envID, nil)
switch {
case err != nil:
@@ -166,26 +166,26 @@ func (s *EnvironmentService) runHealthCheckInternal(ctx context.Context, envID s
var syncErrors []error
syncCtx, cancel := context.WithTimeout(ctx, environmentHealthCheckTimeout)
defer cancel()
- if err := s.SyncRegistriesToEnvironment(syncCtx, envID); err != nil {
- slog.WarnContext(syncCtx, "failed to sync registries during health check", "environment_id", envID, "error", err)
- syncErrors = append(syncErrors, err)
+ if syncRegistriesToEnvironmentErr := s.SyncRegistriesToEnvironment(syncCtx, envID); syncRegistriesToEnvironmentErr != nil {
+ slog.WarnContext(syncCtx, "failed to sync registries during health check", "environment_id", envID, "error", syncRegistriesToEnvironmentErr)
+ syncErrors = append(syncErrors, syncRegistriesToEnvironmentErr)
}
- if err := s.SyncS3DestinationsToEnvironment(syncCtx, envID); err != nil {
- slog.WarnContext(syncCtx, "failed to sync S3 destinations during health check", "environment_id", envID, "error", err)
- syncErrors = append(syncErrors, err)
+ if syncS3DestinationsToEnvironmentErr := s.SyncS3DestinationsToEnvironment(syncCtx, envID); syncS3DestinationsToEnvironmentErr != nil {
+ slog.WarnContext(syncCtx, "failed to sync S3 destinations during health check", "environment_id", envID, "error", syncS3DestinationsToEnvironmentErr)
+ syncErrors = append(syncErrors, syncS3DestinationsToEnvironmentErr)
}
- if err := s.SyncRepositoriesToEnvironment(syncCtx, envID); err != nil {
- slog.WarnContext(syncCtx, "failed to sync git repositories during health check", "environment_id", envID, "error", err)
- syncErrors = append(syncErrors, err)
+ if syncRepositoriesToEnvironmentErr := s.SyncRepositoriesToEnvironment(syncCtx, envID); syncRepositoriesToEnvironmentErr != nil {
+ slog.WarnContext(syncCtx, "failed to sync git repositories during health check", "environment_id", envID, "error", syncRepositoriesToEnvironmentErr)
+ syncErrors = append(syncErrors, syncRepositoriesToEnvironmentErr)
}
if s.variableSyncer != nil {
- if err := s.variableSyncer.SyncEnvironment(syncCtx, envID); err != nil {
- slog.WarnContext(syncCtx, "failed to sync global variables during health check", "environment_id", envID, "error", err)
- syncErrors = append(syncErrors, err)
+ if syncEnvironmentErr := s.variableSyncer.SyncEnvironment(syncCtx, envID); syncEnvironmentErr != nil {
+ slog.WarnContext(syncCtx, "failed to sync global variables during health check", "environment_id", envID, "error", syncEnvironmentErr)
+ syncErrors = append(syncErrors, syncEnvironmentErr)
}
}
- if err := errors.Join(syncErrors...); err != nil {
- return schedulertypes.Outcome{Status: schedulertypes.Partial}, err
+ if joinErr := errors.Join(syncErrors...); joinErr != nil {
+ return schedulertypes.Outcome{Status: schedulertypes.Partial}, joinErr
}
return schedulertypes.Outcome{Status: schedulertypes.Succeeded}, nil
}
@@ -228,7 +228,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, cust
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
- req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, healthURL, nil)
+ req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, healthURL, http.NoBody)
if err != nil {
if customApiUrl == nil {
_ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))
@@ -437,7 +437,7 @@ func ApplyEnvironmentRuntimeState(env *environment.Environment) {
if len(runtimeState.Capabilities) > 0 {
env.EdgeCapabilities = append([]string(nil), runtimeState.Capabilities...)
}
- if transport, ok := edge.GetActiveTunnelTransport(env.ID).Get(); ok {
+ if transport, localOk := edge.GetActiveTunnelTransport(env.ID).Get(); localOk {
env.EdgeTransport = &transport
} else if runtimeState.Transport != "" {
env.EdgeTransport = &runtimeState.Transport
diff --git a/backend/internal/environment/environment_listing.go b/backend/internal/environment/environment_listing.go
index 831c0b11a..3f32e2873 100644
--- a/backend/internal/environment/environment_listing.go
+++ b/backend/internal/environment/environment_listing.go
@@ -72,7 +72,17 @@ func filterEnvironmentsByIDInternal(items []environment.Environment, allowedIDs
return out
}
-func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternal(ctx context.Context, params pagination.QueryParams, accessibleEnvIDs []string) ([]environment.Environment, pagination.Response, error) {
+func (
+ s *EnvironmentService,
+) listEnvironmentsPaginatedWithRuntimeFiltersInternal(
+ ctx context.Context,
+ params pagination.QueryParams,
+ accessibleEnvIDs []string,
+) (
+ []environment.Environment,
+ pagination.Response,
+ error,
+) {
var envs []Environment
if err := s.db.WithContext(ctx).
Model(&Environment{}).
diff --git a/backend/internal/environment/environment_proxy.go b/backend/internal/environment/environment_proxy.go
index 0ed8bf9f6..1f70a3adb 100644
--- a/backend/internal/environment/environment_proxy.go
+++ b/backend/internal/environment/environment_proxy.go
@@ -49,12 +49,12 @@ func (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Cont
continue
}
- if err := s.SyncRegistriesToEnvironment(ctx, env.ID); err != nil {
+ if syncRegistriesToEnvironmentErr := s.SyncRegistriesToEnvironment(ctx, env.ID); syncRegistriesToEnvironmentErr != nil {
failedCount++
slog.WarnContext(ctx, "Failed to sync registries to remote environment",
"environmentID", env.ID,
"environmentName", env.Name,
- "error", err.Error())
+ "error", syncRegistriesToEnvironmentErr.Error())
}
}
@@ -78,9 +78,9 @@ func (s *EnvironmentService) SyncS3DestinationsToRemoteEnvironments(ctx context.
slog.DebugContext(ctx, "Skipping S3 destination sync for environment without access token", "environmentID", env.ID, "environmentName", env.Name)
continue
}
- if err := s.SyncS3DestinationsToEnvironment(ctx, env.ID); err != nil {
+ if syncS3DestinationsToEnvironmentErr := s.SyncS3DestinationsToEnvironment(ctx, env.ID); syncS3DestinationsToEnvironmentErr != nil {
failedCount++
- slog.WarnContext(ctx, "Failed to sync S3 destinations to remote environment", "environmentID", env.ID, "environmentName", env.Name, "error", err)
+ slog.WarnContext(ctx, "Failed to sync S3 destinations to remote environment", "environmentID", env.ID, "environmentName", env.Name, "error", syncS3DestinationsToEnvironmentErr)
}
}
@@ -108,8 +108,17 @@ func (s *EnvironmentService) CheckS3DestinationReferences(ctx context.Context, d
var result struct {
InUse bool `json:"inUse"`
}
- if err := s.ProxyJSONRequestForEnvironment(ctx, env, http.MethodGet, "/api/backups/s3/"+url.PathEscape(destinationID)+"/in-use", nil, &result); err != nil {
- return fmt.Errorf("cannot verify S3 destination references on environment %s; restore connectivity before deleting: %w", env.Name, err)
+ if proxyJSONRequestForEnvironmentErr := s.ProxyJSONRequestForEnvironment(
+ ctx,
+ env,
+ http.MethodGet,
+ "/api/backups/s3/"+url.PathEscape(
+ destinationID,
+ )+"/in-use",
+ nil,
+ &result,
+ ); proxyJSONRequestForEnvironmentErr != nil {
+ return fmt.Errorf("cannot verify S3 destination references on environment %s; restore connectivity before deleting: %w", env.Name, proxyJSONRequestForEnvironmentErr)
}
if result.InUse {
return fmt.Errorf("still referenced by environment %s", env.Name)
@@ -278,16 +287,16 @@ func (s *EnvironmentService) proxyJSONRequestForTargetInternal(
if err != nil {
return err
}
- if err := resp.RequireSuccess(); err != nil {
- return err
+ if requireSuccessErr := resp.RequireSuccess(); requireSuccessErr != nil {
+ return requireSuccessErr
}
// This is the erased decode behind the RemoteJSONProxy func-value seam;
// typed callers go through RemoteJSONProxy.JSON or remenv's generic decode.
if out == nil {
return nil
}
- if err := json.Unmarshal(resp.Body, out); err != nil {
- return &remenv.DecodeError{Err: err}
+ if unmarshalErr := json.Unmarshal(resp.Body, out); unmarshalErr != nil {
+ return &remenv.DecodeError{Err: unmarshalErr}
}
return nil
@@ -479,15 +488,15 @@ func (s *EnvironmentService) fanOutSyncToEnvironment[Model, Item, Request any](
}
var records []Model
- if err := s.db.WithContext(ctx).Find(&records).Error; err != nil {
- return fmt.Errorf("failed to get %s: %w", kind, err)
+ if loadRecordsErr := s.db.WithContext(ctx).Find(&records).Error; loadRecordsErr != nil {
+ return fmt.Errorf("failed to get %s: %w", kind, loadRecordsErr)
}
syncItems := make([]Item, 0, len(records))
for _, record := range records {
- item, keep, err := toSyncItem(record)
- if err != nil {
- return err
+ item, keep, toSyncItemErr := toSyncItem(record)
+ if toSyncItemErr != nil {
+ return toSyncItemErr
}
if keep {
syncItems = append(syncItems, item)
@@ -522,8 +531,8 @@ func (s *EnvironmentService) fanOutSyncToEnvironment[Model, Item, Request any](
Message string `json:"message"`
} `json:"data"`
}
- if err := s.proxyJSONRequestForTargetInternal(reqCtx, target, http.MethodPost, path, reqBody, &result); err != nil {
- return fmt.Errorf("failed to send sync request: %w", err)
+ if proxyJSONRequestForTargetErr := s.proxyJSONRequestForTargetInternal(reqCtx, target, http.MethodPost, path, reqBody, &result); proxyJSONRequestForTargetErr != nil {
+ return fmt.Errorf("failed to send sync request: %w", proxyJSONRequestForTargetErr)
}
if !result.Success {
diff --git a/backend/internal/environment/environment_swarm_nodes.go b/backend/internal/environment/environment_swarm_nodes.go
index 7d2c0e1fa..31f8d3886 100644
--- a/backend/internal/environment/environment_swarm_nodes.go
+++ b/backend/internal/environment/environment_swarm_nodes.go
@@ -175,13 +175,13 @@ func (s *EnvironmentService) applySwarmNodeAgentApiKeyInternal(
return "", fmt.Errorf("failed to create environment API key: %w", err)
}
- if err := s.RegenerateEnvironmentApiKey(ctx, env.ID, apiKeyDto.ID, apiKeyDto.Key, userID, username, env.Name); err != nil {
+ if regenerateEnvironmentApiKeyErr := s.RegenerateEnvironmentApiKey(ctx, env.ID, apiKeyDto.ID, apiKeyDto.Key, userID, username, env.Name); regenerateEnvironmentApiKeyErr != nil {
// The new key was never linked; remove it so a failed rotation does
// not leave an orphaned valid credential behind.
if delErr := s.apiKeyService.DeleteApiKey(ctx, apiKeyDto.ID); delErr != nil && !errors.Is(delErr, apikey.ErrApiKeyNotFound) {
slog.ErrorContext(ctx, "Failed to clean up unlinked environment API key", "environmentID", env.ID, "error", delErr.Error())
}
- return "", err
+ return "", regenerateEnvironmentApiKeyErr
}
// Delete the previous key only after the environment points at the new
@@ -190,8 +190,8 @@ func (s *EnvironmentService) applySwarmNodeAgentApiKeyInternal(
// remains a valid credential until deleted, so log it as an error; the key
// stays visible and deletable on the API Keys page.
if oldApiKeyID != nil && *oldApiKeyID != apiKeyDto.ID {
- if err := s.apiKeyService.DeleteApiKey(ctx, *oldApiKeyID); err != nil && !errors.Is(err, apikey.ErrApiKeyNotFound) {
- slog.ErrorContext(ctx, "Failed to delete previous environment API key; the old key remains valid until deleted manually", "environmentID", env.ID, "error", err.Error())
+ if deleteApiKeyErr := s.apiKeyService.DeleteApiKey(ctx, *oldApiKeyID); deleteApiKeyErr != nil && !errors.Is(deleteApiKeyErr, apikey.ErrApiKeyNotFound) {
+ slog.ErrorContext(ctx, "Failed to delete previous environment API key; the old key remains valid until deleted manually", "environmentID", env.ID, "error", deleteApiKeyErr.Error())
}
}
diff --git a/backend/internal/environment/environment_sync_test.go b/backend/internal/environment/environment_sync_test.go
index e67448b15..8b54cbe26 100644
--- a/backend/internal/environment/environment_sync_test.go
+++ b/backend/internal/environment/environment_sync_test.go
@@ -31,7 +31,17 @@ func setupSyncDBInternal(t *testing.T) *database.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "sync.db")), &gorm.Config{})
require.NoError(t, err)
- require.NoError(t, db.AutoMigrate(&environment.Environment{}, &registry.ContainerRegistry{}, &gitrepo.GitRepository{}, &s3domain.S3Destination{}, &activity.Activity{}, &activity.ActivityMessage{}))
+ require.NoError(
+ t,
+ db.AutoMigrate(
+ &environment.Environment{},
+ &registry.ContainerRegistry{},
+ &gitrepo.GitRepository{},
+ &s3domain.S3Destination{},
+ &activity.Activity{},
+ &activity.ActivityMessage{},
+ ),
+ )
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
@@ -145,7 +155,7 @@ func TestSyncCredentialDecryptionAbortsSnapshot(t *testing.T) {
err := syncResource(t.Context(), "remote")
require.Error(t, err)
require.Contains(t, err.Error(), "bad-credential")
- require.NotNil(t, errors.Unwrap(err))
+ require.Error(t, errors.Unwrap(err))
require.Zero(t, calls.Load(), "an incomplete snapshot must never reach the agent")
})
}
@@ -192,30 +202,30 @@ func TestSyncSkipsUnchangedPayloadUntilForgotten(t *testing.T) {
require.NoError(t, db.Create(&registry.ContainerRegistry{ID: "ghcr", URL: "ghcr.io", RegistryType: registry.RegistryTypeGeneric, Username: "user", Token: token}).Error)
require.NoError(t, db.Create(&environment.Environment{ID: "remote", ApiUrl: server.URL, AccessToken: new("agent-token")}).Error)
service := environment.NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)
- sync := func() error { return service.SyncRegistriesToEnvironment(t.Context(), "remote") }
+ localSync := func() error { return service.SyncRegistriesToEnvironment(t.Context(), "remote") }
changeRegistry := func(url string) {
require.NoError(t, db.Model(&registry.ContainerRegistry{}).Where("id = ?", "ghcr").Update("url", url).Error)
}
- require.NoError(t, sync())
- require.NoError(t, sync())
+ require.NoError(t, localSync())
+ require.NoError(t, localSync())
require.EqualValues(t, 1, calls.Load(), "an unchanged payload is not resent")
changeRegistry("ghcr.io/v2")
- require.NoError(t, sync())
+ require.NoError(t, localSync())
require.EqualValues(t, 2, calls.Load(), "a changed payload is resent")
service.ForgetSyncState("remote")
- require.NoError(t, sync())
+ require.NoError(t, localSync())
require.EqualValues(t, 3, calls.Load(), "forgetting forces a resend")
reject.Store(true)
changeRegistry("ghcr.io/v3")
- require.Error(t, sync())
+ require.Error(t, localSync())
require.EqualValues(t, 4, calls.Load())
reject.Store(false)
- require.NoError(t, sync())
+ require.NoError(t, localSync())
require.EqualValues(t, 5, calls.Load(), "a rejected payload is retried")
- require.NoError(t, sync())
+ require.NoError(t, localSync())
require.EqualValues(t, 5, calls.Load(), "an accepted payload is remembered")
}
diff --git a/backend/internal/environment/handler.go b/backend/internal/environment/handler.go
index 859c62eb1..3ed631009 100644
--- a/backend/internal/environment/handler.go
+++ b/backend/internal/environment/handler.go
@@ -154,7 +154,14 @@ type DownloadEnvironmentMTLSFileInput struct {
// ============================================================================
// NewHandler builds the environment HTTP handler and its stream producer.
-func NewHandler(environmentService *EnvironmentService, settingsService *settings.SettingsService, apiKeyService *apikey.ApiKeyService, eventService *event.EventService, cfg *config.Config, activityService activitylib.Service) *EnvironmentHandler {
+func NewHandler(
+ environmentService *EnvironmentService,
+ settingsService *settings.SettingsService,
+ apiKeyService *apikey.ApiKeyService,
+ eventService *event.EventService,
+ cfg *config.Config,
+ activityService activitylib.Service,
+) *EnvironmentHandler {
return &EnvironmentHandler{
environmentService: environmentService,
settingsService: settingsService,
@@ -672,7 +679,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
// If regenerating API key, return the new key
var newApiKey *string
if input.Body.RegenerateApiKey != nil && *input.Body.RegenerateApiKey {
- user, err := handlerutil.RequireUser(ctx)
+ localUser, err := handlerutil.RequireUser(ctx)
if err != nil {
return nil, err
}
@@ -688,7 +695,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
// Use service method to update environment and create event
apiKey := apiKeyDto.Key
- err = h.environmentService.RegenerateEnvironmentApiKey(ctx, input.ID, apiKeyDto.ID, apiKey, user.ID, user.Username, updated.Name)
+ err = h.environmentService.RegenerateEnvironmentApiKey(ctx, input.ID, apiKeyDto.ID, apiKey, localUser.ID, localUser.Username, updated.Name)
if err != nil {
// The new key was never linked; remove it so a failed rotation does
// not leave an orphaned valid credential behind.
@@ -706,8 +713,8 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
// it as an error; the key stays visible and deletable on the API Keys
// page.
if oldApiKeyID != nil && *oldApiKeyID != apiKeyDto.ID {
- if err := h.apiKeyService.DeleteApiKey(ctx, *oldApiKeyID); err != nil && !errors.Is(err, apikey.ErrApiKeyNotFound) {
- slog.ErrorContext(ctx, "Failed to delete previous environment API key; the old key remains valid until deleted manually", "environmentID", input.ID, "error", err.Error())
+ if deleteApiKeyErr := h.apiKeyService.DeleteApiKey(ctx, *oldApiKeyID); deleteApiKeyErr != nil && !errors.Is(deleteApiKeyErr, apikey.ErrApiKeyNotFound) {
+ slog.ErrorContext(ctx, "Failed to delete previous environment API key; the old key remains valid until deleted manually", "environmentID", input.ID, "error", deleteApiKeyErr.Error())
}
}
@@ -1104,15 +1111,15 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
}
}
- statusCode, respBody, err := edge.DoRequest(reqCtx, input.ID, http.MethodGet, "/api/app-version", nil)
- if err != nil {
- return nil, huma.Error500InternalServerError("Request via tunnel failed: " + err.Error())
+ statusCode, respBody, doRequestErr := edge.DoRequest(reqCtx, input.ID, http.MethodGet, "/api/app-version", nil)
+ if doRequestErr != nil {
+ return nil, huma.Error500InternalServerError("Request via tunnel failed: " + doRequestErr.Error())
}
if statusCode != http.StatusOK {
return nil, huma.Error500InternalServerError(fmt.Sprintf("Unexpected status code: %d", statusCode))
}
- if err := json.Unmarshal(respBody, &versionInfo); err != nil {
+ if unmarshalErr := json.Unmarshal(respBody, &versionInfo); unmarshalErr != nil {
return nil, huma.Error500InternalServerError("Failed to decode version response")
}
} else {
@@ -1125,15 +1132,15 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
validatedURL.Fragment = ""
validatedURL.Path = strings.TrimRight(validatedURL.Path, "/") + "/api/app-version"
- req, err := http.NewRequestWithContext(reqCtx, http.MethodGet, validatedURL.String(), nil)
- if err != nil {
+ req, newRequestWithContextErr := http.NewRequestWithContext(reqCtx, http.MethodGet, validatedURL.String(), http.NoBody)
+ if newRequestWithContextErr != nil {
return nil, huma.Error500InternalServerError("Failed to create request")
}
client := &http.Client{Timeout: 15 * time.Second}
- resp, err := client.Do(req)
- if err != nil {
- return nil, huma.Error500InternalServerError("Request failed: " + err.Error())
+ resp, newRequestWithContextErr := client.Do(req)
+ if newRequestWithContextErr != nil {
+ return nil, huma.Error500InternalServerError("Request failed: " + newRequestWithContextErr.Error())
}
defer func() { _ = resp.Body.Close() }()
@@ -1141,7 +1148,7 @@ func (h *EnvironmentHandler) GetEnvironmentVersion(ctx context.Context, input *G
return nil, huma.Error500InternalServerError(fmt.Sprintf("Unexpected status code: %d", resp.StatusCode))
}
- if err := json.UnmarshalRead(resp.Body, &versionInfo); err != nil {
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &versionInfo); unmarshalReadErr != nil {
return nil, huma.Error500InternalServerError("Failed to decode version response")
}
}
@@ -1238,8 +1245,8 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context,
}
}
- if err := zipWriter.Close(); err != nil {
- slog.ErrorContext(ctx, "Failed to finalize mTLS bundle", "environmentID", input.ID, "error", err.Error())
+ if closeErr := zipWriter.Close(); closeErr != nil {
+ slog.ErrorContext(ctx, "Failed to finalize mTLS bundle", "environmentID", input.ID, "error", closeErr.Error())
return nil, huma.Error500InternalServerError("Failed to build mTLS bundle")
}
@@ -1252,7 +1259,20 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context,
humaCtx.SetHeader("Content-Length", strconv.Itoa(archive.Len()))
if written, writeErr := humaCtx.BodyWriter().Write(archive.Bytes()); writeErr != nil || written != archive.Len() {
- slog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS bundle download", "environmentID", input.ID, "fileName", fileName, "bytesWritten", written, "bytesExpected", archive.Len(), "error", writeErr)
+ slog.WarnContext(
+ humaCtx.Context(),
+ "Failed to stream edge mTLS bundle download",
+ "environmentID",
+ input.ID,
+ "fileName",
+ fileName,
+ "bytesWritten",
+ written,
+ "bytesExpected",
+ archive.Len(),
+ "error",
+ writeErr,
+ )
return
}
h.logMTLSAuditEventInternal(humaCtx.Context(), env, event.EventTypeEnvironmentMTLSDownload,
@@ -1283,7 +1303,22 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSFile(ctx context.Context, in
humaCtx.SetHeader("Content-Length", strconv.Itoa(len(fileContent)))
if written, writeErr := humaCtx.BodyWriter().Write(fileContent); writeErr != nil || written != len(fileContent) {
- slog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS asset download", "environmentID", input.ID, "fileName", file.Name, "bytesWritten", written, "bytesExpected", len(fileContent), "error", writeErr)
+ slog.WarnContext(
+ humaCtx.Context(),
+ "Failed to stream edge mTLS asset download",
+ "environmentID",
+ input.ID,
+ "fileName",
+ file.Name,
+ "bytesWritten",
+ written,
+ "bytesExpected",
+ len(
+ fileContent,
+ ),
+ "error",
+ writeErr,
+ )
return
}
h.logMTLSAuditEventInternal(humaCtx.Context(), env, event.EventTypeEnvironmentMTLSDownload,
diff --git a/backend/internal/environment/module.go b/backend/internal/environment/module.go
index bfe7f99d1..5faffc183 100644
--- a/backend/internal/environment/module.go
+++ b/backend/internal/environment/module.go
@@ -18,7 +18,14 @@ type Module struct {
handler *EnvironmentHandler
}
-func New(service *EnvironmentService, settingsService *settings.SettingsService, apiKey *apikey.ApiKeyService, eventService *event.EventService, cfg *config.Config, activityService activitylib.Service) *Module {
+func New(
+ service *EnvironmentService,
+ settingsService *settings.SettingsService,
+ apiKey *apikey.ApiKeyService,
+ eventService *event.EventService,
+ cfg *config.Config,
+ activityService activitylib.Service,
+) *Module {
return &Module{
service: service,
handler: NewHandler(service, settingsService, apiKey, eventService, cfg, activityService),
diff --git a/backend/internal/environment/service_test.go b/backend/internal/environment/service_test.go
index 22338444a..6c0ee4d49 100644
--- a/backend/internal/environment/service_test.go
+++ b/backend/internal/environment/service_test.go
@@ -52,7 +52,9 @@ func TestEnvironmentService_OverlappingHealthCheckIsSkippedInternal(t *testing.T
service := &EnvironmentService{jobs: entityjobs.New(environmentHealthJobPrefix, environmentHealthAdmissionScopeInternal)}
require.NoError(t, service.SetScheduler(t.Context(), &environmentTestSchedulerInternal{}, gate))
- service.runHealthCheckInternal(t.Context(), "environment-id")
+ outcome, runErr := service.runHealthCheckInternal(t.Context(), "environment-id")
+ require.NoError(t, runErr)
+ require.Equal(t, schedulertypes.Skipped, outcome.Status)
lease.Release(t.Context())
}
@@ -145,12 +147,12 @@ func setupEnvironmentServiceTestDB(t *testing.T) *database.DB {
func createTestEnvironmentServiceUser(t *testing.T, ctx context.Context, userService *user.UserService, id string) *common.User {
t.Helper()
- user := &common.User{
+ localUser := &common.User{
ID: id,
- Username: fmt.Sprintf("user-%s", id),
+ Username: "user-" + id,
}
- created, err := userService.CreateUser(ctx, user)
+ created, err := userService.CreateUser(ctx, localUser)
require.NoError(t, err)
return created
}
@@ -175,7 +177,7 @@ func createNamedTestEnvironmentInternal(t *testing.T, db *database.DB, id, name,
AccessToken: accessToken,
}
- require.NoError(t, db.WithContext(context.Background()).Create(env).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(env).Error)
}
func createTestEnvironmentWithState(t *testing.T, db *database.DB, id, apiURL, status string, isEdge bool, accessToken *string) {
@@ -194,11 +196,11 @@ func createTestEnvironmentWithState(t *testing.T, db *database.DB, id, apiURL, s
AccessToken: accessToken,
}
- require.NoError(t, db.WithContext(context.Background()).Create(env).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(env).Error)
}
func TestEnvironmentService_DeleteEnvironment_CascadesGitOpsSyncs(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
require.NoError(t, db.AutoMigrate(&testProjectRow{}, &testGitOpsSyncRow{}))
@@ -244,7 +246,7 @@ func createTestRegistry(t *testing.T, db *database.DB, id string) {
require.NoError(t, err)
now := time.Now()
- registry := &registry.ContainerRegistry{
+ localRegistry := &registry.ContainerRegistry{
BaseModel: database.BaseModel{
ID: id,
CreatedAt: now,
@@ -260,7 +262,7 @@ func createTestRegistry(t *testing.T, db *database.DB, id string) {
UpdatedAt: now,
}
- require.NoError(t, db.WithContext(context.Background()).Create(registry).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(localRegistry).Error)
}
func createTestECRRegistry(t *testing.T, db *database.DB, id string) {
@@ -270,7 +272,7 @@ func createTestECRRegistry(t *testing.T, db *database.DB, id string) {
require.NoError(t, err)
now := time.Now()
- registry := &registry.ContainerRegistry{
+ localRegistry := &registry.ContainerRegistry{
BaseModel: database.BaseModel{
ID: id,
CreatedAt: now,
@@ -286,7 +288,7 @@ func createTestECRRegistry(t *testing.T, db *database.DB, id string) {
UpdatedAt: now,
}
- require.NoError(t, db.WithContext(context.Background()).Create(registry).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(localRegistry).Error)
}
func createTestGitRepository(t *testing.T, db *database.DB, repository gitrepo.GitRepository) {
@@ -302,7 +304,7 @@ func encryptSecretForTest(t *testing.T, value string) string {
}
func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SyncsEligibleRemotes(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -379,7 +381,7 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SyncsEligibleRemo
}
func TestEnvironmentService_SyncRegistriesToEnvironment_IncludesECRFields(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -436,7 +438,7 @@ func TestEnvironmentService_SyncRegistriesToEnvironment_IncludesECRFields(t *tes
}
func TestEnvironmentService_SyncS3DestinationsToEnvironment(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -457,17 +459,35 @@ func TestEnvironmentService_SyncS3DestinationsToEnvironment(t *testing.T) {
accessToken := "agent-token"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Equal(t, http.MethodPost, r.Method)
- require.Equal(t, "/api/backups/s3/sync", r.URL.Path)
- require.Equal(t, accessToken, r.Header.Get("X-API-Key"))
- require.Equal(t, accessToken, r.Header.Get("X-Arcane-Agent-Token"))
+ if !assert.Equal(t, http.MethodPost, r.Method) {
+ return
+ }
+ if !assert.Equal(t, "/api/backups/s3/sync", r.URL.Path) {
+ return
+ }
+ if !assert.Equal(t, accessToken, r.Header.Get("X-API-Key")) {
+ return
+ }
+ if !assert.Equal(t, accessToken, r.Header.Get("X-Arcane-Agent-Token")) {
+ return
+ }
var syncReq backuptypes.S3DestinationSyncRequest
- require.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq))
- require.Len(t, syncReq.Destinations, 1)
- require.Equal(t, "s3-1", syncReq.Destinations[0].ID)
- require.Equal(t, "s3-secret", syncReq.Destinations[0].SecretAccessKey)
- require.Equal(t, "volume-backups", syncReq.Destinations[0].Bucket)
+ if !assert.NoError(t, json.NewDecoder(r.Body).Decode(&syncReq)) {
+ return
+ }
+ if !assert.Len(t, syncReq.Destinations, 1) {
+ return
+ }
+ if !assert.Equal(t, "s3-1", syncReq.Destinations[0].ID) {
+ return
+ }
+ if !assert.Equal(t, "s3-secret", syncReq.Destinations[0].SecretAccessKey) {
+ return
+ }
+ if !assert.Equal(t, "volume-backups", syncReq.Destinations[0].Bucket) {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"success":true,"data":{"message":"ok"}}`))
@@ -479,7 +499,7 @@ func TestEnvironmentService_SyncS3DestinationsToEnvironment(t *testing.T) {
}
func TestEnvironmentService_SyncRepositoriesToEnvironment_UsesAgentHeaders(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
require.NoError(t, db.AutoMigrate(&gitrepo.GitRepository{}))
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -536,7 +556,7 @@ func TestEnvironmentService_SyncRepositoriesToEnvironment_UsesAgentHeaders(t *te
}
func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SkipsRemoteWithoutAccessToken(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -559,7 +579,7 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_SkipsRemoteWithou
}
func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_ReportsFailuresButContinues(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -583,7 +603,7 @@ func TestEnvironmentService_SyncRegistriesToRemoteEnvironments_ReportsFailuresBu
}
func TestEnvironmentService_ReconcileEdgeStatusesOnStartup(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -613,7 +633,7 @@ func TestEnvironmentService_ReconcileEdgeStatusesOnStartup(t *testing.T) {
}
func TestEnvironmentService_UpdateEnvironmentConnectionState(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -639,7 +659,7 @@ func TestEnvironmentService_UpdateEnvironmentConnectionState(t *testing.T) {
}
func TestEnvironmentService_UpdateEnvironmentStatusInternal_PromotesPendingDirectEnv(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -654,7 +674,7 @@ func TestEnvironmentService_UpdateEnvironmentStatusInternal_PromotesPendingDirec
}
func TestEnvironmentService_UpdateEnvironmentStatusInternal_DoesNotDemotePendingDirectEnvOnFailedTick(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -673,7 +693,7 @@ func TestEnvironmentService_UpdateEnvironmentStatusInternal_DoesNotDemotePending
}
func TestEnvironmentService_UpdateEnvironmentStatusInternal_LeavesPendingEdgeEnvAlone(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -690,7 +710,7 @@ func TestEnvironmentService_UpdateEnvironmentStatusInternal_LeavesPendingEdgeEnv
}
func TestEnvironmentService_ResolveEdgeEnvironmentByToken_CachesAndInvalidatesOnUpdate(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -720,7 +740,7 @@ func TestEnvironmentService_ResolveEdgeEnvironmentByToken_CachesAndInvalidatesOn
}
func TestEnvironmentService_UpdateEnvironment_ClearingAccessTokenInvalidatesCache(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -752,7 +772,7 @@ func TestEnvironmentService_UpdateEnvironment_ClearingAccessTokenInvalidatesCach
}
func TestEnvironmentServiceUpdateEnvironmentRejectsTargetChangeWithStoredTokenInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -824,7 +844,7 @@ func TestEnvironmentService_getCachedEnvironmentIDForTokenInternal_ExpiresAndCle
}
func TestEnvironmentService_ResolveEnvironmentByAccessToken(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -845,7 +865,7 @@ func TestEnvironmentService_ResolveEnvironmentByAccessToken(t *testing.T) {
func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTransport(t *testing.T) {
svc := NewEnvironmentService(nil, nil, nil, nil, nil, nil)
- standard, err := svc.GenerateDeploymentSnippets(context.Background(), "env-1", "https://manager.example.com", "https://agent.example.com", "token-123")
+ standard, err := svc.GenerateDeploymentSnippets(t.Context(), "env-1", "https://manager.example.com", "https://agent.example.com", "token-123")
require.NoError(t, err)
require.NotNil(t, standard)
require.NotContains(t, standard.DockerRun, "EDGE_TRANSPORT=websocket")
@@ -857,7 +877,7 @@ func TestEnvironmentService_GenerateDeploymentSnippets_ExplicitlyUsePollTranspor
require.Contains(t, standard.DockerCompose, "- arcane-data:/app/data")
require.NotContains(t, standard.DockerRun, "-v arcane-data:/data")
- edgeSnippets, err := svc.GenerateEdgeDeploymentSnippets(context.Background(), "env-2", "https://manager.example.com", "token-456", nil)
+ edgeSnippets, err := svc.GenerateEdgeDeploymentSnippets(t.Context(), "env-2", "https://manager.example.com", "token-456", nil)
require.NoError(t, err)
require.NotNil(t, edgeSnippets)
require.NotContains(t, edgeSnippets.DockerRun, "EDGE_TRANSPORT=websocket")
@@ -928,20 +948,20 @@ func TestAgentHostPortInternal(t *testing.T) {
}
func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesVisibleEnvironmentAndReusesToken(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
userService := user.NewUserService(db, nil)
apiKeyService := apikey.NewApiKeyService(db, userService, nil)
svc := NewEnvironmentService(db, nil, nil, nil, nil, apiKeyService)
- user := createTestEnvironmentServiceUser(t, ctx, userService, "swarm-admin")
+ localUser := createTestEnvironmentServiceUser(t, ctx, userService, "swarm-admin")
createdEnv, createdToken, err := svc.EnsureSwarmNodeAgentEnvironment(
ctx,
"manager-env",
"node-1234567890abcdef",
"worker-1",
- user.ID,
- user.Username,
+ localUser.ID,
+ localUser.Username,
false,
)
require.NoError(t, err)
@@ -981,8 +1001,8 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesVisibleEnviro
"manager-env",
"node-1234567890abcdef",
"worker-1",
- user.ID,
- user.Username,
+ localUser.ID,
+ localUser.Username,
false,
)
require.NoError(t, err)
@@ -1000,7 +1020,7 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesVisibleEnviro
}
func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRegistration(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
parentEnvironmentID := "manager-env"
@@ -1048,11 +1068,11 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRe
var environments []Environment
{
- err := db.WithContext(ctx).
+ operationErr := db.WithContext(ctx).
Where("parent_environment_id = ? AND swarm_node_id = ?", parentEnvironmentID, nodeID).
Find(&environments).Error
- require.NoError(t, err,
- "list node environments: %v", err)
+ require.NoError(t, operationErr,
+ "list node environments: %v", operationErr)
}
require.Len(t, environments, 1,
@@ -1068,20 +1088,20 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRe
// transformation (trim, encode, hash) were ever introduced between the
// command-generation path and the poll-validation path.
func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_TokenResolvesEndToEnd(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
userService := user.NewUserService(db, nil)
apiKeyService := apikey.NewApiKeyService(db, userService, nil)
svc := NewEnvironmentService(db, nil, nil, nil, nil, apiKeyService)
- user := createTestEnvironmentServiceUser(t, ctx, userService, "swarm-resolve-admin")
+ localUser := createTestEnvironmentServiceUser(t, ctx, userService, "swarm-resolve-admin")
createdEnv, createdToken, err := svc.EnsureSwarmNodeAgentEnvironment(
ctx,
"manager-env-resolve",
"node-resolve-1234567890",
"resolve-host",
- user.ID,
- user.Username,
+ localUser.ID,
+ localUser.Username,
false,
)
require.NoError(t, err)
@@ -1103,8 +1123,8 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_TokenResolvesEndToEn
"manager-env-resolve",
"node-resolve-1234567890",
"resolve-host",
- user.ID,
- user.Username,
+ localUser.ID,
+ localUser.Username,
true,
)
require.NoError(t, err)
@@ -1121,7 +1141,7 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_TokenResolvesEndToEn
}
func TestEnvironmentService_BindSwarmNodeEnvironment_PreservesVisibleEnvironmentToken(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
token := "existing-agent-token"
createTestEnvironment(t, db, "visible-env", "http://visible.example", &token)
@@ -1143,7 +1163,7 @@ func TestEnvironmentService_BindSwarmNodeEnvironment_PreservesVisibleEnvironment
}
func TestEnvironmentService_BindSwarmNodeEnvironment_RequiresExplicitRebind(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
createTestEnvironment(t, db, "visible-env", "http://visible.example", nil)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -1160,7 +1180,7 @@ func TestEnvironmentService_BindSwarmNodeEnvironment_RequiresExplicitRebind(t *t
}
func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -1195,7 +1215,7 @@ func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T)
}
func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByAccessibleEnvIDs(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -1238,7 +1258,7 @@ func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByAccessibleEnvIDs(
}
func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByRuntimeType(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -1378,7 +1398,7 @@ func TestEnvironmentService_GenerateEdgeDeploymentSnippets_WithAutoGeneratedMTLS
svc := NewEnvironmentService(nil, nil, nil, nil, nil, nil)
assetsDir := filepath.Join(t.TempDir(), "edge-mtls")
- snippets, err := svc.GenerateEdgeDeploymentSnippets(context.Background(), "env-mtls", "https://manager.example.com", "token-789", &edge.Config{
+ snippets, err := svc.GenerateEdgeDeploymentSnippets(t.Context(), "env-mtls", "https://manager.example.com", "token-789", &edge.Config{
EdgeMTLSMode: edge.EdgeMTLSModeRequired,
EdgeMTLSAssetsDir: assetsDir,
})
@@ -1412,7 +1432,7 @@ func TestEnvironmentService_GenerateEdgeDeploymentSnippets_ReturnsBasicSnippetsW
assetsPath := filepath.Join(t.TempDir(), "edge-mtls-file")
require.NoError(t, os.WriteFile(assetsPath, []byte("not a directory"), 0o600))
- snippets, err := svc.GenerateEdgeDeploymentSnippets(context.Background(), "env-mtls", "https://manager.example.com", "token-789", &edge.Config{
+ snippets, err := svc.GenerateEdgeDeploymentSnippets(t.Context(), "env-mtls", "https://manager.example.com", "token-789", &edge.Config{
EdgeMTLSMode: edge.EdgeMTLSModeRequired,
EdgeMTLSAssetsDir: assetsPath,
})
@@ -1425,7 +1445,7 @@ func TestEnvironmentService_GenerateEdgeDeploymentSnippets_ReturnsBasicSnippetsW
}
func TestEnvironmentService_TestConnection_RejectsInvalidCustomURL(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -1442,7 +1462,7 @@ func TestEnvironmentServiceTestConnectionHidesCustomURLFailureInternal(t *testin
}))
t.Cleanup(server.Close)
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)
createTestEnvironment(t, db, "env-1", "http://stored.example", nil)
@@ -1459,7 +1479,7 @@ func TestEnvironmentServiceTestConnectionAllowsStoredPrivateURLInternal(t *testi
}))
t.Cleanup(server.Close)
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)
createTestEnvironment(t, db, "env-private", server.URL, nil)
@@ -1470,7 +1490,7 @@ func TestEnvironmentServiceTestConnectionAllowsStoredPrivateURLInternal(t *testi
}
func TestEnvironmentService_ExecuteRemoteRequest_RejectsInvalidEnvironmentURL(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEnvironmentServiceTestDB(t)
svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
diff --git a/backend/internal/event/docker_correlation_test.go b/backend/internal/event/docker_correlation_test.go
index 3ec7c6ea0..197753abc 100644
--- a/backend/internal/event/docker_correlation_test.go
+++ b/backend/internal/event/docker_correlation_test.go
@@ -108,7 +108,21 @@ func TestCreateEventCorrelationEligibility(t *testing.T) {
t.Run(tc.name, func(t *testing.T) {
db := setupEventServiceTestDB(t)
svc := NewEventService(db, nil, nil)
- _, err := svc.CreateEvent(t.Context(), CreateEventRequest{Type: tc.eventType, Title: "action", ResourceType: new(strings.SplitN(string(tc.eventType), ".", 2)[0]), ResourceID: new("id"), EnvironmentID: tc.environment, Metadata: database.JSON{"source": tc.source}})
+ _, err := svc.CreateEvent(
+ t.Context(),
+ CreateEventRequest{
+ Type: tc.eventType,
+ Title: "action",
+ ResourceType: new(strings.SplitN(
+ string(tc.eventType),
+ ".",
+ 2,
+ )[0]),
+ ResourceID: new("id"),
+ EnvironmentID: tc.environment,
+ Metadata: database.JSON{"source": tc.source},
+ },
+ )
require.NoError(t, err)
require.Equal(t, tc.want, svc.ShouldSuppressDaemonEvent(strings.SplitN(string(tc.eventType), ".", 2)[0], "id", "", ""))
})
diff --git a/backend/internal/event/docker_events_test.go b/backend/internal/event/docker_events_test.go
index 0f7bfee3d..142662066 100644
--- a/backend/internal/event/docker_events_test.go
+++ b/backend/internal/event/docker_events_test.go
@@ -9,6 +9,7 @@ import (
"time"
"github.com/moby/moby/api/types/events"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
kit "go.getarcane.app/kit/pkg"
"go.getarcane.app/streams/bus"
@@ -54,14 +55,44 @@ func TestMapDaemonEventInternal(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- req, ok := mapDaemonEventInternal(events.Message{Type: tc.kind, Action: tc.action, Scope: "local", Actor: events.Actor{ID: "resource-id", Attributes: map[string]string{"name": "web", "image": "alpine", "exitCode": "0", "signal": "15", "com.docker.compose.project": "demo", "com.docker.compose.service": "web", "secret": "never-copy"}}})
+ req, ok := mapDaemonEventInternal(events.Message{
+ Type: tc.kind,
+ Action: tc.action,
+ Scope: "local",
+ Actor: events.Actor{
+ ID: "resource-id",
+ Attributes: map[string]string{
+ "name": "web",
+ "image": "alpine",
+ "exitCode": "0",
+ "signal": "15",
+ "com.docker.compose.project": "demo",
+ "com.docker.compose.service": "web",
+ "secret": "never-copy",
+ },
+ },
+ })
require.True(t, ok)
require.Equal(t, tc.want, req.Type)
require.Equal(t, "web", *req.ResourceName)
require.Equal(t, "0", *req.EnvironmentID)
require.Nil(t, req.UserID)
require.Nil(t, req.Username)
- require.Equal(t, database.JSON{"source": "docker", "action": string(tc.action), "scope": "local", "name": "web", "image": "alpine", "exitCode": "0", "signal": "15", "composeProject": "demo", "composeService": "web"}, req.Metadata)
+ require.Equal(
+ t,
+ database.JSON{
+ "source": "docker",
+ "action": string(tc.action),
+ "scope": "local",
+ "name": "web",
+ "image": "alpine",
+ "exitCode": "0",
+ "signal": "15",
+ "composeProject": "demo",
+ "composeService": "web",
+ },
+ req.Metadata,
+ )
severity := kit.Ternary(tc.action == events.ActionOOM, EventSeverityError, EventSeverityInfo)
if tc.action == events.ActionHealthStatusUnhealthy {
severity = EventSeverityWarning
@@ -71,7 +102,14 @@ func TestMapDaemonEventInternal(t *testing.T) {
}
for _, exitCode := range []string{"1", "137", ""} {
t.Run("die exit "+exitCode, func(t *testing.T) {
- req, ok := mapDaemonEventInternal(events.Message{Type: events.ContainerEventType, Action: events.ActionDie, Actor: events.Actor{ID: "id", Attributes: map[string]string{"exitCode": exitCode}}})
+ req, ok := mapDaemonEventInternal(events.Message{
+ Type: events.ContainerEventType,
+ Action: events.ActionDie,
+ Actor: events.Actor{
+ ID: "id",
+ Attributes: map[string]string{"exitCode": exitCode},
+ },
+ })
require.True(t, ok)
require.Equal(t, EventSeverityWarning, req.Severity)
require.Equal(t, "id", *req.ResourceName)
@@ -90,7 +128,52 @@ func TestMapDaemonEventInternal(t *testing.T) {
action events.Action
id string
}{
- {"exec", events.ContainerEventType, "exec_create", "id"}, {"attach", events.ContainerEventType, "attach", "id"}, {"resize", events.ContainerEventType, "resize", "id"}, {"healthy", events.ContainerEventType, "health_status: healthy", "id"}, {"mount", events.VolumeEventType, "mount", "id"}, {"connect", events.NetworkEventType, "connect", "id"}, {"disconnect", events.NetworkEventType, "disconnect", "id"}, {"unknown action", events.ImageEventType, "unknown-image-action", "image-id"}, {"empty create", events.ContainerEventType, events.ActionCreate, ""},
+ {
+ "exec",
+ events.ContainerEventType,
+ "exec_create",
+ "id",
+ }, {
+ "attach",
+ events.ContainerEventType,
+ "attach",
+ "id",
+ }, {
+ "resize",
+ events.ContainerEventType,
+ "resize",
+ "id",
+ }, {
+ "healthy",
+ events.ContainerEventType,
+ "health_status: healthy",
+ "id",
+ }, {
+ "mount",
+ events.VolumeEventType,
+ "mount",
+ "id",
+ }, {
+ "connect",
+ events.NetworkEventType,
+ "connect",
+ "id",
+ }, {
+ "disconnect",
+ events.NetworkEventType,
+ "disconnect",
+ "id",
+ }, {
+ "unknown action",
+ events.ImageEventType,
+ "unknown-image-action",
+ "image-id",
+ }, {
+ "empty create",
+ events.ContainerEventType,
+ events.ActionCreate,
+ "",
+ },
} {
t.Run(tc.name, func(t *testing.T) {
_, ok := mapDaemonEventInternal(events.Message{Type: tc.kind, Action: tc.action, Actor: events.Actor{ID: tc.id}})
@@ -129,7 +212,10 @@ func TestDaemonSuppressionAndFailureAllowLaterObservations(t *testing.T) {
svc.dockerCorrelation.now = func() time.Time { return now }
msg := events.Message{Type: events.ContainerEventType, Action: events.ActionStart, TimeNano: 123, Actor: events.Actor{ID: "web"}}
if failure {
- require.NoError(t, db.Callback().Create().Before("gorm:create").Register("daemon_failure", func(tx *gorm.DB) { tx.AddError(errors.New("unavailable")) }))
+ require.NoError(t, db.Callback().Create().Before("gorm:create").Register("daemon_failure", func(tx *gorm.DB) {
+ failureErr := errors.New("unavailable")
+ require.ErrorIs(t, tx.AddError(failureErr), failureErr)
+ }))
}
if !failure {
svc.MarkDockerExpectation("container", "web", "")
@@ -154,7 +240,7 @@ func TestDockerEventSubscriptionsReadyAndStop(t *testing.T) {
db := setupEventServiceTestDB(t)
sqlDB, err := db.DB.DB()
require.NoError(t, err)
- defer sqlDB.Close()
+ defer func() { assert.NoError(t, sqlDB.Close()) }()
sqlDB.SetMaxOpenConns(1)
svc := NewEventService(db, nil, nil)
var recovered, published atomic.Int64
diff --git a/backend/internal/event/handler.go b/backend/internal/event/handler.go
index 5df43569c..3bb6e9a3e 100644
--- a/backend/internal/event/handler.go
+++ b/backend/internal/event/handler.go
@@ -83,7 +83,7 @@ func RegisterAgentEventIngestion(g *echo.Group, eventService *EventService, reso
}
var input CreateEventRequest
- if err := json.UnmarshalRead(http.MaxBytesReader(c.Response(), c.Request().Body, 1<<20), &input); err != nil {
+ if unmarshalReadErr := json.UnmarshalRead(http.MaxBytesReader(c.Response(), c.Request().Body, 1<<20), &input); unmarshalReadErr != nil {
return c.JSON(http.StatusBadRequest, base.ApiResponse[base.MessageResponse]{
Success: false,
Data: base.MessageResponse{Message: "invalid event payload"},
@@ -96,10 +96,10 @@ func RegisterAgentEventIngestion(g *echo.Group, eventService *EventService, reso
})
}
- if _, err := eventService.IngestAgentEvent(c.Request().Context(), environmentID, input); err != nil {
+ if _, ingestAgentEventErr := eventService.IngestAgentEvent(c.Request().Context(), environmentID, input); ingestAgentEventErr != nil {
return c.JSON(http.StatusInternalServerError, base.ApiResponse[base.MessageResponse]{
Success: false,
- Data: base.MessageResponse{Message: "Failed to create event: " + err.Error()},
+ Data: base.MessageResponse{Message: "Failed to create event: " + ingestAgentEventErr.Error()},
})
}
diff --git a/backend/internal/event/service_test.go b/backend/internal/event/service_test.go
index ccee0edbe..ac13e69d4 100644
--- a/backend/internal/event/service_test.go
+++ b/backend/internal/event/service_test.go
@@ -1,7 +1,6 @@
package event
import (
- "context"
"encoding/json"
"errors"
"net/http"
@@ -78,7 +77,7 @@ func TestCreateEventRequestJSONOmitempty(t *testing.T) {
}
func TestEventService_LogEventsPersistOptionalPointers(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEventServiceTestDB(t)
svc := NewEventService(db, nil, nil)
@@ -152,7 +151,7 @@ func TestCloneEventMetadataInternal(t *testing.T) {
}
func TestEventService_LogErrorEvent_DoesNotMutateInputMetadata(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEventServiceTestDB(t)
svc := NewEventService(db, nil, nil)
@@ -182,7 +181,7 @@ func TestEventService_LogErrorEvent_DoesNotMutateInputMetadata(t *testing.T) {
}
func TestEventService_CreateEvent_ForwardsToManagerAPIInAgentMode(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEventServiceTestDB(t)
requests := make(chan CreateEventRequest, 1)
@@ -243,7 +242,7 @@ func TestEventService_CreateEvent_ForwardsToManagerAPIInAgentMode(t *testing.T)
}
func TestEventService_CreateEvent_NormalizesActor(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEventServiceTestDB(t)
svc := NewEventService(db, nil, nil)
@@ -290,7 +289,7 @@ func TestEventService_CreateEvent_NormalizesActor(t *testing.T) {
}
func TestEventService_GetEventSeverityCounts(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEventServiceTestDB(t)
svc := NewEventService(db, nil, nil)
@@ -315,7 +314,7 @@ func TestEventService_GetEventSeverityCounts(t *testing.T) {
}
func TestEventService_ListEventsPaginated_TypeCategoryFilter(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupEventServiceTestDB(t)
svc := NewEventService(db, nil, nil)
@@ -351,7 +350,17 @@ func TestIngestAgentEventAuthenticatedEnvironment(t *testing.T) {
t.Run("payload environment "+supplied, func(t *testing.T) {
db := setupEventServiceTestDB(t)
svc := NewEventService(db, nil, nil)
- req, ok := mapDaemonEventInternal(events.Message{Type: events.ContainerEventType, Action: events.ActionStart, Actor: events.Actor{ID: "container-id", Attributes: map[string]string{"name": "web", "com.docker.compose.project": "demo"}}})
+ req, ok := mapDaemonEventInternal(events.Message{
+ Type: events.ContainerEventType,
+ Action: events.ActionStart,
+ Actor: events.Actor{
+ ID: "container-id",
+ Attributes: map[string]string{
+ "name": "web",
+ "com.docker.compose.project": "demo",
+ },
+ },
+ })
require.True(t, ok)
req.EnvironmentID = &supplied
recorded, err := svc.IngestAgentEvent(t.Context(), " remote-environment ", req)
@@ -405,7 +414,19 @@ func TestDaemonEventForwardingPreservesMetadata(t *testing.T) {
defer server.Close()
db := setupEventServiceTestDB(t)
svc := NewEventService(db, &config.Config{AgentMode: true, AgentToken: "agent-token", ManagerApiUrl: server.URL}, server.Client())
- message := events.Message{Type: events.ContainerEventType, Action: events.ActionDie, TimeNano: 123, Actor: events.Actor{ID: "container-id", Attributes: map[string]string{"name": "web", "exitCode": "137", "signal": "9"}}}
+ message := events.Message{
+ Type: events.ContainerEventType,
+ Action: events.ActionDie,
+ TimeNano: 123,
+ Actor: events.Actor{
+ ID: "container-id",
+ Attributes: map[string]string{
+ "name": "web",
+ "exitCode": "137",
+ "signal": "9",
+ },
+ },
+ }
req, ok := mapDaemonEventInternal(message)
require.True(t, ok)
svc.RecordDockerEvent(t.Context(), message)
diff --git a/backend/internal/federated/credential.go b/backend/internal/federated/credential.go
index b5ff2718c..01d6f71cf 100644
--- a/backend/internal/federated/credential.go
+++ b/backend/internal/federated/credential.go
@@ -145,11 +145,11 @@ func (s *FederatedCredentialService) validateRoleGrantAgainstUserInternal(ctx co
if err != nil {
return fmt.Errorf("resolve user permissions: %w", err)
}
- if err := s.roleService.ValidateRoleAssignmentAgainstCaller(ctx, permissions, roleID, environmentID); err != nil {
- if errors.Is(err, common.ErrRolePermissionEscalation) {
- return common.Classify(common.ErrFederatedCredentialPermissionEscalation, fmt.Errorf("cannot map a federated credential to a role you do not hold: %w", err))
+ if validateRoleAssignmentAgainstCallerErr := s.roleService.ValidateRoleAssignmentAgainstCaller(ctx, permissions, roleID, environmentID); validateRoleAssignmentAgainstCallerErr != nil {
+ if errors.Is(validateRoleAssignmentAgainstCallerErr, common.ErrRolePermissionEscalation) {
+ return common.Classify(common.ErrFederatedCredentialPermissionEscalation, fmt.Errorf("cannot map a federated credential to a role you do not hold: %w", validateRoleAssignmentAgainstCallerErr))
}
- return common.Classify(common.ErrFederatedCredentialInvalid, fmt.Errorf("invalid federated credential: %w", err))
+ return common.Classify(common.ErrFederatedCredentialInvalid, fmt.Errorf("invalid federated credential: %w", validateRoleAssignmentAgainstCallerErr))
}
return nil
}
diff --git a/backend/internal/federated/exchange.go b/backend/internal/federated/exchange.go
index 2fabf7593..82e857724 100644
--- a/backend/internal/federated/exchange.go
+++ b/backend/internal/federated/exchange.go
@@ -100,9 +100,9 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fede
return nil, common.Classify(common.ErrFederatedCredentialInvalidGrant, errors.New("invalid federated token grant"))
}
matchedCredential = credential
- if err := s.recordTokenReplayGuardInternal(ctx, issuer, req.SubjectToken, verifiedClaims, verifiedToken.Expiry); err != nil {
+ if recordTokenReplayGuardErr := s.recordTokenReplayGuardInternal(ctx, issuer, req.SubjectToken, verifiedClaims, verifiedToken.Expiry); recordTokenReplayGuardErr != nil {
logReason = "token_replay_rejected"
- return nil, err
+ return nil, recordTokenReplayGuardErr
}
user, err := s.userService.GetUserByID(ctx, credential.IdentityUserID)
@@ -120,13 +120,13 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fede
go func() {
bgCtx := context.WithoutCancel(ctx)
- now := time.Now()
- cutoff := now.Add(-federatedCredentialLastUsedWriteWindow)
- if err := s.db.WithContext(bgCtx).
+ localNow := time.Now()
+ cutoff := localNow.Add(-federatedCredentialLastUsedWriteWindow)
+ if updateLastUsedErr := s.db.WithContext(bgCtx).
Model(&FederatedCredential{}).
Where("id = ? AND (last_used_at IS NULL OR last_used_at < ?)", credential.ID, cutoff).
- Update("last_used_at", now).Error; err != nil {
- slog.WarnContext(bgCtx, "failed to update federated credential last_used_at", "credential_id", credential.ID, "error", err)
+ Update("last_used_at", localNow).Error; updateLastUsedErr != nil {
+ slog.WarnContext(bgCtx, "failed to update federated credential last_used_at", "credential_id", credential.ID, "error", updateLastUsedErr)
}
}()
@@ -157,8 +157,8 @@ func (s *FederatedCredentialService) verifySubjectTokenInternal(ctx context.Cont
}
claims := map[string]any{}
- if err := idToken.Claims(&claims); err != nil {
- return nil, nil, err
+ if claimsErr := idToken.Claims(&claims); claimsErr != nil {
+ return nil, nil, claimsErr
}
return idToken, claims, nil
}
@@ -214,8 +214,8 @@ func (s *FederatedCredentialService) keySetForIssuerInternal(ctx context.Context
var metadata struct {
JWKSURL string `json:"jwks_uri"`
}
- if err := provider.Claims(&metadata); err != nil {
- return nil, fmt.Errorf("failed to read federated issuer metadata: %w", err)
+ if claimsErr := provider.Claims(&metadata); claimsErr != nil {
+ return nil, fmt.Errorf("failed to read federated issuer metadata: %w", claimsErr)
}
if metadata.JWKSURL == "" {
return nil, errors.New("federated issuer metadata is missing jwks_uri")
diff --git a/backend/internal/federated/service.go b/backend/internal/federated/service.go
index c615994f9..6bb0bbb1b 100644
--- a/backend/internal/federated/service.go
+++ b/backend/internal/federated/service.go
@@ -82,8 +82,8 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID st
if err != nil {
return nil, err
}
- if err := s.validateRoleGrantAgainstUserInternal(ctx, callerUserID, normalized.RoleID, normalized.EnvironmentID); err != nil {
- return nil, err
+ if validateRoleGrantAgainstUserErr := s.validateRoleGrantAgainstUserInternal(ctx, callerUserID, normalized.RoleID, normalized.EnvironmentID); validateRoleGrantAgainstUserErr != nil {
+ return nil, validateRoleGrantAgainstUserErr
}
var created FederatedCredential
@@ -93,8 +93,8 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID st
DisplayName: mo.EmptyableToOption(strings.TrimSpace("Federated: " + normalized.Name)).ToPointer(),
IsServiceAccount: true,
}
- if err := tx.Create(&serviceUser).Error; err != nil {
- return fmt.Errorf("failed to create federated service user: %w", err)
+ if createServiceUserErr := tx.Create(&serviceUser).Error; createServiceUserErr != nil {
+ return fmt.Errorf("failed to create federated service user: %w", createServiceUserErr)
}
created = FederatedCredential{
@@ -112,8 +112,8 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID st
TokenTTLSeconds: normalized.TokenTTLSeconds,
ExpiresAt: normalized.ExpiresAt,
}
- if err := tx.Create(&created).Error; err != nil {
- return fmt.Errorf("failed to create federated credential: %w", err)
+ if createCredentialErr := tx.Create(&created).Error; createCredentialErr != nil {
+ return fmt.Errorf("failed to create federated credential: %w", createCredentialErr)
}
assignment := role.UserRoleAssignment{
@@ -122,8 +122,8 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID st
EnvironmentID: normalized.EnvironmentID,
Source: role.RoleAssignmentSourceManual,
}
- if err := tx.Create(&assignment).Error; err != nil {
- return fmt.Errorf("failed to create federated role assignment: %w", err)
+ if createRoleAssignmentErr := tx.Create(&assignment).Error; createRoleAssignmentErr != nil {
+ return fmt.Errorf("failed to create federated role assignment: %w", createRoleAssignmentErr)
}
return nil
})
@@ -197,27 +197,27 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID, i
}
revokeActiveSessions := credential.Enabled && !updated.Enabled
if roleChanged {
- if err := s.validateRoleGrantAgainstUserInternal(ctx, callerUserID, updated.RoleID, updated.EnvironmentID); err != nil {
- return nil, err
+ if validateRoleGrantAgainstUserErr := s.validateRoleGrantAgainstUserInternal(ctx, callerUserID, updated.RoleID, updated.EnvironmentID); validateRoleGrantAgainstUserErr != nil {
+ return nil, validateRoleGrantAgainstUserErr
}
}
err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- if err := tx.Save(&updated).Error; err != nil {
- return fmt.Errorf("failed to update federated credential: %w", err)
+ if updateCredentialErr := tx.Save(&updated).Error; updateCredentialErr != nil {
+ return fmt.Errorf("failed to update federated credential: %w", updateCredentialErr)
}
if revokeActiveSessions {
now := time.Now()
- if err := tx.Model(&session.UserSession{}).
+ if revokeCredentialSessionsErr := tx.Model(&session.UserSession{}).
Where("federated_credential_id = ? AND revoked_at IS NULL", updated.ID).
- Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {
- return fmt.Errorf("failed to revoke federated credential sessions: %w", err)
+ Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; revokeCredentialSessionsErr != nil {
+ return fmt.Errorf("failed to revoke federated credential sessions: %w", revokeCredentialSessionsErr)
}
}
if roleChanged {
- if err := tx.Where("user_id = ? AND source = ?", updated.IdentityUserID, role.RoleAssignmentSourceManual).
- Delete(&role.UserRoleAssignment{}).Error; err != nil {
- return fmt.Errorf("failed to clear federated role assignment: %w", err)
+ if clearRoleAssignmentErr := tx.Where("user_id = ? AND source = ?", updated.IdentityUserID, role.RoleAssignmentSourceManual).
+ Delete(&role.UserRoleAssignment{}).Error; clearRoleAssignmentErr != nil {
+ return fmt.Errorf("failed to clear federated role assignment: %w", clearRoleAssignmentErr)
}
assignment := role.UserRoleAssignment{
UserID: updated.IdentityUserID,
@@ -225,8 +225,8 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID, i
EnvironmentID: updated.EnvironmentID,
Source: role.RoleAssignmentSourceManual,
}
- if err := tx.Create(&assignment).Error; err != nil {
- return fmt.Errorf("failed to update federated role assignment: %w", err)
+ if updateRoleAssignmentErr := tx.Create(&assignment).Error; updateRoleAssignmentErr != nil {
+ return fmt.Errorf("failed to update federated role assignment: %w", updateRoleAssignmentErr)
}
}
return nil
diff --git a/backend/internal/federated/service_test.go b/backend/internal/federated/service_test.go
index 731c715ef..3d781353c 100644
--- a/backend/internal/federated/service_test.go
+++ b/backend/internal/federated/service_test.go
@@ -138,7 +138,7 @@ func setupFederatedCredentialServiceTestDBInternal(t *testing.T) *database.DB {
func setupFederatedCredentialServiceInternal(t *testing.T, issuer *federatedTestIssuerInternal) (*FederatedCredentialService, *auth.AuthService, *database.DB) {
t.Helper()
- ctx := context.Background()
+ ctx := t.Context()
db := setupFederatedCredentialServiceTestDBInternal(t)
roleSvc := role.NewRoleService(db)
userSvc := user.NewUserService(db, roleSvc)
@@ -154,7 +154,7 @@ func setupFederatedCredentialServiceInternal(t *testing.T, issuer *federatedTest
keySetManager := oidcjwk.NewKeySetManager(t.Context())
t.Cleanup(func() {
- shutdownCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), time.Second)
defer cancel()
require.NoError(t, keySetManager.Shutdown(shutdownCtx))
})
@@ -199,7 +199,7 @@ func setupFederatedCredentialServiceInternal(t *testing.T, issuer *federatedTest
func TestFederatedCredentialServiceExchangeToken(t *testing.T) {
issuer := newFederatedTestIssuerInternal(t)
service, authSvc, db := setupFederatedCredentialServiceInternal(t, issuer)
- ctx := context.Background()
+ ctx := t.Context()
tests := []struct {
name string
@@ -248,9 +248,9 @@ func TestFederatedCredentialServiceExchangeToken(t *testing.T) {
require.Positive(t, resp.ExpiresIn)
require.NotEmpty(t, resp.AccessToken)
- user, sessionID, err := authSvc.VerifyToken(ctx, resp.AccessToken)
+ localUser, sessionID, err := authSvc.VerifyToken(ctx, resp.AccessToken)
require.NoError(t, err)
- require.Equal(t, "user-federated-service", user.ID)
+ require.Equal(t, "user-federated-service", localUser.ID)
var userSession session.UserSession
require.NoError(t, db.WithContext(ctx).Where("id = ?", sessionID).First(&userSession).Error)
@@ -266,7 +266,7 @@ func TestFederatedCredentialServiceExchangeTokenRejectsIssuerWithoutCredentialIn
otherIssuer := newFederatedTestIssuerInternal(t)
service, _, _ := setupFederatedCredentialServiceInternal(t, issuer)
- resp, err := service.ExchangeToken(context.Background(), federatedtypes.TokenExchangeRequest{
+ resp, err := service.ExchangeToken(t.Context(), federatedtypes.TokenExchangeRequest{
GrantType: federatedtypes.TokenExchangeGrantType,
SubjectToken: otherIssuer.tokenInternal(t, "repo:getarcaneapp/arcane:ref:refs/heads/main", []string{"arcane-ci"}),
SubjectTokenType: federatedtypes.SubjectTokenTypeJWT,
@@ -274,7 +274,7 @@ func TestFederatedCredentialServiceExchangeTokenRejectsIssuerWithoutCredentialIn
})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalidGrant), "unexpected error: %v", err)
+ require.ErrorIs(t, err, common.ErrFederatedCredentialInvalidGrant, "unexpected error: %v", err)
require.Nil(t, resp)
}
@@ -283,7 +283,7 @@ func TestFederatedCredentialServiceExchangeTokenDoesNotRequireGlobalFeatureFlagI
service, _, _ := setupFederatedCredentialServiceInternal(t, issuer)
service.settingsService = nil
- resp, err := service.ExchangeToken(context.Background(), federatedtypes.TokenExchangeRequest{
+ resp, err := service.ExchangeToken(t.Context(), federatedtypes.TokenExchangeRequest{
GrantType: federatedtypes.TokenExchangeGrantType,
SubjectToken: issuer.tokenInternal(t, "repo:getarcaneapp/arcane:ref:refs/heads/main", []string{"arcane-ci"}),
SubjectTokenType: federatedtypes.SubjectTokenTypeJWT,
@@ -299,12 +299,12 @@ func TestFederatedCredentialServiceExchangeTokenRejectsExpiredCredentialInternal
issuer := newFederatedTestIssuerInternal(t)
service, _, db := setupFederatedCredentialServiceInternal(t, issuer)
expiredAt := time.Now().Add(-time.Minute)
- require.NoError(t, db.WithContext(context.Background()).
+ require.NoError(t, db.WithContext(t.Context()).
Model(&FederatedCredential{}).
Where("id = ?", "cred-github-actions").
Update("expires_at", expiredAt).Error)
- resp, err := service.ExchangeToken(context.Background(), federatedtypes.TokenExchangeRequest{
+ resp, err := service.ExchangeToken(t.Context(), federatedtypes.TokenExchangeRequest{
GrantType: federatedtypes.TokenExchangeGrantType,
SubjectToken: issuer.tokenInternal(t, "repo:getarcaneapp/arcane:ref:refs/heads/main", []string{"arcane-ci"}),
SubjectTokenType: federatedtypes.SubjectTokenTypeJWT,
@@ -312,14 +312,14 @@ func TestFederatedCredentialServiceExchangeTokenRejectsExpiredCredentialInternal
})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalidGrant), "unexpected error: %v", err)
+ require.ErrorIs(t, err, common.ErrFederatedCredentialInvalidGrant, "unexpected error: %v", err)
require.Nil(t, resp)
}
func TestFederatedCredentialServiceUpdateDisableRevokesIssuedSessionsInternal(t *testing.T) {
issuer := newFederatedTestIssuerInternal(t)
service, authSvc, _ := setupFederatedCredentialServiceInternal(t, issuer)
- ctx := context.Background()
+ ctx := t.Context()
resp, err := service.ExchangeToken(ctx, federatedtypes.TokenExchangeRequest{
GrantType: federatedtypes.TokenExchangeGrantType,
@@ -337,13 +337,13 @@ func TestFederatedCredentialServiceUpdateDisableRevokesIssuedSessionsInternal(t
_, _, err = authSvc.VerifyToken(ctx, resp.AccessToken)
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrSessionRevoked), "unexpected error: %v", err)
+ require.ErrorIs(t, err, common.ErrSessionRevoked, "unexpected error: %v", err)
}
func TestFederatedCredentialServiceRejectsReplayedSubjectTokenInternal(t *testing.T) {
issuer := newFederatedTestIssuerInternal(t)
service, _, _ := setupFederatedCredentialServiceInternal(t, issuer)
- ctx := context.Background()
+ ctx := t.Context()
subjectToken := issuer.tokenInternal(t, "repo:getarcaneapp/arcane:ref:refs/heads/main", []string{"arcane-ci"})
req := federatedtypes.TokenExchangeRequest{
GrantType: federatedtypes.TokenExchangeGrantType,
@@ -358,7 +358,7 @@ func TestFederatedCredentialServiceRejectsReplayedSubjectTokenInternal(t *testin
second, err := service.ExchangeToken(ctx, req)
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalidGrant), "unexpected error: %v", err)
+ require.ErrorIs(t, err, common.ErrFederatedCredentialInvalidGrant, "unexpected error: %v", err)
require.Nil(t, second)
}
@@ -366,7 +366,7 @@ func TestFederatedCredentialServiceCreateRejectsBareWildcardGlob(t *testing.T) {
issuer := newFederatedTestIssuerInternal(t)
service, _, _ := setupFederatedCredentialServiceInternal(t, issuer)
- _, err := service.Create(context.Background(), "admin-user", federatedtypes.CreateFederatedCredential{
+ _, err := service.Create(t.Context(), "admin-user", federatedtypes.CreateFederatedCredential{
Name: "Unsafe wildcard",
IssuerURL: "https://token.actions.githubusercontent.com",
Audiences: []string{"arcane-ci"},
@@ -377,7 +377,7 @@ func TestFederatedCredentialServiceCreateRejectsBareWildcardGlob(t *testing.T) {
})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrFederatedCredentialInvalid), "unexpected error: %v", err)
+ require.ErrorIs(t, err, common.ErrFederatedCredentialInvalid, "unexpected error: %v", err)
}
// Test fixtures shared by this package's tests.
@@ -386,7 +386,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
diff --git a/backend/internal/gitops/backup.go b/backend/internal/gitops/backup.go
index b9a88233c..4d2a9e6d0 100644
--- a/backend/internal/gitops/backup.go
+++ b/backend/internal/gitops/backup.go
@@ -139,10 +139,10 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, tx
return nil, common.Classify(common.ErrConflict, errors.New("project is deployed from Git; disconnect that sync before backing it up"))
}
var existing int64
- if err := tx.Model(&projectpkg.GitOpsSync{}).
+ if countBackupsErr := tx.Model(&projectpkg.GitOpsSync{}).
Where("mode = ? AND project_id = ?", gitops.SyncModeBackup, project.ID).
- Count(&existing).Error; err != nil {
- return nil, fmt.Errorf("failed to check existing backups: %w", err)
+ Count(&existing).Error; countBackupsErr != nil {
+ return nil, fmt.Errorf("failed to check existing backups: %w", countBackupsErr)
}
if existing > 0 {
return nil, common.Classify(common.ErrConflict, errors.New("project already has a Git backup; disconnect it first"))
@@ -155,11 +155,11 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, tx
if err != nil {
return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "backupDirectory", Err: err})
}
- if err := ensureBackupDestinationFreeInternal(tx, "", req.RepositoryID, req.Branch, directory); err != nil {
- return nil, err
+ if ensureBackupDestinationFreeErr := ensureBackupDestinationFreeInternal(tx, "", req.RepositoryID, req.Branch, directory); ensureBackupDestinationFreeErr != nil {
+ return nil, ensureBackupDestinationFreeErr
}
- if err := s.projectService.EnsureProjectPathUnderRoot(ctx, project, false); err != nil {
- return nil, err
+ if ensureProjectPathUnderRootErr := s.projectService.EnsureProjectPathUnderRoot(ctx, project, false); ensureProjectPathUnderRootErr != nil {
+ return nil, ensureProjectPathUnderRootErr
}
composeFile, _, err := s.backupComposeFilesInternal(ctx, project)
if err != nil {
@@ -248,74 +248,104 @@ func (s *GitOpsSyncService) applyModeUpdatesInternal(ctx context.Context, curren
}
// performBackupInternal snapshots the project and pushes a commit when it differs; adopt overwrites the remote.
-func (s *GitOpsSyncService) performBackupInternal(ctx context.Context, sync *projectpkg.GitOpsSync, actor common.User, result *gitops.SyncResult, adopt bool) (*gitops.SyncResult, error) {
- if sync.Repository == nil {
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureRepository, "Repository not found", errors.New("repository not found"), false)
+func (s *GitOpsSyncService) performBackupInternal(ctx context.Context, localSync *projectpkg.GitOpsSync, actor common.User, result *gitops.SyncResult, adopt bool) (*gitops.SyncResult, error) {
+ if localSync.Repository == nil {
+ return result, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureRepository, "Repository not found", errors.New("repository not found"), false)
}
- if sync.ProjectID == nil || strings.TrimSpace(*sync.ProjectID) == "" {
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Project not linked", errors.New("backup sync has no project"), false)
+ if localSync.ProjectID == nil || strings.TrimSpace(*localSync.ProjectID) == "" {
+ return result, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureProjectMissing, "Project not linked", errors.New("backup sync has no project"), false)
}
- project, found, err := s.lookupProjectByIDInternal(ctx, *sync.ProjectID)
+ project, found, err := s.lookupProjectByIDInternal(ctx, *localSync.ProjectID)
if err != nil {
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Failed to load project", err, false)
+ return result, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureProjectMissing, "Failed to load project", err, false)
}
if !found {
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Project not found", fmt.Errorf("project %s no longer exists", *sync.ProjectID), false)
+ return result, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureProjectMissing, "Project not found", fmt.Errorf("project %s no longer exists", *localSync.ProjectID), false)
}
- if err := s.projectService.EnsureProjectPathUnderRoot(ctx, project, true); err != nil {
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureProjectMissing, "Project directory is unavailable", err, false)
+ if ensureProjectPathUnderRootErr := s.projectService.EnsureProjectPathUnderRoot(ctx, project, true); ensureProjectPathUnderRootErr != nil {
+ return result, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureProjectMissing, "Project directory is unavailable", ensureProjectPathUnderRootErr, false)
}
- authConfig, err := s.repoService.GetAuthConfig(ctx, sync.Repository)
+ authConfig, err := s.repoService.GetAuthConfig(ctx, localSync.Repository)
if err != nil {
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureAuth, "Failed to get authentication config", err, false)
+ return result, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureAuth, "Failed to get authentication config", err, false)
}
- identity, err := s.repoService.GetCommitIdentity(ctx, sync.Repository)
+ identity, err := s.repoService.GetCommitIdentity(ctx, localSync.Repository)
if err != nil {
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureAuth, "Failed to load commit identity", err, false)
+ return result, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureAuth, "Failed to load commit identity", err, false)
}
startedAt := time.Now()
- if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", sync.ID).Update("last_sync_status", backupStatusRunning).Error; err != nil {
- slog.ErrorContext(ctx, "Failed to mark git backup running", "error", err, "syncId", sync.ID)
+ if markBackupRunningErr := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", localSync.ID).Update("last_sync_status", backupStatusRunning).Error; markBackupRunningErr != nil {
+ slog.ErrorContext(ctx, "Failed to mark git backup running", "error", markBackupRunningErr, "syncId", localSync.ID)
}
- lock := s.backups.branchLock(sync.RepositoryID, sync.Branch)
+ lock := s.backups.branchLock(localSync.RepositoryID, localSync.Branch)
lock.Lock()
defer lock.Unlock()
- snapshot, err := s.buildBackupSnapshotInternal(ctx, sync, project)
+ snapshot, err := s.buildBackupSnapshotInternal(ctx, localSync, project)
if err != nil {
- return result, s.failBackupInternal(ctx, sync, result, actor, backupFailureReasonInternal(err), "Failed to snapshot project files", err, false)
+ return result, s.failBackupInternal(ctx, localSync, result, actor, backupFailureReasonInternal(err), "Failed to snapshot project files", err, false)
}
- baseline := parseBackupSnapshotInternal(sync.LastBackupSnapshot)
+ baseline := parseBackupSnapshotInternal(localSync.LastBackupSnapshot)
for attempt := 1; attempt <= backupPushAttempts; attempt++ {
- retry, err := s.commitBackupInternal(ctx, sync, project, actor, result, authConfig, identity, snapshot, baseline, adopt, startedAt)
+ retry, commitBackupErr := s.commitBackupInternal(ctx, localSync, project, actor, result, authConfig, identity, snapshot, baseline, adopt, startedAt)
if retry {
- slog.InfoContext(ctx, "git backup push rejected; retrying with a fresh checkout", "syncId", sync.ID, "attempt", attempt, "error", err)
+ slog.InfoContext(ctx, "git backup push rejected; retrying with a fresh checkout", "syncId", localSync.ID, "attempt", attempt, "error", commitBackupErr)
continue
}
- return result, err
- }
- return result, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailurePushRejected, "Push rejected by remote", fmt.Errorf("another writer kept updating branch %s; giving up after %d attempts", sync.Branch, backupPushAttempts), false)
+ return result, commitBackupErr
+ }
+ return result, s.failBackupInternal(
+ ctx,
+ localSync,
+ result,
+ actor,
+ gitops.BackupFailurePushRejected,
+ "Push rejected by remote",
+ fmt.Errorf(
+ "another writer kept updating branch %s; giving up after %d attempts",
+ localSync.Branch,
+ backupPushAttempts,
+ ),
+ false,
+ )
}
// commitBackupInternal runs one checkout-analyze-push attempt; retry reports a rejected push worth repeating.
-func (s *GitOpsSyncService) commitBackupInternal(ctx context.Context, sync *projectpkg.GitOpsSync, project *projectpkg.Project, actor common.User, result *gitops.SyncResult, authConfig git.AuthConfig, identity git.CommitIdentity, snapshot *backupSnapshotInternal, baseline map[string]string, adopt bool, startedAt time.Time) (bool, error) {
- checkout, err := s.repoService.CheckoutForWrite(ctx, sync.Repository.URL, sync.Branch, authConfig)
+func (
+ s *GitOpsSyncService,
+) commitBackupInternal(
+ ctx context.Context,
+ localSync *projectpkg.GitOpsSync,
+ project *projectpkg.Project,
+ actor common.User,
+ result *gitops.SyncResult,
+ authConfig git.AuthConfig,
+ identity git.CommitIdentity,
+ snapshot *backupSnapshotInternal,
+ baseline map[string]string,
+ adopt bool,
+ startedAt time.Time,
+) (
+ bool,
+ error,
+) {
+ checkout, err := s.repoService.CheckoutForWrite(ctx, localSync.Repository.URL, localSync.Branch, authConfig)
if err != nil {
- return false, s.failBackupInternal(ctx, sync, result, actor, backupFailureReasonInternal(err), "Failed to prepare repository checkout", err, false)
+ return false, s.failBackupInternal(ctx, localSync, result, actor, backupFailureReasonInternal(err), "Failed to prepare repository checkout", err, false)
}
defer s.repoService.Discard(ctx, checkout.RepoPath)
- analysis, err := analyzeBackupInternal(ctx, checkout.RepoPath, sync.BackupDirectory, snapshot, baseline, adopt)
+ analysis, err := analyzeBackupInternal(ctx, checkout.RepoPath, localSync.BackupDirectory, snapshot, baseline, adopt)
if err != nil {
- return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureRepository, "Failed to read remote backup", err, false)
+ return false, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureRepository, "Failed to read remote backup", err, false)
}
switch analysis.state {
case backupPreviewClean:
- if err := s.recordBackupSuccessInternal(ctx, sync, snapshot, checkout.HeadCommit, false, startedAt); err != nil {
- return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureSnapshot, "Failed to record backup", err, false)
+ if recordBackupSuccessErr := s.recordBackupSuccessInternal(ctx, localSync, snapshot, checkout.HeadCommit, false, startedAt); recordBackupSuccessErr != nil {
+ return false, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureSnapshot, "Failed to record backup", recordBackupSuccessErr, false)
}
result.Success = true
result.Message = "Repository already contains the current files for project " + project.Name
@@ -328,9 +358,40 @@ func (s *GitOpsSyncService) commitBackupInternal(ctx context.Context, sync *proj
if len(analysis.conflicts) > backupCommitFileLines {
names = append(names, "...")
}
- return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureConflict, "Backup files changed in the repository", fmt.Errorf("%d backup file(s) changed in the repository since the last backup: %s", len(analysis.conflicts), strings.Join(names, ", ")), true)
+ return false, s.failBackupInternal(
+ ctx,
+ localSync,
+ result,
+ actor,
+ gitops.BackupFailureConflict,
+ "Backup files changed in the repository",
+ fmt.Errorf(
+ "%d backup file(s) changed in the repository since the last backup: %s",
+ len(
+ analysis.conflicts,
+ ),
+ strings.Join(
+ names,
+ ", ",
+ ),
+ ),
+ true,
+ )
case backupPreviewOccupied:
- return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureDestinationOccupied, "Backup directory already contains unrelated files", fmt.Errorf("directory %s on branch %s already contains files that are not an Arcane backup", sync.BackupDirectory, sync.Branch), true)
+ return false, s.failBackupInternal(
+ ctx,
+ localSync,
+ result,
+ actor,
+ gitops.BackupFailureDestinationOccupied,
+ "Backup directory already contains unrelated files",
+ fmt.Errorf(
+ "directory %s on branch %s already contains files that are not an Arcane backup",
+ localSync.BackupDirectory,
+ localSync.Branch,
+ ),
+ true,
+ )
}
var message strings.Builder
@@ -352,12 +413,12 @@ func (s *GitOpsSyncService) commitBackupInternal(ctx context.Context, sync *proj
SignKey: identity.SignKey,
}
for _, file := range snapshot.files {
- request.Files = append(request.Files, git.CommitFile{Path: path.Join(sync.BackupDirectory, file.Path), Content: file.Content, Executable: file.Executable})
+ request.Files = append(request.Files, git.CommitFile{Path: path.Join(localSync.BackupDirectory, file.Path), Content: file.Content, Executable: file.Executable})
}
for _, removed := range analysis.remove {
- request.Remove = append(request.Remove, path.Join(sync.BackupDirectory, removed))
+ request.Remove = append(request.Remove, path.Join(localSync.BackupDirectory, removed))
}
- legacyManifest := path.Join(sync.BackupDirectory, legacyBackupManifestFileNameInternal)
+ legacyManifest := path.Join(localSync.BackupDirectory, legacyBackupManifestFileNameInternal)
if exists, existsErr := acfs.Exists(ctx, checkout.RepoPath, "/"+legacyManifest); existsErr == nil && exists {
request.Remove = append(request.Remove, legacyManifest)
}
@@ -367,29 +428,29 @@ func (s *GitOpsSyncService) commitBackupInternal(ctx context.Context, sync *proj
if errors.Is(err, git.ErrPushRejected) {
return true, err
}
- return false, s.failBackupInternal(ctx, sync, result, actor, backupFailureReasonInternal(err), "Failed to push backup", err, false)
+ return false, s.failBackupInternal(ctx, localSync, result, actor, backupFailureReasonInternal(err), "Failed to push backup", err, false)
}
- if err := s.recordBackupSuccessInternal(ctx, sync, snapshot, commit, committed, startedAt); err != nil {
- return false, s.failBackupInternal(ctx, sync, result, actor, gitops.BackupFailureSnapshot, "Failed to record backup", err, false)
+ if recordCommittedBackupErr := s.recordBackupSuccessInternal(ctx, localSync, snapshot, commit, committed, startedAt); recordCommittedBackupErr != nil {
+ return false, s.failBackupInternal(ctx, localSync, result, actor, gitops.BackupFailureSnapshot, "Failed to record backup", recordCommittedBackupErr, false)
}
result.Success = true
- result.Message = fmt.Sprintf("Backed up %d file(s) for project %s to %s", len(snapshot.files), project.Name, sync.BackupDirectory)
+ result.Message = fmt.Sprintf("Backed up %d file(s) for project %s to %s", len(snapshot.files), project.Name, localSync.BackupDirectory)
if _, eventErr := s.eventService.CreateEvent(ctx, event.CreateEventRequest{
Type: event.EventTypeGitSyncRun,
Severity: event.EventSeveritySuccess,
Title: "Git backup completed",
- Description: fmt.Sprintf("Backed up project '%s' to '%s' (%s)", project.Name, sync.BackupDirectory, commit[:min(len(commit), 12)]),
+ Description: fmt.Sprintf("Backed up project '%s' to '%s' (%s)", project.Name, localSync.BackupDirectory, commit[:min(len(commit), 12)]),
ResourceType: new("git_sync"),
- ResourceID: new(sync.ID),
- ResourceName: new(sync.Name),
+ ResourceID: new(localSync.ID),
+ ResourceName: new(localSync.Name),
UserID: new(actor.ID),
Username: new(actor.Username),
- EnvironmentID: new(sync.EnvironmentID),
+ EnvironmentID: new(localSync.EnvironmentID),
}); eventErr != nil {
- slog.WarnContext(ctx, "Failed to record git backup audit event", "syncId", sync.ID, "commit", commit, "error", eventErr)
+ slog.WarnContext(ctx, "Failed to record git backup audit event", "syncId", localSync.ID, "commit", commit, "error", eventErr)
}
- slog.InfoContext(ctx, "Git backup completed", "syncId", sync.ID, "project", project.Name, "commit", commit, "committed", committed)
+ slog.InfoContext(ctx, "Git backup completed", "syncId", localSync.ID, "project", project.Name, "commit", commit, "committed", committed)
return false, nil
}
@@ -411,7 +472,14 @@ func backupFailureReasonInternal(err error) string {
return gitops.BackupFailureRepository
}
-func (s *GitOpsSyncService) recordBackupSuccessInternal(ctx context.Context, sync *projectpkg.GitOpsSync, snapshot *backupSnapshotInternal, commit string, committed bool, startedAt time.Time) error {
+func (s *GitOpsSyncService) recordBackupSuccessInternal(
+ ctx context.Context,
+ localSync *projectpkg.GitOpsSync,
+ snapshot *backupSnapshotInternal,
+ commit string,
+ committed bool,
+ startedAt time.Time,
+) error {
now := time.Now()
paths := make([]string, 0, len(snapshot.files))
for _, file := range snapshot.files {
@@ -433,22 +501,32 @@ func (s *GitOpsSyncService) recordBackupSuccessInternal(ctx context.Context, syn
if commit != "" {
updates["last_sync_commit"] = commit
}
- if committed || sync.LastBackupAt == nil {
+ if committed || localSync.LastBackupAt == nil {
updates["last_backup_at"] = now
}
- if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", sync.ID).Updates(updates).Error; err != nil {
- slog.ErrorContext(ctx, "Failed to record git backup success", "error", err, "syncId", sync.ID)
+ if recordBackupSuccessErr := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", localSync.ID).Updates(updates).Error; recordBackupSuccessErr != nil {
+ slog.ErrorContext(ctx, "Failed to record git backup success", "error", recordBackupSuccessErr, "syncId", localSync.ID)
}
- if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).
- Where("id = ? AND (backup_pending_since IS NULL OR backup_pending_since <= ?)", sync.ID, startedAt).
- Updates(map[string]any{"backup_pending": false, "backup_pending_since": nil}).Error; err != nil {
- slog.ErrorContext(ctx, "Failed to clear git backup pending flag", "error", err, "syncId", sync.ID)
+ if clearBackupPendingErr := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).
+ Where("id = ? AND (backup_pending_since IS NULL OR backup_pending_since <= ?)", localSync.ID, startedAt).
+ Updates(map[string]any{"backup_pending": false, "backup_pending_since": nil}).Error; clearBackupPendingErr != nil {
+ slog.ErrorContext(ctx, "Failed to clear git backup pending flag", "error", clearBackupPendingErr, "syncId", localSync.ID)
}
return nil
}
// failBackupInternal records the failure on the sync; needsAttention marks it as a conflict the user must resolve.
-func (s *GitOpsSyncService) failBackupInternal(ctx context.Context, sync *projectpkg.GitOpsSync, result *gitops.SyncResult, actor common.User, reason, message string, failure error, needsAttention bool) error {
+func (
+ s *GitOpsSyncService,
+) failBackupInternal(
+ ctx context.Context,
+ localSync *projectpkg.GitOpsSync,
+ result *gitops.SyncResult,
+ actor common.User,
+ reason, message string,
+ failure error,
+ needsAttention bool,
+) error {
errMsg := failure.Error()
result.Message = message
result.Error = new(errMsg)
@@ -460,10 +538,10 @@ func (s *GitOpsSyncService) failBackupInternal(ctx context.Context, sync *projec
"backup_conflict": needsAttention,
"backup_failure_reason": reason,
}
- if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", sync.ID).Updates(updates).Error; err != nil {
- slog.ErrorContext(ctx, "Failed to record git backup failure", "error", err, "syncId", sync.ID)
+ if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", localSync.ID).Updates(updates).Error; err != nil {
+ slog.ErrorContext(ctx, "Failed to record git backup failure", "error", err, "syncId", localSync.ID)
}
- s.logSyncError(ctx, sync, actor, errMsg)
+ s.logSyncError(ctx, localSync, actor, errMsg)
if needsAttention {
return common.Classify(common.ErrConflict, fmt.Errorf("%s: %w", message, failure))
}
@@ -489,8 +567,8 @@ func (s *GitOpsSyncService) PreviewBackup(ctx context.Context, environmentID, id
if !found {
return nil, common.ErrProjectNotFound
}
- if err := s.projectService.EnsureProjectPathUnderRoot(previewCtx, project, false); err != nil {
- return nil, err
+ if ensureProjectPathUnderRootErr := s.projectService.EnsureProjectPathUnderRoot(previewCtx, project, false); ensureProjectPathUnderRootErr != nil {
+ return nil, ensureProjectPathUnderRootErr
}
snapshot, err := s.buildBackupSnapshotInternal(previewCtx, syncRecord, project)
if err != nil {
@@ -616,8 +694,8 @@ func normalizeBackupPathsInternal(raw []string) ([]string, error) {
if err != nil {
return nil, fmt.Errorf("invalid backup path %q: %w", entry, err)
}
- base := path.Base(cleaned)
- if base == projects.GitSourceEnvFileName || base == projects.GlobalEnvFileName || slices.Contains(strings.Split(cleaned, "/"), ".git") {
+ localBase := path.Base(cleaned)
+ if localBase == projects.GitSourceEnvFileName || localBase == projects.GlobalEnvFileName || slices.Contains(strings.Split(cleaned, "/"), ".git") {
return nil, fmt.Errorf("backup path %q is reserved", entry)
}
normalized = append(normalized, cleaned)
@@ -660,18 +738,18 @@ func (s *GitOpsSyncService) backupComposeFilesInternal(ctx context.Context, proj
}
// buildBackupSnapshotInternal reads the selected project files, retrying when they change mid-read.
-func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, sync *projectpkg.GitOpsSync, project *projectpkg.Project) (*backupSnapshotInternal, error) {
+func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, localSync *projectpkg.GitOpsSync, project *projectpkg.Project) (*backupSnapshotInternal, error) {
_, composeFiles, err := s.backupComposeFilesInternal(ctx, project)
if err != nil {
return nil, fmt.Errorf("%s: %w", err.Error(), git.ErrSelectionInvalid)
}
- paths := slices.Clone([]string(sync.BackupPaths))
+ paths := slices.Clone([]string(localSync.BackupPaths))
for _, composeFile := range composeFiles {
if !backupSelectionCoversInternal(paths, composeFile) {
paths = append(paths, composeFile)
}
}
- maxFiles, maxTotalSize, _ := s.getEffectiveSyncLimits(ctx, sync)
+ maxFiles, maxTotalSize, _ := s.getEffectiveSyncLimits(ctx, localSync)
options := git.CollectOptions{
MaxFiles: maxFiles,
MaxTotalSize: maxTotalSize,
@@ -682,9 +760,9 @@ func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, syn
}
for range backupSnapshotMaxRetry {
- files, err := git.CollectFiles(ctx, project.Path, paths, options)
- if err != nil {
- return nil, err
+ files, collectFilesErr := git.CollectFiles(ctx, project.Path, paths, options)
+ if collectFilesErr != nil {
+ return nil, collectFilesErr
}
snapshot := &backupSnapshotInternal{files: files, hashes: make(map[string]string, len(files))}
for _, file := range files {
@@ -693,9 +771,9 @@ func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, syn
stable := true
for _, file := range files {
- content, err := acfs.ReadFile(ctx, project.Path, "/"+file.Path)
- if err != nil {
- return nil, fmt.Errorf("cannot re-read %s: %v: %w", file.Path, err.Error(), git.ErrSelectionUnreadable)
+ content, readFileErr := acfs.ReadFile(ctx, project.Path, "/"+file.Path)
+ if readFileErr != nil {
+ return nil, fmt.Errorf("cannot re-read %s: %v: %w", file.Path, readFileErr.Error(), git.ErrSelectionUnreadable)
}
if kit.SHA256Hex(content) != snapshot.hashes[file.Path] {
stable = false
diff --git a/backend/internal/gitops/backup_test.go b/backend/internal/gitops/backup_test.go
index ebb49db6e..9c32c8235 100644
--- a/backend/internal/gitops/backup_test.go
+++ b/backend/internal/gitops/backup_test.go
@@ -104,7 +104,7 @@ func setupGitOpsBackupTestServiceInternal(t *testing.T) *backupTestEnvInternal {
t.Helper()
installBackupTestTransportInternal()
- ctx := context.Background()
+ ctx := t.Context()
db := setupGitOpsProjectTestDBInternal(t)
require.NoError(t, db.AutoMigrate(&projectpkg.GitOpsSync{}, &projectpkg.ProjectTag{}, &gitrepo.GitRepository{}, &environment.Environment{}))
@@ -190,27 +190,27 @@ func (e *backupTestEnvInternal) reloadInternal(t *testing.T, id string) *project
}
// checkoutRemoteInternal clones the backup branch so the pushed tree can be inspected.
-func (e *backupTestEnvInternal) checkoutRemoteInternal(t *testing.T, branch string) string {
+func (e *backupTestEnvInternal) checkoutRemoteInternal(t *testing.T) string {
t.Helper()
- repoPath, err := e.remote.Clone(t.Context(), e.repoURL, branch, git.AuthConfig{AuthType: "none"})
+ repoPath, err := e.remote.Clone(t.Context(), e.repoURL, "main", git.AuthConfig{AuthType: "none"})
require.NoError(t, err)
t.Cleanup(func() { _ = e.remote.Cleanup(repoPath) })
return repoPath
}
-func (e *backupTestEnvInternal) remoteHeadInternal(t *testing.T, branch string) string {
+func (e *backupTestEnvInternal) remoteHeadInternal(t *testing.T) string {
t.Helper()
- head, exists, err := e.remote.RemoteBranchHead(t.Context(), e.repoURL, branch, git.AuthConfig{AuthType: "none"})
+ head, exists, err := e.remote.RemoteBranchHead(t.Context(), e.repoURL, "main", git.AuthConfig{AuthType: "none"})
require.NoError(t, err)
require.True(t, exists)
return head
}
// pushRemoteCommitInternal commits directly to the branch as another writer.
-func (e *backupTestEnvInternal) pushRemoteCommitInternal(t *testing.T, branch, message string, files map[string]string) {
+func (e *backupTestEnvInternal) pushRemoteCommitInternal(t *testing.T, message string, files map[string]string) {
t.Helper()
auth := git.AuthConfig{AuthType: "none"}
- checkout, err := e.remote.CheckoutForWrite(t.Context(), e.repoURL, branch, auth)
+ checkout, err := e.remote.CheckoutForWrite(t.Context(), e.repoURL, "main", auth)
require.NoError(t, err)
defer func() { _ = e.remote.Cleanup(checkout.RepoPath) }()
@@ -240,10 +240,10 @@ func TestGitOpsBackup_FirstRunPushesSelectedFiles(t *testing.T) {
assert.False(t, stored.BackupConflict)
assert.Nil(t, stored.BackupFailureReason)
require.NotNil(t, stored.LastSyncCommit)
- assert.Equal(t, env.remoteHeadInternal(t, "main"), *stored.LastSyncCommit)
+ assert.Equal(t, env.remoteHeadInternal(t), *stored.LastSyncCommit)
require.NotNil(t, stored.LastBackupSnapshot)
- repoPath := env.checkoutRemoteInternal(t, "main")
+ repoPath := env.checkoutRemoteInternal(t)
composeBytes, err := os.ReadFile(filepath.Join(repoPath, "backups", "demo", "compose.yaml"))
require.NoError(t, err)
assert.Contains(t, string(composeBytes), "nginx:1.27-alpine")
@@ -259,13 +259,13 @@ func TestGitOpsBackup_FirstRunPushesSelectedFiles(t *testing.T) {
func TestGitOpsBackup_UnchangedContentMakesNoNewCommit(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
syncRecord := env.createBackupInternal(t, gitops.CreateSyncRequest{})
- firstHead := env.remoteHeadInternal(t, "main")
+ firstHead := env.remoteHeadInternal(t)
result, err := env.service.PerformSync(t.Context(), "0", syncRecord.ID, common.SystemUser)
require.NoError(t, err)
assert.True(t, result.Success)
assert.Contains(t, result.Message, "already contains")
- assert.Equal(t, firstHead, env.remoteHeadInternal(t, "main"))
+ assert.Equal(t, firstHead, env.remoteHeadInternal(t))
stored := env.reloadInternal(t, syncRecord.ID)
require.NotNil(t, stored.LastSyncStatus)
@@ -279,7 +279,7 @@ func TestGitOpsBackup_AddsAndRemovesFilesAndKeepsUnrelatedRemoteFiles(t *testing
writeBackupProjectFileInternal(t, env.projectPath, "config/extra.conf", "extra = 1\n")
syncRecord := env.createBackupInternal(t, gitops.CreateSyncRequest{BackupPaths: []string{"compose.yaml", "config"}})
- env.pushRemoteCommitInternal(t, "main", "unrelated docs", map[string]string{"docs/readme.md": "docs\n"})
+ env.pushRemoteCommitInternal(t, "unrelated docs", map[string]string{"docs/readme.md": "docs\n"})
require.NoError(t, os.Remove(filepath.Join(env.projectPath, "config", "extra.conf")))
writeBackupProjectFileInternal(t, env.projectPath, "scripts/run.sh", "#!/bin/sh\necho hi\n")
@@ -293,7 +293,7 @@ func TestGitOpsBackup_AddsAndRemovesFilesAndKeepsUnrelatedRemoteFiles(t *testing
require.NoError(t, err)
require.True(t, result.Success)
- repoPath := env.checkoutRemoteInternal(t, "main")
+ repoPath := env.checkoutRemoteInternal(t)
assert.FileExists(t, filepath.Join(repoPath, "backups", "demo", "scripts", "run.sh"))
assert.FileExists(t, filepath.Join(repoPath, "backups", "demo", "config", "app.conf"))
assert.FileExists(t, filepath.Join(repoPath, "docs", "readme.md"))
@@ -319,7 +319,7 @@ func TestGitOpsBackup_EnvFilesOnlyIncludedWhenListedExplicitly(t *testing.T) {
env.createBackupInternal(t, gitops.CreateSyncRequest{BackupPaths: test.paths})
- repoPath := env.checkoutRemoteInternal(t, "main")
+ repoPath := env.checkoutRemoteInternal(t)
assert.FileExists(t, filepath.Join(repoPath, "backups", "demo", "compose.yaml"))
assert.FileExists(t, filepath.Join(repoPath, "backups", "demo", "config", "app.conf"))
assert.NoFileExists(t, filepath.Join(repoPath, "backups", "demo", "config", ".env"))
@@ -337,7 +337,7 @@ func TestGitOpsBackup_RemoteEditConflictsThenResolvesWithArcane(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
syncRecord := env.createBackupInternal(t, gitops.CreateSyncRequest{})
- env.pushRemoteCommitInternal(t, "main", "edited backup outside arcane", map[string]string{
+ env.pushRemoteCommitInternal(t, "edited backup outside arcane", map[string]string{
"backups/demo/compose.yaml": "services:\n app:\n image: tampered\n",
})
writeBackupProjectFileInternal(t, env.projectPath, "compose.yaml", "services:\n app:\n image: nginx:1.28-alpine\n")
@@ -368,7 +368,7 @@ func TestGitOpsBackup_RemoteEditConflictsThenResolvesWithArcane(t *testing.T) {
assert.Nil(t, resolved.BackupFailureReason)
assert.Equal(t, gitops.BackupStateBackedUp, resolved.BackupState())
- repoPath := env.checkoutRemoteInternal(t, "main")
+ repoPath := env.checkoutRemoteInternal(t)
composeBytes, err := os.ReadFile(filepath.Join(repoPath, "backups", "demo", "compose.yaml"))
require.NoError(t, err)
assert.Contains(t, string(composeBytes), "nginx:1.28-alpine")
@@ -376,7 +376,7 @@ func TestGitOpsBackup_RemoteEditConflictsThenResolvesWithArcane(t *testing.T) {
func TestGitOpsBackup_OccupiedDestinationNeedsAttention(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
- env.pushRemoteCommitInternal(t, "main", "pre-existing files", map[string]string{
+ env.pushRemoteCommitInternal(t, "pre-existing files", map[string]string{
"backups/demo/unrelated.txt": "not an arcane backup\n",
})
@@ -393,7 +393,7 @@ func TestGitOpsBackup_OccupiedDestinationNeedsAttention(t *testing.T) {
func TestGitOpsBackup_AdoptsMatchingRemoteWithoutSnapshot(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
syncRecord := env.createBackupInternal(t, gitops.CreateSyncRequest{})
- head := env.remoteHeadInternal(t, "main")
+ head := env.remoteHeadInternal(t)
require.NoError(t, env.db.Model(&projectpkg.GitOpsSync{}).Where("id = ?", syncRecord.ID).
Update("last_backup_snapshot", nil).Error)
@@ -401,7 +401,7 @@ func TestGitOpsBackup_AdoptsMatchingRemoteWithoutSnapshot(t *testing.T) {
result, err := env.service.PerformSync(t.Context(), "0", syncRecord.ID, common.SystemUser)
require.NoError(t, err)
assert.True(t, result.Success)
- assert.Equal(t, head, env.remoteHeadInternal(t, "main"))
+ assert.Equal(t, head, env.remoteHeadInternal(t))
stored := env.reloadInternal(t, syncRecord.ID)
assert.False(t, stored.BackupConflict)
@@ -412,14 +412,14 @@ func TestGitOpsBackup_SucceedsOnTopOfAnotherWritersCommit(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
syncRecord := env.createBackupInternal(t, gitops.CreateSyncRequest{})
- env.pushRemoteCommitInternal(t, "main", "other writer", map[string]string{"other/notes.txt": "notes\n"})
+ env.pushRemoteCommitInternal(t, "other writer", map[string]string{"other/notes.txt": "notes\n"})
writeBackupProjectFileInternal(t, env.projectPath, "compose.yaml", "services:\n app:\n image: nginx:1.29-alpine\n")
result, err := env.service.PerformSync(t.Context(), "0", syncRecord.ID, common.SystemUser)
require.NoError(t, err)
require.True(t, result.Success)
- repoPath := env.checkoutRemoteInternal(t, "main")
+ repoPath := env.checkoutRemoteInternal(t)
assert.FileExists(t, filepath.Join(repoPath, "other", "notes.txt"))
composeBytes, err := os.ReadFile(filepath.Join(repoPath, "backups", "demo", "compose.yaml"))
require.NoError(t, err)
@@ -525,7 +525,7 @@ func TestGitOpsBackup_CreateWithoutProjectIsRejected(t *testing.T) {
func TestGitOpsBackup_SaveSignalMarksPendingAndRunsAfterDebounce(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
syncRecord := env.createBackupInternal(t, gitops.CreateSyncRequest{})
- firstHead := env.remoteHeadInternal(t, "main")
+ firstHead := env.remoteHeadInternal(t)
env.service.backups.debounce = 50 * time.Millisecond
env.service.SubscribeProjectFileChanges(t.Context())
@@ -538,7 +538,7 @@ func TestGitOpsBackup_SaveSignalMarksPendingAndRunsAfterDebounce(t *testing.T) {
return err == nil && exists && head != firstHead
}, 5*time.Second, 25*time.Millisecond)
require.Positive(t, env.scheduler.submitCount())
- require.NotEqual(t, firstHead, env.remoteHeadInternal(t, "main"))
+ require.NotEqual(t, firstHead, env.remoteHeadInternal(t))
require.Eventually(t, func() bool {
stored := env.reloadInternal(t, syncRecord.ID)
@@ -554,7 +554,7 @@ func TestGitOpsBackup_SaveSignalMarksPendingAndRunsAfterDebounce(t *testing.T) {
func TestGitOpsBackup_SaveSignalOnlyMarksPendingWhenAutoSyncIsOff(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
syncRecord := env.createBackupInternal(t, gitops.CreateSyncRequest{})
- head := env.remoteHeadInternal(t, "main")
+ head := env.remoteHeadInternal(t)
autoSync := false
_, err := env.service.UpdateSync(t.Context(), "0", syncRecord.ID, gitops.UpdateSyncRequest{AutoSync: &autoSync}, common.SystemUser)
@@ -571,7 +571,7 @@ func TestGitOpsBackup_SaveSignalOnlyMarksPendingWhenAutoSyncIsOff(t *testing.T)
}, 5*time.Second, 25*time.Millisecond)
time.Sleep(300 * time.Millisecond)
- assert.Equal(t, head, env.remoteHeadInternal(t, "main"))
+ assert.Equal(t, head, env.remoteHeadInternal(t))
stored := env.reloadInternal(t, syncRecord.ID)
assert.True(t, stored.BackupPending)
@@ -608,9 +608,9 @@ func TestGitOpsBackup_DeletingProjectRemovesBackupSync(t *testing.T) {
func TestGitOpsDeploy_LinksExistingProject(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
- ctx := context.Background()
+ ctx := t.Context()
remoteCompose := "services:\n app:\n image: nginx:1.28-alpine\n"
- env.pushRemoteCommitInternal(t, "main", "seed", map[string]string{"apps/demo/compose.yaml": remoteCompose})
+ env.pushRemoteCommitInternal(t, "seed", map[string]string{"apps/demo/compose.yaml": remoteCompose})
writeBackupProjectFileInternal(t, env.projectPath, ".env", "TOKEN=keep-me\n")
created, err := env.service.CreateSync(ctx, "0", gitops.CreateSyncRequest{
@@ -649,7 +649,7 @@ func TestGitOpsDeploy_LinksExistingProject(t *testing.T) {
func TestGitOpsImport_ForwardsDeployAndLifecycleFields(t *testing.T) {
env := setupGitOpsBackupTestServiceInternal(t)
- ctx := context.Background()
+ ctx := t.Context()
require.NoError(t, env.service.settingsService.SetStringSetting(ctx, "lifecycleEnabled", "true"))
resp, err := env.service.ImportSyncs(ctx, "0", []gitops.ImportGitOpsSyncRequest{
diff --git a/backend/internal/gitops/gitops_sync.go b/backend/internal/gitops/gitops_sync.go
index e74bd0e71..444d3b97f 100644
--- a/backend/internal/gitops/gitops_sync.go
+++ b/backend/internal/gitops/gitops_sync.go
@@ -157,8 +157,16 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,
// toggling unrelated fields on an existing config shouldn't be rejected
// just because the global setting was turned off afterwards.
if lifecycleFieldSet && !s.settingsService.GetBoolSetting(ctx, "lifecycleEnabled", false) {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Pre-deploy lifecycle hooks are disabled. An admin must enable lifecycleEnabled in settings before they can be configured.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployScriptPath",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Pre-deploy lifecycle hooks are disabled. An admin must enable lifecycleEnabled in settings before they can be configured.",
+ ),
+ },
+ )
}
if effectiveScriptPath != "" {
@@ -169,13 +177,31 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,
if in.timeoutSec != nil {
if *in.timeoutSec < 1 {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployTimeoutSec", Err: errors.New("Timeout must be at least 1 second.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployTimeoutSec",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Timeout must be at least 1 second.",
+ ),
+ },
+ )
}
maxTimeoutSec := s.settingsService.GetIntSetting(ctx, "lifecycleMaxTimeoutSec", projectpkg.DefaultMaxTimeoutSec)
if maxTimeoutSec > 0 && *in.timeoutSec > maxTimeoutSec {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployTimeoutSec", Err: fmt.Errorf("Timeout %ds exceeds the lifecycleMaxTimeoutSec setting (%ds).", *in.timeoutSec, maxTimeoutSec)}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployTimeoutSec",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: fmt.Errorf(
+ "Timeout %ds exceeds the lifecycleMaxTimeoutSec setting (%ds).",
+ *in.timeoutSec,
+ maxTimeoutSec,
+ ),
+ },
+ )
}
}
@@ -191,37 +217,85 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,
func (s *GitOpsSyncService) validateLifecycleScriptConfigInternal(ctx context.Context, current *projectpkg.GitOpsSync, in lifecycleConfigInputInternal, scriptPath string) error {
if resolveLifecycleEffectiveTargetTypeInternal(current, in.targetType) == "swarm_stack" {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Pre-deploy lifecycle hooks are only supported for project syncs.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployScriptPath",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Pre-deploy lifecycle hooks are only supported for project syncs.",
+ ),
+ },
+ )
}
if len(scriptPath) > 256 {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Script path must be 256 characters or fewer.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployScriptPath",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Script path must be 256 characters or fewer.",
+ ),
+ },
+ )
}
// scriptPath is a POSIX repo path, not a host path; use path.IsAbs so the
// check behaves the same on Windows-based contributor machines.
if path.IsAbs(filepath.ToSlash(scriptPath)) {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Script path must be relative to the project directory.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployScriptPath",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Script path must be relative to the project directory.",
+ ),
+ },
+ )
}
cleaned := filepath.ToSlash(filepath.Clean(scriptPath))
if cleaned == ".." || strings.HasPrefix(cleaned, "../") {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Script path must not escape the project directory.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployScriptPath",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Script path must not escape the project directory.",
+ ),
+ },
+ )
}
effectiveRunnerImage := resolveLifecycleEffectiveStringInternal(currentStringInternal(current, func(c *projectpkg.GitOpsSync) *string { return c.PreDeployRunnerImage }), in.runnerImage)
defaultRunnerImage := strings.TrimSpace(s.settingsService.GetStringSetting(ctx, "lifecycleDefaultRunnerImage", ""))
if effectiveRunnerImage == "" && defaultRunnerImage == "" {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployRunnerImage", Err: errors.New("Runner image is required when a script path is set.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployRunnerImage",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Runner image is required when a script path is set.",
+ ),
+ },
+ )
}
if !resolveEffectiveSyncDirectoryInternal(current, in.syncDirectory) {
- //nolint:revive // Preserve the existing API validation message.
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "preDeployScriptPath", Err: errors.New("Pre-deploy script requires \"Sync entire directory\" so the script is included in the synced files.")}) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "preDeployScriptPath",
+ //nolint:staticcheck // Preserve the existing error message.
+ Err: errors.New(
+ "Pre-deploy script requires \"Sync entire directory\" so the script is included in the synced files.",
+ ),
+ },
+ )
}
return nil
@@ -359,7 +433,14 @@ func hasEstablishedProjectBindingInternal(sync *projectpkg.GitOpsSync) bool {
return sync != nil && sync.ProjectID != nil && strings.TrimSpace(*sync.ProjectID) != ""
}
-func NewGitOpsSyncService(db *database.DB, repoService *gitrepo.GitRepositoryService, projectService *projectpkg.ProjectService, swarmService *swarm.SwarmService, eventService *event.EventService, settingsService *settings.SettingsService) *GitOpsSyncService {
+func NewGitOpsSyncService(
+ db *database.DB,
+ repoService *gitrepo.GitRepositoryService,
+ projectService *projectpkg.ProjectService,
+ swarmService *swarm.SwarmService,
+ eventService *event.EventService,
+ settingsService *settings.SettingsService,
+) *GitOpsSyncService {
return &GitOpsSyncService{
db: db,
repoService: repoService,
@@ -404,8 +485,8 @@ func (s *GitOpsSyncService) runScheduledSyncInternal(ctx context.Context, enviro
return outcome, nil
}
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: syncID, Status: schedulertypes.Running}); err != nil {
- return schedulertypes.Outcome{}, err
+ if progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: syncID, Status: schedulertypes.Running}); progressErr != nil {
+ return schedulertypes.Outcome{}, progressErr
}
result, err := s.PerformSync(ctx, environmentID, syncID, common.SystemUser)
if err != nil {
@@ -415,8 +496,8 @@ func (s *GitOpsSyncService) runScheduledSyncInternal(ctx context.Context, enviro
if !result.Success {
return schedulertypes.Outcome{Status: schedulertypes.Skipped, Message: result.Message}, nil
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: syncID, Status: schedulertypes.Succeeded}); err != nil {
- return schedulertypes.Outcome{}, err
+ if completeProgressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: syncID, Status: schedulertypes.Succeeded}); completeProgressErr != nil {
+ return schedulertypes.Outcome{}, completeProgressErr
}
return schedulertypes.Outcome{Status: schedulertypes.Succeeded, Message: result.Message}, nil
}
@@ -446,13 +527,13 @@ func (s *GitOpsSyncService) registerSyncJobInternal(ctx context.Context, syncID,
continue
}
var revision syncRevisionInternal
- if err := json.Unmarshal(target.RecoveryData, &revision); err != nil {
- return outcome, err
+ if unmarshalErr := json.Unmarshal(target.RecoveryData, &revision); unmarshalErr != nil {
+ return outcome, unmarshalErr
}
if revision.Commit != "" && record.LastSyncCommit != nil && *record.LastSyncCommit == revision.Commit && record.LastSyncStatus != nil && *record.LastSyncStatus == "success" {
target.Status = schedulertypes.Succeeded
- if err := jobcontext.Progress(ctx, target); err != nil {
- return outcome, err
+ if progressErr := jobcontext.Progress(ctx, target); progressErr != nil {
+ return outcome, progressErr
}
return schedulertypes.Outcome{Status: schedulertypes.Succeeded, Targets: []schedulertypes.TargetOutcome{target}}, nil
}
@@ -714,8 +795,8 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string
if req.RedeployAfterSync != nil {
syncRecord.RedeployAfterSync = *req.RedeployAfterSync
}
- if err := validateSyncLimits(req.MaxSyncFiles, req.MaxSyncTotalSize, req.MaxSyncBinarySize); err != nil {
- return nil, err
+ if validateSyncLimitsErr := validateSyncLimits(req.MaxSyncFiles, req.MaxSyncTotalSize, req.MaxSyncBinarySize); validateSyncLimitsErr != nil {
+ return nil, validateSyncLimitsErr
}
if req.MaxSyncFiles != nil {
syncRecord.MaxSyncFiles = *req.MaxSyncFiles
@@ -737,8 +818,8 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string
networkMode: req.PreDeployNetworkMode,
syncDirectory: req.SyncDirectory,
}
- if err := s.validateLifecycleConfigInternal(ctx, nil, lifecycleCfg); err != nil {
- return nil, err
+ if validateLifecycleConfigErr := s.validateLifecycleConfigInternal(ctx, nil, lifecycleCfg); validateLifecycleConfigErr != nil {
+ return nil, validateLifecycleConfigErr
}
applyLifecycleFieldsToSyncInternal(&syncRecord, lifecycleCfg)
@@ -750,8 +831,8 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string
if adoptedProject != nil {
adoptedProject.GitOpsManagedBy = &syncRecord.ID
- if err := s.projectService.EnsureGitOpsProjectLinked(ctx, &syncRecord, adoptedProject); err != nil {
- return nil, fmt.Errorf("failed to link existing project: %w", err)
+ if ensureGitOpsProjectLinkedErr := s.projectService.EnsureGitOpsProjectLinked(ctx, &syncRecord, adoptedProject); ensureGitOpsProjectLinkedErr != nil {
+ return nil, fmt.Errorf("failed to link existing project: %w", ensureGitOpsProjectLinkedErr)
}
}
@@ -769,8 +850,8 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string
EnvironmentID: new(syncRecord.EnvironmentID),
})
- if _, err := s.PerformSync(ctx, syncRecord.EnvironmentID, syncRecord.ID, actor); err != nil {
- slog.ErrorContext(ctx, "Failed to perform initial sync after creation", "syncId", syncRecord.ID, "error", err)
+ if _, performSyncErr := s.PerformSync(ctx, syncRecord.EnvironmentID, syncRecord.ID, actor); performSyncErr != nil {
+ slog.ErrorContext(ctx, "Failed to perform initial sync after creation", "syncId", syncRecord.ID, "error", performSyncErr)
// Don't fail the entire creation - the sync config exists and can be retried
}
@@ -798,16 +879,16 @@ func (s *GitOpsSyncService) prepareDeployProjectLinkInternal(ctx context.Context
return nil, common.Classify(common.ErrConflict, errors.New("project is already deployed from Git"))
}
var backups int64
- if err := tx.Model(&projectpkg.GitOpsSync{}).
+ if countBackupsErr := tx.Model(&projectpkg.GitOpsSync{}).
Where("mode = ? AND project_id = ?", gitops.SyncModeBackup, project.ID).
- Count(&backups).Error; err != nil {
- return nil, fmt.Errorf("failed to check existing backups: %w", err)
+ Count(&backups).Error; countBackupsErr != nil {
+ return nil, fmt.Errorf("failed to check existing backups: %w", countBackupsErr)
}
if backups > 0 {
return nil, common.Classify(common.ErrConflict, errors.New("project is backed up to Git; disconnect that backup before deploying it from Git"))
}
- if err := s.projectService.EnsureProjectPathUnderRoot(ctx, project, false); err != nil {
- return nil, err
+ if ensureProjectPathUnderRootErr := s.projectService.EnsureProjectPathUnderRoot(ctx, project, false); ensureProjectPathUnderRootErr != nil {
+ return nil, ensureProjectPathUnderRootErr
}
return project, nil
}
@@ -910,9 +991,9 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id st
}
if req.RepositoryID != nil {
// Validate repository exists
- _, err := s.repoService.GetRepositoryByID(ctx, *req.RepositoryID)
- if err != nil {
- return nil, fmt.Errorf("repository not found: %w", err)
+ _, getRepositoryByIDErr := s.repoService.GetRepositoryByID(ctx, *req.RepositoryID)
+ if getRepositoryByIDErr != nil {
+ return nil, fmt.Errorf("repository not found: %w", getRepositoryByIDErr)
}
updates["repository_id"] = *req.RepositoryID
}
@@ -943,8 +1024,8 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id st
if req.RedeployAfterSync != nil {
updates["redeploy_after_sync"] = *req.RedeployAfterSync
}
- if err := validateSyncLimits(req.MaxSyncFiles, req.MaxSyncTotalSize, req.MaxSyncBinarySize); err != nil {
- return nil, err
+ if validateSyncLimitsErr := validateSyncLimits(req.MaxSyncFiles, req.MaxSyncTotalSize, req.MaxSyncBinarySize); validateSyncLimitsErr != nil {
+ return nil, validateSyncLimitsErr
}
if req.MaxSyncFiles != nil {
updates["max_sync_files"] = *req.MaxSyncFiles
@@ -956,8 +1037,8 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id st
updates["max_sync_binary_size"] = *req.MaxSyncBinarySize
}
- if err := s.applyModeUpdatesInternal(ctx, syncRecord, req, updates); err != nil {
- return nil, err
+ if applyModeUpdatesErr := s.applyModeUpdatesInternal(ctx, syncRecord, req, updates); applyModeUpdatesErr != nil {
+ return nil, applyModeUpdatesErr
}
lifecycleCfg := lifecycleConfigInputInternal{
@@ -970,15 +1051,15 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id st
networkMode: req.PreDeployNetworkMode,
syncDirectory: req.SyncDirectory,
}
- if err := s.validateLifecycleConfigInternal(ctx, syncRecord, lifecycleCfg); err != nil {
- return nil, err
+ if validateLifecycleConfigErr := s.validateLifecycleConfigInternal(ctx, syncRecord, lifecycleCfg); validateLifecycleConfigErr != nil {
+ return nil, validateLifecycleConfigErr
}
addLifecycleUpdatesInternal(updates, lifecycleCfg)
if len(updates) > 0 {
// Loaded associations must not overwrite explicitly updated foreign keys.
- if err := s.db.WithContext(ctx).Model(syncRecord).Omit(clause.Associations).Updates(updates).Error; err != nil {
- return nil, fmt.Errorf("failed to update sync: %w", err)
+ if updateSyncErr := s.db.WithContext(ctx).Model(syncRecord).Omit(clause.Associations).Updates(updates).Error; updateSyncErr != nil {
+ return nil, fmt.Errorf("failed to update sync: %w", updateSyncErr)
}
// Log event
@@ -1177,9 +1258,9 @@ func (s *GitOpsSyncService) prepareSyncSource(ctx context.Context, sync *project
envPath := filepath.Join(filepath.Dir(sync.ComposePath), ".env")
if s.repoService.FileExists(ctx, repoPath, envPath) {
- content, err := s.repoService.ReadFile(ctx, repoPath, envPath)
- if err != nil {
- slog.WarnContext(ctx, "Failed to read .env file", "path", envPath, "error", err)
+ content, readFileErr := s.repoService.ReadFile(ctx, repoPath, envPath)
+ if readFileErr != nil {
+ slog.WarnContext(ctx, "Failed to read .env file", "path", envPath, "error", readFileErr)
} else {
source.envContent = &content
}
@@ -1234,8 +1315,8 @@ func pinSyncRevisionInternal(ctx context.Context, syncID, repoPath, commitHash s
if err != nil {
return "", err
}
- if err := tree.Checkout(&gogit.CheckoutOptions{Hash: plumbing.NewHash(revision.Commit)}); err != nil {
- return "", err
+ if checkoutErr := tree.Checkout(&gogit.CheckoutOptions{Hash: plumbing.NewHash(revision.Commit)}); checkoutErr != nil {
+ return "", checkoutErr
}
commitHash = revision.Commit
}
@@ -1248,15 +1329,27 @@ func pinSyncRevisionInternal(ctx context.Context, syncID, repoPath, commitHash s
if commitHash == "" {
return "", errors.New("GitOps source revision is unavailable")
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "gitops_sync", ID: syncID, Status: schedulertypes.Running, RecoveryData: revision}); err != nil {
- return "", err
+ if progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "gitops_sync", ID: syncID, Status: schedulertypes.Running, RecoveryData: revision}); progressErr != nil {
+ return "", progressErr
}
return commitHash, nil
}
// performDirectorySync runs the directory-sync path and only triggers a
// redeploy when an already running project's synced contents changed.
-func (s *GitOpsSyncService) performDirectorySync(ctx context.Context, sync *projectpkg.GitOpsSync, id string, actor common.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {
+func (
+ s *GitOpsSyncService,
+) performDirectorySync(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ id string,
+ actor common.User,
+ result *gitops.SyncResult,
+ source *preparedSyncSource,
+) (
+ *gitops.SyncResult,
+ error,
+) {
slog.InfoContext(ctx, "Using directory sync mode", "syncId", id, "composePath", sync.ComposePath)
syncFiles, err := s.walkAndParseSyncDirectory(ctx, sync, source.repoPath)
@@ -1306,7 +1399,19 @@ func singleFileSyncedFilesInternal(sync *projectpkg.GitOpsSync, source *prepared
}
// performSingleFileSyncInternal preserves the legacy compose-only Git sync behavior.
-func (s *GitOpsSyncService) performSingleFileSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, actor common.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {
+func (
+ s *GitOpsSyncService,
+) performSingleFileSyncInternal(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ id string,
+ actor common.User,
+ result *gitops.SyncResult,
+ source *preparedSyncSource,
+) (
+ *gitops.SyncResult,
+ error,
+) {
slog.InfoContext(ctx, "Using single file sync mode", "syncId", id, "composePath", sync.ComposePath)
// Single-file sync copies only the one compose file (plus .env and a sibling
@@ -1358,7 +1463,19 @@ func buildSwarmStackDeployRequestInternal(sync *projectpkg.GitOpsSync, source *p
}
// performSwarmStackSyncInternal executes a single file sync targeted at a Swarm Stack
-func (s *GitOpsSyncService) performSwarmStackSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, actor common.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {
+func (
+ s *GitOpsSyncService,
+) performSwarmStackSyncInternal(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ id string,
+ actor common.User,
+ result *gitops.SyncResult,
+ source *preparedSyncSource,
+) (
+ *gitops.SyncResult,
+ error,
+) {
slog.InfoContext(ctx, "Deploying Swarm Stack from GitOps sync", "syncId", id, "stackName", sync.ProjectName)
if s.swarmService == nil {
@@ -1448,9 +1565,9 @@ func (s *GitOpsSyncService) redeployIfRunningAfterSync(ctx context.Context, sync
}
slog.InfoContext(ctx, "Redeploying project due to content change from Git sync", "syncMode", syncMode, "projectName", project.Name, "projectId", project.ID, "wasRunning", running)
- if err := s.projectService.RedeployProject(ctx, project.ID, actor, nil); err != nil {
- slog.ErrorContext(ctx, "Failed to redeploy project after Git sync", "syncMode", syncMode, "error", err, "projectId", project.ID)
- return common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", err))
+ if redeployProjectErr := s.projectService.RedeployProject(ctx, project.ID, actor, nil); redeployProjectErr != nil {
+ slog.ErrorContext(ctx, "Failed to redeploy project after Git sync", "syncMode", syncMode, "error", redeployProjectErr, "projectId", project.ID)
+ return common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", redeployProjectErr))
}
return nil
}
@@ -1656,7 +1773,7 @@ func (s *GitOpsSyncService) ReconcileDirectorySyncProjectsOnStartup(ctx context.
return nil
}
-func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id, path string) (*gitops.BrowseResponse, error) {
+func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id, localPath string) (*gitops.BrowseResponse, error) {
browseCtx, cancel := context.WithTimeout(ctx, defaultGitSyncTimeout)
defer cancel()
@@ -1683,13 +1800,13 @@ func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id,
defer s.repoService.Discard(browseCtx, repoPath)
// Browse the tree
- files, err := s.repoService.BrowseTree(browseCtx, repoPath, path)
+ files, err := s.repoService.BrowseTree(browseCtx, repoPath, localPath)
if err != nil {
return nil, err
}
return &gitops.BrowseResponse{
- Path: path,
+ Path: localPath,
Files: files,
}, nil
}
@@ -1767,7 +1884,17 @@ func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *git
// lifecycle hook returning non-zero). The synced-files list and commit hash
// are preserved on the row so operators can see what reached disk; the
// error message surfaces the redeploy failure on LastSyncError.
-func (s *GitOpsSyncService) markSyncRedeployFailedInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id, commitHash string, syncedFiles []string, redeployErr error, actor common.User, result *gitops.SyncResult) {
+func (
+ s *GitOpsSyncService,
+) markSyncRedeployFailedInternal(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ id, commitHash string,
+ syncedFiles []string,
+ redeployErr error,
+ actor common.User,
+ result *gitops.SyncResult,
+) {
errMsg := redeployErr.Error()
result.Success = false
result.Message = "Sync wrote files but redeploy failed"
@@ -1790,7 +1917,17 @@ func (s *GitOpsSyncService) disableAutoSyncForBrokenBindingInternal(ctx context.
s.unregisterSyncJobInternal(ctx, sync.ID)
}
-func (s *GitOpsSyncService) failSyncAndDisableAutoSyncInternal(ctx context.Context, id string, result *gitops.SyncResult, sync *projectpkg.GitOpsSync, actor common.User, message string, failure error) error {
+func (
+ s *GitOpsSyncService,
+) failSyncAndDisableAutoSyncInternal(
+ ctx context.Context,
+ id string,
+ result *gitops.SyncResult,
+ sync *projectpkg.GitOpsSync,
+ actor common.User,
+ message string,
+ failure error,
+) error {
errMsg := failure.Error()
_ = s.failSync(ctx, id, result, sync, actor, message, errMsg)
s.disableAutoSyncForBrokenBindingInternal(ctx, sync)
@@ -1807,14 +1944,37 @@ func (s *GitOpsSyncService) recordBrokenProjectBindingInternal(ctx context.Conte
s.disableAutoSyncForBrokenBindingInternal(ctx, sync)
}
-func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id, composeContent string, envContent, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {
+func (
+ s *GitOpsSyncService,
+) createProjectForSyncInternal(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ id, composeContent string,
+ envContent, overrideContent *string,
+ overrideFileName string,
+ result *gitops.SyncResult,
+ actor common.User,
+) (
+ *projectpkg.Project,
+ error,
+) {
// Use the non-suffixing create: a GitOps sync must never mint a "-N" duplicate.
// A name collision means a project directory already exists for this name, so the
// binding is broken — fail loudly and disable auto-sync instead of duplicating.
project, err := s.projectService.CreateProject(ctx, sync.ProjectName, composeContent, envContent, projecttypes.CreateProjectWorkspaceManifest{}, nil, nil, nil, actor, false)
if err != nil {
if errors.Is(err, projects.ErrProjectDirExists) {
- bindingErr := common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s cannot create project %q: a directory with that name already exists; refusing to create a duplicate", sync.ID, projects.SanitizeProjectName(sync.ProjectName)))
+ bindingErr := common.Classify(
+ common.ErrGitOpsSyncProjectBindingBroken,
+ fmt.Errorf(
+ "GitOps sync project binding broken: sync %s cannot create project %q: a directory with that name "+
+ "already exists; refusing to create a duplicate",
+ sync.ID,
+ projects.SanitizeProjectName(
+ sync.ProjectName,
+ ),
+ ),
+ )
return nil, s.failSyncAndDisableAutoSyncInternal(ctx, id, result, sync, actor, "GitOps project binding broken", bindingErr)
}
@@ -1822,19 +1982,21 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sy
}
// Update sync with project ID
- if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", id).Updates(map[string]any{
+ if linkSyncProjectErr := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", id).Updates(map[string]any{
"project_id": project.ID,
- }).Error; err != nil {
- return nil, s.failSync(ctx, id, result, sync, actor, "Failed to update sync with project ID", err.Error())
+ }).Error; linkSyncProjectErr != nil {
+ return nil, s.failSync(ctx, id, result, sync, actor, "Failed to update sync with project ID", linkSyncProjectErr.Error())
}
// Mark project as GitOps-managed
- if err := s.db.WithContext(ctx).Model(&projectpkg.Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", id).Error; err != nil {
- return nil, s.failSync(ctx, id, result, sync, actor, "Failed to mark project as GitOps-managed", err.Error())
+ if markProjectManagedErr := s.db.WithContext(ctx).Model(&projectpkg.Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", id).Error; markProjectManagedErr != nil {
+ return nil, s.failSync(ctx, id, result, sync, actor, "Failed to mark project as GitOps-managed", markProjectManagedErr.Error())
}
- if _, _, err := s.projectService.ApplyGitSyncProjectFiles(ctx, project.ID, composeContent, envContent, overrideContent, overrideFileName, actor); err != nil {
- return nil, s.failSync(ctx, id, result, sync, actor, "Failed to sync project env files", err.Error())
+ if _, _, applyGitSyncProjectFilesErr := s.projectService.ApplyGitSyncProjectFiles(
+ ctx, project.ID, composeContent, envContent, overrideContent, overrideFileName, actor,
+ ); applyGitSyncProjectFilesErr != nil {
+ return nil, s.failSync(ctx, id, result, sync, actor, "Failed to sync project env files", applyGitSyncProjectFilesErr.Error())
}
slog.InfoContext(ctx, "Created project for GitOps sync", "projectName", sync.ProjectName, "projectId", project.ID)
@@ -1845,18 +2007,31 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sy
// silently leaving the new project undeployed with no image pulled.
if sync.RedeployAfterSync {
slog.InfoContext(ctx, "Redeploying newly created project from Git sync", "projectName", project.Name, "projectId", project.ID)
- if err := s.projectService.RedeployProject(ctx, project.ID, actor, nil); err != nil {
- slog.ErrorContext(ctx, "Failed to redeploy newly created project after Git sync", "error", err, "projectId", project.ID)
- return nil, common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", err))
+ if redeployProjectErr := s.projectService.RedeployProject(ctx, project.ID, actor, nil); redeployProjectErr != nil {
+ slog.ErrorContext(ctx, "Failed to redeploy newly created project after Git sync", "error", redeployProjectErr, "projectId", project.ID)
+ return nil, common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", redeployProjectErr))
}
- } else if err := s.pullImageAfterSyncIfConfiguredInternal(ctx, sync, project, actor); err != nil {
- return nil, err
+ } else if pullImageAfterSyncIfConfiguredErr := s.pullImageAfterSyncIfConfiguredInternal(ctx, sync, project, actor); pullImageAfterSyncIfConfiguredErr != nil {
+ return nil, pullImageAfterSyncIfConfiguredErr
}
return project, nil
}
-func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id, composeContent string, envContent, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {
+func (
+ s *GitOpsSyncService,
+) getOrCreateProjectInternal(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ id, composeContent string,
+ envContent, overrideContent *string,
+ overrideFileName string,
+ result *gitops.SyncResult,
+ actor common.User,
+) (
+ *projectpkg.Project,
+ error,
+) {
var project *projectpkg.Project
if sync.ProjectID != nil && *sync.ProjectID != "" {
@@ -1884,8 +2059,22 @@ func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, sync
return project, nil
}
-func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, project *projectpkg.Project, composeContent string, envContent, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) error {
- _, changed, err := s.projectService.ApplyGitSyncProjectFiles(ctx, project.ID, composeContent, envContent, overrideContent, overrideFileName, actor)
+func (
+ s *GitOpsSyncService,
+) updateProjectForSyncInternal(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ id string,
+ project *projectpkg.Project,
+ composeContent string,
+ envContent, overrideContent *string,
+ overrideFileName string,
+ result *gitops.SyncResult,
+ actor common.User,
+) error {
+ _, changed, err := s.projectService.ApplyGitSyncProjectFiles(
+ ctx, project.ID, composeContent, envContent, overrideContent, overrideFileName, actor,
+ )
if err != nil {
return s.failSync(ctx, id, result, sync, actor, "Failed to update project files", err.Error())
}
@@ -1966,7 +2155,20 @@ func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, sync
// syncProjectDirectoryInternal runs the new directory-sync path end to end:
// stage files, validate the staged tree, then create or update the project.
-func (s *GitOpsSyncService) syncProjectDirectoryInternal(ctx context.Context, sync *projectpkg.GitOpsSync, syncFiles []projects.SyncFile, actor common.User) (*projectpkg.Project, []string, bool, bool, error) {
+func (
+ s *GitOpsSyncService,
+) syncProjectDirectoryInternal(
+ ctx context.Context,
+ sync *projectpkg.GitOpsSync,
+ syncFiles []projects.SyncFile,
+ actor common.User,
+) (
+ *projectpkg.Project,
+ []string,
+ bool,
+ bool,
+ error,
+) {
stage, err := s.stageDirectorySyncInternal(ctx, sync, syncFiles)
if err != nil {
s.recordBrokenProjectBindingInternal(ctx, sync, actor, err)
@@ -1981,12 +2183,12 @@ func (s *GitOpsSyncService) syncProjectDirectoryInternal(ctx context.Context, sy
}()
if stage.project == nil {
- project, err := s.createDirectorySyncProjectInternal(ctx, sync, stage, actor)
- if err != nil {
+ project, createDirectorySyncProjectErr := s.createDirectorySyncProjectInternal(ctx, sync, stage, actor)
+ if createDirectorySyncProjectErr != nil {
// A name-collision on create surfaces as a broken-binding error; disable
// auto-sync so it cannot keep retrying (no-op for other error kinds).
- s.recordBrokenProjectBindingInternal(ctx, sync, actor, err)
- return nil, nil, false, false, err
+ s.recordBrokenProjectBindingInternal(ctx, sync, actor, createDirectorySyncProjectErr)
+ return nil, nil, false, false, createDirectorySyncProjectErr
}
return project, stage.syncedFiles, true, true, nil
}
@@ -2056,18 +2258,18 @@ func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, sync
}
stage.backupScope.Paths = slices.Concat(stage.syncedFiles, stage.oldSyncedFiles, staleFiles,
[]string{projects.EffectiveEnvFileName, projects.GitSourceEnvFileName, projects.OverrideEnvFileName})
- if err := linkProjectIntoStageInternal(stage.project.Path, stage.stagePath, stage.backupScope.Paths); err != nil {
- return nil, fmt.Errorf("failed to stage current project files: %w", err)
+ if linkProjectIntoStageErr := linkProjectIntoStageInternal(stage.project.Path, stage.stagePath, stage.backupScope.Paths); linkProjectIntoStageErr != nil {
+ return nil, fmt.Errorf("failed to stage current project files: %w", linkProjectIntoStageErr)
}
- if _, err := seedStageEnvFromDirInternal(ctx, stage.project.Path, projectsDir, stage.stagePath); err != nil {
- return nil, err
+ if _, seedStageEnvFromDirErr := seedStageEnvFromDirInternal(ctx, stage.project.Path, projectsDir, stage.stagePath); seedStageEnvFromDirErr != nil {
+ return nil, seedStageEnvFromDirErr
}
stage.contentsChanged, err = projects.DirectorySyncContentsChanged(ctx, stage.project.Path, filteredSyncFiles, stage.oldSyncedFiles, stage.composeFileName)
if err != nil {
return nil, fmt.Errorf("failed to compare staged directory changes: %w", err)
}
- } else if err := s.seedStageEnvFromCandidateDirInternal(ctx, sync, projectsDir, stage.stagePath); err != nil {
- return nil, err
+ } else if seedStageEnvFromCandidateDirErr := s.seedStageEnvFromCandidateDirInternal(ctx, sync, projectsDir, stage.stagePath); seedStageEnvFromCandidateDirErr != nil {
+ return nil, seedStageEnvFromCandidateDirErr
}
preEnvContent, postEnvContent, err := s.applyDirectorySyncInternal(ctx, stage.stagePath, stage)
@@ -2144,16 +2346,16 @@ func linkProjectIntoStageInternal(livePath, stagePath string, scopePaths []strin
}
stageEntry := filepath.Join(stagePath, filepath.FromSlash(entryRel))
if _, isAncestor := ancestors[entryRel]; isAncestor && entry.IsDir() {
- if err := os.Mkdir(stageEntry, utils.DirPerm); err != nil {
- return err
+ if mkdirErr := os.Mkdir(stageEntry, utils.DirPerm); mkdirErr != nil {
+ return mkdirErr
}
- if err := link(entryRel); err != nil {
- return err
+ if linkErr := link(entryRel); linkErr != nil {
+ return linkErr
}
continue
}
- if err := os.Symlink(filepath.Join(livePath, filepath.FromSlash(entryRel)), stageEntry); err != nil {
- return err
+ if symlinkErr := os.Symlink(filepath.Join(livePath, filepath.FromSlash(entryRel)), stageEntry); symlinkErr != nil {
+ return symlinkErr
}
}
return nil
@@ -2233,18 +2435,18 @@ func seedStageEnvFromDirInternal(ctx context.Context, sourceDir, projectsDir, st
return state, fmt.Errorf("read env files from %s: %w", sourceDir, err)
}
if state.HasGitSource {
- if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.GitSourceEnvFileName, state.GitContent); err != nil {
- return state, fmt.Errorf("seed stage .env.git: %w", err)
+ if writeProjectFileErr := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.GitSourceEnvFileName, state.GitContent); writeProjectFileErr != nil {
+ return state, fmt.Errorf("seed stage .env.git: %w", writeProjectFileErr)
}
}
if state.HasOverride {
- if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.OverrideEnvFileName, state.OverrideContent); err != nil {
- return state, fmt.Errorf("seed stage project.env: %w", err)
+ if writeOverrideEnvErr := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.OverrideEnvFileName, state.OverrideContent); writeOverrideEnvErr != nil {
+ return state, fmt.Errorf("seed stage project.env: %w", writeOverrideEnvErr)
}
}
if state.HasEffective {
- if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.EffectiveEnvFileName, state.DirectContent); err != nil {
- return state, fmt.Errorf("seed stage .env: %w", err)
+ if writeEffectiveEnvErr := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.EffectiveEnvFileName, state.DirectContent); writeEffectiveEnvErr != nil {
+ return state, fmt.Errorf("seed stage .env: %w", writeEffectiveEnvErr)
}
}
return state, nil
@@ -2284,8 +2486,8 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Con
if mergeErr != nil {
return fmt.Errorf("build effective env from pre-existing project: %w", mergeErr)
}
- if err := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.EffectiveEnvFileName, merged); err != nil {
- return fmt.Errorf("seed stage .env: %w", err)
+ if writeProjectFileErr := projects.WriteProjectFile(ctx, projectsDir, stagePath, projects.EffectiveEnvFileName, merged); writeProjectFileErr != nil {
+ return fmt.Errorf("seed stage .env: %w", writeProjectFileErr)
}
}
@@ -2444,11 +2646,11 @@ func (s *GitOpsSyncService) recoverProjectFromDirectoryCandidateInternal(ctx con
return nil, err
}
if found {
- if err := s.projectService.EnsureProjectPathUnderRoot(ctx, project, true); err != nil {
- return nil, err
+ if ensureProjectPathUnderRootErr := s.projectService.EnsureProjectPathUnderRoot(ctx, project, true); ensureProjectPathUnderRootErr != nil {
+ return nil, ensureProjectPathUnderRootErr
}
- if err := s.projectService.EnsureGitOpsProjectLinked(ctx, sync, project); err != nil {
- return nil, err
+ if ensureGitOpsProjectLinkedErr := s.projectService.EnsureGitOpsProjectLinked(ctx, sync, project); ensureGitOpsProjectLinkedErr != nil {
+ return nil, ensureGitOpsProjectLinkedErr
}
return project, nil
}
@@ -2470,11 +2672,11 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,
return nil, err
}
if found {
- if err := s.projectService.EnsureProjectPathUnderRoot(ctx, project, true); err != nil {
- return nil, err
+ if ensureProjectPathUnderRootErr := s.projectService.EnsureProjectPathUnderRoot(ctx, project, true); ensureProjectPathUnderRootErr != nil {
+ return nil, ensureProjectPathUnderRootErr
}
- if err := s.projectService.EnsureGitOpsProjectLinked(ctx, sync, project); err != nil {
- return nil, err
+ if ensureGitOpsProjectLinkedErr := s.projectService.EnsureGitOpsProjectLinked(ctx, sync, project); ensureGitOpsProjectLinkedErr != nil {
+ return nil, ensureGitOpsProjectLinkedErr
}
return project, nil
}
@@ -2482,12 +2684,20 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,
slog.WarnContext(ctx, "Existing project not found, attempting recovery", "projectId", *sync.ProjectID, "syncId", sync.ID)
}
- project, err := s.findRecoverableManagedProjectInternal(ctx, sync)
- if err != nil {
+ project, findRecoverableManagedProjectErr := s.findRecoverableManagedProjectInternal(ctx, sync)
+ if findRecoverableManagedProjectErr != nil {
if establishedBinding {
- return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s references missing project %s: %w", sync.ID, *sync.ProjectID, err))
+ return nil, common.Classify(
+ common.ErrGitOpsSyncProjectBindingBroken,
+ fmt.Errorf(
+ "GitOps sync project binding broken: sync %s references missing project %s: %w",
+ sync.ID,
+ *sync.ProjectID,
+ findRecoverableManagedProjectErr,
+ ),
+ )
}
- return nil, err
+ return nil, findRecoverableManagedProjectErr
}
if project != nil {
if err := s.projectService.EnsureGitOpsProjectLinked(ctx, sync, project); err != nil {
@@ -2496,19 +2706,34 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,
return project, nil
}
- project, err = s.recoverProjectFromDirectoryCandidateInternal(ctx, sync)
- if err != nil {
+ project, findRecoverableManagedProjectErr = s.recoverProjectFromDirectoryCandidateInternal(ctx, sync)
+ if findRecoverableManagedProjectErr != nil {
if establishedBinding {
- return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s references missing project %s: %w", sync.ID, *sync.ProjectID, err))
+ return nil, common.Classify(
+ common.ErrGitOpsSyncProjectBindingBroken,
+ fmt.Errorf(
+ "GitOps sync project binding broken: sync %s references missing project %s: %w",
+ sync.ID,
+ *sync.ProjectID,
+ findRecoverableManagedProjectErr,
+ ),
+ )
}
- return nil, err
+ return nil, findRecoverableManagedProjectErr
}
if project != nil {
return project, nil
}
if establishedBinding {
- return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s references missing project %s: no unique recovery candidate was found", sync.ID, *sync.ProjectID))
+ return nil, common.Classify(
+ common.ErrGitOpsSyncProjectBindingBroken,
+ fmt.Errorf(
+ "GitOps sync project binding broken: sync %s references missing project %s: no unique recovery candidate was found",
+ sync.ID,
+ *sync.ProjectID,
+ ),
+ )
}
return nil, nil
@@ -2530,7 +2755,17 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Conte
projectPath, folderName, err := projects.CreateExactDir(ctx, projectsDir, basePath, sync.ProjectName, utils.DirPerm)
if err != nil {
if errors.Is(err, projects.ErrProjectDirExists) {
- return nil, common.Classify(common.ErrGitOpsSyncProjectBindingBroken, fmt.Errorf("GitOps sync project binding broken: sync %s cannot create project %q: a directory with that name already exists; refusing to create a duplicate", sync.ID, projects.SanitizeProjectName(sync.ProjectName)))
+ return nil, common.Classify(
+ common.ErrGitOpsSyncProjectBindingBroken,
+ fmt.Errorf(
+ "GitOps sync project binding broken: sync %s cannot create project %q: a directory with that name "+
+ "already exists; refusing to create a duplicate",
+ sync.ID,
+ projects.SanitizeProjectName(
+ sync.ProjectName,
+ ),
+ ),
+ )
}
return nil, fmt.Errorf("failed to create project directory: %w", err)
}
@@ -2539,18 +2774,18 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Conte
if err != nil {
return nil, fmt.Errorf("failed to resolve created project directory: %w", err)
}
- if err := acfs.Remove(ctx, projectsDir, projectLogical); err != nil {
- return nil, fmt.Errorf("failed to prepare project directory: %w", err)
+ if removeErr := acfs.Remove(ctx, projectsDir, projectLogical); removeErr != nil {
+ return nil, fmt.Errorf("failed to prepare project directory: %w", removeErr)
}
- if err := acfs.Rename(ctx, projectsDir, stage.stageLogical, projectLogical); err != nil {
- return nil, fmt.Errorf("failed to promote staged project directory: %w", err)
+ if renameErr := acfs.Rename(ctx, projectsDir, stage.stageLogical, projectLogical); renameErr != nil {
+ return nil, fmt.Errorf("failed to promote staged project directory: %w", renameErr)
}
stage.stagePath = ""
- if err := os.Chmod(projectPath, utils.DirPerm); err != nil {
+ if chmodErr := os.Chmod(projectPath, utils.DirPerm); chmodErr != nil {
_ = acfs.RemoveAll(ctx, projectsDir, projectLogical)
- return nil, fmt.Errorf("failed to set project directory permissions: %w", err)
+ return nil, fmt.Errorf("failed to set project directory permissions: %w", chmodErr)
}
project := &projectpkg.Project{
@@ -2562,9 +2797,9 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Conte
RunningCount: 0,
}
- if err := s.projectService.CreateGitOpsManagedProject(ctx, sync, project, actor); err != nil {
+ if createGitOpsManagedProjectErr := s.projectService.CreateGitOpsManagedProject(ctx, sync, project, actor); createGitOpsManagedProjectErr != nil {
_ = acfs.RemoveAll(ctx, projectsDir, projectLogical)
- return nil, err
+ return nil, createGitOpsManagedProjectErr
}
return project, nil
@@ -2586,11 +2821,11 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Conte
}
} else if errors.Is(err, os.ErrNotExist) {
existed = false
- if err := os.MkdirAll(projectPath, utils.DirPerm); err != nil {
- return nil, fmt.Errorf("failed to recreate project directory: %w", err)
+ if mkdirAllErr := os.MkdirAll(projectPath, utils.DirPerm); mkdirAllErr != nil {
+ return nil, fmt.Errorf("failed to recreate project directory: %w", mkdirAllErr)
}
- if err := os.Chmod(projectPath, utils.DirPerm); err != nil {
- return nil, fmt.Errorf("failed to set project directory permissions: %w", err)
+ if chmodErr := os.Chmod(projectPath, utils.DirPerm); chmodErr != nil {
+ return nil, fmt.Errorf("failed to set project directory permissions: %w", chmodErr)
}
} else {
return nil, fmt.Errorf("failed to inspect current project directory: %w", err)
diff --git a/backend/internal/gitops/handler.go b/backend/internal/gitops/handler.go
index e8f33fdd3..d89039705 100644
--- a/backend/internal/gitops/handler.go
+++ b/backend/internal/gitops/handler.go
@@ -119,19 +119,163 @@ func RegisterGitOpsSyncs(api huma.API, syncService *GitOpsSyncService) {
const basePath = "/environments/{id}/gitops-syncs"
const syncPath = basePath + "/{syncId}"
- handlerutil.RegisterSecured(api, handlerutil.Operation("listGitOpsSyncs", "GET", basePath, "List GitOps syncs", "Get a paginated list of GitOps syncs for an environment", "GitOps Syncs"), authz.PermGitOpsList, h.ListSyncs)
- handlerutil.RegisterSecured(api, handlerutil.Operation("createGitOpsSync", "POST", basePath, "Create a GitOps sync", "Create a new GitOps sync configuration for an environment", "GitOps Syncs"), authz.PermGitOpsCreate, h.CreateSync)
- handlerutil.RegisterSecured(api, handlerutil.Operation("importGitOpsSyncs", "POST", basePath+"/import", "Import GitOps syncs", "Import multiple GitOps sync configurations from JSON", "GitOps Syncs"), authz.PermGitOpsCreate, h.ImportSyncs)
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "listGitOpsSyncs",
+ "GET",
+ basePath,
+ "List GitOps syncs",
+ "Get a paginated list of GitOps syncs for an environment",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsList,
+ h.ListSyncs,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "createGitOpsSync",
+ "POST",
+ basePath,
+ "Create a GitOps sync",
+ "Create a new GitOps sync configuration for an environment",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsCreate,
+ h.CreateSync,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "importGitOpsSyncs",
+ "POST",
+ basePath+"/import",
+ "Import GitOps syncs",
+ "Import multiple GitOps sync configurations from JSON",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsCreate,
+ h.ImportSyncs,
+ )
handlerutil.RegisterSecured(api, handlerutil.Operation("getGitOpsSync", "GET", syncPath, "Get a GitOps sync", "Get a GitOps sync by ID", "GitOps Syncs"), authz.PermGitOpsRead, h.GetSync)
- handlerutil.RegisterSecured(api, handlerutil.Operation("updateGitOpsSync", "PUT", syncPath, "Update a GitOps sync", "Update an existing GitOps sync configuration", "GitOps Syncs"), authz.PermGitOpsUpdate, h.UpdateSync)
- handlerutil.RegisterSecured(api, handlerutil.Operation("deleteGitOpsSync", "DELETE", syncPath, "Delete a GitOps sync", "Delete a GitOps sync configuration by ID", "GitOps Syncs"), authz.PermGitOpsDelete, h.DeleteSync)
- handlerutil.RegisterSecured(api, handlerutil.Operation("performGitOpsSync", "POST", syncPath+"/sync", "Perform a GitOps sync", "Manually trigger a sync operation", "GitOps Syncs"), authz.PermGitOpsSync, h.PerformSync)
- handlerutil.RegisterSecured(api, handlerutil.Operation("getGitOpsSyncStatus", "GET", syncPath+"/status", "Get GitOps sync status", "Get the current status of a GitOps sync", "GitOps Syncs"), authz.PermGitOpsRead, h.GetStatus)
- handlerutil.RegisterSecured(api, handlerutil.Operation("browseGitOpsSyncFiles", "GET", syncPath+"/files", "Browse GitOps sync files", "Browse files in the synced repository", "GitOps Syncs"), authz.PermGitOpsRead, h.BrowseFiles)
- handlerutil.RegisterSecured(api, handlerutil.Operation("previewGitOpsBackup", "GET", syncPath+"/backup/preview", "Preview a Git backup", "Show the files the next backup would commit and any conflicts", "GitOps Syncs"), authz.PermGitOpsBackup, h.PreviewBackup)
- handlerutil.RegisterSecured(api, handlerutil.Operation("listGitOpsBackupHistory", "GET", syncPath+"/backup/history", "List Git backup history", "List repository revisions that changed the backup", "GitOps Syncs"), authz.PermGitOpsBackup, h.BackupHistory)
- handlerutil.RegisterSecured(api, handlerutil.Operation("getGitOpsBackupRevision", "GET", syncPath+"/backup/history/{commit}", "Get a Git backup revision", "Get one revision with per-file diffs", "GitOps Syncs"), authz.PermGitOpsBackup, h.BackupRevision)
- handlerutil.RegisterSecured(api, handlerutil.Operation("resolveGitOpsBackupConflict", "POST", syncPath+"/backup/resolve", "Resolve a Git backup conflict", "Resolve a backup that needs attention", "GitOps Syncs"), authz.PermGitOpsBackup, h.ResolveBackupConflict)
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "updateGitOpsSync",
+ "PUT",
+ syncPath,
+ "Update a GitOps sync",
+ "Update an existing GitOps sync configuration",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsUpdate,
+ h.UpdateSync,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "deleteGitOpsSync",
+ "DELETE",
+ syncPath,
+ "Delete a GitOps sync",
+ "Delete a GitOps sync configuration by ID",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsDelete,
+ h.DeleteSync,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "performGitOpsSync",
+ "POST",
+ syncPath+"/sync",
+ "Perform a GitOps sync",
+ "Manually trigger a sync operation",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsSync,
+ h.PerformSync,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "getGitOpsSyncStatus",
+ "GET",
+ syncPath+"/status",
+ "Get GitOps sync status",
+ "Get the current status of a GitOps sync",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsRead,
+ h.GetStatus,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "browseGitOpsSyncFiles",
+ "GET",
+ syncPath+"/files",
+ "Browse GitOps sync files",
+ "Browse files in the synced repository",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsRead,
+ h.BrowseFiles,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "previewGitOpsBackup",
+ "GET",
+ syncPath+"/backup/preview",
+ "Preview a Git backup",
+ "Show the files the next backup would commit and any conflicts",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsBackup,
+ h.PreviewBackup,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "listGitOpsBackupHistory",
+ "GET",
+ syncPath+"/backup/history",
+ "List Git backup history",
+ "List repository revisions that changed the backup",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsBackup,
+ h.BackupHistory,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "getGitOpsBackupRevision",
+ "GET",
+ syncPath+"/backup/history/{commit}",
+ "Get a Git backup revision",
+ "Get one revision with per-file diffs",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsBackup,
+ h.BackupRevision,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "resolveGitOpsBackupConflict",
+ "POST",
+ syncPath+"/backup/resolve",
+ "Resolve a Git backup conflict",
+ "Resolve a backup that needs attention",
+ "GitOps Syncs",
+ ),
+ authz.PermGitOpsBackup,
+ h.ResolveBackupConflict,
+ )
}
// requireLifecyclePermissionInternal rejects callers lacking gitops:lifecycle
diff --git a/backend/internal/gitops/service_test.go b/backend/internal/gitops/service_test.go
index 35db493f8..9bb5b7fea 100644
--- a/backend/internal/gitops/service_test.go
+++ b/backend/internal/gitops/service_test.go
@@ -68,7 +68,7 @@ func newGitOpsAdmissionGateForTestInternal(t testing.TB) *runs.Admission {
func setupGitOpsSyncDirectoryTestService(t *testing.T) (*GitOpsSyncService, *database.DB, string) {
t.Helper()
- ctx := context.Background()
+ ctx := t.Context()
db := setupGitOpsProjectTestDBInternal(t)
require.NoError(t, db.AutoMigrate(&projectpkg.GitOpsSync{}))
@@ -145,7 +145,7 @@ func TestApplyLifecycleFieldsToSyncInternal_UsesExplicitPreDeployTimeout(t *test
}
func TestGitOpsSyncService_GetSyncByID_ReturnsNotFoundError(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, _, _ := setupGitOpsSyncDirectoryTestService(t)
_, err := svc.GetSyncByID(ctx, "0", "missing-sync")
@@ -154,7 +154,7 @@ func TestGitOpsSyncService_GetSyncByID_ReturnsNotFoundError(t *testing.T) {
}
func TestGitOpsSyncService_CleanupOrphanedSyncsOnStartup_DeletesOnlyOrphans(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
require.NoError(t, db.AutoMigrate(&environment.Environment{}))
@@ -206,7 +206,7 @@ func TestGitOpsSyncService_CleanupOrphanedSyncsOnStartup_DeletesOnlyOrphans(t *t
}
func TestGitOpsSyncService_RegisterAutoSyncJobsOnStartup_SkipsOrphans(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
require.NoError(t, db.AutoMigrate(&environment.Environment{}))
@@ -246,7 +246,7 @@ func TestGitOpsSyncService_RegisterAutoSyncJobsOnStartup_SkipsOrphans(t *testing
}
func TestGitOpsSyncService_DeleteSync_DeletesStaleProjectReference(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
missingProjectID := "missing-project"
@@ -273,7 +273,7 @@ func TestGitOpsSyncService_DeleteSync_DeletesStaleProjectReference(t *testing.T)
// corrupt/env-mismatched sync is still deletable via the API: the request env ("0")
// does not match the row's env ("5"), yet the delete must succeed and stop the job.
func TestGitOpsSyncService_DeleteSync_SucceedsWhenEnvironmentMismatched(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
scheduler := &gitOpsSyncTestSchedulerInternal{}
require.NoError(t, svc.SetScheduler(ctx, scheduler, newGitOpsAdmissionGateForTestInternal(t)))
@@ -298,7 +298,7 @@ func TestGitOpsSyncService_DeleteSync_SucceedsWhenEnvironmentMismatched(t *testi
// TestGitOpsSyncService_DeleteSync_ClearsOrphanedManagedFlag verifies the managed
// flag is cleared keyed on the sync id even when the sync's ProjectID is nil.
func TestGitOpsSyncService_DeleteSync_ClearsOrphanedManagedFlag(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
syncID := "sync-orphan-flag"
@@ -330,12 +330,13 @@ func TestGitOpsSyncService_DeleteSync_ClearsOrphanedManagedFlag(t *testing.T) {
// run whose row no longer exists (e.g. deleted out-of-band via raw SQL) unregisters
// its own job instead of firing forever.
func TestGitOpsSyncService_RunScheduledSync_UnregistersMissingSync(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, _, _ := setupGitOpsSyncDirectoryTestService(t)
scheduler := &gitOpsSyncTestSchedulerInternal{}
require.NoError(t, svc.SetScheduler(ctx, scheduler, newGitOpsAdmissionGateForTestInternal(t)))
- svc.runScheduledSyncInternal(ctx, "0", "ghost-sync")
+ _, scheduledSyncErr := svc.runScheduledSyncInternal(ctx, "0", "ghost-sync")
+ require.NoError(t, scheduledSyncErr)
assert.Contains(t, scheduler.removed, entityjobs.GitOpsSyncJobPrefix+"ghost-sync")
}
@@ -344,7 +345,7 @@ func TestGitOpsSyncService_RunScheduledSync_UnregistersMissingSync(t *testing.T)
// startup sweep removes leaked gitops scratch dirs (hidden and legacy name-embedded
// forms) while leaving real project directories untouched.
func TestGitOpsSyncService_CleanupLeakedScratchDirsOnStartup_RemovesOrphans(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, _, projectsDir := setupGitOpsSyncDirectoryTestService(t)
mkdir := func(name string) string {
@@ -373,7 +374,7 @@ func TestGitOpsSyncService_CleanupLeakedScratchDirsOnStartup_RemovesOrphans(t *t
// TestGitOpsSyncService_CleanupLeakedCloneDirsOnStartup_RemovesAll verifies the
// startup sweep purges leaked git clone scratch dirs from the git work dir.
func TestGitOpsSyncService_CleanupLeakedCloneDirsOnStartup_RemovesAll(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, _, _ := setupGitOpsSyncDirectoryTestService(t)
workDir := t.TempDir()
@@ -405,14 +406,14 @@ func TestGitOpsSyncService_CleanupLeakedCloneDirsOnStartup_NilRepoServiceIsNoop(
svc, _, _ := setupGitOpsSyncDirectoryTestService(t)
svc.repoService = nil
- require.NoError(t, svc.CleanupLeakedCloneDirsOnStartup(context.Background()))
+ require.NoError(t, svc.CleanupLeakedCloneDirsOnStartup(t.Context()))
}
// TestGitOpsSyncService_SyncProjectDirectory_RefusesDuplicateOnNameCollision verifies a
// directory sync refuses to create a "-N" sibling when its target name is already taken
// by a non-adoptable directory; instead it errors as a broken binding and disables auto-sync.
func TestGitOpsSyncService_SyncProjectDirectory_RefusesDuplicateOnNameCollision(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
// Occupy the target name with a dir that is NOT an adoptable GitOps project
@@ -451,7 +452,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_RefusesDuplicateOnNameCollision(
// single-file-sync analogue of the directory refuse: a name collision on create is a
// broken binding, not a "-N" duplicate.
func TestGitOpsSyncService_GetOrCreateProject_RefusesDuplicateOnNameCollision(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
require.NoError(t, svc.SetScheduler(ctx, &gitOpsSyncTestSchedulerInternal{}, newGitOpsAdmissionGateForTestInternal(t)))
@@ -481,7 +482,7 @@ func TestGitOpsSyncService_GetOrCreateProject_RefusesDuplicateOnNameCollision(t
}
func TestGitOpsSyncService_SyncProjectDirectory_CreatesProjectPreservingRepoLayout(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
sync := &projectpkg.GitOpsSync{
@@ -556,11 +557,11 @@ services:
assert.Equal(t, "$pbkdf2-sha512$310000$XXX", parsedEnv["QUOTED_SECRET"])
_, statErr := os.Stat(filepath.Join(project.Path, "compose.yaml"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
}
func TestGitOpsSyncService_SyncProjectDirectory_UpdatesProjectAndCleansOldSyncedFiles(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
projectPath := filepath.Join(projectsDir, "demo-project")
@@ -664,7 +665,7 @@ services:
// git still flows into the effective .env. This is the core regression test
// for https://github.com/getarcaneapp/arcane/issues/2476.
func TestGitOpsSyncService_SyncProjectDirectory_PreservesEnvOverrideAndAddsNewGitKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
projectPath := filepath.Join(projectsDir, "demo-project")
@@ -757,7 +758,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_PreservesEnvOverrideAndAddsNewGi
// merge step reads it, or a local-only key would be silently dropped instead
// of migrated into project.env.
func TestGitOpsSyncService_SyncProjectDirectory_MigratesLegacyTrackedEnvOnFirstSyncAfterUpgrade(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
projectPath := filepath.Join(projectsDir, "demo-project")
@@ -828,7 +829,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_MigratesLegacyTrackedEnvOnFirstS
// are dropped from the raw sync write, never tracked in syncedFiles, and the actual
// .env.git/project.env on disk are still produced solely by the merge.
func TestGitOpsSyncService_SyncProjectDirectory_IgnoresCommittedReservedEnvFiles(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
sync := &projectpkg.GitOpsSync{
@@ -886,7 +887,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_IgnoresCommittedReservedEnvFiles
}
func TestGitOpsSyncService_DirectorySync_RealWalkWithNestedConfig(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
svc.repoService = &gitrepo.GitRepositoryService{Client: git.NewClient("")}
@@ -948,7 +949,7 @@ func TestGitOpsSyncService_DirectorySync_RealWalkWithNestedConfig(t *testing.T)
}
func TestGitOpsSyncService_DirectorySync_OverwritesExistingDirectoryAtFilePath(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
svc.repoService = &gitrepo.GitRepositoryService{Client: git.NewClient("")}
@@ -1023,7 +1024,7 @@ func TestGitOpsSyncService_DirectorySync_OverwritesExistingDirectoryAtFilePath(t
}
func TestGitOpsSyncService_CreateDirectorySyncProjectInternal_RollsBackProjectOnUpdateFailure(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
sync := &projectpkg.GitOpsSync{
@@ -1073,7 +1074,7 @@ func TestGitOpsSyncService_CreateDirectorySyncProjectInternal_RollsBackProjectOn
assert.Nil(t, storedSync.ProjectID)
_, statErr := os.Stat(filepath.Join(projectsDir, "demo-project"))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
}
// TestGitOpsSyncService_UpdateDirectorySyncProjectInternal_RollsBackScopedChangesOnUpdateFailure
@@ -1082,7 +1083,7 @@ func TestGitOpsSyncService_CreateDirectorySyncProjectInternal_RollsBackProjectOn
// sync touched (in place, keeping inodes) while unrelated files are never copied,
// rewritten or pruned.
func TestGitOpsSyncService_UpdateDirectorySyncProjectInternal_RollsBackScopedChangesOnUpdateFailure(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
projectPath := filepath.Join(projectsDir, "demo-project")
@@ -1198,7 +1199,7 @@ func TestGitOpsSyncService_UpdateDirectorySyncProjectInternal_RollsBackScopedCha
require.NoError(t, err)
assert.Equal(t, "A=1\n", string(envBytes))
_, statErr := os.Lstat(filepath.Join(projectPath, projects.GitSourceEnvFileName))
- assert.ErrorIs(t, statErr, os.ErrNotExist)
+ require.ErrorIs(t, statErr, os.ErrNotExist)
// Unrelated files were left alone.
keepAfter, err := os.Stat(filepath.Join(projectPath, "keep.txt"))
@@ -1240,7 +1241,7 @@ func TestProjectsRemoveStaleComposeFiles_RemovesStaleCustomComposeFiles(t *testi
}
func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RelinksManagedProjectWhenProjectIDStale(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
projectPath := filepath.Join(projectsDir, "Radarr-3")
@@ -1283,7 +1284,7 @@ func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RelinksManagedProject
}
func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RecoversUniqueDirectoryCandidate(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
projectPath := filepath.Join(projectsDir, "Radarr-3")
@@ -1322,7 +1323,7 @@ func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RecoversUniqueDirecto
}
func TestGitOpsSyncService_ReconcileDirectorySyncProjectsOnStartup_SkipsAmbiguousDuplicates(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
for _, dirName := range []string{"Radarr-3", "Radarr-30"} {
@@ -1357,7 +1358,7 @@ func TestGitOpsSyncService_ReconcileDirectorySyncProjectsOnStartup_SkipsAmbiguou
}
func TestGitOpsSyncService_SyncProjectDirectory_FailsWhenBoundProjectMissing(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
testScheduler := &gitOpsSyncTestSchedulerInternal{}
require.NoError(t, svc.SetScheduler(ctx, testScheduler, newGitOpsAdmissionGateForTestInternal(t)))
@@ -1412,7 +1413,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_FailsWhenBoundProjectMissing(t *
}
func TestGitOpsSyncService_SyncProjectDirectory_DisablesAutoSyncWhenBoundProjectRecoveryAmbiguous(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
testScheduler := &gitOpsSyncTestSchedulerInternal{}
require.NoError(t, svc.SetScheduler(ctx, testScheduler, newGitOpsAdmissionGateForTestInternal(t)))
@@ -1467,7 +1468,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_DisablesAutoSyncWhenBoundProject
}
func TestGitOpsSyncService_GetOrCreateProjectInternal_FailsWhenBoundProjectMissing(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
testScheduler := &gitOpsSyncTestSchedulerInternal{}
require.NoError(t, svc.SetScheduler(ctx, testScheduler, newGitOpsAdmissionGateForTestInternal(t)))
@@ -1542,7 +1543,7 @@ func TestBuildSwarmStackDeployRequestInternal(t *testing.T) {
Files: files,
Prune: true,
WithRegistryAuth: true,
- WorkingDir: filepath.Join("/tmp/repo", "deploy/swarm"),
+ WorkingDir: filepath.Join(string(filepath.Separator), "tmp", "repo", "deploy", "swarm"),
},
},
{
@@ -1569,7 +1570,7 @@ func TestBuildSwarmStackDeployRequestInternal(t *testing.T) {
Files: []swarmtypes.SyncFile{},
Prune: true,
WithRegistryAuth: true,
- WorkingDir: filepath.Join("/tmp/repo", "stacks"),
+ WorkingDir: filepath.Join(string(filepath.Separator), "tmp", "repo", "stacks"),
},
},
}
@@ -1583,7 +1584,7 @@ func TestBuildSwarmStackDeployRequestInternal(t *testing.T) {
}
func TestGitOpsSyncService_GetEnvironmentSyncLimits(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupGitOpsProjectTestDBInternal(t)
settingsSvc, err := newGitOpsSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1602,7 +1603,7 @@ func TestGitOpsSyncService_GetEnvironmentSyncLimits(t *testing.T) {
}
func TestGitOpsSyncService_GetEffectiveSyncLimits(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Setenv("GIT_SYNC_MAX_FILES", "")
t.Setenv("GIT_SYNC_MAX_TOTAL_SIZE_MB", "")
t.Setenv("GIT_SYNC_MAX_BINARY_SIZE_MB", "")
@@ -1707,7 +1708,7 @@ func TestGitOpsSyncService_GetEffectiveSyncLimits(t *testing.T) {
// the rule checks under test.
func setupLifecycleValidationService(t *testing.T) (*GitOpsSyncService, context.Context) {
t.Helper()
- ctx := context.Background()
+ ctx := t.Context()
svc, _, _ := setupGitOpsSyncDirectoryTestService(t)
require.NoError(t, svc.settingsService.SetStringSetting(ctx, "lifecycleEnabled", "true"))
return svc, ctx
@@ -1720,7 +1721,7 @@ func TestValidateLifecycleConfig_AllNilNoError(t *testing.T) {
func TestValidateLifecycleConfig_RejectsWhenGloballyDisabled(t *testing.T) {
svc, _, _ := setupGitOpsSyncDirectoryTestService(t)
- ctx := context.Background()
+ ctx := t.Context()
// lifecycleEnabled defaults to false; do not enable.
err := svc.validateLifecycleConfigInternal(ctx, nil, lifecycleConfigInputInternal{
scriptPath: new("scripts/deploy.sh"),
@@ -1944,13 +1945,13 @@ func TestRedeployAfterSyncFailedError_FormatAndUnwrap(t *testing.T) {
err := common.Classify(common.ErrRedeployAfterSyncFailed, fmt.Errorf("redeploy failed: %w", cause))
require.Equal(t, "redeploy failed: pre-deploy hook bombed", err.Error())
- require.True(t, errors.Is(err, cause), "Unwrap should expose the cause for errors.Is")
+ require.ErrorIs(t, err, cause, "Unwrap should expose the cause for errors.Is")
require.ErrorIs(t, err, common.ErrRedeployAfterSyncFailed)
}
func TestMarkSyncRedeployFailedInternal_PersistsErrorOnSyncRow(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, _ := setupGitOpsSyncDirectoryTestService(t)
// Event logging requires a real event.EventService; the shared setup leaves it
// nil since most tests don't exercise the event path.
diff --git a/backend/internal/gitops/service_unix_test.go b/backend/internal/gitops/service_unix_test.go
index 12463298c..ba9cc51e9 100644
--- a/backend/internal/gitops/service_unix_test.go
+++ b/backend/internal/gitops/service_unix_test.go
@@ -3,7 +3,6 @@
package gitops
import (
- "context"
"encoding/json"
"os"
"path/filepath"
@@ -27,7 +26,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_PreservesUnreadableBindMountData
t.Skip("permission bits are ignored when running as root")
}
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)
projectPath := filepath.Join(projectsDir, "demo-project")
diff --git a/backend/internal/gitrepo/handler.go b/backend/internal/gitrepo/handler.go
index d239aaafa..68e92bff9 100644
--- a/backend/internal/gitrepo/handler.go
+++ b/backend/internal/gitrepo/handler.go
@@ -73,15 +73,123 @@ type SyncGitRepositoriesInput struct {
func RegisterGitRepositories(api huma.API, repoService *GitRepositoryService) {
h := &GitRepositoryHandler{repoService: repoService}
- handlerutil.RegisterSecured(api, handlerutil.Operation("listGitRepositories", "GET", "/customize/git-repositories", "List git repositories", "Get a paginated list of git repositories", "Customize"), authz.PermGitReposList, h.ListRepositories)
- handlerutil.RegisterSecured(api, handlerutil.Operation("createGitRepository", "POST", "/customize/git-repositories", "Create a git repository", "Create a new git repository configuration", "Customize"), authz.PermGitReposCreate, h.CreateRepository)
- handlerutil.RegisterSecured(api, handlerutil.Operation("getGitRepository", "GET", "/customize/git-repositories/{id}", "Get a git repository", "Get a git repository by ID", "Customize"), authz.PermGitReposRead, h.GetRepository)
- handlerutil.RegisterSecured(api, handlerutil.Operation("updateGitRepository", "PUT", "/customize/git-repositories/{id}", "Update a git repository", "Update an existing git repository configuration", "Customize"), authz.PermGitReposUpdate, h.UpdateRepository)
- handlerutil.RegisterSecured(api, handlerutil.Operation("deleteGitRepository", "DELETE", "/customize/git-repositories/{id}", "Delete a git repository", "Delete a git repository configuration by ID", "Customize"), authz.PermGitReposDelete, h.DeleteRepository)
- handlerutil.RegisterSecured(api, handlerutil.Operation("testGitRepository", "POST", "/customize/git-repositories/{id}/test", "Test a git repository", "Test connectivity and authentication to a git repository", "Customize"), authz.PermGitReposTest, h.TestRepository)
- handlerutil.RegisterSecured(api, handlerutil.Operation("listGitRepositoryBranches", "GET", "/customize/git-repositories/{id}/branches", "List repository branches", "Get all branches from a git repository with default branch detection", "Customize"), authz.PermGitReposRead, h.ListBranches)
- handlerutil.RegisterSecured(api, handlerutil.Operation("browseGitRepositoryFiles", "GET", "/customize/git-repositories/{id}/files", "Browse repository files", "Browse files and directories in a git repository", "Customize"), authz.PermGitReposRead, h.BrowseFiles)
- handlerutil.RegisterSecured(api, handlerutil.Operation("syncGitRepositories", "POST", "/git-repositories/sync", "Sync git repositories", "Sync git repositories from a manager to this agent instance", "Git Repositories"), authz.PermGitReposSync, h.SyncRepositories)
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "listGitRepositories",
+ "GET",
+ "/customize/git-repositories",
+ "List git repositories",
+ "Get a paginated list of git repositories",
+ "Customize",
+ ),
+ authz.PermGitReposList,
+ h.ListRepositories,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "createGitRepository",
+ "POST",
+ "/customize/git-repositories",
+ "Create a git repository",
+ "Create a new git repository configuration",
+ "Customize",
+ ),
+ authz.PermGitReposCreate,
+ h.CreateRepository,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "getGitRepository",
+ "GET",
+ "/customize/git-repositories/{id}",
+ "Get a git repository",
+ "Get a git repository by ID",
+ "Customize",
+ ),
+ authz.PermGitReposRead,
+ h.GetRepository,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "updateGitRepository",
+ "PUT",
+ "/customize/git-repositories/{id}",
+ "Update a git repository",
+ "Update an existing git repository configuration",
+ "Customize",
+ ),
+ authz.PermGitReposUpdate,
+ h.UpdateRepository,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "deleteGitRepository",
+ "DELETE",
+ "/customize/git-repositories/{id}",
+ "Delete a git repository",
+ "Delete a git repository configuration by ID",
+ "Customize",
+ ),
+ authz.PermGitReposDelete,
+ h.DeleteRepository,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "testGitRepository",
+ "POST",
+ "/customize/git-repositories/{id}/test",
+ "Test a git repository",
+ "Test connectivity and authentication to a git repository",
+ "Customize",
+ ),
+ authz.PermGitReposTest,
+ h.TestRepository,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "listGitRepositoryBranches",
+ "GET",
+ "/customize/git-repositories/{id}/branches",
+ "List repository branches",
+ "Get all branches from a git repository with default branch detection",
+ "Customize",
+ ),
+ authz.PermGitReposRead,
+ h.ListBranches,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "browseGitRepositoryFiles",
+ "GET",
+ "/customize/git-repositories/{id}/files",
+ "Browse repository files",
+ "Browse files and directories in a git repository",
+ "Customize",
+ ),
+ authz.PermGitReposRead,
+ h.BrowseFiles,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "syncGitRepositories",
+ "POST",
+ "/git-repositories/sync",
+ "Sync git repositories",
+ "Sync git repositories from a manager to this agent instance",
+ "Git Repositories",
+ ),
+ authz.PermGitReposSync,
+ h.SyncRepositories,
+ )
}
// ============================================================================
diff --git a/backend/internal/gitrepo/service.go b/backend/internal/gitrepo/service.go
index 283e017fd..20030baff 100644
--- a/backend/internal/gitrepo/service.go
+++ b/backend/internal/gitrepo/service.go
@@ -199,7 +199,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
return nil, err
}
- if err := validation.ValidateCredentialTargetChange(
+ if validateCredentialTargetChangeErr := validation.ValidateCredentialTargetChange(
"repository URL",
repository.URL,
req.URL,
@@ -212,8 +212,8 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
"sshKey": req.SSHKey != nil,
"token": req.Token != nil,
},
- ); err != nil {
- return nil, err
+ ); validateCredentialTargetChangeErr != nil {
+ return nil, validateCredentialTargetChangeErr
}
updates := make(map[string]any)
@@ -250,9 +250,9 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
if *req.Token == "" {
updates["token"] = ""
} else {
- encrypted, err := crypto.Encrypt(*req.Token)
- if err != nil {
- return nil, fmt.Errorf("failed to encrypt token: %w", err)
+ encrypted, encryptErr := crypto.Encrypt(*req.Token)
+ if encryptErr != nil {
+ return nil, fmt.Errorf("failed to encrypt token: %w", encryptErr)
}
updates["token"] = encrypted
}
@@ -262,21 +262,21 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
if *req.SSHKey == "" {
updates["ssh_key"] = ""
} else {
- encrypted, err := crypto.Encrypt(*req.SSHKey)
- if err != nil {
- return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)
+ encrypted, encryptSSHKeyErr := crypto.Encrypt(*req.SSHKey)
+ if encryptSSHKeyErr != nil {
+ return nil, fmt.Errorf("failed to encrypt SSH key: %w", encryptSSHKeyErr)
}
updates["ssh_key"] = encrypted
}
}
- if err := applySigningKeyUpdateInternal(repository, req, updates); err != nil {
- return nil, err
+ if applySigningKeyUpdateErr := applySigningKeyUpdateInternal(repository, req, updates); applySigningKeyUpdateErr != nil {
+ return nil, applySigningKeyUpdateErr
}
if len(updates) > 0 {
- if err := s.db.WithContext(ctx).Model(repository).Updates(updates).Error; err != nil {
- return nil, fmt.Errorf("failed to update repository: %w", err)
+ if updateRepositoryErr := s.db.WithContext(ctx).Model(repository).Updates(updates).Error; updateRepositoryErr != nil {
+ return nil, fmt.Errorf("failed to update repository: %w", updateRepositoryErr)
}
// Log event
@@ -313,8 +313,8 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,
return err
}
- if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&GitRepository{}).Error; err != nil {
- return fmt.Errorf("failed to delete repository: %w", err)
+ if deleteRepositoryErr := s.db.WithContext(ctx).Where("id = ?", id).Delete(&GitRepository{}).Error; deleteRepositoryErr != nil {
+ return fmt.Errorf("failed to delete repository: %w", deleteRepositoryErr)
}
// Log event
@@ -334,8 +334,8 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,
}
func (s *GitRepositoryService) TestConnection(ctx context.Context, id, branch string, actor common.User) error {
- settings := s.settingsService.GetSettingsConfig()
- ctx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))
+ localSettings := s.settingsService.GetSettingsConfig()
+ ctx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(localSettings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))
defer cancel()
repository, err := s.GetRepositoryByID(ctx, id)
@@ -493,8 +493,8 @@ func applySigningKeyUpdateInternal(current *GitRepository, req gitops.UpdateRepo
}
func (s *GitRepositoryService) ListBranches(ctx context.Context, id string) ([]gitops.BranchInfo, error) {
- settings := s.settingsService.GetSettingsConfig()
- listCtx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))
+ localSettings := s.settingsService.GetSettingsConfig()
+ listCtx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(localSettings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))
defer cancel()
repository, err := s.GetRepositoryByID(listCtx, id)
@@ -524,8 +524,8 @@ func (s *GitRepositoryService) ListBranches(ctx context.Context, id string) ([]g
}
func (s *GitRepositoryService) BrowseFiles(ctx context.Context, id, branch, path string) (*gitops.BrowseResponse, error) {
- settings := s.settingsService.GetSettingsConfig()
- ctx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))
+ localSettings := s.settingsService.GetSettingsConfig()
+ ctx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(localSettings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))
defer cancel()
repository, err := s.GetRepositoryByID(ctx, id)
@@ -574,8 +574,8 @@ func (s *GitRepositoryService) SyncRepositories(ctx context.Context, syncItems [
for _, item := range syncItems {
syncedIDs[item.ID] = true
- if err := s.processSyncItem(ctx, item, existingMap); err != nil {
- return err
+ if processSyncItemErr := s.processSyncItem(ctx, item, existingMap); processSyncItemErr != nil {
+ return processSyncItemErr
}
}
@@ -612,8 +612,8 @@ func (s *GitRepositoryService) updateExistingRepository(ctx context.Context, ite
if needsUpdate {
// Use Save to trigger GORM callbacks including UpdatedAt
- if err := s.db.WithContext(ctx).Save(existing).Error; err != nil {
- return fmt.Errorf("failed to update repository %s: %w", item.ID, err)
+ if syncRepositoryErr := s.db.WithContext(ctx).Save(existing).Error; syncRepositoryErr != nil {
+ return fmt.Errorf("failed to update repository %s: %w", item.ID, syncRepositoryErr)
}
}
@@ -699,8 +699,8 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item git
Enabled: item.Enabled,
ID: item.ID,
}
- if err := s.db.WithContext(ctx).Create(&repo).Error; err != nil {
- return fmt.Errorf("failed to create repository %s: %w", item.ID, err)
+ if createRepositoryErr := s.db.WithContext(ctx).Create(&repo).Error; createRepositoryErr != nil {
+ return fmt.Errorf("failed to create repository %s: %w", item.ID, createRepositoryErr)
}
return nil
}
diff --git a/backend/internal/gitrepo/service_test.go b/backend/internal/gitrepo/service_test.go
index 3584a3e58..4226813e0 100644
--- a/backend/internal/gitrepo/service_test.go
+++ b/backend/internal/gitrepo/service_test.go
@@ -24,7 +24,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
)
-func setupGitRepositoryServiceTestInternal(t *testing.T) (*GitRepositoryService, *database.DB) {
+func setupGitRepositoryServiceTestInternal(t *testing.T) *GitRepositoryService {
t.Helper()
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()))
@@ -50,19 +50,19 @@ func setupGitRepositoryServiceTestInternal(t *testing.T) (*GitRepositoryService,
})
wrappedDB := &database.DB{DB: db}
- settingsService, err := newSettingsServiceForTestInternal(t, context.Background(), wrappedDB)
+ settingsService, err := newSettingsServiceForTestInternal(t, t.Context(), wrappedDB)
require.NoError(t, err)
eventService := event.NewEventService(wrappedDB, &config.Config{}, nil)
- return NewGitRepositoryService(wrappedDB, t.TempDir(), eventService, settingsService), wrappedDB
+ return NewGitRepositoryService(wrappedDB, t.TempDir(), eventService, settingsService)
}
func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *database.DB) (*settings.SettingsService, error) {
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -70,7 +70,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepositoryService, req gitops.CreateRepositoryRequest) *GitRepository {
t.Helper()
- repo, err := svc.CreateRepository(context.Background(), req, common.User{
+ repo, err := svc.CreateRepository(t.Context(), req, common.User{
ID: "admin-1",
Username: "admin",
})
@@ -88,7 +88,7 @@ func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepository
}
func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWouldBeReused(t *testing.T) {
- svc, _ := setupGitRepositoryServiceTestInternal(t)
+ svc := setupGitRepositoryServiceTestInternal(t)
repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
@@ -97,7 +97,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWo
Token: "ghp_old_token",
})
- _, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
+ _, err := svc.UpdateRepository(t.Context(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://attacker.tld/repo.git"),
}, common.User{})
require.Error(t, err)
@@ -108,14 +108,14 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWo
assert.Equal(t, "token", fieldErr.Field)
assert.Contains(t, err.Error(), "repository URL")
- stored, loadErr := svc.GetRepositoryByID(context.Background(), repo.ID)
+ stored, loadErr := svc.GetRepositoryByID(t.Context(), repo.ID)
require.NoError(t, loadErr)
assert.Equal(t, "https://github.com/acme/private.git", stored.URL)
assert.Equal(t, repo.Token, stored.Token)
}
func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyWouldBeReused(t *testing.T) {
- svc, _ := setupGitRepositoryServiceTestInternal(t)
+ svc := setupGitRepositoryServiceTestInternal(t)
repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "infra-repo",
URL: "[email protected]:acme/private.git",
@@ -123,7 +123,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyW
SSHKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nkey-material\n-----END OPENSSH PRIVATE KEY-----",
})
- _, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
+ _, err := svc.UpdateRepository(t.Context(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("[email protected]:acme/private.git"),
}, common.User{})
require.Error(t, err)
@@ -134,14 +134,14 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyW
assert.Equal(t, "sshKey", fieldErr.Field)
assert.Contains(t, err.Error(), "repository URL")
- stored, loadErr := svc.GetRepositoryByID(context.Background(), repo.ID)
+ stored, loadErr := svc.GetRepositoryByID(t.Context(), repo.ID)
require.NoError(t, loadErr)
assert.Equal(t, "[email protected]:acme/private.git", stored.URL)
assert.Equal(t, repo.SSHKey, stored.SSHKey)
}
func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAndSSHKeyWouldBeReused(t *testing.T) {
- svc, _ := setupGitRepositoryServiceTestInternal(t)
+ svc := setupGitRepositoryServiceTestInternal(t)
repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "hybrid-repo",
URL: "https://github.com/acme/private.git",
@@ -151,7 +151,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAn
SSHKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nkey-material\n-----END OPENSSH PRIVATE KEY-----",
})
- _, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
+ _, err := svc.UpdateRepository(t.Context(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://attacker.tld/repo.git"),
}, common.User{})
require.Error(t, err)
@@ -164,7 +164,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAn
}
func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResupplied(t *testing.T) {
- svc, _ := setupGitRepositoryServiceTestInternal(t)
+ svc := setupGitRepositoryServiceTestInternal(t)
repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
@@ -173,7 +173,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResuppl
Token: "ghp_old_token",
})
- updated, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
+ updated, err := svc.UpdateRepository(t.Context(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://github.com/acme/private-rotated.git"),
Token: new("ghp_new_token"),
}, common.User{})
@@ -190,7 +190,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResuppl
}
func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsCleared(t *testing.T) {
- svc, _ := setupGitRepositoryServiceTestInternal(t)
+ svc := setupGitRepositoryServiceTestInternal(t)
repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
@@ -199,7 +199,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsCleared
Token: "ghp_old_token",
})
- updated, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
+ updated, err := svc.UpdateRepository(t.Context(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://github.com/acme/public.git"),
Token: new(""),
}, common.User{})
@@ -214,7 +214,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsCleared
}
func TestGitRepositoryService_UpdateRepository_AllowsSameURLWithoutCredentialResupply(t *testing.T) {
- svc, _ := setupGitRepositoryServiceTestInternal(t)
+ svc := setupGitRepositoryServiceTestInternal(t)
repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
@@ -223,7 +223,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsSameURLWithoutCredentialRes
Token: "ghp_old_token",
})
- updated, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
+ updated, err := svc.UpdateRepository(t.Context(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://github.com/acme/private.git"),
Username: new("deploy-bot"),
}, common.User{})
diff --git a/backend/internal/image/attestations_test.go b/backend/internal/image/attestations_test.go
index 27cd64fcf..48d285b38 100644
--- a/backend/internal/image/attestations_test.go
+++ b/backend/internal/image/attestations_test.go
@@ -60,9 +60,9 @@ func TestReadAttestationLayerBytesInternalDecompressesZstd(t *testing.T) {
compressed := encoder.EncodeAll(statement, nil)
{
- err := encoder.Close()
- require.NoError(t, err,
- "zstd close: %v", err)
+ closeErr := encoder.Close()
+ require.NoError(t, closeErr,
+ "zstd close: %v", closeErr)
}
layer := static.NewLayer(compressed, inTotoLayerMediaTypeInternal)
diff --git a/backend/internal/image/handler.go b/backend/internal/image/handler.go
index 15a50f80c..ac4ce809c 100644
--- a/backend/internal/image/handler.go
+++ b/backend/internal/image/handler.go
@@ -152,7 +152,17 @@ type UploadImageInput struct {
}
// RegisterImages registers image management routes using Huma.
-func RegisterImages(api huma.API, dockerService *docker.DockerClientService, imageService *ImageService, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, buildService *build.BuildService, activityService *activity.ActivityService, uploadService *upload.UploadService, appCtx handlerutil.ActivityAppContext) {
+func RegisterImages(
+ api huma.API,
+ dockerService *docker.DockerClientService,
+ imageService *ImageService,
+ imageUpdateService *imageupdate.ImageUpdateService,
+ settingsService *settings.SettingsService,
+ buildService *build.BuildService,
+ activityService *activity.ActivityService,
+ uploadService *upload.UploadService,
+ appCtx handlerutil.ActivityAppContext,
+) {
h := &ImageHandler{
dockerService: dockerService,
imageService: imageService,
@@ -309,7 +319,9 @@ func RegisterImages(api huma.API, dockerService *docker.DockerClientService, ima
Method: http.MethodPost,
Path: "/environments/{id}/images/upload",
Summary: "Upload an image",
- Description: "Load a Docker image tar archive from a complete chunked upload session. multipart/form-data bodies are still accepted for backward compatibility; that form is deprecated and will be removed in a future release.",
+ Description: "Load a Docker image tar archive from a complete chunked upload session. multipart/form-data bodies " +
+ "are still accepted for backward compatibility; that form is deprecated and will be removed in a " +
+ "future release.",
Tags: []string{"Images"},
Security: handlerutil.DefaultOperationSecurity(),
Middlewares: upload.LegacyMultipartMiddleware(api, h.uploadService, uploadtypes.KindImage),
@@ -370,7 +382,7 @@ func (h *ImageHandler) GetImageAttestations(ctx context.Context, input *GetImage
}
if input.Platform != "" {
- if _, err := platforms.Parse(input.Platform); err != nil {
+ if _, parseErr := platforms.Parse(input.Platform); parseErr != nil {
return nil, huma.Error400BadRequest(fmt.Sprintf("invalid platform %q", input.Platform))
}
}
@@ -407,8 +419,8 @@ func (h *ImageHandler) TagImage(ctx context.Context, input *TagImageInput) (*han
return nil, err
}
- if err := h.imageService.TagImage(ctx, imageName, input.Body, *user); err != nil {
- return nil, huma.Error500InternalServerError(fmt.Sprintf("failed to tag image: %v", err))
+ if tagImageErr := h.imageService.TagImage(ctx, imageName, input.Body, *user); tagImageErr != nil {
+ return nil, huma.Error500InternalServerError(fmt.Sprintf("failed to tag image: %v", tagImageErr))
}
return &handlerutil.Out[base.MessageResponse]{
@@ -508,8 +520,8 @@ func (h *ImageHandler) RemoveImage(ctx context.Context, input *RemoveImageInput)
return nil, err
}
- if err := h.imageService.RemoveImage(ctx, input.ImageID, input.Force, *user); err != nil {
- return nil, huma.Error500InternalServerError("Failed to remove image: " + err.Error())
+ if removeImageErr := h.imageService.RemoveImage(ctx, input.ImageID, input.Force, *user); removeImageErr != nil {
+ return nil, huma.Error500InternalServerError("Failed to remove image: " + removeImageErr.Error())
}
return &handlerutil.Out[base.MessageResponse]{
@@ -564,10 +576,10 @@ func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*h
activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, input.EnvironmentID)
writer := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, rawWriter, "Pulling image")
- if err := h.imageService.PullImage(runtimeCtx, fullImageName, writer, *user, credentials); err != nil {
+ if pullImageErr := h.imageService.PullImage(runtimeCtx, fullImageName, writer, *user, credentials); pullImageErr != nil {
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image pull failed", err)
- _, _ = fmt.Fprintf(writer, "{\"error\":%q}\n", err.Error())
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image pull failed", pullImageErr)
+ _, _ = fmt.Fprintf(writer, "{\"error\":%q}\n", pullImageErr.Error())
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
@@ -622,10 +634,10 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (
activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, input.EnvironmentID)
writer := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, rawWriter, "Building image")
- if _, err := h.buildService.BuildImage(runtimeCtx, input.EnvironmentID, input.Body, writer, "", user); err != nil {
+ if _, buildImageErr := h.buildService.BuildImage(runtimeCtx, input.EnvironmentID, input.Body, writer, "", user); buildImageErr != nil {
activitylib.FlushWriter(writer)
- activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image build failed", err)
- _, _ = fmt.Fprintf(writer, "{\"error\":%q}\n", err.Error())
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Image build failed", buildImageErr)
+ _, _ = fmt.Fprintf(writer, "{\"error\":%q}\n", buildImageErr.Error())
if f, ok := writer.(http.Flusher); ok {
f.Flush()
}
diff --git a/backend/internal/image/image.go b/backend/internal/image/image.go
index ecdd87fad..6cb4abc57 100644
--- a/backend/internal/image/image.go
+++ b/backend/internal/image/image.go
@@ -52,7 +52,14 @@ type ImageService struct {
projectIDCache *hot.HotCache[struct{}, map[string]string]
}
-func NewImageService(db *database.DB, dockerService *docker.DockerClientService, registryService *registry.ContainerRegistryService, imageUpdateService *imageupdate.ImageUpdateService, vulnerabilityService *vulnerability.VulnerabilityService, eventService *event.EventService) *ImageService {
+func NewImageService(
+ db *database.DB,
+ dockerService *docker.DockerClientService,
+ registryService *registry.ContainerRegistryService,
+ imageUpdateService *imageupdate.ImageUpdateService,
+ vulnerabilityService *vulnerability.VulnerabilityService,
+ eventService *event.EventService,
+) *ImageService {
return &ImageService{
db: db,
dockerService: dockerService,
@@ -86,10 +93,10 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetyp
g.Go(func() (workerErr error) {
defer utils.RecoverToError(&workerErr, "image worker")
- var err error
- inspectResult, err := dockerClient.ImageInspect(gctx, id)
- if err != nil {
- return fmt.Errorf("inspect not found: %w", err)
+ var inspectImageErr error
+ inspectResult, inspectImageErr := dockerClient.ImageInspect(gctx, id)
+ if inspectImageErr != nil {
+ return fmt.Errorf("inspect not found: %w", inspectImageErr)
}
inspect = inspectResult.InspectResponse
return nil
@@ -98,9 +105,9 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetyp
g.Go(func() (workerErr error) {
defer utils.RecoverToError(&workerErr, "image worker")
- imageList, err := dockerClient.ImageList(gctx, client.ImageListOptions{})
- if err != nil {
- return fmt.Errorf("failed to list images: %w", err)
+ imageList, imageListErr := dockerClient.ImageList(gctx, client.ImageListOptions{})
+ if imageListErr != nil {
+ return fmt.Errorf("failed to list images: %w", imageListErr)
}
for _, img := range imageList.Items {
if img.ID == id {
@@ -114,17 +121,17 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetyp
g.Go(func() (workerErr error) {
defer utils.RecoverToError(&workerErr, "image worker")
- containerList, err := s.dockerService.ListContainers(gctx)
- if err != nil {
- slog.DebugContext(gctx, "failed to list containers for image detail pinned references", "id", id, "error", err)
+ containerList, listContainersErr := s.dockerService.ListContainers(gctx)
+ if listContainersErr != nil {
+ slog.DebugContext(gctx, "failed to list containers for image detail pinned references", "id", id, "error", listContainersErr)
return nil
}
containers = containerList
return nil
})
- if err := g.Wait(); err != nil {
- return nil, err
+ if waitErr := g.Wait(); waitErr != nil {
+ return nil, waitErr
}
out := imagetypes.NewDetailSummary(&inspect)
@@ -162,8 +169,14 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, u
defer s.eventService.BeginDockerResourceSuppressionWindow("image", id, imageName)()
if inspectErr == nil {
defer s.eventService.BeginDockerResourceSuppressionWindow("image", imageDetails.ID, "")()
+ tagReleases := make([]func(), 0, len(imageDetails.RepoTags))
+ defer func() {
+ for _, release := range slices.Backward(tagReleases) {
+ release()
+ }
+ }()
for _, tag := range imageDetails.RepoTags {
- defer s.eventService.BeginDockerResourceSuppressionWindow("image", "", tag)()
+ tagReleases = append(tagReleases, s.eventService.BeginDockerResourceSuppressionWindow("image", "", tag))
}
}
removed, err := dockerClient.ImageRemove(ctx, id, options)
@@ -177,8 +190,8 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, u
// Clean up vulnerability scan records for the deleted image
if s.vulnerabilityService != nil {
- if err := s.vulnerabilityService.DeleteScanResult(ctx, id); err != nil {
- slog.WarnContext(ctx, "failed to delete vulnerability scan record", "id", id, "error", err)
+ if deleteScanResultErr := s.vulnerabilityService.DeleteScanResult(ctx, id); deleteScanResultErr != nil {
+ slog.WarnContext(ctx, "failed to delete vulnerability scan record", "id", id, "error", deleteScanResultErr)
}
}
@@ -221,7 +234,20 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progress
reader, err = dockerClient.ImagePull(ctx, imageName, pullOptions)
}
if err != nil {
- slog.ErrorContext(ctx, "Docker ImagePull failed", "image", imageName, "hasAuth", pullOptions.RegistryAuth != "", "initialHasAuth", initialHasAuth, "retriedWithoutAuth", retriedWithoutAuth, "error", err.Error())
+ slog.ErrorContext(
+ ctx,
+ "Docker ImagePull failed",
+ "image",
+ imageName,
+ "hasAuth",
+ pullOptions.RegistryAuth != "",
+ "initialHasAuth",
+ initialHasAuth,
+ "retriedWithoutAuth",
+ retriedWithoutAuth,
+ "error",
+ err.Error(),
+ )
s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, database.JSON{"action": "pull"})
return fmt.Errorf("failed to initiate image pull for %s: %w", imageName, err)
}
@@ -250,8 +276,8 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progress
slog.Warn("could not log image pull action", "err", logErr, "image", imageName)
}
if s.registryService != nil {
- if err := s.registryService.RecordImagePull(ctx, imageName); err != nil {
- slog.WarnContext(ctx, "failed to record registry pull count", "image", imageName, "error", err)
+ if recordImagePullErr := s.registryService.RecordImagePull(ctx, imageName); recordImagePullErr != nil {
+ slog.WarnContext(ctx, "failed to record registry pull count", "image", imageName, "error", recordImagePullErr)
}
}
@@ -428,7 +454,22 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Reader
var responseBuilder strings.Builder
streamErr := dockerutils.RenderJSONMessageStream(loadResp, &responseBuilder)
if streamErr != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "load", "file": fileName, "step": "read_response"})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeImageError,
+ "image",
+ "",
+ fileName,
+ user.ID,
+ user.Username,
+ "0",
+ streamErr,
+ database.JSON{
+ "action": "load",
+ "file": fileName,
+ "step": "read_response",
+ },
+ )
return nil, fmt.Errorf("failed to read load response: %w", streamErr)
}
@@ -1085,8 +1126,8 @@ func determineRepoAndTag(di image.Summary) (repo, tag string) {
}
if len(di.RepoDigests) > 0 {
- if repo, found := parseRepoFromDigests(di.RepoDigests).Get(); found {
- return repo, "<none>"
+ if localRepo, found := parseRepoFromDigests(di.RepoDigests).Get(); found {
+ return localRepo, "<none>"
}
}
@@ -1135,7 +1176,13 @@ func collectPinnedReferencesByImageIDInternal(containers []container.Summary) ma
return result
}
-func MapDockerImagesToDTOs(dockerImages []image.Summary, containers []container.Summary, usageMap map[string][]imagetypes.UsedBy, updateMap map[string]*imageupdate.ImageUpdateRecord, vulnerabilityMap map[string]*vulnerabilitytypes.ScanSummary) []imagetypes.Summary {
+func MapDockerImagesToDTOs(
+ dockerImages []image.Summary,
+ containers []container.Summary,
+ usageMap map[string][]imagetypes.UsedBy,
+ updateMap map[string]*imageupdate.ImageUpdateRecord,
+ vulnerabilityMap map[string]*vulnerabilitytypes.ScanSummary,
+) []imagetypes.Summary {
pinnedRefsByImageID := collectPinnedReferencesByImageIDInternal(containers)
items := make([]imagetypes.Summary, 0, len(dockerImages))
for _, di := range dockerImages {
@@ -1200,11 +1247,11 @@ func (s *ImageService) getImagePaginationConfig() pagination.Config[imagetypes.S
{
Key: "repo",
Fn: func(a, b imagetypes.Summary) int {
- if cmp := strings.Compare(a.Repo, b.Repo); cmp != 0 {
- return cmp
+ if localCmp := strings.Compare(a.Repo, b.Repo); localCmp != 0 {
+ return localCmp
}
- if cmp := strings.Compare(a.Tag, b.Tag); cmp != 0 {
- return cmp
+ if localCmp2 := strings.Compare(a.Tag, b.Tag); localCmp2 != 0 {
+ return localCmp2
}
return strings.Compare(a.ID, b.ID)
},
diff --git a/backend/internal/image/image_attestations.go b/backend/internal/image/image_attestations.go
index 20d672550..b4feadccd 100644
--- a/backend/internal/image/image_attestations.go
+++ b/backend/internal/image/image_attestations.go
@@ -105,17 +105,17 @@ func (s *ImageService) GetImageAttestations(ctx context.Context, imageName strin
attestations := make([]imagetypes.Attestation, 0)
for _, subject := range subjects {
- referrerAttestations, err := s.readReferrerAttestationsInternal(ctx, ref.Context(), subject, remoteOptions, query)
- if err != nil {
- return nil, err
+ referrerAttestations, readReferrerAttestationsErr := s.readReferrerAttestationsInternal(ctx, ref.Context(), subject, remoteOptions, query)
+ if readReferrerAttestationsErr != nil {
+ return nil, readReferrerAttestationsErr
}
attestations = append(attestations, referrerAttestations...)
}
if index != nil {
- inlineAttestations, err := readInlineAttestationsInternal(ctx, index, subjects, query)
- if err != nil {
- return nil, err
+ inlineAttestations, readInlineAttestationsErr := readInlineAttestationsInternal(ctx, index, subjects, query)
+ if readInlineAttestationsErr != nil {
+ return nil, readInlineAttestationsErr
}
attestations = append(attestations, inlineAttestations...)
}
@@ -343,7 +343,18 @@ func dedupeSubjectsInternal(subjects []imageAttestationSubjectInternal) []imageA
return out
}
-func (s *ImageService) readReferrerAttestationsInternal(ctx context.Context, repository name.Repository, subject imageAttestationSubjectInternal, remoteOptions []remote.Option, query ImageAttestationQuery) ([]imagetypes.Attestation, error) {
+func (
+ s *ImageService,
+) readReferrerAttestationsInternal(
+ ctx context.Context,
+ repository name.Repository,
+ subject imageAttestationSubjectInternal,
+ remoteOptions []remote.Option,
+ query ImageAttestationQuery,
+) (
+ []imagetypes.Attestation,
+ error,
+) {
referrers, err := remote.Referrers(repository.Digest(subject.Digest), remoteOptions...)
if err != nil {
if shouldIgnoreReferrersErrorInternal(err) {
@@ -359,13 +370,13 @@ func (s *ImageService) readReferrerAttestationsInternal(ctx context.Context, rep
attestations := make([]imagetypes.Attestation, 0, len(manifest.Manifests))
for _, referrer := range manifest.Manifests {
- referrerDescriptor, err := remote.Get(repository.Digest(referrer.Digest.String()), remoteOptions...)
- if err != nil {
- return nil, fmt.Errorf("get image referrer %s: %w", referrer.Digest.String(), err)
+ referrerDescriptor, getErr := remote.Get(repository.Digest(referrer.Digest.String()), remoteOptions...)
+ if getErr != nil {
+ return nil, fmt.Errorf("get image referrer %s: %w", referrer.Digest.String(), getErr)
}
- referrerImage, err := referrerDescriptor.Image()
- if err != nil {
+ referrerImage, getErr := referrerDescriptor.Image()
+ if getErr != nil {
continue
}
@@ -376,9 +387,9 @@ func (s *ImageService) readReferrerAttestationsInternal(ctx context.Context, rep
referrer.MediaType = referrerDescriptor.MediaType
}
- items, err := readAttestationImageInternal(ctx, referrerImage, referrer, subject.Platform, query)
- if err != nil {
- return nil, err
+ items, getErr := readAttestationImageInternal(ctx, referrerImage, referrer, subject.Platform, query)
+ if getErr != nil {
+ return nil, getErr
}
attestations = append(attestations, items...)
}
@@ -422,14 +433,14 @@ func readInlineAttestationsInternal(ctx context.Context, index v1.ImageIndex, su
subject = firstSubjectInternal(subjects)
}
- attestationImage, err := index.Image(descriptor.Digest)
- if err != nil {
- return nil, fmt.Errorf("read inline attestation image %s: %w", descriptor.Digest.String(), err)
+ attestationImage, imageErr := index.Image(descriptor.Digest)
+ if imageErr != nil {
+ return nil, fmt.Errorf("read inline attestation image %s: %w", descriptor.Digest.String(), imageErr)
}
- items, err := readAttestationImageInternal(ctx, attestationImage, descriptor, subject.Platform, query)
- if err != nil {
- return nil, err
+ items, imageErr := readAttestationImageInternal(ctx, attestationImage, descriptor, subject.Platform, query)
+ if imageErr != nil {
+ return nil, imageErr
}
attestations = append(attestations, items...)
}
@@ -461,9 +472,9 @@ func readAttestationImageInternal(ctx context.Context, attestationImage v1.Image
attestations := make([]imagetypes.Attestation, 0, len(manifest.Layers))
for _, layerDescriptor := range manifest.Layers {
- attestation, ok, err := readAttestationLayerInternal(ctx, attestationImage, layerDescriptor, artifactType, platform, query)
- if err != nil {
- return nil, err
+ attestation, ok, readAttestationLayerErr := readAttestationLayerInternal(ctx, attestationImage, layerDescriptor, artifactType, platform, query)
+ if readAttestationLayerErr != nil {
+ return nil, readAttestationLayerErr
}
if ok {
attestations = append(attestations, attestation)
@@ -472,7 +483,17 @@ func readAttestationImageInternal(ctx context.Context, attestationImage v1.Image
return attestations, nil
}
-func readAttestationLayerInternal(ctx context.Context, attestationImage v1.Image, layerDescriptor v1.Descriptor, artifactType, platform string, query ImageAttestationQuery) (imagetypes.Attestation, bool, error) {
+func readAttestationLayerInternal(
+ ctx context.Context,
+ attestationImage v1.Image,
+ layerDescriptor v1.Descriptor,
+ artifactType, platform string,
+ query ImageAttestationQuery,
+) (
+ imagetypes.Attestation,
+ bool,
+ error,
+) {
if err := ctx.Err(); err != nil {
return imagetypes.Attestation{}, false, err
}
diff --git a/backend/internal/image/module.go b/backend/internal/image/module.go
index 657dced84..6448105d8 100644
--- a/backend/internal/image/module.go
+++ b/backend/internal/image/module.go
@@ -23,7 +23,15 @@ type Module struct {
upload *upload.UploadService
}
-func New(service *ImageService, dockerService *docker.DockerClientService, imageUpdate *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, buildService *build.BuildService, activityService *activity.ActivityService, uploadService *upload.UploadService) *Module {
+func New(
+ service *ImageService,
+ dockerService *docker.DockerClientService,
+ imageUpdate *imageupdate.ImageUpdateService,
+ settingsService *settings.SettingsService,
+ buildService *build.BuildService,
+ activityService *activity.ActivityService,
+ uploadService *upload.UploadService,
+) *Module {
return &Module{service: service, docker: dockerService, imageUpdate: imageUpdate, settings: settingsService, build: buildService, activity: activityService, upload: uploadService}
}
diff --git a/backend/internal/image/service_test.go b/backend/internal/image/service_test.go
index 7a8884317..0ec94f087 100644
--- a/backend/internal/image/service_test.go
+++ b/backend/internal/image/service_test.go
@@ -1,7 +1,6 @@
package image
import (
- "context"
"encoding/json"
"errors"
"io"
@@ -17,7 +16,6 @@ import (
imagetypes "github.com/getarcaneapp/arcane/types/v2/image"
"github.com/libtnb/sqlite"
dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"
- "github.com/moby/moby/api/types/container"
dockercontainer "github.com/moby/moby/api/types/container"
dockertypesimage "github.com/moby/moby/api/types/image"
dockerregistry "github.com/moby/moby/api/types/registry"
@@ -40,7 +38,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref"
)
-var imageDockerAPIVersionPrefixInternal = regexp.MustCompile(`^/v[0-9]+\.[0-9]+`)
+var imageDockerAPIVersionPrefixInternal = regexp.MustCompile(`^/v\d+\.\d+`)
func imageDockerTestPathInternal(path string) string {
return imageDockerAPIVersionPrefixInternal.ReplaceAllString(path, "")
@@ -210,7 +208,7 @@ func TestImageService_GetImageDetail_EnrichesPinnedReferencesInternal(t *testing
imageSvc := NewImageService(db, &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}, nil, nil, nil, event.NewEventService(db, nil, nil))
- detail, err := imageSvc.GetImageDetail(context.Background(), pinnedID)
+ detail, err := imageSvc.GetImageDetail(t.Context(), pinnedID)
require.NoError(t, err)
require.NotNil(t, detail)
assert.Equal(t, pinnedID, detail.ID)
@@ -243,7 +241,7 @@ func TestImageService_GetImageDetail_ContainerFailureDoesNotBreakInspectionInter
imageSvc := NewImageService(db, &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}, nil, nil, nil, event.NewEventService(db, nil, nil))
- detail, err := imageSvc.GetImageDetail(context.Background(), testID)
+ detail, err := imageSvc.GetImageDetail(t.Context(), testID)
require.NoError(t, err)
require.NotNil(t, detail)
assert.Equal(t, testID, detail.ID)
@@ -252,7 +250,7 @@ func TestImageService_GetImageDetail_ContainerFailureDoesNotBreakInspectionInter
func TestImagePaginationConfig_SearchesPinnedReferencesInternal(t *testing.T) {
svc := &ImageService{}
- config := svc.getImagePaginationConfig()
+ localConfig := svc.getImagePaginationConfig()
item := imagetypes.Summary{
ID: "sha256:syncthing",
@@ -261,13 +259,13 @@ func TestImagePaginationConfig_SearchesPinnedReferencesInternal(t *testing.T) {
PinnedReferences: []string{"ghcr.io/syncthing/syncthing:2.1.3@sha256:8c8ff37ab6aa8be23b700648a90fa9412e214852e9fd6ea8477c8334792daec0"},
}
- res := config.SearchOrderAndPaginate([]imagetypes.Summary{item}, pagination.QueryParams{
+ res := localConfig.SearchOrderAndPaginate([]imagetypes.Summary{item}, pagination.QueryParams{
Search: "8c8ff37",
Limit: 10,
})
require.Len(t, res.Items, 1)
- resTag := config.SearchOrderAndPaginate([]imagetypes.Summary{item}, pagination.QueryParams{
+ resTag := localConfig.SearchOrderAndPaginate([]imagetypes.Summary{item}, pagination.QueryParams{
Search: "2.1.3",
Limit: 10,
})
@@ -307,7 +305,7 @@ func TestImageService_GetUpdateInfoByImageRefs_MatchesCanonicalAndFamiliarRepos(
require.NoError(t, db.Create(&records[i]).Error)
}
- updates, err := svc.GetUpdateInfoByImageRefs(context.Background(), []string{
+ updates, err := svc.GetUpdateInfoByImageRefs(t.Context(), []string{
"nginx:latest",
"docker.io/library/nginx:latest",
"redis:7",
@@ -342,27 +340,27 @@ func setupImageServiceAuthTest(t *testing.T) (*ImageService, *database.DB) {
return svc, dbWrap
}
-func createTestPullRegistry(t *testing.T, db *database.DB, url, username, token string) {
+func createTestPullRegistry(t *testing.T, db *database.DB, localUrl, username, token string) {
t.Helper()
encryptedToken, err := crypto.Encrypt(token)
require.NoError(t, err)
reg := &registry.ContainerRegistry{
- URL: url,
+ URL: localUrl,
Username: username,
Token: encryptedToken,
Enabled: true,
RegistryType: registry.RegistryTypeGeneric,
}
- require.NoError(t, db.WithContext(context.Background()).Create(reg).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(reg).Error)
}
func TestGetPullOptionsWithAuth_DBRegistrySkipsEmptyToken(t *testing.T) {
svc, db := setupImageServiceAuthTest(t)
createTestPullRegistry(t, db, "https://docker.io", "docker-user", " ")
- pullOptions, err := svc.PullOptionsWithAuth(context.Background(), "docker.io/library/nginx:latest", nil)
+ pullOptions, err := svc.PullOptionsWithAuth(t.Context(), "docker.io/library/nginx:latest", nil)
require.NoError(t, err)
assert.Empty(t, pullOptions.RegistryAuth)
}
@@ -371,7 +369,7 @@ func TestGetPullOptionsWithAuth_DBRegistrySkipsEmptyUsername(t *testing.T) {
svc, db := setupImageServiceAuthTest(t)
createTestPullRegistry(t, db, "https://docker.io", " ", "docker-token")
- pullOptions, err := svc.PullOptionsWithAuth(context.Background(), "docker.io/library/nginx:latest", nil)
+ pullOptions, err := svc.PullOptionsWithAuth(t.Context(), "docker.io/library/nginx:latest", nil)
require.NoError(t, err)
assert.Empty(t, pullOptions.RegistryAuth)
}
@@ -380,7 +378,7 @@ func TestGetPullOptionsWithAuth_DBRegistryUsesValidCredentials(t *testing.T) {
svc, db := setupImageServiceAuthTest(t)
createTestPullRegistry(t, db, "https://index.docker.io/v1/", "docker-user", "docker-token")
- pullOptions, err := svc.PullOptionsWithAuth(context.Background(), "docker.io/library/nginx:latest", nil)
+ pullOptions, err := svc.PullOptionsWithAuth(t.Context(), "docker.io/library/nginx:latest", nil)
require.NoError(t, err)
require.NotEmpty(t, pullOptions.RegistryAuth)
@@ -394,7 +392,7 @@ func TestGetPullOptionsWithAuth_ExternalCredentialsOverrideDBRegistryInternal(t
svc, db := setupImageServiceAuthTest(t)
createTestPullRegistry(t, db, "https://registry.example.com", "db-user", "db-token")
- pullOptions, err := svc.PullOptionsWithAuth(context.Background(), "registry.example.com/team/app:latest", []containerregistry.Credential{
+ pullOptions, err := svc.PullOptionsWithAuth(t.Context(), "registry.example.com/team/app:latest", []containerregistry.Credential{
{URL: "https://registry.example.com", Username: "external-user", Token: "external-token", Enabled: true},
})
require.NoError(t, err)
@@ -429,7 +427,7 @@ func TestImageServicePullImageRetriesAnonymouslyAfterAuthRejectedInternal(t *tes
dockerService := &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}
imageSvc := NewImageService(db, dockerService, nil, nil, nil, eventService)
- err := imageSvc.PullImage(context.Background(), "registry.example.com/team/app:latest", io.Discard, common.SystemUser, []containerregistry.Credential{
+ err := imageSvc.PullImage(t.Context(), "registry.example.com/team/app:latest", io.Discard, common.SystemUser, []containerregistry.Credential{
{URL: "https://registry.example.com", Username: "external-user", Token: "external-token", Enabled: true},
})
require.NoError(t, err)
@@ -456,7 +454,7 @@ func TestImageServiceTagImageCallsDockerAPIInternal(t *testing.T) {
imageSvc := NewImageService(db, &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}, nil, nil, nil, eventService)
- err := imageSvc.TagImage(context.Background(), "source:latest", imagetypes.TagRequest{Repository: "registry.example.com/team/app", Tag: "v2"}, common.SystemUser)
+ err := imageSvc.TagImage(t.Context(), "source:latest", imagetypes.TagRequest{Repository: "registry.example.com/team/app", Tag: "v2"}, common.SystemUser)
require.NoError(t, err)
assert.Equal(t, "registry.example.com/team/app", gotRepo)
assert.Equal(t, "v2", gotTag)
@@ -477,7 +475,7 @@ func TestImageServiceGetImageHistoryCallsDockerAPIInternal(t *testing.T) {
imageSvc := NewImageService(db, &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}, nil, nil, nil, event.NewEventService(db, nil, nil))
- history, err := imageSvc.GetImageHistory(context.Background(), "source:latest")
+ history, err := imageSvc.GetImageHistory(t.Context(), "source:latest")
require.NoError(t, err)
require.Len(t, history, 1)
assert.Equal(t, "layer-1", history[0].ID)
@@ -487,7 +485,7 @@ func TestImageServiceGetImageHistoryCallsDockerAPIInternal(t *testing.T) {
func TestImageServiceSearchImagesRequiresTermInternal(t *testing.T) {
imageSvc := NewImageService(nil, &docker.DockerClientService{}, nil, nil, nil, nil)
- _, err := imageSvc.SearchImages(context.Background(), " ")
+ _, err := imageSvc.SearchImages(t.Context(), " ")
require.Error(t, err)
assert.Contains(t, err.Error(), "search term is required")
}
@@ -509,7 +507,7 @@ func TestImageServiceExportImageReturnsTarStreamInternal(t *testing.T) {
imageSvc := NewImageService(db, &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}, nil, nil, nil, event.NewEventService(db, nil, nil))
- reader, err := imageSvc.ExportImage(context.Background(), "source:latest")
+ reader, err := imageSvc.ExportImage(t.Context(), "source:latest")
require.NoError(t, err)
t.Cleanup(func() { _ = reader.Close() })
body, err := io.ReadAll(reader)
@@ -534,7 +532,7 @@ func TestImageServiceSearchImagesCallsDockerAPIInternal(t *testing.T) {
imageSvc := NewImageService(db, &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}, nil, nil, nil, event.NewEventService(db, nil, nil))
- results, err := imageSvc.SearchImages(context.Background(), "nginx")
+ results, err := imageSvc.SearchImages(t.Context(), "nginx")
require.NoError(t, err)
require.Len(t, results, 1)
assert.Equal(t, "nginx", gotTerm)
@@ -586,62 +584,6 @@ func newTestDockerClientInternal(t *testing.T, server *httptest.Server) *client.
return cli
}
-// newImagePullServerWithObserverInternal is NewImagePullServer with a pull callback.
-func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[string]dockertypesimage.InspectResponse, onPull func(fullRef, authHeader string)) *httptest.Server {
- t.Helper()
-
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- switch {
- case strings.HasSuffix(r.URL.Path, "/images/create"):
- fullRef := strings.TrimSpace(r.URL.Query().Get("fromImage"))
- tag := strings.TrimSpace(r.URL.Query().Get("tag"))
- if fullRef != "" && tag != "" {
- lastSlash := strings.LastIndex(fullRef, "/")
- lastColon := strings.LastIndex(fullRef, ":")
- if lastColon <= lastSlash {
- fullRef += ":" + tag
- }
- }
- if onPull != nil {
- onPull(fullRef, strings.TrimSpace(r.Header.Get("X-Registry-Auth")))
- }
-
- w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(map[string]string{"status": "Pulled", "id": fullRef})
- return
- case strings.Contains(r.URL.Path, "/images/") && strings.HasSuffix(r.URL.Path, "/json"):
- path := r.URL.Path
- imagePathIndex := strings.Index(path, "/images/")
- if !assert.NotEqual(t, -1, imagePathIndex) {
- return
- }
- encodedRef := strings.TrimSuffix(path[imagePathIndex+len("/images/"):], "/json")
- imageRef, err := url.PathUnescape(encodedRef)
- if !assert.NoError(t, err) {
- return
- }
-
- inspect, ok := inspectByRef[imageRef]
- if !ok {
- http.Error(w, "not found", http.StatusNotFound)
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
- if !assert.NoError(t, json.NewEncoder(w).Encode(inspect)) {
- return
- }
- return
- default:
- http.NotFound(w, r)
- }
- }))
-
- t.Cleanup(server.Close)
-
- return server
-}
-
// testProjectRow is a minimal stand-in for project.Project: the project
// package imports this one, so the in-package test cannot import it back.
type testProjectRow struct {
@@ -664,11 +606,56 @@ func TestImageServiceContainerTagUpdatesStayScoped(t *testing.T) {
firstTarget, secondTarget := "3.2.0", "4.0.0"
records := []imageupdate.ImageUpdateRecord{
{ID: "shared-image", Repository: "docker.io/library/example", Tag: "3.1.0", CurrentVersion: "3.1.0", UpdateType: "digest", CheckTime: now},
- {ID: "container::first", PolicyKey: imageref.UpdatePolicyKey("example:3.1.0", firstLabels), ContainerID: "first", ImageID: "shared-image", Repository: "docker.io/library/example", Tag: "3.1.0", CurrentVersion: "3.1.0", LatestVersion: &firstTarget, HasUpdate: true, UpdateType: "tag", CheckTime: now.Add(time.Second)},
- {ID: "container::second", PolicyKey: imageref.UpdatePolicyKey("example:3.1.0", secondLabels), ContainerID: "second", ImageID: "shared-image", Repository: "docker.io/library/example", Tag: "3.1.0", CurrentVersion: "3.1.0", LatestVersion: &secondTarget, HasUpdate: true, UpdateType: "tag", CheckTime: now.Add(2 * time.Second)},
+ {
+ ID: "container::first",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "example:3.1.0",
+ firstLabels,
+ ),
+ ContainerID: "first",
+ ImageID: "shared-image",
+ Repository: "docker.io/library/example",
+ Tag: "3.1.0",
+ CurrentVersion: "3.1.0",
+ LatestVersion: &firstTarget,
+ HasUpdate: true,
+ UpdateType: "tag",
+ CheckTime: now.Add(time.Second),
+ },
+ {
+ ID: "container::second",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "example:3.1.0",
+ secondLabels,
+ ),
+ ContainerID: "second",
+ ImageID: "shared-image",
+ Repository: "docker.io/library/example",
+ Tag: "3.1.0",
+ CurrentVersion: "3.1.0",
+ LatestVersion: &secondTarget,
+ HasUpdate: true,
+ UpdateType: "tag",
+ CheckTime: now.Add(2 * time.Second),
+ },
}
require.NoError(t, db.Create(&records).Error)
- scoped, err := svc.GetUpdateInfoByContainers(t.Context(), []container.Summary{{ID: "first", Image: "example:3.1.0", Labels: firstLabels}, {ID: "second", Image: "example:3.1.0", Labels: secondLabels}, {ID: "unseen"}})
+ scoped, err := svc.GetUpdateInfoByContainers(
+ t.Context(),
+ []dockercontainer.Summary{
+ {
+ ID: "first",
+ Image: "example:3.1.0",
+ Labels: firstLabels,
+ },
+ {
+ ID: "second",
+ Image: "example:3.1.0",
+ Labels: secondLabels,
+ },
+ {ID: "unseen"},
+ },
+ )
require.NoError(t, err)
require.Len(t, scoped, 2)
require.Equal(t, firstTarget, scoped["first"].LatestVersion)
@@ -697,22 +684,51 @@ func TestImageServiceContainerTagUpdatesStayScoped(t *testing.T) {
{"com.getarcaneapp.arcane.updater.strategy": "tag", "com.getarcaneapp.arcane.updater.constraint": "3.x", "com.getarcaneapp.arcane.updater.tag-pattern": ".*"},
{"com.getarcaneapp.arcane.updater.strategy": "tag", "com.getarcaneapp.arcane.updater.constraint": "3.x", imageref.UpdateCheckLabel: "false"},
} {
- checks, err := svc.GetUpdateInfoByContainers(t.Context(), []container.Summary{{ID: "first", Image: "example:3.1.0", Labels: currentLabels}, {ID: "second", Image: "example:3.1.0", Labels: secondLabels}})
- require.NoError(t, err)
+ checks, getUpdateInfoByContainersErr := svc.GetUpdateInfoByContainers(
+ t.Context(),
+ []dockercontainer.Summary{
+ {
+ ID: "first",
+ Image: "example:3.1.0",
+ Labels: currentLabels,
+ },
+ {
+ ID: "second",
+ Image: "example:3.1.0",
+ Labels: secondLabels,
+ },
+ },
+ )
+ require.NoError(t, getUpdateInfoByContainersErr)
require.NotContains(t, checks, "first")
require.Contains(t, checks, "second")
}
// Disabling automatic installation does not change the monitoring policy,
// so the stored check stays visible (#3532).
- installExcluded := map[string]string{"com.getarcaneapp.arcane.updater.strategy": "tag", "com.getarcaneapp.arcane.updater.constraint": "3.x", "com.getarcaneapp.arcane.updater": "false"}
- checks, err := svc.GetUpdateInfoByContainers(t.Context(), []container.Summary{{ID: "first", Image: "example:3.1.0", Labels: installExcluded}})
+ installExcluded := map[string]string{
+ "com.getarcaneapp.arcane.updater.strategy": "tag",
+ "com.getarcaneapp.arcane.updater.constraint": "3.x",
+ "com.getarcaneapp.arcane.updater": "false",
+ }
+ checks, err := svc.GetUpdateInfoByContainers(t.Context(), []dockercontainer.Summary{{ID: "first", Image: "example:3.1.0", Labels: installExcluded}})
require.NoError(t, err)
require.Equal(t, firstTarget, checks["first"].LatestVersion)
// A digest check recorded under another local tag of the running image
// applies to every digest-policy container using that image ID.
- require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "moving-image", Repository: "docker.io/library/app", Tag: "stable", CurrentVersion: "stable", HasUpdate: true, UpdateType: "digest", CheckTime: now}).Error)
- digestContainers := []container.Summary{
+ require.NoError(
+ t,
+ db.Create(&imageupdate.ImageUpdateRecord{
+ ID: "moving-image",
+ Repository: "docker.io/library/app",
+ Tag: "stable",
+ CurrentVersion: "stable",
+ HasUpdate: true,
+ UpdateType: "digest",
+ CheckTime: now,
+ }).Error,
+ )
+ digestContainers := []dockercontainer.Summary{
{ID: "moving", Image: "app:latest", ImageID: "moving-image"},
{ID: "moving-twin", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{"com.getarcaneapp.arcane.updater": "false"}},
{ID: "moving-unmonitored", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{imageref.UpdateCheckLabel: "false"}},
diff --git a/backend/internal/imagepatch/handler.go b/backend/internal/imagepatch/handler.go
index 77b80bc61..a57da85b7 100644
--- a/backend/internal/imagepatch/handler.go
+++ b/backend/internal/imagepatch/handler.go
@@ -58,10 +58,24 @@ func RegisterImagePatches(api huma.API, imagePatchService *ImagePatchService, ap
handlerutil.Operation("list-image-patches", http.MethodGet, "/environments/{id}/images/patches", "List image patches", "Retrieves the paginated image patch history for the environment", "Images"),
authz.PermImagesList, h.ListImagePatches)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("list-image-patch-targets", http.MethodGet, "/environments/{id}/images/patch-targets", "List image patch targets", "Retrieves scanned images with fixable vulnerability counts and their latest patch run", "Images"),
+ handlerutil.Operation(
+ "list-image-patch-targets",
+ http.MethodGet,
+ "/environments/{id}/images/patch-targets",
+ "List image patch targets",
+ "Retrieves scanned images with fixable vulnerability counts and their latest patch run",
+ "Images",
+ ),
authz.PermVulnsRead, h.ListPatchTargets)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("patch-image", http.MethodPost, "/environments/{id}/images/{imageId}/patch", "Patch image", "Patches OS package vulnerabilities in the image using Copacetic, producing a new patched tag", "Images"),
+ handlerutil.Operation(
+ "patch-image",
+ http.MethodPost,
+ "/environments/{id}/images/{imageId}/patch",
+ "Patch image",
+ "Patches OS package vulnerabilities in the image using Copacetic, producing a new patched tag",
+ "Images",
+ ),
authz.PermImagesPatch, h.PatchImage)
}
diff --git a/backend/internal/imagepatch/imagepatch.go b/backend/internal/imagepatch/imagepatch.go
index 348ac671a..5fdb19312 100644
--- a/backend/internal/imagepatch/imagepatch.go
+++ b/backend/internal/imagepatch/imagepatch.go
@@ -60,7 +60,14 @@ type ImagePatchService struct {
patchSlot chan struct{}
}
-func NewImagePatchService(db *database.DB, dockerService *docker.DockerClientService, settingsService *settings.SettingsService, activityService *activity.ActivityService, registryService *registry.ContainerRegistryService, vulnerabilityService *vulnerability.VulnerabilityService) *ImagePatchService {
+func NewImagePatchService(
+ db *database.DB,
+ dockerService *docker.DockerClientService,
+ settingsService *settings.SettingsService,
+ activityService *activity.ActivityService,
+ registryService *registry.ContainerRegistryService,
+ vulnerabilityService *vulnerability.VulnerabilityService,
+) *ImagePatchService {
// Copa logs through the global logrus logger; route it into slog so its
// output follows Arcane's log format.
logging.InstallLogrusBridge()
@@ -101,8 +108,8 @@ func (s *ImagePatchService) PatchImage(ctx context.Context, envID, imageID strin
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
}
- if err := requireContainerdImageStoreInternal(runCtx, dockerClient); err != nil {
- return nil, err
+ if requireContainerdImageStoreErr := requireContainerdImageStoreInternal(runCtx, dockerClient); requireContainerdImageStoreErr != nil {
+ return nil, requireContainerdImageStoreErr
}
imageInspect, err := dockerClient.ImageInspect(runCtx, imageID)
@@ -130,7 +137,7 @@ func (s *ImagePatchService) PatchImage(ctx context.Context, envID, imageID strin
return nil, common.ErrPatchScanImageMismatch
}
var report vulnerability.VulnerabilityReportRecord
- if err := s.db.WithContext(runCtx).First(&report, "image_id = ?", opts.ScanID).Error; err != nil || len(report.Data) == 0 {
+ if loadScanReportErr := s.db.WithContext(runCtx).First(&report, "image_id = ?", opts.ScanID).Error; loadScanReportErr != nil || report.Data == "" {
return nil, common.ErrPatchScanReportUnavailable
}
reportData = []byte(report.Data)
@@ -179,8 +186,8 @@ func (s *ImagePatchService) PatchImage(ctx context.Context, envID, imageID strin
Status: string(imagepatch.PatchStatusPatching),
ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer(),
}
- if err := s.db.WithContext(runCtx).Create(record).Error; err != nil {
- return nil, fmt.Errorf("failed to create image patch record: %w", err)
+ if createPatchRecordErr := s.db.WithContext(runCtx).Create(record).Error; createPatchRecordErr != nil {
+ return nil, fmt.Errorf("failed to create image patch record: %w", createPatchRecordErr)
}
slog.InfoContext(runCtx, "image patch queued",
@@ -223,7 +230,11 @@ func (s *ImagePatchService) patchInBackgroundInternal(ctx context.Context, recor
if err == nil {
reportPath = filepath.Join(reportDir, "report.json")
err = os.WriteFile(reportPath, reportData, 0o600)
- defer os.RemoveAll(reportDir)
+ defer func() {
+ if cleanupErr := os.RemoveAll(reportDir); cleanupErr != nil {
+ slog.WarnContext(ctx, "Failed to remove image patch temporary directory", "directory", reportDir, "error", cleanupErr)
+ }
+ }()
}
if err != nil {
s.finishPatchRecordInternal(ctx, record, imagepatch.PatchStatusFailed, err.Error(), nil, 0)
@@ -264,7 +275,11 @@ func (s *ImagePatchService) patchInBackgroundInternal(ctx context.Context, recor
vexOutputPath = filepath.Join(vexDir, "vex.json")
copaOpts.Format = "openvex"
copaOpts.Output = vexOutputPath
- defer os.RemoveAll(vexDir)
+ defer func() {
+ if cleanupErr := os.RemoveAll(vexDir); cleanupErr != nil {
+ slog.WarnContext(ctx, "Failed to remove image patch temporary directory", "directory", vexDir, "error", cleanupErr)
+ }
+ }()
}
}
@@ -303,7 +318,7 @@ func (s *ImagePatchService) patchInBackgroundInternal(ctx context.Context, recor
var doc struct {
Statements []jsontext.Value `json:"statements"`
}
- if err := json.Unmarshal(data, &doc); err == nil {
+ if unmarshalErr := json.Unmarshal(data, &doc); unmarshalErr == nil {
count := len(doc.Statements)
packagesUpdated = &count
}
@@ -327,13 +342,13 @@ func (s *ImagePatchService) verifyPatchedImageInternal(ctx context.Context, reco
// took the multi-platform path and arch-suffixed the tag). When it exists,
// re-scan it so the security page can show whether the patch worked.
if dockerClient, err := s.dockerService.GetClient(ctx); err == nil {
- if patchedInspect, err := dockerClient.ImageInspect(ctx, record.PatchedRef); err != nil {
- slog.WarnContext(ctx, "patched image tag not found after patching", "patchedRef", record.PatchedRef, "error", err)
+ if patchedInspect, imageInspectErr := dockerClient.ImageInspect(ctx, record.PatchedRef); imageInspectErr != nil {
+ slog.WarnContext(ctx, "patched image tag not found after patching", "patchedRef", record.PatchedRef, "error", imageInspectErr)
s.appendPatchActivityInternal(ctx, activityID, 95, "Patched image was created but the expected tag "+record.PatchedRef+" was not found; check the image list")
} else if s.vulnerabilityService != nil && s.settingsService.IsFeatureEnabled(ctx, features.VulnerabilityManagement) {
s.appendPatchActivityInternal(ctx, activityID, 95, "Re-scanning patched image to verify the patch")
- if _, err := s.vulnerabilityService.ScanImage(context.WithoutCancel(ctx), record.EnvironmentID, patchedInspect.ID, common.User{Username: "System"}); err != nil {
- slog.WarnContext(ctx, "failed to start verification scan of patched image", "patchedRef", record.PatchedRef, "error", err)
+ if _, scanImageErr := s.vulnerabilityService.ScanImage(context.WithoutCancel(ctx), record.EnvironmentID, patchedInspect.ID, common.User{Username: "System"}); scanImageErr != nil {
+ slog.WarnContext(ctx, "failed to start verification scan of patched image", "patchedRef", record.PatchedRef, "error", scanImageErr)
}
}
}
@@ -388,11 +403,11 @@ func resolvePatchedRef(imageRef, patchedTag, suffix string) (string, error) {
if err != nil {
return "", fmt.Errorf("failed to parse image reference: %w", err)
}
- name, tag, err := copacommon.ResolvePatchedImageName(named, patchedTag, suffix)
+ localName, tag, err := copacommon.ResolvePatchedImageName(named, patchedTag, suffix)
if err != nil {
return "", fmt.Errorf("failed to resolve patched image name: %w", err)
}
- return name + ":" + tag, nil
+ return localName + ":" + tag, nil
}
// writeRegistryAuthConfigInternal merges Arcane's registry credentials into the
@@ -418,26 +433,26 @@ func (s *ImagePatchService) writeRegistryAuthConfigInternal(ctx context.Context)
var arcane struct {
Auths map[string]jsontext.Value `json:"auths"`
}
- if err := json.Unmarshal(arcaneConfig, &arcane); err != nil {
+ if unmarshalErr := json.Unmarshal(arcaneConfig, &arcane); unmarshalErr != nil {
return
}
- if err := acfs.MkdirAll(ctx, filepath.Dir(configDir), "/"+filepath.Base(configDir), 0o700); err != nil {
- slog.WarnContext(ctx, "failed to create docker config directory for image patching", "path", configDir, "error", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, filepath.Dir(configDir), "/"+filepath.Base(configDir), 0o700); mkdirAllErr != nil {
+ slog.WarnContext(ctx, "failed to create docker config directory for image patching", "path", configDir, "error", mkdirAllErr)
return
}
merged := map[string]jsontext.Value{}
- if existing, err := acfs.ReadFile(ctx, configDir, "/config.json"); err == nil {
- if err := json.Unmarshal(existing, &merged); err != nil {
- slog.WarnContext(ctx, "existing docker config is not valid JSON; leaving it untouched", "path", configDir, "error", err)
+ if existing, readFileErr := acfs.ReadFile(ctx, configDir, "/config.json"); readFileErr == nil {
+ if decodeExistingConfigErr := json.Unmarshal(existing, &merged); decodeExistingConfigErr != nil {
+ slog.WarnContext(ctx, "existing docker config is not valid JSON; leaving it untouched", "path", configDir, "error", decodeExistingConfigErr)
return
}
}
auths := map[string]jsontext.Value{}
if raw, ok := merged["auths"]; ok {
- if err := json.Unmarshal(raw, &auths); err != nil {
+ if decodeAuthConfigErr := json.Unmarshal(raw, &auths); decodeAuthConfigErr != nil {
auths = map[string]jsontext.Value{}
}
}
@@ -452,8 +467,8 @@ func (s *ImagePatchService) writeRegistryAuthConfigInternal(ctx context.Context)
if err != nil {
return
}
- if err := acfs.Write(ctx, configDir, "/config.json", payload, acfs.WriteOptions{Mode: 0o600}); err != nil {
- slog.WarnContext(ctx, "failed to write docker config for image patching", "path", configDir, "error", err)
+ if writeErr := acfs.Write(ctx, configDir, "/config.json", payload, acfs.WriteOptions{Mode: 0o600}); writeErr != nil {
+ slog.WarnContext(ctx, "failed to write docker config for image patching", "path", configDir, "error", writeErr)
}
}
@@ -534,7 +549,7 @@ func (s *ImagePatchService) ListPatchTargets(ctx context.Context, envID string,
excludedNames := make([]string, 0, len(patchedRefs)*2)
for ref := range patchedRefs {
excludedNames = append(excludedNames, ref)
- if named, err := reference.ParseNormalizedNamed(ref); err == nil {
+ if named, parseNormalizedNamedErr := reference.ParseNormalizedNamed(ref); parseNormalizedNamedErr == nil {
excludedNames = append(excludedNames, reference.FamiliarString(named))
}
}
@@ -571,12 +586,12 @@ func (s *ImagePatchService) ListPatchTargets(ctx context.Context, envID string,
// Best-effort: mark images without a registry source so the UI can explain
// why they cannot be patched.
repoDigestsByID := map[string][]string{}
- if images, err := s.dockerService.ListImages(ctx); err == nil {
+ if images, listImagesErr := s.dockerService.ListImages(ctx); listImagesErr == nil {
for i := range images {
repoDigestsByID[images[i].ID] = images[i].RepoDigests
}
} else {
- slog.WarnContext(ctx, "failed to list images for patch targets", "error", err)
+ slog.WarnContext(ctx, "failed to list images for patch targets", "error", listImagesErr)
}
imageIDs := make([]string, 0, len(scans))
@@ -694,23 +709,23 @@ func (s *ImagePatchService) latestPatchesByImageInternal(ctx context.Context, en
// images already patched since their latest scan. Used by the scheduled
// auto-patch job.
func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID string, user common.User) (patched, skipped int, err error) {
- if err := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); err != nil {
- return 0, 0, err
+ if requireFeatureErr := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); requireFeatureErr != nil {
+ return 0, 0, requireFeatureErr
}
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
return 0, 0, fmt.Errorf("failed to connect to Docker: %w", err)
}
- if err := requireContainerdImageStoreInternal(ctx, dockerClient); err != nil {
- return 0, 0, err
+ if requireContainerdImageStoreErr := requireContainerdImageStoreInternal(ctx, dockerClient); requireContainerdImageStoreErr != nil {
+ return 0, 0, requireContainerdImageStoreErr
}
var scans []vulnerability.VulnerabilityScanRecord
- if err := s.db.WithContext(ctx).
+ if loadFixableScansErr := s.db.WithContext(ctx).
Where("status = ? AND fixable_count > 0", vulnerability.ScanStatusCompleted).
Where("id IN (?)", s.db.Model(&vulnerability.VulnerabilityReportRecord{}).Select("image_id")).
Where("image_name NOT LIKE 'sha256:%' AND image_name NOT LIKE '%<none>%' AND image_name <> id").
- Find(&scans).Error; err != nil {
- return 0, 0, fmt.Errorf("failed to list vulnerability scans: %w", err)
+ Find(&scans).Error; loadFixableScansErr != nil {
+ return 0, 0, fmt.Errorf("failed to list vulnerability scans: %w", loadFixableScansErr)
}
patchedRefs, err := s.PatchedRefs(ctx, envID)
@@ -731,20 +746,20 @@ func (s *ImagePatchService) PatchFlaggedImages(ctx context.Context, envID string
// Skip images already patched (or being patched) since their latest scan.
var recent int64
- if err := s.db.WithContext(ctx).
+ if countRecentPatchesErr := s.db.WithContext(ctx).
Model(&ImagePatchRecord{}).
Where("environment_id = ? AND original_image_id = ? AND status IN ? AND created_at >= ?",
envID, scan.ID, []string{string(imagepatch.PatchStatusCompleted), string(imagepatch.PatchStatusPatching)}, scan.ScanTime).
- Count(&recent).Error; err == nil && recent > 0 {
+ Count(&recent).Error; countRecentPatchesErr == nil && recent > 0 {
skipped++
continue
}
- if _, err := s.PatchImage(ctx, envID, scan.ID, imagepatch.PatchOptions{ScanID: scan.ID}, user); err != nil {
+ if _, patchImageErr := s.PatchImage(ctx, envID, scan.ID, imagepatch.PatchOptions{ScanID: scan.ID}, user); patchImageErr != nil {
slog.WarnContext(ctx, "scheduled image patch failed to start",
"imageId", scan.ID,
"imageName", scan.ImageName,
- "error", err,
+ "error", patchImageErr,
)
skipped++
continue
diff --git a/backend/internal/imagepatch/imagepatch_feature_test.go b/backend/internal/imagepatch/imagepatch_feature_test.go
index c72102451..ebc23e16f 100644
--- a/backend/internal/imagepatch/imagepatch_feature_test.go
+++ b/backend/internal/imagepatch/imagepatch_feature_test.go
@@ -12,6 +12,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/imagepatch"
"github.com/libtnb/sqlite"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
@@ -32,7 +33,7 @@ func patchFeatureSettingsInternal(t *testing.T) (*settings.SettingsService, *dat
db := &database.DB{DB: gdb}
svc, err := settings.NewSettingsService(t.Context(), db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
require.NoError(t, err)
return svc, db
@@ -99,7 +100,7 @@ func TestDisabledFeatureSkipsPatchVerificationScan(t *testing.T) {
defer server.Close()
dockerClient, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.41"))
require.NoError(t, err)
- defer dockerClient.Close()
+ defer func() { assert.NoError(t, dockerClient.Close()) }()
svc := &ImagePatchService{
settingsService: settingsSvc,
dockerService: &docker.DockerClientService{Client: dockerClient},
diff --git a/backend/internal/imagepatch/imagepatch_test.go b/backend/internal/imagepatch/imagepatch_test.go
index defeb1307..5c56d104b 100644
--- a/backend/internal/imagepatch/imagepatch_test.go
+++ b/backend/internal/imagepatch/imagepatch_test.go
@@ -1,7 +1,6 @@
package imagepatch
import (
- "context"
"fmt"
"testing"
"time"
@@ -56,7 +55,7 @@ func TestResolvePatchedRef(t *testing.T) {
}
func TestListPatchTargets_ExcludesUntaggedImages(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
dsn := fmt.Sprintf("file:image-patch-test-%d?mode=memory&cache=shared", time.Now().UnixNano())
gdb, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
require.NoError(t, err)
diff --git a/backend/internal/imageupdate/handler.go b/backend/internal/imageupdate/handler.go
index 1b2b7128c..710128384 100644
--- a/backend/internal/imageupdate/handler.go
+++ b/backend/internal/imageupdate/handler.go
@@ -53,7 +53,18 @@ type GetUpdateSummaryInput struct {
}
// RegisterImageUpdates registers image update endpoints.
-func RegisterImageUpdates(api huma.API, imageUpdateSvc *ImageUpdateService, getUpdateInfoByImageRefs func(context.Context, []string) (map[string]*imagetypes.UpdateInfo, error), appCtx handlerutil.ActivityAppContext) {
+func RegisterImageUpdates(
+ api huma.API,
+ imageUpdateSvc *ImageUpdateService,
+ getUpdateInfoByImageRefs func(
+ context.Context,
+ []string,
+ ) (
+ map[string]*imagetypes.UpdateInfo,
+ error,
+ ),
+ appCtx handlerutil.ActivityAppContext,
+) {
h := &ImageUpdateHandler{
imageUpdateService: imageUpdateSvc,
getUpdateInfoByImageRefs: getUpdateInfoByImageRefs,
diff --git a/backend/internal/imageupdate/image_update.go b/backend/internal/imageupdate/image_update.go
index c660f70ac..27b5a22e0 100644
--- a/backend/internal/imageupdate/image_update.go
+++ b/backend/internal/imageupdate/image_update.go
@@ -73,7 +73,15 @@ type localImageSnapshot struct {
IsLocalBuild bool
}
-func NewImageUpdateService(db *database.DB, settingsService *settings.SettingsService, registryService *registry.ContainerRegistryService, dockerService *docker.DockerClientService, eventService *event.EventService, notificationService *notification.NotificationService, activityService *activity.ActivityService) *ImageUpdateService {
+func NewImageUpdateService(
+ db *database.DB,
+ settingsService *settings.SettingsService,
+ registryService *registry.ContainerRegistryService,
+ dockerService *docker.DockerClientService,
+ eventService *event.EventService,
+ notificationService *notification.NotificationService,
+ activityService *activity.ActivityService,
+) *ImageUpdateService {
return &ImageUpdateService{
db: db,
settingsService: settingsService,
@@ -169,7 +177,7 @@ func (s *ImageUpdateService) startImageUpdateActivityInternal(ctx context.Contex
return ""
}
resourceType := kit.Ternary(count > 1, "images", "image")
- activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
+ localActivity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
EnvironmentID: "0",
Type: activitytypes.TypeImageUpdateCheck,
Queue: true,
@@ -185,7 +193,7 @@ func (s *ImageUpdateService) startImageUpdateActivityInternal(ctx context.Contex
slog.DebugContext(ctx, "failed to start image update activity", "error", err)
return ""
}
- return activity.ID
+ return localActivity.ID
}
func (s *ImageUpdateService) appendImageUpdateActivityMessageInternal(ctx context.Context, activityID string, level activitytypes.MessageLevel, message string, progress int, step string) {
@@ -403,7 +411,7 @@ func digestPinnedImageUpdateResultInternal(imageRef string) mo.Option[*imageupda
tag := "latest"
if named, err := ref.ParseNormalizedNamed(imageRef); err == nil {
- if tagged, ok := named.(ref.NamedTagged); ok {
+ if tagged, localOk := named.(ref.NamedTagged); localOk {
tag = tagged.Tag()
}
}
@@ -569,9 +577,6 @@ func (s *ImageUpdateService) parseImageReference(imageRef string) *ImageParts {
tag := "latest"
if tagged, ok := named.(ref.NamedTagged); ok {
tag = tagged.Tag()
- } else if _, ok := named.(ref.Digested); ok {
- // If it's a digest reference, still use "latest" as the tag for registry queries
- tag = "latest"
}
return &ImageParts{
@@ -1195,16 +1200,16 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,
// Only clear synthetic ref:: records, not real sha256 image ID records.
// Clearing sha256 records would incorrectly mark containers that are still
// running the old image as up-to-date (see: #2453).
- if err := tx.Model(&ImageUpdateRecord{}).
+ if clearStaleUpdatesErr := tx.Model(&ImageUpdateRecord{}).
Where("id LIKE 'ref::%' AND tag = ? AND repository IN ?", tag, repositories).
- Update("has_update", false).Error; err != nil {
- return fmt.Errorf("clear stale image updates: %w", err)
+ Update("has_update", false).Error; clearStaleUpdatesErr != nil {
+ return fmt.Errorf("clear stale image updates: %w", clearStaleUpdatesErr)
}
}
}
- if err := savePreparedUpdateResultWithTxInternal(tx, snapshot.ImageID, snapshot.Repository, snapshot.Tag, result); err != nil {
- return fmt.Errorf("save pulled image update state: %w", err)
+ if savePreparedUpdateResultWithTxErr := savePreparedUpdateResultWithTxInternal(tx, snapshot.ImageID, snapshot.Repository, snapshot.Tag, result); savePreparedUpdateResultWithTxErr != nil {
+ return fmt.Errorf("save pulled image update state: %w", savePreparedUpdateResultWithTxErr)
}
return nil
@@ -1293,13 +1298,13 @@ type batchImageProgressRecorder struct {
total int
}
-func (r *batchImageProgressRecorder) recordInternal(refs []string, res *imageupdate.Response) int {
+func (r *batchImageProgressRecorder) recordInternal(localRefs []string, res *imageupdate.Response) int {
r.mu.Lock()
defer r.mu.Unlock()
r.completed++
progress := 10 + int(float64(r.completed)/float64(r.total)*80)
- for _, imageRef := range refs {
+ for _, imageRef := range localRefs {
r.results[imageRef] = res
}
return progress
@@ -1346,7 +1351,17 @@ func (s *ImageUpdateService) parseAndGroupImagesInternal(imageRefs []string) (ma
return regRepos, results, images
}
-func (s *ImageUpdateService) checkSingleImageInBatchInternal(ctx context.Context, externalCreds []containerregistry.Credential, parts *ImageParts, composeBuildRefs map[string]struct{}) (*imageupdate.Response, *localImageSnapshot) {
+func (
+ s *ImageUpdateService,
+) checkSingleImageInBatchInternal(
+ ctx context.Context,
+ externalCreds []containerregistry.Credential,
+ parts *ImageParts,
+ composeBuildRefs map[string]struct{},
+) (
+ *imageupdate.Response,
+ *localImageSnapshot,
+) {
if s.registryService == nil {
return &imageupdate.Response{
Error: "registry service unavailable",
@@ -1487,7 +1502,16 @@ func (s *ImageUpdateService) resolveBatchCredentialsInternal(ctx context.Context
return credentials
}
-func (s *ImageUpdateService) checkBatchImageInternal(ctx context.Context, activityID string, resolvedCreds []containerregistry.Credential, img batchImage, composeBuildRefs map[string]struct{}, recorder *batchImageProgressRecorder) error {
+func (
+ s *ImageUpdateService,
+) checkBatchImageInternal(
+ ctx context.Context,
+ activityID string,
+ resolvedCreds []containerregistry.Credential,
+ img batchImage,
+ composeBuildRefs map[string]struct{},
+ recorder *batchImageProgressRecorder,
+) error {
registryRecord := img.parts.Registry
if err := s.registryLimiter.Acquire(ctx, registryRecord); err != nil {
@@ -1522,7 +1546,16 @@ func (s *ImageUpdateService) checkBatchImageInternal(ctx context.Context, activi
return nil
}
-func (s *ImageUpdateService) recordBatchImageCheckInternal(ctx context.Context, activityID string, img batchImage, res *imageupdate.Response, snapshot *localImageSnapshot, recorder *batchImageProgressRecorder) {
+func (
+ s *ImageUpdateService,
+) recordBatchImageCheckInternal(
+ ctx context.Context,
+ activityID string,
+ img batchImage,
+ res *imageupdate.Response,
+ snapshot *localImageSnapshot,
+ recorder *batchImageProgressRecorder,
+) {
progress := recorder.recordInternal(img.refs, res)
level, message := imageCheckResultMessageInternal(img.canonicalRef, res)
@@ -1777,8 +1810,8 @@ func (s *ImageUpdateService) CheckAllImages(ctx context.Context, limit int, exte
return nil, err
}
- if err := s.CleanupOrphanedRecords(ctx); err != nil {
- slog.WarnContext(ctx, "failed to cleanup orphaned image update records after check-all", "error", err.Error())
+ if cleanupOrphanedRecordsErr := s.CleanupOrphanedRecords(ctx); cleanupOrphanedRecordsErr != nil {
+ slog.WarnContext(ctx, "failed to cleanup orphaned image update records after check-all", "error", cleanupOrphanedRecordsErr.Error())
}
return results, nil
diff --git a/backend/internal/imageupdate/service_test.go b/backend/internal/imageupdate/service_test.go
index 77c445298..023abdc73 100644
--- a/backend/internal/imageupdate/service_test.go
+++ b/backend/internal/imageupdate/service_test.go
@@ -103,12 +103,12 @@ func setupImageUpdateRegistryTestDBInternal(t *testing.T) *database.DB {
return &database.DB{DB: db}
}
-func createImageUpdateTestPullRegistryInternal(t *testing.T, db *database.DB, url, username, token string) {
+func createImageUpdateTestPullRegistryInternal(t *testing.T, db *database.DB, localUrl, username, token string) {
t.Helper()
encryptedToken, err := crypto.Encrypt(token)
require.NoError(t, err)
require.NoError(t, db.Create(&registry.ContainerRegistry{
- URL: url,
+ URL: localUrl,
Username: username,
Token: encryptedToken,
Enabled: true,
@@ -392,7 +392,7 @@ func newComposeBuildImageUpdateServiceInternal(t *testing.T) (*ImageUpdateServic
func TestImageUpdateService_CheckImageUpdate_ComposeBuildSkipsRegistryWithRepoDigests(t *testing.T) {
svc, registryCalls := newComposeBuildImageUpdateServiceInternal(t)
- result, err := svc.CheckImageUpdate(context.Background(), "test2:latest")
+ result, err := svc.CheckImageUpdate(t.Context(), "test2:latest")
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, UpdateTypeLocal, result.UpdateType)
@@ -415,7 +415,7 @@ func TestImageUpdateService_CheckMultipleImages_ComposeBuildSkipsRegistryWithRep
Enabled: true,
}}
- results, err := svc.CheckMultipleImages(context.Background(), []string{"test2:latest"}, credentials)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{"test2:latest"}, credentials)
require.NoError(t, err)
result := results["test2:latest"]
require.NotNil(t, result)
@@ -437,7 +437,9 @@ func TestImageUpdateService_CheckMultipleImages_ComposeBuildMissingLocallySkipsR
dockerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{})) {
+ return
+ }
return
}
@@ -459,7 +461,7 @@ func TestImageUpdateService_CheckMultipleImages_ComposeBuildMissingLocallySkipsR
eventService := event.NewEventService(db, nil, nil)
svc := NewImageUpdateService(db, nil, registryService, dockerService, eventService, nil, nil)
- results, err := svc.CheckMultipleImages(context.Background(), []string{"test2:latest"}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{"test2:latest"}, nil)
require.NoError(t, err)
result := results["test2:latest"]
require.NotNil(t, result)
@@ -477,7 +479,9 @@ func newArcaneLocalImageUpdateServiceInternal(t *testing.T, imageExists bool) (*
dockerServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{})) {
+ return
+ }
return
}
@@ -522,7 +526,7 @@ func TestImageUpdateService_CheckImageUpdate_ArcaneLocalHostSkipsRegistry(t *tes
CheckTime: time.Now(),
}).Error)
- result, err := svc.CheckImageUpdate(context.Background(), "arcane.local/demo-2ab41b29/worker:latest")
+ result, err := svc.CheckImageUpdate(t.Context(), "arcane.local/demo-2ab41b29/worker:latest")
require.NoError(t, err)
require.NotNil(t, result)
assert.Equal(t, UpdateTypeLocal, result.UpdateType)
@@ -539,7 +543,7 @@ func TestImageUpdateService_CheckImageUpdate_ArcaneLocalHostSkipsRegistry(t *tes
func TestImageUpdateService_CheckMultipleImages_ArcaneLocalMissingImageSkipsRegistry(t *testing.T) {
svc, registryCalls := newArcaneLocalImageUpdateServiceInternal(t, false)
- results, err := svc.CheckMultipleImages(context.Background(), []string{"arcane.local/demo-2ab41b29/worker:latest"}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{"arcane.local/demo-2ab41b29/worker:latest"}, nil)
require.NoError(t, err)
result := results["arcane.local/demo-2ab41b29/worker:latest"]
require.NotNil(t, result)
@@ -552,7 +556,7 @@ func TestImageUpdateService_CheckMultipleImages_ArcaneLocalMissingImageSkipsRegi
func TestImageUpdateService_CheckMultipleImages_OtherDottedRegistryStillChecked(t *testing.T) {
svc, registryCalls := newArcaneLocalImageUpdateServiceInternal(t, false)
- results, err := svc.CheckMultipleImages(context.Background(), []string{"registry.local/team/app:latest"}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{"registry.local/team/app:latest"}, nil)
require.NoError(t, err)
result := results["registry.local/team/app:latest"]
require.NotNil(t, result)
@@ -565,7 +569,9 @@ func TestImageUpdateService_InspectLocalImageSnapshot_NoRepoDigestsRemainsLocal(
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{})) {
+ return
+ }
return
}
@@ -584,7 +590,7 @@ func TestImageUpdateService_InspectLocalImageSnapshot_NoRepoDigestsRemainsLocal(
t.Cleanup(server.Close)
svc := &ImageUpdateService{dockerService: &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, server)}}
- snapshot, err := svc.inspectLocalImageSnapshotInternal(context.Background(), "local-only:latest", map[string]struct{}{})
+ snapshot, err := svc.inspectLocalImageSnapshotInternal(t.Context(), "local-only:latest", map[string]struct{}{})
require.NoError(t, err)
assert.True(t, snapshot.IsLocalBuild)
assert.Equal(t, "sha256:local-only-image", snapshot.PrimaryDigest)
@@ -600,10 +606,10 @@ func registryPingInternal(w http.ResponseWriter, r *http.Request) bool {
}
// writeManifestHeadInternal answers a manifest HEAD with the headers a client needs to trust the digest without a body.
-func writeManifestHeadInternal(w http.ResponseWriter, digest string) {
+func writeManifestHeadInternal(w http.ResponseWriter, localDigest string) {
w.Header().Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")
w.Header().Set("Content-Length", "0")
- w.Header().Set("Docker-Content-Digest", digest)
+ w.Header().Set("Docker-Content-Digest", localDigest)
w.WriteHeader(http.StatusOK)
}
@@ -621,7 +627,9 @@ func newImageUpdateFallbackServer(t *testing.T, repositoryTag, localDigest, remo
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{})) {
+ return
+ }
return
}
@@ -667,7 +675,9 @@ func newImageUpdateRegistryOnlyServer(t *testing.T, repositoryTag, remoteDigest
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{})) {
+ return
+ }
return
}
@@ -742,7 +752,7 @@ func TestImageUpdateService_GetImageRefByIDInternal_UsesContainerFallback(t *tes
dockerService: &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, server)},
}
- imageRef, err := svc.getImageRefByIDInternal(context.Background(), imageID)
+ imageRef, err := svc.getImageRefByIDInternal(t.Context(), imageID)
if tt.wantErr != "" {
require.Error(t, err)
require.ErrorContains(t, err, tt.wantErr)
@@ -763,7 +773,7 @@ func TestImageUpdateService_CheckImageUpdate_SkipsDigestPinnedReferenceInternal(
eventService := event.NewEventService(db, nil, nil)
svc := NewImageUpdateService(db, nil, nil, nil, eventService, nil, nil)
- result, err := svc.CheckImageUpdate(context.Background(), imageRef)
+ result, err := svc.CheckImageUpdate(t.Context(), imageRef)
require.NoError(t, err)
require.NotNil(t, result)
assert.False(t, result.HasUpdate)
@@ -786,7 +796,7 @@ func TestImageUpdateService_CheckMultipleImages_SkipsDigestPinnedReferenceIntern
require.NotNil(t, initialResults[imageRef])
assert.Empty(t, initialResults[imageRef].Error)
- results, err := svc.CheckMultipleImages(context.Background(), []string{imageRef}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{imageRef}, nil)
require.NoError(t, err)
require.Contains(t, results, imageRef)
require.NotNil(t, results[imageRef])
@@ -815,13 +825,13 @@ func TestImageUpdateService_CheckMultipleImages_SkippedDigestPinnedReferenceClea
}).Error)
svc := NewImageUpdateService(db, nil, nil, nil, nil, nil, nil)
- results, err := svc.CheckMultipleImages(context.Background(), []string{imageRef}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{imageRef}, nil)
require.NoError(t, err)
require.Contains(t, results, imageRef)
assert.Empty(t, results[imageRef].Error)
var saved ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", recordID).First(&saved).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", recordID).First(&saved).Error)
assert.False(t, saved.HasUpdate)
assert.Nil(t, saved.LastError)
assert.Equal(t, pinnedDigest, mo.PointerToOption(saved.CurrentDigest).OrEmpty())
@@ -843,14 +853,14 @@ func TestImageUpdateService_CheckMultipleImages_DigestPinnedTagPreservedWhenLoca
dockerService := &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, server)}
svc := NewImageUpdateService(db, nil, nil, dockerService, nil, nil, nil)
- results, err := svc.CheckMultipleImages(context.Background(), []string{imageRef}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{imageRef}, nil)
require.NoError(t, err)
require.Contains(t, results, imageRef)
assert.False(t, results[imageRef].HasUpdate)
assert.Empty(t, results[imageRef].Error)
var saved ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:pinned-local-id").First(&saved).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", "sha256:pinned-local-id").First(&saved).Error)
assert.Equal(t, "9", saved.Tag, "tag should come from the original tag@digest reference, not fall back to the RepoDigests-only placeholder")
}
@@ -860,7 +870,9 @@ func newImageUpdateNoRepoTagsServer(t *testing.T, imageID, localDigest string) *
return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{})) {
+ return
+ }
return
}
@@ -903,7 +915,7 @@ func TestImageUpdateService_CheckImageUpdate_UsesRegistryFallback(t *testing.T)
eventService := event.NewEventService(db, nil, nil)
svc := NewImageUpdateService(db, nil, registryService, dockerService, eventService, nil, nil)
- result, err := svc.CheckImageUpdate(context.Background(), imageRef)
+ result, err := svc.CheckImageUpdate(t.Context(), imageRef)
require.NoError(t, err)
require.NotNil(t, result)
assert.True(t, result.HasUpdate)
@@ -914,7 +926,7 @@ func TestImageUpdateService_CheckImageUpdate_UsesRegistryFallback(t *testing.T)
assert.Equal(t, serverURL.Host, result.AuthRegistry)
var saved ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)
assert.Equal(t, remoteDigest, mo.PointerToOption(saved.LatestDigest).OrEmpty())
}
@@ -933,7 +945,8 @@ func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.
registryService := registry.NewContainerRegistryService(db, func(context.Context) (registry.RegistryDaemonClient, error) {
return &fakeRegistryDaemonClient{
distributionInspectFn: func(ctx context.Context, imageRef string, options client.DistributionInspectOptions) (client.DistributionInspectResult, error) {
- return client.DistributionInspectResult{}, errors.New("error response from daemon: <html><body><h1>403 Forbidden</h1> Request forbidden by administrative rules. </body></html>")
+ return client.DistributionInspectResult{}, errors.New("error response from daemon: <html><body><h1>403 Forbidden</h1> Request forbidden by administrative r" +
+ "ules. </body></html>")
},
}, nil
}, nil, nil, server.Client())
@@ -942,7 +955,7 @@ func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.
eventService := event.NewEventService(db, nil, nil)
svc := NewImageUpdateService(db, nil, registryService, dockerService, eventService, nil, nil)
- results, err := svc.CheckMultipleImages(context.Background(), []string{imageRef}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{imageRef}, nil)
require.NoError(t, err)
require.Contains(t, results, imageRef)
@@ -955,7 +968,7 @@ func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.
assert.Equal(t, serverURL.Host, result.AuthRegistry)
var saved ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)
assert.Equal(t, remoteDigest, mo.PointerToOption(saved.LatestDigest).OrEmpty())
}
@@ -967,7 +980,7 @@ func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestConte
svc := NewImageUpdateService(db, nil, nil, nil, nil, nil, activityService)
for range 5 {
- require.NoError(t, svc.registryLimiter.Acquire(context.Background(), "docker.io"))
+ require.NoError(t, svc.registryLimiter.Acquire(t.Context(), "docker.io"))
}
defer func() {
for range 5 {
@@ -975,16 +988,16 @@ func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestConte
}
}()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
errCh := make(chan error, 1)
go func() {
_, err := svc.CheckMultipleImages(ctx, []string{"nginx:latest"}, nil)
errCh <- err
}()
- var activity activity.Activity
+ var localActivity activity.Activity
require.Eventually(t, func() bool {
- return db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&activity).Error == nil
+ return db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&localActivity).Error == nil
}, time.Second, 10*time.Millisecond)
cancel()
@@ -997,13 +1010,13 @@ func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestConte
}
require.Eventually(t, func() bool {
- if err := db.First(&activity, "id = ?", activity.ID).Error; err != nil {
+ if err := db.First(&localActivity, "id = ?", localActivity.ID).Error; err != nil {
return false
}
- return activity.Status == activitytypes.StatusFailed
+ return localActivity.Status == activitytypes.StatusFailed
}, time.Second, 10*time.Millisecond)
- assert.Equal(t, "Image update check complete", activity.Step)
- assert.Contains(t, activity.LatestMessage, "Image update check failed")
+ assert.Equal(t, "Image update check complete", localActivity.Step)
+ assert.Contains(t, localActivity.LatestMessage, "Image update check failed")
}
func TestImageUpdateService_CheckMultipleImagesTimesOutStalledRegistryCheckInternal(t *testing.T) {
@@ -1023,10 +1036,21 @@ func TestImageUpdateService_CheckMultipleImagesTimesOutStalledRegistryCheckInter
}, nil
}, nil, nil)
- parentCtx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
+ parentCtx, cancel := context.WithTimeout(t.Context(), 2500*time.Millisecond)
defer cancel()
- svc := NewImageUpdateService(db, settingsService, registryService, &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, dockerServer)}, nil, nil, activityService)
+ svc := NewImageUpdateService(
+ db,
+ settingsService,
+ registryService,
+ &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(
+ t,
+ dockerServer,
+ )},
+ nil,
+ nil,
+ activityService,
+ )
start := time.Now()
results, err := svc.CheckMultipleImages(parentCtx, []string{"registry.example.com/team/app:1.2.3"}, nil)
@@ -1038,13 +1062,13 @@ func TestImageUpdateService_CheckMultipleImagesTimesOutStalledRegistryCheckInter
require.NotNil(t, results["registry.example.com/team/app:1.2.3"])
require.Contains(t, results["registry.example.com/team/app:1.2.3"].Error, context.DeadlineExceeded.Error())
- var activity activity.Activity
- require.NoError(t, db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&activity).Error)
- require.Equal(t, activitytypes.StatusFailed, activity.Status)
- require.NotNil(t, activity.EndedAt)
- require.NotNil(t, activity.DurationMs)
- require.Equal(t, "Image update check complete", activity.Step)
- require.Contains(t, activity.LatestMessage, "0 checked, 1 errors")
+ var localActivity activity.Activity
+ require.NoError(t, db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&localActivity).Error)
+ require.Equal(t, activitytypes.StatusFailed, localActivity.Status)
+ require.NotNil(t, localActivity.EndedAt)
+ require.NotNil(t, localActivity.DurationMs)
+ require.Equal(t, "Image update check complete", localActivity.Step)
+ require.Contains(t, localActivity.LatestMessage, "0 checked, 1 errors")
}
func TestImageUpdateService_CheckMultipleImagesPanicMarksActivityFailedInternal(t *testing.T) {
@@ -1063,18 +1087,29 @@ func TestImageUpdateService_CheckMultipleImagesPanicMarksActivityFailedInternal(
}, nil
}, nil, nil)
- svc := NewImageUpdateService(db, settingsService, registryService, &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, dockerServer)}, nil, nil, activityService)
+ svc := NewImageUpdateService(
+ db,
+ settingsService,
+ registryService,
+ &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(
+ t,
+ dockerServer,
+ )},
+ nil,
+ nil,
+ activityService,
+ )
- _, err := svc.CheckMultipleImages(context.Background(), []string{"registry.example.com/team/app:1.2.3"}, nil)
+ _, err := svc.CheckMultipleImages(t.Context(), []string{"registry.example.com/team/app:1.2.3"}, nil)
require.Error(t, err)
require.Contains(t, err.Error(), "image update check panicked")
require.Contains(t, err.Error(), "registry check exploded")
- var activity activity.Activity
- require.NoError(t, db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&activity).Error)
- require.Equal(t, activitytypes.StatusFailed, activity.Status)
- require.NotNil(t, activity.EndedAt)
- require.Contains(t, activity.LatestMessage, "Image update check failed")
+ var localActivity activity.Activity
+ require.NoError(t, db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&localActivity).Error)
+ require.Equal(t, activitytypes.StatusFailed, localActivity.Status)
+ require.NotNil(t, localActivity.EndedAt)
+ require.Contains(t, localActivity.LatestMessage, "Image update check failed")
}
func TestImageUpdateService_GetAllImageRefsUsesDockerAPITimeoutInternal(t *testing.T) {
@@ -1083,7 +1118,7 @@ func TestImageUpdateService_GetAllImageRefsUsesDockerAPITimeoutInternal(t *testi
server := newBlockedDockerAPIServerInternal(t, "/images/json")
svc := NewImageUpdateService(db, settingsService, nil, &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, server)}, nil, nil, nil)
- parentCtx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
+ parentCtx, cancel := context.WithTimeout(t.Context(), 2500*time.Millisecond)
defer cancel()
start := time.Now()
@@ -1101,7 +1136,7 @@ func TestImageUpdateService_InspectLocalImageSnapshotUsesDockerAPITimeoutInterna
server := newBlockedDockerAPIServerInternal(t, "/images/")
svc := NewImageUpdateService(db, settingsService, nil, &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, server)}, nil, nil, nil)
- parentCtx, cancel := context.WithTimeout(context.Background(), 2500*time.Millisecond)
+ parentCtx, cancel := context.WithTimeout(t.Context(), 2500*time.Millisecond)
defer cancel()
start := time.Now()
@@ -1149,7 +1184,7 @@ func TestImageUpdateService_CheckMultipleImages_UsesDockerHubCredentialsOnFirstA
eventService := event.NewEventService(db, nil, nil)
svc := NewImageUpdateService(db, nil, registryService, dockerService, eventService, nil, nil)
- results, err := svc.CheckMultipleImages(context.Background(), []string{"docker.io/library/registry:3"}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{"docker.io/library/registry:3"}, nil)
require.NoError(t, err)
require.Contains(t, results, "docker.io/library/registry:3")
@@ -1188,7 +1223,7 @@ func TestImageUpdateService_CheckMultipleImages_ReportsNotPulledWhenLocalImageMi
eventService := event.NewEventService(db, nil, nil)
svc := NewImageUpdateService(db, nil, registryService, dockerService, eventService, nil, nil)
- results, err := svc.CheckMultipleImages(context.Background(), []string{imageRef}, nil)
+ results, err := svc.CheckMultipleImages(t.Context(), []string{imageRef}, nil)
require.NoError(t, err)
require.Contains(t, results, imageRef)
require.NotNil(t, results[imageRef])
@@ -1198,8 +1233,8 @@ func TestImageUpdateService_CheckMultipleImages_ReportsNotPulledWhenLocalImageMi
assert.Equal(t, remoteDigest, results[imageRef].LatestDigest)
var saved ImageUpdateRecord
- repository := fmt.Sprintf("%s/library/nginx", serverURL.Host)
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", fmt.Sprintf("ref::%s@alpine", strings.ToLower(strings.TrimSpace(repository)))).First(&saved).Error)
+ repository := serverURL.Host + "/library/nginx"
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", fmt.Sprintf("ref::%s@alpine", strings.ToLower(strings.TrimSpace(repository)))).First(&saved).Error)
assert.Equal(t, repository, saved.Repository)
assert.Equal(t, "alpine", saved.Tag)
assert.False(t, saved.HasUpdate)
@@ -1230,11 +1265,11 @@ func TestImageUpdateService_SaveUpdateResultWithSnapshotInternal_PersistsRegistr
ResponseTimeMs: 25,
}
- require.NoError(t, svc.saveUpdateResultWithSnapshotInternal(context.Background(), imageRef, result, nil))
+ require.NoError(t, svc.saveUpdateResultWithSnapshotInternal(t.Context(), imageRef, result, nil))
var saved ImageUpdateRecord
- repository := fmt.Sprintf("%s/library/nginx", serverURL.Host)
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", fmt.Sprintf("ref::%s@alpine", strings.ToLower(strings.TrimSpace(repository)))).First(&saved).Error)
+ repository := serverURL.Host + "/library/nginx"
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", fmt.Sprintf("ref::%s@alpine", strings.ToLower(strings.TrimSpace(repository)))).First(&saved).Error)
assert.Equal(t, repository, saved.Repository)
assert.Equal(t, "alpine", saved.Tag)
assert.True(t, saved.HasUpdate)
@@ -1291,25 +1326,25 @@ func TestImageUpdateService_MarkImageRefUpToDateAfterPull_ClearsMatchingRecordsA
svc := NewImageUpdateService(db, nil, nil, &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, server)}, nil, nil, nil)
- require.NoError(t, svc.MarkImageRefUpToDateAfterPull(context.Background(), imageRef))
+ require.NoError(t, svc.MarkImageRefUpToDateAfterPull(t.Context(), imageRef))
// Sha256 records for old images that other containers are still running must stay HasUpdate=true.
var fullRecord ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:old-full").First(&fullRecord).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", "sha256:old-full").First(&fullRecord).Error)
assert.True(t, fullRecord.HasUpdate, "sha256 record for old image still in use must not be cleared")
var shortRecord ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:old-short").First(&shortRecord).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", "sha256:old-short").First(&shortRecord).Error)
assert.True(t, shortRecord.HasUpdate, "sha256 record for old image still in use must not be cleared")
// Synthetic ref:: record must be cleared since a fresh image was pulled.
var synthRecord ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", syntheticID).First(&synthRecord).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", syntheticID).First(&synthRecord).Error)
assert.False(t, synthRecord.HasUpdate, "synthetic ref:: record must be cleared after pull")
// The newly pulled image record must be saved as up-to-date.
var currentRecord ImageUpdateRecord
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(&currentRecord).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", "sha256:local-image-id").First(&currentRecord).Error)
assert.False(t, currentRecord.HasUpdate)
assert.Equal(t, repository, currentRecord.Repository)
assert.Equal(t, "1.2.3", currentRecord.Tag)
@@ -1492,7 +1527,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {
digestChanged := mo.PointerToOption(existingRecord.LatestDigest).OrEmpty() != mo.PointerToOption(updateRecord.LatestDigest).OrEmpty()
versionChanged := mo.PointerToOption(existingRecord.LatestVersion).OrEmpty() != mo.PointerToOption(updateRecord.LatestVersion).OrEmpty()
- updateRecord.NotificationSent = !stateChanged && !(updateRecord.HasUpdate && (digestChanged || versionChanged)) && existingRecord.NotificationSent
+ updateRecord.NotificationSent = !stateChanged && (!updateRecord.HasUpdate || (!digestChanged && !versionChanged)) && existingRecord.NotificationSent
// Save the updated record
err = db.Save(updateRecord).Error
@@ -1576,7 +1611,7 @@ func TestImageUpdateService_RateLimitErrorPreservesPreviousResult(t *testing.T)
// TestGetUnnotifiedUpdates tests retrieving updates that haven't been notified
func TestImageUpdateService_GetUnnotifiedUpdates(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
svc := &ImageUpdateService{db: db}
@@ -1631,7 +1666,7 @@ func TestImageUpdateService_GetUnnotifiedUpdates(t *testing.T) {
// TestMarkUpdatesAsNotified tests marking images as notified
func TestImageUpdateService_MarkUpdatesAsNotified(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
svc := &ImageUpdateService{db: db}
@@ -1673,7 +1708,7 @@ func TestImageUpdateService_MarkUpdatesAsNotified(t *testing.T) {
// TestMarkUpdatesAsNotified_EmptyList tests handling of empty ID list
func TestImageUpdateService_MarkUpdatesAsNotified_EmptyList(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
svc := &ImageUpdateService{db: db}
@@ -1739,13 +1774,29 @@ func TestImageUpdateService_SendBatchNotifications_FiltersByUpdateCheckEligibili
{ID: "sha256:shared", Repository: "docker.io/test/shared", Tag: "latest", HasUpdate: true},
{ID: "sha256:pruned", Repository: "docker.io/test/ref-only", Tag: "2.0", HasUpdate: true},
{ID: "sha256:unused", Repository: "docker.io/test/unused", Tag: "latest", HasUpdate: true},
- {ID: "container::install-excluded", ContainerID: "install-excluded", ImageID: "sha256:install-excluded", Repository: "docker.io/test/install-excluded", Tag: "latest", HasUpdate: true, UpdateType: UpdateTypeTag},
- {ID: "container::unmonitored", ContainerID: "unmonitored", ImageID: "sha256:unmonitored", Repository: "docker.io/test/unmonitored", Tag: "latest", HasUpdate: true, UpdateType: UpdateTypeTag},
+ {
+ ID: "container::install-excluded",
+ ContainerID: "install-excluded",
+ ImageID: "sha256:install-excluded",
+ Repository: "docker.io/test/install-excluded",
+ Tag: "latest",
+ HasUpdate: true,
+ UpdateType: UpdateTypeTag,
+ },
+ {
+ ID: "container::unmonitored",
+ ContainerID: "unmonitored",
+ ImageID: "sha256:unmonitored",
+ Repository: "docker.io/test/unmonitored",
+ Tag: "latest",
+ HasUpdate: true,
+ UpdateType: UpdateTypeTag,
+ },
{ID: "container::gone", ContainerID: "gone", ImageID: "sha256:gone", Repository: "docker.io/test/gone", Tag: "latest", HasUpdate: true, UpdateType: UpdateTypeTag},
}
require.NoError(t, db.Create(&records).Error)
- svc.SendBatchUpdateNotifications(context.Background())
+ require.NoError(t, svc.SendBatchUpdateNotifications(t.Context()))
require.EqualValues(t, 1, calls.Load(), "eligible records are delivered in one batch")
notified := map[string]bool{}
@@ -1766,7 +1817,7 @@ func TestImageUpdateService_SendBatchNotifications_FiltersByUpdateCheckEligibili
// Re-enabling monitoring lets the held-back records notify on the next flush.
containers[1].Labels = nil
svc.dockerService = newImageUpdateNotificationDockerServiceInternal(t, containers)
- svc.SendBatchUpdateNotifications(context.Background())
+ require.NoError(t, svc.SendBatchUpdateNotifications(t.Context()))
require.EqualValues(t, 2, calls.Load())
var resumed ImageUpdateRecord
require.NoError(t, db.First(&resumed, "id = ?", "container::unmonitored").Error)
@@ -1782,7 +1833,7 @@ func TestImageUpdateService_SendBatchNotifications_UnresolvedEligibilityLeavesUn
svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)
require.NoError(t, db.Create(&ImageUpdateRecord{ID: "sha256:img", Repository: "test/repo", Tag: "latest", HasUpdate: true}).Error)
- svc.SendBatchUpdateNotifications(context.Background())
+ require.ErrorContains(t, svc.SendBatchUpdateNotifications(t.Context()), "resolve update-check eligibility: docker service unavailable")
require.Zero(t, calls.Load(), "nothing is sent when eligibility cannot be resolved")
var reloaded ImageUpdateRecord
@@ -1828,10 +1879,10 @@ func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *te
// canceled. Derive it from a lifecycle-marked parent to mirror production,
// where every request/scheduler ctx inherits the marker via the server
// BaseContext — the detach must work even then.
- ctx, cancel := context.WithCancel(utils.WithAppLifecycleContext(context.Background()))
+ ctx, cancel := context.WithCancel(utils.WithAppLifecycleContext(t.Context()))
cancel()
- svc.SendBatchUpdateNotifications(ctx)
+ require.NoError(t, svc.SendBatchUpdateNotifications(ctx))
// The provider being reached, and the record being marked notified, both prove
// GetUnnotifiedUpdates + the send + MarkUpdatesAsNotified ran despite the canceled
@@ -1863,13 +1914,13 @@ func TestImageUpdateService_SendBatchNotifications_NoEligibleProviders_LeavesUnn
}
require.NoError(t, db.Create(&rec).Error)
- svc.SendBatchUpdateNotifications(context.Background())
+ require.NoError(t, svc.SendBatchUpdateNotifications(t.Context()))
var reloaded ImageUpdateRecord
require.NoError(t, db.First(&reloaded, "id = ?", "sha256:img-no-provider").Error)
assert.False(t, reloaded.NotificationSent)
- unnotified, err := svc.GetUnnotifiedUpdates(context.Background())
+ unnotified, err := svc.GetUnnotifiedUpdates(t.Context())
require.NoError(t, err)
require.Contains(t, unnotified, "sha256:img-no-provider")
}
@@ -1915,7 +1966,7 @@ func TestImageUpdateService_SendBatchNotifications_PartialFailureStillMarksNotif
}
require.NoError(t, db.Create(&rec).Error)
- svc.SendBatchUpdateNotifications(context.Background())
+ require.NoError(t, svc.SendBatchUpdateNotifications(t.Context()))
var reloaded ImageUpdateRecord
require.NoError(t, db.First(&reloaded, "id = ?", "sha256:img-partial").Error)
@@ -1923,7 +1974,7 @@ func TestImageUpdateService_SendBatchNotifications_PartialFailureStillMarksNotif
}
func TestImageUpdateService_GetUpdateSummaryForImageIDs_FiltersToLiveImages(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
svc := &ImageUpdateService{db: db}
now := time.Now()
@@ -1974,7 +2025,7 @@ func TestImageUpdateService_GetUpdateSummaryForImageIDs_FiltersToLiveImages(t *t
}
func TestImageUpdateService_GetUpdateSummaryForImageIDs_EmptyLiveSet(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
svc := &ImageUpdateService{db: db}
@@ -2023,14 +2074,14 @@ func newImageUpdateTestSettingsServiceInternal(t *testing.T, registryTimeout, do
t.Helper()
t.Setenv("REGISTRY_TIMEOUT", registryTimeout)
t.Setenv("DOCKER_API_TIMEOUT", dockerAPITimeout)
- ctx := context.Background()
+ ctx := t.Context()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))
dbWrap := &database.DB{DB: db}
service, err := settings.NewSettingsService(ctx, dbWrap)
if err == nil {
- t.Cleanup(func() { require.NoError(t, service.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, service.Stop(context.WithoutCancel(t.Context()))) })
}
require.NoError(t, err)
return service
@@ -2042,7 +2093,9 @@ func newBlockedDockerAPIServerInternal(t *testing.T, pathContains string) *httpt
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/containers/json") {
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{})) {
+ return
+ }
return
}
@@ -2154,7 +2207,7 @@ func TestImageUpdateService_GetAllImageRefsHonorsExclusiveContainerOptOutInterna
nil,
)
- got, err := svc.getAllImageRefsInternal(context.Background(), 0)
+ got, err := svc.getAllImageRefsInternal(t.Context(), 0)
require.NoError(t, err)
assert.Equal(t, []string{enabledRef, sharedRef, unusedRef, runningOnlyRef, stoppedOnlyRef, pinnedRef}, got)
@@ -2199,11 +2252,11 @@ func TestImageUpdateService_GetAllImageRefsAppliesLimitAfterOptOutFilteringInter
nil,
)
- got, err := svc.getAllImageRefsInternal(context.Background(), 2)
+ got, err := svc.getAllImageRefsInternal(t.Context(), 2)
require.NoError(t, err)
assert.Equal(t, []string{enabledRef, unusedRef}, got)
- got, err = svc.getAllImageRefsInternal(context.Background(), 3)
+ got, err = svc.getAllImageRefsInternal(t.Context(), 3)
require.NoError(t, err)
assert.Equal(t, []string{enabledRef, unusedRef, containerOnlyRef}, got)
}
@@ -2253,7 +2306,7 @@ func TestImageUpdateService_GetAllImageRefsExcludesAliasesOfOptedOutImageInterna
nil,
)
- got, err := svc.getAllImageRefsInternal(context.Background(), 0)
+ got, err := svc.getAllImageRefsInternal(t.Context(), 0)
require.NoError(t, err)
assert.NotContains(t, got, primaryRef)
@@ -2301,7 +2354,7 @@ func TestImageUpdateService_GetAllImageRefsKeepsImageSharedByEligibleContainerIn
nil,
)
- got, err := svc.getAllImageRefsInternal(context.Background(), 0)
+ got, err := svc.getAllImageRefsInternal(t.Context(), 0)
require.NoError(t, err)
assert.Contains(t, got, imageRef)
@@ -2339,7 +2392,7 @@ func TestImageUpdateService_GetAllImageRefsFallsBackToRefWhenImageIDsDifferInter
nil,
)
- got, err := svc.getAllImageRefsInternal(context.Background(), 0)
+ got, err := svc.getAllImageRefsInternal(t.Context(), 0)
require.NoError(t, err)
assert.NotContains(t, got, imageRef)
@@ -2384,7 +2437,7 @@ func TestImageUpdateService_GetAllImageRefsMergesIDAndReferenceEligibilityIntern
nil,
)
- got, err := svc.getAllImageRefsInternal(context.Background(), 0)
+ got, err := svc.getAllImageRefsInternal(t.Context(), 0)
require.NoError(t, err)
assert.Contains(t, got, imageRef)
@@ -2424,7 +2477,7 @@ func TestImageUpdateService_GetAllImageRefsFallsBackWhenContainerDiscoveryFailsI
nil,
)
- got, err := svc.getAllImageRefsInternal(context.Background(), 0)
+ got, err := svc.getAllImageRefsInternal(t.Context(), 0)
require.NoError(t, err)
assert.Equal(t, []string{firstRef, secondRef}, got)
@@ -2451,7 +2504,16 @@ func TestFilterImageSummariesKeepsInstallExcludedContainersMonitoredInternal(t *
{ID: "c2", Names: []string{"/ui-excluded"}, ImageID: "sha256:ui-excluded", Image: uiExcludedRef},
{ID: "c3", Names: []string{"/unmonitored"}, ImageID: "sha256:unmonitored", Image: unmonitoredRef, Labels: map[string]string{strings.ToUpper(imageref.UpdateCheckLabel): "no"}},
{ID: "c4", Names: []string{"/shared-unmonitored"}, ImageID: "sha256:shared", Image: sharedRef, Labels: map[string]string{imageref.UpdateCheckLabel: "off"}},
- {ID: "c5", Names: []string{"/shared-garbage-value"}, ImageID: "sha256:shared", Image: "docker.io/local/shared:latest", Labels: map[string]string{imageref.UpdateCheckLabel: "maybe", labels.LabelUpdater: "false"}},
+ {
+ ID: "c5",
+ Names: []string{"/shared-garbage-value"},
+ ImageID: "sha256:shared",
+ Image: "docker.io/local/shared:latest",
+ Labels: map[string]string{
+ imageref.UpdateCheckLabel: "maybe",
+ labels.LabelUpdater: "false",
+ },
+ },
{ID: "c6", Names: []string{"/unmonitored-only"}, ImageID: "sha256:pruned", Image: "local/unmonitored-only:1.0", Labels: map[string]string{imageref.UpdateCheckLabel: "0"}},
}
@@ -2484,7 +2546,9 @@ func TestContainerTagChecksPersistIndependentPoliciesInternal(t *testing.T) {
}
tagListings.Add(1)
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/app", "tags": []string{"1.0.0", "1.1.0", "2.0.0"}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/app", "tags": []string{"1.0.0", "1.1.0", "2.0.0"}})) {
+ return
+ }
}))
defer registryServer.Close()
registryURL, err := url.Parse(registryServer.URL)
@@ -2499,12 +2563,51 @@ func TestContainerTagChecksPersistIndependentPoliciesInternal(t *testing.T) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{{ID: "one", Image: imageRef, ImageID: imageID, Labels: values["one"]}, {ID: "two", Image: imageRef, ImageID: imageID, Labels: values["two"]}}))
+ if !assert.NoError(
+ t,
+ json.NewEncoder(w).Encode([]dockertypescontainer.Summary{
+ {
+ ID: "one",
+ Image: imageRef,
+ ImageID: imageID,
+ Labels: values["one"],
+ },
+ {
+ ID: "two",
+ Image: imageRef,
+ ImageID: imageID,
+ Labels: values["two"],
+ },
+ }),
+ ) {
+ return
+ }
case strings.Contains(r.URL.Path, "/images/"):
- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{ID: imageID, RepoTags: []string{imageRef}, RepoDigests: []string{registryURL.Host + "/team/app@" + imageID}}))
+ if !assert.NoError(
+ t,
+ json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{
+ ID: imageID,
+ RepoTags: []string{imageRef},
+ RepoDigests: []string{registryURL.Host + "/team/app@" + imageID},
+ }),
+ ) {
+ return
+ }
case strings.Contains(r.URL.Path, "/containers/"):
id := kit.Ternary(strings.Contains(r.URL.Path, "/two/"), "two", "one")
- require.NoError(t, json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{ID: id, Image: imageID, Config: &dockertypescontainer.Config{Image: imageRef, Labels: values[id]}}))
+ if !assert.NoError(
+ t,
+ json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{
+ ID: id,
+ Image: imageID,
+ Config: &dockertypescontainer.Config{
+ Image: imageRef,
+ Labels: values[id],
+ },
+ }),
+ ) {
+ return
+ }
default:
t.Errorf("unexpected Docker request %s", r.URL.Path)
http.NotFound(w, r)
@@ -2582,7 +2685,9 @@ func TestContainerTagChecksSeparateMonitoringFromInstallationInternal(t *testing
return
}
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/app", "tags": []string{"1.0.0", "1.1.0"}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/app", "tags": []string{"1.0.0", "1.1.0"}})) {
+ return
+ }
}))
defer registryServer.Close()
registryURL, err := url.Parse(registryServer.URL)
@@ -2598,14 +2703,29 @@ func TestContainerTagChecksSeparateMonitoringFromInstallationInternal(t *testing
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{
{ID: "install-excluded", Names: []string{"/install-excluded"}, Image: imageRef, ImageID: imageID, Labels: values["install-excluded"]},
{ID: "unmonitored", Names: []string{"/unmonitored"}, Image: imageRef, ImageID: imageID, Labels: values["unmonitored"]},
- }))
+ })) {
+ return
+ }
case strings.Contains(r.URL.Path, "/containers/"):
id := kit.Ternary(strings.Contains(r.URL.Path, "/unmonitored/"), "unmonitored", "install-excluded")
inspected = append(inspected, id)
- require.NoError(t, json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{ID: id, Name: "/" + id, Image: imageID, Config: &dockertypescontainer.Config{Image: imageRef, Labels: values[id]}}))
+ if !assert.NoError(
+ t,
+ json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{
+ ID: id,
+ Name: "/" + id,
+ Image: imageID,
+ Config: &dockertypescontainer.Config{
+ Image: imageRef,
+ Labels: values[id],
+ },
+ }),
+ ) {
+ return
+ }
default:
t.Errorf("unexpected Docker request %s", r.URL.Path)
http.NotFound(w, r)
@@ -2621,7 +2741,21 @@ func TestContainerTagChecksSeparateMonitoringFromInstallationInternal(t *testing
svc := NewImageUpdateService(db, settingsService, registryService, &docker.DockerClientService{Client: newImageUpdateTestDockerClientInternal(t, dockerServer)}, nil, nil, nil)
pending := "1.1.0"
- stale := ImageUpdateRecord{ID: "container::unmonitored", ContainerID: "unmonitored", ImageID: imageID, PolicyKey: imageref.UpdatePolicyKey(imageRef, values["unmonitored"]), Repository: registryURL.Host + "/team/app", Tag: "1.0.0", HasUpdate: true, UpdateType: UpdateTypeTag, LatestVersion: &pending, CheckTime: time.Now().UTC()}
+ stale := ImageUpdateRecord{
+ ID: "container::unmonitored",
+ ContainerID: "unmonitored",
+ ImageID: imageID,
+ PolicyKey: imageref.UpdatePolicyKey(
+ imageRef,
+ values["unmonitored"],
+ ),
+ Repository: registryURL.Host + "/team/app",
+ Tag: "1.0.0",
+ HasUpdate: true,
+ UpdateType: UpdateTypeTag,
+ LatestVersion: &pending,
+ CheckTime: time.Now().UTC(),
+ }
require.NoError(t, db.Create(&stale).Error)
checks, err := svc.checkContainerTagUpdatesInternal(t.Context(), []string{imageRef}, nil)
@@ -2664,7 +2798,9 @@ func TestContainerTagChecksUseRegistryTagTimeoutInternal(t *testing.T) {
{name: "listing slower than registry timeout succeeds within tag budget", tagTimeout: "30", respond: func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(1300 * time.Millisecond)
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/app", "tags": []string{"1.0.0", "1.1.0"}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/app", "tags": []string{"1.0.0", "1.1.0"}})) {
+ return
+ }
}},
{name: "stalled listing fails at tag budget", tagTimeout: "1", respond: func(_ http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
@@ -2693,11 +2829,27 @@ func TestContainerTagChecksUseRegistryTagTimeoutInternal(t *testing.T) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{{ID: "one", Image: imageRef, ImageID: imageID, Labels: autoLabels}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{{ID: "one", Image: imageRef, ImageID: imageID, Labels: autoLabels}})) {
+ return
+ }
case strings.Contains(r.URL.Path, "/images/"):
- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{ID: imageID, RepoTags: []string{imageRef}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{ID: imageID, RepoTags: []string{imageRef}})) {
+ return
+ }
case strings.Contains(r.URL.Path, "/containers/"):
- require.NoError(t, json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{ID: "one", Image: imageID, Config: &dockertypescontainer.Config{Image: imageRef, Labels: autoLabels}}))
+ if !assert.NoError(
+ t,
+ json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{
+ ID: "one",
+ Image: imageID,
+ Config: &dockertypescontainer.Config{
+ Image: imageRef,
+ Labels: autoLabels,
+ },
+ }),
+ ) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -2736,7 +2888,9 @@ func TestContainerTagChecksPersistResultsFinishedBeforeScanDeadlineInternal(t *t
case registryPingInternal(w, r):
case strings.HasSuffix(r.URL.Path, "/team/fast/tags/list"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/fast", "tags": []string{"1.0.0", "1.1.0"}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(map[string]any{"name": "team/fast", "tags": []string{"1.0.0", "1.1.0"}})) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/team/slow/tags/list"):
// Stall until the scan deadline cancels the request.
<-r.Context().Done()
@@ -2757,14 +2911,30 @@ func TestContainerTagChecksPersistResultsFinishedBeforeScanDeadlineInternal(t *t
name := nameFor(r.URL.Path)
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]dockertypescontainer.Summary{
{ID: "fast", Image: imageRefs["fast"], ImageID: imageIDs["fast"], Labels: autoLabels},
{ID: "slow", Image: imageRefs["slow"], ImageID: imageIDs["slow"], Labels: autoLabels},
- }))
+ })) {
+ return
+ }
case strings.Contains(r.URL.Path, "/images/"):
- require.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{ID: imageIDs[name], RepoTags: []string{imageRefs[name]}}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode(dockertypesimage.InspectResponse{ID: imageIDs[name], RepoTags: []string{imageRefs[name]}})) {
+ return
+ }
case strings.Contains(r.URL.Path, "/containers/"):
- require.NoError(t, json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{ID: name, Image: imageIDs[name], Config: &dockertypescontainer.Config{Image: imageRefs[name], Labels: autoLabels}}))
+ if !assert.NoError(
+ t,
+ json.NewEncoder(w).Encode(dockertypescontainer.InspectResponse{
+ ID: name,
+ Image: imageIDs[name],
+ Config: &dockertypescontainer.Config{
+ Image: imageRefs[name],
+ Labels: autoLabels,
+ },
+ }),
+ ) {
+ return
+ }
default:
http.NotFound(w, r)
}
diff --git a/backend/internal/imageupdate/tag_updates.go b/backend/internal/imageupdate/tag_updates.go
index d37eacaf0..a12831edc 100644
--- a/backend/internal/imageupdate/tag_updates.go
+++ b/backend/internal/imageupdate/tag_updates.go
@@ -51,7 +51,12 @@ type tagRegistryInternal struct {
digests *scanRegistryMemoInternal[string]
}
-func newTagRegistryInternal(service *registry.ContainerRegistryService, credentials []containerregistry.Credential, dockerService *docker.DockerClientService, settingsService *settings.SettingsService) tagRegistryInternal {
+func newTagRegistryInternal(
+ service *registry.ContainerRegistryService,
+ credentials []containerregistry.Credential,
+ dockerService *docker.DockerClientService,
+ settingsService *settings.SettingsService,
+) tagRegistryInternal {
return tagRegistryInternal{
service: service,
credentials: credentials,
@@ -198,8 +203,8 @@ func (s *ImageUpdateService) checkContainerTagUpdatesInternal(ctx context.Contex
}
candidates = append(candidates, cnt)
}
- if err := s.deleteContainerUpdateRecordsInternal(ctx, staleDigestContainerIDs); err != nil {
- return results, err
+ if deleteContainerUpdateRecordsErr := s.deleteContainerUpdateRecordsInternal(ctx, staleDigestContainerIDs); deleteContainerUpdateRecordsErr != nil {
+ return results, deleteContainerUpdateRecordsErr
}
// Policies are evaluated concurrently; the shared adapter dedupes registry
@@ -255,8 +260,8 @@ func (s *ImageUpdateService) checkContainerTagInternal(ctx context.Context, engi
return result
}
if s.registryLimiter != nil {
- if err := s.registryLimiter.Acquire(ctx, parsed.RegistryHost); err != nil {
- result.Error = err.Error()
+ if acquireErr := s.registryLimiter.Acquire(ctx, parsed.RegistryHost); acquireErr != nil {
+ result.Error = acquireErr.Error()
return result
}
defer s.registryLimiter.Release(parsed.RegistryHost)
@@ -281,9 +286,9 @@ func (s *ImageUpdateService) checkContainerTagInternal(ctx context.Context, engi
result.CurrentDigest = check.CurrentDigest
result.LatestDigest = check.TargetDigest
if check.TargetRef != "" {
- target, err := refs.NormalizeReference(check.TargetRef)
- if err != nil {
- result.Error = err.Error()
+ target, normalizeReferenceErr := refs.NormalizeReference(check.TargetRef)
+ if normalizeReferenceErr != nil {
+ result.Error = normalizeReferenceErr.Error()
result.HasUpdate = false
return result
}
@@ -311,11 +316,11 @@ func (s *ImageUpdateService) saveContainerTagResultInternal(ctx context.Context,
policyKey := imageref.UpdatePolicyKey(cnt.Image, cnt.Labels)
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// A previous good result must not survive a rate limit under a different policy.
- if err := tx.Where("id = ? AND policy_key <> ?", id, policyKey).Delete(&ImageUpdateRecord{}).Error; err != nil {
- return err
+ if deleteStaleUpdatesErr := tx.Where("id = ? AND policy_key <> ?", id, policyKey).Delete(&ImageUpdateRecord{}).Error; deleteStaleUpdatesErr != nil {
+ return deleteStaleUpdatesErr
}
- if err := savePreparedUpdateResultWithTxInternal(tx, id, parsed.RegistryHost+"/"+parsed.Repository, parsed.Tag, result); err != nil {
- return err
+ if savePreparedUpdateResultWithTxErr := savePreparedUpdateResultWithTxInternal(tx, id, parsed.RegistryHost+"/"+parsed.Repository, parsed.Tag, result); savePreparedUpdateResultWithTxErr != nil {
+ return savePreparedUpdateResultWithTxErr
}
return tx.Model(&ImageUpdateRecord{}).Where("id = ?", id).Updates(map[string]any{"container_id": cnt.ID, "image_id": cnt.ImageID, "policy_key": policyKey}).Error
})
diff --git a/backend/internal/job/activity.go b/backend/internal/job/activity.go
index ebacb8b46..0d373d9fa 100644
--- a/backend/internal/job/activity.go
+++ b/backend/internal/job/activity.go
@@ -82,14 +82,14 @@ func (s *JobService) ReconcileStartupActivities(ctx context.Context, extraProtec
}
}
}
- if err := s.activity.FailInterruptedBackups(ctx, protected...); err != nil {
- return err
+ if failInterruptedBackupsErr := s.activity.FailInterruptedBackups(ctx, protected...); failInterruptedBackupsErr != nil {
+ return failInterruptedBackupsErr
}
- if _, err := s.activity.FailStaleImageUpdateChecks(ctx); err != nil {
- return err
+ if _, failStaleImageUpdateChecksErr := s.activity.FailStaleImageUpdateChecks(ctx); failStaleImageUpdateChecksErr != nil {
+ return failStaleImageUpdateChecksErr
}
- if _, err := s.activity.ResolveStaleAutoUpdateActivities(ctx, protected...); err != nil {
- return err
+ if _, resolveStaleAutoUpdateActivitiesErr := s.activity.ResolveStaleAutoUpdateActivities(ctx, protected...); resolveStaleAutoUpdateActivitiesErr != nil {
+ return resolveStaleAutoUpdateActivitiesErr
}
_, err = s.activity.ResolveOrphanedQueuedActivities(ctx, protected...)
return err
diff --git a/backend/internal/job/activity_test.go b/backend/internal/job/activity_test.go
index cc284721b..641ac2cd3 100644
--- a/backend/internal/job/activity_test.go
+++ b/backend/internal/job/activity_test.go
@@ -114,8 +114,8 @@ func TestJobActivityVisibilityAndGrouping(t *testing.T) {
require.Equal(t, test.visible, run.ActivityID != "")
if test.visible {
require.Equal(t, test.environment, run.ActivityEnvironmentID)
- detail, err := activities.GetActivityDetail(t.Context(), test.environment, run.ActivityID, 10)
- require.NoError(t, err)
+ detail, getActivityDetailErr := activities.GetActivityDetail(t.Context(), test.environment, run.ActivityID, 10)
+ require.NoError(t, getActivityDetailErr)
require.Equal(t, test.environment, detail.Activity.Metadata["environmentId"])
}
child, err := activities.StartActivity(svc.runContextInternal(t.Context(), run), activity.StartActivityRequest{Type: activitytypes.TypeImagePull})
@@ -142,7 +142,7 @@ func TestJobActivityRestartRepairsFailedProjection(t *testing.T) {
restarted := NewJobService(db, nil, &config.Config{}, svc.runs, nil, nil, activities)
require.NoError(t, restarted.runs.Start(ctx, ctx))
t.Cleanup(func() {
- stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), time.Second)
defer cancel()
require.NoError(t, restarted.runs.Stop(stopCtx))
})
diff --git a/backend/internal/job/execution.go b/backend/internal/job/execution.go
index 0883ef6ac..5fde19c5f 100644
--- a/backend/internal/job/execution.go
+++ b/backend/internal/job/execution.go
@@ -44,7 +44,15 @@ func (s *JobService) Submit(ctx context.Context, request st.Request) (st.Run, er
} else if err := s.validateLocalJobInternal(ctx, request.JobID); err != nil {
return st.Run{}, err
}
- if err := s.authorizeRunInternal(ctx, st.Run{Trigger: request.Trigger, RequestedBy: request.RequestedBy, RequestedWithKey: request.RequestedWithKey, EnvironmentID: request.EnvironmentID}); err != nil {
+ if err := s.authorizeRunInternal(
+ ctx,
+ st.Run{
+ Trigger: request.Trigger,
+ RequestedBy: request.RequestedBy,
+ RequestedWithKey: request.RequestedWithKey,
+ EnvironmentID: request.EnvironmentID,
+ },
+ ); err != nil {
return st.Run{}, err
}
return s.runs.Submit(ctx, request)
@@ -77,7 +85,7 @@ func (s *JobService) validateLocalJobInternal(ctx context.Context, jobID string)
if !ok {
return errors.New("job is not registered")
}
- if conditional, ok := job.(st.ConditionalJob); ok && !conditional.ShouldSchedule(ctx) {
+ if conditional, localOk := job.(st.ConditionalJob); localOk && !conditional.ShouldSchedule(ctx) {
return errors.New("job is disabled")
}
return nil
@@ -133,7 +141,7 @@ func (s *JobService) executeRunInternal(ctx context.Context, run st.Run) (st.Out
if !ok {
return st.Outcome{Status: unavailableStatus, Message: "Job or target no longer exists"}, nil
}
- if conditional, ok := job.(st.ConditionalJob); ok && !conditional.ShouldSchedule(ctx) {
+ if conditional, localOk := job.(st.ConditionalJob); localOk && !conditional.ShouldSchedule(ctx) {
return st.Outcome{Status: unavailableStatus, Message: "Job is disabled"}, nil
}
outcome, err := job.Run(ctx)
@@ -169,7 +177,8 @@ func classifyOutcomeInternal(jobID string, outcome st.Outcome, err error) (st.Ou
func safeJobInternal(jobID string) bool {
switch jobID {
- case "image-polling", "environment-health", "docker-client-refresh", "event-cleanup", "expired-sessions-cleanup", "activity-sweep", "upload-sessions-cleanup", "git-clone-scratch-cleanup", "analytics-heartbeat", "apns-outbox", "vulnerability-scan":
+ case "image-polling", "environment-health", "docker-client-refresh", "event-cleanup", "expired-sessions-cleanup", "activity-sweep", "upload-sessions-cleanup",
+ "git-clone-scratch-cleanup", "analytics-heartbeat", "apns-outbox", "vulnerability-scan":
return true
}
return strings.HasPrefix(jobID, "environment-health:")
@@ -187,7 +196,7 @@ func (s *JobService) reconcileRunInternal(ctx context.Context, run st.Run) (st.O
}
if s.scheduler != nil {
if job, ok := s.scheduler.GetJob(run.JobID); ok {
- if reconciler, ok := job.(st.Reconciler); ok {
+ if reconciler, localOk := job.(st.Reconciler); localOk {
return reconciler.Reconcile(s.runContextInternal(ctx, run), run)
}
}
@@ -213,7 +222,7 @@ func (s *JobService) reconcileRunInternal(ctx context.Context, run st.Run) (st.O
run.Outcome.Targets[index].Status = st.Succeeded
}
if job, ok := s.scheduler.GetJob(run.JobID); ok {
- if reconciler, ok := job.(st.Reconciler); ok {
+ if reconciler, localOk2 := job.(st.Reconciler); localOk2 {
outcome, err := reconciler.Reconcile(s.runContextInternal(ctx, run), run)
if err != nil {
slog.WarnContext(ctx, "Job reconciliation requires attention", "runId", run.ID, "error", err)
diff --git a/backend/internal/job/module.go b/backend/internal/job/module.go
index 638ba0202..7c7001672 100644
--- a/backend/internal/job/module.go
+++ b/backend/internal/job/module.go
@@ -12,8 +12,8 @@ type Module struct {
environment *environment.EnvironmentService
}
-func New(service *JobService, environment *environment.EnvironmentService) *Module {
- return &Module{service: service, environment: environment}
+func New(service *JobService, localEnvironment *environment.EnvironmentService) *Module {
+ return &Module{service: service, environment: localEnvironment}
}
func (m *Module) Service() *JobService {
diff --git a/backend/internal/job/remote.go b/backend/internal/job/remote.go
index 89cce28c6..87111d3aa 100644
--- a/backend/internal/job/remote.go
+++ b/backend/internal/job/remote.go
@@ -44,8 +44,8 @@ func (s *JobService) deliverRemoteInternal(ctx context.Context, run st.Run) (st.
return s.acknowledgeRemoteInternal(ctx, run, runPath, *run.RemoteOutcome)
}
var catalog jobschedule.JobListResponse
- if err := s.environment.ProxyJSONRequest(ctx, run.EnvironmentID, http.MethodGet, "/api/environments/0/jobs", nil, &catalog); err != nil {
- return remoteFailureInternal(err)
+ if proxyJSONRequestErr := s.environment.ProxyJSONRequest(ctx, run.EnvironmentID, http.MethodGet, "/api/environments/0/jobs", nil, &catalog); proxyJSONRequestErr != nil {
+ return remoteFailureInternal(proxyJSONRequestErr)
}
if !catalog.DurableRuns {
return st.Outcome{Status: st.Failed, Message: "Upgrade required: agent does not support durable job runs"}, nil
@@ -165,8 +165,8 @@ func (s *JobService) ListRemoteJobs(ctx context.Context, environmentID string) (
if err != nil {
return nil, err
}
- if err := s.store.Set(ctx, key, string(raw)); err != nil {
- return nil, err
+ if setErr := s.store.Set(ctx, key, string(raw)); setErr != nil {
+ return nil, setErr
}
} else {
var status *remenv.StatusError
@@ -178,8 +178,8 @@ func (s *JobService) ListRemoteJobs(ctx context.Context, environmentID string) (
return nil, err
}
if found {
- if err := json.Unmarshal([]byte(raw), &catalog); err != nil {
- return nil, err
+ if unmarshalErr := json.Unmarshal([]byte(raw), &catalog); unmarshalErr != nil {
+ return nil, unmarshalErr
}
} else {
catalog.IsAgent = true
@@ -207,14 +207,14 @@ func (s *JobService) RetryRemoteRun(ctx context.Context, environmentID, jobID, r
if err != nil {
return run, err
}
- if err := s.authorizeRunInternal(ctx, run); err != nil {
- return run, err
+ if authorizeRunErr := s.authorizeRunInternal(ctx, run); authorizeRunErr != nil {
+ return run, authorizeRunErr
}
if run.Resolution != nil && run.Resolution.ResolvedBy == common.SystemUser.Username {
var remote st.Run
path := "/api/environments/0/jobs/" + url.PathEscape(jobID) + "/runs/" + url.PathEscape(runID)
- if err := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &remote); err != nil {
- return run, err
+ if proxyJSONRequestErr := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &remote); proxyJSONRequestErr != nil {
+ return run, proxyJSONRequestErr
}
if remote.ID != runID || remote.JobID != jobID || remote.EnvironmentID != "0" || remote.Status != st.Failed {
return run, errors.New("upgrade the agent before retrying a legacy settled run")
@@ -294,8 +294,8 @@ func (s *JobService) admitRemoteInternal(ctx context.Context, run st.Run, catalo
}
path := "/api/environments/0/jobs/" + url.PathEscape(run.JobID) + "/run"
var accepted jobschedule.JobRunResponse
- if err := s.environment.ProxyJSONRequest(ctx, run.EnvironmentID, http.MethodPost, path, body, &accepted); err != nil {
- return st.Run{}, err
+ if proxyJSONRequestErr := s.environment.ProxyJSONRequest(ctx, run.EnvironmentID, http.MethodPost, path, body, &accepted); proxyJSONRequestErr != nil {
+ return st.Run{}, proxyJSONRequestErr
}
if accepted.RunID != run.ID {
return st.Run{}, errors.New("Agent returned an inconsistent delivery receipt") //nolint:staticcheck // Preserve the existing error message.
diff --git a/backend/internal/job/remote_history.go b/backend/internal/job/remote_history.go
index c0816186b..aeb8988db 100644
--- a/backend/internal/job/remote_history.go
+++ b/backend/internal/job/remote_history.go
@@ -42,43 +42,43 @@ func (s *JobService) ListRuns(ctx context.Context, environmentID, jobID string,
merged[run.ID] = run
}
}
- runs := make([]st.Run, 0, len(merged))
+ localRuns := make([]st.Run, 0, len(merged))
for _, run := range merged {
- runs = append(runs, projectRunOutcomeInternal(run))
+ localRuns = append(localRuns, projectRunOutcomeInternal(run))
}
- sort.Slice(runs, func(i, j int) bool {
- if runs[i].CreatedAt.Equal(runs[j].CreatedAt) {
- return runs[i].ID < runs[j].ID
+ sort.Slice(localRuns, func(i, j int) bool {
+ if localRuns[i].CreatedAt.Equal(localRuns[j].CreatedAt) {
+ return localRuns[i].ID < localRuns[j].ID
}
- return runs[i].CreatedAt.After(runs[j].CreatedAt)
+ return localRuns[i].CreatedAt.After(localRuns[j].CreatedAt)
})
page = max(page, 1)
limit = min(max(limit, 1), 100)
- start := len(runs)
- if page-1 <= len(runs)/limit {
- start = min((page-1)*limit, len(runs))
+ start := len(localRuns)
+ if page-1 <= len(localRuns)/limit {
+ start = min((page-1)*limit, len(localRuns))
}
- return st.RunList{Runs: runs[start:min(start+limit, len(runs))], Total: len(runs), Page: page, Limit: limit}, nil
+ return st.RunList{Runs: localRuns[start:min(start+limit, len(localRuns))], Total: len(localRuns), Page: page, Limit: limit}, nil
}
func (s *JobService) remoteHistoryInternal(ctx context.Context, environmentID, jobID string) (map[string]st.Run, error) {
- runs := make(map[string]st.Run)
+ localRuns := make(map[string]st.Run)
for page := 1; ; page++ {
path := "/api/environments/0/jobs/" + url.PathEscape(jobID) + "/runs?page=" + strconv.Itoa(page) + "&limit=100"
var response st.RunList
if err := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &response); err != nil {
return nil, err
}
- previous := len(runs)
+ previous := len(localRuns)
for _, run := range response.Runs {
run.EnvironmentID = environmentID
if run.ActivityID != "" {
run.ActivityEnvironmentID = environmentID
}
- runs[run.ID] = run
+ localRuns[run.ID] = run
}
- if len(runs) >= response.Total || len(runs) == previous {
- return runs, nil
+ if len(localRuns) >= response.Total || len(localRuns) == previous {
+ return localRuns, nil
}
}
}
@@ -90,8 +90,8 @@ func (s *JobService) GetRun(ctx context.Context, environmentID, jobID, runID str
return projectRunOutcomeInternal(run), err
}
path := "/api/environments/0/jobs/" + url.PathEscape(jobID) + "/runs/" + url.PathEscape(runID)
- if err := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &run); err != nil {
- return st.Run{}, err
+ if proxyJSONRequestErr := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &run); proxyJSONRequestErr != nil {
+ return st.Run{}, proxyJSONRequestErr
}
if run.ID != runID || run.JobID != jobID {
return st.Run{}, errors.New("agent returned an inconsistent run identity")
@@ -126,8 +126,8 @@ func (s *JobService) mutateAgentRunInternal(ctx context.Context, environmentID,
path := "/api/environments/0/jobs/" + url.PathEscape(jobID) + "/runs/" + url.PathEscape(runID) + "/" + action
var run st.Run
// This is an explicit operator action. Never replay a lost mutation response.
- if err := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodPost, path, nil, &run); err != nil {
- return st.Run{}, err
+ if proxyJSONRequestErr := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodPost, path, nil, &run); proxyJSONRequestErr != nil {
+ return st.Run{}, proxyJSONRequestErr
}
if run.ID != runID || run.JobID != jobID {
return st.Run{}, errors.New("agent returned an inconsistent run identity")
diff --git a/backend/internal/job/remote_resolution.go b/backend/internal/job/remote_resolution.go
index 6bea81000..7a57fef81 100644
--- a/backend/internal/job/remote_resolution.go
+++ b/backend/internal/job/remote_resolution.go
@@ -72,7 +72,7 @@ func (s *JobService) resolveRemoteRunInternal(ctx context.Context, environmentID
return acknowledged, nil
}
now := time.Now().UTC()
- if err := s.runs.UpdateRun(ctx, local, func(current *st.Run) error {
+ if updateRunErr := s.runs.UpdateRun(ctx, local, func(current *st.Run) error {
if current.Status != st.NeedsAttention {
return runs.ErrRunConflict
}
@@ -83,8 +83,8 @@ func (s *JobService) resolveRemoteRunInternal(ctx context.Context, environmentID
current.RemoteSettled = true
current.LastConfirmedAt = &now
return nil
- }); err != nil {
- return st.Run{}, err
+ }); updateRunErr != nil {
+ return st.Run{}, updateRunErr
}
return s.runs.Resolve(ctx, environmentID, jobID, runID, acknowledged.Resolution.ResolvedBy)
}
@@ -102,19 +102,19 @@ func (s *JobService) resolveAgentReviewInternal(ctx context.Context, environment
path := "/api/environments/0/jobs/" + url.PathEscape(jobID) + "/runs/" + url.PathEscape(runID)
var remote st.Run
// Read the owner on every request, including retries after a lost response.
- if err := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &remote); err != nil {
- return st.Run{}, err
+ if proxyJSONRequestErr := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodGet, path, nil, &remote); proxyJSONRequestErr != nil {
+ return st.Run{}, proxyJSONRequestErr
}
if remote.ID != runID || remote.JobID != jobID || remote.EnvironmentID != "0" {
return st.Run{}, errors.New("agent returned an inconsistent run identity")
}
if remote.Status == st.NeedsAttention {
- body, err := json.Marshal(map[string]string{"resolvedBy": actor})
- if err != nil {
- return st.Run{}, err
+ body, marshalErr := json.Marshal(map[string]string{"resolvedBy": actor})
+ if marshalErr != nil {
+ return st.Run{}, marshalErr
}
- if err := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodPost, path+"/resolve", body, &remote); err != nil {
- return st.Run{}, err
+ if resolveRemoteJobErr := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodPost, path+"/resolve", body, &remote); resolveRemoteJobErr != nil {
+ return st.Run{}, resolveRemoteJobErr
}
} else if actor != common.SystemUser.Username {
if remote.Status != st.Canceled || remote.Resolution == nil {
@@ -126,8 +126,8 @@ func (s *JobService) resolveAgentReviewInternal(ctx context.Context, environment
return st.Run{}, errors.New("agent resolution was not confirmed")
}
var acknowledged st.Run
- if err := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodPost, path+"/ack", nil, &acknowledged); err != nil {
- return st.Run{}, err
+ if acknowledgeRemoteResolutionErr := s.environment.ProxyJSONRequest(ctx, environmentID, http.MethodPost, path+"/ack", nil, &acknowledged); acknowledgeRemoteResolutionErr != nil {
+ return st.Run{}, acknowledgeRemoteResolutionErr
}
if acknowledged.ID != runID || acknowledged.JobID != jobID || acknowledged.EnvironmentID != "0" || acknowledged.Status != remote.Status || !acknowledged.RemoteSettled ||
(remote.Resolution != nil && (acknowledged.Resolution == nil || acknowledged.Resolution.ResolvedBy != remote.Resolution.ResolvedBy)) {
diff --git a/backend/internal/job/remote_resolution_test.go b/backend/internal/job/remote_resolution_test.go
index d576eaeef..7b5231072 100644
--- a/backend/internal/job/remote_resolution_test.go
+++ b/backend/internal/job/remote_resolution_test.go
@@ -42,7 +42,20 @@ func TestResolveRemoteRunConfirmsOwnerAfterLostResponse(t *testing.T) {
run.Outcome = st.Outcome{Status: st.NeedsAttention, Message: "original failure"}
return nil
}))
- remote := st.Run{ID: local.ID, JobID: local.JobID, EnvironmentID: "0", Status: st.Running, Outcome: st.Outcome{Status: st.NeedsAttention, Message: "original failure", Targets: []st.TargetOutcome{{ID: "completed", Status: st.Succeeded}}}}
+ remote := st.Run{
+ ID: local.ID,
+ JobID: local.JobID,
+ EnvironmentID: "0",
+ Status: st.Running,
+ Outcome: st.Outcome{
+ Status: st.NeedsAttention,
+ Message: "original failure",
+ Targets: []st.TargetOutcome{{
+ ID: "completed",
+ Status: st.Succeeded,
+ }},
+ },
+ }
mutations, acknowledgements := 0, 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
diff --git a/backend/internal/job/run_routes.go b/backend/internal/job/run_routes.go
index dee537a93..8e1f496f4 100644
--- a/backend/internal/job/run_routes.go
+++ b/backend/internal/job/run_routes.go
@@ -18,13 +18,92 @@ import (
func (h *JobSchedulesHandler) registerRunRoutesInternal(api huma.API) {
base := "/environments/{id}/jobs/{jobId}"
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-job-runs", Method: http.MethodGet, Path: base + "/runs", Summary: "List job runs", Security: handlerutil.DefaultOperationSecurity()}, authz.PermJobsManage, h.ListRuns)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-job-run", Method: http.MethodGet, Path: base + "/runs/{runId}", Summary: "Get job run", Security: handlerutil.DefaultOperationSecurity()}, authz.PermJobsManage, h.GetRun)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "retry-job-run", Method: http.MethodPost, Path: base + "/runs/{runId}/retry", Summary: "Retry job run", Security: handlerutil.DefaultOperationSecurity()}, authz.PermJobsManage, h.RetryRun)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "cancel-job-run", Method: http.MethodPost, Path: base + "/runs/{runId}/cancel", Summary: "Cancel pending job run", Security: handlerutil.DefaultOperationSecurity()}, authz.PermJobsManage, h.CancelRun)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "resolve-job-run", Method: http.MethodPost, Path: base + "/runs/{runId}/resolve", Summary: "Resolve legacy job run", Description: "Deprecated compatibility endpoint for mixed-version upgrades. Removed in v3.", Deprecated: true, Security: handlerutil.DefaultOperationSecurity()}, authz.PermJobsManage, h.ResolveRun)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "ack-job-run", Method: http.MethodPost, Path: base + "/runs/{runId}/ack", Summary: "Acknowledge remote run completion", Security: handlerutil.DefaultOperationSecurity()}, authz.PermJobsManage, h.AcknowledgeRun)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "restart-job-worker", Method: http.MethodPost, Path: base + "/restart", Summary: "Restart continuous job worker", Security: handlerutil.DefaultOperationSecurity()}, authz.PermJobsManage, h.RestartWorker)
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-job-runs",
+ Method: http.MethodGet,
+ Path: base + "/runs",
+ Summary: "List job runs",
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermJobsManage,
+ h.ListRuns,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-job-run",
+ Method: http.MethodGet,
+ Path: base + "/runs/{runId}",
+ Summary: "Get job run",
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermJobsManage,
+ h.GetRun,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "retry-job-run",
+ Method: http.MethodPost,
+ Path: base + "/runs/{runId}/retry",
+ Summary: "Retry job run",
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermJobsManage,
+ h.RetryRun,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "cancel-job-run",
+ Method: http.MethodPost,
+ Path: base + "/runs/{runId}/cancel",
+ Summary: "Cancel pending job run",
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermJobsManage,
+ h.CancelRun,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "resolve-job-run",
+ Method: http.MethodPost,
+ Path: base + "/runs/{runId}/resolve",
+ Summary: "Resolve legacy job run",
+ Description: "Deprecated compatibility endpoint for mixed-version upgrades. Removed in v3.",
+ Deprecated: true,
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermJobsManage,
+ h.ResolveRun,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "ack-job-run",
+ Method: http.MethodPost,
+ Path: base + "/runs/{runId}/ack",
+ Summary: "Acknowledge remote run completion",
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermJobsManage,
+ h.AcknowledgeRun,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "restart-job-worker",
+ Method: http.MethodPost,
+ Path: base + "/restart",
+ Summary: "Restart continuous job worker",
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermJobsManage,
+ h.RestartWorker,
+ )
}
// ListRuns returns paginated history for the requested job and environment.
@@ -139,9 +218,9 @@ func (s *JobService) RetryRun(ctx context.Context, environmentID, jobID, runID s
}
if s.scheduler != nil {
if job, ok := s.scheduler.GetJob(jobID); ok {
- if validator, ok := job.(st.RetryValidator); ok {
- if err := validator.ValidateRetry(ctx, run); err != nil {
- return run, err
+ if validator, localOk := job.(st.RetryValidator); localOk {
+ if validateRetryErr := validator.ValidateRetry(ctx, run); validateRetryErr != nil {
+ return run, validateRetryErr
}
}
}
diff --git a/backend/internal/job/service.go b/backend/internal/job/service.go
index e5f629759..5b7ae22cd 100644
--- a/backend/internal/job/service.go
+++ b/backend/internal/job/service.go
@@ -57,22 +57,30 @@ type JobService struct {
RunEnvironmentHealthNow func(ctx context.Context) error
}
-func NewJobService(db *database.DB, settings *settings.SettingsService, cfg *config.Config, coordinator *runs.Coordinator, roles *role.RoleService, environment *environment.EnvironmentService, activity *activity.ActivityService) *JobService {
+func NewJobService(
+ db *database.DB,
+ localSettings *settings.SettingsService,
+ cfg *config.Config,
+ coordinator *runs.Coordinator,
+ roles *role.RoleService,
+ localEnvironment *environment.EnvironmentService,
+ localActivity *activity.ActivityService,
+) *JobService {
service := &JobService{
roles: roles,
- environment: environment,
- activity: activity,
+ environment: localEnvironment,
+ activity: localActivity,
store: kv.NewKVService(db),
runs: coordinator,
db: db,
- settings: settings,
+ settings: localSettings,
cfg: cfg,
location: cfg.GetLocation(),
}
if coordinator != nil {
coordinator.SetExecutor(service.executeRunInternal, service.reconcileRunInternal)
- if activity != nil {
+ if localActivity != nil {
coordinator.SetObserver(service)
}
}
@@ -81,7 +89,7 @@ func NewJobService(db *database.DB, settings *settings.SettingsService, cfg *con
func (s *JobService) SetScheduler(ctx context.Context, scheduler schedulertypes.JobController) { //nolint:contextcheck // scheduler jobs must capture the app lifecycle context, not request contexts
if ctx == nil {
- ctx = context.Background()
+ ctx = context.Background() //nolint:forbidigo // A nil scheduler context uses an independent lifecycle root.
}
s.lifecycleCtx = ctx
s.scheduler = scheduler
@@ -335,44 +343,44 @@ func (s *JobService) ListJobs(ctx context.Context) (*jobschedule.JobListResponse
}, nil
}
-func (s *JobService) getJobScheduleInternal(ctx context.Context, meta meta.JobMetadata) string {
+func (s *JobService) getJobScheduleInternal(ctx context.Context, localMeta meta.JobMetadata) string {
// Continuous jobs with a settings key (image-polling) are event-driven but
// also poll on that cron schedule, so surface the real expression.
- if meta.IsContinuous && meta.SettingsKey == "" {
+ if localMeta.IsContinuous && localMeta.SettingsKey == "" {
return "continuous"
}
- if meta.ID == "analytics-heartbeat" {
+ if localMeta.ID == "analytics-heartbeat" {
return "automatic (checked hourly; sent once per 24h)"
}
- if meta.SettingsKey == "" {
+ if localMeta.SettingsKey == "" {
return ""
}
- defaultSchedule, _, _, err := settings.DefaultSettingsConfig().FieldByKey(meta.SettingsKey)
+ defaultSchedule, _, _, err := settings.DefaultSettingsConfig().FieldByKey(localMeta.SettingsKey)
if err != nil || defaultSchedule == "" {
defaultSchedule = "0 0 0 * * *"
}
- return s.settings.GetStringSetting(ctx, meta.SettingsKey, defaultSchedule)
+ return s.settings.GetStringSetting(ctx, localMeta.SettingsKey, defaultSchedule)
}
-func (s *JobService) isJobEnabledInternal(ctx context.Context, meta meta.JobMetadata) bool {
- if meta.EnabledKey != "" {
- return s.settings.GetBoolSetting(ctx, meta.EnabledKey, false)
+func (s *JobService) isJobEnabledInternal(ctx context.Context, localMeta meta.JobMetadata) bool {
+ if localMeta.EnabledKey != "" {
+ return s.settings.GetBoolSetting(ctx, localMeta.EnabledKey, false)
}
- if meta.IsContinuous {
+ if localMeta.IsContinuous {
return true
}
return true
}
-func (s *JobService) evaluatePrerequisitesInternal(ctx context.Context, meta meta.JobMetadata) []jobschedule.JobPrerequisite {
- prerequisites := make([]jobschedule.JobPrerequisite, 0, len(meta.Prerequisites))
+func (s *JobService) evaluatePrerequisitesInternal(ctx context.Context, localMeta meta.JobMetadata) []jobschedule.JobPrerequisite {
+ prerequisites := make([]jobschedule.JobPrerequisite, 0, len(localMeta.Prerequisites))
- for _, prereq := range meta.Prerequisites {
+ for _, prereq := range localMeta.Prerequisites {
isMet := s.settings.GetBoolSetting(ctx, prereq.SettingKey, false)
prerequisites = append(prerequisites, jobschedule.JobPrerequisite{
diff --git a/backend/internal/job/service_test.go b/backend/internal/job/service_test.go
index af21e7e52..a03f400c6 100644
--- a/backend/internal/job/service_test.go
+++ b/backend/internal/job/service_test.go
@@ -63,7 +63,7 @@ func newJobServiceForTestInternal(t *testing.T, db *database.DB, settingsService
}
func TestJobService_GetJobSchedules_DefaultDockerClientRefreshInterval(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -77,7 +77,7 @@ func TestJobService_GetJobSchedules_DefaultDockerClientRefreshInterval(t *testin
}
func TestJobService_ListJobs_AnalyticsHeartbeatIsManagedInternally(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -96,7 +96,7 @@ func TestJobService_ListJobs_AnalyticsHeartbeatIsManagedInternally(t *testing.T)
}
func TestJobService_ListJobs_IncludesDisabledAutoHealJob(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -113,7 +113,7 @@ func TestJobService_ListJobs_IncludesDisabledAutoHealJob(t *testing.T) {
}
func TestJobService_ListJobs_IncludesDockerClientRefreshJob(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -132,7 +132,7 @@ func TestJobService_ListJobs_IncludesDockerClientRefreshJob(t *testing.T) {
}
func TestJobService_ListJobs_UsesRuntimeScheduleAndNextRun(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -160,7 +160,14 @@ func TestJobService_ListJobs_UsesRuntimeScheduleAndNextRun(t *testing.T) {
ID: "failed", EnvironmentID: "0", Status: schedulertypes.Failed, CreatedAt: now.Add(-time.Hour), UpdatedAt: now,
Outcome: schedulertypes.Outcome{Status: schedulertypes.Failed, Message: "clone failed"},
}
- succeeded := schedulertypes.Run{ID: "succeeded", EnvironmentID: "0", Status: schedulertypes.Succeeded, CreatedAt: now.Add(-time.Minute), UpdatedAt: now.Add(-time.Minute), FinishedAt: new(now.Add(-time.Minute))}
+ succeeded := schedulertypes.Run{
+ ID: "succeeded",
+ EnvironmentID: "0",
+ Status: schedulertypes.Succeeded,
+ CreatedAt: now.Add(-time.Minute),
+ UpdatedAt: now.Add(-time.Minute),
+ FinishedAt: new(now.Add(-time.Minute)),
+ }
for _, history := range [][]schedulertypes.Run{{failed, succeeded}, {succeeded, failed}} {
status := jobschedule.JobStatus{LastRun: new(failed), LastError: failed.Outcome.Message}
applyRunStatusInternal(&status, history)
@@ -227,7 +234,7 @@ func TestJobService_ListJobs_UsesRuntimeScheduleAndNextRun(t *testing.T) {
}
func TestJobService_ListJobs_ImageUpdateWatcherIsContinuousAndRespectsEnabled(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -249,7 +256,7 @@ func TestJobService_ListJobs_ImageUpdateWatcherIsContinuousAndRespectsEnabled(t
}
func TestJobService_UpdateJobSchedules_ReschedulesChangedJob(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -268,7 +275,7 @@ func TestJobService_UpdateJobSchedules_ReschedulesChangedJob(t *testing.T) {
}
func TestJobService_UpdateJobSchedules_DeprecatedPollingIntervalDoesNotReschedule(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -287,15 +294,15 @@ func TestJobService_UpdateJobSchedules_DeprecatedPollingIntervalDoesNotReschedul
}
func TestJobService_UpdateJobSchedules_UsesLifecycleContextForReschedule(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
type lifecycleContextKey struct{}
- lifecycleCtx := context.WithValue(context.Background(), lifecycleContextKey{}, true)
- requestCtx, cancelRequest := context.WithCancel(context.Background())
+ lifecycleCtx := context.WithValue(t.Context(), lifecycleContextKey{}, true)
+ requestCtx, cancelRequest := context.WithCancel(t.Context())
jobSvc := newJobServiceForTestInternal(t, db, settingsSvc, &config.Config{})
scheduler := newFakeJobSchedulerInternal("auto-update")
@@ -314,7 +321,7 @@ func TestJobService_UpdateJobSchedules_UsesLifecycleContextForReschedule(t *test
}
func TestJobService_UpdateJobSchedules_RejectsInvalidCronWithoutChangingSetting(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -335,7 +342,7 @@ func TestJobService_UpdateJobSchedules_RejectsInvalidCronWithoutChangingSetting(
}
func TestJobService_UpdateJobSchedules_UnchangedScheduleDoesNotReschedule(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -350,7 +357,7 @@ func TestJobService_UpdateJobSchedules_UnchangedScheduleDoesNotReschedule(t *tes
}
func TestJobService_UpdateJobSchedules_RestoresPreviousScheduleWhenRescheduleFails(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -375,7 +382,7 @@ func TestJobService_UpdateJobSchedules_RestoresPreviousScheduleWhenRescheduleFai
}
func TestJobService_UpdateJobSchedules_SkipsManagerOnlyJobsInAgentMode(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -394,7 +401,7 @@ func TestJobService_UpdateJobSchedules_SkipsManagerOnlyJobsInAgentMode(t *testin
}
func TestJobService_UpdateJobSchedules_DelegatesEnvironmentHealthReschedule(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDBInternal(t)
settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, db)
diff --git a/backend/internal/kv/prefix_test.go b/backend/internal/kv/prefix_test.go
index 5072101ad..c4e400ea9 100644
--- a/backend/internal/kv/prefix_test.go
+++ b/backend/internal/kv/prefix_test.go
@@ -1,14 +1,13 @@
package kv
import (
- "context"
"testing"
"github.com/stretchr/testify/require"
)
func TestKVService_ListByPrefix_EscapesLikeWildcards(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc := setupKVServiceInternal(t)
entries := map[string]string{
diff --git a/backend/internal/kv/service_test.go b/backend/internal/kv/service_test.go
index e5f5db356..fd2533280 100644
--- a/backend/internal/kv/service_test.go
+++ b/backend/internal/kv/service_test.go
@@ -1,7 +1,6 @@
package kv
import (
- "context"
"testing"
"github.com/libtnb/sqlite"
@@ -22,7 +21,7 @@ func setupKVServiceInternal(t *testing.T) *KVService {
}
func TestKVService_Get_MissingKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc := setupKVServiceInternal(t)
value, ok, err := svc.Get(ctx, "missing")
@@ -32,7 +31,7 @@ func TestKVService_Get_MissingKey(t *testing.T) {
}
func TestKVService_Set_UpsertsValue(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc := setupKVServiceInternal(t)
require.NoError(t, svc.Set(ctx, "analytics.heartbeat.last_attempt_at", "2026-03-10T00:00:00Z"))
diff --git a/backend/internal/middleware/csrf_middleware_test.go b/backend/internal/middleware/csrf_middleware_test.go
index 48ec61094..fe2268e94 100644
--- a/backend/internal/middleware/csrf_middleware_test.go
+++ b/backend/internal/middleware/csrf_middleware_test.go
@@ -22,7 +22,7 @@ func newCSRFTestRouterInternal() *echo.Echo {
func TestCSRF_BlocksCrossSiteStateChange(t *testing.T) {
router := newCSRFTestRouterInternal()
- req := httptest.NewRequest(http.MethodPost, "/api/test", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/test", http.NoBody)
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Origin", "https://evil.example.com")
rec := httptest.NewRecorder()
@@ -32,7 +32,7 @@ func TestCSRF_BlocksCrossSiteStateChange(t *testing.T) {
func TestCSRF_AllowsSameOrigin(t *testing.T) {
router := newCSRFTestRouterInternal()
- req := httptest.NewRequest(http.MethodPost, "/api/test", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/test", http.NoBody)
req.Header.Set("Sec-Fetch-Site", "same-origin")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -43,7 +43,7 @@ func TestCSRF_AllowsSameOrigin(t *testing.T) {
// Sec-Fetch-Site header and must not be blocked.
func TestCSRF_AllowsNonBrowserClient(t *testing.T) {
router := newCSRFTestRouterInternal()
- req := httptest.NewRequest(http.MethodPost, "/api/test", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/test", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code)
@@ -53,7 +53,7 @@ func TestCSRF_AllowsNonBrowserClient(t *testing.T) {
// cross-site Origin must not block such a request.
func TestCSRF_SkipsHeaderCredentialedRequests(t *testing.T) {
router := newCSRFTestRouterInternal()
- req := httptest.NewRequest(http.MethodPost, "/api/test", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/test", http.NoBody)
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Origin", "https://evil.example.com")
req.Header.Set("X-Api-Key", "some-key")
@@ -66,7 +66,7 @@ func TestCSRF_SkipsHeaderCredentialedRequests(t *testing.T) {
// and may receive an Origin header from an external caller; it must be bypassed.
func TestCSRF_AllowsPublicBypassPaths(t *testing.T) {
router := newCSRFTestRouterInternal()
- req := httptest.NewRequest(http.MethodPost, "/api/webhooks/trigger/abc", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/webhooks/trigger/abc", http.NoBody)
req.Header.Set("Sec-Fetch-Site", "cross-site")
req.Header.Set("Origin", "https://ci.example.com")
rec := httptest.NewRecorder()
diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.go
index 9aa7cb285..cd3a94fcb 100644
--- a/backend/internal/middleware/environment_middleware.go
+++ b/backend/internal/middleware/environment_middleware.go
@@ -176,13 +176,13 @@ func (m *EnvironmentMiddleware) Handle(c *echo.Context, next echo.HandlerFunc) e
isEdgeEnvironment := isEdgeEnvironmentURLInternal(apiURL)
- if handled, err := m.proxyActiveEdgeTunnelInternal(c, envID, accessToken); handled {
- return err
+ if handled, proxyActiveEdgeTunnelErr := m.proxyActiveEdgeTunnelInternal(c, envID, accessToken); handled {
+ return proxyActiveEdgeTunnelErr
}
if isEdgeEnvironment {
- if handled, err := m.proxyRecoveredEdgeTunnelInternal(c, envID, accessToken); handled {
- return err
+ if handled, proxyRecoveredEdgeTunnelErr := m.proxyRecoveredEdgeTunnelInternal(c, envID, accessToken); handled {
+ return proxyRecoveredEdgeTunnelErr
}
slog.WarnContext(c.Request().Context(), "No active edge tunnel for environment", "environment_id", envID)
@@ -379,8 +379,8 @@ func proxiedVolumeWorkspacePermissionsInternal(request *http.Request) ([]string,
return nil, errors.New("workspace manifest is too large")
}
var manifest volumetypes.WorkspaceUpdateManifest
- if err := json.Unmarshal(manifestJSON, &manifest); err != nil {
- return nil, fmt.Errorf("decode workspace manifest: %w", err)
+ if unmarshalErr := json.Unmarshal(manifestJSON, &manifest); unmarshalErr != nil {
+ return nil, fmt.Errorf("decode workspace manifest: %w", unmarshalErr)
}
required, valid := authz.VolumeWorkspaceRequiredPermissions(manifest.FileChanges)
if !valid {
diff --git a/backend/internal/middleware/environment_middleware_authz_test.go b/backend/internal/middleware/environment_middleware_authz_test.go
index f333cd43d..406470a37 100644
--- a/backend/internal/middleware/environment_middleware_authz_test.go
+++ b/backend/internal/middleware/environment_middleware_authz_test.go
@@ -24,7 +24,7 @@ func newProxyAuthzMiddleware(matcher *authz.PermissionMatcher) *EnvironmentMiddl
func newProxyRequestContext(method, path string) *echo.Context {
e := echo.New()
- req := httptest.NewRequest(method, path, nil)
+ req := httptest.NewRequest(method, path, http.NoBody)
return e.NewContext(req, httptest.NewRecorder())
}
diff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.go
index 5c329d552..f8738c935 100644
--- a/backend/internal/middleware/environment_middleware_test.go
+++ b/backend/internal/middleware/environment_middleware_test.go
@@ -54,7 +54,7 @@ func TestEnvironmentMiddleware_ReturnsBadGatewayForEdgeResourcesWithoutTunnel(t
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -75,7 +75,7 @@ func TestEnvironmentMiddleware_ProxiesDashboardResourcesForRemoteEnvironments(t
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/dashboard", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/dashboard", http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -96,7 +96,7 @@ func TestEnvironmentMiddleware_KeepsEdgeManagementEndpointsLocal(t *testing.T) {
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/settings", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/settings", http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -117,7 +117,7 @@ func TestEnvironmentMiddleware_KeepsEdgeMTLSDownloadEndpointsLocal(t *testing.T)
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/deployment/mtls/bundle", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/deployment/mtls/bundle", http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -138,7 +138,7 @@ func TestEnvironmentMiddleware_KeepsNotificationEndpointsLocal(t *testing.T) {
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/notifications/settings", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/notifications/settings", http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -181,7 +181,7 @@ func TestEnvironmentMiddleware_KeepsWebhookEndpointsLocal(t *testing.T) {
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(tt.method, tt.path, nil)
+ req := httptest.NewRequest(tt.method, tt.path, http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -220,7 +220,7 @@ func TestEnvironmentMiddleware_KeepsActivityEndpointsLocal(t *testing.T) {
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(tt.method, tt.path, nil)
+ req := httptest.NewRequest(tt.method, tt.path, http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -264,7 +264,7 @@ func TestEnvironmentMiddleware_LocalEnvironmentSkipsProxyPermissionCheck(t *test
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/0/containers", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/0/containers", http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -276,7 +276,7 @@ func TestEnvironmentMiddleware_ProxyWebSocketRejectsEdgeTargetsWithoutTunnel(t *
middleware := newTestEnvironmentMiddleware()
e := echo.New()
recorder := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/ws/system/stats", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/ws/system/stats", http.NoBody)
c := e.NewContext(req, recorder)
_ = middleware.proxyWebSocket(c, "edge://oracle-1/api/environments/0/ws/system/stats", nil, "env-edge")
@@ -289,7 +289,7 @@ func TestEnvironmentMiddleware_ProxyHTTPRejectsEdgeTargetsWithoutTunnel(t *testi
middleware := newTestEnvironmentMiddleware()
e := echo.New()
recorder := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", http.NoBody)
c := e.NewContext(req, recorder)
_ = middleware.proxyHTTP(c, "edge://oracle-1/api/environments/0/containers", nil)
@@ -302,7 +302,7 @@ func TestEnvironmentMiddleware_CreateProxyRequest_RejectsInvalidProxyTarget(t *t
middleware := newTestEnvironmentMiddleware()
e := echo.New()
recorder := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/env-edge/containers", http.NoBody)
c := e.NewContext(req, recorder)
_, err := middleware.createProxyRequest(c, "ftp://example.com/containers", nil)
@@ -321,7 +321,7 @@ func TestEnvironmentMiddleware_KeepsNodeAgentDeploymentCreationLocal(t *testing.
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodPost, "/api/environments/env-edge/swarm/nodes/node-1/agent/deployment", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-edge/swarm/nodes/node-1/agent/deployment", http.NoBody)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
@@ -382,7 +382,7 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing.
return c.JSON(http.StatusOK, map[string]any{"success": true})
})
- req := httptest.NewRequest(http.MethodPost, "/api/environments/env-remote/containers/container-1/update", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-remote/containers/container-1/update", http.NoBody)
req.Header.Set(HeaderUpdateInitiatorID, "spoofed")
req.Header.Set(HeaderUpdateInitiatorName, "spoofed")
if tt.clientSupplied != "" {
diff --git a/backend/internal/middleware/rate_limit_middleware_test.go b/backend/internal/middleware/rate_limit_middleware_test.go
index 75c0f1137..4545d59c7 100644
--- a/backend/internal/middleware/rate_limit_middleware_test.go
+++ b/backend/internal/middleware/rate_limit_middleware_test.go
@@ -19,7 +19,7 @@ func TestPerIPRateLimit_AllowsUnderBurstAndBlocksOver(t *testing.T) {
}, PerIPRateLimit(60, 2))
doReq := func() int {
- req := httptest.NewRequest(http.MethodPost, "/t", nil)
+ req := httptest.NewRequest(http.MethodPost, "/t", http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -38,7 +38,7 @@ func TestPerIPRateLimit_TracksDistinctClients(t *testing.T) {
}, PerIPRateLimit(60, 1))
doReqFrom := func(addr string) int {
- req := httptest.NewRequest(http.MethodPost, "/t", nil)
+ req := httptest.NewRequest(http.MethodPost, "/t", http.NoBody)
req.RemoteAddr = addr
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -57,7 +57,7 @@ func TestStackedAgentEnrollmentRateLimits_KeepIPBackPressure(t *testing.T) {
}, PerIPRateLimit(60, 1), PerAgentTokenRateLimit(60, 10))
doReq := func(token string) int {
- req := httptest.NewRequest(http.MethodPost, "/t", nil)
+ req := httptest.NewRequest(http.MethodPost, "/t", http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
req.Header.Set("X-Arcane-Agent-Token", token)
rec := httptest.NewRecorder()
@@ -82,7 +82,7 @@ func TestPerIPRateLimitForPaths_AppliesOnlyToConfiguredPaths(t *testing.T) {
})
doReq := func(path string) int {
- req := httptest.NewRequest(http.MethodPost, path, nil)
+ req := httptest.NewRequest(http.MethodPost, path, http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -107,7 +107,7 @@ func TestPerIPRateLimitForPaths_TracksDistinctIPs(t *testing.T) {
})
doReqFrom := func(addr string) int {
- req := httptest.NewRequest(http.MethodPost, "/limited", nil)
+ req := httptest.NewRequest(http.MethodPost, "/limited", http.NoBody)
req.RemoteAddr = addr
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -128,7 +128,7 @@ func TestPerIPRateLimitForPaths_IndependentBucketPerPath(t *testing.T) {
router.POST("/b", func(c *echo.Context) error { return c.NoContent(http.StatusOK) })
doReq := func(path string) int {
- req := httptest.NewRequest(http.MethodPost, path, nil)
+ req := httptest.NewRequest(http.MethodPost, path, http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -152,7 +152,7 @@ func TestPerIPRateLimitForPaths_RouteParamsDoNotEscapeFilter(t *testing.T) {
})
doReq := func(token string) int {
- req := httptest.NewRequest(http.MethodPost, "/webhooks/trigger/"+token, nil)
+ req := httptest.NewRequest(http.MethodPost, "/webhooks/trigger/"+token, http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -179,7 +179,7 @@ func newTokenRateLimitTestRouterInternal(
router.POST("/webhooks/trigger/:token", handler)
return func(token string) int {
- req := httptest.NewRequest(http.MethodPost, "/webhooks/trigger/"+token, nil)
+ req := httptest.NewRequest(http.MethodPost, "/webhooks/trigger/"+token, http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -282,7 +282,7 @@ func TestPerTokenRateLimitForPaths_AppliesOnlyToConfiguredPaths(t *testing.T) {
})
doReq := func(path string) int {
- req := httptest.NewRequest(http.MethodPost, path, nil)
+ req := httptest.NewRequest(http.MethodPost, path, http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
diff --git a/backend/internal/middleware/role_test.go b/backend/internal/middleware/role_test.go
index 1e6493751..46e06b5f4 100644
--- a/backend/internal/middleware/role_test.go
+++ b/backend/internal/middleware/role_test.go
@@ -39,7 +39,7 @@ func TestRequirePermission_RejectsCallerMissingPermission(t *testing.T) {
return nil, nil
})
- req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/containers/c/start", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/containers/c/start", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -79,7 +79,7 @@ func TestRequirePermission_AllowsCallerWithPermissionOnEnv(t *testing.T) {
}{Success: true}}, nil
})
- req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/containers/c/start", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/containers/c/start", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -112,7 +112,7 @@ func TestRequirePermission_EnvScopedDoesNotLeakAcrossEnvs(t *testing.T) {
return nil, nil
})
- req := httptest.NewRequest(http.MethodPost, "/api/environments/env-2/containers/c/start", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-2/containers/c/start", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -142,7 +142,7 @@ func TestRequirePermissionEnvironmentGrantCannotManageGlobalNotificationsInterna
return nil, nil
})
- req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/notifications/settings", nil)
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/notifications/settings", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -171,7 +171,7 @@ func TestRequirePermission_SudoCallerAllowed(t *testing.T) {
return &struct{}{}, nil
})
- req := httptest.NewRequest(http.MethodDelete, "/api/users/u-1", nil)
+ req := httptest.NewRequest(http.MethodDelete, "/api/users/u-1", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -216,7 +216,7 @@ func TestRequireSudoRejectsHumanAdminAndAllowsAgent(t *testing.T) {
return &struct{}{}, nil
})
- req := httptest.NewRequest(http.MethodGet, "/api/environments/0/templates/variables", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/environments/0/templates/variables", http.NoBody)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
diff --git a/backend/internal/network/handler.go b/backend/internal/network/handler.go
index 0308cd57b..d2b5b8905 100644
--- a/backend/internal/network/handler.go
+++ b/backend/internal/network/handler.go
@@ -319,8 +319,8 @@ func (h *NetworkHandler) GetNetwork(ctx context.Context, input *GetNetworkInput)
valA := cmp.Or(a.IPv4Address, a.IPv6Address)
valB := cmp.Or(b.IPv4Address, b.IPv6Address)
- cmp := kit.CompareAddresses(valA, valB)
- return kit.Ternary(input.Order == "desc", cmp > 0, cmp < 0)
+ localCmp := kit.CompareAddresses(valA, valB)
+ return kit.Ternary(input.Order == "desc", localCmp > 0, localCmp < 0)
}
// Default to Name
diff --git a/backend/internal/network/service.go b/backend/internal/network/service.go
index 70a0dc920..07f12869c 100644
--- a/backend/internal/network/service.go
+++ b/backend/internal/network/service.go
@@ -92,9 +92,9 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.
g.Go(func() (workerErr error) {
defer utils.RecoverToError(&workerErr, "network worker")
- inspected, err := compat.NetworkInspectWithCompatibility(groupCtx, dockerClient, rawNetwork.ID, client.NetworkInspectOptions{})
- if err != nil {
- return fmt.Errorf("failed to inspect network %s: %w", rawNetwork.Name, err)
+ inspected, networkInspectWithCompatibilityErr := compat.NetworkInspectWithCompatibility(groupCtx, dockerClient, rawNetwork.ID, client.NetworkInspectOptions{})
+ if networkInspectWithCompatibilityErr != nil {
+ return fmt.Errorf("failed to inspect network %s: %w", rawNetwork.Name, networkInspectWithCompatibilityErr)
}
inspectedNetworks[i] = struct {
@@ -108,8 +108,8 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.
})
}
- if err := g.Wait(); err != nil {
- return nil, err
+ if waitErr := g.Wait(); waitErr != nil {
+ return nil, waitErr
}
for _, inspectedNetwork := range inspectedNetworks {
@@ -223,9 +223,9 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user comm
networkName := kit.Ternary(err == nil, networkInfo.Network.Name, id)
defer s.eventService.BeginDockerResourceSuppressionWindow("network", id, networkName)()
- if _, err := dockerClient.NetworkRemove(ctx, id, client.NetworkRemoveOptions{}); err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", id, networkName, user.ID, user.Username, "0", err, database.JSON{"action": "delete"})
- return fmt.Errorf("failed to remove network: %w", err)
+ if _, networkRemoveErr := dockerClient.NetworkRemove(ctx, id, client.NetworkRemoveOptions{}); networkRemoveErr != nil {
+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", id, networkName, user.ID, user.Username, "0", networkRemoveErr, database.JSON{"action": "delete"})
+ return fmt.Errorf("failed to remove network: %w", networkRemoveErr)
}
metadata := database.JSON{
@@ -269,12 +269,26 @@ func (s *NetworkService) ConnectContainer(ctx context.Context, networkID string,
endpoint.IPAMConfig = ipam
}
- if _, err := dockerClient.NetworkConnect(ctx, networkID, client.NetworkConnectOptions{
+ if _, networkConnectErr := dockerClient.NetworkConnect(ctx, networkID, client.NetworkConnectOptions{
Container: req.ContainerID,
EndpointConfig: endpoint,
- }); err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "connect", "containerId": req.ContainerID})
- return fmt.Errorf("failed to connect container to network: %w", err)
+ }); networkConnectErr != nil {
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeNetworkError,
+ "network",
+ networkID,
+ "",
+ user.ID,
+ user.Username,
+ "0",
+ networkConnectErr,
+ database.JSON{
+ "action": "connect",
+ "containerId": req.ContainerID,
+ },
+ )
+ return fmt.Errorf("failed to connect container to network: %w", networkConnectErr)
}
metadata := database.JSON{
@@ -297,12 +311,26 @@ func (s *NetworkService) DisconnectContainer(ctx context.Context, networkID stri
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.NetworkDisconnect(ctx, networkID, client.NetworkDisconnectOptions{
+ if _, networkDisconnectErr := dockerClient.NetworkDisconnect(ctx, networkID, client.NetworkDisconnectOptions{
Container: req.ContainerID,
Force: req.Force,
- }); err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", networkID, "", user.ID, user.Username, "0", err, database.JSON{"action": "disconnect", "containerId": req.ContainerID})
- return fmt.Errorf("failed to disconnect container from network: %w", err)
+ }); networkDisconnectErr != nil {
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeNetworkError,
+ "network",
+ networkID,
+ "",
+ user.ID,
+ user.Username,
+ "0",
+ networkDisconnectErr,
+ database.JSON{
+ "action": "disconnect",
+ "containerId": req.ContainerID,
+ },
+ )
+ return fmt.Errorf("failed to disconnect container from network: %w", networkDisconnectErr)
}
metadata := database.JSON{
diff --git a/backend/internal/notification/email_templates.go b/backend/internal/notification/email_templates.go
index 494dd7721..e3be46845 100644
--- a/backend/internal/notification/email_templates.go
+++ b/backend/internal/notification/email_templates.go
@@ -160,8 +160,8 @@ func (s *NotificationService) renderTemplatesInternal(name string, data any, tex
}
var htmlBuf bytes.Buffer
- if err := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); err != nil {
- return "", "", fmt.Errorf("failed to execute HTML template: %w", err)
+ if executeTemplateErr := htmlTmpl.ExecuteTemplate(&htmlBuf, "root", data); executeTemplateErr != nil {
+ return "", "", fmt.Errorf("failed to execute HTML template: %w", executeTemplateErr)
}
textContent, err := resources.FS.ReadFile(fmt.Sprintf("email-templates/%s_text.tmpl", name))
@@ -179,9 +179,9 @@ func (s *NotificationService) renderTemplatesInternal(name string, data any, tex
return htmlBuf.String(), "", nil
}
var textBuf bytes.Buffer
- if err := textTmpl.ExecuteTemplate(&textBuf, "root", data); err != nil {
+ if executeTextTemplateErr := textTmpl.ExecuteTemplate(&textBuf, "root", data); executeTextTemplateErr != nil {
if textRequired {
- return "", "", fmt.Errorf("failed to execute text template: %w", err)
+ return "", "", fmt.Errorf("failed to execute text template: %w", executeTextTemplateErr)
}
return htmlBuf.String(), "", nil
}
diff --git a/backend/internal/notification/notification.go b/backend/internal/notification/notification.go
index 649c492fa..370b1748e 100644
--- a/backend/internal/notification/notification.go
+++ b/backend/internal/notification/notification.go
@@ -190,8 +190,8 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.
// AGENT_TOKEN configured for HTTP; ride the agent-to-manager event channel
// instead so their notifications are not silently lost (#3002).
if s.config == nil || strings.TrimSpace(httpx.ManagerBaseURL(s.config.ManagerApiUrl)) == "" || strings.TrimSpace(s.config.AgentToken) == "" {
- if err := publishViaTunnel(); err != nil {
- return notificationdto.DispatchResponse{}, fmt.Errorf("notification dispatch needs either MANAGER_API_URL + AGENT_TOKEN or a connected edge tunnel: %w", err)
+ if publishViaTunnelErr := publishViaTunnel(); publishViaTunnelErr != nil {
+ return notificationdto.DispatchResponse{}, fmt.Errorf("notification dispatch needs either MANAGER_API_URL + AGENT_TOKEN or a connected edge tunnel: %w", publishViaTunnelErr)
}
return notificationdto.DispatchResponse{Message: "notification dispatched via edge tunnel"}, nil
}
@@ -219,8 +219,8 @@ func (s *NotificationService) dispatchNotificationToManagerInternal(ctx context.
var apiResponse struct {
Data notificationdto.DispatchResponse `json:"data"`
}
- if err := json.UnmarshalRead(resp.Body, &apiResponse); err != nil {
- return notificationdto.DispatchResponse{}, fmt.Errorf("failed to decode manager notification dispatch response: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &apiResponse); unmarshalReadErr != nil {
+ return notificationdto.DispatchResponse{}, fmt.Errorf("failed to decode manager notification dispatch response: %w", unmarshalReadErr)
}
return apiResponse.Data, nil
}
@@ -274,7 +274,13 @@ func (s *NotificationService) dispatchForTargetInternal(ctx context.Context, tar
return notificationdto.DispatchResponse{}, errors.New("image update payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- dispatchResponse.Delivered, err = s.sendImageUpdateNotificationForTargetInternal(ctx, target, payload.ImageUpdate.ImageRef, &payload.ImageUpdate.UpdateInfo, notifications.NotificationEventImageUpdate)
+ dispatchResponse.Delivered, err = s.sendImageUpdateNotificationForTargetInternal(
+ ctx,
+ target,
+ payload.ImageUpdate.ImageRef,
+ &payload.ImageUpdate.UpdateInfo,
+ notifications.NotificationEventImageUpdate,
+ )
return dispatchResponse, err
case notificationdto.DispatchKindBatchImageUpdate:
if payload.BatchImageUpdate == nil {
@@ -288,7 +294,14 @@ func (s *NotificationService) dispatchForTargetInternal(ctx context.Context, tar
return notificationdto.DispatchResponse{}, errors.New("container update payload is required")
}
logManagerDispatchNotificationInternal(ctx, target, payload.Kind)
- return dispatchResponse, s.sendContainerUpdateNotificationForTargetInternal(ctx, target, payload.ContainerUpdate.ContainerName, payload.ContainerUpdate.ImageRef, payload.ContainerUpdate.OldDigest, payload.ContainerUpdate.NewDigest)
+ return dispatchResponse, s.sendContainerUpdateNotificationForTargetInternal(
+ ctx,
+ target,
+ payload.ContainerUpdate.ContainerName,
+ payload.ContainerUpdate.ImageRef,
+ payload.ContainerUpdate.OldDigest,
+ payload.ContainerUpdate.NewDigest,
+ )
case notificationdto.DispatchKindBatchContainerUpdate:
if payload.BatchContainerUpdate == nil {
return notificationdto.DispatchResponse{}, errors.New("batch container update payload is required")
@@ -351,9 +364,9 @@ func (s *NotificationService) GetSettingsByProvider(ctx context.Context, provide
return &setting, nil
}
-func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provider notifications.NotificationProvider, enabled bool, config database.JSON) (*NotificationSettings, error) {
+func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provider notifications.NotificationProvider, enabled bool, localConfig database.JSON) (*NotificationSettings, error) {
if provider == notifications.NotificationProviderGeneric {
- genericConfig, decodeErr := notifications.DecodeConfig[notifications.GenericConfig](config, "Generic")
+ genericConfig, decodeErr := notifications.DecodeConfig[notifications.GenericConfig](localConfig, "Generic")
if decodeErr != nil {
return nil, decodeErr
}
@@ -370,14 +383,14 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provid
err := s.db.WithContext(ctx).Where("provider = ?", provider).First(&setting).Error
existingConfig := kit.Ternary(err == nil, setting.Config, database.JSON(nil))
- encryptedConfig, encryptErr := encryptNotificationConfigCredentialsInternal(provider, config, existingConfig)
+ encryptedConfig, encryptErr := encryptNotificationConfigCredentialsInternal(provider, localConfig, existingConfig)
if encryptErr != nil {
return nil, encryptErr
}
- config = encryptedConfig
- if _, ok := config["events"]; !ok {
- if existingEvents, ok := existingConfig["events"]; ok {
- config["events"] = existingEvents
+ localConfig = encryptedConfig
+ if _, ok := localConfig["events"]; !ok {
+ if existingEvents, localOk := existingConfig["events"]; localOk {
+ localConfig["events"] = existingEvents
}
}
@@ -385,16 +398,16 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provid
setting = NotificationSettings{
Provider: provider,
Enabled: enabled,
- Config: config,
+ Config: localConfig,
}
- if err := s.db.WithContext(ctx).Create(&setting).Error; err != nil {
- return nil, fmt.Errorf("failed to create notification settings: %w", err)
+ if createSettingsErr := s.db.WithContext(ctx).Create(&setting).Error; createSettingsErr != nil {
+ return nil, fmt.Errorf("failed to create notification settings: %w", createSettingsErr)
}
} else {
setting.Enabled = enabled
- setting.Config = config
- if err := s.db.WithContext(ctx).Save(&setting).Error; err != nil {
- return nil, fmt.Errorf("failed to update notification settings: %w", err)
+ setting.Config = localConfig
+ if updateSettingsErr := s.db.WithContext(ctx).Save(&setting).Error; updateSettingsErr != nil {
+ return nil, fmt.Errorf("failed to update notification settings: %w", updateSettingsErr)
}
}
@@ -402,8 +415,8 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provid
}
// RedactNotificationConfigCredentials returns a copy of config with provider credential fields blanked for API responses.
-func RedactNotificationConfigCredentials(provider notifications.NotificationProvider, config database.JSON) database.JSON {
- redacted := cloneNotificationConfigInternal(config)
+func RedactNotificationConfigCredentials(provider notifications.NotificationProvider, localConfig database.JSON) database.JSON {
+ redacted := cloneNotificationConfigInternal(localConfig)
for _, field := range notificationCredentialFieldsByProviderInternal[provider] {
value, ok := redacted[field]
if !ok {
@@ -418,14 +431,14 @@ func RedactNotificationConfigCredentials(provider notifications.NotificationProv
return redacted
}
-func encryptNotificationConfigCredentialsInternal(provider notifications.NotificationProvider, config, existingConfig database.JSON) (database.JSON, error) {
- encryptedConfig := cloneNotificationConfigInternal(config)
+func encryptNotificationConfigCredentialsInternal(provider notifications.NotificationProvider, localConfig, existingConfig database.JSON) (database.JSON, error) {
+ encryptedConfig := cloneNotificationConfigInternal(localConfig)
preserveConfig := existingConfig
if provider == notifications.NotificationProviderSignal {
- preserveConfig = signalCredentialPreservationConfigInternal(config, existingConfig)
+ preserveConfig = signalCredentialPreservationConfigInternal(localConfig, existingConfig)
}
if provider == notifications.NotificationProviderEmail {
- preserveConfig = emailCredentialPreservationConfigInternal(config, existingConfig)
+ preserveConfig = emailCredentialPreservationConfigInternal(localConfig, existingConfig)
}
if targetField := notificationTargetFieldByProviderInternal[provider]; targetField != "" {
currentTarget, _ := existingConfig[targetField].(string)
@@ -475,11 +488,11 @@ func encryptNotificationConfigCredentialsInternal(provider notifications.Notific
return encryptedConfig, nil
}
-func signalCredentialPreservationConfigInternal(config, existingConfig database.JSON) database.JSON {
+func signalCredentialPreservationConfigInternal(localConfig, existingConfig database.JSON) database.JSON {
preserveConfig := cloneNotificationConfigInternal(existingConfig)
- user, _ := config["user"].(string)
- password, _ := config["password"].(string)
- token, _ := config["token"].(string)
+ user, _ := localConfig["user"].(string)
+ password, _ := localConfig["password"].(string)
+ token, _ := localConfig["token"].(string)
if strings.TrimSpace(token) != "" {
delete(preserveConfig, "password")
@@ -491,9 +504,9 @@ func signalCredentialPreservationConfigInternal(config, existingConfig database.
return preserveConfig
}
-func emailCredentialPreservationConfigInternal(config, existingConfig database.JSON) database.JSON {
+func emailCredentialPreservationConfigInternal(localConfig, existingConfig database.JSON) database.JSON {
preserveConfig := cloneNotificationConfigInternal(existingConfig)
- if authMode, _ := config["authMode"].(string); authMode == string(notifications.EmailAuthModeNone) {
+ if authMode, _ := localConfig["authMode"].(string); authMode == string(notifications.EmailAuthModeNone) {
delete(preserveConfig, "smtpPassword")
}
return preserveConfig
@@ -509,12 +522,12 @@ func encryptNotificationCredentialInternal(value string) (string, error) {
return crypto.Encrypt(value)
}
-func cloneNotificationConfigInternal(config database.JSON) database.JSON {
- if config == nil {
+func cloneNotificationConfigInternal(localConfig database.JSON) database.JSON {
+ if localConfig == nil {
return database.JSON{}
}
- cloned := make(database.JSON, len(config))
- maps.Copy(cloned, config)
+ cloned := make(database.JSON, len(localConfig))
+ maps.Copy(cloned, localConfig)
return cloned
}
@@ -525,8 +538,8 @@ func (s *NotificationService) DeleteSettings(ctx context.Context, provider notif
return nil
}
-func (s *NotificationService) isEventEnabled(config database.JSON, eventType notifications.NotificationEventType) bool {
- events, ok := config["events"].(map[string]any)
+func (s *NotificationService) isEventEnabled(localConfig database.JSON, eventType notifications.NotificationEventType) bool {
+ events, ok := localConfig["events"].(map[string]any)
if !ok {
return true // If no events config, default to enabled
}
@@ -541,7 +554,16 @@ func (s *NotificationService) isEventEnabled(config database.JSON, eventType not
// logNotificationInternal records a delivery attempt in the event log so sends and
// failures are visible alongside every other Arcane event.
-func (s *NotificationService) logNotificationInternal(ctx context.Context, environmentID string, provider notifications.NotificationProvider, subject, status string, errMsg *string, metadata database.JSON) {
+func (
+ s *NotificationService,
+) logNotificationInternal(
+ ctx context.Context,
+ environmentID string,
+ provider notifications.NotificationProvider,
+ subject, status string,
+ errMsg *string,
+ metadata database.JSON,
+) {
if s.eventSvc == nil {
return
}
@@ -628,8 +650,8 @@ func (s *NotificationService) notifyEnabledProvidersInternal(
})
}
var errs []string
- if err := g.Wait(); err != nil {
- errs = append(errs, fmt.Sprintf("notification dispatch: %v", err))
+ if waitErr := g.Wait(); waitErr != nil {
+ errs = append(errs, fmt.Sprintf("notification dispatch: %v", waitErr))
}
delivered := 0
@@ -646,8 +668,8 @@ func (s *NotificationService) notifyEnabledProvidersInternal(
}
if s.apnsSvc != nil {
- if err := s.apnsSvc.Enqueue(ctx, target.EnvironmentID, target.EnvironmentName, eventType, logRef, metadata); err != nil {
- slog.WarnContext(ctx, "Failed to enqueue mobile push notification", "error", err)
+ if enqueueErr := s.apnsSvc.Enqueue(ctx, target.EnvironmentID, target.EnvironmentName, eventType, logRef, metadata); enqueueErr != nil {
+ slog.WarnContext(ctx, "Failed to enqueue mobile push notification", "error", enqueueErr)
}
}
@@ -657,13 +679,13 @@ func (s *NotificationService) notifyEnabledProvidersInternal(
return delivered, nil
}
-func collectNotificationSendResultInternal(errors *[]string, provider notifications.NotificationProvider, sendErr error) (string, *string) {
+func collectNotificationSendResultInternal(localErrors *[]string, provider notifications.NotificationProvider, sendErr error) (string, *string) {
if sendErr == nil {
return "success", nil
}
msg := sendErr.Error()
- *errors = append(*errors, fmt.Sprintf("%s: %s", provider, msg))
+ *localErrors = append(*localErrors, fmt.Sprintf("%s: %s", provider, msg))
return "failed", &msg
}
@@ -822,7 +844,17 @@ func (s *NotificationService) sendBatchContainerUpdateNotificationForTargetInter
}
content := s.batchContainerUpdateNotificationContentInternal(target.EnvironmentName, entries)
content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventContainerUpdate)
- _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventContainerUpdate, strings.Join(containerNames, ", "), metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {
+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventContainerUpdate, strings.Join(
+ containerNames,
+ ", ",
+ ), metadata, func(
+ ctx context.Context,
+ provider notifications.NotificationProvider,
+ config database.JSON,
+ ) (
+ bool,
+ error,
+ ) {
return notifications.Deliver(ctx, provider, config, content)
})
return err
@@ -920,7 +952,18 @@ func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, i
return s.sendImageUpdateNotificationForTargetInternal(ctx, target, imageRef, updateInfo, eventType)
}
-func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, imageRef string, updateInfo *imageupdate.Response, eventType notifications.NotificationEventType) (int, error) {
+func (
+ s *NotificationService,
+) sendImageUpdateNotificationForTargetInternal(
+ ctx context.Context,
+ target NotificationTarget,
+ imageRef string,
+ updateInfo *imageupdate.Response,
+ eventType notifications.NotificationEventType,
+) (
+ int,
+ error,
+) {
metadata := database.JSON{
"hasUpdate": updateInfo.HasUpdate,
"currentDigest": updateInfo.CurrentDigest,
@@ -966,7 +1009,14 @@ func (s *NotificationService) sendContainerUpdateNotificationForTargetInternal(c
}
content := s.containerUpdateNotificationContentInternal(target.EnvironmentName, containerName, imageRef, oldDigest, newDigest)
content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventContainerUpdate)
- _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventContainerUpdate, imageRef, metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {
+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventContainerUpdate, imageRef, metadata, func(
+ ctx context.Context,
+ provider notifications.NotificationProvider,
+ config database.JSON,
+ ) (
+ bool,
+ error,
+ ) {
return notifications.Deliver(ctx, provider, config, content)
})
return err
@@ -1017,7 +1067,14 @@ func (s *NotificationService) sendVulnerabilityNotificationForTargetInternal(ctx
}
content := s.vulnerabilityNotificationContentInternal(target.EnvironmentName, payload)
content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventVulnerabilityFound)
- _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventVulnerabilityFound, payload.ImageName, metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {
+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventVulnerabilityFound, payload.ImageName, metadata, func(
+ ctx context.Context,
+ provider notifications.NotificationProvider,
+ config database.JSON,
+ ) (
+ bool,
+ error,
+ ) {
return notifications.Deliver(ctx, provider, config, content)
})
return err
@@ -1079,7 +1136,17 @@ func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(
}
content := s.batchImageUpdateNotificationContentInternal(target.EnvironmentName, updatesWithChanges)
content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventImageUpdate)
- return s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventImageUpdate, strings.Join(imageRefs, ", "), metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {
+ return s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventImageUpdate, strings.Join(
+ imageRefs,
+ ", ",
+ ), metadata, func(
+ ctx context.Context,
+ provider notifications.NotificationProvider,
+ config database.JSON,
+ ) (
+ bool,
+ error,
+ ) {
return notifications.Deliver(ctx, provider, config, content)
})
}
@@ -1125,7 +1192,14 @@ func (s *NotificationService) sendPruneReportNotificationForTargetInternal(ctx c
}
content := s.pruneReportNotificationContentInternal(target.EnvironmentName, result)
content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventPruneReport)
- _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventPruneReport, "System Prune Report", metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {
+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventPruneReport, "System Prune Report", metadata, func(
+ ctx context.Context,
+ provider notifications.NotificationProvider,
+ config database.JSON,
+ ) (
+ bool,
+ error,
+ ) {
return notifications.Deliver(ctx, provider, config, content)
})
if err != nil {
@@ -1181,7 +1255,14 @@ func (s *NotificationService) sendAutoHealNotificationForTargetInternal(ctx cont
}
content := s.autoHealNotificationContentInternal(target.EnvironmentName, containerName)
content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventAutoHeal)
- _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventAutoHeal, containerName, metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {
+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventAutoHeal, containerName, metadata, func(
+ ctx context.Context,
+ provider notifications.NotificationProvider,
+ config database.JSON,
+ ) (
+ bool,
+ error,
+ ) {
return notifications.Deliver(ctx, provider, config, content)
})
return err
@@ -1327,8 +1408,8 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentI
return warning, sendErr
}
-func (s *NotificationService) sendTestEmailInternal(ctx context.Context, environmentName string, config database.JSON) error {
- _, err := notifications.Deliver(ctx, notifications.NotificationProviderEmail, config, notifications.Content{
+func (s *NotificationService) sendTestEmailInternal(ctx context.Context, environmentName string, localConfig database.JSON) error {
+ _, err := notifications.Deliver(ctx, notifications.NotificationProviderEmail, localConfig, notifications.Content{
RenderEmail: func() (string, string, error) {
htmlBody, _, err := s.renderTestEmailTemplateInternal(environmentName)
if err != nil {
diff --git a/backend/internal/notification/service_test.go b/backend/internal/notification/service_test.go
index cc8c0d66b..3c3f2a8cc 100644
--- a/backend/internal/notification/service_test.go
+++ b/backend/internal/notification/service_test.go
@@ -53,7 +53,7 @@ func setupNotificationTestDB(t *testing.T) *database.DB {
return &database.DB{DB: db}
}
-func setupNotificationTestServiceInternal(t *testing.T) (*database.DB, *environment.EnvironmentService, *NotificationService) {
+func setupNotificationTestServiceInternal(t *testing.T) (*database.DB, *NotificationService) {
t.Helper()
db := setupNotificationTestDB(t)
@@ -63,7 +63,7 @@ func setupNotificationTestServiceInternal(t *testing.T) (*database.DB, *environm
AppUrl: "http://localhost:3552",
}
- return db, envSvc, NewNotificationService(db, cfg, envSvc, event.NewEventService(db, cfg, nil), nil)
+ return db, NewNotificationService(db, cfg, envSvc, event.NewEventService(db, cfg, nil), nil)
}
func newNotificationTestUpdateInfoInternal() *imageupdate.Response {
@@ -91,8 +91,8 @@ func captureNotificationServiceLogsInternal(t *testing.T) *bytes.Buffer {
}
func TestNotificationService_ResolveNotificationTargetInternal_UsesEnvironmentRecordAndFallback(t *testing.T) {
- ctx := context.Background()
- db, _, svc := setupNotificationTestServiceInternal(t)
+ ctx := t.Context()
+ db, svc := setupNotificationTestServiceInternal(t)
target, err := svc.resolveNotificationTargetInternal(ctx, "")
require.NoError(t, err)
@@ -115,8 +115,8 @@ func TestNotificationService_ResolveNotificationTargetInternal_UsesEnvironmentRe
}
func TestNotificationService_ResolveNotificationTargetForAccessTokenInternal_UsesStoredEnvironmentName(t *testing.T) {
- ctx := context.Background()
- db, _, svc := setupNotificationTestServiceInternal(t)
+ ctx := t.Context()
+ db, svc := setupNotificationTestServiceInternal(t)
token := "remote-token"
now := time.Now()
@@ -136,8 +136,8 @@ func TestNotificationService_ResolveNotificationTargetForAccessTokenInternal_Use
}
func TestNotificationService_DispatchNotification_InvalidAccessTokenReturnsUnauthorizedSentinel(t *testing.T) {
- ctx := context.Background()
- _, _, svc := setupNotificationTestServiceInternal(t)
+ ctx := t.Context()
+ _, svc := setupNotificationTestServiceInternal(t)
_, err := svc.DispatchNotification(ctx, "missing-token", notificationdto.DispatchRequest{
Kind: notificationdto.DispatchKindImageUpdate,
@@ -152,8 +152,8 @@ func TestNotificationService_DispatchNotification_InvalidAccessTokenReturnsUnaut
}
func TestNotificationService_DispatchNotification_UnsupportedKindReturnsSentinel(t *testing.T) {
- ctx := context.Background()
- db, _, svc := setupNotificationTestServiceInternal(t)
+ ctx := t.Context()
+ db, svc := setupNotificationTestServiceInternal(t)
token := "remote-token"
now := time.Now()
@@ -178,8 +178,8 @@ func TestNotificationService_DispatchNotification_UnsupportedKindReturnsSentinel
}
func TestNotificationService_DispatchNotification_LogsManagerDispatchForAgent(t *testing.T) {
- ctx := context.Background()
- db, _, svc := setupNotificationTestServiceInternal(t)
+ ctx := t.Context()
+ db, svc := setupNotificationTestServiceInternal(t)
logBuffer := captureNotificationServiceLogsInternal(t)
token := "remote-token"
@@ -212,7 +212,7 @@ func TestNotificationService_DispatchNotification_LogsManagerDispatchForAgent(t
}
func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToManager(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
envSvc := environment.NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -261,7 +261,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMa
}
func TestNotificationService_SendBatchImageUpdateNotification_AgentModeUsesManagerDeliveredCountInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
envSvc := environment.NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -309,7 +309,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeUsesManag
}
func TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdateInfo(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
envSvc := environment.NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -324,7 +324,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdate
}
func TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOpDispatchInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
envSvc := environment.NewEnvironmentService(db, nil, nil, nil, nil, nil)
@@ -365,7 +365,7 @@ func TestNotificationService_SendBatchImageUpdateNotification_AgentModeSkipsNoOp
}
func TestNotificationService_RenderEmailTemplate_IncludesEnvironment(t *testing.T) {
- _, _, svc := setupNotificationTestServiceInternal(t)
+ _, svc := setupNotificationTestServiceInternal(t)
htmlBody, textBody, err := svc.renderEmailTemplateInternal("Homelab Prod", "nginx:latest", newNotificationTestUpdateInfoInternal())
require.NoError(t, err)
@@ -377,7 +377,7 @@ func TestNotificationService_RenderEmailTemplate_IncludesEnvironment(t *testing.
}
func TestNotificationService_RenderContainerUpdateEmailTemplate_IncludesEnvironment(t *testing.T) {
- _, _, svc := setupNotificationTestServiceInternal(t)
+ _, svc := setupNotificationTestServiceInternal(t)
htmlBody, textBody, err := svc.renderContainerUpdateEmailTemplateInternal("Lab Remote", "nginx", "nginx:latest", "sha256:old", "sha256:new")
require.NoError(t, err)
@@ -389,7 +389,7 @@ func TestNotificationService_RenderContainerUpdateEmailTemplate_IncludesEnvironm
}
func TestNotificationService_RenderBatchEmailTemplate_IncludesEnvironment(t *testing.T) {
- _, _, svc := setupNotificationTestServiceInternal(t)
+ _, svc := setupNotificationTestServiceInternal(t)
updates := map[string]*imageupdate.Response{
"nginx:latest": newNotificationTestUpdateInfoInternal(),
@@ -412,7 +412,7 @@ func TestNotificationService_RenderBatchEmailTemplate_IncludesEnvironment(t *tes
}
func TestNotificationService_RenderVulnerabilitySummaryEmailTemplate_IncludesEnvironment(t *testing.T) {
- _, _, svc := setupNotificationTestServiceInternal(t)
+ _, svc := setupNotificationTestServiceInternal(t)
htmlBody, textBody, err := svc.renderVulnerabilitySummaryEmailTemplateInternal("Remote Alpha", VulnerabilityNotificationPayload{
CVEID: "Daily Summary - 2026-01-09",
@@ -427,7 +427,7 @@ func TestNotificationService_RenderVulnerabilitySummaryEmailTemplate_IncludesEnv
}
func TestNotificationService_RenderPruneReportEmailTemplate_IncludesEnvironment(t *testing.T) {
- _, _, svc := setupNotificationTestServiceInternal(t)
+ _, svc := setupNotificationTestServiceInternal(t)
htmlBody, textBody, err := svc.renderPruneReportEmailTemplateInternal("Cluster West", &system.PruneAllResult{
SpaceReclaimed: 3825205248,
@@ -552,7 +552,7 @@ func TestNotificationCredentialInternal_LeavesEmptyValuesEmpty(t *testing.T) {
}
func TestNotificationService_CreateOrUpdateSettingsEncryptsCredentialFieldsInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
@@ -575,7 +575,7 @@ func TestNotificationService_CreateOrUpdateSettingsEncryptsCredentialFieldsInter
}
func TestNotificationService_CreateOrUpdateSettingsPreservesStoredCredentialWhenEmptyInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
@@ -603,7 +603,7 @@ func TestNotificationService_CreateOrUpdateSettingsPreservesStoredCredentialWhen
}
func TestNotificationService_CreateOrUpdateSettingsRejectsTargetChangeWithStoredCredentialInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
@@ -638,7 +638,7 @@ func TestNotificationService_CreateOrUpdateSettingsRejectsTargetChangeWithStored
}
func TestNotificationService_CreateOrUpdateSettingsClearsEmailPasswordWhenAuthModeNoneInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
@@ -662,7 +662,7 @@ func TestNotificationService_CreateOrUpdateSettingsClearsEmailPasswordWhenAuthMo
}
func TestNotificationService_CreateOrUpdateSettingsPreservesCredentialAcrossDisableInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
@@ -693,7 +693,7 @@ func TestNotificationService_CreateOrUpdateSettingsPreservesCredentialAcrossDisa
}
func TestNotificationService_CreateOrUpdateSettingsKeepsConfigWhenDisabledInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{}, nil, nil, nil)
@@ -729,7 +729,7 @@ func TestNotificationService_CreateOrUpdateSettingsKeepsConfigWhenDisabledIntern
}
func TestNotificationService_NotifyEnabledProvidersInternal_SkipsFiltersAndAggregatesInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{}, nil, event.NewEventService(db, nil, nil), nil)
@@ -831,8 +831,8 @@ func TestSupportedNotificationTestTypes_IncludesAutoHeal(t *testing.T) {
}
func TestNotificationService_DispatchNotificationForEnvironment_ResolvesTunnelSessionEnvironment(t *testing.T) {
- ctx := context.Background()
- db, _, svc := setupNotificationTestServiceInternal(t)
+ ctx := t.Context()
+ db, svc := setupNotificationTestServiceInternal(t)
now := time.Now()
require.NoError(t, db.WithContext(ctx).Create(&environment.Environment{
@@ -858,7 +858,7 @@ func TestNotificationService_DispatchNotificationForEnvironment_ResolvesTunnelSe
}
func TestNotificationService_AgentDispatchWithoutHTTPConfigFallsBackToTunnel(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
svc := NewNotificationService(db, &config.Config{AgentMode: true}, nil, event.NewEventService(db, &config.Config{AgentMode: true}, nil), nil)
@@ -876,7 +876,7 @@ func TestNotificationService_AgentDispatchWithoutHTTPConfigFallsBackToTunnel(t *
}
func TestNotificationService_AgentDispatchHTTPFailureFallsBackToTunnel(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupNotificationTestDB(t)
cfg := &config.Config{AgentMode: true, ManagerApiUrl: "http://127.0.0.1:0", AgentToken: "token"}
svc := NewNotificationService(db, cfg, nil, event.NewEventService(db, cfg, nil), nil)
diff --git a/backend/internal/oidc/handler.go b/backend/internal/oidc/handler.go
index cb8a479d4..c4a98fc8d 100644
--- a/backend/internal/oidc/handler.go
+++ b/backend/internal/oidc/handler.go
@@ -131,7 +131,15 @@ type DeleteOidcRoleMappingOutput struct {
// RegisterOidc registers all OIDC authentication endpoints (plus the OIDC
// group → role mapping CRUD) using Huma.
-func RegisterOidc(api huma.API, authService *auth.AuthService, passkeyService *passkey.PasskeyService, oidcService *OidcService, roleService *role.RoleService, userService *user.UserService, cfg *config.Config) {
+func RegisterOidc(
+ api huma.API,
+ authService *auth.AuthService,
+ passkeyService *passkey.PasskeyService,
+ oidcService *OidcService,
+ roleService *role.RoleService,
+ userService *user.UserService,
+ cfg *config.Config,
+) {
h := &OidcHandler{authService: authService, passkeyService: passkeyService, oidcService: oidcService, roleService: roleService, userService: userService, config: cfg}
huma.Register(api, huma.Operation{
@@ -299,9 +307,9 @@ func (h *OidcHandler) GetOidcAuthUrl(ctx context.Context, input *GetOidcAuthUrlI
mobileRedirectURI := input.Body.MobileRedirectUri
if mobileRedirectURI != "" {
- if err := h.oidcService.ValidateMobileRedirectURI(ctx, mobileRedirectURI); err != nil {
- slog.WarnContext(ctx, "OIDC auth URL: rejected mobile redirect URI", "uri", mobileRedirectURI, "error", err)
- return nil, huma.Error400BadRequest(err.Error())
+ if validateMobileRedirectURIErr := h.oidcService.ValidateMobileRedirectURI(ctx, mobileRedirectURI); validateMobileRedirectURIErr != nil {
+ slog.WarnContext(ctx, "OIDC auth URL: rejected mobile redirect URI", "uri", mobileRedirectURI, "error", validateMobileRedirectURIErr)
+ return nil, huma.Error400BadRequest(validateMobileRedirectURIErr.Error())
}
}
@@ -366,8 +374,8 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
clearStateCookie := cookie.BuildClearOidcStateCookieString(cookie.SecureCookieFromContext(ctx))
setCookies := []string{clearStateCookie}
if userModel.PasskeyMFAEnabled {
- challenge, err := h.passkeyService.BeginMFAAuthentication(ctx, userModel.ID, meta, session.UserSessionSourceOidc)
- if err != nil {
+ challenge, beginMFAAuthenticationErr := h.passkeyService.BeginMFAAuthentication(ctx, userModel.ID, meta, session.UserSessionSourceOidc)
+ if beginMFAAuthenticationErr != nil {
return nil, huma.Error500InternalServerError("Authentication failed")
}
return &HandleOidcCallbackOutput{
diff --git a/backend/internal/oidc/service.go b/backend/internal/oidc/service.go
index 005e5f924..1e7c63b0a 100644
--- a/backend/internal/oidc/service.go
+++ b/backend/internal/oidc/service.go
@@ -122,7 +122,7 @@ func (s *OidcService) getInsecureHttpClientInternal() *http.Client {
insecureTransport = transport.Clone()
} else {
// Transport is nil or not *http.Transport - create a new default transport
- if defaultTransport, ok := http.DefaultTransport.(*http.Transport); ok {
+ if defaultTransport, localOk := http.DefaultTransport.(*http.Transport); localOk {
insecureTransport = defaultTransport.Clone()
} else {
insecureTransport = &http.Transport{}
@@ -229,11 +229,11 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo, origin, m
var provider *oidc.Provider
if !s.hasManualEndpointsInternal(oidcConfig) {
- var err error
- provider, err = s.getOrDiscoverProviderInternal(ctx, oidcConfig)
- if err != nil {
- slog.Error("GenerateAuthURL: provider discovery failed", "issuer", oidcConfig.IssuerURL, "error", err)
- return "", "", fmt.Errorf("failed to discover provider: %w", err)
+ var discoverProviderErr error
+ provider, discoverProviderErr = s.getOrDiscoverProviderInternal(ctx, oidcConfig)
+ if discoverProviderErr != nil {
+ slog.Error("GenerateAuthURL: provider discovery failed", "issuer", oidcConfig.IssuerURL, "error", discoverProviderErr)
+ return "", "", fmt.Errorf("failed to discover provider: %w", discoverProviderErr)
}
}
@@ -370,12 +370,12 @@ func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *settings.Oid
}
return nil, fmt.Errorf("failed to fetch userinfo: %w", err)
}
- if err := userInfo.Claims(&userInfoClaims); err != nil {
- slog.Warn("fetchClaimsInternal: failed to decode userinfo claims", "error", err)
+ if claimsErr := userInfo.Claims(&userInfoClaims); claimsErr != nil {
+ slog.Warn("fetchClaimsInternal: failed to decode userinfo claims", "error", claimsErr)
if claims != nil {
return claims, nil
}
- return nil, fmt.Errorf("failed to decode userinfo claims: %w", err)
+ return nil, fmt.Errorf("failed to decode userinfo claims: %w", claimsErr)
}
slog.Debug("fetchClaimsInternal: fetched userinfo claims successfully")
case cfg.UserinfoEndpoint != "":
@@ -415,7 +415,7 @@ func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *sett
return nil, errors.New("missing access token for userinfo request")
}
- request, err := http.NewRequestWithContext(ctx, http.MethodGet, cfg.UserinfoEndpoint, nil)
+ request, err := http.NewRequestWithContext(ctx, http.MethodGet, cfg.UserinfoEndpoint, http.NoBody)
if err != nil {
return nil, err
}
@@ -436,8 +436,8 @@ func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *sett
}
var claims map[string]any
- if err := json.UnmarshalRead(resp.Body, &claims); err != nil {
- return nil, err
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &claims); unmarshalReadErr != nil {
+ return nil, unmarshalReadErr
}
return claims, nil
@@ -549,9 +549,9 @@ func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.
var claims struct {
Nonce string `json:"nonce"`
}
- if err := idToken.Claims(&claims); err != nil {
- slog.Error("HandleCallback: failed to extract nonce from ID token", "error", err)
- return nil, "", fmt.Errorf("failed to verify nonce: %w", err)
+ if claimsErr := idToken.Claims(&claims); claimsErr != nil {
+ slog.Error("HandleCallback: failed to extract nonce from ID token", "error", claimsErr)
+ return nil, "", fmt.Errorf("failed to verify nonce: %w", claimsErr)
}
if claims.Nonce != nonce {
slog.Error("HandleCallback: nonce mismatch", "expected", nonce, "got", claims.Nonce)
@@ -563,7 +563,20 @@ func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.
return idToken, rawIDToken, nil
}
-func (s *OidcService) buildUserInfoInternal(ctx context.Context, provider *oidc.Provider, cfg *settings.OidcConfig, token *oauth2.Token, idToken *oidc.IDToken, rawIDToken string) (*authtypes.OidcUserInfo, *authtypes.OidcTokenResponse, error) {
+func (
+ s *OidcService,
+) buildUserInfoInternal(
+ ctx context.Context,
+ provider *oidc.Provider,
+ cfg *settings.OidcConfig,
+ token *oauth2.Token,
+ idToken *oidc.IDToken,
+ rawIDToken string,
+) (
+ *authtypes.OidcUserInfo,
+ *authtypes.OidcTokenResponse,
+ error,
+) {
claims, err := s.fetchClaimsInternal(ctx, cfg, provider, token, idToken)
if err != nil {
slog.Error("HandleCallback: failed to fetch claims", "error", err)
@@ -615,9 +628,9 @@ func (s *OidcService) decodeStateInternal(encodedState string) (*OidcState, erro
}
var stateData OidcState
- if err := json.Unmarshal(stateJSON, &stateData); err != nil {
- slog.Error("decodeStateInternal: failed to unmarshal state JSON", "error", err)
- return nil, err
+ if unmarshalErr := json.Unmarshal(stateJSON, &stateData); unmarshalErr != nil {
+ slog.Error("decodeStateInternal: failed to unmarshal state JSON", "error", unmarshalErr)
+ return nil, unmarshalErr
}
return &stateData, nil
@@ -679,10 +692,10 @@ func (s *OidcService) InitiateDeviceAuth(ctx context.Context) (*authtypes.OidcDe
ExpiresIn: int(expiresIn),
}
- if uri, ok := respData["verification_uri_complete"].(string); ok {
+ if uri, localOk := respData["verification_uri_complete"].(string); localOk {
response.VerificationUriComplete = uri
}
- if interval, ok := respData["interval"].(float64); ok {
+ if interval, localOk2 := respData["interval"].(float64); localOk2 {
response.Interval = int(interval)
} else {
response.Interval = 5
@@ -706,8 +719,8 @@ func (s *OidcService) getDeviceAuthorizationEndpointInternal(ctx context.Context
var claims struct {
DeviceAuthorizationEndpoint string `json:"device_authorization_endpoint"`
}
- if err := provider.Claims(&claims); err != nil {
- return "", fmt.Errorf("failed to get device authorization endpoint from provider: %w", err)
+ if claimsErr := provider.Claims(&claims); claimsErr != nil {
+ return "", fmt.Errorf("failed to get device authorization endpoint from provider: %w", claimsErr)
}
if claims.DeviceAuthorizationEndpoint == "" {
@@ -738,7 +751,7 @@ func (s *OidcService) makeDeviceAuthRequestInternal(ctx context.Context, endpoin
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var errorResp map[string]any
- if err := json.UnmarshalRead(resp.Body, &errorResp); err == nil {
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &errorResp); unmarshalReadErr == nil {
if errMsg, ok := errorResp["error"].(string); ok {
return nil, fmt.Errorf("device authorization failed: %s", errMsg)
}
@@ -747,8 +760,8 @@ func (s *OidcService) makeDeviceAuthRequestInternal(ctx context.Context, endpoin
}
var respData map[string]any
- if err := json.UnmarshalRead(resp.Body, &respData); err != nil {
- return nil, fmt.Errorf("failed to decode device authorization response: %w", err)
+ if decodeDeviceAuthorizationErr := json.UnmarshalRead(resp.Body, &respData); decodeDeviceAuthorizationErr != nil {
+ return nil, fmt.Errorf("failed to decode device authorization response: %w", decodeDeviceAuthorizationErr)
}
return respData, nil
@@ -766,9 +779,9 @@ func (s *OidcService) ExchangeDeviceToken(ctx context.Context, deviceCode string
if cfg.TokenEndpoint != "" {
tokenEndpoint = cfg.TokenEndpoint
} else {
- provider, err := s.getOrDiscoverProviderInternal(ctx, cfg)
- if err != nil {
- return nil, nil, err
+ provider, getOrDiscoverProviderErr := s.getOrDiscoverProviderInternal(ctx, cfg)
+ if getOrDiscoverProviderErr != nil {
+ return nil, nil, getOrDiscoverProviderErr
}
tokenEndpoint = provider.Endpoint().TokenURL
}
@@ -804,13 +817,13 @@ func (s *OidcService) ExchangeDeviceToken(ctx context.Context, deviceCode string
AccessToken: accessToken,
TokenType: kit.As(tokenResp["token_type"], "Bearer"),
}
- if refreshToken, ok := tokenResp["refresh_token"].(string); ok {
+ if refreshToken, localOk := tokenResp["refresh_token"].(string); localOk {
token.RefreshToken = refreshToken
}
- if expiresIn, ok := tokenResp["expires_in"].(float64); ok {
+ if expiresIn, localOk2 := tokenResp["expires_in"].(float64); localOk2 {
token.Expiry = time.Now().Add(time.Duration(expiresIn) * time.Second)
}
- if idToken, ok := tokenResp["id_token"].(string); ok {
+ if idToken, localOk3 := tokenResp["id_token"].(string); localOk3 {
token = token.WithExtra(map[string]any{"id_token": idToken})
}
@@ -846,8 +859,8 @@ func (s *OidcService) makeTokenRequestInternal(ctx context.Context, endpoint str
defer func() { _ = resp.Body.Close() }()
var tokenResp map[string]any
- if err := json.UnmarshalRead(resp.Body, &tokenResp); err != nil {
- return nil, fmt.Errorf("failed to decode token response: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &tokenResp); unmarshalReadErr != nil {
+ return nil, fmt.Errorf("failed to decode token response: %w", unmarshalReadErr)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
diff --git a/backend/internal/oidc/service_test.go b/backend/internal/oidc/service_test.go
index ecb27b06d..0024dcce3 100644
--- a/backend/internal/oidc/service_test.go
+++ b/backend/internal/oidc/service_test.go
@@ -14,7 +14,7 @@ import (
)
func TestValidateMobileRedirectURI(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
s := &OidcService{
config: &config.Config{
OidcMobileRedirectUris: "arcane-mobile://oidc-callback, arcane-mobile://oauth",
@@ -45,7 +45,7 @@ func TestValidateMobileRedirectURI(t *testing.T) {
}
func TestGetMobileRedirectAllowlistTrimsWhitespace(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
s := &OidcService{
config: &config.Config{
OidcMobileRedirectUris: " arcane-mobile://a ,arcane-mobile://b ,, arcane-mobile://c",
@@ -65,7 +65,7 @@ func TestGetMobileRedirectAllowlistTrimsWhitespace(t *testing.T) {
}
func TestGetMobileRedirectAllowlistUsesSettings(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -73,9 +73,9 @@ func TestGetMobileRedirectAllowlistUsesSettings(t *testing.T) {
"settings.NewSettingsService: %v", err)
{
- err := settingsService.UpdateSetting(ctx, "oidcMobileRedirectUris", "arcane-mobile://db-callback")
- require.NoError(t, err,
- "UpdateSetting: %v", err)
+ updateSettingErr := settingsService.UpdateSetting(ctx, "oidcMobileRedirectUris", "arcane-mobile://db-callback")
+ require.NoError(t, updateSettingErr,
+ "UpdateSetting: %v", updateSettingErr)
}
s := &OidcService{
@@ -86,14 +86,14 @@ func TestGetMobileRedirectAllowlistUsesSettings(t *testing.T) {
}
{
- err := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://db-callback")
- require.NoError(t, err,
- "ValidateMobileRedirectURI db value: %v", err)
+ validateMobileRedirectURIErr := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://db-callback")
+ require.NoError(t, validateMobileRedirectURIErr,
+ "ValidateMobileRedirectURI db value: %v", validateMobileRedirectURIErr)
}
{
- err := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://config-callback")
- require.Error(t, err,
+ validateMobileRedirectURIErr2 := s.ValidateMobileRedirectURI(ctx, "arcane-mobile://config-callback")
+ require.Error(t, validateMobileRedirectURIErr2,
"ValidateMobileRedirectURI config fallback should fail when DB setting is configured")
}
}
@@ -112,7 +112,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
diff --git a/backend/internal/passkey/handler.go b/backend/internal/passkey/handler.go
index fc3ebfd84..b0b0c134c 100644
--- a/backend/internal/passkey/handler.go
+++ b/backend/internal/passkey/handler.go
@@ -356,7 +356,14 @@ func (h *PasskeyHandler) getLoginAvailabilityInternal(ctx context.Context, _ *st
if err != nil {
return nil, passkeyHTTPErrorInternal(err)
}
- return &handlerutil.Out[authtypes.PasskeyLoginAvailability]{Body: base.ApiResponse[authtypes.PasskeyLoginAvailability]{Success: true, Data: authtypes.PasskeyLoginAvailability{Available: available}}}, nil
+ return &handlerutil.Out[authtypes.PasskeyLoginAvailability]{
+ Body: base.ApiResponse[authtypes.PasskeyLoginAvailability]{
+ Success: true,
+ Data: authtypes.PasskeyLoginAvailability{
+ Available: available,
+ },
+ },
+ }, nil
}
func (h *PasskeyHandler) BeginPasskeyLogin(ctx context.Context, _ *struct{}) (*handlerutil.Out[passkeyBeginResponse], error) {
@@ -550,8 +557,8 @@ func (h *PasskeyHandler) DeletePasskey(ctx context.Context, input *DeletePasskey
if err != nil {
return nil, huma.Error500InternalServerError("failed to check OIDC status")
}
- if err := h.passkeyService.DeletePasskey(ctx, userModel.ID, input.ID, sessionID, input.StepUpToken, oidcEnabled); err != nil {
- return nil, passkeyHTTPErrorInternal(err)
+ if deletePasskeyErr := h.passkeyService.DeletePasskey(ctx, userModel.ID, input.ID, sessionID, input.StepUpToken, oidcEnabled); deletePasskeyErr != nil {
+ return nil, passkeyHTTPErrorInternal(deletePasskeyErr)
}
return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Passkey deleted"}}}, nil
}
@@ -592,7 +599,7 @@ func (h *PasskeyHandler) PasswordStepUp(ctx context.Context, input *PasswordStep
if strings.TrimSpace(userModel.PasswordHash) == "" {
return nil, huma.Error400BadRequest("this account has no local password")
}
- if err := h.userService.ValidatePassword(userModel.PasswordHash, input.Body.Password); err != nil {
+ if validatePasswordErr := h.userService.ValidatePassword(userModel.PasswordHash, input.Body.Password); validatePasswordErr != nil {
return nil, huma.Error401Unauthorized("password is incorrect")
}
grant, err := h.passkeyService.CreatePasswordStepUpGrant(ctx, userModel.ID, sessionID)
@@ -631,8 +638,8 @@ func (h *PasskeyHandler) DisableMFA(ctx context.Context, input *MFASettingsInput
if err != nil {
return nil, err
}
- if err := h.passkeyService.DisableMFA(ctx, userModel.ID, sessionID, input.StepUpToken); err != nil {
- return nil, passkeyHTTPErrorInternal(err)
+ if disableMFAErr := h.passkeyService.DisableMFA(ctx, userModel.ID, sessionID, input.StepUpToken); disableMFAErr != nil {
+ return nil, passkeyHTTPErrorInternal(disableMFAErr)
}
h.authService.InvalidateUserTokenCache(userModel.ID)
return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Passkey MFA disabled"}}}, nil
diff --git a/backend/internal/passkey/service.go b/backend/internal/passkey/service.go
index e60b97154..983cef295 100644
--- a/backend/internal/passkey/service.go
+++ b/backend/internal/passkey/service.go
@@ -302,12 +302,12 @@ func (s *PasskeyService) BeginPasskeyLogin(ctx context.Context) (*PasskeyChallen
return nil, err
}
- assertion, session, err := s.webAuthn.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))
+ assertion, localSession, err := s.webAuthn.BeginDiscoverableLogin(webauthn.WithUserVerification(protocol.VerificationRequired))
if err != nil {
return nil, fmt.Errorf("failed to begin passkey login: %w", err)
}
- ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeLogin, nil, nil, nil, session)
+ ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeLogin, nil, nil, nil, localSession)
if err != nil {
return nil, err
}
@@ -335,8 +335,8 @@ func (s *PasskeyService) BeginMFAAuthentication(ctx context.Context, userID stri
}
transaction := newAuthTransactionInternal(userID, authTransactionKindMFA, source, meta, nil)
- if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {
- return nil, fmt.Errorf("failed to create MFA transaction: %w", err)
+ if createMFATransactionErr := s.db.WithContext(ctx).Create(transaction).Error; createMFATransactionErr != nil {
+ return nil, fmt.Errorf("failed to create MFA transaction: %w", createMFATransactionErr)
}
challenge, err := s.beginMFAForTransactionInternal(ctx, transaction)
if err != nil {
@@ -376,10 +376,10 @@ func (s *PasskeyService) beginMFAForTransactionInternal(ctx context.Context, tra
}
// A transaction has one active assertion at a time. Replacing an older
// pending ceremony prevents a client from accumulating reusable challenges.
- if err := s.db.WithContext(ctx).
+ if invalidateMFACeremoniesErr := s.db.WithContext(ctx).
Where("auth_transaction_id = ? AND purpose = ? AND consumed_at IS NULL", transaction.ID, passkeyCeremonyPurposeMFA).
- Delete(&PasskeyCeremony{}).Error; err != nil {
- return nil, fmt.Errorf("failed to replace MFA ceremony: %w", err)
+ Delete(&PasskeyCeremony{}).Error; invalidateMFACeremoniesErr != nil {
+ return nil, fmt.Errorf("failed to replace MFA ceremony: %w", invalidateMFACeremoniesErr)
}
assertion, webSession, err := s.webAuthn.BeginLogin(adapter, webauthn.WithUserVerification(protocol.VerificationRequired))
@@ -422,11 +422,11 @@ func (s *PasskeyService) BeginStepUp(ctx context.Context, userID, sessionID stri
}
transaction := newAuthTransactionInternal(userID, authTransactionKindStepUp, session.UserSessionSourceLocal, meta, &sessionID)
- if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {
- return nil, fmt.Errorf("failed to create step-up transaction: %w", err)
+ if createStepUpTransactionErr := s.db.WithContext(ctx).Create(transaction).Error; createStepUpTransactionErr != nil {
+ return nil, fmt.Errorf("failed to create step-up transaction: %w", createStepUpTransactionErr)
}
- assertion, session, err := s.webAuthn.BeginLogin(adapter, webauthn.WithUserVerification(protocol.VerificationRequired))
+ assertion, localSession, err := s.webAuthn.BeginLogin(adapter, webauthn.WithUserVerification(protocol.VerificationRequired))
if err != nil {
_ = s.db.WithContext(ctx).Delete(transaction).Error
return nil, fmt.Errorf("failed to begin step-up passkey ceremony: %w", err)
@@ -434,7 +434,7 @@ func (s *PasskeyService) BeginStepUp(ctx context.Context, userID, sessionID stri
transactionID := transaction.ID
userIDPointer := userID
- ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeStepUp, &userIDPointer, &sessionID, &transactionID, session)
+ ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeStepUp, &userIDPointer, &sessionID, &transactionID, localSession)
if err != nil {
_ = s.db.WithContext(ctx).Delete(transaction).Error
return nil, err
@@ -464,7 +464,7 @@ func (s *PasskeyService) BeginRegistration(ctx context.Context, userID, sessionI
return nil, err
}
exclusions := webauthn.Credentials(adapter.credentials).CredentialDescriptors()
- creation, session, err := s.webAuthn.BeginRegistration(
+ creation, localSession, err := s.webAuthn.BeginRegistration(
adapter,
webauthn.WithCredentialParameters(webauthn.CredentialParametersPQCRecommendedL3()),
webauthn.WithExclusions(exclusions),
@@ -476,7 +476,7 @@ func (s *PasskeyService) BeginRegistration(ctx context.Context, userID, sessionI
}
userIDPointer := userID
- ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeRegistration, &userIDPointer, &sessionID, nil, session)
+ ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeRegistration, &userIDPointer, &sessionID, nil, localSession)
if err != nil {
return nil, err
}
@@ -503,8 +503,8 @@ func (s *PasskeyService) FinishRegistration(ctx context.Context, userID, session
return nil, ErrPasskeyCeremony
}
- var session webauthn.SessionData
- if err := json.Unmarshal([]byte(ceremony.SessionData), &session); err != nil {
+ var localSession webauthn.SessionData
+ if unmarshalErr := json.Unmarshal([]byte(ceremony.SessionData), &localSession); unmarshalErr != nil {
return nil, ErrPasskeyCeremony
}
adapter, err := s.loadWebAuthnUserInternal(ctx, userID)
@@ -515,7 +515,7 @@ func (s *PasskeyService) FinishRegistration(ctx context.Context, userID, session
if err != nil {
return nil, ErrPasskeyResponse
}
- credential, err := s.webAuthn.CreateCredential(adapter, session, parsed)
+ credential, err := s.webAuthn.CreateCredential(adapter, localSession, parsed)
if err != nil {
return nil, ErrPasskeyResponse
}
@@ -547,8 +547,8 @@ func (s *PasskeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID stri
if err != nil {
return nil, err
}
- var session webauthn.SessionData
- if err := json.Unmarshal([]byte(ceremony.SessionData), &session); err != nil {
+ var localSession webauthn.SessionData
+ if unmarshalErr := json.Unmarshal([]byte(ceremony.SessionData), &localSession); unmarshalErr != nil {
return nil, ErrPasskeyCeremony
}
parsed, err := protocol.ParseCredentialRequestResponseBytes(payload)
@@ -556,7 +556,7 @@ func (s *PasskeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID stri
slog.WarnContext(ctx, "passkey login validation failed", "stage", "parse", "error", err)
return nil, ErrPasskeyResponse
}
- utils.NormalizePasskeyAssertionExtensions(session.Extensions, parsed)
+ utils.NormalizePasskeyAssertionExtensions(localSession.Extensions, parsed)
var resolved *webAuthnUser
user, credential, err := s.webAuthn.ValidatePasskeyLogin(func(_, userHandle []byte) (webauthn.User, error) {
@@ -566,14 +566,14 @@ func (s *PasskeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID stri
}
resolved = adapter
return adapter, nil
- }, session, parsed)
+ }, localSession, parsed)
if err != nil || user == nil || credential == nil || resolved == nil {
slog.WarnContext(ctx, "passkey login validation failed", "stage", "assertion", "error", err)
return nil, ErrPasskeyResponse
}
- if err := s.updateCredentialAfterAssertionInternal(ctx, resolved, credential); err != nil {
- return nil, err
+ if updateCredentialAfterAssertionErr := s.updateCredentialAfterAssertionInternal(ctx, resolved, credential); updateCredentialAfterAssertionErr != nil {
+ return nil, updateCredentialAfterAssertionErr
}
return &resolved.model, nil
}
@@ -590,8 +590,8 @@ func (s *PasskeyService) FinishMobilePasskeyLogin(ctx context.Context, ceremonyI
transaction := newAuthTransactionInternal(user.ID, authTransactionKindMobilePasskey, session.UserSessionSourcePasskey, auth.SessionMeta{}, nil)
transaction.SecretHash = &codeChallenge
- if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {
- return nil, fmt.Errorf("failed to create mobile passkey transaction: %w", err)
+ if createMobileTransactionErr := s.db.WithContext(ctx).Create(transaction).Error; createMobileTransactionErr != nil {
+ return nil, fmt.Errorf("failed to create mobile passkey transaction: %w", createMobileTransactionErr)
}
return &auth.MobilePasskeyCompletion{TransactionID: transaction.ID, ExpiresAt: transaction.ExpiresAt}, nil
}
@@ -607,11 +607,20 @@ func (s *PasskeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transac
var transaction AuthTransaction
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := tx.Where("id = ? AND kind = ? AND status = ? AND secret_hash = ? AND expires_at > ?", transactionID, authTransactionKindMobilePasskey, authTransactionPending, codeChallenge, time.Now()).First(&transaction).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
+ if loadMobileTransactionErr := tx.Where(
+ "id = ? AND kind = ? AND status = ? AND secret_hash = ? AND expires_at > ?",
+ transactionID,
+ authTransactionKindMobilePasskey,
+ authTransactionPending,
+ codeChallenge,
+ time.Now(),
+ ).First(
+ &transaction,
+ ).Error; loadMobileTransactionErr != nil {
+ if errors.Is(loadMobileTransactionErr, gorm.ErrRecordNotFound) {
return ErrPasskeyTransaction
}
- return fmt.Errorf("failed to load mobile passkey transaction: %w", err)
+ return fmt.Errorf("failed to load mobile passkey transaction: %w", loadMobileTransactionErr)
}
now := time.Now()
@@ -638,8 +647,8 @@ func (s *PasskeyService) FinishMFA(ctx context.Context, transactionID string, pa
if err != nil {
return nil, err
}
- if err := s.completeTransactionInternal(ctx, transaction.ID); err != nil {
- return nil, err
+ if completeTransactionErr := s.completeTransactionInternal(ctx, transaction.ID); completeTransactionErr != nil {
+ return nil, completeTransactionErr
}
now := time.Now()
@@ -662,7 +671,19 @@ func (s *PasskeyService) FinishRecoveryCode(ctx context.Context, transactionID,
hash := kit.SHA256Hex(normalized)
var transaction AuthTransaction
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ? AND kind = ? AND status = ? AND expires_at > ?", transactionID, authTransactionKindMFA, authTransactionPending, time.Now()).First(&transaction).Error; err != nil {
+ if err := tx.Clauses(
+ clause.Locking{
+ Strength: "UPDATE",
+ },
+ ).Where(
+ "id = ? AND kind = ? AND status = ? AND expires_at > ?",
+ transactionID,
+ authTransactionKindMFA,
+ authTransactionPending,
+ time.Now(),
+ ).First(
+ &transaction,
+ ).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrPasskeyTransaction
}
@@ -725,11 +746,11 @@ func (s *PasskeyService) FinishStepUp(ctx context.Context, transactionID, sessio
if transaction.SessionID == nil || *transaction.SessionID != sessionID {
return nil, ErrPasskeyTransaction
}
- if err := s.ensureActiveSessionInternal(ctx, transaction.UserID, sessionID); err != nil {
- return nil, err
+ if ensureActiveSessionErr := s.ensureActiveSessionInternal(ctx, transaction.UserID, sessionID); ensureActiveSessionErr != nil {
+ return nil, ensureActiveSessionErr
}
- if _, err := s.finishKnownUserAssertionInternal(ctx, transaction, passkeyCeremonyPurposeStepUp, payload); err != nil {
- return nil, err
+ if _, finishKnownUserAssertionErr := s.finishKnownUserAssertionInternal(ctx, transaction, passkeyCeremonyPurposeStepUp, payload); finishKnownUserAssertionErr != nil {
+ return nil, finishKnownUserAssertionErr
}
return s.issueStepUpGrantInternal(ctx, transaction.ID)
}
@@ -832,8 +853,8 @@ func (s *PasskeyService) RenamePasskey(ctx context.Context, userID, passkeyID, n
return nil, fmt.Errorf("failed to load passkey: %w", result.Error)
}
now := time.Now()
- if err := s.db.WithContext(ctx).Model(&row).Updates(map[string]any{"name": name, "updated_at": now}).Error; err != nil {
- return nil, fmt.Errorf("failed to rename passkey: %w", err)
+ if renamePasskeyErr := s.db.WithContext(ctx).Model(&row).Updates(map[string]any{"name": name, "updated_at": now}).Error; renamePasskeyErr != nil {
+ return nil, fmt.Errorf("failed to rename passkey: %w", renamePasskeyErr)
}
row.Name = name
row.UpdatedAt = &now
@@ -888,8 +909,8 @@ func (s *PasskeyService) GetMFAStatus(ctx context.Context, userID string) (*MFAS
return nil, err
}
var recoveryCodes int64
- if err := s.db.WithContext(ctx).Model(&PasskeyRecoveryCode{}).Where("user_id = ? AND used_at IS NULL", userID).Count(&recoveryCodes).Error; err != nil {
- return nil, fmt.Errorf("failed to count recovery codes: %w", err)
+ if countRecoveryCodesErr := s.db.WithContext(ctx).Model(&PasskeyRecoveryCode{}).Where("user_id = ? AND used_at IS NULL", userID).Count(&recoveryCodes).Error; countRecoveryCodesErr != nil {
+ return nil, fmt.Errorf("failed to count recovery codes: %w", countRecoveryCodesErr)
}
return &MFAStatus{Enabled: user.PasskeyMFAEnabled, PasskeyCount: passkeyCount, RecoveryCodesRemaining: int(recoveryCodes)}, nil
}
@@ -907,12 +928,12 @@ func (s *PasskeyService) EnableMFA(ctx context.Context, userID, sessionID, stepU
}
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var user common.User
- if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {
- return fmt.Errorf("failed to lock user for MFA enable: %w", err)
+ if lockMFAUserErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; lockMFAUserErr != nil {
+ return fmt.Errorf("failed to lock user for MFA enable: %w", lockMFAUserErr)
}
var count int64
- if err := tx.Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {
- return fmt.Errorf("failed to count passkeys for MFA enable: %w", err)
+ if countPasskeysErr := tx.Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; countPasskeysErr != nil {
+ return fmt.Errorf("failed to count passkeys for MFA enable: %w", countPasskeysErr)
}
if count == 0 {
return ErrPasskeyNoCredential
@@ -920,14 +941,14 @@ func (s *PasskeyService) EnableMFA(ctx context.Context, userID, sessionID, stepU
if user.PasskeyMFAEnabled {
return ErrPasskeyMFAAlreadyEnabled
}
- if err := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", true).Error; err != nil {
- return fmt.Errorf("failed to enable passkey MFA: %w", err)
+ if enableMFAErr := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", true).Error; enableMFAErr != nil {
+ return fmt.Errorf("failed to enable passkey MFA: %w", enableMFAErr)
}
- if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {
- return fmt.Errorf("failed to replace recovery codes: %w", err)
+ if clearRecoveryCodesErr := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; clearRecoveryCodesErr != nil {
+ return fmt.Errorf("failed to replace recovery codes: %w", clearRecoveryCodesErr)
}
- if err := tx.Create(&rows).Error; err != nil {
- return fmt.Errorf("failed to create recovery codes: %w", err)
+ if createRecoveryCodesErr := tx.Create(&rows).Error; createRecoveryCodesErr != nil {
+ return fmt.Errorf("failed to create recovery codes: %w", createRecoveryCodesErr)
}
return nil
})
@@ -984,17 +1005,17 @@ func (s *PasskeyService) RegenerateRecoveryCodes(ctx context.Context, userID, se
}
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var user common.User
- if err := tx.Where("id = ?", userID).First(&user).Error; err != nil {
- return fmt.Errorf("failed to load user for recovery code regeneration: %w", err)
+ if loadRecoveryUserErr := tx.Where("id = ?", userID).First(&user).Error; loadRecoveryUserErr != nil {
+ return fmt.Errorf("failed to load user for recovery code regeneration: %w", loadRecoveryUserErr)
}
if !user.PasskeyMFAEnabled {
return ErrPasskeyMFANotEnabled
}
- if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {
- return fmt.Errorf("failed to replace recovery codes: %w", err)
+ if clearRecoveryCodesErr := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; clearRecoveryCodesErr != nil {
+ return fmt.Errorf("failed to replace recovery codes: %w", clearRecoveryCodesErr)
}
- if err := tx.Create(&rows).Error; err != nil {
- return fmt.Errorf("failed to create recovery codes: %w", err)
+ if createRecoveryCodesErr := tx.Create(&rows).Error; createRecoveryCodesErr != nil {
+ return fmt.Errorf("failed to create recovery codes: %w", createRecoveryCodesErr)
}
return nil
})
@@ -1038,15 +1059,15 @@ func (s *PasskeyService) ResetMFAForUser(ctx context.Context, userID string) err
})
}
-func (s *PasskeyService) createCeremonyInternal(ctx context.Context, purpose string, userID, sessionID, transactionID *string, session *webauthn.SessionData) (*PasskeyCeremony, error) {
- if session == nil {
+func (s *PasskeyService) createCeremonyInternal(ctx context.Context, purpose string, userID, sessionID, transactionID *string, localSession *webauthn.SessionData) (*PasskeyCeremony, error) {
+ if localSession == nil {
return nil, ErrPasskeyCeremony
}
- serialized, err := json.Marshal(session)
+ serialized, err := json.Marshal(localSession)
if err != nil {
return nil, fmt.Errorf("failed to serialize WebAuthn session: %w", err)
}
- expiresAt := session.Expires
+ expiresAt := localSession.Expires
if expiresAt.IsZero() {
expiresAt = time.Now().Add(passkeyCeremonyTTL)
}
@@ -1060,8 +1081,8 @@ func (s *PasskeyService) createCeremonyInternal(ctx context.Context, purpose str
SessionData: string(serialized),
ExpiresAt: expiresAt,
}
- if err := s.db.WithContext(ctx).Create(ceremony).Error; err != nil {
- return nil, fmt.Errorf("failed to store passkey ceremony: %w", err)
+ if createCeremonyErr := s.db.WithContext(ctx).Create(ceremony).Error; createCeremonyErr != nil {
+ return nil, fmt.Errorf("failed to store passkey ceremony: %w", createCeremonyErr)
}
return ceremony, nil
}
@@ -1126,8 +1147,8 @@ func (s *PasskeyService) finishKnownUserAssertionInternal(ctx context.Context, t
if ceremony.AuthTransactionID == nil || *ceremony.AuthTransactionID != transaction.ID || ceremony.UserID == nil || *ceremony.UserID != transaction.UserID {
return nil, ErrPasskeyCeremony
}
- var session webauthn.SessionData
- if err := json.Unmarshal([]byte(ceremony.SessionData), &session); err != nil {
+ var localSession webauthn.SessionData
+ if unmarshalErr := json.Unmarshal([]byte(ceremony.SessionData), &localSession); unmarshalErr != nil {
return nil, ErrPasskeyCeremony
}
adapter, err := s.loadWebAuthnUserInternal(ctx, transaction.UserID)
@@ -1138,13 +1159,13 @@ func (s *PasskeyService) finishKnownUserAssertionInternal(ctx context.Context, t
if err != nil {
return nil, ErrPasskeyResponse
}
- utils.NormalizePasskeyAssertionExtensions(session.Extensions, parsed)
- credential, err := s.webAuthn.ValidateLogin(adapter, session, parsed)
+ utils.NormalizePasskeyAssertionExtensions(localSession.Extensions, parsed)
+ credential, err := s.webAuthn.ValidateLogin(adapter, localSession, parsed)
if err != nil || credential == nil {
return nil, ErrPasskeyResponse
}
- if err := s.updateCredentialAfterAssertionInternal(ctx, adapter, credential); err != nil {
- return nil, err
+ if updateCredentialAfterAssertionErr := s.updateCredentialAfterAssertionInternal(ctx, adapter, credential); updateCredentialAfterAssertionErr != nil {
+ return nil, updateCredentialAfterAssertionErr
}
return &adapter.model, nil
}
@@ -1222,10 +1243,10 @@ func (s *PasskeyService) ensureActiveSessionInternal(ctx context.Context, userID
if strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {
return ErrPasskeyStepUpRequired
}
- var session session.UserSession
+ var localSession session.UserSession
if err := s.db.WithContext(ctx).
Where("id = ? AND user_id = ? AND revoked_at IS NULL AND expires_at > ?", sessionID, userID, time.Now()).
- First(&session).Error; err != nil {
+ First(&localSession).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrPasskeyStepUpRequired
}
@@ -1403,7 +1424,7 @@ func loadAuthenticatorNamesInternal() {
if err != nil {
return
}
- if err := json.Unmarshal(data, &authenticatorNames); err != nil {
+ if unmarshalErr := json.Unmarshal(data, &authenticatorNames); unmarshalErr != nil {
authenticatorNames = map[string]string{}
}
}
diff --git a/backend/internal/passkey/service_test.go b/backend/internal/passkey/service_test.go
index 0b3653ea3..365978d2f 100644
--- a/backend/internal/passkey/service_test.go
+++ b/backend/internal/passkey/service_test.go
@@ -1,7 +1,6 @@
package passkey
import (
- "context"
"testing"
"time"
"uuid"
@@ -71,7 +70,7 @@ func createPasskeyTestCredential(t *testing.T, db *database.DB, service *Passkey
func TestPasskeyService_BeginPasskeyLoginStoresAndConsumesCeremony(t *testing.T) {
db := newPasskeyServiceTestDB(t)
service := newPasskeyServiceForTest(t, db)
- ctx := context.Background()
+ ctx := t.Context()
challenge, err := service.BeginPasskeyLogin(ctx)
require.NoError(t, err)
@@ -133,10 +132,10 @@ func TestPasskeyService_LoginAvailability(t *testing.T) {
func TestPasskeyService_FirstEnrollmentUsesActiveSession(t *testing.T) {
db := newPasskeyServiceTestDB(t)
service := newPasskeyServiceForTest(t, db)
- ctx := context.Background()
+ ctx := t.Context()
user := createPasskeyTestUser(t, db, "first-enrollment-user")
sessionService := session.NewSessionService(db)
- session, _, err := sessionService.CreateSession(ctx, user.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
+ localSession, _, err := sessionService.CreateSession(ctx, user.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
require.NoError(t, err)
capabilities, err := service.GetCapabilities(ctx, user.ID, false)
@@ -145,7 +144,7 @@ func TestPasskeyService_FirstEnrollmentUsesActiveSession(t *testing.T) {
require.True(t, capabilities.CanEnrollWithActiveSession)
require.False(t, capabilities.RequiresStepUp)
- challenge, err := service.BeginRegistration(ctx, user.ID, session.ID, "")
+ challenge, err := service.BeginRegistration(ctx, user.ID, localSession.ID, "")
require.NoError(t, err)
require.NotEmpty(t, challenge.CeremonyID)
require.NotNil(t, challenge.Options)
@@ -157,7 +156,7 @@ func TestPasskeyService_FirstEnrollmentUsesActiveSession(t *testing.T) {
require.False(t, capabilities.CanEnrollWithActiveSession)
require.True(t, capabilities.RequiresStepUp)
- _, err = service.BeginRegistration(ctx, user.ID, session.ID, "")
+ _, err = service.BeginRegistration(ctx, user.ID, localSession.ID, "")
require.ErrorIs(t, err, ErrPasskeyStepUpRequired)
}
@@ -174,33 +173,33 @@ func TestPasskeyService_DefaultPasskeyNameUsesAAGUIDCatalog(t *testing.T) {
func TestPasskeyService_PasswordStepUpGrantIsBoundToActiveSessionAndReusableUntilExpiry(t *testing.T) {
db := newPasskeyServiceTestDB(t)
service := newPasskeyServiceForTest(t, db)
- ctx := context.Background()
+ ctx := t.Context()
user := createPasskeyTestUser(t, db, "step-up-user")
sessionService := session.NewSessionService(db)
- session, _, err := sessionService.CreateSession(ctx, user.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
+ localSession, _, err := sessionService.CreateSession(ctx, user.ID, time.Now().Add(time.Hour), auth.SessionMeta{})
require.NoError(t, err)
_, err = service.CreatePasswordStepUpGrant(ctx, user.ID, "missing-session")
require.ErrorIs(t, err, ErrPasskeyStepUpRequired)
- grant, err := service.CreatePasswordStepUpGrant(ctx, user.ID, session.ID)
+ grant, err := service.CreatePasswordStepUpGrant(ctx, user.ID, localSession.ID)
require.NoError(t, err)
require.NotEmpty(t, grant.Token)
require.True(t, grant.ExpiresAt.After(time.Now()))
- require.NoError(t, service.VerifyStepUpToken(ctx, user.ID, session.ID, grant.Token))
- require.NoError(t, service.VerifyStepUpToken(ctx, user.ID, session.ID, grant.Token))
+ require.NoError(t, service.VerifyStepUpToken(ctx, user.ID, localSession.ID, grant.Token))
+ require.NoError(t, service.VerifyStepUpToken(ctx, user.ID, localSession.ID, grant.Token))
require.ErrorIs(t, service.VerifyStepUpToken(ctx, user.ID, "other-session", grant.Token), ErrPasskeyStepUpRequired)
- require.NoError(t, sessionService.RevokeSession(ctx, session.ID))
- _, err = service.CreatePasswordStepUpGrant(ctx, user.ID, session.ID)
+ require.NoError(t, sessionService.RevokeSession(ctx, localSession.ID))
+ _, err = service.CreatePasswordStepUpGrant(ctx, user.ID, localSession.ID)
require.ErrorIs(t, err, ErrPasskeyStepUpRequired)
}
func TestPasskeyService_RecoveryCodeConsumptionIsAtomicAndSingleUse(t *testing.T) {
db := newPasskeyServiceTestDB(t)
service := newPasskeyServiceForTest(t, db)
- ctx := context.Background()
+ ctx := t.Context()
user := createPasskeyTestUser(t, db, "recovery-user")
codes, rows, err := generateRecoveryCodeRowsInternal(user.ID)
@@ -246,7 +245,7 @@ func TestPasskeyService_RecoveryCodeConsumptionIsAtomicAndSingleUse(t *testing.T
func TestPasskeyService_EnableAndDisableMFAManagesCodesAndSessions(t *testing.T) {
db := newPasskeyServiceTestDB(t)
service := newPasskeyServiceForTest(t, db)
- ctx := context.Background()
+ ctx := t.Context()
user := createPasskeyTestUser(t, db, "mfa-user")
createPasskeyTestCredential(t, db, service, user.ID, "mfa-passkey")
sessionService := session.NewSessionService(db)
@@ -289,7 +288,7 @@ func TestPasskeyService_EnableAndDisableMFAManagesCodesAndSessions(t *testing.T)
func TestPasskeyService_ResetMFARevokesSessionsAndPreservesPasskeys(t *testing.T) {
db := newPasskeyServiceTestDB(t)
service := newPasskeyServiceForTest(t, db)
- ctx := context.Background()
+ ctx := t.Context()
user := createPasskeyTestUser(t, db, "reset-user")
user.PasskeyMFAEnabled = true
require.NoError(t, db.Save(user).Error)
diff --git a/backend/internal/playwright/gitops.go b/backend/internal/playwright/gitops.go
index 0573e5af4..6d1102d18 100644
--- a/backend/internal/playwright/gitops.go
+++ b/backend/internal/playwright/gitops.go
@@ -43,16 +43,16 @@ func (ps *PlaywrightService) CreateTestGitOpsProject(ctx context.Context) error
}
// CreateSync already ran the initial sync; retry only if it failed.
if !created || sync.LastSyncStatus == nil || *sync.LastSyncStatus != "success" || sync.LastSyncError != nil {
- result, err := ps.syncService.PerformSync(ctx, "0", sync.ID, *actor)
- if err != nil {
- return fmt.Errorf("failed to sync GitOps test project: %w", err)
+ result, performSyncErr := ps.syncService.PerformSync(ctx, "0", sync.ID, *actor)
+ if performSyncErr != nil {
+ return fmt.Errorf("failed to sync GitOps test project: %w", performSyncErr)
}
if !result.Success {
return fmt.Errorf("GitOps test sync failed: %s", result.Message)
}
- sync, err = ps.syncService.GetSyncByID(ctx, "0", sync.ID)
- if err != nil {
- return err
+ sync, performSyncErr = ps.syncService.GetSyncByID(ctx, "0", sync.ID)
+ if performSyncErr != nil {
+ return performSyncErr
}
}
if sync.ProjectID == nil || sync.LastSyncCommit == nil || *sync.LastSyncCommit == "" || sync.LastSyncStatus == nil || *sync.LastSyncStatus != "success" || sync.LastSyncError != nil {
@@ -62,7 +62,11 @@ func (ps *PlaywrightService) CreateTestGitOpsProject(ctx context.Context) error
if err != nil {
return fmt.Errorf("failed to verify GitOps test project: %w", err)
}
- if details.Name != testProjectNameInternal || details.GitOpsManagedBy == nil || *details.GitOpsManagedBy != sync.ID || details.LastSyncCommit == nil || *details.LastSyncCommit != *sync.LastSyncCommit {
+ if details.Name != testProjectNameInternal ||
+ details.GitOpsManagedBy == nil ||
+ *details.GitOpsManagedBy != sync.ID ||
+ details.LastSyncCommit == nil ||
+ *details.LastSyncCommit != *sync.LastSyncCommit {
return errors.New("GitOps test project does not match its managed sync")
}
return nil
@@ -79,26 +83,26 @@ func (ps *PlaywrightService) ensureTestRepositoryInternal(ctx context.Context, a
if repository.Name != testRepositoryNameInternal {
continue
}
- updated, err := ps.repositoryService.UpdateRepository(ctx, repository.ID, gitopstypes.UpdateRepositoryRequest{
+ updated, updateRepositoryErr := ps.repositoryService.UpdateRepository(ctx, repository.ID, gitopstypes.UpdateRepositoryRequest{
Name: new(testRepositoryNameInternal), URL: new(testRepositoryURLInternal), AuthType: new("none"), Enabled: new(true),
}, actor)
- if err != nil {
- return "", err
+ if updateRepositoryErr != nil {
+ return "", updateRepositoryErr
}
repositoryID = updated.ID
break
}
if repositoryID == "" {
- created, err := ps.repositoryService.CreateRepository(ctx, gitopstypes.CreateRepositoryRequest{
+ created, createRepositoryErr := ps.repositoryService.CreateRepository(ctx, gitopstypes.CreateRepositoryRequest{
Name: testRepositoryNameInternal, URL: testRepositoryURLInternal, AuthType: "none", Enabled: new(true),
}, actor)
- if err != nil {
- return "", err
+ if createRepositoryErr != nil {
+ return "", createRepositoryErr
}
repositoryID = created.ID
}
- if err := ps.repositoryService.TestConnection(ctx, repositoryID, testBranchInternal, actor); err != nil {
- return "", fmt.Errorf("failed to connect to GitOps test repository: %w", err)
+ if testConnectionErr := ps.repositoryService.TestConnection(ctx, repositoryID, testBranchInternal, actor); testConnectionErr != nil {
+ return "", fmt.Errorf("failed to connect to GitOps test repository: %w", testConnectionErr)
}
return repositoryID, nil
}
@@ -113,12 +117,12 @@ func (ps *PlaywrightService) ensureTestSyncInternal(ctx context.Context, reposit
if sync.Name != testSyncNameInternal {
continue
}
- updated, err := ps.syncService.UpdateSync(ctx, "0", sync.ID, gitopstypes.UpdateSyncRequest{
+ updated, updateSyncErr := ps.syncService.UpdateSync(ctx, "0", sync.ID, gitopstypes.UpdateSyncRequest{
Name: new(testSyncNameInternal), RepositoryID: new(repositoryID), Branch: new(testBranchInternal), ComposePath: new(testComposePathInternal),
TargetType: new("project"), ProjectName: new(testProjectNameInternal), AutoSync: new(false), SyncDirectory: new(false), PullImageAfterSync: new(false), RedeployAfterSync: new(false),
}, actor)
- if err != nil {
- return nil, false, err
+ if updateSyncErr != nil {
+ return nil, false, updateSyncErr
}
return updated, false, nil
}
diff --git a/backend/internal/playwright/service.go b/backend/internal/playwright/service.go
index 7577fca25..ce9dea87a 100644
--- a/backend/internal/playwright/service.go
+++ b/backend/internal/playwright/service.go
@@ -26,7 +26,13 @@ type PlaywrightService struct {
projectService *project.ProjectService
}
-func NewPlaywrightService(apiKeyService *apikey.ApiKeyService, userService *user.UserService, repositoryService *gitrepo.GitRepositoryService, syncService *gitops.GitOpsSyncService, projectService *project.ProjectService) *PlaywrightService {
+func NewPlaywrightService(
+ apiKeyService *apikey.ApiKeyService,
+ userService *user.UserService,
+ repositoryService *gitrepo.GitRepositoryService,
+ syncService *gitops.GitOpsSyncService,
+ projectService *project.ProjectService,
+) *PlaywrightService {
return &PlaywrightService{
apiKeyService: apiKeyService,
userService: userService,
@@ -40,7 +46,7 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (
slog.Info("Playwright: Creating test API keys", "count", count)
// Get the arcane user to associate the API keys with
- user, err := ps.userService.GetUserByUsername(ctx, "arcane")
+ localUser, err := ps.userService.GetUserByUsername(ctx, "arcane")
if err != nil {
return nil, fmt.Errorf("failed to get arcane user: %w", err)
}
@@ -63,9 +69,9 @@ func (ps *PlaywrightService) CreateTestApiKeys(ctx context.Context, count int) (
Permissions: grants,
}
- apiKey, err := ps.apiKeyService.CreateApiKey(ctx, user.ID, authz.SudoPermissionSet(), req)
- if err != nil {
- return nil, fmt.Errorf("failed to create test API key %d: %w", i+1, err)
+ apiKey, createApiKeyErr := ps.apiKeyService.CreateApiKey(ctx, localUser.ID, authz.SudoPermissionSet(), req)
+ if createApiKeyErr != nil {
+ return nil, fmt.Errorf("failed to create test API key %d: %w", i+1, createApiKeyErr)
}
createdKeys = append(createdKeys, apiKey)
@@ -91,8 +97,8 @@ func (ps *PlaywrightService) DeleteAllTestApiKeys(ctx context.Context) error {
}
for _, apiKey := range apiKeys {
- if err := ps.apiKeyService.DeleteApiKey(ctx, apiKey.ID); err != nil {
- slog.Warn("Failed to delete test API key", "id", apiKey.ID, "error", err)
+ if deleteApiKeyErr := ps.apiKeyService.DeleteApiKey(ctx, apiKey.ID); deleteApiKeyErr != nil {
+ slog.Warn("Failed to delete test API key", "id", apiKey.ID, "error", deleteApiKeyErr)
}
}
diff --git a/backend/internal/port/service_test.go b/backend/internal/port/service_test.go
index 542bc3a10..98b91ead9 100644
--- a/backend/internal/port/service_test.go
+++ b/backend/internal/port/service_test.go
@@ -1,7 +1,6 @@
package port
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -57,7 +56,7 @@ func TestPortService_ListPortsPaginated_FlattensPublishedAndExposedPorts(t *test
},
}))
- items, page, err := svc.ListPortsPaginated(context.Background(), pagination.QueryParams{
+ items, page, err := svc.ListPortsPaginated(t.Context(), pagination.QueryParams{
Limit: 20,
})
require.NoError(t, err)
@@ -109,7 +108,7 @@ func TestPortService_ListPortsPaginated_SortsByHostPortWithUnpublishedLast(t *te
},
}))
- items, _, err := svc.ListPortsPaginated(context.Background(), pagination.QueryParams{
+ items, _, err := svc.ListPortsPaginated(t.Context(), pagination.QueryParams{
Sort: "hostPort",
Order: pagination.SortAsc,
Limit: 20,
@@ -154,7 +153,7 @@ func TestPortService_ListPortsPaginated_SortsByHostPortDescWithUnpublishedLast(t
},
}))
- items, _, err := svc.ListPortsPaginated(context.Background(), pagination.QueryParams{
+ items, _, err := svc.ListPortsPaginated(t.Context(), pagination.QueryParams{
Sort: "hostPort",
Order: pagination.SortDesc,
Limit: 20,
@@ -199,7 +198,7 @@ func TestPortService_ListPortsPaginated_SortsByHostIPDescWithUnpublishedLast(t *
},
}))
- items, _, err := svc.ListPortsPaginated(context.Background(), pagination.QueryParams{
+ items, _, err := svc.ListPortsPaginated(t.Context(), pagination.QueryParams{
Sort: "hostIp",
Order: pagination.SortDesc,
Limit: 20,
diff --git a/backend/internal/project/deployment.go b/backend/internal/project/deployment.go
index 4337e28b1..dbe648beb 100644
--- a/backend/internal/project/deployment.go
+++ b/backend/internal/project/deployment.go
@@ -83,17 +83,17 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID st
return err
}
if discoverTags {
- effective, _, err := s.loadComposeProjectForProjectInternal(ctx, proj, nil, servicesToUpdate...)
- if err != nil {
- return fmt.Errorf("load project for service image checks: %w", err)
+ effective, _, loadComposeProjectForProjectErr := s.loadComposeProjectForProjectInternal(ctx, proj, nil, servicesToUpdate...)
+ if loadComposeProjectForProjectErr != nil {
+ return fmt.Errorf("load project for service image checks: %w", loadComposeProjectForProjectErr)
}
- changes, err := s.projectServiceImageChangesInternal(ctx, proj, effective)
- if err != nil {
- return err
+ changes, loadComposeProjectForProjectErr := s.projectServiceImageChangesInternal(ctx, proj, effective)
+ if loadComposeProjectForProjectErr != nil {
+ return loadComposeProjectForProjectErr
}
if len(changes) > 0 {
- if _, err := s.persistProjectImageChangesInternal(ctx, projectID, changes); err != nil {
- return err
+ if _, persistProjectImageChangesErr := s.persistProjectImageChangesInternal(ctx, projectID, changes); persistProjectImageChangesErr != nil {
+ return persistProjectImageChangesErr
}
}
}
@@ -124,8 +124,8 @@ func (s *ProjectService) updateProjectServicesInternal(ctx context.Context, proj
defer s.eventService.BeginComposeSuppressionWindow(compProj.Name)()
// 2. Set status to deploying/restarting
- if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusDeploying); err != nil {
- return err
+ if updateProjectStatusErr := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusDeploying); updateProjectStatusErr != nil {
+ return updateProjectStatusErr
}
credentials, err := s.ResolveRegistryCredentials(ctx)
@@ -137,7 +137,7 @@ func (s *ProjectService) updateProjectServicesInternal(ctx context.Context, proj
}
progressWriter, _ := ctx.Value(dockerutil.ProgressWriterKey{}).(io.Writer)
- if err := s.composeCoordinator.UpdateServices(ctx, projecttypes.ComposeServiceUpdate{
+ if updateServicesErr := s.composeCoordinator.UpdateServices(ctx, projecttypes.ComposeServiceUpdate{
Project: compProj, Services: servicesToUpdate, Dependents: dependents, StoppedDependents: stoppedDependents,
Images: s.composeImageOperationsInternal(&user, credentials), Progress: progressWriter,
AuthConfigs: s.composeRegistryAuthConfigsInternal(ctx), WaitTimeout: timeouts.GetDuration(s.settingsService.GetSettingsConfig().DeployWaitTimeout.AsInt(), timeouts.DefaultDeployWait),
@@ -147,13 +147,13 @@ func (s *ProjectService) updateProjectServicesInternal(ctx context.Context, proj
}
},
Recover: func(ctx context.Context) { s.restoreProjectStatusAfterFailedDeployInternal(ctx, projectID) },
- }); err != nil {
- return err
+ }); updateServicesErr != nil {
+ return updateServicesErr
}
// 6. Finalize status
- if err := s.updateProjectStatusandCountsInternal(ctx, projectID, ProjectStatusRunning); err != nil {
- return err
+ if updateProjectStatusandCountsErr := s.updateProjectStatusandCountsInternal(ctx, projectID, ProjectStatusRunning); updateProjectStatusandCountsErr != nil {
+ return updateProjectStatusandCountsErr
}
metadata := database.JSON{
@@ -263,8 +263,8 @@ func ensureProjectBindDirectoryInternal(ctx context.Context, projectPath, source
return err
}
- if err := acfs.MkdirAll(ctx, projectPath, logicalPath, utils.DirPerm); err != nil {
- return kit.Ternary(errors.Is(err, acfs.ErrOutsideRoot), nil, err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, projectPath, logicalPath, utils.DirPerm); mkdirAllErr != nil {
+ return kit.Ternary(errors.Is(mkdirAllErr, acfs.ErrOutsideRoot), nil, mkdirAllErr)
}
slog.InfoContext(ctx, "created missing bind directory for project deployment", "projectPath", projectPath, "source", source)
return nil
@@ -294,11 +294,11 @@ func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, u
}
now := time.Now()
- if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{
+ if archiveProjectErr := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{
"is_archived": true,
"archived_at": now,
- }).Error; err != nil {
- return fmt.Errorf("failed to archive project: %w", err)
+ }).Error; archiveProjectErr != nil {
+ return fmt.Errorf("failed to archive project: %w", archiveProjectErr)
}
metadata := database.JSON{"action": "archived", "projectID": projectID, "projectName": proj.Name}
@@ -316,11 +316,11 @@ func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string,
return nil
}
- if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{
+ if unarchiveProjectErr := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{
"is_archived": false,
"archived_at": gorm.Expr("NULL"),
- }).Error; err != nil {
- return fmt.Errorf("failed to unarchive project: %w", err)
+ }).Error; unarchiveProjectErr != nil {
+ return fmt.Errorf("failed to unarchive project: %w", unarchiveProjectErr)
}
metadata := database.JSON{"action": "unarchived", "projectID": projectID, "projectName": proj.Name}
@@ -337,12 +337,12 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us
if projectFromDb != nil && projectFromDb.IsArchived {
return common.Classify(common.ErrProjectArchived, errors.New("project is archived and must be unarchived before this action"))
}
- if _, err := s.ResolveProjectComposeFile(ctx, projectFromDb); err != nil {
- return err
+ if _, resolveProjectComposeFileErr := s.ResolveProjectComposeFile(ctx, projectFromDb); resolveProjectComposeFileErr != nil {
+ return resolveProjectComposeFileErr
}
- if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusDeploying); err != nil {
- return fmt.Errorf("failed to update project status to deploying: %w", err)
+ if updateProjectStatusErr := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusDeploying); updateProjectStatusErr != nil {
+ return fmt.Errorf("failed to update project status to deploying: %w", updateProjectStatusErr)
}
var closeSuppression func()
defer func() {
@@ -356,7 +356,12 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us
ProjectID: projectID, ProjectPath: projectFromDb.Path, Options: options,
DefaultPullPolicy: s.settingsService.GetStringSetting(ctx, "defaultDeployPullPolicy", "missing"),
GitOpsManaged: projectFromDb.GitOpsManagedBy != nil && *projectFromDb.GitOpsManagedBy != "",
- WaitTimeout: timeouts.GetDuration(s.settingsService.GetSettingsConfig().DeployWaitTimeout.AsInt(), timeouts.DefaultDeployWait), AuthConfigs: s.composeRegistryAuthConfigsInternal(ctx), Progress: progressWriter,
+ WaitTimeout: timeouts.GetDuration(
+ s.settingsService.GetSettingsConfig().DeployWaitTimeout.AsInt(),
+ timeouts.DefaultDeployWait,
+ ), AuthConfigs: s.composeRegistryAuthConfigsInternal(
+ ctx,
+ ), Progress: progressWriter,
PreDeploy: func(ctx context.Context) error {
if s.lifecycleService == nil {
return nil
@@ -364,18 +369,18 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us
return s.lifecycleService.RunPreDeploy(ctx, projectFromDb, user)
},
Load: func(ctx context.Context) (*composetypes.Project, error) {
- model, _, err := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, prepareProjectBindDirectoriesInternal(projectFromDb.Path))
- if err == nil {
+ model, _, loadComposeProjectForProjectErr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, prepareProjectBindDirectoriesInternal(projectFromDb.Path))
+ if loadComposeProjectForProjectErr == nil {
closeSuppression = s.eventService.BeginComposeSuppressionWindow(model.Name)
}
- return model, err
+ return model, loadComposeProjectForProjectErr
},
ResolveImages: func(ctx context.Context) (projecttypes.ComposeImageOperations, error) {
- credentials, err := s.ResolveRegistryCredentials(ctx)
+ credentials, resolveRegistryCredentialsErr := s.ResolveRegistryCredentials(ctx)
operations := s.composeImageOperationsInternal(&user, credentials)
// Deployment pulls are recorded as system actions; builds retain the requesting actor.
operations.Pull = s.composeImageOperationsInternal(nil, credentials).Pull
- return operations, err
+ return operations, resolveRegistryCredentialsErr
},
Recover: func(ctx context.Context) { s.restoreProjectStatusAfterFailedDeployInternal(ctx, projectID) },
})
@@ -405,15 +410,15 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, user
return fmt.Errorf("failed to load compose project: %w", lerr)
}
- if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusStopped); err != nil {
- return fmt.Errorf("failed to update project status to stopping: %w", err)
+ if updateProjectStatusErr := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusStopped); updateProjectStatusErr != nil {
+ return fmt.Errorf("failed to update project status to stopping: %w", updateProjectStatusErr)
}
defer s.eventService.BeginComposeSuppressionWindow(proj.Name)()
- if err := projects.ComposeDown(ctx, proj, false); err != nil {
+ if composeDownErr := projects.ComposeDown(ctx, proj, false); composeDownErr != nil {
_ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)
- return fmt.Errorf("failed to bring down project: %w", err)
+ return fmt.Errorf("failed to bring down project: %w", composeDownErr)
}
metadata := database.JSON{
@@ -431,7 +436,22 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, user
// "-N" (the interactive default). When false a collision returns
// projects.ErrProjectDirExists (wrapped) so GitOps creates fail loudly instead of
// minting runaway "-N" duplicate projects on a broken binding.
-func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, manifest projecttypes.CreateProjectWorkspaceManifest, uploads map[int][]byte, uiTags []string, uiTagColors map[string]projecttypes.TagColor, user common.User, allowNameSuffixOptions ...bool) (*Project, error) {
+func (
+ s *ProjectService,
+) CreateProject(
+ ctx context.Context,
+ name, composeContent string,
+ envContent *string,
+ manifest projecttypes.CreateProjectWorkspaceManifest,
+ uploads map[int][]byte,
+ uiTags []string,
+ uiTagColors map[string]projecttypes.TagColor,
+ user common.User,
+ allowNameSuffixOptions ...bool,
+) (
+ *Project,
+ error,
+) {
normalizedUITags, err := projects.NormalizeProjectTags(uiTags)
if err != nil {
return nil, fmt.Errorf("invalid project tags: %w", err)
@@ -480,29 +500,39 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent
RunningCount: 0,
}
- if err := projects.ApplyProjectWorkspaceChanges(projectPath, manifest.FileChanges, uploads, projects.ProjectWorkspaceApplyOptions{
+ if applyProjectWorkspaceChangesErr := projects.ApplyProjectWorkspaceChanges(projectPath, manifest.FileChanges, uploads, projects.ProjectWorkspaceApplyOptions{
MaxDepth: s.config.ProjectWorkspaceMaxDepth,
MaxEntries: s.config.ProjectWorkspaceMaxEntries,
MaxFileSizeBytes: workspace.MaxFileSizeBytes(s.config.ProjectWorkspaceMaxFileSizeMB),
SkipDirectories: s.config.ProjectScanSkipDirs,
ComposeFileName: projects.DefaultComposeFileName,
- }); err != nil {
+ }); applyProjectWorkspaceChangesErr != nil {
_ = acfs.RemoveAll(context.WithoutCancel(ctx), projectsDirectory, projectLogical)
- return nil, wrapProjectWorkspaceErrorInternal(err)
+ return nil, wrapProjectWorkspaceErrorInternal(applyProjectWorkspaceChangesErr)
}
// GitOps-originated creates (allowNameSuffix=false) tolerate not-yet-supplied
// ${VAR} references the same way single-file git sync updates do; interactive
// creates (allowNameSuffix=true) stay strict.
- if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, projectPath, name, composeContent, envContent, nil, "", !allowNameSuffix); err != nil {
+ if validateComposeContentForUpdateErr := projects.ValidateComposeContentForUpdate(
+ ctx,
+ projectsDirectory,
+ projectPath,
+ name,
+ composeContent,
+ envContent,
+ nil,
+ "",
+ !allowNameSuffix,
+ ); validateComposeContentForUpdateErr != nil {
_ = acfs.RemoveAll(context.WithoutCancel(ctx), projectsDirectory, projectLogical)
- return nil, fmt.Errorf("invalid compose file: %w", err)
+ return nil, fmt.Errorf("invalid compose file: %w", validateComposeContentForUpdateErr)
}
- if err := projects.WriteProjectFiles(ctx, projectsDirectory, projectPath, composeContent, envContent); err != nil {
+ if writeProjectFilesErr := projects.WriteProjectFiles(ctx, projectsDirectory, projectPath, composeContent, envContent); writeProjectFilesErr != nil {
// Best-effort cleanup to restore pre-transaction behavior.
_ = acfs.RemoveAll(context.WithoutCancel(ctx), projectsDirectory, projectLogical)
- return nil, fmt.Errorf("failed to save project files: %w", err)
+ return nil, fmt.Errorf("failed to save project files: %w", writeProjectFilesErr)
}
composeMeta, err := projects.ParseArcaneComposeMetadata(
ctx,
@@ -516,18 +546,18 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent
}
normalizedUITags = excludeComposeOwnedUITagsInternal(normalizedUITags, composeMeta.ProjectTags)
- if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := tx.Create(proj).Error; err != nil {
- return err
+ if transactionErr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if createProjectErr := tx.Create(proj).Error; createProjectErr != nil {
+ return createProjectErr
}
return createUIProjectTagsInternal(tx, proj.ID, normalizedUITags, normalizedTagColors)
- }); err != nil {
+ }); transactionErr != nil {
_ = acfs.RemoveAll(context.WithoutCancel(ctx), projectsDirectory, projectLogical)
- return nil, fmt.Errorf("failed to create project: %w", err)
+ return nil, fmt.Errorf("failed to create project: %w", transactionErr)
}
s.refreshComposeProjectNameInternal(ctx, proj)
s.refreshProjectImageRefsInternal(ctx, proj)
- if err := s.reconcileComposeProjectTagsInternal(ctx, proj.ID, composeMeta.ProjectTags); err != nil {
+ if reconcileComposeProjectTagsErr := s.reconcileComposeProjectTagsInternal(ctx, proj.ID, composeMeta.ProjectTags); reconcileComposeProjectTagsErr != nil {
cleanupCtx := context.WithoutCancel(ctx)
databaseCleanupErr := s.db.WithContext(cleanupCtx).Transaction(func(tx *gorm.DB) error {
return deleteProjectWithTagsInternal(tx, proj.ID)
@@ -539,7 +569,7 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent
if fileCleanupErr != nil {
fileCleanupErr = fmt.Errorf("rollback project files after tag reconciliation failure: %w", fileCleanupErr)
}
- return nil, errors.Join(fmt.Errorf("reconcile Compose project tags: %w", err), databaseCleanupErr, fileCleanupErr)
+ return nil, errors.Join(fmt.Errorf("reconcile Compose project tags: %w", reconcileComposeProjectTagsErr), databaseCleanupErr, fileCleanupErr)
}
metadata := database.JSON{"action": "create", "projectID": proj.ID, "projectName": proj.Name, "path": projectPath}
@@ -565,8 +595,8 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, r
"projectName", proj.Name,
"projectPath", proj.Path)
- if err := s.DownProject(ctx, projectID, common.SystemUser); err != nil {
- slog.WarnContext(ctx, "failed to bring down project", "error", err)
+ if downProjectErr := s.DownProject(ctx, projectID, common.SystemUser); downProjectErr != nil {
+ slog.WarnContext(ctx, "failed to bring down project", "error", downProjectErr)
}
if removeVolumes {
@@ -584,17 +614,17 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, r
slog.DebugContext(ctx, "Removing project files", "path", proj.Path)
// An imported project can live anywhere, so the removal is rooted at the
// parent directory and names the project directory itself.
- if err := acfs.RemoveAll(ctx, filepath.Dir(proj.Path), "/"+filepath.Base(proj.Path)); err != nil {
- slog.ErrorContext(ctx, "Failed to remove project files", "path", proj.Path, "error", err)
- return fmt.Errorf("failed to remove project files: %w", err)
+ if removeAllErr := acfs.RemoveAll(ctx, filepath.Dir(proj.Path), "/"+filepath.Base(proj.Path)); removeAllErr != nil {
+ slog.ErrorContext(ctx, "Failed to remove project files", "path", proj.Path, "error", removeAllErr)
+ return fmt.Errorf("failed to remove project files: %w", removeAllErr)
}
slog.InfoContext(ctx, "Project files removed successfully", "path", proj.Path)
}
- if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if transactionErr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return deleteProjectWithTagsInternal(tx, projectID)
- }); err != nil {
- return fmt.Errorf("failed to delete project from database: %w", err)
+ }); transactionErr != nil {
+ return fmt.Errorf("failed to delete project from database: %w", transactionErr)
}
if !removeFiles {
@@ -603,8 +633,8 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, r
} else if projects.IsSafeSubdirectory(projectsDir, proj.Path) && filepath.Clean(projectsDir) != filepath.Clean(proj.Path) {
trashName := fmt.Sprintf("%s%s-%d", projects.ArcaneTrashPrefix, filepath.Base(proj.Path), time.Now().Unix())
trashPath := filepath.Join(filepath.Dir(proj.Path), trashName)
- if err := acfs.Rename(ctx, filepath.Dir(proj.Path), "/"+filepath.Base(proj.Path), "/"+trashName); err != nil {
- slog.WarnContext(ctx, "Failed to quarantine project files", "path", proj.Path, "trashPath", trashPath, "error", err)
+ if renameErr := acfs.Rename(ctx, filepath.Dir(proj.Path), "/"+filepath.Base(proj.Path), "/"+trashName); renameErr != nil {
+ slog.WarnContext(ctx, "Failed to quarantine project files", "path", proj.Path, "trashPath", trashPath, "error", renameErr)
} else {
slog.InfoContext(ctx, "Project files quarantined successfully", "path", proj.Path, "trashPath", trashPath)
}
@@ -624,8 +654,8 @@ func (s *ProjectService) RedeployProject(ctx context.Context, projectID string,
return err
}
- if _, err := s.ResolveProjectComposeFile(ctx, proj); err != nil {
- return err
+ if _, resolveProjectComposeFileErr := s.ResolveProjectComposeFile(ctx, proj); resolveProjectComposeFileErr != nil {
+ return resolveProjectComposeFileErr
}
disabled := s.projectRedeployDisabledInternal(ctx, *proj)
@@ -642,8 +672,8 @@ func (s *ProjectService) RedeployProject(ctx context.Context, projectID string,
if cerr != nil {
slog.WarnContext(ctx, "failed to resolve registry credentials for redeploy pull", "error", cerr)
}
- if err := s.PullProjectImages(ctx, projectID, progressWriter, user, credentials); err != nil {
- slog.WarnContext(ctx, "failed to pull project images", "error", err)
+ if pullProjectImagesErr := s.PullProjectImages(ctx, projectID, progressWriter, user, credentials); pullProjectImagesErr != nil {
+ slog.WarnContext(ctx, "failed to pull project images", "error", pullProjectImagesErr)
}
return s.DeployProject(ctx, projectID, user, options)
@@ -682,8 +712,8 @@ func (s *ProjectService) PullProjectImages(ctx context.Context, projectID string
defer s.eventService.BeginComposeSuppressionWindow(compProj.Name)()
for _, img := range projects.PullableImageRefs(compProj) {
- if err := s.pullAndReconcileImageInternal(ctx, img, progressWriter, user, credentials); err != nil {
- return err
+ if pullAndReconcileImageErr := s.pullAndReconcileImageInternal(ctx, img, progressWriter, user, credentials); pullAndReconcileImageErr != nil {
+ return pullAndReconcileImageErr
}
}
@@ -756,12 +786,12 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, s
if err != nil {
return err
}
- if _, err := s.ResolveProjectComposeFile(ctx, proj); err != nil {
- return err
+ if _, resolveProjectComposeFileErr := s.ResolveProjectComposeFile(ctx, proj); resolveProjectComposeFileErr != nil {
+ return resolveProjectComposeFileErr
}
- if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRestarting); err != nil {
- return fmt.Errorf("failed to update project status to restarting: %w", err)
+ if updateProjectStatusErr := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRestarting); updateProjectStatusErr != nil {
+ return fmt.Errorf("failed to update project status to restarting: %w", updateProjectStatusErr)
}
compProj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, proj, nil)
@@ -772,9 +802,9 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, s
defer s.eventService.BeginComposeSuppressionWindow(compProj.Name)()
- if err := projects.ComposeRestart(ctx, compProj, services); err != nil {
+ if composeRestartErr := projects.ComposeRestart(ctx, compProj, services); composeRestartErr != nil {
_ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)
- return fmt.Errorf("failed to restart project: %w", err)
+ return fmt.Errorf("failed to restart project: %w", composeRestartErr)
}
metadata := database.JSON{
diff --git a/backend/internal/project/details.go b/backend/internal/project/details.go
index 7b1261318..863a0e133 100644
--- a/backend/internal/project/details.go
+++ b/backend/internal/project/details.go
@@ -73,13 +73,13 @@ func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Contex
}
serviceCount, runningCount := getServiceCounts(services)
- if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{
+ if updateStatusErr := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{
"status": status,
"service_count": serviceCount,
"running_count": runningCount,
"updated_at": time.Now(),
- }).Error; err != nil {
- return fmt.Errorf("failed to update project status and counts: %w", err)
+ }).Error; updateStatusErr != nil {
+ return fmt.Errorf("failed to update project status and counts: %w", updateStatusErr)
}
return nil
}
@@ -272,8 +272,8 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string
}
var resp project.Details
- if err := mapping.MapStruct(proj, &resp); err != nil {
- return project.Details{}, fmt.Errorf("failed to map project: %w", err)
+ if mapStructErr := mapping.MapStruct(proj, &resp); mapStructErr != nil {
+ return project.Details{}, fmt.Errorf("failed to map project: %w", mapStructErr)
}
resp.CreatedAt = proj.CreatedAt.Format(time.RFC3339)
@@ -312,17 +312,17 @@ func (s *ProjectService) GetProjectDetails(ctx context.Context, projectID string
resp.ComposeFiles = composeSelectionRelativePathsInternal(proj.Path, composeSelection)
resp.ConfigurationError = projects.CheckProjectEnvAccess(ctx, projectsDir, proj.Path)
- if err := s.populateDetailsComposeContentInternal(ctx, proj, opts, composeSelection, &resp); err != nil {
- return project.Details{}, err
+ if populateDetailsComposeContentErr := s.populateDetailsComposeContentInternal(ctx, proj, opts, composeSelection, &resp); populateDetailsComposeContentErr != nil {
+ return project.Details{}, populateDetailsComposeContentErr
}
if opts.IncludeEnvState {
- envState, err := projects.ReadProjectEnvState(proj.Path)
- if err != nil {
- return project.Details{}, fmt.Errorf("failed to read project env state: %w", err)
+ envState, readProjectEnvStateErr := projects.ReadProjectEnvState(proj.Path)
+ if readProjectEnvStateErr != nil {
+ return project.Details{}, fmt.Errorf("failed to read project env state: %w", readProjectEnvStateErr)
}
- effectiveEnvContent, err := resolveStoredEffectiveEnvContentInternal(envState)
- if err != nil {
- return project.Details{}, err
+ effectiveEnvContent, readProjectEnvStateErr := resolveStoredEffectiveEnvContentInternal(envState)
+ if readProjectEnvStateErr != nil {
+ return project.Details{}, readProjectEnvStateErr
}
resp.EnvContent = effectiveEnvContent
}
@@ -599,7 +599,17 @@ func (s *ProjectService) enrichProjectsWithUpdateInfoInternal(
scoped := s.getProjectContainerUpdateInfoInternal(ctx, details)
for i := range details {
if services := servicesByProjectID[details[i].ID]; services != nil {
- details[i].UpdateInfo = BuildConfiguredUpdateInfo(details[i].ID, services, updateInfoByRef, recordsByProjectID[details[i].ID], configuredRuntimeServiceUpdateInfoInternal(services, details[i].RuntimeServices, scoped))
+ details[i].UpdateInfo = BuildConfiguredUpdateInfo(
+ details[i].ID,
+ services,
+ updateInfoByRef,
+ recordsByProjectID[details[i].ID],
+ configuredRuntimeServiceUpdateInfoInternal(
+ services,
+ details[i].RuntimeServices,
+ scoped,
+ ),
+ )
continue
}
refs := imageRefsByProjectID[details[i].ID]
@@ -610,7 +620,18 @@ func (s *ProjectService) enrichProjectsWithUpdateInfoInternal(
}
}
-func (s *ProjectService) resolveProjectUpdateServicesInternal(ctx context.Context, proj Project, env *projectMetadataEnvInternal, includeHidden bool, hiddenRuntimeServices, hiddenRuntimeRefs map[string]bool) ([]string, []composetypes.ServiceConfig) {
+func (
+ s *ProjectService,
+) resolveProjectUpdateServicesInternal(
+ ctx context.Context,
+ proj Project,
+ env *projectMetadataEnvInternal,
+ includeHidden bool,
+ hiddenRuntimeServices, hiddenRuntimeRefs map[string]bool,
+) (
+ []string,
+ []composetypes.ServiceConfig,
+) {
composeProject, err := s.getCachedComposeProjectInternal(ctx, &proj, env)
if err != nil {
slog.WarnContext(ctx, "failed to resolve project services for update summary", "projectID", proj.ID, "projectName", proj.Name, "error", err)
@@ -649,7 +670,13 @@ func groupUpdateRecordsByProjectInternal(records []imageupdate.ImageUpdateRecord
}
// BuildConfiguredUpdateInfo matches checks to current services and aggregates their results.
-func BuildConfiguredUpdateInfo(projectID string, services []composetypes.ServiceConfig, byRef map[string]*imagetypes.UpdateInfo, records []imageupdate.ImageUpdateRecord, runtimeUpdates ...map[string]*imagetypes.UpdateInfo) *project.UpdateInfo {
+func BuildConfiguredUpdateInfo(
+ projectID string,
+ services []composetypes.ServiceConfig,
+ byRef map[string]*imagetypes.UpdateInfo,
+ records []imageupdate.ImageUpdateRecord,
+ runtimeUpdates ...map[string]*imagetypes.UpdateInfo,
+) *project.UpdateInfo {
checks := make(map[string]*imageupdate.ImageUpdateRecord)
for i := range records {
if records[i].ProjectID == projectID {
@@ -675,7 +702,23 @@ func BuildConfiguredUpdateInfo(projectID string, services []composetypes.Service
}
if len(runtimeUpdates) > 0 && runtimeUpdates[0][service.Name] != nil {
- info = mergeProjectContainerUpdateInfoInternal(nil, []project.RuntimeService{{ContainerID: "preview", Image: imageRef}, {ContainerID: "runtime", Image: imageRef}}, map[string]*imagetypes.UpdateInfo{"preview": info, "runtime": runtimeUpdates[0][service.Name]})[imageRef]
+ info = mergeProjectContainerUpdateInfoInternal(
+ nil,
+ []project.RuntimeService{
+ {
+ ContainerID: "preview",
+ Image: imageRef,
+ },
+ {
+ ContainerID: "runtime",
+ Image: imageRef,
+ },
+ },
+ map[string]*imagetypes.UpdateInfo{
+ "preview": info,
+ "runtime": runtimeUpdates[0][service.Name],
+ },
+ )[imageRef]
}
serviceUpdates[service.Name] = project.ServiceUpdateInfo{ImageRef: imageRef, UpdateInfo: info}
selected[service.Name] = info
@@ -969,9 +1012,9 @@ func (s *ProjectService) StreamProjectLogs(ctx context.Context, projectID string
// Writer goroutine: compose logs -> pipe
go func() {
- err := projects.ComposeLogs(ctx, projects.NormalizeProjectName(proj.Name), pw, follow, tail, since, timestamps)
+ composeLogsErr := projects.ComposeLogs(ctx, projects.NormalizeProjectName(proj.Name), pw, follow, tail, since, timestamps)
_ = pw.Close()
- done <- err
+ done <- composeLogsErr
}()
// Wait for both goroutines to finish to avoid sending on a closed channel
diff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.go
index 92df5b476..1829c973c 100644
--- a/backend/internal/project/handler.go
+++ b/backend/internal/project/handler.go
@@ -420,7 +420,7 @@ func (h *ProjectHandler) ListProjects(ctx context.Context, input *ListProjectsIn
// GetProjectStatusCounts returns counts of projects by status.
func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetProjectStatusCountsInput) (*handlerutil.Out[projecttypes.StatusCounts], error) {
- _, running, stopped, total, archived, err := h.projectService.GetProjectStatusCounts(ctx)
+ counts, err := h.projectService.GetProjectStatusCounts(ctx)
if err != nil {
return nil, huma.Error500InternalServerError("Failed to get project status counts: " + err.Error())
}
@@ -428,12 +428,7 @@ func (h *ProjectHandler) GetProjectStatusCounts(ctx context.Context, input *GetP
return &handlerutil.Out[projecttypes.StatusCounts]{
Body: base.ApiResponse[projecttypes.StatusCounts]{
Success: true,
- Data: projecttypes.StatusCounts{
- RunningProjects: running,
- StoppedProjects: stopped,
- TotalProjects: total,
- ArchivedProjects: archived,
- },
+ Data: counts,
},
}, nil
}
@@ -587,7 +582,8 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject
return nil, err
}
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
ActivityType: activitytypes.TypeProjectDeploy,
Step: "Starting deployment",
StartMessage: "Project deployment started",
@@ -608,16 +604,34 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu
}
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeProjectDown, "project", input.ProjectID, h.projectActivityNameInternal(runtimeCtx, input.ProjectID), user, "Stopping project", "Project stop requested", database.JSON{"projectID": input.ProjectID}, false)
+ activityID, runtimeCtx := activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ input.EnvironmentID,
+ activitytypes.TypeProjectDown,
+ "project",
+ input.ProjectID,
+ h.projectActivityNameInternal(
+ runtimeCtx,
+ input.ProjectID,
+ ),
+ user,
+ "Stopping project",
+ "Project stop requested",
+ database.JSON{
+ "projectID": input.ProjectID,
+ },
+ false,
+ )
activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Stopping project")
downCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)
- if err := h.projectService.DownProject(downCtx, input.ProjectID, *user); err != nil {
+ if downProjectErr := h.projectService.DownProject(downCtx, input.ProjectID, *user); downProjectErr != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", err)
- if errors.Is(err, common.ErrProjectArchived) || errors.Is(err, common.ErrProjectEnvUnreadable) {
- return nil, huma.Error400BadRequest(err.Error())
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", downProjectErr)
+ if errors.Is(downProjectErr, common.ErrProjectArchived) || errors.Is(downProjectErr, common.ErrProjectEnvUnreadable) {
+ return nil, huma.Error400BadRequest(downProjectErr.Error())
}
- return nil, huma.Error500InternalServerError("Failed to bring down project: " + err.Error())
+ return nil, huma.Error500InternalServerError("Failed to bring down project: " + downProjectErr.Error())
}
activitylib.FlushWriter(activityWriter)
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project stopped", nil)
@@ -699,7 +713,17 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
Metadata: database.JSON{"action": "create_project"},
}, func(runtimeCtx context.Context) error {
var createErr error
- proj, createErr = h.projectService.CreateProject(runtimeCtx, projectInput.Name, projectInput.ComposeContent, projectInput.EnvContent, manifest, uploads, projectInput.Tags, projectInput.TagColors, *user)
+ proj, createErr = h.projectService.CreateProject(
+ runtimeCtx,
+ projectInput.Name,
+ projectInput.ComposeContent,
+ projectInput.EnvContent,
+ manifest,
+ uploads,
+ projectInput.Tags,
+ projectInput.TagColors,
+ *user,
+ )
return createErr
})
if err != nil {
@@ -710,7 +734,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProject
}
var response projecttypes.CreateReponse
- if err := mapping.MapStruct(proj, &response); err != nil {
+ if mapStructErr := mapping.MapStruct(proj, &response); mapStructErr != nil {
return nil, huma.Error500InternalServerError("failed to map response")
}
response.Status = string(proj.Status)
@@ -808,7 +832,8 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro
return nil, err
}
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
ActivityType: activitytypes.TypeProjectRedeploy,
Step: "Starting redeploy",
StartMessage: "Project redeploy started",
@@ -845,13 +870,33 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje
}
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeProjectDestroy, "project", input.ProjectID, h.projectActivityNameInternal(runtimeCtx, input.ProjectID), user, "Destroying project", "Project destroy requested", database.JSON{"projectID": input.ProjectID, "removeFiles": removeFiles, "removeVolumes": removeVolumes}, false)
+ activityID, runtimeCtx := activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ input.EnvironmentID,
+ activitytypes.TypeProjectDestroy,
+ "project",
+ input.ProjectID,
+ h.projectActivityNameInternal(
+ runtimeCtx,
+ input.ProjectID,
+ ),
+ user,
+ "Destroying project",
+ "Project destroy requested",
+ database.JSON{
+ "projectID": input.ProjectID,
+ "removeFiles": removeFiles,
+ "removeVolumes": removeVolumes,
+ },
+ false,
+ )
activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Destroying project")
destroyCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)
- if err := h.projectService.DestroyProject(destroyCtx, input.ProjectID, removeFiles, removeVolumes, *user); err != nil {
+ if destroyProjectErr := h.projectService.DestroyProject(destroyCtx, input.ProjectID, removeFiles, removeVolumes, *user); destroyProjectErr != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", err)
- return nil, huma.Error500InternalServerError("Failed to destroy project: " + err.Error())
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", destroyProjectErr)
+ return nil, huma.Error500InternalServerError("Failed to destroy project: " + destroyProjectErr.Error())
}
activitylib.FlushWriter(activityWriter)
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Project destroyed", nil)
@@ -1044,17 +1089,47 @@ func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, e
projectName := h.projectActivityNameInternal(runtimeCtx, projectID)
var activityID string
if cfg.Queue {
- activityID, runtimeCtx = activitylib.StartHandlerActivity(runtimeCtx, h.activityService, environmentID, cfg.ActivityType, "project", projectID, projectName, user, cfg.Step, cfg.StartMessage, database.JSON{"projectID": projectID}, true)
+ activityID, runtimeCtx = activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ environmentID,
+ cfg.ActivityType,
+ "project",
+ projectID,
+ projectName,
+ user,
+ cfg.Step,
+ cfg.StartMessage,
+ database.JSON{
+ "projectID": projectID,
+ },
+ true,
+ )
activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, environmentID)
} else {
- activityID, runtimeCtx = activitylib.StartHandlerActivity(runtimeCtx, h.activityService, environmentID, cfg.ActivityType, "project", projectID, projectName, user, cfg.Step, cfg.StartMessage, database.JSON{"projectID": projectID}, false)
+ activityID, runtimeCtx = activitylib.StartHandlerActivity(
+ runtimeCtx,
+ h.activityService,
+ environmentID,
+ cfg.ActivityType,
+ "project",
+ projectID,
+ projectName,
+ user,
+ cfg.Step,
+ cfg.StartMessage,
+ database.JSON{
+ "projectID": projectID,
+ },
+ false,
+ )
}
activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, cfg.WriterStep)
actionCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)
- if err := cfg.Action(actionCtx, projectID, *user); err != nil {
+ if actionErr := cfg.Action(actionCtx, projectID, *user); actionErr != nil {
activitylib.FlushWriter(activityWriter)
- activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.FailureMessage, err)
- return base.MessageResponse{}, cfg.Error(err)
+ activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.FailureMessage, actionErr)
+ return base.MessageResponse{}, cfg.Error(actionErr)
}
activitylib.FlushWriter(activityWriter)
activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.SuccessComplete, nil)
@@ -1075,11 +1150,11 @@ func (h *ProjectHandler) ArchiveProject(ctx context.Context, input *ArchiveProje
return nil, err
}
- if err := h.projectService.ArchiveProject(ctx, input.ProjectID, *user); err != nil {
- if errors.Is(err, common.ErrProjectMustBeStopped) {
- return nil, huma.Error400BadRequest(err.Error())
+ if archiveProjectErr := h.projectService.ArchiveProject(ctx, input.ProjectID, *user); archiveProjectErr != nil {
+ if errors.Is(archiveProjectErr, common.ErrProjectMustBeStopped) {
+ return nil, huma.Error400BadRequest(archiveProjectErr.Error())
}
- return nil, huma.Error500InternalServerError("Failed to archive project: " + err.Error())
+ return nil, huma.Error500InternalServerError("Failed to archive project: " + archiveProjectErr.Error())
}
return &handlerutil.Out[base.MessageResponse]{
@@ -1100,8 +1175,8 @@ func (h *ProjectHandler) UnarchiveProject(ctx context.Context, input *UnarchiveP
return nil, err
}
- if err := h.projectService.UnarchiveProject(ctx, input.ProjectID, *user); err != nil {
- return nil, huma.Error500InternalServerError("Failed to unarchive project: " + err.Error())
+ if unarchiveProjectErr := h.projectService.UnarchiveProject(ctx, input.ProjectID, *user); unarchiveProjectErr != nil {
+ return nil, huma.Error500InternalServerError("Failed to unarchive project: " + unarchiveProjectErr.Error())
}
return &handlerutil.Out[base.MessageResponse]{
@@ -1123,7 +1198,8 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje
return nil, err
}
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
ActivityType: activitytypes.TypeProjectPull,
Step: "Pulling project images",
StartMessage: "Project image pull started",
@@ -1155,7 +1231,8 @@ func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildPro
options.Load = input.Body.Load
}
- return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx
+ return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{
ActivityType: activitytypes.TypeProjectBuild,
Step: "Building project images",
StartMessage: "Project image build started",
@@ -1190,8 +1267,32 @@ func registerProjectWorkspaceRoutesInternal(api huma.API, h *ProjectHandler) {
basePath := "/environments/{id}/projects/{projectId}/workspace"
tag := "Project Workspace"
handlerutil.RegisterSecured(api, handlerutil.Operation("get-project-workspace", http.MethodGet, basePath, "Get project workspace", "", tag), authz.PermProjectsRead, h.GetProjectWorkspace)
- handlerutil.RegisterSecured(api, handlerutil.Operation("get-project-workspace-file", http.MethodGet, basePath+"/file", "Get project workspace file", "", tag), authz.PermProjectsRead, h.GetProjectWorkspaceFile)
- handlerutil.RegisterSecured(api, handlerutil.Operation("download-project-workspace-file", http.MethodGet, basePath+"/file/download", "Download project workspace file", "", tag), authz.PermProjectsRead, h.DownloadProjectWorkspaceFile)
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "get-project-workspace-file",
+ http.MethodGet,
+ basePath+"/file",
+ "Get project workspace file",
+ "",
+ tag,
+ ),
+ authz.PermProjectsRead,
+ h.GetProjectWorkspaceFile,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "download-project-workspace-file",
+ http.MethodGet,
+ basePath+"/file/download",
+ "Download project workspace file",
+ "",
+ tag,
+ ),
+ authz.PermProjectsRead,
+ h.DownloadProjectWorkspaceFile,
+ )
updateOperation := handlerutil.Operation("update-project-workspace", http.MethodPut, basePath, "Update project workspace", "", tag)
updateOperation.RequestBody = handlerutil.WorkspaceMultipartRequestBody("JSON encoded project workspace manifest")
handlerutil.RegisterSecured(api, updateOperation, authz.PermProjectsUpdate, h.UpdateProjectWorkspace)
@@ -1258,7 +1359,10 @@ func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *Upda
var result *workspacetypes.Workspace
runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)
activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{
- EnvironmentID: input.EnvironmentID, Type: activitytypes.TypeResourceAction, ResourceType: "project", ResourceID: input.ProjectID, ResourceName: h.projectActivityNameInternal(runtimeCtx, input.ProjectID), User: user,
+ EnvironmentID: input.EnvironmentID, Type: activitytypes.TypeResourceAction, ResourceType: "project", ResourceID: input.ProjectID, ResourceName: h.projectActivityNameInternal(
+ runtimeCtx,
+ input.ProjectID,
+ ), User: user,
Step: "Updating project workspace", Message: "Updating project workspace", SuccessMessage: "Project workspace updated successfully",
Metadata: database.JSON{"action": "update_project_workspace", "fileChangeCount": len(manifest.FileChanges)},
}, func(runtimeCtx context.Context) error {
diff --git a/backend/internal/project/lifecycle.go b/backend/internal/project/lifecycle.go
index efc8ddb8f..f21a8b8ab 100644
--- a/backend/internal/project/lifecycle.go
+++ b/backend/internal/project/lifecycle.go
@@ -89,7 +89,13 @@ type LifecycleService struct {
// infrastructure. The Docker client is obtained lazily on each hook run via
// dockerService.GetClient so reconnects are transparent. Runner image pulls go
// through imageService so configured registry credentials apply.
-func NewLifecycleService(db *database.DB, settingsService *settings.SettingsService, eventService *event.EventService, dockerService *docker.DockerClientService, imageService *image.ImageService) *LifecycleService {
+func NewLifecycleService(
+ db *database.DB,
+ settingsService *settings.SettingsService,
+ eventService *event.EventService,
+ dockerService *docker.DockerClientService,
+ imageService *image.ImageService,
+) *LifecycleService {
return &LifecycleService{
db: db,
settingsService: settingsService,
@@ -222,8 +228,8 @@ func (s *LifecycleService) runScriptInContainerInternal(
return "", "", 0, fmt.Errorf("failed to connect to Docker: %w", dErr)
}
- if err := s.ensureRunnerImageInternal(ctx, dockerClient, runnerImage, actor); err != nil {
- return "", "", 0, fmt.Errorf("failed to ensure runner image %s: %w", runnerImage, err)
+ if ensureRunnerImageErr := s.ensureRunnerImageInternal(ctx, dockerClient, runnerImage, actor); ensureRunnerImageErr != nil {
+ return "", "", 0, fmt.Errorf("failed to ensure runner image %s: %w", runnerImage, ensureRunnerImageErr)
}
// Resolve the workspace mount. When Arcane runs inside a container whose
@@ -298,8 +304,8 @@ func (s *LifecycleService) runScriptInContainerInternal(
startCtx, startCancel := context.WithTimeout(ctx, timeouts.GetDuration(apiTimeoutSec, timeouts.DefaultDockerAPI))
defer startCancel()
- if _, err := dockerClient.ContainerStart(startCtx, containerID, client.ContainerStartOptions{}); err != nil {
- return "", "", 0, fmt.Errorf("start lifecycle container: %w", err)
+ if _, containerStartErr := dockerClient.ContainerStart(startCtx, containerID, client.ContainerStartOptions{}); containerStartErr != nil {
+ return "", "", 0, fmt.Errorf("start lifecycle container: %w", containerStartErr)
}
logsCtx, logsCancel := context.WithCancel(ctx)
@@ -357,8 +363,8 @@ func (s *LifecycleService) runScriptInContainerInternal(
// pulling it on a miss. The pull is delegated to the image service so the
// configured registry credentials (and its anonymous retry) apply, bounded by
// the dockerImagePullTimeout setting so operators on slow networks can tune it.
-func (s *LifecycleService) ensureRunnerImageInternal(ctx context.Context, dockerClient *client.Client, image string, actor common.User) error {
- if _, err := dockerClient.ImageInspect(ctx, image); err == nil {
+func (s *LifecycleService) ensureRunnerImageInternal(ctx context.Context, dockerClient *client.Client, imageName string, actor common.User) error {
+ if _, err := dockerClient.ImageInspect(ctx, imageName); err == nil {
return nil
}
if s.imageService == nil {
@@ -369,11 +375,11 @@ func (s *LifecycleService) ensureRunnerImageInternal(ctx context.Context, docker
pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(pullTimeoutSec, timeouts.DefaultDockerImagePull))
defer pullCancel()
- if err := s.imageService.PullImage(pullCtx, image, io.Discard, actor, nil); err != nil {
+ if err := s.imageService.PullImage(pullCtx, imageName, io.Discard, actor, nil); err != nil {
if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {
- return fmt.Errorf("runner image pull timed out for %s (increase dockerImagePullTimeout setting if needed)", image)
+ return fmt.Errorf("runner image pull timed out for %s (increase dockerImagePullTimeout setting if needed)", imageName)
}
- return fmt.Errorf("pull runner image %s: %w", image, err)
+ return fmt.Errorf("pull runner image %s: %w", imageName, err)
}
return nil
}
diff --git a/backend/internal/project/lifecycle_test.go b/backend/internal/project/lifecycle_test.go
index 8596c81ba..f392dce87 100644
--- a/backend/internal/project/lifecycle_test.go
+++ b/backend/internal/project/lifecycle_test.go
@@ -34,11 +34,11 @@ func setupLifecycleTestDB(t *testing.T) *database.DB {
func newLifecycleTestService(t *testing.T, db *database.DB) (*LifecycleService, *settings.SettingsService) {
t.Helper()
- settings, err := settings.NewSettingsService(t.Context(), db)
+ settingsService, err := settings.NewSettingsService(t.Context(), db)
require.NoError(t, err)
- t.Cleanup(func() { require.NoError(t, settings.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, settingsService.Stop(context.WithoutCancel(t.Context()))) })
events := event.NewEventService(db, nil, nil)
- return NewLifecycleService(db, settings, events, nil, nil), settings
+ return NewLifecycleService(db, settingsService, events, nil, nil), settingsService
}
func writeLifecycleProjectDirWithScript(t *testing.T, scriptRel, scriptBody string) string {
@@ -238,20 +238,20 @@ func TestCombineLifecycleOutput(t *testing.T) {
func TestRunPreDeploy_NilProject(t *testing.T) {
db := setupLifecycleTestDB(t)
svc, _ := newLifecycleTestService(t, db)
- require.NoError(t, svc.RunPreDeploy(context.Background(), nil, common.User{}))
+ require.NoError(t, svc.RunPreDeploy(t.Context(), nil, common.User{}))
}
func TestRunPreDeploy_ProjectNotGitOpsManaged(t *testing.T) {
db := setupLifecycleTestDB(t)
- svc, settings := newLifecycleTestService(t, db)
- require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleEnabled", "true"))
+ svc, settingsService := newLifecycleTestService(t, db)
+ require.NoError(t, settingsService.SetStringSetting(t.Context(), "lifecycleEnabled", "true"))
project := &Project{
Name: "demo",
Path: t.TempDir(),
GitOpsManagedBy: nil,
}
- require.NoError(t, svc.RunPreDeploy(context.Background(), project, common.User{}))
+ require.NoError(t, svc.RunPreDeploy(t.Context(), project, common.User{}))
}
func TestRunPreDeploy_KillSwitchDisabled(t *testing.T) {
@@ -284,13 +284,13 @@ func TestRunPreDeploy_KillSwitchDisabled(t *testing.T) {
sync.ID = syncID
require.NoError(t, db.Create(sync).Error)
- require.NoError(t, svc.RunPreDeploy(context.Background(), project, common.User{}))
+ require.NoError(t, svc.RunPreDeploy(t.Context(), project, common.User{}))
}
func TestRunPreDeploy_NoScriptConfigured(t *testing.T) {
db := setupLifecycleTestDB(t)
- svc, settings := newLifecycleTestService(t, db)
- require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleEnabled", "true"))
+ svc, settingsService := newLifecycleTestService(t, db)
+ require.NoError(t, settingsService.SetStringSetting(t.Context(), "lifecycleEnabled", "true"))
syncID := "sync-1"
project := &Project{
@@ -314,14 +314,14 @@ func TestRunPreDeploy_NoScriptConfigured(t *testing.T) {
sync.ID = syncID
require.NoError(t, db.Create(sync).Error)
- require.NoError(t, svc.RunPreDeploy(context.Background(), project, common.User{}))
+ require.NoError(t, svc.RunPreDeploy(t.Context(), project, common.User{}))
}
func TestRunPreDeploy_MissingRunnerImage(t *testing.T) {
db := setupLifecycleTestDB(t)
- svc, settings := newLifecycleTestService(t, db)
- require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleEnabled", "true"))
- require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleDefaultRunnerImage", " "))
+ svc, settingsService := newLifecycleTestService(t, db)
+ require.NoError(t, settingsService.SetStringSetting(t.Context(), "lifecycleEnabled", "true"))
+ require.NoError(t, settingsService.SetStringSetting(t.Context(), "lifecycleDefaultRunnerImage", " "))
syncID := "sync-1"
projectDir := writeLifecycleProjectDirWithScript(t, "pre-deploy.sh", "echo hi\n")
@@ -348,28 +348,28 @@ func TestRunPreDeploy_MissingRunnerImage(t *testing.T) {
sync.ID = syncID
require.NoError(t, db.Create(sync).Error)
- err := svc.RunPreDeploy(context.Background(), project, common.User{})
+ err := svc.RunPreDeploy(t.Context(), project, common.User{})
require.Error(t, err)
assert.Contains(t, err.Error(), "runner image")
}
func TestResolveRunnerImage_UsesSettingDefault(t *testing.T) {
db := setupLifecycleTestDB(t)
- svc, settings := newLifecycleTestService(t, db)
- require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleDefaultRunnerImage", "alpine:latest"))
+ svc, settingsService := newLifecycleTestService(t, db)
+ require.NoError(t, settingsService.SetStringSetting(t.Context(), "lifecycleDefaultRunnerImage", "alpine:latest"))
- assert.Equal(t, "alpine:latest", svc.resolveRunnerImageInternal(context.Background(), &GitOpsSync{}))
+ assert.Equal(t, "alpine:latest", svc.resolveRunnerImageInternal(t.Context(), &GitOpsSync{}))
override := "debian:stable-slim"
- assert.Equal(t, override, svc.resolveRunnerImageInternal(context.Background(), &GitOpsSync{
+ assert.Equal(t, override, svc.resolveRunnerImageInternal(t.Context(), &GitOpsSync{
PreDeployRunnerImage: &override,
}))
}
func TestRunPreDeploy_PathTraversalRejected(t *testing.T) {
db := setupLifecycleTestDB(t)
- svc, settings := newLifecycleTestService(t, db)
- require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleEnabled", "true"))
+ svc, settingsService := newLifecycleTestService(t, db)
+ require.NoError(t, settingsService.SetStringSetting(t.Context(), "lifecycleEnabled", "true"))
syncID := "sync-1"
project := &Project{
@@ -397,14 +397,14 @@ func TestRunPreDeploy_PathTraversalRejected(t *testing.T) {
sync.ID = syncID
require.NoError(t, db.Create(sync).Error)
- err := svc.RunPreDeploy(context.Background(), project, common.User{})
+ err := svc.RunPreDeploy(t.Context(), project, common.User{})
require.Error(t, err)
assert.Contains(t, err.Error(), "script path")
}
func TestLoadGitOpsSyncForProject_ReturnsNilWhenAbsent(t *testing.T) {
db := setupLifecycleTestDB(t)
- sync, err := loadGitOpsSyncForProjectInternal(context.Background(), db, "nonexistent")
+ sync, err := loadGitOpsSyncForProjectInternal(t.Context(), db, "nonexistent")
require.NoError(t, err)
assert.Nil(t, sync)
}
@@ -426,7 +426,7 @@ func TestPersistLastRun_UpdatesGitOpsSyncRow(t *testing.T) {
require.NoError(t, db.Create(sync).Error)
now := time.Now().UTC().Truncate(time.Second)
- svc.persistLastRunInternal(context.Background(), sync.ID, lifecycleStatusSuccess, "all good", now)
+ svc.persistLastRunInternal(t.Context(), sync.ID, lifecycleStatusSuccess, "all good", now)
var got GitOpsSync
require.NoError(t, db.Where("id = ?", sync.ID).First(&got).Error)
diff --git a/backend/internal/project/listing.go b/backend/internal/project/listing.go
index 5a23736dc..50331a1c7 100644
--- a/backend/internal/project/listing.go
+++ b/backend/internal/project/listing.go
@@ -199,21 +199,19 @@ func incrementStatusCounts(status ProjectStatus, running, stopped *int) {
}
}
-func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCount, runningProjects, stoppedProjects, totalProjects, archivedProjects int, err error) {
- folderCount, _ = s.countProjectFolders(ctx)
+func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (project.StatusCounts, error) {
+ counts := project.StatusCounts{}
var projectsList []Project
- if err := s.db.WithContext(ctx).Find(&projectsList).Error; err != nil {
- return folderCount, 0, 0, 0, 0, fmt.Errorf("failed to list projects: %w", err)
+ if listProjectsErr := s.db.WithContext(ctx).Find(&projectsList).Error; listProjectsErr != nil {
+ return counts, fmt.Errorf("failed to list projects: %w", listProjectsErr)
}
- totalProjects = len(projectsList)
- runningProjects = 0
- stoppedProjects = 0
+ counts.TotalProjects = len(projectsList)
activeProjects := make([]Project, 0, len(projectsList))
for _, p := range projectsList {
if p.IsArchived {
- archivedProjects++
+ counts.ArchivedProjects++
continue
}
activeProjects = append(activeProjects, p)
@@ -225,9 +223,9 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCoun
slog.ErrorContext(ctx, "Failed to list global compose containers for counts", "error", err)
// Fallback to DB status
for _, p := range activeProjects {
- incrementStatusCounts(p.Status, &runningProjects, &stoppedProjects)
+ incrementStatusCounts(p.Status, &counts.RunningProjects, &counts.StoppedProjects)
}
- return folderCount, runningProjects, stoppedProjects, totalProjects, archivedProjects, nil
+ return counts, nil
}
// 2. Group by project
@@ -252,10 +250,10 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCoun
status = calculateProjectStatus(services)
}
- incrementStatusCounts(status, &runningProjects, &stoppedProjects)
+ incrementStatusCounts(status, &counts.RunningProjects, &counts.StoppedProjects)
}
- return folderCount, runningProjects, stoppedProjects, totalProjects, archivedProjects, nil
+ return counts, nil
}
func (s *ProjectService) ListProjects(ctx context.Context, params pagination.QueryParams) ([]project.Details, pagination.Response, error) {
@@ -297,8 +295,8 @@ func (s *ProjectService) ListProjects(ctx context.Context, params pagination.Que
// Fetch live status concurrently for all projects
env := s.newProjectMetadataEnvInternal(ctx, projectsArray)
result := s.fetchProjectStatusConcurrently(ctx, projectsArray, env)
- if err := s.enrichProjectsWithTagsInternal(ctx, result); err != nil {
- return nil, pagination.Response{}, err
+ if enrichProjectsWithTagsErr := s.enrichProjectsWithTagsInternal(ctx, result); enrichProjectsWithTagsErr != nil {
+ return nil, pagination.Response{}, enrichProjectsWithTagsErr
}
s.enrichProjectsWithUpdateInfoInternal(ctx, projectsArray, result, true, env)
@@ -814,7 +812,18 @@ func (s *ProjectService) CountProjectsWithPendingUpdates(ctx context.Context, al
for i, proj := range activeProjects {
details[i].ID = proj.ID
for _, c := range lookupProjectContainersInternal(proj, containersByProject) {
- details[i].RuntimeServices = append(details[i].RuntimeServices, project.RuntimeService{Name: dockerutil.ComposeServiceLabel(c.Labels), ContainerID: c.ID, Image: c.Image, ImageID: c.ImageID, ContainerLabels: c.Labels})
+ details[i].RuntimeServices = append(
+ details[i].RuntimeServices,
+ project.RuntimeService{
+ Name: dockerutil.ComposeServiceLabel(
+ c.Labels,
+ ),
+ ContainerID: c.ID,
+ Image: c.Image,
+ ImageID: c.ImageID,
+ ContainerLabels: c.Labels,
+ },
+ )
}
}
s.enrichProjectsWithUpdateInfoInternal(ctx, activeProjects, details, false, nil)
@@ -936,8 +945,8 @@ func (s *ProjectService) applyProjectPresentationInternal(ctx context.Context, p
resp.ConfigurationError = projects.CheckProjectEnvAccess(ctx, metaEnv.projectsDirectory, projectsList[i].Path)
for k := range resp.RuntimeServices {
service := &resp.RuntimeServices[k]
- icon := resolveServiceIconInternal(catalog, service.ContainerLabels, service.Name, metas[i])
- service.IconLightURL, service.IconDarkURL = icon.IconLightURL, icon.IconDarkURL
+ localIcon := resolveServiceIconInternal(catalog, service.ContainerLabels, service.Name, metas[i])
+ service.IconLightURL, service.IconDarkURL = localIcon.IconLightURL, localIcon.IconDarkURL
}
}
}
@@ -1095,8 +1104,8 @@ func (s *ProjectService) ProjectMetadata(ctx context.Context, p Project, env *pr
if s.metaCache == nil || p.ID == "" {
return meta
}
- if err := s.metaCache.Set(p.ID, fingerprint, p.Path, env.projectsDirectory, composeFile, meta.ComposeFiles, meta.EnvFiles, meta); err != nil {
- slog.DebugContext(ctx, "failed to cache Compose metadata", "projectID", p.ID, "error", err)
+ if setErr := s.metaCache.Set(p.ID, fingerprint, p.Path, env.projectsDirectory, composeFile, meta.ComposeFiles, meta.EnvFiles, meta); setErr != nil {
+ slog.DebugContext(ctx, "failed to cache Compose metadata", "projectID", p.ID, "error", setErr)
}
return meta
diff --git a/backend/internal/project/model.go b/backend/internal/project/model.go
index d0542c364..877e40242 100644
--- a/backend/internal/project/model.go
+++ b/backend/internal/project/model.go
@@ -90,18 +90,19 @@ type GitOpsSync struct {
RepositoryID string `json:"repositoryId" sortable:"true"`
Branch string `json:"branch" sortable:"true" search:"branch,main,master,develop,feature,release"`
ComposePath string `json:"composePath" sortable:"true" search:"compose,docker-compose,path,file,yaml,yml"`
- TargetType string `json:"targetType" gorm:"column:target_type;default:'project'"` // "project" or "swarm_stack"
- ProjectName string `json:"projectName" sortable:"true" search:"project,name,stack,application,service"` // Name of project to create/update
- PreDeployNetworkMode string `json:"preDeployNetworkMode" gorm:"column:pre_deploy_network_mode;default:'none'"` // Docker network mode passed to the runner container. Default "none" denies network access; set to "bridge", "host", or a named network when the script needs it.
- SyncInterval int `json:"syncInterval" sortable:"true" search:"interval,frequency,schedule,cron,minutes"` // in minutes
- MaxSyncFiles int `json:"maxSyncFiles" gorm:"column:max_sync_files;default:500"` // 0 = unlimited; env var overrides take precedence
- MaxSyncTotalSize int64 `json:"maxSyncTotalSize" gorm:"column:max_sync_total_size;default:52428800"` // bytes; 0 = unlimited; env var overrides take precedence
- MaxSyncBinarySize int64 `json:"maxSyncBinarySize" gorm:"column:max_sync_binary_size;default:10485760"` // bytes; 0 = unlimited; env var overrides take precedence
- PreDeployTimeoutSec int `json:"preDeployTimeoutSec" gorm:"column:pre_deploy_timeout_sec;default:60"`
- AutoSync bool `json:"autoSync" sortable:"true" search:"auto,automatic,sync,continuous,scheduled"`
- SyncDirectory bool `json:"syncDirectory" gorm:"column:sync_directory"` // Sync entire directory containing compose file
- PullImageAfterSync bool `json:"pullImageAfterSync" gorm:"column:pull_image_after_sync;default:false"`
- RedeployAfterSync bool `json:"redeployAfterSync" gorm:"column:redeploy_after_sync;default:false"`
+ TargetType string `json:"targetType" gorm:"column:target_type;default:'project'"` // "project" or "swarm_stack"
+ ProjectName string `json:"projectName" sortable:"true" search:"project,name,stack,application,service"` // Name of project to create/update
+ // Docker network mode for the runner: "none" denies access; "bridge", "host", or a named network enables it.
+ PreDeployNetworkMode string `json:"preDeployNetworkMode" gorm:"column:pre_deploy_network_mode;default:'none'"`
+ SyncInterval int `json:"syncInterval" sortable:"true" search:"interval,frequency,schedule,cron,minutes"` // in minutes
+ MaxSyncFiles int `json:"maxSyncFiles" gorm:"column:max_sync_files;default:500"` // 0 = unlimited; env var overrides take precedence
+ MaxSyncTotalSize int64 `json:"maxSyncTotalSize" gorm:"column:max_sync_total_size;default:52428800"` // bytes; 0 = unlimited; env var overrides take precedence
+ MaxSyncBinarySize int64 `json:"maxSyncBinarySize" gorm:"column:max_sync_binary_size;default:10485760"` // bytes; 0 = unlimited; env var overrides take precedence
+ PreDeployTimeoutSec int `json:"preDeployTimeoutSec" gorm:"column:pre_deploy_timeout_sec;default:60"`
+ AutoSync bool `json:"autoSync" sortable:"true" search:"auto,automatic,sync,continuous,scheduled"`
+ SyncDirectory bool `json:"syncDirectory" gorm:"column:sync_directory"` // Sync entire directory containing compose file
+ PullImageAfterSync bool `json:"pullImageAfterSync" gorm:"column:pull_image_after_sync;default:false"`
+ RedeployAfterSync bool `json:"redeployAfterSync" gorm:"column:redeploy_after_sync;default:false"`
// Backup mode ("backup" commits saved project files to the repository;
// "deploy" is the original pull direction).
diff --git a/backend/internal/project/path_diagnostics_other.go b/backend/internal/project/path_diagnostics_other.go
index a4f17b614..36e19d5b1 100644
--- a/backend/internal/project/path_diagnostics_other.go
+++ b/backend/internal/project/path_diagnostics_other.go
@@ -5,7 +5,9 @@ package project
import "fmt"
func describeLifecyclePathAccessInternal(projectPath, resolvedScriptPath string) string {
- return fmt.Sprintf("Project path=%q, resolved script path=%q. Ensure the Arcane process can traverse every parent directory and inspect the script. A script being executable is not sufficient when ownership, ACLs, or mount permissions block access.", projectPath,
+ return fmt.Sprintf("Project path=%q, resolved script path=%q. Ensure the Arcane process can traverse every parent "+
+ "directory and inspect the script. A script being executable is not sufficient when ownership, ACLs, "+
+ "or mount permissions block access.", projectPath,
resolvedScriptPath,
)
}
diff --git a/backend/internal/project/service.go b/backend/internal/project/service.go
index ae2259961..4b5123435 100644
--- a/backend/internal/project/service.go
+++ b/backend/internal/project/service.go
@@ -74,29 +74,29 @@ type ProjectService struct {
// EnsureGitOpsProjectLinked persists the bidirectional GitOps/project binding
// and refreshes the compose-name cache as one domain operation.
-func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *GitOpsSync, project *Project) error {
- if sync == nil || project == nil {
+func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, gitOpsSync *GitOpsSync, project *Project) error {
+ if gitOpsSync == nil || project == nil {
return nil
}
- if project.GitOpsManagedBy != nil && *project.GitOpsManagedBy != "" && *project.GitOpsManagedBy != sync.ID {
+ if project.GitOpsManagedBy != nil && *project.GitOpsManagedBy != "" && *project.GitOpsManagedBy != gitOpsSync.ID {
return fmt.Errorf("project %s is already managed by a different GitOps sync", project.ID)
}
cacheBinding := func() {
s.composeNames.putInternal(projects.NormalizeProjectName(project.Name), project.ID)
}
- if sync.ProjectID != nil && *sync.ProjectID == project.ID && project.GitOpsManagedBy != nil && *project.GitOpsManagedBy == sync.ID {
+ if gitOpsSync.ProjectID != nil && *gitOpsSync.ProjectID == project.ID && project.GitOpsManagedBy != nil && *project.GitOpsManagedBy == gitOpsSync.ID {
cacheBinding()
return nil
}
updatesSync := map[string]any{}
updatesProject := map[string]any{}
- if sync.ProjectID == nil || *sync.ProjectID != project.ID {
+ if gitOpsSync.ProjectID == nil || *gitOpsSync.ProjectID != project.ID {
updatesSync["project_id"] = project.ID
}
- if project.GitOpsManagedBy == nil || *project.GitOpsManagedBy != sync.ID {
- updatesProject["gitops_managed_by"] = sync.ID
+ if project.GitOpsManagedBy == nil || *project.GitOpsManagedBy != gitOpsSync.ID {
+ updatesProject["gitops_managed_by"] = gitOpsSync.ID
}
if len(updatesSync) == 0 && len(updatesProject) == 0 {
cacheBinding()
@@ -105,13 +105,13 @@ func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *Gi
if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if len(updatesSync) > 0 {
- if err := tx.Model(&GitOpsSync{}).Where("id = ?", sync.ID).Updates(updatesSync).Error; err != nil {
- return fmt.Errorf("failed to relink GitOps sync %s: %w", sync.ID, err)
+ if err := tx.Model(&GitOpsSync{}).Where("id = ?", gitOpsSync.ID).Updates(updatesSync).Error; err != nil {
+ return fmt.Errorf("failed to relink GitOps sync %s: %w", gitOpsSync.ID, err)
}
}
if len(updatesProject) > 0 {
if err := tx.Model(&Project{}).Where("id = ?", project.ID).Updates(updatesProject).Error; err != nil {
- return fmt.Errorf("failed to relink project %s to GitOps sync %s: %w", project.ID, sync.ID, err)
+ return fmt.Errorf("failed to relink project %s to GitOps sync %s: %w", project.ID, gitOpsSync.ID, err)
}
}
return nil
@@ -119,8 +119,8 @@ func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *Gi
return err
}
- sync.ProjectID = &project.ID
- project.GitOpsManagedBy = &sync.ID
+ gitOpsSync.ProjectID = &project.ID
+ project.GitOpsManagedBy = &gitOpsSync.ID
cacheBinding()
return nil
}
@@ -152,18 +152,18 @@ func (s *ProjectService) ValidateComposeDirectory(ctx context.Context, projectNa
// CreateGitOpsManagedProject persists a promoted GitOps project, links both
// records, updates the compose-name cache, and records the creation event.
-func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, sync *GitOpsSync, project *Project, actor common.User, logEventOptions ...bool) error {
- if sync == nil || project == nil {
+func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, gitOpsSync *GitOpsSync, project *Project, actor common.User, logEventOptions ...bool) error {
+ if gitOpsSync == nil || project == nil {
return errors.New("GitOps sync and project are required")
}
if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
if err := tx.Create(project).Error; err != nil {
return fmt.Errorf("failed to create project: %w", err)
}
- if err := tx.Model(&GitOpsSync{}).Where("id = ?", sync.ID).Update("project_id", project.ID).Error; err != nil {
+ if err := tx.Model(&GitOpsSync{}).Where("id = ?", gitOpsSync.ID).Update("project_id", project.ID).Error; err != nil {
return fmt.Errorf("failed to update sync with project ID: %w", err)
}
- if err := tx.Model(&Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", sync.ID).Error; err != nil {
+ if err := tx.Model(&Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", gitOpsSync.ID).Error; err != nil {
return fmt.Errorf("failed to mark project as GitOps-managed: %w", err)
}
return nil
@@ -171,8 +171,8 @@ func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, sync *G
return err
}
- sync.ProjectID = &project.ID
- project.GitOpsManagedBy = &sync.ID
+ gitOpsSync.ProjectID = &project.ID
+ project.GitOpsManagedBy = &gitOpsSync.ID
s.composeNames.putInternal(projects.NormalizeProjectName(project.Name), project.ID)
if err := s.reconcileComposeTagsForProjectInternal(ctx, project); err != nil {
slog.WarnContext(ctx, "failed to reconcile Compose project tags during GitOps project creation", "projectID", project.ID, "error", err)
@@ -304,7 +304,24 @@ func (env *projectMetadataEnvInternal) composeFileInternal(projectID string, res
return path, nil
}
-func NewProjectService(db *database.DB, settingsService *settings.SettingsService, eventService *event.EventService, imageService *image.ImageService, dockerService *docker.DockerClientService, buildService buildServiceInternal, lifecycleService *LifecycleService, containerRegistryService *registry.ContainerRegistryService, cfg *config.Config, kvService *kv.KVService, registryCredentialsProvider func(context.Context) ([]containerregistry.Credential, error)) *ProjectService {
+func NewProjectService(
+ db *database.DB,
+ settingsService *settings.SettingsService,
+ eventService *event.EventService,
+ imageService *image.ImageService,
+ dockerService *docker.DockerClientService,
+ buildService buildServiceInternal,
+ lifecycleService *LifecycleService,
+ containerRegistryService *registry.ContainerRegistryService,
+ cfg *config.Config,
+ kvService *kv.KVService,
+ registryCredentialsProvider func(
+ context.Context,
+ ) (
+ []containerregistry.Credential,
+ error,
+ ),
+) *ProjectService {
return &ProjectService{
KVService: kvService,
RegistryCredentialsProvider: registryCredentialsProvider,
@@ -454,8 +471,8 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strin
return cachedProject, nil
}
- if err := s.rebuildComposeNameCacheInternal(ctx); err != nil {
- return nil, fmt.Errorf("failed to list projects by compose name: %w", err)
+ if rebuildComposeNameCacheErr := s.rebuildComposeNameCacheInternal(ctx); rebuildComposeNameCacheErr != nil {
+ return nil, fmt.Errorf("failed to list projects by compose name: %w", rebuildComposeNameCacheErr)
}
if cachedProject, found, cacheErr := s.lookupProjectByCachedComposeNameInternal(ctx, normalized); cacheErr != nil {
@@ -736,7 +753,26 @@ func (s *ProjectService) loadComposeProjectForProjectInternal(ctx context.Contex
pathMapper := s.projectPathMapperInternal(ctx)
- composeProject, loadErr := projects.LoadComposeProject(ctx, composeFileFullPath, projects.NormalizeProjectName(proj.Name), projectsDirectory, kit.ParseOrDefault(cfg.AutoInjectEnv.Value, false, strconv.ParseBool), pathMapper, nil, nil, false, nil, services, prepare)
+ composeProject, loadErr := projects.LoadComposeProject(
+ ctx,
+ composeFileFullPath,
+ projects.NormalizeProjectName(
+ proj.Name,
+ ),
+ projectsDirectory,
+ kit.ParseOrDefault(
+ cfg.AutoInjectEnv.Value,
+ false,
+ strconv.ParseBool,
+ ),
+ pathMapper,
+ nil,
+ nil,
+ false,
+ nil,
+ services,
+ prepare,
+ )
if loadErr != nil {
return nil, "", loadErr
}
@@ -759,7 +795,28 @@ func (s *ProjectService) getCachedComposeProjectInternal(ctx context.Context, pr
if err != nil {
return nil, err
}
- return projects.LoadCachedComposeProject(ctx, s.parsedCompose, proj.ID, proj.Path, composePath, projects.NormalizeProjectName(proj.Name), getProjectsDirectoryOrDefaultInternal(ctx, cfg), kit.ParseOrDefault(cfg.AutoInjectEnv.Value, false, strconv.ParseBool), s.projectPathMapperInternal(ctx))
+ return projects.LoadCachedComposeProject(
+ ctx,
+ s.parsedCompose,
+ proj.ID,
+ proj.Path,
+ composePath,
+ projects.NormalizeProjectName(
+ proj.Name,
+ ),
+ getProjectsDirectoryOrDefaultInternal(
+ ctx,
+ cfg,
+ ),
+ kit.ParseOrDefault(
+ cfg.AutoInjectEnv.Value,
+ false,
+ strconv.ParseBool,
+ ),
+ s.projectPathMapperInternal(
+ ctx,
+ ),
+ )
}
func (s *ProjectService) refreshComposeProjectNameInternal(ctx context.Context, proj *Project) {
@@ -795,11 +852,11 @@ func (s *ProjectService) refreshComposeProjectNameInternal(ctx context.Context,
}
updates["updated_at"] = time.Now()
- if err := s.db.WithContext(ctx).
+ if persistComposeNameErr := s.db.WithContext(ctx).
Model(&Project{}).
Where("id = ?", proj.ID).
- Updates(updates).Error; err != nil {
- slog.WarnContext(ctx, "failed to persist refreshed compose project name", "projectID", proj.ID, "error", err)
+ Updates(updates).Error; persistComposeNameErr != nil {
+ slog.WarnContext(ctx, "failed to persist refreshed compose project name", "projectID", proj.ID, "error", persistComposeNameErr)
return
}
diff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.go
index 7d2fbc500..16dbffba9 100644
--- a/backend/internal/project/service_test.go
+++ b/backend/internal/project/service_test.go
@@ -89,7 +89,7 @@ func setupProjectTestDB(t *testing.T) *database.DB {
func TestUpdateProjectWorkspaceRejectsInvalidManifestBeforeProjectLookup(t *testing.T) {
service := &ProjectService{}
- _, err := service.UpdateProjectWorkspace(context.Background(), "missing", projecttypes.WorkspaceUpdateManifest{}, nil, common.User{})
+ _, err := service.UpdateProjectWorkspace(t.Context(), "missing", projecttypes.WorkspaceUpdateManifest{}, nil, common.User{})
require.ErrorIs(t, err, common.ErrProjectWorkspaceBadRequest)
require.ErrorContains(t, err, "revision")
}
@@ -122,7 +122,7 @@ func newSettingsServiceForTestInternal(t *testing.T, ctx context.Context, db *da
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -194,7 +194,7 @@ func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[strin
}
func TestProjectService_RefreshProjectImageRefs_PersistsBuildMetadata(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -230,7 +230,7 @@ func TestProjectService_RefreshProjectImageRefs_PersistsBuildMetadata(t *testing
}
func TestProjectService_BackfillProjectImageRefs_RetriesOnlyMissingMetadata(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -291,7 +291,7 @@ func TestProjectService_BackfillProjectImageRefs_RetriesOnlyMissingMetadata(t *t
func setupProjectDestroyTestServiceInternal(t *testing.T) (*ProjectService, *database.DB, string) {
t.Helper()
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -304,7 +304,7 @@ func setupProjectDestroyTestServiceInternal(t *testing.T) (*ProjectService, *dat
}
func TestProjectService_DestroyProject_RemovesFilesWhenRequested(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupProjectDestroyTestServiceInternal(t)
projectPath := filepath.Join(projectsDir, "demo-remove")
@@ -328,7 +328,7 @@ func TestProjectService_DestroyProject_RemovesFilesWhenRequested(t *testing.T) {
}
func TestProjectService_DestroyProject_PreservesFilesWhenRequested(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc, db, projectsDir := setupProjectDestroyTestServiceInternal(t)
projectPath := filepath.Join(projectsDir, "demo-preserve")
@@ -361,7 +361,7 @@ func TestProjectService_DestroyProject_PreservesFilesWhenRequested(t *testing.T)
func TestProjectService_GetProjectFromDatabaseByID(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
// Setup dependencies
settingsService, _ := newSettingsServiceForTestInternal(t, ctx, db)
@@ -475,7 +475,7 @@ func TestProjectService_CalculateProjectStatus(t *testing.T) {
func TestProjectService_UpdateProjectStatusInternal(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
svc := NewProjectService(db, nil, nil, nil, nil, nil, nil, nil, config.Load(), nil, nil)
proj := &Project{
@@ -515,7 +515,7 @@ func TestProjectService_IncrementStatusCounts(t *testing.T) {
}
func TestProjectService_GetProjectByComposeName(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("exact match", func(t *testing.T) {
db := setupProjectTestDB(t)
@@ -636,7 +636,7 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {
}
func TestProjectService_PullProjectImages_UpdatesCurrentImageRecordAfterPull(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
projectsDir := t.TempDir()
@@ -737,7 +737,7 @@ func TestProjectService_PullProjectImages_UpdatesCurrentImageRecordAfterPull(t *
}
func TestProjectService_EnsureImagesPresent_UpdatesCurrentImageRecordAfterPull(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -772,7 +772,25 @@ func TestProjectService_EnsureImagesPresent_UpdatesCurrentImageRecordAfterPull(t
CheckTime: time.Now().UTC().Add(-time.Hour),
}).Error)
- require.NoError(t, svc.composeCoordinator.EnsureImagesPresent(ctx, &composetypes.Project{Services: composetypes.Services{"api": {Image: imageRef, PullPolicy: composetypes.PullPolicyAlways}}}, io.Discard, svc.composeImageOperationsInternal(nil, nil)))
+ require.NoError(
+ t,
+ svc.composeCoordinator.EnsureImagesPresent(
+ ctx,
+ &composetypes.Project{
+ Services: composetypes.Services{
+ "api": {
+ Image: imageRef,
+ PullPolicy: composetypes.PullPolicyAlways,
+ },
+ },
+ },
+ io.Discard,
+ svc.composeImageOperationsInternal(
+ nil,
+ nil,
+ ),
+ ),
+ )
// sha256:old-api may still be in use by another container — pulling for one container
// must not clear it (fixes #2453).
@@ -787,7 +805,7 @@ func TestProjectService_EnsureImagesPresent_UpdatesCurrentImageRecordAfterPull(t
}
func TestProjectService_PullImageForService_UpdatesCurrentImageRecordAfterPull(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -836,7 +854,7 @@ func TestProjectService_PullImageForService_UpdatesCurrentImageRecordAfterPull(t
}
func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSuccess(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -956,7 +974,7 @@ func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSucc
}
func TestProjectService_ComposePullSelectedServicesInternal_LeavesRecordsWhenPullFails(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -1013,7 +1031,7 @@ func TestProjectService_ComposePullSelectedServicesInternal_LeavesRecordsWhenPul
}
func TestProjectService_UpdateProjectServicesHardFailsWhenPullFailsInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1037,7 +1055,19 @@ func TestProjectService_UpdateProjectServicesHardFailsWhenPullFailsInternal(t *t
imageService := image.NewImageService(db, dockerService, nil, imageUpdateService, nil, event.NewEventService(db, nil, nil))
projectPath := createComposeProjectDir(t, projectsDir, "compose-update-pull-fail")
- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: "+imageRef+"\n labels:\n com.getarcaneapp.arcane.updater.strategy: digest\n"), 0o644))
+ require.NoError(
+ t,
+ os.WriteFile(
+ filepath.Join(
+ projectPath,
+ "compose.yaml",
+ ),
+ []byte(
+ "services:\n app:\n image: "+imageRef+"\n labels:\n com.getarcaneapp.arcane.updater.strategy: digest\n",
+ ),
+ 0o644,
+ ),
+ )
projectRecord := &Project{
ID: "project-update-pull-fail",
@@ -1083,7 +1113,7 @@ func TestProjectService_UpdateProjectServicesHardFailsWhenPullFailsInternal(t *t
}
func TestProjectService_UpdateProjectServicesForcesRecreateInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1113,7 +1143,23 @@ func TestProjectService_UpdateProjectServicesForcesRecreateInternal(t *testing.T
imageService := image.NewImageService(db, dockerService, nil, imageUpdateService, nil, eventService)
projectPath := createComposeProjectDir(t, projectsDir, "compose-update-force")
- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: "+imageRef+"\n labels:\n com.getarcaneapp.arcane.updater.strategy: digest\n sidecar:\n image: busybox:latest\n network_mode: service:app\n dormant:\n image: busybox:latest\n network_mode: service:app\n never:\n image: busybox:latest\n pid: service:app\n gated:\n image: busybox:latest\n network_mode: service:app\n profiles: [extra]\n unrelated:\n image: busybox:latest\n"), 0o644))
+ require.NoError(
+ t,
+ os.WriteFile(
+ filepath.Join(
+ projectPath,
+ "compose.yaml",
+ ),
+ []byte(
+ "services:\n app:\n image: "+imageRef+"\n labels:\n com.getarcaneapp.arcane.updater.strategy: digest\n sidecar:\n image: "+
+ "busybox:latest\n network_mode: service:app\n dormant:\n image: busybox:latest\n network_mode: "+
+ "service:app\n never:\n image: busybox:latest\n pid: service:app\n gated:\n image: "+
+ "busybox:latest\n network_mode: service:app\n profiles: [extra]\n unrelated:\n image: "+
+ "busybox:latest\n",
+ ),
+ 0o644,
+ ),
+ )
composeContainerInternal := func(service string, state container.ContainerState) container.Summary {
return container.Summary{
@@ -1152,7 +1198,14 @@ func TestProjectService_UpdateProjectServicesForcesRecreateInternal(t *testing.T
}
upCalled := false
forceRecreate := false
- composeUpProjectServicesInternal = func(_ context.Context, selected *composetypes.Project, services []string, removeOrphans, force, _ bool, _ map[string]dockerregistry.AuthConfig, _ time.Duration) error {
+ composeUpProjectServicesInternal = func(
+ _ context.Context,
+ selected *composetypes.Project,
+ services []string,
+ removeOrphans, force, _ bool,
+ _ map[string]dockerregistry.AuthConfig,
+ _ time.Duration,
+ ) error {
assert.True(t, eventService.ShouldSuppressDaemonEvent("container", "replacement", "app", selected.Name))
assert.False(t, eventService.ShouldSuppressDaemonEvent("image", "pulled-image", "", ""))
upCalled = true
@@ -1199,7 +1252,7 @@ func (m *fakeProjectVolumeRenameMigrationInternal) Commit(context.Context) error
func TestProjectService_UpdateProject_RenameFailsWhenVolumeMigrationPreparationFails(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1246,7 +1299,19 @@ func TestProjectService_UpdateProject_RenameFailsWhenVolumeMigrationPreparationF
originalDirName := "Foo"
originalPath := createComposeProjectDir(t, projectsDir, originalDirName)
- require.NoError(t, os.WriteFile(filepath.Join(originalPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n"), 0o644))
+ require.NoError(
+ t,
+ os.WriteFile(
+ filepath.Join(
+ originalPath,
+ "compose.yaml",
+ ),
+ []byte(
+ "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n",
+ ),
+ 0o644,
+ ),
+ )
project := &Project{
ID: "proj-volume-conflict",
@@ -1275,7 +1340,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenVolumeMigrationPreparationF
func TestProjectService_ApplyProjectUpdateWithRenameJournal_AppliesVolumeMigrationWhenNameChanges(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1322,7 +1387,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_AppliesVolumeMigrati
func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesComposePreview(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1377,9 +1442,9 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesCompose
t.Run("skips volume made explicit in pending compose", func(t *testing.T) {
newCompose := "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n name: fixed-data\n"
- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
+ migration, prepareProjectRenameVolumeMigrationForUpdateErr := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
- require.NoError(t, err)
+ require.NoError(t, prepareProjectRenameVolumeMigrationForUpdateErr)
require.Nil(t, migration)
bytes, readErr := os.ReadFile(filepath.Join(projectPath, "compose.yaml"))
require.NoError(t, readErr)
@@ -1390,9 +1455,9 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesCompose
t.Run("plans unchanged auto-managed volume from pending compose", func(t *testing.T) {
newCompose := "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n"
- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
+ migration, prepareProjectRenameVolumeMigrationForUpdateErr := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
- require.NoError(t, err)
+ require.NoError(t, prepareProjectRenameVolumeMigrationForUpdateErr)
require.NotNil(t, migration)
journalSource, ok := migration.(volumetypes.JournalSource)
require.True(t, ok)
@@ -1407,9 +1472,9 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesCompose
t.Run("plans auto-managed volume when pending compose name renames project", func(t *testing.T) {
newCompose := "name: web\nservices:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n"
- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
+ migration, prepareProjectRenameVolumeMigrationForUpdateErr := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
- require.NoError(t, err)
+ require.NoError(t, prepareProjectRenameVolumeMigrationForUpdateErr)
require.NotNil(t, migration)
journalSource, ok := migration.(volumetypes.JournalSource)
require.True(t, ok)
@@ -1424,9 +1489,9 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesCompose
t.Run("plans interpolated explicit name from pending compose", func(t *testing.T) {
newCompose := "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n name: ${DATA_VOLUME:-nginx_data}\n"
- migration, err := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
+ migration, prepareProjectRenameVolumeMigrationForUpdateErr := svc.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, project, new("web"), projectsDir, &newCompose, nil, nil)
- require.NoError(t, err)
+ require.NoError(t, prepareProjectRenameVolumeMigrationForUpdateErr)
require.NotNil(t, migration)
journalSource, ok := migration.(volumetypes.JournalSource)
require.True(t, ok)
@@ -1441,7 +1506,7 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesCompose
func TestProjectService_ApplyProjectUpdateWithRenameJournal_RollsBackVolumeMigrationWhenProjectSaveFails(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1490,7 +1555,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_RollsBackVolumeMigra
func TestProjectService_ApplyProjectUpdateWithRenameJournal_SucceedsCommittedRenameWhenSourceCleanupFails(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1540,7 +1605,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_SucceedsCommittedRen
func TestProjectService_UpdateProject_ClearsJournalForNonRenameWhenRecoveryDockerUnavailable(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1607,7 +1672,7 @@ func TestProjectService_UpdateProject_ClearsJournalForNonRenameWhenRecoveryDocke
func TestProjectService_UpdateProject_AllowsRenameAfterJournalRecoveryWithoutDockerService(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1672,7 +1737,7 @@ func TestProjectService_UpdateProject_AllowsRenameAfterJournalRecoveryWithoutDoc
func TestProjectService_UpdateProject_RenamesDirectoryWhenNameChanges(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1721,7 +1786,7 @@ func TestProjectService_UpdateProject_RenamesDirectoryWhenNameChanges(t *testing
func TestProjectService_UpdateProject_RenameFailsWhenTargetDirectoryExists(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1768,7 +1833,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenTargetDirectoryExists(t *te
func TestProjectService_UpdateProject_RenameFailsWhenProjectRunning(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1812,7 +1877,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenProjectRunning(t *testing.T
func TestProjectService_UpdateProject_RenameRejectsStaleStoppedWhenRuntimeIsRunning(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1870,7 +1935,7 @@ func TestProjectService_UpdateProject_RenameRejectsStaleStoppedWhenRuntimeIsRunn
func TestProjectService_UpdateProject_RenameResolvesUnknownStoppedStatusBeforeVolumeMigration(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1928,7 +1993,7 @@ func TestProjectService_UpdateProject_RenameResolvesUnknownStoppedStatusBeforeVo
func TestProjectService_UpdateProject_RenameRejectsUnknownWhenRuntimeIsRunning(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -1992,7 +2057,7 @@ func TestProjectService_UpdateProject_RenameRejectsUnknownWhenRuntimeIsRunning(t
func TestProjectService_UpdateProject_ValidatesComposeUsingExistingProjectName(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2035,7 +2100,7 @@ services:
func TestProjectService_UpdateProject_AllowsMissingEnvFileDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2080,7 +2145,7 @@ func TestProjectService_UpdateProject_AllowsMissingEnvFileDuringComposeValidatio
func TestProjectService_UpdateProject_EnvRetargetWritesExplicitIdenticalComposeToSelectedBase(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2134,7 +2199,7 @@ func TestProjectService_UpdateProject_EnvRetargetWritesExplicitIdenticalComposeT
func TestProjectService_UpdateProject_EnvRetargetWithoutComposePayloadPreservesNewBase(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2186,7 +2251,7 @@ func TestProjectService_UpdateProject_EnvRetargetWithoutComposePayloadPreservesN
func TestProjectService_UpdateProject_EnvRetargetWritesEditedComposeToSelectedBase(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2233,7 +2298,7 @@ func TestProjectService_UpdateProject_EnvRetargetWritesEditedComposeToSelectedBa
func TestProjectService_UpdateProject_AllowsMissingLocalIncludeDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2283,7 +2348,7 @@ services:
func TestProjectService_CreateProject_AllowsExternalInclude(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2314,7 +2379,7 @@ services:
func TestProjectService_UpdateProject_AllowsExternalInclude(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2360,7 +2425,7 @@ services:
func TestProjectService_CreateProject_CommitsWorkspaceAndConfigurationTogether(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2395,7 +2460,7 @@ func TestProjectService_CreateProject_CommitsWorkspaceAndConfigurationTogether(t
func TestProjectService_CreateProject_RollsBackInvalidWorkspaceManifest(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2428,7 +2493,7 @@ func TestProjectService_CreateProject_RollsBackInvalidWorkspaceManifest(t *testi
func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2475,10 +2540,10 @@ func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation
// newProjectServiceForOverrideTestInternal builds a project with a base compose
// file on disk and returns the service, the project record, and the project path.
-func newProjectServiceForOverrideTestInternal(t *testing.T, dirName, baseCompose string) (*ProjectService, *Project, string) {
+func newProjectServiceForOverrideTestInternal(t *testing.T, dirName string) (*ProjectService, *Project, string) {
t.Helper()
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2491,7 +2556,7 @@ func newProjectServiceForOverrideTestInternal(t *testing.T, dirName, baseCompose
projectPath := filepath.Join(projectsDir, dirName)
require.NoError(t, os.MkdirAll(projectPath, 0o755))
- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(baseCompose), 0o600))
+ require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:alpine\n"), 0o600))
project := &Project{
ID: "proj-" + dirName,
@@ -2506,8 +2571,8 @@ func newProjectServiceForOverrideTestInternal(t *testing.T, dirName, baseCompose
}
func TestProjectService_UpdateProject_CreatesOverrideWithDefaultName(t *testing.T) {
- ctx := context.Background()
- svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-create", "services:\n app:\n image: nginx:alpine\n")
+ ctx := t.Context()
+ svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-create")
override := "services:\n app:\n image: busybox:latest\n"
_, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), common.User{
@@ -2529,8 +2594,8 @@ func TestProjectService_UpdateProject_CreatesOverrideWithDefaultName(t *testing.
}
func TestProjectService_UpdateProject_PreservesExistingOverrideName(t *testing.T) {
- ctx := context.Background()
- svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-preserve", "services:\n app:\n image: nginx:alpine\n")
+ ctx := t.Context()
+ svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-preserve")
// An existing docker-compose.override.yml must keep its name on edit rather
// than being rewritten to the default compose.override.yaml.
@@ -2550,8 +2615,8 @@ func TestProjectService_UpdateProject_PreservesExistingOverrideName(t *testing.T
}
func TestProjectService_UpdateProject_DeletesOverrideOnBlank(t *testing.T) {
- ctx := context.Background()
- svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-delete", "services:\n app:\n image: nginx:alpine\n")
+ ctx := t.Context()
+ svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-delete")
overridePath := filepath.Join(projectPath, "compose.override.yaml")
require.NoError(t, os.WriteFile(overridePath, []byte("services:\n app:\n image: busybox:latest\n"), 0o600))
@@ -2567,9 +2632,9 @@ func TestProjectService_UpdateProject_DeletesOverrideOnBlank(t *testing.T) {
}
func TestProjectService_UpdateProject_MergedValidationFailureLeavesDiskUnchanged(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
baseCompose := "services:\n app:\n image: nginx:alpine\n"
- svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-invalid", baseCompose)
+ svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-invalid")
// A new base compose plus a malformed override must fail validation, and the
// backup/restore must leave both the base and the override untouched on disk.
@@ -2589,7 +2654,7 @@ func TestProjectService_UpdateProject_MergedValidationFailureLeavesDiskUnchanged
func TestProjectService_UpdateProject_UsesProvidedEnvContentDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2636,7 +2701,7 @@ func TestProjectService_UpdateProject_UsesProvidedEnvContentDuringComposeValidat
func TestProjectService_UpdateProject_ReturnsEnvParseErrorDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2681,7 +2746,7 @@ func TestProjectService_UpdateProject_ReturnsEnvParseErrorDuringComposeValidatio
func TestProjectService_UpdateProject_UsesGlobalEnvDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2729,7 +2794,7 @@ func TestProjectService_UpdateProject_UsesGlobalEnvDuringComposeValidation(t *te
func TestProjectService_UpdateProject_DoesNotResolveHostEnvThroughGlobalEnvDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2774,7 +2839,7 @@ func TestProjectService_UpdateProject_DoesNotResolveHostEnvThroughGlobalEnvDurin
func TestProjectService_UpdateProject_DerivesProjectOverrideEnvWhenGitSourceExists(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2821,7 +2886,7 @@ func TestProjectService_UpdateProject_DerivesProjectOverrideEnvWhenGitSourceExis
func TestProjectService_UpdateProject_UnchangedGitEnvLeavesFilesUntouched(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2918,7 +2983,7 @@ func TestProjectService_PersistEffectiveEnvContent_RemovesStaleGitOverride(t *te
func TestProjectService_UpdateProject_DeletingGitBackedKeyFallsBackToGit(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -2968,7 +3033,7 @@ func TestProjectService_UpdateProject_DeletingGitBackedKeyFallsBackToGit(t *test
func TestProjectService_ApplyGitSyncProjectFiles_MigratesDirectEnvIntoProjectOverride(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3019,7 +3084,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_MigratesDirectEnvIntoProjectOve
func TestProjectService_ApplyGitSyncProjectFiles_PreservesGitEnvSyntax(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3053,11 +3118,11 @@ func TestProjectService_ApplyGitSyncProjectFiles_PreservesGitEnvSyntax(t *testin
gitEnv := "# keep git formatting\nZ_LAST=last\nCLOUDFLARE_CLIENT_SECRET=$$pbkdf2-sha512$$310000$$XXX\nQUOTED_SECRET='$pbkdf2-sha512$310000$XXX'\nA_FIRST=first"
for i := range 2 {
- updated, changed, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, &gitEnv, nil, "", common.User{
+ updated, changed, applyGitSyncProjectFilesErr := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, &gitEnv, nil, "", common.User{
ID: "u1",
Username: "tester",
})
- require.NoError(t, err)
+ require.NoError(t, applyGitSyncProjectFilesErr)
require.NotNil(t, updated)
assert.Equal(t, i == 0, changed)
@@ -3081,7 +3146,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_PreservesGitEnvSyntax(t *testin
func TestProjectService_ApplyGitSyncProjectFiles_NormalizesStaleCopiedGitOverrides(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3129,7 +3194,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_NormalizesStaleCopiedGitOverrid
func TestProjectService_ApplyGitSyncProjectFiles_RemovesLegacyDeletedGitMasks(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3178,7 +3243,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_RemovesLegacyDeletedGitMasks(t
func TestProjectService_ApplyGitSyncProjectFiles_RemovesGitEnvSource(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3222,7 +3287,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_RemovesGitEnvSource(t *testing.
func TestProjectService_ApplyGitSyncProjectFiles_WritesAndRemovesComposeOverride(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3273,7 +3338,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_WritesAndRemovesComposeOverride
func TestProjectService_ApplyGitSyncProjectFiles_UsesGlobalEnvDuringComposeValidation(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3324,7 +3389,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_UsesGlobalEnvDuringComposeValid
// typed-decode error like `strconv.ParseFloat: parsing "": invalid syntax`.
func TestProjectService_ApplyGitSyncProjectFiles_TolerantOfUndefinedComposeVar(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3372,7 +3437,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_TolerantOfUndefinedComposeVar(t
func TestProjectService_PersistGitSyncEnvFiles_UsesPreparedState(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3410,7 +3475,7 @@ func TestProjectService_PersistGitSyncEnvFiles_UsesPreparedState(t *testing.T) {
func TestProjectService_GetProjectDetails_ReturnsEffectiveEnvContent(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3549,7 +3614,7 @@ func TestBuildProjectUpdateInfoSummaryInternal(t *testing.T) {
func TestProjectService_GetProjectDetails_IncludesUpdateInfo(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3597,7 +3662,7 @@ func TestProjectService_GetProjectDetails_IncludesUpdateInfo(t *testing.T) {
func TestProjectService_GetProjectDetails_RefreshesRuntimeStatusWithoutRuntimeServices(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3670,7 +3735,7 @@ func TestProjectService_GetProjectDetails_RefreshesRuntimeStatusWithoutRuntimeSe
func TestProjectService_GetProjectDetails_PopulatesRuntimeServicesFromComposePs(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3731,7 +3796,7 @@ func TestBuildProjectLabelFilterAccessorInternal(t *testing.T) {
{ID: "other", RuntimeServices: []projecttypes.RuntimeService{{Name: "web", ContainerLabels: map[string]string{"heal": "false"}}}},
{ID: "down"},
}
- config := pagination.Config[projecttypes.Details]{FilterAccessors: []pagination.FilterAccessor[projecttypes.Details]{buildProjectLabelFilterAccessorInternal()}}
+ paginationConfig := pagination.Config[projecttypes.Details]{FilterAccessors: []pagination.FilterAccessor[projecttypes.Details]{buildProjectLabelFilterAccessorInternal()}}
tests := []struct {
name string
@@ -3746,7 +3811,7 @@ func TestBuildProjectLabelFilterAccessorInternal(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- result := config.SearchOrderAndPaginate(items, pagination.QueryParams{Filters: map[string]string{"label": tt.filter}})
+ result := paginationConfig.SearchOrderAndPaginate(items, pagination.QueryParams{Filters: map[string]string{"label": tt.filter}})
var got []string
for _, item := range result.Items {
got = append(got, item.ID)
@@ -3758,7 +3823,7 @@ func TestBuildProjectLabelFilterAccessorInternal(t *testing.T) {
func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -3851,14 +3916,14 @@ func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- items, page, err := svc.ListProjects(ctx, pagination.QueryParams{
+ items, page, listProjectsErr := svc.ListProjects(ctx, pagination.QueryParams{
Filters: map[string]string{
"updates": tt.filter,
},
Limit: -1,
Sort: "name", Order: pagination.SortAsc,
})
- require.NoError(t, err)
+ require.NoError(t, listProjectsErr)
require.EqualValues(t, len(tt.expected), page.TotalItems)
names := make([]string, 0, len(items))
@@ -3872,7 +3937,7 @@ func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {
func TestBuildDiscoveredComposeProjectUpdateRowsInternal(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
imageService := image.NewImageService(db, nil, nil, nil, nil, nil)
now := time.Now().UTC()
@@ -3940,7 +4005,7 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal(t *testing.T) {
func TestBuildDiscoveredComposeProjectUpdateRowsInternal_FallsBackToImageID(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
imageService := image.NewImageService(db, nil, nil, nil, nil, nil)
require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{
@@ -3995,7 +4060,18 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal_FallsBackToImageID(t *t
// The tracked-project path resolves the same record through the runtime image ID.
service := &ProjectService{imageService: imageService}
- detail := projecttypes.Details{ID: "tracked", RuntimeServices: []projecttypes.RuntimeService{{Name: "web", ContainerID: "media-web", Image: "nginx:latest", ImageID: "sha256:media-image", ContainerLabels: containers[0].Labels}}}
+ detail := projecttypes.Details{
+ ID: "tracked",
+ RuntimeServices: []projecttypes.RuntimeService{
+ {
+ Name: "web",
+ ContainerID: "media-web",
+ Image: "nginx:latest",
+ ImageID: "sha256:media-image",
+ ContainerLabels: containers[0].Labels,
+ },
+ },
+ }
service.enrichProjectUpdateInfoInternal(ctx, &detail)
require.True(t, detail.UpdateInfo.HasUpdate)
assert.Equal(t, []string{"nginx:latest"}, detail.UpdateInfo.UpdatedImageRefs)
@@ -4006,7 +4082,7 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal_FallsBackToImageID(t *t
func TestProjectService_ListProjects_FiltersArchivedProjects(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4067,7 +4143,7 @@ func TestProjectService_ListProjects_FiltersArchivedProjects(t *testing.T) {
func TestProjectService_ArchiveProject_RequiresStoppedProject(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsRoot := t.TempDir()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -4113,7 +4189,7 @@ func TestProjectService_ArchiveProject_RequiresStoppedProject(t *testing.T) {
func TestProjectService_ArchiveProject_TogglesArchiveFlag(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsRoot := t.TempDir()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -4149,7 +4225,7 @@ func TestProjectService_ArchiveProject_TogglesArchiveFlag(t *testing.T) {
func TestProjectService_ArchiveProject_LiveVerificationErrorPolicy(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsRoot := t.TempDir()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -4274,7 +4350,7 @@ func TestProjectService_MapProjectToDto_SetsRedeployDisabledFromRuntimeServices(
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.labels[composeapi.WorkingDirLabel] = projectPath
- details := projectListRowInternal(context.Background(), filepath.Dir(projectPath), proj, projectContainerSnapshotInternal{byProject: map[string][]container.Summary{
+ details := projectListRowInternal(t.Context(), filepath.Dir(projectPath), proj, projectContainerSnapshotInternal{byProject: map[string][]container.Summary{
"arcane": {
{
ID: tt.containerID,
@@ -4330,7 +4406,7 @@ func TestProjectService_ProjectListRows_PersistsInferredServiceCount(t *testing.
},
}}
- rows := service.projectListRowsInternal(context.Background(), projectsDir, []Project{inferred, known}, snapshot)
+ rows := service.projectListRowsInternal(t.Context(), projectsDir, []Project{inferred, known}, snapshot)
require.Len(t, rows, 2)
require.Equal(t, 2, rows[0].ServiceCount)
require.Equal(t, 4, rows[1].ServiceCount)
@@ -4348,7 +4424,7 @@ func TestProjectService_ProjectListRows_PersistsInferredServiceCount(t *testing.
func TestProjectService_ListProjects_WithDerivedStatusFilter_AllowsAllPageSizeSentinel(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4386,7 +4462,7 @@ func TestProjectService_ListProjects_WithDerivedStatusFilter_AllowsAllPageSizeSe
func TestProjectService_DeployProject_StopsOnBuildPreparationError(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4421,14 +4497,16 @@ func TestProjectService_DeployProject_StopsOnBuildPreparationError(t *testing.T)
func TestProjectService_DeployProject_BuildsGeneratedImageWithoutPull(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
projectsRoot := t.TempDir()
projectDir := filepath.Join(projectsRoot, "demo")
require.NoError(t, os.MkdirAll(projectDir, 0o755))
- composeContent := "services:\n caddy:\n build:\n dockerfile_inline: |\n FROM caddy:builder AS builder\n RUN xcaddy build --with github.com/caddyserver/replace-response\n\n FROM caddy:latest\n COPY --from=builder /usr/bin/caddy /usr/bin/caddy\n"
+ composeContent := "services:\n caddy:\n build:\n dockerfile_inline: |\n FROM caddy:builder AS builder\n " +
+ " RUN xcaddy build --with github.com/caddyserver/replace-response\n\n FROM caddy:latest\n " +
+ " COPY --from=builder /usr/bin/caddy /usr/bin/caddy\n"
require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte(composeContent), 0o644))
require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot+":"+projectsRoot))
@@ -4454,7 +4532,7 @@ func TestProjectService_DeployProject_BuildsGeneratedImageWithoutPull(t *testing
func TestProjectService_SyncProjectsFromFileSystem_IgnoresSymlinkedProjectDirsWhenDisabled(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4480,7 +4558,7 @@ func TestProjectService_SyncProjectsFromFileSystem_IgnoresSymlinkedProjectDirsWh
func TestProjectService_SyncProjectsFromFileSystem_DetectsSymlinkedProjectDirsWhenEnabled(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4506,7 +4584,7 @@ func TestProjectService_SyncProjectsFromFileSystem_DetectsSymlinkedProjectDirsWh
func TestProjectService_CountProjectFolders_RespectsFollowProjectSymlinks(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4534,7 +4612,7 @@ func TestProjectService_CountProjectFolders_RespectsFollowProjectSymlinks(t *tes
func TestProjectService_SyncProjectsFromFileSystem_DiscoversNestedProjectsAndRelativePaths(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4567,7 +4645,7 @@ func TestProjectService_SyncProjectsFromFileSystem_DiscoversNestedProjectsAndRel
func TestProjectService_SyncProjectsFromFileSystem_RespectsConfiguredScanMaxDepth(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4591,7 +4669,7 @@ func TestProjectService_SyncProjectsFromFileSystem_RespectsConfiguredScanMaxDept
func TestProjectService_ListProjects_LoadsProjectIconFromGlobalEnvInIncludedMetadata(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4642,7 +4720,7 @@ services:
func TestProjectService_CountProjectFolders_RecursivelyCountsNestedProjects(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4663,7 +4741,7 @@ func TestProjectService_CountProjectFolders_RecursivelyCountsNestedProjects(t *t
func TestProjectService_CountProjectFolders_RespectsConfiguredScanMaxDepth(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4684,7 +4762,7 @@ func TestProjectService_CountProjectFolders_RespectsConfiguredScanMaxDepth(t *te
func TestProjectService_SyncProjectsFromFileSystem_RemovesDeletedNestedProject(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4715,7 +4793,7 @@ func TestProjectService_SyncProjectsFromFileSystem_RemovesDeletedNestedProject(t
// resurrected on restart" loop for gitops scratch leftovers.
func TestProjectService_SyncProjectsFromFileSystem_PrunesLeakedScratchRow(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4745,7 +4823,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PrunesLeakedScratchRow(t *tes
func TestProjectService_SyncProjectsFromFileSystem_PreservesProjectsWhenDirectoryEmptyOrUnmounted(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4780,7 +4858,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesProjectsWhenDirector
func TestProjectService_SyncProjectsFromFileSystem_PreservesProjectWithAmbiguousCustomCompose(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4816,7 +4894,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesProjectWithAmbiguous
func TestProjectService_SyncProjectsFromFileSystem_RemovesProjectsBeyondReducedScanMaxDepth(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4862,7 +4940,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesDBRecordsWhenDirecto
}
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4911,7 +4989,7 @@ func TestProjectService_SyncProjectsFromFileSystem_DiscoversReadableProjectsDesp
}
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4962,7 +5040,7 @@ func TestProjectService_SyncProjectsFromFileSystem_DiscoversReadableProjectsDesp
func TestProjectService_SyncProjectsFromFileSystem_AllowsDuplicateLeafDirectoriesInDifferentParents(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -4990,7 +5068,7 @@ func TestProjectService_SyncProjectsFromFileSystem_AllowsDuplicateLeafDirectorie
func TestProjectService_SyncProjectsFromFileSystem_DetectsNestedSymlinkedProjectDirsWhenEnabled(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5021,7 +5099,7 @@ func TestProjectService_SyncProjectsFromFileSystem_DetectsNestedSymlinkedProject
func TestProjectService_SyncProjectsFromFileSystem_RemovesSymlinkedProjectsWhenDisabled(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5055,7 +5133,7 @@ func TestProjectService_SyncProjectsFromFileSystem_RemovesSymlinkedProjectsWhenD
func TestProjectService_SyncProjectsFromFileSystem_RefreshesServiceCountOnComposeChange(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5082,7 +5160,7 @@ func TestProjectService_SyncProjectsFromFileSystem_RefreshesServiceCountOnCompos
func TestProjectService_SyncProjectsFromFileSystem_AlignsNameToEffectiveComposeName(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5111,7 +5189,7 @@ services:
func TestProjectService_SyncProjectsFromFileSystem_PreservesValidCustomNameWithoutExplicitComposeName(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5143,7 +5221,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesValidCustomNameWitho
func TestProjectService_SyncProjectsFromFileSystem_PreservesGitOpsProjectWithCustomComposeFilename(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
require.NoError(t, db.AutoMigrate(&GitOpsSync{}))
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -5193,7 +5271,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesGitOpsProjectWithCus
func TestProjectService_GetProjectDetails_UsesGitOpsCustomComposeFilename(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
require.NoError(t, db.AutoMigrate(&GitOpsSync{}))
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -5247,7 +5325,7 @@ func TestProjectService_GetProjectDetails_UsesGitOpsCustomComposeFilename(t *tes
func TestProjectService_UpdateProject_WritesThroughSymlinkedProjectPath(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5296,7 +5374,7 @@ func TestProjectService_UpdateProject_WritesThroughSymlinkedProjectPath(t *testi
func TestProjectService_UpdateProject_WritesThroughExternalEnvSymlink(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5310,8 +5388,8 @@ func TestProjectService_UpdateProject_WritesThroughExternalEnvSymlink(t *testing
require.NoError(t, os.Chmod(targetPath, targetPerm))
envPath := filepath.Join(projectPath, projects.EffectiveEnvFileName)
- if err := os.Symlink(targetPath, envPath); err != nil {
- t.Skipf("symlink creation is unavailable: %v", err)
+ if symlinkErr := os.Symlink(targetPath, envPath); symlinkErr != nil {
+ t.Skipf("symlink creation is unavailable: %v", symlinkErr)
}
originalLinkTarget, err := os.Readlink(envPath)
require.NoError(t, err)
@@ -5354,7 +5432,7 @@ func TestProjectService_UpdateProject_WritesThroughExternalEnvSymlink(t *testing
func TestProjectService_UpdateProject_RestoresExternalEnvSymlinkTargetWhenProjectSaveFails(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -5369,8 +5447,8 @@ func TestProjectService_UpdateProject_RestoresExternalEnvSymlinkTargetWhenProjec
require.NoError(t, os.Chmod(targetPath, targetPerm))
envPath := filepath.Join(projectPath, projects.EffectiveEnvFileName)
- if err := os.Symlink(targetPath, envPath); err != nil {
- t.Skipf("symlink creation is unavailable: %v", err)
+ if symlinkErr := os.Symlink(targetPath, envPath); symlinkErr != nil {
+ t.Skipf("symlink creation is unavailable: %v", symlinkErr)
}
originalLinkTarget, err := os.Readlink(envPath)
require.NoError(t, err)
@@ -5517,7 +5595,7 @@ func TestResolveRemoveOrphans(t *testing.T) {
func TestProjectService_RecoverProjectRenameJournals_RollsBackUncommittedDirectoryRename(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -5572,7 +5650,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackUncommittedDirecto
func TestProjectService_RecoverProjectRenameJournals_StartedPhaseSkipsVolumeRollback(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -5634,7 +5712,7 @@ func TestProjectService_RecoverProjectRenameJournals_StartedPhaseSkipsVolumeRoll
func TestProjectService_RecoverProjectRenameJournals_RelocatesTargetWhenBothPathsExist(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -5702,7 +5780,7 @@ func TestProjectService_RecoverProjectRenameJournals_RelocatesTargetWhenBothPath
func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDirectoryPathsMissing(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -5748,7 +5826,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDir
func TestProjectService_RecoverProjectRenameJournals_ClearsPreservedTargetJournalWhenPathExists(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -5821,7 +5899,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsPreservedTargetJourna
func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournal(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -5867,7 +5945,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournal(t *t
func TestProjectService_FinalizeProjectRenameAfterCommit_ClearsJournalAfterSourceCleanup(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
oldDir := "nginx"
newDir := "web"
@@ -5909,7 +5987,7 @@ func TestProjectService_FinalizeProjectRenameAfterCommit_ClearsJournalAfterSourc
func TestProjectService_FinalizeProjectRenameAfterCommit_KeepsJournalWhenSourceCleanupFails(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
oldDir := "nginx"
newDir := "web"
@@ -5957,7 +6035,7 @@ func TestProjectService_FinalizeProjectRenameAfterCommit_KeepsJournalWhenSourceC
func TestProjectService_RecoverProjectRenameJournals_KeepsJournalWhenDirectoryRollbackFails(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var targetRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -6063,7 +6141,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsJournalWhenDirectoryRo
func TestProjectService_RecoverProjectRenameJournals_CompletesCommittedVolumeJournalWithoutHelperImage(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var imageInspectCalled atomic.Bool
var oldVolumeRemoved atomic.Bool
@@ -6139,7 +6217,7 @@ func TestProjectService_RecoverProjectRenameJournals_CompletesCommittedVolumeJou
func TestProjectService_RecoverProjectRenameJournals_RollsBackCommittedJournalWhenTargetMissingAndSourceExists(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var oldVolumeRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -6222,7 +6300,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackCommittedJournalWh
func TestProjectService_RecoverProjectRenameJournals_ClearsJournalAfterDBRestoreWhenVolumeRollbackFails(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var targetRemoveAttempts atomic.Int32
var targetExists atomic.Bool
@@ -6350,7 +6428,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalAfterDBRestore
func TestProjectService_RecoverProjectRenameJournals_KeepsRollbackCleanupWhenDockerUnavailable(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -6399,7 +6477,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsRollbackCleanupWhenDoc
func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalWhenSourceAndTargetMissing(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
@@ -6472,7 +6550,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalWhenS
func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalAndCleansRemainingSourcesWhenSomeVolumesExternallyRemoved(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var cacheSourceRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -6565,7 +6643,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalAndCl
func TestProjectService_RecoverProjectRenameJournals_MarksSourceCleanupPendingWhenCommittedCleanupFails(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var sourceRemoveAttempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -6651,7 +6729,7 @@ func TestProjectService_RecoverProjectRenameJournals_MarksSourceCleanupPendingWh
func TestProjectService_RecoverProjectRenameJournals_ClearsSourceCleanupPendingJournalAfterCleanup(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var sourceRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -6725,7 +6803,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsSourceCleanupPendingJ
func TestProjectService_RecoverProjectRenameJournals_RollsBackSourceCleanupPendingWhenTargetMissing(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var dataSourceRemoved atomic.Bool
var dataTargetRemoved atomic.Bool
@@ -6842,7 +6920,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackSourceCleanupPendi
func TestProjectService_RecoverProjectRenameJournals_KeepsSourceCleanupPendingJournalWhenCleanupFails(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var sourceRemoveAttempts atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -6928,7 +7006,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsSourceCleanupPendingJo
func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDirectoriesAreMissing(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
oldDir := "nginx"
@@ -6974,7 +7052,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDir
func TestProjectService_RecoverProjectRenameJournals_ClearsMissingPathJournalWhenTargetPreserved(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var targetRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -7058,7 +7136,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsMissingPathJournalWhe
func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackSourceInspectFails(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var targetRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -7133,7 +7211,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackSo
func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackTargetInspectFails(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var targetRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -7213,7 +7291,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackTa
func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenTargetPreservedAndDirectoryRolledBack(t *testing.T) {
db := setupProjectTestDB(t)
require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- ctx := context.Background()
+ ctx := t.Context()
var targetRemoved atomic.Bool
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -7293,7 +7371,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenTargetPres
}
func TestProjectListRow_SeedsHasBuildDirectiveFromPersistedRefs(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
projectsDirectory := t.TempDir()
now := time.Now()
@@ -7325,16 +7403,45 @@ func TestProjectPathMapperUsesCurrentSettingsInternal(t *testing.T) {
require.NoError(t, settingsService.SetStringSetting(t.Context(), "projectsDirectory", containerDir+":"+hostDir))
mapper := service.projectPathMapperInternal(t.Context())
require.NotNil(t, mapper)
- mapped, _, err := mapper.ContainerToHost(filepath.Join(containerDir, "data"))
- require.NoError(t, err)
+ mapped, _, containerToHostErr := mapper.ContainerToHost(filepath.Join(containerDir, "data"))
+ require.NoError(t, containerToHostErr)
require.Equal(t, filepath.Join(hostDir, "data"), mapped)
}
}
func TestPrepareProjectServiceImages(t *testing.T) {
- source := []byte("\xEF\xBB\xBF# operator configuration\r\n\r\nservices:\r\n web:\r\n image: \"app:${VERSION}\" # keep this comment\r\n environment:\r\n VERSION: ${VERSION}\r\n\r\n worker:\r\n image: 'app:1.2.0' \r\n tagged:\r\n image: !!str app:1.2.0\r\n escaped:\r\n image: \"app\\u003a1.2.0\"\r\n untouched:\r\n image: app:1.2.0 # stays\r\n\r\r plain:\r\n image: app:1.2.0")
- expected := "\xEF\xBB\xBF# operator configuration\r\n\r\nservices:\r\n web:\r\n image: \"app:1.3.0\" # keep this comment\r\n environment:\r\n VERSION: ${VERSION}\r\n\r\n worker:\r\n image: 'docker.io/library/app:1.3.0' \r\n tagged:\r\n image: !!str app:1.3.0\r\n escaped:\r\n image: \"app:1.3.0\"\r\n untouched:\r\n image: app:1.2.0 # stays\r\n\r\r plain:\r\n image: app:1.3.0"
- effective := &composetypes.Project{Services: composetypes.Services{"web": {Image: "app:1.2.0"}, "worker": {Image: "app:1.2.0"}, "tagged": {Image: "app:1.2.0"}, "escaped": {Image: "app:1.2.0"}, "untouched": {Image: "app:1.2.0"}, "plain": {Image: "app:1.2.0"}}}
+ source := []byte(
+ "\ufeff# operator configuration\r\n\r\nservices:\r\n web:\r\n image: \"app:${VERSION}\" # keep this comment\r\n " +
+ " environment:\r\n VERSION: ${VERSION}\r\n\r\n worker:\r\n image: 'app:1.2.0' \r\n tagged:\r\n " +
+ "image: !!str app:1.2.0\r\n escaped:\r\n image: \"app\\u003a1.2.0\"\r\n untouched:\r\n image: app:1.2.0 " +
+ "# stays\r\n\r\r plain:\r\n image: app:1.2.0",
+ )
+ expected := "\ufeff# operator configuration\r\n\r\nservices:\r\n web:\r\n image: \"app:1.3.0\" # keep this comment\r\n " +
+ "environment:\r\n VERSION: ${VERSION}\r\n\r\n worker:\r\n image: 'docker.io/library/app:1.3.0' \r\n " +
+ "tagged:\r\n image: !!str app:1.3.0\r\n escaped:\r\n image: \"app:1.3.0\"\r\n untouched:\r\n image: " +
+ "app:1.2.0 # stays\r\n\r\r plain:\r\n image: app:1.3.0"
+ effective := &composetypes.Project{
+ Services: composetypes.Services{
+ "web": {
+ Image: "app:1.2.0",
+ },
+ "worker": {
+ Image: "app:1.2.0",
+ },
+ "tagged": {
+ Image: "app:1.2.0",
+ },
+ "escaped": {
+ Image: "app:1.2.0",
+ },
+ "untouched": {
+ Image: "app:1.2.0",
+ },
+ "plain": {
+ Image: "app:1.2.0",
+ },
+ },
+ }
updated, names, err := prepareProjectServiceImagesInternal(source, effective, map[string]updatertypes.ServiceImageChange{
"web": {ExpectedRef: "docker.io/library/app:1.2.0", TargetRef: "app:1.3.0"},
"worker": {ExpectedRef: "app:1.2.0", TargetRef: "docker.io/library/app:1.3.0"},
@@ -7377,7 +7484,7 @@ func TestPersistProjectServiceImages(t *testing.T) {
original := []byte("services: {}\n")
updated := []byte("services: {web: {image: app:1.3.0}}\n")
require.NoError(t, os.WriteFile(path, original, 0o600))
- ctx := context.Background()
+ ctx := t.Context()
switch name {
case "concurrent edit":
require.NoError(t, os.WriteFile(path, []byte("# operator edit\n"), 0o600))
@@ -7415,7 +7522,7 @@ func TestUpdateProjectServiceImagesRejectsManagedOrArchived(t *testing.T) {
}
require.NoError(t, db.Create(&proj).Error)
service := &ProjectService{db: db}
- err := service.UpdateProjectServiceImages(context.Background(), proj.ID, map[string]updatertypes.ServiceImageChange{"web": {ExpectedRef: "app:1.0.0", TargetRef: "app:1.1.0"}}, common.User{})
+ err := service.UpdateProjectServiceImages(t.Context(), proj.ID, map[string]updatertypes.ServiceImageChange{"web": {ExpectedRef: "app:1.0.0", TargetRef: "app:1.1.0"}}, common.User{})
require.Error(t, err)
if name == "archived" {
require.ErrorIs(t, err, common.ErrProjectArchived)
@@ -7438,7 +7545,7 @@ func (c *serviceImageCoordinatorInternal) UpdateServices(_ context.Context, requ
}
func TestUpdateProjectServiceImagesPersistsBeforeDeploymentAndRetries(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
directory := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", directory)
@@ -7457,13 +7564,13 @@ func TestUpdateProjectServiceImagesPersistsBeforeDeploymentAndRetries(t *testing
service := &ProjectService{db: db, settingsService: settingsService, eventService: event.NewEventService(db, nil, nil), composeCoordinator: coordinator}
changes := map[string]updatertypes.ServiceImageChange{"app": {ExpectedRef: "app:1.2.0", TargetRef: "app:1.3.0"}}
for range 2 {
- err := service.UpdateProjectServiceImages(ctx, proj.ID, changes, common.SystemUser)
- require.ErrorIs(t, err, deploymentError)
- content, err := os.ReadFile(filepath.Join(projectPath, "compose.yaml"))
- require.NoError(t, err)
+ updateProjectServiceImagesErr := service.UpdateProjectServiceImages(ctx, proj.ID, changes, common.SystemUser)
+ require.ErrorIs(t, updateProjectServiceImagesErr, deploymentError)
+ content, readComposeErr := os.ReadFile(filepath.Join(projectPath, "compose.yaml"))
+ require.NoError(t, readComposeErr)
require.Equal(t, "# keep\n\nservices:\n app:\n image: app:1.3.0\n\n worker:\n image: app:${VERSION}\n", string(content))
- mode, err := os.Stat(filepath.Join(projectPath, "compose.yaml"))
- require.NoError(t, err)
+ mode, statComposeErr := os.Stat(filepath.Join(projectPath, "compose.yaml"))
+ require.NoError(t, statComposeErr)
require.Equal(t, os.FileMode(0o600), mode.Mode().Perm())
}
require.Len(t, coordinator.requests, 2)
@@ -7477,7 +7584,7 @@ func TestUpdateProjectServiceImagesPersistsBeforeDeploymentAndRetries(t *testing
}
func TestUpdateProjectServiceImagesRejectsOverrideBeforeWriting(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
directory := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", directory)
@@ -7506,10 +7613,47 @@ func TestDiscoveredProjectTagUpdatesRemainScoped(t *testing.T) {
db := setupProjectTestDB(t)
target := "3.2.0"
tagLabels := map[string]string{labels.LabelUpdateStrategy: "tag"}
- require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "container::first", PolicyKey: imageref.UpdatePolicyKey("example:3.1.0", tagLabels), ContainerID: "first", ImageID: "shared", Repository: "docker.io/library/example", Tag: "3.1.0", HasUpdate: true, UpdateType: "tag", LatestVersion: &target, CheckTime: time.Now()}).Error)
+ require.NoError(
+ t,
+ db.Create(
+ &imageupdate.ImageUpdateRecord{
+ ID: "container::first",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "example:3.1.0",
+ tagLabels,
+ ),
+ ContainerID: "first",
+ ImageID: "shared",
+ Repository: "docker.io/library/example",
+ Tag: "3.1.0",
+ HasUpdate: true,
+ UpdateType: "tag",
+ LatestVersion: &target,
+ CheckTime: time.Now(),
+ },
+ ).Error,
+ )
containers := []container.Summary{
- {ID: "first-replica", Image: "example:3.1.0", ImageID: "shared", Labels: map[string]string{labels.LabelUpdateStrategy: "tag", "com.docker.compose.project": "first-project", "com.docker.compose.service": "web"}},
- {ID: "first", Image: "example:3.1.0", ImageID: "shared", Labels: map[string]string{labels.LabelUpdateStrategy: "tag", "com.docker.compose.project": "first-project", "com.docker.compose.service": "web"}},
+ {
+ ID: "first-replica",
+ Image: "example:3.1.0",
+ ImageID: "shared",
+ Labels: map[string]string{
+ labels.LabelUpdateStrategy: "tag",
+ "com.docker.compose.project": "first-project",
+ "com.docker.compose.service": "web",
+ },
+ },
+ {
+ ID: "first",
+ Image: "example:3.1.0",
+ ImageID: "shared",
+ Labels: map[string]string{
+ labels.LabelUpdateStrategy: "tag",
+ "com.docker.compose.project": "first-project",
+ "com.docker.compose.service": "web",
+ },
+ },
{ID: "second", Image: "example:3.1.0", ImageID: "shared", Labels: map[string]string{"com.docker.compose.project": "second-project", "com.docker.compose.service": "web"}},
}
imageSvc := image.NewImageService(db, nil, nil, nil, nil, nil)
@@ -7533,7 +7677,23 @@ func TestDiscoveredProjectTagUpdatesRemainScoped(t *testing.T) {
containers[1].Labels = map[string]string{labels.LabelUpdateStrategy: "tag", labels.LabelUpdater: "off", "com.docker.compose.project": "first-project", "com.docker.compose.service": "web"}
rows = buildDiscoveredComposeProjectUpdateRowsInternal(t.Context(), containers, nil, imageSvc, "")
require.Len(t, rows, 1, "updater=false containers keep their check results")
- for _, policy := range []map[string]string{{labels.LabelUpdateStrategy: "digest"}, {labels.LabelUpdateStrategy: "tag", labels.LabelUpdateConstraint: "3.1.x"}, {labels.LabelUpdateStrategy: "tag", labels.LabelUpdateTagPattern: ".*"}, {labels.LabelUpdateStrategy: "tag", imageref.UpdateCheckLabel: "off"}} {
+ for _, policy := range []map[string]string{
+ {
+ labels.LabelUpdateStrategy: "digest",
+ },
+ {
+ labels.LabelUpdateStrategy: "tag",
+ labels.LabelUpdateConstraint: "3.1.x",
+ },
+ {
+ labels.LabelUpdateStrategy: "tag",
+ labels.LabelUpdateTagPattern: ".*",
+ },
+ {
+ labels.LabelUpdateStrategy: "tag",
+ imageref.UpdateCheckLabel: "off",
+ },
+ } {
current := map[string]string{"com.docker.compose.project": "first-project", "com.docker.compose.service": "web"}
maps.Copy(current, policy)
containers[1].Labels = current
@@ -7561,7 +7721,24 @@ func TestProjectTagSummaryDoesNotMutateSharedReferenceResults(t *testing.T) {
// opted out of update checks, and kept while one still monitors it.
base = map[string]*imagetypes.UpdateInfo{"example:3.1.0": {HasUpdate: true, UpdateType: "digest"}, "other:1.0": {HasUpdate: true, UpdateType: "digest"}}
unmonitored := map[string]string{imageref.UpdateCheckLabel: "false"}
- merged = mergeProjectContainerUpdateInfoInternal(base, []projecttypes.RuntimeService{{ContainerID: "a", Image: "example:3.1.0", ContainerLabels: unmonitored}, {ContainerID: "b", Image: "example:3.1.0", ContainerLabels: map[string]string{labels.LabelUpdater: "false"}}}, nil)
+ merged = mergeProjectContainerUpdateInfoInternal(
+ base,
+ []projecttypes.RuntimeService{
+ {
+ ContainerID: "a",
+ Image: "example:3.1.0",
+ ContainerLabels: unmonitored,
+ },
+ {
+ ContainerID: "b",
+ Image: "example:3.1.0",
+ ContainerLabels: map[string]string{
+ labels.LabelUpdater: "false",
+ },
+ },
+ },
+ nil,
+ )
require.True(t, merged["example:3.1.0"].HasUpdate, "updater=false keeps the shared result")
require.True(t, merged["other:1.0"].HasUpdate, "references without runtime services are untouched")
merged = mergeProjectContainerUpdateInfoInternal(base, []projecttypes.RuntimeService{{ContainerID: "a", Image: "example:3.1.0", ContainerLabels: unmonitored}}, nil)
@@ -7573,15 +7750,41 @@ func TestCountProjectsWithPendingTagUpdatesUsesRuntimeContainers(t *testing.T) {
db := setupProjectTestDB(t)
settingsService, err := newSettingsServiceForTestInternal(t, t.Context(), db)
require.NoError(t, err)
- projects := []Project{
+ projectRecords := []Project{
{Name: "first", Path: "first", ImageRefsJSON: `["example:3.1.0"]`},
{Name: "second", Path: "second", ImageRefsJSON: `["example:3.1.0"]`},
}
- require.NoError(t, db.Create(&projects).Error)
- require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "container::first-container", PolicyKey: imageref.UpdatePolicyKey("example:3.1.0", map[string]string{labels.LabelUpdateStrategy: "tag"}), ContainerID: "first-container", ImageID: "shared", HasUpdate: true, UpdateType: "tag"}).Error)
+ require.NoError(t, db.Create(&projectRecords).Error)
+ require.NoError(
+ t,
+ db.Create(
+ &imageupdate.ImageUpdateRecord{
+ ID: "container::first-container",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "example:3.1.0",
+ map[string]string{
+ labels.LabelUpdateStrategy: "tag",
+ },
+ ),
+ ContainerID: "first-container",
+ ImageID: "shared",
+ HasUpdate: true,
+ UpdateType: "tag",
+ },
+ ).Error,
+ )
service := &ProjectService{db: db, settingsService: settingsService, imageService: image.NewImageService(db, nil, nil, nil, nil, nil)}
containers := []container.Summary{
- {ID: "first-container", Image: "example:3.1.0", ImageID: "shared", Labels: map[string]string{labels.LabelUpdateStrategy: "tag", "com.docker.compose.project": "first", "com.docker.compose.service": "web"}},
+ {
+ ID: "first-container",
+ Image: "example:3.1.0",
+ ImageID: "shared",
+ Labels: map[string]string{
+ labels.LabelUpdateStrategy: "tag",
+ "com.docker.compose.project": "first",
+ "com.docker.compose.service": "web",
+ },
+ },
{ID: "second-container", Image: "example:3.1.0", ImageID: "shared", Labels: map[string]string{"com.docker.compose.project": "second", "com.docker.compose.service": "web"}},
}
count, err := service.CountProjectsWithPendingUpdates(t.Context(), containers)
@@ -7598,7 +7801,16 @@ func TestCountProjectsWithPendingTagUpdatesUsesRuntimeContainers(t *testing.T) {
require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "moving-image", Repository: "docker.io/library/app", Tag: "stable", HasUpdate: true, UpdateType: "digest"}).Error)
containers = append(containers,
container.Summary{ID: "third-one", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{"com.docker.compose.project": "third", "com.docker.compose.service": "web"}},
- container.Summary{ID: "third-two", Image: "app:latest", ImageID: "moving-image", Labels: map[string]string{"com.docker.compose.project": "third", "com.docker.compose.service": "web", labels.LabelUpdater: "false"}},
+ container.Summary{
+ ID: "third-two",
+ Image: "app:latest",
+ ImageID: "moving-image",
+ Labels: map[string]string{
+ "com.docker.compose.project": "third",
+ "com.docker.compose.service": "web",
+ labels.LabelUpdater: "false",
+ },
+ },
)
count, err = service.CountProjectsWithPendingUpdates(t.Context(), containers)
require.NoError(t, err)
@@ -7647,7 +7859,7 @@ func TestProjectServiceManualUpdateDiscoversTags(t *testing.T) {
{name: "explicit digest optout", tags: []string{"1.2.0", "1.3.0"}, wantRef: "app:1.2.0", strategy: "digest"},
} {
t.Run(tt.name, func(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDB(t)
directory := t.TempDir()
require.NoError(t, db.AutoMigrate(&registry.ContainerRegistry{}))
@@ -7656,7 +7868,9 @@ func TestProjectServiceManualUpdateDiscoversTags(t *testing.T) {
require.NoError(t, err)
require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", directory))
path := createComposeProjectDir(t, directory, "manual-tag")
- source := "services:\n app:\n image: app:1.2.0\n labels:\n com.getarcaneapp.arcane.updater.strategy: tag\n com.getarcaneapp.arcane.updater.constraint: 1.x\n selected-digest:\n image: busybox:latest\n unselected:\n image: busybox:latest\n"
+ source := "services:\n app:\n image: app:1.2.0\n labels:\n com.getarcaneapp.arcane.updater.strategy: " +
+ "tag\n com.getarcaneapp.arcane.updater.constraint: 1.x\n selected-digest:\n image: " +
+ "busybox:latest\n unselected:\n image: busybox:latest\n"
if tt.omitLabels {
source = strings.Replace(source, " labels:\n com.getarcaneapp.arcane.updater.strategy: tag\n com.getarcaneapp.arcane.updater.constraint: 1.x\n", "", 1)
} else if tt.strategy != "" {
@@ -7702,10 +7916,10 @@ func TestProjectServiceManualUpdateRejectsUnsafeTagPolicies(t *testing.T) {
{name: "digest pin", change: func(s *composetypes.ServiceConfig) { s.Image = "app@sha256:" + strings.Repeat("a", 64) }},
} {
t.Run(tt.name, func(t *testing.T) {
- config := composetypes.ServiceConfig{Image: "app:1.2.0", Labels: composetypes.Labels{labels.LabelUpdateStrategy: "tag"}}
- tt.change(&config)
+ serviceConfig := composetypes.ServiceConfig{Image: "app:1.2.0", Labels: composetypes.Labels{labels.LabelUpdateStrategy: "tag"}}
+ tt.change(&serviceConfig)
service := &ProjectService{}
- changes, err := service.projectServiceImageChangesInternal(context.Background(), &Project{}, &composetypes.Project{Services: composetypes.Services{"app": config}})
+ changes, err := service.projectServiceImageChangesInternal(t.Context(), &Project{}, &composetypes.Project{Services: composetypes.Services{"app": serviceConfig}})
require.Error(t, err)
require.NotContains(t, err.Error(), "registry service unavailable")
require.Nil(t, changes)
@@ -7754,7 +7968,20 @@ func TestStoppedProjectTagPolicyNeverInheritsSharedDigestCheck(t *testing.T) {
require.NoError(t, err)
require.NoError(t, settingsService.SetStringSetting(t.Context(), "projectsDirectory", projectsDir))
projectPath := createComposeProjectDir(t, projectsDir, "tag-stopped")
- require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("x-arcane:\n hidden: true\nservices:\n app:\n image: nginx:3.1.0\n labels:\n com.getarcaneapp.arcane.updater.strategy: tag\n com.getarcaneapp.arcane.updater.constraint: 3.x\n"), 0o644))
+ require.NoError(
+ t,
+ os.WriteFile(
+ filepath.Join(
+ projectPath,
+ "compose.yaml",
+ ),
+ []byte(
+ "x-arcane:\n hidden: true\nservices:\n app:\n image: nginx:3.1.0\n labels:\n "+
+ "com.getarcaneapp.arcane.updater.strategy: tag\n com.getarcaneapp.arcane.updater.constraint: 3.x\n",
+ ),
+ 0o644,
+ ),
+ )
projectRecord := &Project{ID: "tag-stopped", Name: "tag-stopped", DirName: new("tag-stopped"), Path: projectPath, Status: ProjectStatusStopped, ImageRefsJSON: `["nginx:3.1.0"]`}
require.NoError(t, db.Create(projectRecord).Error)
require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "shared-digest", Repository: "docker.io/library/nginx", Tag: "3.1.0", UpdateType: "digest", CheckTime: time.Now()}).Error)
@@ -7770,7 +7997,24 @@ func TestStoppedProjectTagPolicyNeverInheritsSharedDigestCheck(t *testing.T) {
require.Nil(t, list[0].UpdateInfo.ServiceUpdates["app"].UpdateInfo)
target := "3.2.0"
policy := map[string]string{labels.LabelUpdateStrategy: "tag", labels.LabelUpdateConstraint: "3.x"}
- require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "project::tag-stopped::app", ProjectID: projectRecord.ID, ServiceName: "app", PolicyKey: imageref.UpdatePolicyKey("nginx:3.1.0", policy), HasUpdate: true, UpdateType: "tag", LatestVersion: &target, CheckTime: time.Now()}).Error)
+ require.NoError(
+ t,
+ db.Create(
+ &imageupdate.ImageUpdateRecord{
+ ID: "project::tag-stopped::app",
+ ProjectID: projectRecord.ID,
+ ServiceName: "app",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "nginx:3.1.0",
+ policy,
+ ),
+ HasUpdate: true,
+ UpdateType: "tag",
+ LatestVersion: &target,
+ CheckTime: time.Now(),
+ },
+ ).Error,
+ )
detail, err = service.GetProjectDetails(t.Context(), projectRecord.ID, projecttypes.AllDetails())
require.NoError(t, err)
require.Equal(t, "has_update", detail.UpdateInfo.Status)
@@ -7812,15 +8056,36 @@ func TestConfiguredProjectUsesScheduledRuntimeChecks(t *testing.T) {
proj := Project{ID: "scheduled-project", Name: "scheduled-project", Path: path}
require.NoError(t, db.Create(&proj).Error)
target := "3.2.0"
- require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "container::scheduled", ContainerID: "scheduled", ImageID: "shared", PolicyKey: imageref.UpdatePolicyKey("example:3.1.0", map[string]string{labels.LabelUpdateStrategy: "auto"}), Repository: "docker.io/library/example", Tag: "3.1.0", LatestVersion: &target, HasUpdate: true, UpdateType: "tag", CheckTime: time.Now()}).Error)
+ require.NoError(
+ t,
+ db.Create(
+ &imageupdate.ImageUpdateRecord{
+ ID: "container::scheduled",
+ ContainerID: "scheduled",
+ ImageID: "shared",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "example:3.1.0",
+ map[string]string{
+ labels.LabelUpdateStrategy: "auto",
+ },
+ ),
+ Repository: "docker.io/library/example",
+ Tag: "3.1.0",
+ LatestVersion: &target,
+ HasUpdate: true,
+ UpdateType: "tag",
+ CheckTime: time.Now(),
+ },
+ ).Error,
+ )
runtimeLabels := map[string]string{"com.docker.compose.project": "scheduled-project", "com.docker.compose.service": "web", labels.LabelUpdateStrategy: "auto"}
runtimeLabels[labels.LabelUpdateConstraint] = cmp.Or(tt.runtimeConstraint, runtimeLabels[labels.LabelUpdateConstraint])
- runtime := []projecttypes.RuntimeService{{Name: "web", ContainerID: "scheduled", Image: "example:3.1.0", ContainerLabels: runtimeLabels}}
+ runtimeServices := []projecttypes.RuntimeService{{Name: "web", ContainerID: "scheduled", Image: "example:3.1.0", ContainerLabels: runtimeLabels}}
service := &ProjectService{db: db, settingsService: settingsService, imageService: image.NewImageService(db, nil, nil, nil, nil, nil)}
- detail := projecttypes.Details{ID: proj.ID, Services: []composetypes.ServiceConfig{{Name: "web", Image: tt.sourceRef, Labels: sourceLabels}}, RuntimeServices: runtime}
+ detail := projecttypes.Details{ID: proj.ID, Services: []composetypes.ServiceConfig{{Name: "web", Image: tt.sourceRef, Labels: sourceLabels}}, RuntimeServices: runtimeServices}
service.enrichProjectUpdateInfoInternal(ctx, &detail)
require.Equal(t, tt.wantUpdate, detail.UpdateInfo.HasUpdate)
- list := []projecttypes.Details{{ID: proj.ID, RuntimeServices: runtime}}
+ list := []projecttypes.Details{{ID: proj.ID, RuntimeServices: runtimeServices}}
service.enrichProjectsWithUpdateInfoInternal(ctx, []Project{proj}, list, true, nil)
require.Equal(t, tt.wantUpdate, list[0].UpdateInfo.HasUpdate)
for _, info := range []*projecttypes.UpdateInfo{detail.UpdateInfo, list[0].UpdateInfo} {
@@ -7837,7 +8102,7 @@ func TestConfiguredProjectUsesScheduledRuntimeChecks(t *testing.T) {
func TestConfiguredProjectAggregatesReplicaAndPreviewChecks(t *testing.T) {
configs := []composetypes.ServiceConfig{{Name: "web", Image: "example:3.1.0"}}
- runtime := []projecttypes.RuntimeService{
+ runtimeServices := []projecttypes.RuntimeService{
{Name: "web", ContainerID: "one", Image: "example:3.1.0"},
{Name: "web", ContainerID: "two", Image: "docker.io/library/example:3.1.0"},
{Name: "other", ContainerID: "unrelated", Image: "example:3.1.0"},
@@ -7847,12 +8112,24 @@ func TestConfiguredProjectAggregatesReplicaAndPreviewChecks(t *testing.T) {
"two": {HasUpdate: true, LatestVersion: "3.2.0", UpdateType: "tag"},
"unrelated": {HasUpdate: true, LatestVersion: "4.0.0", UpdateType: "tag"},
}
- runtimeUpdates := configuredRuntimeServiceUpdateInfoInternal(configs, runtime, scoped)
+ runtimeUpdates := configuredRuntimeServiceUpdateInfoInternal(configs, runtimeServices, scoped)
require.Len(t, runtimeUpdates, 1)
require.True(t, runtimeUpdates["web"].HasUpdate)
require.Empty(t, runtimeUpdates["web"].LatestVersion, "conflicting replica targets must not choose an arbitrary version")
previewTarget := "3.3.0"
- records := []imageupdate.ImageUpdateRecord{{ProjectID: "project", ServiceName: "web", PolicyKey: imageref.UpdatePolicyKey("example:3.1.0", nil), HasUpdate: true, LatestVersion: &previewTarget, UpdateType: "tag"}}
+ records := []imageupdate.ImageUpdateRecord{
+ {
+ ProjectID: "project",
+ ServiceName: "web",
+ PolicyKey: imageref.UpdatePolicyKey(
+ "example:3.1.0",
+ nil,
+ ),
+ HasUpdate: true,
+ LatestVersion: &previewTarget,
+ UpdateType: "tag",
+ },
+ }
summary := BuildConfiguredUpdateInfo("project", configs, nil, records, runtimeUpdates)
require.True(t, summary.HasUpdate)
require.Empty(t, summary.ServiceUpdates["web"].UpdateInfo.LatestVersion)
@@ -7902,7 +8179,7 @@ func TestPrepareProjectBindDirectoriesInternal(t *testing.T) {
composetypes.ServiceVolumeConfig{Type: composetypes.VolumeTypeVolume, Source: "named", Target: "/v"},
)
- require.NoError(t, prepareProjectBindDirectoriesInternal(projectPath)(context.Background(), project))
+ require.NoError(t, prepareProjectBindDirectoriesInternal(projectPath)(t.Context(), project))
assert.DirExists(t, filepath.Join(projectPath, "caddy", "conf"))
assert.DirExists(t, filepath.Join(projectPath, "plain"), "long syntax without bind block is auto-created like the daemon would")
@@ -7934,7 +8211,7 @@ func TestPrepareProjectBindDirectoriesInternal(t *testing.T) {
bind(filepath.Join(projectPath, "local", "conf")),
)
- require.NoError(t, prepareProjectBindDirectoriesInternal(projectPath)(context.Background(), project))
+ require.NoError(t, prepareProjectBindDirectoriesInternal(projectPath)(t.Context(), project))
info, err := os.Stat(existingExternal)
require.NoError(t, err)
@@ -7949,11 +8226,11 @@ func TestPrepareProjectBindDirectoriesInternal(t *testing.T) {
projectPath := t.TempDir()
require.NoError(t, os.Symlink("loop", filepath.Join(projectPath, "loop")))
- err := prepareProjectBindDirectoriesInternal(projectPath)(context.Background(), newProject(bind(filepath.Join(projectPath, "loop", "conf"))))
+ err := prepareProjectBindDirectoriesInternal(projectPath)(t.Context(), newProject(bind(filepath.Join(projectPath, "loop", "conf"))))
require.ErrorIs(t, err, acfs.ErrSymlinkLoop)
assert.Contains(t, err.Error(), "service app")
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
cancel()
err = prepareProjectBindDirectoriesInternal(projectPath)(ctx, newProject(bind(filepath.Join(projectPath, "conf"))))
require.ErrorIs(t, err, context.Canceled)
diff --git a/backend/internal/project/service_unix_test.go b/backend/internal/project/service_unix_test.go
index 25706e4c0..90a1b1edf 100644
--- a/backend/internal/project/service_unix_test.go
+++ b/backend/internal/project/service_unix_test.go
@@ -29,7 +29,7 @@ func TestProjectService_ApplyGitSyncProjectFiles_TolerantOfPermissionLockedEnv(t
}
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
@@ -128,7 +128,7 @@ func TestPrepareProjectBindDirectoriesInternal_PermissionFailure(t *testing.T) {
}}},
}}
- err := prepareProjectBindDirectoriesInternal(projectPath)(context.Background(), project)
+ err := prepareProjectBindDirectoriesInternal(projectPath)(t.Context(), project)
if tc.wantError {
require.ErrorIs(t, err, fs.ErrPermission)
assert.Contains(t, err.Error(), source)
@@ -141,8 +141,8 @@ func TestPrepareProjectBindDirectoriesInternal_PermissionFailure(t *testing.T) {
assert.Equal(t, tc.dirMode, dirInfo.Mode().Perm())
require.NoError(t, os.Chmod(locked, 0o700))
if !tc.createFile {
- _, err := os.Lstat(source)
- require.ErrorIs(t, err, fs.ErrNotExist)
+ _, lstatErr := os.Lstat(source)
+ require.ErrorIs(t, lstatErr, fs.ErrNotExist)
return
}
info, err := os.Stat(source)
@@ -162,7 +162,7 @@ func newEnvDirectoryProjectInternal(t *testing.T, id string) (*ProjectService, *
t.Helper()
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
diff --git a/backend/internal/project/sync.go b/backend/internal/project/sync.go
index f67307ec0..3c19e7603 100644
--- a/backend/internal/project/sync.go
+++ b/backend/internal/project/sync.go
@@ -58,14 +58,14 @@ func (s *ProjectService) refreshProjectImageRefsInternal(ctx context.Context, pr
}
imageRefsJSON := projects.MarshalImageRefsJSON(refs)
buildImageRefsJSON := cmp.Or(projects.MarshalImageRefsJSON(buildRefs), "[]")
- if err := s.db.WithContext(ctx).
+ if persistImageRefsErr := s.db.WithContext(ctx).
Model(&Project{}).
Where("id = ?", proj.ID).
Updates(map[string]any{
"image_refs_json": imageRefsJSON,
"build_image_refs_json": buildImageRefsJSON,
- }).Error; err != nil {
- slog.WarnContext(ctx, "failed to persist project image refs", "projectID", proj.ID, "error", err)
+ }).Error; persistImageRefsErr != nil {
+ slog.WarnContext(ctx, "failed to persist project image refs", "projectID", proj.ID, "error", persistImageRefsErr)
return
}
proj.ImageRefsJSON = imageRefsJSON
@@ -85,8 +85,8 @@ func (s *ProjectService) HandleProjectFilesChanged(ctx context.Context, paths []
for i := range affected {
s.invalidateProjectCachesInternal(affected[i].ID)
s.refreshProjectImageRefsInternal(ctx, &affected[i])
- if err := s.reconcileComposeTagsForProjectInternal(ctx, &affected[i]); err != nil {
- slog.WarnContext(ctx, "failed to reconcile Compose project tags after file change", "projectID", affected[i].ID, "error", err)
+ if reconcileComposeTagsForProjectErr := s.reconcileComposeTagsForProjectInternal(ctx, &affected[i]); reconcileComposeTagsForProjectErr != nil {
+ slog.WarnContext(ctx, "failed to reconcile Compose project tags after file change", "projectID", affected[i].ID, "error", reconcileComposeTagsForProjectErr)
}
}
}
@@ -341,7 +341,9 @@ func cleanupWouldMassWipeInternal(ctx context.Context, candidates, deleteCount i
}
slog.WarnContext(ctx,
- "skipping project cleanup: this reconcile would delete most projects in a single pass, which usually means the projects directory is empty, unmounted, or mis-mapped; preserving DB records — check the projects volume is mounted and mapped correctly",
+ "skipping project cleanup: this reconcile would delete most projects in a single pass, which usually "+
+ "means the projects directory is empty, unmounted, or mis-mapped; preserving DB records — check the "+
+ "projects volume is mounted and mapped correctly",
"wouldDelete", deleteCount,
"cleanupCandidates", candidates,
"projectsDir", projectsDir,
@@ -404,7 +406,7 @@ func (s *ProjectService) projectExceedsScanDepthInternal(p Project, projectsDir
}
rel := getProjectRelativePathInternal(projectsDir, p.Path)
- return rel != "" && strings.Count(rel, "/")+1 > maxDepth
+ return rel != "" && strings.Count(rel, "/") >= maxDepth
}
func evaluateProjectPathErrorInternal(ctx context.Context, p Project, err error) mo.Option[projectCleanupDecision] {
@@ -573,8 +575,8 @@ func persistEffectiveEnvContentInternal(ctx context.Context, projectPath, projec
if !state.HasGitSource {
if state.HasOverride {
- if err := projects.RemoveProjectFile(ctx, projectsDirectory, projectPath, projects.OverrideEnvFileName); err != nil {
- return err
+ if removeProjectFileErr := projects.RemoveProjectFile(ctx, projectsDirectory, projectPath, projects.OverrideEnvFileName); removeProjectFileErr != nil {
+ return removeProjectFileErr
}
}
return projects.WriteManagedEnvFile(ctx, projectsDirectory, projectPath, projects.EffectiveEnvFileName, state.EffectiveUnreadable, envContent)
@@ -590,8 +592,15 @@ func persistEffectiveEnvContentInternal(ctx context.Context, projectPath, projec
return fmt.Errorf("build effective env content: %w", err)
}
- if err := projects.WriteManagedEnvFile(ctx, projectsDirectory, projectPath, projects.EffectiveEnvFileName, state.EffectiveUnreadable, effectiveContent); err != nil {
- return err
+ if writeManagedEnvFileErr := projects.WriteManagedEnvFile(
+ ctx,
+ projectsDirectory,
+ projectPath,
+ projects.EffectiveEnvFileName,
+ state.EffectiveUnreadable,
+ effectiveContent,
+ ); writeManagedEnvFileErr != nil {
+ return writeManagedEnvFileErr
}
return projects.WriteManagedEnvFile(ctx, projectsDirectory, projectPath, projects.OverrideEnvFileName, state.OverrideUnreadable, overrideContent)
@@ -605,12 +614,12 @@ func (s *ProjectService) ensureEffectiveEnvFileInternal(ctx context.Context, pro
if !state.HasGitSource {
if state.HasOverride {
- if err := projects.RemoveProjectFile(ctx, projectsDirectory, projectPath, projects.OverrideEnvFileName); err != nil {
- return err
+ if removeProjectFileErr := projects.RemoveProjectFile(ctx, projectsDirectory, projectPath, projects.OverrideEnvFileName); removeProjectFileErr != nil {
+ return removeProjectFileErr
}
- effectiveContent, err := resolveStoredEffectiveEnvContentInternal(state)
- if err != nil {
- return err
+ effectiveContent, resolveStoredEffectiveEnvContentErr := resolveStoredEffectiveEnvContentInternal(state)
+ if resolveStoredEffectiveEnvContentErr != nil {
+ return resolveStoredEffectiveEnvContentErr
}
return projects.WriteManagedEnvFile(ctx, projectsDirectory, projectPath, projects.EffectiveEnvFileName, state.EffectiveUnreadable, effectiveContent)
}
@@ -637,9 +646,9 @@ func (s *ProjectService) prepareGitSyncEnvUpdateInternal(projectPath string, git
}
if gitEnvContent == nil {
- effectiveContent, err := resolveStoredEffectiveEnvContentInternal(state)
- if err != nil {
- return gitSyncEnvUpdateInternal{}, err
+ effectiveContent, resolveStoredEffectiveEnvContentErr := resolveStoredEffectiveEnvContentInternal(state)
+ if resolveStoredEffectiveEnvContentErr != nil {
+ return gitSyncEnvUpdateInternal{}, resolveStoredEffectiveEnvContentErr
}
if effectiveContent == "" && !state.HasEffective && !state.HasGitSource && !state.HasOverride {
return update, nil
@@ -743,8 +752,8 @@ func (s *ProjectService) ApplyGitSyncEnvToDirectory(ctx context.Context, project
if update.effectiveContent != nil {
after = *update.effectiveContent
}
- if err := persistGitSyncEnvFilesInternal(ctx, projectPath, projectsDirectory, update); err != nil {
- return "", "", fmt.Errorf("failed to sync git env files: %w", err)
+ if persistGitSyncEnvFilesErr := persistGitSyncEnvFilesInternal(ctx, projectPath, projectsDirectory, update); persistGitSyncEnvFilesErr != nil {
+ return "", "", fmt.Errorf("failed to sync git env files: %w", persistGitSyncEnvFilesErr)
}
return before, after, nil
}
diff --git a/backend/internal/project/tags.go b/backend/internal/project/tags.go
index e5e6ce0c5..70b2b3b9a 100644
--- a/backend/internal/project/tags.go
+++ b/backend/internal/project/tags.go
@@ -61,53 +61,53 @@ func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name s
var projectModel Project
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&projectModel, "id = ?", projectID).Error; err != nil {
- return fmt.Errorf("find project for tag update: %w", err)
+ if findProjectErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&projectModel, "id = ?", projectID).Error; findProjectErr != nil {
+ return fmt.Errorf("find project for tag update: %w", findProjectErr)
}
var composeCount int64
- if err := tx.Model(&ProjectTag{}).
+ if countComposeTagsErr := tx.Model(&ProjectTag{}).
Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceCompose).
- Count(&composeCount).Error; err != nil {
- return fmt.Errorf("check Compose tag source: %w", err)
+ Count(&composeCount).Error; countComposeTagsErr != nil {
+ return fmt.Errorf("check Compose tag source: %w", countComposeTagsErr)
}
if composeCount > 0 {
return errComposeTagReadOnly
}
if !attached {
- if err := tx.Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).
- Delete(&ProjectTag{}).Error; err != nil {
- return fmt.Errorf("detach UI project tag: %w", err)
+ if detachTagErr := tx.Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).
+ Delete(&ProjectTag{}).Error; detachTagErr != nil {
+ return fmt.Errorf("detach UI project tag: %w", detachTagErr)
}
return nil
}
var existing int64
- if err := tx.Model(&ProjectTag{}).
+ if countExistingTagsErr := tx.Model(&ProjectTag{}).
Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).
- Count(&existing).Error; err != nil {
- return fmt.Errorf("check UI tag source: %w", err)
+ Count(&existing).Error; countExistingTagsErr != nil {
+ return fmt.Errorf("check UI tag source: %w", countExistingTagsErr)
}
if existing > 0 {
return nil
}
var count int64
- if err := tx.Model(&ProjectTag{}).
+ if countUITagsErr := tx.Model(&ProjectTag{}).
Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceUI).
- Count(&count).Error; err != nil {
- return fmt.Errorf("count UI project tags: %w", err)
+ Count(&count).Error; countUITagsErr != nil {
+ return fmt.Errorf("count UI project tags: %w", countUITagsErr)
}
if count >= projectpkg.ProjectTagsPerSourceLimit {
return fmt.Errorf("a project cannot have more than %d UI tags", projectpkg.ProjectTagsPerSourceLimit)
}
- resolvedColor, err := resolveProjectTagColorInternal(tx, normalized, normalizedColor)
- if err != nil {
- return err
+ resolvedColor, resolveProjectTagColorErr := resolveProjectTagColorInternal(tx, normalized, normalizedColor)
+ if resolveProjectTagColorErr != nil {
+ return resolveProjectTagColorErr
}
row := ProjectTag{ProjectID: projectID, Name: normalized, Source: string(projecttypes.TagSourceUI), Color: string(resolvedColor)}
- if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; err != nil {
- return fmt.Errorf("attach UI project tag: %w", err)
+ if attachTagErr := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error; attachTagErr != nil {
+ return fmt.Errorf("attach UI project tag: %w", attachTagErr)
}
return nil
})
@@ -127,11 +127,11 @@ func (s *ProjectService) reconcileComposeProjectTagsInternal(ctx context.Context
}
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var projectModel Project
- if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").First(&projectModel, "id = ?", projectID).Error; err != nil {
- return fmt.Errorf("find project for Compose tag reconciliation: %w", err)
+ if findProjectErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").First(&projectModel, "id = ?", projectID).Error; findProjectErr != nil {
+ return fmt.Errorf("find project for Compose tag reconciliation: %w", findProjectErr)
}
- if err := tx.Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceCompose).Delete(&ProjectTag{}).Error; err != nil {
- return fmt.Errorf("clear Compose project tags: %w", err)
+ if clearComposeTagsErr := tx.Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceCompose).Delete(&ProjectTag{}).Error; clearComposeTagsErr != nil {
+ return fmt.Errorf("clear Compose project tags: %w", clearComposeTagsErr)
}
if len(normalized) == 0 {
return nil
@@ -140,8 +140,8 @@ func (s *ProjectService) reconcileComposeProjectTagsInternal(ctx context.Context
for _, tag := range normalized {
rows = append(rows, ProjectTag{ProjectID: projectID, Name: tag.Name, Source: string(projecttypes.TagSourceCompose), Color: string(tag.Color)})
}
- if err := tx.Create(&rows).Error; err != nil {
- return fmt.Errorf("replace Compose project tags: %w", err)
+ if replaceComposeTagsErr := tx.Create(&rows).Error; replaceComposeTagsErr != nil {
+ return fmt.Errorf("replace Compose project tags: %w", replaceComposeTagsErr)
}
return nil
})
diff --git a/backend/internal/project/tags_test.go b/backend/internal/project/tags_test.go
index 66c078170..c2c261462 100644
--- a/backend/internal/project/tags_test.go
+++ b/backend/internal/project/tags_test.go
@@ -1,7 +1,6 @@
package project
import (
- "context"
"testing"
projecttypes "github.com/getarcaneapp/arcane/types/v2/project"
@@ -13,7 +12,7 @@ import (
func TestProjectTags_ReconcilePreservesUIAndComposeOwnershipIsReadOnly(t *testing.T) {
db := setupProjectTestDB(t)
service := &ProjectService{db: db}
- ctx := context.Background()
+ ctx := t.Context()
projectModel := Project{
ID: "project-tags",
Name: "tagged",
@@ -52,7 +51,7 @@ func TestProjectTags_ReconcilePreservesUIAndComposeOwnershipIsReadOnly(t *testin
func TestProjectTags_FilterUsesExactORNames(t *testing.T) {
db := setupProjectTestDB(t)
- ctx := context.Background()
+ ctx := t.Context()
projects := []Project{
{ID: "one", Name: "one", Path: "/tmp/one", Status: ProjectStatusStopped},
{ID: "two", Name: "two", Path: "/tmp/two", Status: ProjectStatusStopped},
diff --git a/backend/internal/project/update.go b/backend/internal/project/update.go
index c93dff824..3bf6ae297 100644
--- a/backend/internal/project/update.go
+++ b/backend/internal/project/update.go
@@ -43,15 +43,15 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, na
name = resolveAuthoritativeProjectNameInternal(ctx, &proj, name, composeContent)
renameRequested := isProjectRenameRequestedInternal(&proj, name)
- if err := s.recoverProjectRenameJournalForProjectInternal(ctx, projectID); err != nil {
+ if recoverProjectRenameJournalForProjectErr := s.recoverProjectRenameJournalForProjectInternal(ctx, projectID); recoverProjectRenameJournalForProjectErr != nil {
if renameRequested {
- return nil, err
+ return nil, recoverProjectRenameJournalForProjectErr
}
- slog.WarnContext(ctx, "project rename journal recovery failed before non-rename update; continuing", "projectID", projectID, "error", err)
+ slog.WarnContext(ctx, "project rename journal recovery failed before non-rename update; continuing", "projectID", projectID, "error", recoverProjectRenameJournalForProjectErr)
} else {
- proj, projectsDirectory, err = s.getProjectForUpdate(ctx, projectID)
- if err != nil {
- return nil, err
+ proj, projectsDirectory, recoverProjectRenameJournalForProjectErr = s.getProjectForUpdate(ctx, projectID)
+ if recoverProjectRenameJournalForProjectErr != nil {
+ return nil, recoverProjectRenameJournalForProjectErr
}
name = resolveAuthoritativeProjectNameInternal(ctx, &proj, name, composeContent)
}
@@ -59,11 +59,11 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, na
if proj.IsArchived {
return nil, common.Classify(common.ErrProjectArchived, errors.New("project is archived and must be unarchived before this action"))
}
- if err := ensureProjectEnvReadableInternal(ctx, projectsDirectory, proj.Path); err != nil {
- return nil, err
+ if ensureProjectEnvReadableErr := ensureProjectEnvReadableInternal(ctx, projectsDirectory, proj.Path); ensureProjectEnvReadableErr != nil {
+ return nil, ensureProjectEnvReadableErr
}
- if err := s.ensureProjectStoppedForRenameInternal(ctx, &proj, name); err != nil {
- return nil, err
+ if ensureProjectStoppedForRenameErr := s.ensureProjectStoppedForRenameInternal(ctx, &proj, name); ensureProjectStoppedForRenameErr != nil {
+ return nil, ensureProjectStoppedForRenameErr
}
volumeMigration, err := s.prepareProjectRenameVolumeMigrationForUpdateInternal(ctx, &proj, name, projectsDirectory, composeContent, envContent, overrideContent)
@@ -81,17 +81,29 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, na
journalActive := renameJournal != nil
if journalActive {
- if err := s.writeProjectRenameJournalInternal(ctx, renameJournal, projecttypes.RenameJournalPhaseStarted); err != nil {
- return nil, err
+ if writeProjectRenameJournalErr := s.writeProjectRenameJournalInternal(ctx, renameJournal, projecttypes.RenameJournalPhaseStarted); writeProjectRenameJournalErr != nil {
+ return nil, writeProjectRenameJournalErr
}
}
projectStateCommitted := false
- if err := withProjectRenameRollbackInternal(ctx, &proj, &projectStateCommitted, func() error {
- return s.applyProjectUpdateWithRenameJournalInternal(ctx, &proj, name, projectsDirectory, composeContent, envContent, overrideContent, volumeMigration, renameJournal, &journalActive, &projectStateCommitted)
- }); err != nil {
- err = s.handleProjectUpdateFailureInternal(ctx, projectID, projectsDirectory, &proj, backup, &journalActive, projectStateCommitted, err)
- return nil, err
+ if withProjectRenameRollbackErr := withProjectRenameRollbackInternal(ctx, &proj, &projectStateCommitted, func() error {
+ return s.applyProjectUpdateWithRenameJournalInternal(
+ ctx,
+ &proj,
+ name,
+ projectsDirectory,
+ composeContent,
+ envContent,
+ overrideContent,
+ volumeMigration,
+ renameJournal,
+ &journalActive,
+ &projectStateCommitted,
+ )
+ }); withProjectRenameRollbackErr != nil {
+ withProjectRenameRollbackErr = s.handleProjectUpdateFailureInternal(ctx, projectID, projectsDirectory, &proj, backup, &journalActive, projectStateCommitted, withProjectRenameRollbackErr)
+ return nil, withProjectRenameRollbackErr
}
s.refreshProjectAfterContentUpdateInternal(ctx, &proj, composeContent, overrideContent)
@@ -111,7 +123,15 @@ func ensureProjectEnvReadableInternal(ctx context.Context, projectsDirectory, pr
if cfgErr == nil || !cfgErr.BlocksOperations {
return nil
}
- return common.Classify(common.ErrProjectEnvUnreadable, fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it", cfgErr.Path, cfgErr.UID, cfgErr.GID))
+ return common.Classify(
+ common.ErrProjectEnvUnreadable,
+ fmt.Errorf(
+ "%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it",
+ cfgErr.Path,
+ cfgErr.UID,
+ cfgErr.GID,
+ ),
+ )
}
// resolveAuthoritativeProjectNameInternal enforces that a top-level `name:` in
@@ -135,7 +155,17 @@ func resolveAuthoritativeProjectNameInternal(ctx context.Context, proj *Project,
return name
}
-func (s *ProjectService) prepareProjectUpdateBackupInternal(ctx context.Context, projectsDirectory, projectPath string, composeContent, envContent, overrideContent *string) (*projects.ProjectUpdateBackup, func(), error) {
+func (
+ s *ProjectService,
+) prepareProjectUpdateBackupInternal(
+ ctx context.Context,
+ projectsDirectory, projectPath string,
+ composeContent, envContent, overrideContent *string,
+) (
+ *projects.ProjectUpdateBackup,
+ func(),
+ error,
+) {
if composeContent == nil && envContent == nil && overrideContent == nil {
return nil, func() {}, nil
}
@@ -148,7 +178,20 @@ func (s *ProjectService) prepareProjectUpdateBackupInternal(ctx context.Context,
return projects.BackupProjectDirectory(ctx, projectsDirectory, projectPath, ".project-update-backup-*", scope)
}
-func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context.Context, proj *Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, volumeMigration volumetypes.Migration, renameJournal *projecttypes.RenameJournal, journalActive, projectStateCommitted *bool) (err error) {
+func (
+ s *ProjectService,
+) applyProjectUpdateWithRenameJournalInternal(
+ ctx context.Context,
+ proj *Project,
+ name *string,
+ projectsDirectory string,
+ composeContent, envContent, overrideContent *string,
+ volumeMigration volumetypes.Migration,
+ renameJournal *projecttypes.RenameJournal,
+ journalActive, projectStateCommitted *bool,
+) (
+ err error,
+) {
volumeMigrationApplied := false
defer func() {
stateCommitted := projectStateCommitted != nil && *projectStateCommitted
@@ -159,17 +202,17 @@ func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context
}
}()
- if err = s.applyProjectRenameIfNeeded(ctx, proj, name, projectsDirectory); err != nil {
- return err
+ if renameErr := s.applyProjectRenameIfNeeded(ctx, proj, name, projectsDirectory); renameErr != nil {
+ return renameErr
}
- if err = s.persistUpdatedProjectFiles(ctx, proj, projectsDirectory, composeContent, envContent, overrideContent); err != nil {
- return err
+ if persistFilesErr := s.persistUpdatedProjectFiles(ctx, proj, projectsDirectory, composeContent, envContent, overrideContent); persistFilesErr != nil {
+ return persistFilesErr
}
- if err = projects.ApplyRenameVolumeMigration(ctx, s.renameRecoveryOperationsInternal(), volumeMigration, renameJournal, &volumeMigrationApplied); err != nil {
- return err
+ if migrationErr := projects.ApplyRenameVolumeMigration(ctx, s.renameRecoveryOperationsInternal(), volumeMigration, renameJournal, &volumeMigrationApplied); migrationErr != nil {
+ return migrationErr
}
- if err = s.saveProjectUpdateInternal(ctx, proj); err != nil {
- return err
+ if saveProjectErr := s.saveProjectUpdateInternal(ctx, proj); saveProjectErr != nil {
+ return saveProjectErr
}
if projectStateCommitted != nil {
*projectStateCommitted = true
@@ -201,7 +244,17 @@ func (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *Pr
return nil
}
-func (s *ProjectService) handleProjectUpdateFailureInternal(ctx context.Context, projectID, projectsDirectory string, proj *Project, backup *projects.ProjectUpdateBackup, journalActive *bool, projectStateCommitted bool, err error) error {
+func (
+ s *ProjectService,
+) handleProjectUpdateFailureInternal(
+ ctx context.Context,
+ projectID, projectsDirectory string,
+ proj *Project,
+ backup *projects.ProjectUpdateBackup,
+ journalActive *bool,
+ projectStateCommitted bool,
+ err error,
+) error {
if projectStateCommitted {
return err
}
@@ -254,7 +307,19 @@ func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Co
}
}
-func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID, composeContent string, gitEnvContent, gitOverrideContent *string, gitOverrideFileName string, user common.User) (*Project, bool, error) {
+func (
+ s *ProjectService,
+) ApplyGitSyncProjectFiles(
+ ctx context.Context,
+ projectID, composeContent string,
+ gitEnvContent, gitOverrideContent *string,
+ gitOverrideFileName string,
+ user common.User,
+) (
+ *Project,
+ bool,
+ error,
+) {
proj, projectsDirectory, err := s.getProjectForUpdate(ctx, projectID)
if err != nil {
return nil, false, err
@@ -269,8 +334,18 @@ func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID
return nil, false, fmt.Errorf("failed to resolve git env state: %w", err)
}
- if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, composeContent, envUpdate.effectiveContent, gitOverrideContent, gitOverrideFileName, true); err != nil {
- return nil, false, fmt.Errorf("invalid compose file: %w", err)
+ if validateComposeContentForUpdateErr := projects.ValidateComposeContentForUpdate(
+ ctx,
+ projectsDirectory,
+ proj.Path,
+ proj.Name,
+ composeContent,
+ envUpdate.effectiveContent,
+ gitOverrideContent,
+ gitOverrideFileName,
+ true,
+ ); validateComposeContentForUpdateErr != nil {
+ return nil, false, fmt.Errorf("invalid compose file: %w", validateComposeContentForUpdateErr)
}
backup, cleanupBackup, err := s.prepareProjectUpdateBackupInternal(ctx, projectsDirectory, proj.Path, &composeContent, gitEnvContent, gitOverrideContent)
@@ -281,22 +356,31 @@ func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID
journalActive := false
projectStateCommitted := false
- if err := s.applyGitSyncProjectFilesInternal(ctx, &proj, projectsDirectory, composeContent, envUpdate, gitOverrideContent, gitOverrideFileName, &projectStateCommitted); err != nil {
+ if applyGitSyncProjectFilesErr := s.applyGitSyncProjectFilesInternal(
+ ctx,
+ &proj,
+ projectsDirectory,
+ composeContent,
+ envUpdate,
+ gitOverrideContent,
+ gitOverrideFileName,
+ &projectStateCommitted,
+ ); applyGitSyncProjectFilesErr != nil {
// A failure after the env persist would otherwise leave the project with
// new env values and an old or partially updated compose file set.
- err = s.handleProjectUpdateFailureInternal(ctx, projectID, projectsDirectory, &proj, backup, &journalActive, projectStateCommitted, err)
- return nil, false, err
+ applyGitSyncProjectFilesErr = s.handleProjectUpdateFailureInternal(ctx, projectID, projectsDirectory, &proj, backup, &journalActive, projectStateCommitted, applyGitSyncProjectFilesErr)
+ return nil, false, applyGitSyncProjectFilesErr
}
s.refreshComposeProjectNameInternal(ctx, &proj)
s.refreshProjectImageRefsInternal(ctx, &proj)
- if err := s.reconcileComposeTagsForProjectInternal(ctx, &proj); err != nil {
- slog.WarnContext(ctx, "failed to reconcile Compose project tags after git sync", "projectID", proj.ID, "error", err)
+ if reconcileComposeTagsForProjectErr := s.reconcileComposeTagsForProjectInternal(ctx, &proj); reconcileComposeTagsForProjectErr != nil {
+ slog.WarnContext(ctx, "failed to reconcile Compose project tags after git sync", "projectID", proj.ID, "error", reconcileComposeTagsForProjectErr)
}
// Recalculate service counts and status after compose file sync
- if err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {
- slog.WarnContext(ctx, "failed to update service counts after git sync", "projectID", proj.ID, "error", err)
+ if updateProjectStatusandCountsErr := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); updateProjectStatusandCountsErr != nil {
+ slog.WarnContext(ctx, "failed to update service counts after git sync", "projectID", proj.ID, "error", updateProjectStatusandCountsErr)
}
after := s.readGitSyncProjectContentInternal(ctx, proj.ID)
@@ -354,7 +438,17 @@ func (s *ProjectService) logGitSyncProjectUpdateInternal(ctx context.Context, pr
// WriteComposeFile targets the COMPOSE_FILE base the updated .env selects, not
// the one the old .env selected. When it fails before the project row is saved,
// the caller restores the pre-update backup.
-func (s *ProjectService) applyGitSyncProjectFilesInternal(ctx context.Context, proj *Project, projectsDirectory, composeContent string, envUpdate gitSyncEnvUpdateInternal, gitOverrideContent *string, gitOverrideFileName string, projectStateCommitted *bool) error {
+func (
+ s *ProjectService,
+) applyGitSyncProjectFilesInternal(
+ ctx context.Context,
+ proj *Project,
+ projectsDirectory, composeContent string,
+ envUpdate gitSyncEnvUpdateInternal,
+ gitOverrideContent *string,
+ gitOverrideFileName string,
+ projectStateCommitted *bool,
+) error {
if err := persistGitSyncEnvFilesInternal(ctx, proj.Path, projectsDirectory, envUpdate); err != nil {
return fmt.Errorf("failed to sync git env files: %w", err)
}
@@ -387,14 +481,25 @@ func (s *ProjectService) getProjectForUpdate(ctx context.Context, projectID stri
return Project{}, "", fmt.Errorf("failed to get projects directory: %w", err)
}
- if err := s.EnsureProjectPathUnderRoot(ctx, &proj, false); err != nil {
- return Project{}, "", err
+ if ensureProjectPathUnderRootErr := s.EnsureProjectPathUnderRoot(ctx, &proj, false); ensureProjectPathUnderRootErr != nil {
+ return Project{}, "", ensureProjectPathUnderRootErr
}
return proj, projectsDirectory, nil
}
-func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctx context.Context, proj *Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string) (volumetypes.Migration, error) {
+func (
+ s *ProjectService,
+) prepareProjectRenameVolumeMigrationForUpdateInternal(
+ ctx context.Context,
+ proj *Project,
+ name *string,
+ projectsDirectory string,
+ composeContent, envContent, overrideContent *string,
+) (
+ volumetypes.Migration,
+ error,
+) {
if !isProjectRenameRequestedInternal(proj, name) {
return nil, nil
}
@@ -418,14 +523,14 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ct
}
}()
- if _, err := acfs.CopyDir(ctx, proj.Path, previewPath, acfstypes.CopyOptions{}); err != nil {
- return nil, fmt.Errorf("failed to prepare project update preview: %w", err)
+ if _, copyDirErr := acfs.CopyDir(ctx, proj.Path, previewPath, acfstypes.CopyOptions{}); copyDirErr != nil {
+ return nil, fmt.Errorf("failed to prepare project update preview: %w", copyDirErr)
}
previewProject := *proj
previewProject.Path = previewPath
- if err := s.persistUpdatedProjectFiles(ctx, &previewProject, projectsDirectory, composeContent, envContent, overrideContent); err != nil {
- return nil, fmt.Errorf("failed to prepare project update preview: %w", err)
+ if persistUpdatedProjectFilesErr := s.persistUpdatedProjectFiles(ctx, &previewProject, projectsDirectory, composeContent, envContent, overrideContent); persistUpdatedProjectFilesErr != nil {
+ return nil, fmt.Errorf("failed to prepare project update preview: %w", persistUpdatedProjectFilesErr)
}
return s.prepareProjectRenameVolumeMigrationInternal(ctx, &previewProject, name)
@@ -493,25 +598,35 @@ func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *P
return fmt.Errorf("invalid compose file: %w", err)
}
valOverride, valOverrideName := projects.ResolveEffectiveOverrideForValidation(proj.Path, overrideContent)
- if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, *composeContent, effectiveEnvContent, valOverride, valOverrideName, false); err != nil {
- return fmt.Errorf("invalid compose file: %w", err)
+ if validateComposeContentForUpdateErr := projects.ValidateComposeContentForUpdate(
+ ctx,
+ projectsDirectory,
+ proj.Path,
+ proj.Name,
+ *composeContent,
+ effectiveEnvContent,
+ valOverride,
+ valOverrideName,
+ false,
+ ); validateComposeContentForUpdateErr != nil {
+ return fmt.Errorf("invalid compose file: %w", validateComposeContentForUpdateErr)
}
// The env is persisted first so WriteComposeFile targets the COMPOSE_FILE
// base the updated .env selects, not the one the old .env selected. A
// non-nil composeContent is an explicit submission and is always written;
// clients omit it when the compose editor is unchanged.
if envContent != nil {
- if err := persistEffectiveEnvContentInternal(ctx, proj.Path, projectsDirectory, *envContent); err != nil {
- return fmt.Errorf("failed to save project files: %w", err)
+ if persistEffectiveEnvContentErr := persistEffectiveEnvContentInternal(ctx, proj.Path, projectsDirectory, *envContent); persistEffectiveEnvContentErr != nil {
+ return fmt.Errorf("failed to save project files: %w", persistEffectiveEnvContentErr)
}
- } else if err := s.ensureEffectiveEnvFileInternal(ctx, proj.Path, projectsDirectory); err != nil {
- return fmt.Errorf("failed to save project files: %w", err)
+ } else if ensureEffectiveEnvFileErr := s.ensureEffectiveEnvFileInternal(ctx, proj.Path, projectsDirectory); ensureEffectiveEnvFileErr != nil {
+ return fmt.Errorf("failed to save project files: %w", ensureEffectiveEnvFileErr)
}
- if err := projects.WriteComposeFile(ctx, projectsDirectory, proj.Path, *composeContent); err != nil {
- return fmt.Errorf("failed to save project files: %w", err)
+ if writeComposeFileErr := projects.WriteComposeFile(ctx, projectsDirectory, proj.Path, *composeContent); writeComposeFileErr != nil {
+ return fmt.Errorf("failed to save project files: %w", writeComposeFileErr)
}
- if err := projects.ApplyOverrideFileChange(ctx, projectsDirectory, proj.Path, overrideContent); err != nil {
- return fmt.Errorf("failed to save project files: %w", err)
+ if applyOverrideFileChangeErr := projects.ApplyOverrideFileChange(ctx, projectsDirectory, proj.Path, overrideContent); applyOverrideFileChangeErr != nil {
+ return fmt.Errorf("failed to save project files: %w", applyOverrideFileChangeErr)
}
case overrideContent != nil:
if err := s.persistOverrideOnlyUpdateInternal(ctx, proj, projectsDirectory, envContent, overrideContent); err != nil {
@@ -541,16 +656,26 @@ func (s *ProjectService) persistOverrideOnlyUpdateInternal(ctx context.Context,
return fmt.Errorf("invalid compose file: %w", err)
}
valOverride, valOverrideName := projects.ResolveEffectiveOverrideForValidation(proj.Path, overrideContent)
- if err := projects.ValidateComposeContentForUpdate(ctx, projectsDirectory, proj.Path, proj.Name, baseContent, effectiveEnvContent, valOverride, valOverrideName, false); err != nil {
- return fmt.Errorf("invalid compose file: %w", err)
+ if validateComposeContentForUpdateErr := projects.ValidateComposeContentForUpdate(
+ ctx,
+ projectsDirectory,
+ proj.Path,
+ proj.Name,
+ baseContent,
+ effectiveEnvContent,
+ valOverride,
+ valOverrideName,
+ false,
+ ); validateComposeContentForUpdateErr != nil {
+ return fmt.Errorf("invalid compose file: %w", validateComposeContentForUpdateErr)
}
if envContent != nil {
- if err := persistEffectiveEnvContentInternal(ctx, proj.Path, projectsDirectory, *envContent); err != nil {
- return fmt.Errorf("failed to save project files: %w", err)
+ if persistEffectiveEnvContentErr := persistEffectiveEnvContentInternal(ctx, proj.Path, projectsDirectory, *envContent); persistEffectiveEnvContentErr != nil {
+ return fmt.Errorf("failed to save project files: %w", persistEffectiveEnvContentErr)
}
}
- if err := projects.ApplyOverrideFileChange(ctx, projectsDirectory, proj.Path, overrideContent); err != nil {
- return fmt.Errorf("failed to save project files: %w", err)
+ if applyOverrideFileChangeErr := projects.ApplyOverrideFileChange(ctx, projectsDirectory, proj.Path, overrideContent); applyOverrideFileChangeErr != nil {
+ return fmt.Errorf("failed to save project files: %w", applyOverrideFileChangeErr)
}
return nil
}
@@ -622,8 +747,8 @@ func (s *ProjectService) applyProjectRenameIfNeeded(ctx context.Context, proj *P
if currentErr != nil {
// The cross-root move cannot go through acfs, so the cancellation
// check acfs.Rename performs happens here instead.
- if err := ctx.Err(); err != nil {
- return err
+ if cancellationErr := ctx.Err(); cancellationErr != nil {
+ return cancellationErr
}
err = os.Rename(currentPath, targetPath)
} else {
@@ -663,8 +788,8 @@ func (s *ProjectService) activeProjectRenameSyncStateInternal(ctx context.Contex
for _, entry := range entries {
var journal projecttypes.RenameJournal
- if err := json.Unmarshal([]byte(entry.Value), &journal); err != nil {
- slog.WarnContext(ctx, "failed to decode project rename journal during filesystem sync", "key", entry.Key, "error", err)
+ if unmarshalErr := json.Unmarshal([]byte(entry.Value), &journal); unmarshalErr != nil {
+ slog.WarnContext(ctx, "failed to decode project rename journal during filesystem sync", "key", entry.Key, "error", unmarshalErr)
continue
}
if !projects.RenameJournalFilesystemSyncPending(journal.Phase) {
@@ -775,8 +900,8 @@ func (s *ProjectService) writeProjectRenameJournalInternal(ctx context.Context,
return fmt.Errorf("marshal project rename journal: %w", err)
}
- if err := s.KVService.Set(ctx, projecttypes.RenameJournalKeyPrefix+journal.ProjectID, string(payload)); err != nil {
- return fmt.Errorf("write project rename journal: %w", err)
+ if setErr := s.KVService.Set(ctx, projecttypes.RenameJournalKeyPrefix+journal.ProjectID, string(payload)); setErr != nil {
+ return fmt.Errorf("write project rename journal: %w", setErr)
}
return nil
}
@@ -806,8 +931,8 @@ func (s *ProjectService) writeProjectRenameRollbackCleanupInternal(ctx context.C
if err != nil {
return fmt.Errorf("marshal project rename rollback cleanup: %w", err)
}
- if err := s.KVService.Set(ctx, projecttypes.RenameRollbackCleanupKeyPrefix+journal.ProjectID, string(payload)); err != nil {
- return fmt.Errorf("write project rename rollback cleanup: %w", err)
+ if setErr := s.KVService.Set(ctx, projecttypes.RenameRollbackCleanupKeyPrefix+journal.ProjectID, string(payload)); setErr != nil {
+ return fmt.Errorf("write project rename rollback cleanup: %w", setErr)
}
return nil
}
@@ -832,12 +957,12 @@ func (s *ProjectService) RecoverProjectRenameJournals(ctx context.Context) error
var recoverErr error
for _, entry := range entries {
var journal projecttypes.RenameJournal
- if err := json.Unmarshal([]byte(entry.Value), &journal); err != nil {
- recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename journal %s: %w", entry.Key, err))
+ if unmarshalErr := json.Unmarshal([]byte(entry.Value), &journal); unmarshalErr != nil {
+ recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename journal %s: %w", entry.Key, unmarshalErr))
continue
}
- if err := s.recoverProjectRenameJournalInternal(ctx, &journal); err != nil {
- recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename journal %s: %w", entry.Key, err))
+ if recoverProjectRenameJournalErr := s.recoverProjectRenameJournalInternal(ctx, &journal); recoverProjectRenameJournalErr != nil {
+ recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename journal %s: %w", entry.Key, recoverProjectRenameJournalErr))
continue
}
}
@@ -855,8 +980,8 @@ func (s *ProjectService) recoverProjectRenameJournalForProjectInternal(ctx conte
}
var journal projecttypes.RenameJournal
- if err := json.Unmarshal([]byte(raw), &journal); err != nil {
- return fmt.Errorf("decode project rename journal: %w", err)
+ if unmarshalErr := json.Unmarshal([]byte(raw), &journal); unmarshalErr != nil {
+ return fmt.Errorf("decode project rename journal: %w", unmarshalErr)
}
return s.recoverProjectRenameJournalInternal(ctx, &journal)
}
@@ -889,12 +1014,12 @@ func (s *ProjectService) recoverProjectRenameRollbackCleanupsInternal(ctx contex
var recoverErr error
for _, entry := range entries {
var cleanup projecttypes.RenameRollbackCleanup
- if err := json.Unmarshal([]byte(entry.Value), &cleanup); err != nil {
- recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename rollback cleanup %s: %w", entry.Key, err))
+ if unmarshalErr := json.Unmarshal([]byte(entry.Value), &cleanup); unmarshalErr != nil {
+ recoverErr = errors.Join(recoverErr, fmt.Errorf("decode project rename rollback cleanup %s: %w", entry.Key, unmarshalErr))
continue
}
- if err := s.recoverProjectRenameRollbackCleanupInternal(ctx, &cleanup); err != nil {
- recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename rollback cleanup %s: %w", entry.Key, err))
+ if recoverProjectRenameRollbackCleanupErr := s.recoverProjectRenameRollbackCleanupInternal(ctx, &cleanup); recoverProjectRenameRollbackCleanupErr != nil {
+ recoverErr = errors.Join(recoverErr, fmt.Errorf("recover project rename rollback cleanup %s: %w", entry.Key, recoverProjectRenameRollbackCleanupErr))
continue
}
}
@@ -997,8 +1122,8 @@ func (s *ProjectService) persistProjectImageChangesInternal(ctx context.Context,
if err != nil {
return nil, err
}
- if err := persistProjectServiceImagesInternal(ctx, proj.Path, logical, original, updated); err != nil {
- return nil, err
+ if persistProjectServiceImagesErr := persistProjectServiceImagesInternal(ctx, proj.Path, logical, original, updated); persistProjectServiceImagesErr != nil {
+ return nil, persistProjectServiceImagesErr
}
s.invalidateProjectCachesInternal(projectID)
// Keep the desired source on deployment failure: Compose may have partially
@@ -1164,8 +1289,8 @@ func persistProjectServiceImagesInternal(ctx context.Context, projectPath, logic
if !bytes.Equal(current, original) {
return errors.New("Compose source changed during the image update; check updates again") //nolint:staticcheck // Preserve the existing error message.
}
- if err := acfs.Write(ctx, projectPath, logical, updated, acfs.WriteOptions{Mode: os.FileMode(entry.UnixMode).Perm()}); err != nil {
- return fmt.Errorf("persist Compose image changes: %w", err)
+ if writeErr := acfs.Write(ctx, projectPath, logical, updated, acfs.WriteOptions{Mode: os.FileMode(entry.UnixMode).Perm()}); writeErr != nil {
+ return fmt.Errorf("persist Compose image changes: %w", writeErr)
}
return nil
}
diff --git a/backend/internal/project/workspace.go b/backend/internal/project/workspace.go
index 3b2ad78ea..69448f349 100644
--- a/backend/internal/project/workspace.go
+++ b/backend/internal/project/workspace.go
@@ -30,8 +30,8 @@ func (s *ProjectService) GetProjectWorkspace(ctx context.Context, projectID stri
if err != nil {
return nil, err
}
- if err := s.EnsureProjectPathUnderRoot(ctx, proj, false); err != nil {
- return nil, err
+ if ensureProjectPathUnderRootErr := s.EnsureProjectPathUnderRoot(ctx, proj, false); ensureProjectPathUnderRootErr != nil {
+ return nil, ensureProjectPathUnderRootErr
}
composeFileName := projects.DefaultComposeFileName
if composeFile, resolveErr := s.ResolveProjectComposeFile(ctx, proj); resolveErr == nil {
@@ -129,7 +129,18 @@ func (s *ProjectService) DownloadProjectWorkspaceFile(ctx context.Context, proje
return file, size, filepath.Base(rel), nil
}
-func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID string, manifest projecttypes.WorkspaceUpdateManifest, uploads map[int][]byte, user common.User) (*workspacetypes.Workspace, error) {
+func (
+ s *ProjectService,
+) UpdateProjectWorkspace(
+ ctx context.Context,
+ projectID string,
+ manifest projecttypes.WorkspaceUpdateManifest,
+ uploads map[int][]byte,
+ user common.User,
+) (
+ *workspacetypes.Workspace,
+ error,
+) {
if err := workspacepkg.ValidateUpdateManifest(manifest.FileTreeRevision, len(manifest.FileChanges), 500); err != nil {
return nil, common.Classify(common.ErrProjectWorkspaceBadRequest, err)
}
@@ -144,19 +155,19 @@ func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID s
if err != nil {
return nil, err
}
- if err := validateWorkspaceChangesAgainstGitOpsInternal(manifest.FileChanges, ownedPaths); err != nil {
- return nil, err
+ if validateWorkspaceChangesAgainstGitOpsErr := validateWorkspaceChangesAgainstGitOpsInternal(manifest.FileChanges, ownedPaths); validateWorkspaceChangesAgainstGitOpsErr != nil {
+ return nil, validateWorkspaceChangesAgainstGitOpsErr
}
- if err := s.EnsureProjectPathUnderRoot(ctx, proj, true); err != nil {
- return nil, err
+ if ensureProjectPathUnderRootErr := s.EnsureProjectPathUnderRoot(ctx, proj, true); ensureProjectPathUnderRootErr != nil {
+ return nil, ensureProjectPathUnderRootErr
}
projectsDirectory, err := s.GetProjectsDirectory(ctx)
if err != nil {
return nil, err
}
- if err := ensureProjectEnvReadableInternal(ctx, projectsDirectory, proj.Path); err != nil {
- return nil, err
+ if ensureProjectEnvReadableErr := ensureProjectEnvReadableInternal(ctx, projectsDirectory, proj.Path); ensureProjectEnvReadableErr != nil {
+ return nil, ensureProjectEnvReadableErr
}
scope := projects.ProjectUpdateBackupScope{}
for _, change := range manifest.FileChanges {
@@ -169,16 +180,16 @@ func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID s
defer cleanup()
opts := s.projectWorkspaceApplyOptionsInternal(ctx, proj, manifest.FileTreeRevision)
- if err := projects.ApplyProjectWorkspaceChanges(proj.Path, manifest.FileChanges, uploads, opts); err != nil {
+ if applyProjectWorkspaceChangesErr := projects.ApplyProjectWorkspaceChanges(proj.Path, manifest.FileChanges, uploads, opts); applyProjectWorkspaceChangesErr != nil {
if restoreErr := projects.RestoreProjectUpdateBackup(ctx, proj.Path, backup); restoreErr != nil {
- return nil, errors.Join(wrapProjectWorkspaceErrorInternal(err), fmt.Errorf("rollback project workspace: %w", restoreErr))
+ return nil, errors.Join(wrapProjectWorkspaceErrorInternal(applyProjectWorkspaceChangesErr), fmt.Errorf("rollback project workspace: %w", restoreErr))
}
- return nil, wrapProjectWorkspaceErrorInternal(err)
+ return nil, wrapProjectWorkspaceErrorInternal(applyProjectWorkspaceChangesErr)
}
s.refreshProjectImageRefsInternal(ctx, proj)
- if err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {
- return nil, fmt.Errorf("refresh project after workspace update: %w", err)
+ if updateProjectStatusandCountsErr := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); updateProjectStatusandCountsErr != nil {
+ return nil, fmt.Errorf("refresh project after workspace update: %w", updateProjectStatusandCountsErr)
}
s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, proj.ID, proj.Name, user, database.JSON{
"action": "update_project_workspace",
@@ -269,7 +280,7 @@ func (s *ProjectService) gitOpsOwnedWorkspacePathsInternal(ctx context.Context,
owned := make(map[string]struct{})
add := func(p string) {
- if rel, err := kit.NormalizeRelativePath(p); err == nil {
+ if rel, normalizeRelativePathErr := kit.NormalizeRelativePath(p); normalizeRelativePathErr == nil {
owned[rel] = struct{}{}
}
}
@@ -277,8 +288,8 @@ func (s *ProjectService) gitOpsOwnedWorkspacePathsInternal(ctx context.Context,
var files []string
// Fail closed: an incomplete ownership set would expose synced files
// as editable, and the next sync would silently overwrite the edits.
- if err := json.Unmarshal([]byte(*sync.SyncedFiles), &files); err != nil {
- return nil, fmt.Errorf("parse gitops synced files for workspace: %w", err)
+ if unmarshalErr := json.Unmarshal([]byte(*sync.SyncedFiles), &files); unmarshalErr != nil {
+ return nil, fmt.Errorf("parse gitops synced files for workspace: %w", unmarshalErr)
}
for _, f := range files {
add(f)
diff --git a/backend/internal/registry/browse.go b/backend/internal/registry/browse.go
index a67ce0bc8..932df0ac8 100644
--- a/backend/internal/registry/browse.go
+++ b/backend/internal/registry/browse.go
@@ -90,9 +90,9 @@ func (s *ContainerRegistryService) ListRepositoryTags(ctx context.Context, id, r
group.SetLimit(tagDetailsConcurrency)
for i, tagName := range page {
group.Go(func() error {
- tag, err := tagDetailsInternal(repo, target.options, tagName)
- if err != nil {
- tag.Error = err.Error()
+ tag, tagDetailsErr := tagDetailsInternal(repo, target.options, tagName)
+ if tagDetailsErr != nil {
+ tag.Error = tagDetailsErr.Error()
}
items[i] = tag
return nil
@@ -127,8 +127,8 @@ func (s *ContainerRegistryService) DeleteRepositoryTag(ctx context.Context, id,
return "", classifyBrowseErrorInternal(err, "failed to resolve tag digest")
}
digest := descriptor.Digest.String()
- if err := remote.Delete(repo.Digest(digest), target.options...); err != nil {
- return "", classifyBrowseErrorInternal(err, "failed to delete manifest")
+ if deleteErr := remote.Delete(repo.Digest(digest), target.options...); deleteErr != nil {
+ return "", classifyBrowseErrorInternal(deleteErr, "failed to delete manifest")
}
return digest, nil
}
@@ -214,17 +214,17 @@ func tagDetailsInternal(repo name.Repository, options []remote.Option, tagName s
tag.MediaType = string(descriptor.MediaType)
if !descriptor.MediaType.IsIndex() {
- img, err := descriptor.Image()
- if err != nil {
- return tag, err
+ img, imageErr := descriptor.Image()
+ if imageErr != nil {
+ return tag, imageErr
}
- config, err := img.ConfigFile()
- if err != nil {
- return tag, err
+ config, imageErr := img.ConfigFile()
+ if imageErr != nil {
+ return tag, imageErr
}
- platform, err := tagPlatformInternal(img, config.Platform(), descriptor.Digest)
- if err != nil {
- return tag, err
+ platform, imageErr := tagPlatformInternal(img, config.Platform(), descriptor.Digest)
+ if imageErr != nil {
+ return tag, imageErr
}
tag.Platforms = []containerregistry.TagPlatform{platform}
tag.Size = platform.Size
@@ -252,13 +252,13 @@ func tagDetailsInternal(repo name.Repository, options []remote.Option, tagName s
continue
}
group.Go(func() error {
- img, err := index.Image(child.Digest)
- if err != nil {
- return err
+ img, imageErr := index.Image(child.Digest)
+ if imageErr != nil {
+ return imageErr
}
- platform, err := tagPlatformInternal(img, child.Platform, child.Digest)
- if err != nil {
- return err
+ platform, imageErr := tagPlatformInternal(img, child.Platform, child.Digest)
+ if imageErr != nil {
+ return imageErr
}
mu.Lock()
tag.Platforms = append(tag.Platforms, platform)
@@ -267,8 +267,8 @@ func tagDetailsInternal(repo name.Repository, options []remote.Option, tagName s
return nil
})
}
- if err := group.Wait(); err != nil {
- return tag, err
+ if waitErr := group.Wait(); waitErr != nil {
+ return tag, waitErr
}
slices.SortFunc(tag.Platforms, func(a, b containerregistry.TagPlatform) int {
diff --git a/backend/internal/registry/browse_test.go b/backend/internal/registry/browse_test.go
index a72312fad..3b2f7f207 100644
--- a/backend/internal/registry/browse_test.go
+++ b/backend/internal/registry/browse_test.go
@@ -37,7 +37,7 @@ func createBrowseTestRegistryInternal(t *testing.T, db *database.DB, registryURL
require.NoError(t, err)
record.Token = encryptedToken
}
- require.NoError(t, db.WithContext(context.Background()).Create(record).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(record).Error)
return record.ID
}
@@ -95,7 +95,7 @@ func TestContainerRegistryService_ListRepositoriesInternal(t *testing.T) {
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- ctx := context.Background()
+ ctx := t.Context()
id := createBrowseTestRegistryInternal(t, db, host, "", "")
repositories, page, err := svc.ListRepositories(ctx, id, browseParamsInternal(""))
@@ -124,7 +124,7 @@ func TestContainerRegistryService_ListRepositoryTagsSingleImageInternal(t *testi
svc := NewContainerRegistryService(db, nil, nil, nil)
id := createBrowseTestRegistryInternal(t, db, host, "", "")
- tags, page, err := svc.ListRepositoryTags(context.Background(), id, "team/api", pagination.QueryParams{Start: 0, Limit: 1})
+ tags, page, err := svc.ListRepositoryTags(t.Context(), id, "team/api", pagination.QueryParams{Start: 0, Limit: 1})
require.NoError(t, err)
assert.EqualValues(t, 2, page.TotalItems)
require.Len(t, tags, 1)
@@ -168,7 +168,7 @@ func TestContainerRegistryService_ListRepositoryTagsIndexInternal(t *testing.T)
svc := NewContainerRegistryService(db, nil, nil, nil)
id := createBrowseTestRegistryInternal(t, db, host, "", "")
- tags, _, err := svc.ListRepositoryTags(context.Background(), id, "team/api", browseParamsInternal(""))
+ tags, _, err := svc.ListRepositoryTags(t.Context(), id, "team/api", browseParamsInternal(""))
require.NoError(t, err)
require.Len(t, tags, 1)
@@ -194,7 +194,7 @@ func TestContainerRegistryService_DeleteRepositoryTagInternal(t *testing.T) {
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
id := createBrowseTestRegistryInternal(t, db, host, "", "")
- ctx := context.Background()
+ ctx := t.Context()
digest, err := svc.DeleteRepositoryTag(ctx, id, "team/api", "1.0")
require.NoError(t, err)
@@ -229,7 +229,7 @@ func TestContainerRegistryService_BrowseUsesStoredCredentialsInternal(t *testing
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- ctx := context.Background()
+ ctx := t.Context()
id := createBrowseTestRegistryInternal(t, db, host, "robot", "secret")
repositories, _, err := svc.ListRepositories(ctx, id, browseParamsInternal(""))
diff --git a/backend/internal/registry/handler.go b/backend/internal/registry/handler.go
index c4b1291e1..c4a4c941f 100644
--- a/backend/internal/registry/handler.go
+++ b/backend/internal/registry/handler.go
@@ -287,8 +287,8 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
// ECR registries use a different auth flow: generate a temporary token via AWS API.
if reg.RegistryType == "ecr" {
- if err := h.registryService.TestECRRegistry(ctx, reg); err != nil {
- return nil, huma.Error400BadRequest("Registry test failed: " + err.Error())
+ if testECRRegistryErr := h.registryService.TestECRRegistry(ctx, reg); testECRRegistryErr != nil {
+ return nil, huma.Error400BadRequest("Registry test failed: " + testECRRegistryErr.Error())
}
return &handlerutil.Out[base.MessageResponse]{
Body: base.ApiResponse[base.MessageResponse]{
@@ -305,8 +305,8 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
return nil, huma.Error500InternalServerError("Failed to decrypt token: " + err.Error())
}
- if err := h.registryService.TestRegistry(ctx, reg.URL, reg.Username, decryptedToken); err != nil {
- return nil, huma.Error400BadRequest("Registry test failed: " + err.Error())
+ if testRegistryErr := h.registryService.TestRegistry(ctx, reg.URL, reg.Username, decryptedToken); testRegistryErr != nil {
+ return nil, huma.Error400BadRequest("Registry test failed: " + testRegistryErr.Error())
}
noCredentials := strings.TrimSpace(reg.Username) == "" && strings.TrimSpace(decryptedToken) == ""
diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.go
index a29a9484d..9e02f9c2f 100644
--- a/backend/internal/registry/service.go
+++ b/backend/internal/registry/service.go
@@ -88,7 +88,13 @@ type ContainerRegistryService struct {
// NewContainerRegistryService creates a registry service. kvService may be nil
// in tests that do not need pull tracking or rate-limit caching.
-func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGetter, kvService *kv.KVService, settingsService *settings.SettingsService, distributionHTTPClients ...*http.Client) *ContainerRegistryService {
+func NewContainerRegistryService(
+ db *database.DB,
+ dockerClient registryDaemonGetter,
+ kvService *kv.KVService,
+ settingsService *settings.SettingsService,
+ distributionHTTPClients ...*http.Client,
+) *ContainerRegistryService {
distributionHTTPClient := &http.Client{Timeout: 30 * time.Second}
if len(distributionHTTPClients) > 0 && distributionHTTPClients[0] != nil {
distributionHTTPClient = distributionHTTPClients[0]
@@ -108,7 +114,7 @@ func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGet
// sequential batch left later refs with whatever the earlier ones
// had not already spent, so one slow registry starved the tail.
result, err := func() (*containerregistry.DigestResult, error) {
- ctx, cancel := context.WithTimeout(context.Background(), timeouts.DefaultRegistry)
+ ctx, cancel := context.WithTimeout(context.Background(), timeouts.DefaultRegistry) //nolint:forbidigo // Cache revalidation runs independently of request cancellation.
defer cancel()
return service.InspectImageDigest(ctx, imageRef, nil)
}()
@@ -218,29 +224,29 @@ func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req conta
if strings.TrimSpace(req.AWSSecretAccessKey) == "" {
return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "awsSecretAccessKey", Err: errors.New("AWS Secret Access Key is required")})
}
- encryptedSecret, err := crypto.Encrypt(req.AWSSecretAccessKey)
- if err != nil {
- return nil, fmt.Errorf("failed to encrypt AWS secret access key: %w", err)
+ encryptedSecret, encryptErr := crypto.Encrypt(req.AWSSecretAccessKey)
+ if encryptErr != nil {
+ return nil, fmt.Errorf("failed to encrypt AWS secret access key: %w", encryptErr)
}
registryRecord.AWSAccessKeyID = req.AWSAccessKeyID
registryRecord.AWSSecretAccessKey = encryptedSecret
registryRecord.AWSRegion = req.AWSRegion
} else {
if strings.TrimSpace(req.Username) == "" {
- return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "username", Err: errors.New("Username is required")}) //nolint:staticcheck // Preserve the existing error message.
+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "username", Err: errors.New("username is required")})
}
if strings.TrimSpace(req.Token) == "" {
- return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "token", Err: errors.New("Token is required")}) //nolint:staticcheck // Preserve the existing error message.
+ return nil, common.Classify(common.ErrValidation, &base.FieldError{Field: "token", Err: errors.New("token is required")})
}
- encryptedToken, err := crypto.Encrypt(req.Token)
- if err != nil {
- return nil, fmt.Errorf("failed to encrypt token: %w", err)
+ encryptedToken, encryptTokenErr := crypto.Encrypt(req.Token)
+ if encryptTokenErr != nil {
+ return nil, fmt.Errorf("failed to encrypt token: %w", encryptTokenErr)
}
registryRecord.Username = req.Username
registryRecord.Token = encryptedToken
}
- if err := s.db.WithContext(ctx).Create(registryRecord).Error; err != nil {
- return nil, fmt.Errorf("failed to create registry: %w", err)
+ if createRegistryErr := s.db.WithContext(ctx).Create(registryRecord).Error; createRegistryErr != nil {
+ return nil, fmt.Errorf("failed to create registry: %w", createRegistryErr)
}
return registryRecord, nil
}
@@ -254,8 +260,8 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
return nil, err
}
- if err := s.applyRegistryTypeUpdateInternal(registryRecord, req.RegistryType); err != nil {
- return nil, err
+ if applyRegistryTypeUpdateErr := s.applyRegistryTypeUpdateInternal(registryRecord, req.RegistryType); applyRegistryTypeUpdateErr != nil {
+ return nil, applyRegistryTypeUpdateErr
}
storedCredentials := map[string]bool{"token": registryRecord.Token != ""}
@@ -270,15 +276,15 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
"awsSecretAccessKey": req.AWSSecretAccessKey != nil && *req.AWSSecretAccessKey != "",
}
}
- if err := validation.ValidateCredentialTargetChange(
+ if validateCredentialTargetChangeErr := validation.ValidateCredentialTargetChange(
"registry URL",
registryRecord.URL,
req.URL,
normalizeRegistryServerAddressInternal,
storedCredentials,
updatedCredentials,
- ); err != nil {
- return nil, err
+ ); validateCredentialTargetChangeErr != nil {
+ return nil, validateCredentialTargetChangeErr
}
// Update common fields
@@ -289,30 +295,30 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
// RepositoryNames: nil pointer means "don't touch"; empty slice means "clear".
if req.RepositoryNames != nil {
- repositoryNames, err := normalizeRepositoryNamesInternal(*req.RepositoryNames)
- if err != nil {
- return nil, err
+ repositoryNames, normalizeRepositoryNamesErr := normalizeRepositoryNamesInternal(*req.RepositoryNames)
+ if normalizeRepositoryNamesErr != nil {
+ return nil, normalizeRepositoryNamesErr
}
registryRecord.RepositoryNames = repositoryNames
}
if registryRecord.RegistryType == RegistryTypeECR {
- if err := s.updateECRRegistryFieldsInternal(registryRecord, req); err != nil {
- return nil, err
+ if updateECRRegistryFieldsErr := s.updateECRRegistryFieldsInternal(registryRecord, req); updateECRRegistryFieldsErr != nil {
+ return nil, updateECRRegistryFieldsErr
}
- } else if err := s.updateGenericRegistryFieldsInternal(registryRecord, req); err != nil {
- return nil, err
+ } else if updateGenericRegistryFieldsErr := s.updateGenericRegistryFieldsInternal(registryRecord, req); updateGenericRegistryFieldsErr != nil {
+ return nil, updateGenericRegistryFieldsErr
}
registryRecord.UpdatedAt = time.Now()
- if err := s.db.WithContext(ctx).Save(registryRecord).Error; err != nil {
- return nil, fmt.Errorf("failed to update registry: %w", err)
+ if updateRegistryErr := s.db.WithContext(ctx).Save(registryRecord).Error; updateRegistryErr != nil {
+ return nil, fmt.Errorf("failed to update registry: %w", updateRegistryErr)
}
return registryRecord,
nil
}
-func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *ContainerRegistry, registryType *string) error {
+func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(localRegistry *ContainerRegistry, registryType *string) error {
if registryType == nil {
return nil
}
@@ -322,56 +328,64 @@ func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *Con
return err
}
- if nextType != registry.RegistryType {
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "registryType", Err: errors.New("Registry type cannot be changed after creation")}) //nolint:staticcheck // Preserve the existing error message.
+ if nextType != localRegistry.RegistryType {
+ return common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "registryType",
+ Err: errors.New(
+ "registry type cannot be changed after creation",
+ ),
+ },
+ )
}
return nil
}
-func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *ContainerRegistry, req containerregistry.UpdateContainerRegistryRequest) error {
- utils.ApplyChanged(&registry.AWSAccessKeyID, mo.PointerToOption(req.AWSAccessKeyID))
- utils.ApplyChanged(&registry.AWSRegion, mo.PointerToOption(req.AWSRegion))
+func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(localRegistry *ContainerRegistry, req containerregistry.UpdateContainerRegistryRequest) error {
+ utils.ApplyChanged(&localRegistry.AWSAccessKeyID, mo.PointerToOption(req.AWSAccessKeyID))
+ utils.ApplyChanged(&localRegistry.AWSRegion, mo.PointerToOption(req.AWSRegion))
if req.AWSSecretAccessKey != nil && *req.AWSSecretAccessKey != "" {
encryptedSecret, err := crypto.Encrypt(*req.AWSSecretAccessKey)
if err != nil {
return fmt.Errorf("failed to encrypt AWS secret access key: %w", err)
}
- utils.ApplyChanged(&registry.AWSSecretAccessKey, mo.Some(encryptedSecret))
+ utils.ApplyChanged(&localRegistry.AWSSecretAccessKey, mo.Some(encryptedSecret))
}
- if strings.TrimSpace(registry.AWSAccessKeyID) == "" {
+ if strings.TrimSpace(localRegistry.AWSAccessKeyID) == "" {
return common.Classify(common.ErrValidation, &base.FieldError{Field: "awsAccessKeyId", Err: errors.New("AWS Access Key ID is required")})
}
- if strings.TrimSpace(registry.AWSRegion) == "" {
+ if strings.TrimSpace(localRegistry.AWSRegion) == "" {
return common.Classify(common.ErrValidation, &base.FieldError{Field: "awsRegion", Err: errors.New("AWS Region is required")})
}
- if strings.TrimSpace(registry.AWSSecretAccessKey) == "" {
+ if strings.TrimSpace(localRegistry.AWSSecretAccessKey) == "" {
return common.Classify(common.ErrValidation, &base.FieldError{Field: "awsSecretAccessKey", Err: errors.New("AWS Secret Access Key is required")})
}
if req.AWSAccessKeyID != nil || req.AWSSecretAccessKey != nil || req.AWSRegion != nil {
- registry.ECRToken = ""
- registry.ECRTokenGeneratedAt = nil
+ localRegistry.ECRToken = ""
+ localRegistry.ECRTokenGeneratedAt = nil
}
return nil
}
-func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registry *ContainerRegistry, req containerregistry.UpdateContainerRegistryRequest) error {
- utils.ApplyChanged(&registry.Username, mo.PointerToOption(req.Username))
+func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(localRegistry *ContainerRegistry, req containerregistry.UpdateContainerRegistryRequest) error {
+ utils.ApplyChanged(&localRegistry.Username, mo.PointerToOption(req.Username))
if req.Token != nil && *req.Token != "" {
encryptedToken, err := crypto.Encrypt(*req.Token)
if err != nil {
return fmt.Errorf("failed to encrypt token: %w", err)
}
- utils.ApplyChanged(&registry.Token, mo.Some(encryptedToken))
+ utils.ApplyChanged(&localRegistry.Token, mo.Some(encryptedToken))
}
- if strings.TrimSpace(registry.Username) == "" {
- return common.Classify(common.ErrValidation, &base.FieldError{Field: "username", Err: errors.New("Username is required")}) //nolint:staticcheck // Preserve the existing error message.
+ if strings.TrimSpace(localRegistry.Username) == "" {
+ return common.Classify(common.ErrValidation, &base.FieldError{Field: "username", Err: errors.New("username is required")})
}
return nil
@@ -532,8 +546,8 @@ func (s *ContainerRegistryService) RecordImagePull(ctx context.Context, imageRef
return nil
}
- if _, err := s.kvService.IncrementInt64(ctx, registryPullCountKeyInternal(registryHost), 1); err != nil {
- return err
+ if _, incrementInt64Err := s.kvService.IncrementInt64(ctx, registryPullCountKeyInternal(registryHost), 1); incrementInt64Err != nil {
+ return incrementInt64Err
}
return nil
@@ -699,8 +713,8 @@ func (s *ContainerRegistryService) getCachedRateLimitInternal(ctx context.Contex
}
var entry registryRateLimitCacheEntryInternal
- if err := json.Unmarshal([]byte(raw), &entry); err != nil {
- slog.WarnContext(ctx, "failed to parse registry rate limit cache", "registryID", registryID, "error", err)
+ if unmarshalErr := json.Unmarshal([]byte(raw), &entry); unmarshalErr != nil {
+ slog.WarnContext(ctx, "failed to parse registry rate limit cache", "registryID", registryID, "error", unmarshalErr)
return nil, time.Time{}, false
}
if time.Since(entry.CheckedAt) > registryCacheTTL {
@@ -724,8 +738,8 @@ func (s *ContainerRegistryService) setCachedRateLimitInternal(ctx context.Contex
return
}
- if err := s.kvService.Set(ctx, registryRateLimitKeyInternal(registryID), string(payload)); err != nil {
- slog.WarnContext(ctx, "failed to save registry rate limit cache", "registryID", registryID, "error", err)
+ if setErr := s.kvService.Set(ctx, registryRateLimitKeyInternal(registryID), string(payload)); setErr != nil {
+ slog.WarnContext(ctx, "failed to save registry rate limit cache", "registryID", registryID, "error", setErr)
}
}
@@ -862,25 +876,25 @@ func (s *ContainerRegistryService) InspectImageDigest(ctx context.Context, image
bo.RandomizationFactor = 0.3
_, retryErr := backoff.Retry(ctx, func() (*containerregistry.DigestResult, error) {
- result, err := s.inspectImageDigestViaDaemonInternal(ctx, parts.NormalizedRef, parts.RegistryHost, externalCreds)
- if err == nil {
+ result, inspectImageDigestViaDaemonErr := s.inspectImageDigestViaDaemonInternal(ctx, parts.NormalizedRef, parts.RegistryHost, externalCreds)
+ if inspectImageDigestViaDaemonErr == nil {
lastResult = result
return result, nil
}
- if isRateLimitErrorInternal(err) {
+ if isRateLimitErrorInternal(inspectImageDigestViaDaemonErr) {
lastResult = result
- lastErr = err
+ lastErr = inspectImageDigestViaDaemonErr
slog.DebugContext(ctx, "rate limited by registry, will retry",
"registry", parts.RegistryHost,
"imageRef", parts.NormalizedRef)
- return nil, err
+ return nil, inspectImageDigestViaDaemonErr
}
- if !isDistributionFallbackEligibleInternal(err) {
+ if !isDistributionFallbackEligibleInternal(inspectImageDigestViaDaemonErr) {
lastResult = result
- lastErr = err
- return nil, backoff.Permanent(err)
+ lastErr = inspectImageDigestViaDaemonErr
+ return nil, backoff.Permanent(inspectImageDigestViaDaemonErr)
}
if !fallbackWarningLogged {
@@ -888,7 +902,7 @@ func (s *ContainerRegistryService) InspectImageDigest(ctx context.Context, image
slog.WarnContext(ctx, "distribution inspect unavailable, falling back to direct registry digest lookup",
"imageRef", parts.NormalizedRef,
"registry", parts.RegistryHost,
- "error", err.Error())
+ "error", inspectImageDigestViaDaemonErr.Error())
}
fallbackResult, fallbackErr := s.inspectImageDigestViaRegistryInternal(ctx, parts.RegistryHost, parts.Repository, parts.Tag, externalCreds)
@@ -907,7 +921,7 @@ func (s *ContainerRegistryService) InspectImageDigest(ctx context.Context, image
}
lastResult = fallbackResult
- lastErr = fmt.Errorf("daemon digest lookup failed; registry fallback failed: %w", errors.Join(err, fallbackErr))
+ lastErr = fmt.Errorf("daemon digest lookup failed; registry fallback failed: %w", errors.Join(inspectImageDigestViaDaemonErr, fallbackErr))
return nil, backoff.Permanent(lastErr)
}, backoff.WithBackOff(bo), backoff.WithMaxTries(5))
@@ -921,7 +935,16 @@ func (s *ContainerRegistryService) InspectImageDigest(ctx context.Context, image
return lastResult, nil
}
-func (s *ContainerRegistryService) inspectImageDigestViaDaemonInternal(ctx context.Context, normalizedRef, registryHost string, externalCreds []containerregistry.Credential) (*containerregistry.DigestResult, error) {
+func (
+ s *ContainerRegistryService,
+) inspectImageDigestViaDaemonInternal(
+ ctx context.Context,
+ normalizedRef, registryHost string,
+ externalCreds []containerregistry.Credential,
+) (
+ *containerregistry.DigestResult,
+ error,
+) {
dockerClient, err := s.getDockerClientInternal(ctx)
if err != nil {
return nil, err
@@ -937,7 +960,16 @@ func (s *ContainerRegistryService) inspectImageDigestViaDaemonInternal(ctx conte
return result, err
}
-func (s *ContainerRegistryService) inspectImageDigestViaRegistryInternal(ctx context.Context, registryHost, repository, tag string, externalCreds []containerregistry.Credential) (*containerregistry.DigestResult, error) {
+func (
+ s *ContainerRegistryService,
+) inspectImageDigestViaRegistryInternal(
+ ctx context.Context,
+ registryHost, repository, tag string,
+ externalCreds []containerregistry.Credential,
+) (
+ *containerregistry.DigestResult,
+ error,
+) {
value, result, err := registryOperationWithCredentialsInternal(ctx, s, registryHost, "registry manifest inspect of "+registryHost+"/"+repository+":"+tag, externalCreds,
func(ctx context.Context, credential *resolvedRegistryCredential) (string, error) {
return s.fetchDigestFromRegistryInternal(ctx, registryHost, repository, tag, credential)
@@ -949,7 +981,25 @@ func (s *ContainerRegistryService) inspectImageDigestViaRegistryInternal(ctx con
}
// Stored credentials go first: anonymous requests share a per-registry quota with every other unauthenticated client.
-func registryOperationWithCredentialsInternal[T any](ctx context.Context, s *ContainerRegistryService, registryHost, operation string, externalCreds []containerregistry.Credential, fetch func(context.Context, *resolvedRegistryCredential) (T, error)) (T, *containerregistry.DigestResult, error) {
+func registryOperationWithCredentialsInternal[
+ T any,
+](
+ ctx context.Context,
+ s *ContainerRegistryService,
+ registryHost, operation string,
+ externalCreds []containerregistry.Credential,
+ fetch func(
+ context.Context,
+ *resolvedRegistryCredential,
+ ) (
+ T,
+ error,
+ ),
+) (
+ T,
+ *containerregistry.DigestResult,
+ error,
+) {
var zero T
credentials, credErr := s.getMatchingRegistryCredentialsInternal(ctx, registryHost, externalCreds)
@@ -1004,7 +1054,16 @@ func (s *ContainerRegistryService) getDockerClientInternal(ctx context.Context)
return dockerClient, nil
}
-func (s *ContainerRegistryService) getMatchingRegistryCredentialsInternal(ctx context.Context, registryHost string, externalCreds []containerregistry.Credential) ([]resolvedRegistryCredential, error) {
+func (
+ s *ContainerRegistryService,
+) getMatchingRegistryCredentialsInternal(
+ ctx context.Context,
+ registryHost string,
+ externalCreds []containerregistry.Credential,
+) (
+ []resolvedRegistryCredential,
+ error,
+) {
if len(externalCreds) > 0 {
credentials := make([]resolvedRegistryCredential, 0, len(externalCreds))
for _, cred := range externalCreds {
@@ -1106,8 +1165,8 @@ func (s *ContainerRegistryService) SyncRegistries(ctx context.Context, syncItems
for _, item := range syncItems {
syncedIDs[item.ID] = true
- if err := s.processSyncItemInternal(ctx, item, existingMap); err != nil {
- return err
+ if processSyncItemErr := s.processSyncItemInternal(ctx, item, existingMap); processSyncItemErr != nil {
+ return processSyncItemErr
}
}
@@ -1145,8 +1204,8 @@ func (s *ContainerRegistryService) updateExistingRegistryInternal(ctx context.Co
if needsUpdate {
existing.UpdatedAt = time.Now()
- if err := s.db.WithContext(ctx).Save(existing).Error; err != nil {
- return fmt.Errorf("failed to update registry %s: %w", item.ID, err)
+ if syncRegistryErr := s.db.WithContext(ctx).Save(existing).Error; syncRegistryErr != nil {
+ return fmt.Errorf("failed to update registry %s: %w", item.ID, syncRegistryErr)
}
}
@@ -1192,9 +1251,9 @@ func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item contain
if newType == RegistryTypeGeneric {
needsUpdate = utils.ApplyChanged(&existing.Username, mo.Some(item.Username)) || needsUpdate
- tokenChanged, err := utils.ApplyEncrypted(&existing.Token, item.Token)
- if err != nil {
- return false, fmt.Errorf("failed to apply token for registry %s: %w", existing.ID, err)
+ tokenChanged, applyEncryptedErr := utils.ApplyEncrypted(&existing.Token, item.Token)
+ if applyEncryptedErr != nil {
+ return false, fmt.Errorf("failed to apply token for registry %s: %w", existing.ID, applyEncryptedErr)
}
return tokenChanged || needsUpdate, nil
}
@@ -1204,9 +1263,9 @@ func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item contain
// Update the AWS secret only when the manager sent one that differs.
if item.AWSSecretAccessKey != "" {
- secretChanged, err := utils.ApplyEncrypted(&existing.AWSSecretAccessKey, item.AWSSecretAccessKey)
- if err != nil {
- return false, fmt.Errorf("failed to apply AWS secret for registry %s: %w", existing.ID, err)
+ secretChanged, encryptAWSSecretErr := utils.ApplyEncrypted(&existing.AWSSecretAccessKey, item.AWSSecretAccessKey)
+ if encryptAWSSecretErr != nil {
+ return false, fmt.Errorf("failed to apply AWS secret for registry %s: %w", existing.ID, encryptAWSSecretErr)
}
credChanged = secretChanged || credChanged
}
@@ -1248,20 +1307,20 @@ func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.Context
if registryType == RegistryTypeGeneric {
newRegistry.Username = item.Username
- encryptedToken, err := crypto.Encrypt(item.Token)
- if err != nil {
- return fmt.Errorf("failed to encrypt token for new registry %s: %w", item.ID, err)
+ encryptedToken, encryptErr := crypto.Encrypt(item.Token)
+ if encryptErr != nil {
+ return fmt.Errorf("failed to encrypt token for new registry %s: %w", item.ID, encryptErr)
}
newRegistry.Token = encryptedToken
} else if item.AWSSecretAccessKey != "" {
- encryptedSecret, err := crypto.Encrypt(item.AWSSecretAccessKey)
- if err != nil {
- return fmt.Errorf("failed to encrypt AWS secret for new registry %s: %w", item.ID, err)
+ encryptedSecret, encryptNewAWSSecretErr := crypto.Encrypt(item.AWSSecretAccessKey)
+ if encryptNewAWSSecretErr != nil {
+ return fmt.Errorf("failed to encrypt AWS secret for new registry %s: %w", item.ID, encryptNewAWSSecretErr)
}
newRegistry.AWSSecretAccessKey = encryptedSecret
}
- if err := s.db.WithContext(ctx).Create(newRegistry).Error; err != nil {
- return fmt.Errorf("failed to create registry %s: %w", item.ID, err)
+ if createRegistryErr := s.db.WithContext(ctx).Create(newRegistry).Error; createRegistryErr != nil {
+ return fmt.Errorf("failed to create registry %s: %w", item.ID, createRegistryErr)
}
return nil
}
@@ -1276,7 +1335,15 @@ func NormalizeRegistryType(value string) (string, error) {
case RegistryTypeGeneric, RegistryTypeECR:
return registryType, nil
default:
- return "", common.Classify(common.ErrValidation, &base.FieldError{Field: "registryType", Err: errors.New("Registry type must be one of: generic, ecr")}) //nolint:staticcheck // Preserve the existing error message.
+ return "", common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: "registryType",
+ Err: errors.New(
+ "registry type must be one of: generic, ecr",
+ ),
+ },
+ )
}
}
@@ -1417,7 +1484,17 @@ func isDistributionFallbackEligibleInternal(err error) bool {
strings.Contains(errLower, "i/o timeout")
}
-func (s *ContainerRegistryService) fetchDigestFromDaemonInternal(ctx context.Context, dockerClient RegistryDaemonClient, registryHost, normalizedRef string, credential *resolvedRegistryCredential) (string, error) {
+func (
+ s *ContainerRegistryService,
+) fetchDigestFromDaemonInternal(
+ ctx context.Context,
+ dockerClient RegistryDaemonClient,
+ registryHost, normalizedRef string,
+ credential *resolvedRegistryCredential,
+) (
+ string,
+ error,
+) {
var inspectOptions client.DistributionInspectOptions
if credential != nil {
authHeader, err := utilsregistry.EncodeAuthHeader(credential.Username, credential.Token, credential.ServerAddress)
diff --git a/backend/internal/registry/service_label_test.go b/backend/internal/registry/service_label_test.go
index 175c9356c..7eb2ca326 100644
--- a/backend/internal/registry/service_label_test.go
+++ b/backend/internal/registry/service_label_test.go
@@ -1,7 +1,6 @@
package registry
import (
- "context"
"io"
"log"
"net/http/httptest"
@@ -35,12 +34,12 @@ func pushLabeledImageInternal(t *testing.T, imageRef string, imageLabels map[str
require.NoError(t, err)
if imageLabels != nil {
- cfg, err := img.ConfigFile()
- require.NoError(t, err)
+ cfg, configFileErr := img.ConfigFile()
+ require.NoError(t, configFileErr)
cfg = cfg.DeepCopy()
cfg.Config.Labels = imageLabels
- img, err = mutate.ConfigFile(img, cfg)
- require.NoError(t, err)
+ img, configFileErr = mutate.ConfigFile(img, cfg)
+ require.NoError(t, configFileErr)
}
ref, err := name.ParseReference(imageRef)
@@ -58,14 +57,14 @@ func TestContainerRegistryService_ImageVersionLabelInternal(t *testing.T) {
svc := NewContainerRegistryService(nil, nil, nil, nil)
- label, err := svc.ImageVersionLabel(context.Background(), imageRef)
+ label, err := svc.ImageVersionLabel(t.Context(), imageRef)
require.NoError(t, err)
assert.Equal(t, "v2.8.0-next.66", label)
// Digest references resolve too — the version service prefers them.
imgDigest, err := img.Digest()
require.NoError(t, err)
- label, err = svc.ImageVersionLabel(context.Background(), host+"/getarcaneapp/arcane@"+imgDigest.String())
+ label, err = svc.ImageVersionLabel(t.Context(), host+"/getarcaneapp/arcane@"+imgDigest.String())
require.NoError(t, err)
assert.Equal(t, "v2.8.0-next.66", label)
}
@@ -76,7 +75,7 @@ func TestContainerRegistryService_ImageVersionLabelMissingLabelInternal(t *testi
pushLabeledImageInternal(t, imageRef, nil)
svc := NewContainerRegistryService(nil, nil, nil, nil)
- _, err := svc.ImageVersionLabel(context.Background(), imageRef)
+ _, err := svc.ImageVersionLabel(t.Context(), imageRef)
assert.ErrorIs(t, err, ErrNoVersionLabel)
}
@@ -87,14 +86,14 @@ func TestContainerRegistryService_ImageVersionLabelErrorNotCachedInternal(t *tes
svc := NewContainerRegistryService(nil, nil, nil, nil)
// The image does not exist yet: the lookup must fail...
- _, err := svc.ImageVersionLabel(context.Background(), imageRef)
+ _, err := svc.ImageVersionLabel(t.Context(), imageRef)
require.Error(t, err)
// ...and the failure must not be cached: after the push the same ref resolves.
pushLabeledImageInternal(t, imageRef, map[string]string{
ociImageVersionLabel: "v2.8.0-next.67",
})
- label, err := svc.ImageVersionLabel(context.Background(), imageRef)
+ label, err := svc.ImageVersionLabel(t.Context(), imageRef)
require.NoError(t, err)
assert.Equal(t, "v2.8.0-next.67", label)
}
diff --git a/backend/internal/registry/service_test.go b/backend/internal/registry/service_test.go
index bd398b0a6..00319d903 100644
--- a/backend/internal/registry/service_test.go
+++ b/backend/internal/registry/service_test.go
@@ -51,20 +51,20 @@ func setupContainerRegistryTestDBInternal(t *testing.T) *database.DB {
return &database.DB{DB: db}
}
-func createTestPullRegistryInternal(t *testing.T, db *database.DB, url, username, token string) {
+func createTestPullRegistryInternal(t *testing.T, db *database.DB, localUrl, username, token string) {
t.Helper()
encryptedToken, err := crypto.Encrypt(token)
require.NoError(t, err)
record := &ContainerRegistry{
- URL: url,
+ URL: localUrl,
Username: username,
Token: encryptedToken,
Enabled: true,
RegistryType: RegistryTypeGeneric,
}
- require.NoError(t, db.WithContext(context.Background()).Create(record).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(record).Error)
}
func decodeRegistryAuthInternal(t *testing.T, encoded string) dockerregistry.AuthConfig {
@@ -112,10 +112,10 @@ func registryPingInternal(w http.ResponseWriter, r *http.Request, challenge stri
}
// writeManifestHeadInternal answers a manifest HEAD with the headers a client needs to trust the digest without a body.
-func writeManifestHeadInternal(w http.ResponseWriter, digest string) {
+func writeManifestHeadInternal(w http.ResponseWriter, localDigest string) {
w.Header().Set("Content-Type", "application/vnd.docker.distribution.manifest.v2+json")
w.Header().Set("Content-Length", "0")
- w.Header().Set("Docker-Content-Digest", digest)
+ w.Header().Set("Docker-Content-Digest", localDigest)
w.WriteHeader(http.StatusOK)
}
@@ -160,7 +160,7 @@ func TestContainerRegistryService_GetAllRegistryAuthConfigs_NormalizesHosts(t *t
createTestPullRegistryInternal(t, db, "https://GHCR.IO/", "gh-user", "gh-token")
svc := NewContainerRegistryService(db, nil, nil, nil)
- authConfigs, err := svc.GetAllRegistryAuthConfigs(context.Background())
+ authConfigs, err := svc.GetAllRegistryAuthConfigs(t.Context())
require.NoError(t, err)
require.NotNil(t, authConfigs)
@@ -187,7 +187,7 @@ func TestContainerRegistryService_GetAllRegistryAuthConfigs_SkipsInvalidEntries(
createTestPullRegistryInternal(t, db, "https://registry.example.com", "example-user", "example-token")
svc := NewContainerRegistryService(db, nil, nil, nil)
- authConfigs, err := svc.GetAllRegistryAuthConfigs(context.Background())
+ authConfigs, err := svc.GetAllRegistryAuthConfigs(t.Context())
require.NoError(t, err)
require.NotNil(t, authConfigs)
@@ -206,7 +206,7 @@ func TestContainerRegistryService_GetRegistryAuthForHost_UsesDatabaseCredentials
createTestPullRegistryInternal(t, db, "https://index.docker.io/v1/", "docker-user", "docker-token")
svc := NewContainerRegistryService(db, nil, nil, nil)
- auth, err := svc.GetRegistryAuthForHost(context.Background(), "registry-1.docker.io")
+ auth, err := svc.GetRegistryAuthForHost(t.Context(), "registry-1.docker.io")
require.NoError(t, err)
require.NotEmpty(t, auth)
@@ -221,7 +221,7 @@ func TestContainerRegistryService_GetRegistryAuthForImage_UsesHostLookup(t *test
createTestPullRegistryInternal(t, db, "https://ghcr.io", "gh-user", "gh-token")
svc := NewContainerRegistryService(db, nil, nil, nil)
- auth, err := svc.GetRegistryAuthForImage(context.Background(), "ghcr.io/getarcaneapp/arcane:latest")
+ auth, err := svc.GetRegistryAuthForImage(t.Context(), "ghcr.io/getarcaneapp/arcane:latest")
require.NoError(t, err)
require.NotEmpty(t, auth)
@@ -233,7 +233,7 @@ func TestContainerRegistryService_GetRegistryAuthForImage_UsesHostLookup(t *test
func TestContainerRegistryService_NilService_RegistryAuthMethodsReturnEmpty(t *testing.T) {
var svc *ContainerRegistryService
- ctx := context.Background()
+ ctx := t.Context()
authConfigs, err := svc.GetAllRegistryAuthConfigs(ctx)
require.NoError(t, err)
@@ -250,7 +250,7 @@ func TestContainerRegistryService_NilService_RegistryAuthMethodsReturnEmpty(t *t
func TestContainerRegistryService_GetRegistryPullUsage_AnonymousDockerHubLimit(t *testing.T) {
db := setupContainerRegistryTestDBInternal(t)
- require.NoError(t, db.WithContext(context.Background()).Create(&ContainerRegistry{
+ require.NoError(t, db.WithContext(t.Context()).Create(&ContainerRegistry{
URL: "docker.io",
Enabled: true,
RegistryType: RegistryTypeGeneric,
@@ -281,7 +281,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_AnonymousDockerHubLimit(t
}
})
- result, err := svc.GetRegistryPullUsage(context.Background())
+ result, err := svc.GetRegistryPullUsage(t.Context())
require.NoError(t, err)
require.Len(t, result.Registries, 1)
@@ -297,7 +297,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_AnonymousDockerHubLimit(t
assert.Equal(t, 10, *registry.Used)
assert.Equal(t, 1, tokenCalls)
- cachedResult, err := svc.GetRegistryPullUsage(context.Background())
+ cachedResult, err := svc.GetRegistryPullUsage(t.Context())
require.NoError(t, err)
require.Len(t, cachedResult.Registries, 1)
require.NotNil(t, cachedResult.Registries[0].Remaining)
@@ -333,7 +333,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_UsesDockerHubCredential(t
}
})
- result, err := svc.GetRegistryPullUsage(context.Background())
+ result, err := svc.GetRegistryPullUsage(t.Context())
require.NoError(t, err)
require.Len(t, result.Registries, 2)
@@ -367,7 +367,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_CredentialErrorIsNonFatal
}
})
- result, err := svc.GetRegistryPullUsage(context.Background())
+ result, err := svc.GetRegistryPullUsage(t.Context())
require.NoError(t, err)
require.Len(t, result.Registries, 1)
@@ -379,17 +379,17 @@ func TestContainerRegistryService_GetRegistryPullUsage_CredentialErrorIsNonFatal
func TestContainerRegistryService_RecordImagePull_IncrementsObservedRegistryCount(t *testing.T) {
db := setupContainerRegistryTestDBInternal(t)
- require.NoError(t, db.WithContext(context.Background()).Create(&ContainerRegistry{
+ require.NoError(t, db.WithContext(t.Context()).Create(&ContainerRegistry{
URL: "ghcr.io",
Enabled: true,
RegistryType: RegistryTypeGeneric,
}).Error)
svc := NewContainerRegistryService(db, nil, kv.NewKVService(db), nil)
- require.NoError(t, svc.RecordImagePull(context.Background(), "ghcr.io/example/app:latest"))
- require.NoError(t, svc.RecordImagePull(context.Background(), "ghcr.io/example/worker:latest"))
+ require.NoError(t, svc.RecordImagePull(t.Context(), "ghcr.io/example/app:latest"))
+ require.NoError(t, svc.RecordImagePull(t.Context(), "ghcr.io/example/worker:latest"))
- result, err := svc.GetRegistryPullUsage(context.Background())
+ result, err := svc.GetRegistryPullUsage(t.Context())
require.NoError(t, err)
require.Len(t, result.Registries, 1)
assert.Equal(t, "ghcr.io", result.Registries[0].Registry)
@@ -401,7 +401,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsUnsupportedRegistryType(
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "registry.example.com",
RegistryType: "ECR-ish",
})
@@ -417,7 +417,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyUsernameForGeneric(
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "",
Token: "my-token",
@@ -434,7 +434,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyTokenForGeneric(t *
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "",
@@ -451,7 +451,7 @@ func TestContainerRegistryService_CreateRegistry_AcceptsValidGenericCredentials(
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -465,14 +465,14 @@ func TestContainerRegistryService_UpdateRegistry_RejectsBlankingUsername(t *test
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- _, err = svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(t.Context(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
Username: new(""),
})
require.Error(t, err)
@@ -487,7 +487,7 @@ func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProvid
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -495,7 +495,7 @@ func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProvid
require.NoError(t, err)
originalToken := reg.Token
- updated, err := svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(t.Context(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
Username: new("updated-user"),
})
require.NoError(t, err)
@@ -517,7 +517,7 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTo
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -525,7 +525,7 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTo
require.NoError(t, err)
originalToken := registry.Token
- _, err = svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(t.Context(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("https://attacker.example.com"),
Token: tt.token,
})
@@ -536,7 +536,7 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTo
require.True(t, ok)
assert.Equal(t, "token", fieldErr.Field)
- stored, loadErr := svc.GetRegistryByID(context.Background(), registry.ID)
+ stored, loadErr := svc.GetRegistryByID(t.Context(), registry.ID)
require.NoError(t, loadErr)
assert.Equal(t, "https://registry.example.com", stored.URL)
assert.Equal(t, originalToken, stored.Token)
@@ -548,7 +548,7 @@ func TestContainerRegistryService_UpdateRegistry_AllowsPathChangeOnSameHostWitho
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com/one",
Username: "my-user",
Token: "my-token",
@@ -556,7 +556,7 @@ func TestContainerRegistryService_UpdateRegistry_AllowsPathChangeOnSameHostWitho
require.NoError(t, err)
originalToken := registry.Token
- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(t.Context(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("REGISTRY.EXAMPLE.COM/two"),
})
require.NoError(t, err)
@@ -568,14 +568,14 @@ func TestContainerRegistryService_UpdateRegistry_AllowsTargetChangeWhenTokenIsRe
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(t.Context(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("https://registry.example.net"),
Token: new("new-token"),
})
@@ -591,7 +591,7 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStored
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "123456789012.dkr.ecr.us-east-1.amazonaws.com",
RegistryType: RegistryTypeECR,
AWSAccessKeyID: "old-access-key",
@@ -601,7 +601,7 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStored
require.NoError(t, err)
originalSecret := registry.AWSSecretAccessKey
- _, err = svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(t.Context(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),
})
require.Error(t, err)
@@ -611,12 +611,12 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStored
require.Equal(t, common.APIErrorCodeValidationError, apiErr.Code)
require.ElementsMatch(t, []string{"awsAccessKeyId", "awsSecretAccessKey"}, apiErr.Details.(map[string]any)["fields"])
- stored, loadErr := svc.GetRegistryByID(context.Background(), registry.ID)
+ stored, loadErr := svc.GetRegistryByID(t.Context(), registry.ID)
require.NoError(t, loadErr)
require.Equal(t, "123456789012.dkr.ecr.us-east-1.amazonaws.com", stored.URL)
require.Equal(t, originalSecret, stored.AWSSecretAccessKey)
- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(t.Context(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),
AWSAccessKeyID: new("new-access-key"),
AWSSecretAccessKey: new("new-secret-key"),
@@ -633,14 +633,14 @@ func TestContainerRegistryService_UpdateRegistry_RejectsChangingRegistryType(t *
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- _, err = svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(t.Context(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
RegistryType: new("ecr"),
})
require.Error(t, err)
@@ -655,14 +655,14 @@ func TestContainerRegistryService_UpdateRegistry_AllowsSameRegistryType(t *testi
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- updated, err := svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(t.Context(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
RegistryType: new("generic"),
Username: new("updated-user"),
})
@@ -676,10 +676,10 @@ func TestContainerRegistryService_SyncRegistries_ClearsGenericTokenWhenManagerSe
createTestPullRegistryInternal(t, db, "https://registry.example.com", "registry-user", "old-token")
var existing ContainerRegistry
- require.NoError(t, db.WithContext(context.Background()).First(&existing).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&existing).Error)
svc := NewContainerRegistryService(db, nil, nil, nil)
- err := svc.SyncRegistries(context.Background(), []containerregistry.Sync{
+ err := svc.SyncRegistries(t.Context(), []containerregistry.Sync{
{
ID: existing.ID,
URL: existing.URL,
@@ -694,7 +694,7 @@ func TestContainerRegistryService_SyncRegistries_ClearsGenericTokenWhenManagerSe
require.NoError(t, err)
var updated ContainerRegistry
- require.NoError(t, db.WithContext(context.Background()).First(&updated, "id = ?", existing.ID).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&updated, "id = ?", existing.ID).Error)
decryptedToken, err := crypto.Decrypt(updated.Token)
require.NoError(t, err)
@@ -713,7 +713,7 @@ func TestContainerRegistryService_TestRegistry_UsesDockerDaemon(t *testing.T) {
}, nil
}, nil, nil)
- err := svc.TestRegistry(context.Background(), "https://registry.example.com:5443", "user", "token")
+ err := svc.TestRegistry(t.Context(), "https://registry.example.com:5443", "user", "token")
require.NoError(t, err)
}
@@ -727,7 +727,7 @@ func TestContainerRegistryService_TestRegistry_PropagatesDaemonError(t *testing.
}, nil
}, nil, nil)
- err := svc.TestRegistry(context.Background(), "registry.example.com", "user", "token")
+ err := svc.TestRegistry(t.Context(), "registry.example.com", "user", "token")
require.Error(t, err)
assert.ErrorIs(t, err, expectedErr)
}
@@ -742,10 +742,10 @@ func TestContainerRegistryService_TestRegistry_SkipsLoginForEmptyCredentials(t *
}, nil
}, nil, nil)
- err := svc.TestRegistry(context.Background(), "registry.example.com", "", "")
+ err := svc.TestRegistry(t.Context(), "registry.example.com", "", "")
require.NoError(t, err)
- err = svc.TestRegistry(context.Background(), "registry.example.com", " ", " ")
+ err = svc.TestRegistry(t.Context(), "registry.example.com", " ", " ")
require.NoError(t, err)
}
@@ -766,7 +766,7 @@ func TestContainerRegistryService_InspectImageDigest_AnonymousSuccess(t *testing
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "registry.example.com:5443/team/app:1.2.3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "registry.example.com:5443/team/app:1.2.3", nil)
require.NoError(t, err)
assert.Equal(t, wantDigest, result.Digest)
assert.Equal(t, "anonymous", result.AuthMethod)
@@ -789,7 +789,7 @@ func TestContainerRegistryService_GetImageDigest_HonorsCallerCancellation(t *tes
}, nil, nil)
t.Cleanup(svc.cache.StopJanitor)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
result := make(chan error, 1)
go func() {
@@ -838,7 +838,7 @@ func TestContainerRegistryService_InspectImageDigest_UsesStoredDockerHubCredenti
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "registry-1.docker.io/library/nginx:latest", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "registry-1.docker.io/library/nginx:latest", nil)
require.NoError(t, err)
assert.Equal(t, 1, calls)
assert.Equal(t, wantDigest, result.Digest)
@@ -873,7 +873,7 @@ func TestContainerRegistryService_InspectImageDigest_UsesStoredDockerHubCredenti
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "docker.io/library/registry:3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "docker.io/library/registry:3", nil)
require.NoError(t, err)
assert.Equal(t, 1, calls)
assert.Equal(t, wantDigest, result.Digest)
@@ -907,7 +907,7 @@ func TestContainerRegistryService_InspectImageDigest_UsesStoredCredentialsForNon
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "ghcr.io/getarcaneapp/agent:latest", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "ghcr.io/getarcaneapp/agent:latest", nil)
require.NoError(t, err)
assert.Equal(t, 1, calls)
assert.Equal(t, wantDigest, result.Digest)
@@ -943,7 +943,7 @@ func TestContainerRegistryService_InspectImageDigest_UsesStoredCredentialsInstea
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "ghcr.io/getarcaneapp/agent:latest", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "ghcr.io/getarcaneapp/agent:latest", nil)
require.NoError(t, err)
assert.Zero(t, anonymousCalls)
assert.Equal(t, wantDigest, result.Digest)
@@ -974,7 +974,7 @@ func TestContainerRegistryService_InspectImageDigest_FallsBackToAnonymousWhenSto
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "ghcr.io/immich-app/immich-server:release", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "ghcr.io/immich-app/immich-server:release", nil)
require.NoError(t, err)
assert.Equal(t, 1, anonymousCalls)
assert.Equal(t, wantDigest, result.Digest)
@@ -1001,7 +1001,7 @@ func TestContainerRegistryService_InspectImageDigest_DoesNotFallBackToAnonymousO
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "ghcr.io/getarcaneapp/agent:latest", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "ghcr.io/getarcaneapp/agent:latest", nil)
require.Error(t, err)
assert.Zero(t, anonymousCalls, "must not burn anonymous quota when the credential itself is rate limited")
require.NotNil(t, result)
@@ -1046,7 +1046,7 @@ func TestContainerRegistryService_InspectImageDigest_FallbackUsesStoredCredentia
}),
}
- result, err := svc.InspectImageDigest(context.Background(), "ghcr.io/getarcaneapp/agent:latest", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "ghcr.io/getarcaneapp/agent:latest", nil)
require.NoError(t, err)
assert.Zero(t, anonymousCalls)
assert.Equal(t, wantDigest, result.Digest)
@@ -1086,7 +1086,7 @@ func TestContainerRegistryService_InspectImageDigest_FallsBackWhenDistributionNo
}, nil, nil)
svc.distributionHTTPClient = server.Client()
- result, err := svc.InspectImageDigest(context.Background(), serverURL.Host+"/team/app:1.2.3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), serverURL.Host+"/team/app:1.2.3", nil)
require.NoError(t, err)
assert.Equal(t, 1, calls)
assert.Equal(t, wantDigest, result.Digest)
@@ -1119,13 +1119,14 @@ func TestContainerRegistryService_InspectImageDigest_FallsBackWhenDistributionFo
calls++
assert.Equal(t, serverURL.Host+"/team/app:1.2.3", imageRef)
assert.Empty(t, options.EncodedRegistryAuth)
- return client.DistributionInspectResult{}, errors.New("Error response from daemon: <html><body><h1>403 Forbidden</h1> Request forbidden by administrative rules. </body></html>")
+ return client.DistributionInspectResult{}, errors.New("Error response from daemon: <html><body><h1>403 Forbidden</h1> Request forbidden by administrative r" +
+ "ules. </body></html>")
},
}, nil
}, nil, nil)
svc.distributionHTTPClient = server.Client()
- result, err := svc.InspectImageDigest(context.Background(), serverURL.Host+"/team/app:1.2.3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), serverURL.Host+"/team/app:1.2.3", nil)
require.NoError(t, err)
assert.Equal(t, 1, calls)
assert.Equal(t, wantDigest, result.Digest)
@@ -1201,7 +1202,7 @@ func TestContainerRegistryService_InspectImageDigest_RetriesStoredCredentialsAft
}, nil, nil)
svc.distributionHTTPClient = server.Client()
- result, err := svc.InspectImageDigest(context.Background(), serverURL.Host+"/team/app:1.2.3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), serverURL.Host+"/team/app:1.2.3", nil)
require.NoError(t, err)
assert.Equal(t, wantDigest, result.Digest)
// Stored credentials go first; only after rejection does the lookup retry anonymously.
@@ -1221,7 +1222,7 @@ func TestContainerRegistryService_InspectImageDigest_DoesNotFallbackOnTLSFailure
}, nil
}, nil, nil)
- result, err := svc.InspectImageDigest(context.Background(), "registry.example.com/team/app:1.2.3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "registry.example.com/team/app:1.2.3", nil)
require.Error(t, err)
require.NotNil(t, result)
assert.Contains(t, strings.ToLower(err.Error()), "x509")
@@ -1247,7 +1248,7 @@ func TestContainerRegistryService_InspectImageDigest_PreservesDaemonAndFallbackE
}),
}
- result, err := svc.InspectImageDigest(context.Background(), "registry.example.com/team/app:1.2.3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), "registry.example.com/team/app:1.2.3", nil)
require.Error(t, err)
require.NotNil(t, result)
require.ErrorIs(t, err, daemonErr)
@@ -1295,7 +1296,7 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthori
}, nil, nil)
svc.distributionHTTPClient = server.Client()
- result, err := svc.InspectImageDigest(context.Background(), serverURL.Host+"/team/app:1.2.3", nil)
+ result, err := svc.InspectImageDigest(t.Context(), serverURL.Host+"/team/app:1.2.3", nil)
require.Error(t, err)
require.NotNil(t, result)
assert.Equal(t, "anonymous", result.AuthMethod)
@@ -1307,7 +1308,7 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthori
func createRegistryWithRepositoryNames(t *testing.T, svc *ContainerRegistryService, repositoryNames ...string) *ContainerRegistry {
t.Helper()
- registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -1322,7 +1323,7 @@ func fetchRegistry(t *testing.T, db *database.DB, id string) ContainerRegistry {
t.Helper()
var fetched ContainerRegistry
- require.NoError(t, db.WithContext(context.Background()).First(&fetched, "id = ?", id).Error)
+ require.NoError(t, db.WithContext(t.Context()).First(&fetched, "id = ?", id).Error)
return fetched
}
@@ -1342,7 +1343,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsInvalidRepositoryName(t
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(t.Context(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
RepositoryNames: []string{"team:latest"},
})
@@ -1359,14 +1360,14 @@ func TestContainerRegistryService_UpdateRegistry_RepositoryNamesPointerSemantics
registry := createRegistryWithRepositoryNames(t, svc, "team", "team/platform")
// A nil pointer leaves the existing names untouched.
- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(t.Context(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
Username: new("updated-user"),
})
require.NoError(t, err)
assert.Equal(t, database.StringSlice{"team", "team/platform"}, updated.RepositoryNames)
// An empty slice clears them.
- updated, err = svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
+ updated, err = svc.UpdateRegistry(t.Context(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
RepositoryNames: &[]string{},
})
require.NoError(t, err)
diff --git a/backend/internal/registry/tags_test.go b/backend/internal/registry/tags_test.go
index c476b5d9c..8fc889ddd 100644
--- a/backend/internal/registry/tags_test.go
+++ b/backend/internal/registry/tags_test.go
@@ -3,7 +3,6 @@ package registry
import (
"context"
"encoding/base64"
- "errors"
"io"
"net/http"
"strings"
@@ -22,7 +21,17 @@ func TestListImageTagsCredentialsInternal(t *testing.T) {
wantPassword string
}{
{name: "stored", wantUser: "stored-user", wantPassword: "stored-token"},
- {name: "external overrides stored", external: []containerregistry.Credential{{URL: "docker.io", Username: "external-user", Token: "external-token", Enabled: true}}, wantUser: "external-user", wantPassword: "external-token"},
+ {
+ name: "external overrides stored",
+ external: []containerregistry.Credential{{
+ URL: "docker.io",
+ Username: "external-user",
+ Token: "external-token",
+ Enabled: true,
+ }},
+ wantUser: "external-user",
+ wantPassword: "external-token",
+ },
{name: "external excludes unrelated stored", external: []containerregistry.Credential{{URL: "other.test", Username: "external-user", Token: "external-token", Enabled: true}}},
{name: "disabled external ignored", external: []containerregistry.Credential{{URL: "docker.io", Username: "external-user", Token: "external-token", Enabled: false}}},
} {
@@ -65,7 +74,16 @@ func TestListImageTagsDoesNotFallBackOnRateLimitInternal(t *testing.T) {
}
return &http.Response{StatusCode: http.StatusTooManyRequests, Body: http.NoBody, Header: http.Header{}}, nil
})})
- tags, err := svc.ListImageTags(t.Context(), "registry.test/team/app:1.0.0", []containerregistry.Credential{{URL: "registry.test", Username: "user", Token: "token", Enabled: true}})
+ tags, err := svc.ListImageTags(
+ t.Context(),
+ "registry.test/team/app:1.0.0",
+ []containerregistry.Credential{{
+ URL: "registry.test",
+ Username: "user",
+ Token: "token",
+ Enabled: true,
+ }},
+ )
require.Error(t, err)
assert.Nil(t, tags)
assert.Positive(t, credentialed)
@@ -77,7 +95,7 @@ func TestListImageTagsCancellationInternal(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
cancel()
_, err := svc.ListImageTags(ctx, "registry.test/team/app:1.0.0", nil)
- require.True(t, errors.Is(err, context.Canceled), "error = %v", err)
+ require.ErrorIs(t, err, context.Canceled, "error = %v", err)
}
func TestListImageTagsRejectedCredentialFallbackInternal(t *testing.T) {
diff --git a/backend/internal/role/service.go b/backend/internal/role/service.go
index 45593a43d..5d8be9eef 100644
--- a/backend/internal/role/service.go
+++ b/backend/internal/role/service.go
@@ -110,10 +110,10 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {
return nil
}
var rows []legacyUser
- if err := tx.Table("users").Select("id, roles").
+ if loadLegacyUsersErr := tx.Table("users").Select("id, roles").
Where("NOT EXISTS (SELECT 1 FROM user_role_assignments ura WHERE ura.user_id = users.id)").
- Scan(&rows).Error; err != nil {
- return fmt.Errorf("failed to read legacy users.roles for backfill: %w", err)
+ Scan(&rows).Error; loadLegacyUsersErr != nil {
+ return fmt.Errorf("failed to read legacy users.roles for backfill: %w", loadLegacyUsersErr)
}
for _, u := range rows {
roleID := kit.Ternary(legacyRolesContainsAdminInternal(u.Roles), authz.BuiltInRoleAdmin, authz.BuiltInRoleViewer)
@@ -291,8 +291,8 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti
existing.Name = input.Name
existing.Description = input.Description
existing.Permissions = permissions
- if err := tx.Save(&existing).Error; err != nil {
- return fmt.Errorf("failed to update role: %w", err)
+ if updateRoleErr := tx.Save(&existing).Error; updateRoleErr != nil {
+ return fmt.Errorf("failed to update role: %w", updateRoleErr)
}
out = existing
return nil
@@ -326,8 +326,8 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {
return err
}
affected = ids
- if err := tx.Delete(&Role{}, "id = ?", id).Error; err != nil {
- return fmt.Errorf("failed to delete role: %w", err)
+ if deleteRoleErr := tx.Delete(&Role{}, "id = ?", id).Error; deleteRoleErr != nil {
+ return fmt.Errorf("failed to delete role: %w", deleteRoleErr)
}
return nil
})
@@ -994,8 +994,8 @@ func (s *RoleService) ValidateRoleAssignmentAgainstCaller(ctx context.Context, c
}
desired := []string(role.Permissions)
- if err := validatePermissionsInternal(desired); err != nil {
- return err
+ if validatePermissionsErr := validatePermissionsInternal(desired); validatePermissionsErr != nil {
+ return validatePermissionsErr
}
return validatePermissionSetAgainstCallerInternal(caller, desired, mo.PointerToOption(environmentID).OrEmpty())
}
diff --git a/backend/internal/role/service_test.go b/backend/internal/role/service_test.go
index 6c7b203dc..07e821140 100644
--- a/backend/internal/role/service_test.go
+++ b/backend/internal/role/service_test.go
@@ -1,8 +1,6 @@
package role
import (
- "context"
- "errors"
"path/filepath"
"slices"
"testing"
@@ -30,7 +28,7 @@ func TestValidatePermissionsAgainstCallerRejectsEscalation(t *testing.T) {
authz.PermUsersDelete,
})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrRolePermissionEscalation))
+ require.ErrorIs(t, err, common.ErrRolePermissionEscalation)
require.NoError(t, roleSvc.ValidatePermissionsAgainstCaller(caller, []string{authz.PermRolesRead}))
require.NoError(t, roleSvc.ValidatePermissionsAgainstCaller(authz.SudoPermissionSet(), []string{authz.PermUsersDelete}))
@@ -44,7 +42,7 @@ func TestValidatePermissionsAgainstCallerRejectsEnvOnlyGrantForGlobalRole(t *tes
err := roleSvc.ValidatePermissionsAgainstCaller(caller, []string{authz.PermContainersStart})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrRolePermissionEscalation))
+ require.ErrorIs(t, err, common.ErrRolePermissionEscalation)
}
func TestValidatePermissionsAgainstCallerRejectsUnknownPermissionBeforeEscalation(t *testing.T) {
@@ -55,12 +53,12 @@ func TestValidatePermissionsAgainstCallerRejectsUnknownPermissionBeforeEscalatio
// not as an opaque escalation 403 or a silent pass.
err := roleSvc.ValidatePermissionsAgainstCaller(authz.SudoPermissionSet(), []string{"containrs:start"})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrUnknownPermission))
- require.False(t, errors.Is(err, common.ErrRolePermissionEscalation))
+ require.ErrorIs(t, err, common.ErrUnknownPermission)
+ require.NotErrorIs(t, err, common.ErrRolePermissionEscalation)
}
func TestBackfillLegacyRoleAssignments(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("no-op without legacy column", func(t *testing.T) {
_, roleSvc := setupUserAndRoleServices(t)
@@ -124,7 +122,7 @@ func TestBackfillLegacyRoleAssignments(t *testing.T) {
func assignedRoleIDs(t *testing.T, roleSvc *RoleService, userID string) []string {
t.Helper()
- assignments, err := roleSvc.ListUserAssignments(context.Background(), userID)
+ assignments, err := roleSvc.ListUserAssignments(t.Context(), userID)
require.NoError(t, err)
ids := make([]string, 0, len(assignments))
for _, a := range assignments {
@@ -134,7 +132,7 @@ func assignedRoleIDs(t *testing.T, roleSvc *RoleService, userID string) []string
}
func TestEnsureBuiltInRolesMigratesVariablePermissionsWithoutBackfillingCustomGrants(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
customRole, err := roleSvc.CreateRole(ctx, "Template Reader", nil, []string{authz.PermTemplatesRead})
@@ -207,7 +205,7 @@ func TestEnsureBuiltInRolesMigratesVariablePermissionsWithoutBackfillingCustomGr
}
func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
user := createTestUser(t, userSvc, "victim", "victim")
@@ -215,11 +213,11 @@ func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {
{RoleID: "role_does_not_exist"},
})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrInvalidRoleAssignment))
+ require.ErrorIs(t, err, common.ErrInvalidRoleAssignment)
}
func TestReplaceOidcAssignmentsRejectsUnknownRole(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
user := createTestUser(t, userSvc, "oidc-user", "oidc-user")
@@ -227,11 +225,11 @@ func TestReplaceOidcAssignmentsRejectsUnknownRole(t *testing.T) {
{RoleID: "role_does_not_exist"},
})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrInvalidRoleAssignment))
+ require.ErrorIs(t, err, common.ErrInvalidRoleAssignment)
}
func TestReplaceOidcAssignmentsRejectsUnknownEnvironment(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
user := createTestUser(t, userSvc, "oidc-user-env", "oidc-user-env")
missingEnv := "env_does_not_exist"
@@ -242,11 +240,11 @@ func TestReplaceOidcAssignmentsRejectsUnknownEnvironment(t *testing.T) {
{RoleID: authz.BuiltInRoleViewer, EnvironmentID: &missingEnv},
})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrInvalidRoleAssignment))
+ require.ErrorIs(t, err, common.ErrInvalidRoleAssignment)
}
func TestEffectiveGlobalAdminCountIncludesCustomAllPermissionsRole(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
user := createTestUser(t, userSvc, "custom-admin", "custom-admin")
customRole, err := roleSvc.CreateRole(ctx, "Custom Admin", nil, authz.AllPermissions())
@@ -263,11 +261,11 @@ func TestEffectiveGlobalAdminCountIncludesCustomAllPermissionsRole(t *testing.T)
err = roleSvc.SetUserAssignments(ctx, user.ID, nil)
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrNoGlobalAdminRemains))
+ require.ErrorIs(t, err, common.ErrNoGlobalAdminRemains)
}
func TestEffectiveGlobalAdminCountIgnoresEnvScopedAndServiceAccounts(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
userSvc, roleSvc := setupUserAndRoleServices(t)
customRole, err := roleSvc.CreateRole(ctx, "Custom Admin", nil, authz.AllPermissions())
require.NoError(t, err)
@@ -320,20 +318,20 @@ func setupUserAndRoleServices(t *testing.T) (*database.DB, *RoleService) {
t.Helper()
db := setupAuthServiceTestDB(t)
roleService := NewRoleService(db)
- require.NoError(t, roleService.EnsureBuiltInRoles(context.Background()))
+ require.NoError(t, roleService.EnsureBuiltInRoles(t.Context()))
return db, roleService
}
func createTestUser(t *testing.T, db *database.DB, id, username string) *common.User {
t.Helper()
created := &common.User{ID: id, Username: username}
- require.NoError(t, db.WithContext(context.Background()).Create(created).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(created).Error)
return created
}
func grantGlobalAdmin(t *testing.T, roleService *RoleService, userID string) {
t.Helper()
- require.NoError(t, roleService.SetUserAssignments(context.Background(), userID, []UserRoleAssignment{
+ require.NoError(t, roleService.SetUserAssignments(t.Context(), userID, []UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin},
}))
}
@@ -341,7 +339,7 @@ func grantGlobalAdmin(t *testing.T, roleService *RoleService, userID string) {
func createTestEnvironment(t *testing.T, db *database.DB, id, apiURL string, accessToken *string) {
t.Helper()
now := time.Now()
- require.NoError(t, db.WithContext(context.Background()).Create(&testEnvironmentRow{
+ require.NoError(t, db.WithContext(t.Context()).Create(&testEnvironmentRow{
ID: id, CreatedAt: now, UpdatedAt: &now,
Name: "env-" + id,
ApiUrl: apiURL,
diff --git a/backend/internal/s3/handler.go b/backend/internal/s3/handler.go
index f7cd02cd6..0eb4b39f4 100644
--- a/backend/internal/s3/handler.go
+++ b/backend/internal/s3/handler.go
@@ -72,13 +72,34 @@ func RegisterS3Destinations(api huma.API, service *S3DestinationService, syncRem
handler := &s3DestinationHandlerInternal{service: service, syncRemoteDestinations: syncRemoteDestinations}
handlerutil.RegisterSecured(api,
- handlerutil.Operation("list-s3-destinations", http.MethodGet, s3DestinationPathInternal, "List S3 destinations", "List saved S3-compatible backup destinations with search, sorting, and pagination", s3DestinationTagInternal),
+ handlerutil.Operation(
+ "list-s3-destinations",
+ http.MethodGet,
+ s3DestinationPathInternal,
+ "List S3 destinations",
+ "List saved S3-compatible backup destinations with search, sorting, and pagination",
+ s3DestinationTagInternal,
+ ),
authz.PermS3DestinationsList, handler.listInternal)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("list-all-s3-destinations", http.MethodGet, s3DestinationPathInternal+"/options", "List all S3 destination options", "List saved S3-compatible destinations for backup configuration selectors", s3DestinationTagInternal),
+ handlerutil.Operation(
+ "list-all-s3-destinations",
+ http.MethodGet,
+ s3DestinationPathInternal+"/options",
+ "List all S3 destination options",
+ "List saved S3-compatible destinations for backup configuration selectors",
+ s3DestinationTagInternal,
+ ),
authz.PermS3DestinationsList, handler.listAllInternal)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("sync-s3-destinations", http.MethodPost, s3DestinationPathInternal+"/sync", "Sync S3 destinations", "Synchronize manager-owned S3 destinations to an agent", s3DestinationTagInternal),
+ handlerutil.Operation(
+ "sync-s3-destinations",
+ http.MethodPost,
+ s3DestinationPathInternal+"/sync",
+ "Sync S3 destinations",
+ "Synchronize manager-owned S3 destinations to an agent",
+ s3DestinationTagInternal,
+ ),
authz.PermS3DestinationsSync, handler.syncInternal)
handlerutil.RegisterSecured(api,
handlerutil.Operation("get-s3-destination", http.MethodGet, s3DestinationPathInternal+"/{id}", "Get S3 destination", "", s3DestinationTagInternal),
@@ -90,13 +111,34 @@ func RegisterS3Destinations(api huma.API, service *S3DestinationService, syncRem
handlerutil.Operation("update-s3-destination", http.MethodPut, s3DestinationPathInternal+"/{id}", "Update S3 destination", "", s3DestinationTagInternal),
authz.PermS3DestinationsUpdate, handler.updateInternal)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("test-s3-destination-configuration", http.MethodPost, s3DestinationPathInternal+"/test", "Test unsaved S3 destination configuration", "Verify upload, download, and delete access before saving an S3 destination", s3DestinationTagInternal),
+ handlerutil.Operation(
+ "test-s3-destination-configuration",
+ http.MethodPost,
+ s3DestinationPathInternal+"/test",
+ "Test unsaved S3 destination configuration",
+ "Verify upload, download, and delete access before saving an S3 destination",
+ s3DestinationTagInternal,
+ ),
authz.PermS3DestinationsTest, handler.testConfigurationInternal)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("test-s3-destination", http.MethodPost, s3DestinationPathInternal+"/{id}/test", "Test S3 destination", "Verify upload, download, and delete access using the saved or supplied S3 destination configuration", s3DestinationTagInternal),
+ handlerutil.Operation(
+ "test-s3-destination",
+ http.MethodPost,
+ s3DestinationPathInternal+"/{id}/test",
+ "Test S3 destination",
+ "Verify upload, download, and delete access using the saved or supplied S3 destination configuration",
+ s3DestinationTagInternal,
+ ),
authz.PermS3DestinationsTest, handler.testInternal)
handlerutil.RegisterSecured(api,
- handlerutil.Operation("get-s3-destination-usage", http.MethodGet, s3DestinationPathInternal+"/{id}/in-use", "Check S3 destination references", "Report whether backup records, policies, or settings on this environment still reference the destination", s3DestinationTagInternal),
+ handlerutil.Operation(
+ "get-s3-destination-usage",
+ http.MethodGet,
+ s3DestinationPathInternal+"/{id}/in-use",
+ "Check S3 destination references",
+ "Report whether backup records, policies, or settings on this environment still reference the destination",
+ s3DestinationTagInternal,
+ ),
authz.PermS3DestinationsRead, handler.inUseInternal)
handlerutil.RegisterSecured(api,
handlerutil.Operation("delete-s3-destination", http.MethodDelete, s3DestinationPathInternal+"/{id}", "Delete S3 destination", "", s3DestinationTagInternal),
diff --git a/backend/internal/s3/service.go b/backend/internal/s3/service.go
index 748fba341..b7ae33fe6 100644
--- a/backend/internal/s3/service.go
+++ b/backend/internal/s3/service.go
@@ -145,8 +145,8 @@ func (s *S3DestinationService) CreateS3Destination(ctx context.Context, input ba
}
destination := &S3Destination{}
applyS3ConfigurationInternal(destination, configuration, encryptedSecret)
- if err := s.db.WithContext(ctx).Create(destination).Error; err != nil {
- return nil, fmt.Errorf("failed to create S3 destination: %w", err)
+ if createDestinationErr := s.db.WithContext(ctx).Create(destination).Error; createDestinationErr != nil {
+ return nil, fmt.Errorf("failed to create S3 destination: %w", createDestinationErr)
}
dto := destination.ToDTO()
return &dto, nil
@@ -191,8 +191,8 @@ func (s *S3DestinationService) UpdateS3Destination(ctx context.Context, id strin
}
}
applyS3ConfigurationInternal(destination, configuration, encryptedSecret)
- if err := s.db.WithContext(ctx).Save(destination).Error; err != nil {
- return nil, fmt.Errorf("failed to update S3 destination: %w", err)
+ if updateDestinationErr := s.db.WithContext(ctx).Save(destination).Error; updateDestinationErr != nil {
+ return nil, fmt.Errorf("failed to update S3 destination: %w", updateDestinationErr)
}
dto := destination.ToDTO()
return &dto, nil
@@ -211,12 +211,12 @@ func (s *S3DestinationService) DeleteS3Destination(ctx context.Context, id strin
return fmt.Errorf("%w: remove it from backup configurations and retained backups first", ErrS3DestinationInUse)
}
if s.checkRemoteReferences != nil {
- if err := s.checkRemoteReferences(ctx, id); err != nil {
- return fmt.Errorf("%w: %s", ErrS3DestinationInUse, err.Error())
+ if checkRemoteReferencesErr := s.checkRemoteReferences(ctx, id); checkRemoteReferencesErr != nil {
+ return fmt.Errorf("%w: %s", ErrS3DestinationInUse, checkRemoteReferencesErr.Error())
}
}
- if err := s.db.WithContext(ctx).Delete(destination).Error; err != nil {
- return fmt.Errorf("failed to delete S3 destination: %w", err)
+ if deleteDestinationErr := s.db.WithContext(ctx).Delete(destination).Error; deleteDestinationErr != nil {
+ return fmt.Errorf("failed to delete S3 destination: %w", deleteDestinationErr)
}
return nil
}
@@ -294,8 +294,8 @@ func (s *S3DestinationService) SyncS3Destinations(ctx context.Context, destinati
changed = true
}
if changed {
- if err := s.db.WithContext(ctx).Save(destination).Error; err != nil {
- return fmt.Errorf("failed to sync S3 destination %s: %w", configuration.ID, err)
+ if syncDestinationErr := s.db.WithContext(ctx).Save(destination).Error; syncDestinationErr != nil {
+ return fmt.Errorf("failed to sync S3 destination %s: %w", configuration.ID, syncDestinationErr)
}
}
syncedIDs[configuration.ID] = struct{}{}
@@ -345,8 +345,8 @@ func (s *S3DestinationService) TestS3Destination(ctx context.Context, id string,
return err
}
if input != nil {
- if err := normalization.Normalize(input); err != nil {
- return err
+ if normalizeErr := normalization.Normalize(input); normalizeErr != nil {
+ return normalizeErr
}
updated := destinationConfigurationInternal("", *input)
updated.ID = configuration.ID
diff --git a/backend/internal/s3/service_test.go b/backend/internal/s3/service_test.go
index 77b40e731..03213af04 100644
--- a/backend/internal/s3/service_test.go
+++ b/backend/internal/s3/service_test.go
@@ -1,7 +1,6 @@
package s3
import (
- "context"
"io"
"net/http"
"net/http/httptest"
@@ -12,6 +11,7 @@ import (
backuptypes "github.com/getarcaneapp/arcane/types/v2/backup"
"github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
kit "go.getarcane.app/kit/pkg"
"go.getarcane.app/sys/crypto"
@@ -45,7 +45,7 @@ func setupS3DestinationServiceTestInternal(t *testing.T) (*S3DestinationService,
func TestS3DestinationService_CRUD(t *testing.T) {
service, gormDB := setupS3DestinationServiceTestInternal(t)
- ctx := context.Background()
+ ctx := t.Context()
created, err := service.CreateS3Destination(ctx, backuptypes.CreateS3Destination{
Name: " Cafe\u0301 offsite ",
@@ -100,7 +100,7 @@ func TestS3DestinationService_CRUD(t *testing.T) {
func TestS3DestinationService_DeleteRejectsConfiguredDestination(t *testing.T) {
service, gormDB := setupS3DestinationServiceTestInternal(t)
- ctx := context.Background()
+ ctx := t.Context()
destination, err := service.CreateS3Destination(ctx, backuptypes.CreateS3Destination{
Name: "In use",
Bucket: "arcane-backups",
@@ -118,7 +118,7 @@ func TestS3DestinationService_DeleteRejectsConfiguredDestination(t *testing.T) {
func TestS3DestinationService_SyncS3Destinations(t *testing.T) {
service, gormDB := setupS3DestinationServiceTestInternal(t)
- ctx := context.Background()
+ ctx := t.Context()
legacy, err := service.CreateS3Destination(ctx, backuptypes.CreateS3Destination{
Name: "Legacy",
@@ -184,14 +184,20 @@ func TestS3DestinationService_TestS3DestinationRoundTrip(t *testing.T) {
var requestMethods []string
expectedPathPrefix := "/arcane-backups/production/.arcane-connection-test-"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.NotEmpty(t, r.Header.Get("Authorization"))
- require.True(t, strings.HasPrefix(r.URL.Path, expectedPathPrefix))
+ if !assert.NotEmpty(t, r.Header.Get("Authorization")) {
+ return
+ }
+ if !assert.True(t, strings.HasPrefix(r.URL.Path, expectedPathPrefix)) {
+ return
+ }
requestMethods = append(requestMethods, r.Method)
switch r.Method {
case http.MethodPut:
var err error
object, err = io.ReadAll(r.Body)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
w.Header().Set("ETag", `"test-etag"`)
w.WriteHeader(http.StatusOK)
case http.MethodGet:
@@ -208,7 +214,7 @@ func TestS3DestinationService_TestS3DestinationRoundTrip(t *testing.T) {
defer server.Close()
service, _ := setupS3DestinationServiceTestInternal(t)
- require.NoError(t, service.TestS3DestinationConfiguration(context.Background(), backuptypes.CreateS3Destination{
+ require.NoError(t, service.TestS3DestinationConfiguration(t.Context(), backuptypes.CreateS3Destination{
Name: "Unsaved destination",
Endpoint: server.URL,
Bucket: "arcane-backups",
@@ -219,7 +225,7 @@ func TestS3DestinationService_TestS3DestinationRoundTrip(t *testing.T) {
UseSSL: false,
ForcePathStyle: true,
}))
- destination, err := service.CreateS3Destination(context.Background(), backuptypes.CreateS3Destination{
+ destination, err := service.CreateS3Destination(t.Context(), backuptypes.CreateS3Destination{
Name: "Test destination",
Endpoint: server.URL,
Bucket: "arcane-backups",
@@ -232,13 +238,13 @@ func TestS3DestinationService_TestS3DestinationRoundTrip(t *testing.T) {
})
require.NoError(t, err)
- require.NoError(t, service.TestS3Destination(context.Background(), destination.ID, nil))
+ require.NoError(t, service.TestS3Destination(t.Context(), destination.ID, nil))
// Changing a connection field without re-supplying the secret is rejected
// before any outbound request: the stored secret must never sign requests
// against caller-modified connection settings.
requestsBeforeRejection := len(requestMethods)
- err = service.TestS3Destination(context.Background(), destination.ID, &backuptypes.UpdateS3Destination{
+ err = service.TestS3Destination(t.Context(), destination.ID, &backuptypes.UpdateS3Destination{
Name: destination.Name,
Endpoint: server.URL,
Bucket: "edited-bucket",
@@ -252,7 +258,7 @@ func TestS3DestinationService_TestS3DestinationRoundTrip(t *testing.T) {
require.Len(t, requestMethods, requestsBeforeRejection)
expectedPathPrefix = "/edited-bucket/edited/.arcane-connection-test-"
- require.NoError(t, service.TestS3Destination(context.Background(), destination.ID, &backuptypes.UpdateS3Destination{
+ require.NoError(t, service.TestS3Destination(t.Context(), destination.ID, &backuptypes.UpdateS3Destination{
Name: destination.Name,
Endpoint: server.URL,
Bucket: "edited-bucket",
@@ -270,7 +276,7 @@ func TestS3DestinationService_TestS3DestinationRoundTrip(t *testing.T) {
http.MethodPut, http.MethodGet, http.MethodDelete,
}, requestMethods)
require.Empty(t, object)
- persisted, err := service.GetS3Destination(context.Background(), destination.ID)
+ persisted, err := service.GetS3Destination(t.Context(), destination.ID)
require.NoError(t, err)
require.Equal(t, "arcane-backups", persisted.Bucket)
require.Equal(t, "production", persisted.Prefix)
diff --git a/backend/internal/search/model.go b/backend/internal/search/model.go
index d246ac67e..3ca2ceed4 100644
--- a/backend/internal/search/model.go
+++ b/backend/internal/search/model.go
@@ -3,6 +3,8 @@ package search
// CustomizeItem represents a customization configuration item
// This struct uses reflection tags to define customization categories and metadata
// Categories must be grouped together and use `catmeta` tag for category-level metadata
+//
+//nolint:lll // Reflection metadata must remain in single struct-tag literals.
type CustomizeItem struct {
// Defaults category
DefaultProjectTemplate CustomizeVariable `key:"defaultProjectTemplate" meta:"label=Default Project Template;type=select;keywords=template,default,project,scaffold,boilerplate,starter;category=defaults;description=Set the default template for new projects"`
diff --git a/backend/internal/session/service_test.go b/backend/internal/session/service_test.go
index 4bb93c7b6..45c2e7dbe 100644
--- a/backend/internal/session/service_test.go
+++ b/backend/internal/session/service_test.go
@@ -1,7 +1,6 @@
package session
import (
- "context"
"testing"
"time"
@@ -18,7 +17,7 @@ import (
)
func TestSessionService_RotateRefreshTokenRequiresCurrentHash(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthServiceTestDB(t)
require.NoError(t, db.Create(&common.User{
ID: "u-session",
@@ -40,7 +39,7 @@ func TestSessionService_RotateRefreshTokenRequiresCurrentHash(t *testing.T) {
}
func TestSessionService_DeleteExpiredSessions(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupAuthServiceTestDB(t)
require.NoError(t, db.Create(&common.User{
ID: "u-cleanup",
@@ -91,7 +90,18 @@ func setupAuthServiceTestDB(t *testing.T) *database.DB {
))
// environments and api_keys live in packages that import this one; the
// in-package tests only need the tables to exist.
- require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS environments (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, api_url text, status text, enabled numeric, is_edge numeric, hidden numeric, last_seen datetime, last_edge_transport text, access_token text, api_key_id text, parent_environment_id text, swarm_node_id text)").Error)
- require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, description text, key_hash text, key_prefix text, kind text, user_id text, environment_id text, managed_by text, expires_at datetime, last_used_at datetime)").Error)
+ require.NoError(
+ t,
+ db.Exec("CREATE TABLE IF NOT EXISTS environments (id text PRIMARY KEY, created_at datetime, updated_at dateti"+
+ "me, name text, api_url text, status text, enabled numeric, is_edge numeric, hidden numeric, last_see"+
+ "n datetime, last_edge_transport text, access_token text, api_key_id text, parent_environment_id text"+
+ ", swarm_node_id text)").Error,
+ )
+ require.NoError(
+ t,
+ db.Exec("CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY, created_at datetime, updated_at datetime, "+
+ "name text, description text, key_hash text, key_prefix text, kind text, user_id text, environment_id"+
+ " text, managed_by text, expires_at datetime, last_used_at datetime)").Error,
+ )
return &database.DB{DB: db}
}
diff --git a/backend/internal/settings/features_test.go b/backend/internal/settings/features_test.go
index e7499fec1..770971743 100644
--- a/backend/internal/settings/features_test.go
+++ b/backend/internal/settings/features_test.go
@@ -1,7 +1,6 @@
package settings
import (
- "context"
"net/http"
"testing"
@@ -94,7 +93,7 @@ func TestSettingsService_RejectInvalidFeatureBoolean(t *testing.T) {
require.ErrorIs(t, err, common.ErrValidation)
err = svc.UpdateSetting(t.Context(), features.VulnerabilityManagementSettingKey, invalid)
require.ErrorIs(t, err, common.ErrValidation)
- err = svc.UpdateSettingValues(context.Background(), []libarcane.SettingUpdate{{Key: features.VulnerabilityManagementSettingKey, Value: invalid}})
+ err = svc.UpdateSettingValues(t.Context(), []libarcane.SettingUpdate{{Key: features.VulnerabilityManagementSettingKey, Value: invalid}})
require.ErrorIs(t, err, common.ErrValidation)
require.True(t, svc.IsFeatureEnabled(t.Context(), features.VulnerabilityManagement))
})
diff --git a/backend/internal/settings/handler.go b/backend/internal/settings/handler.go
index 5c6399b96..b50f6a24e 100644
--- a/backend/internal/settings/handler.go
+++ b/backend/internal/settings/handler.go
@@ -413,8 +413,8 @@ func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context,
if err != nil {
return nil, huma.Error400BadRequest(fmt.Sprintf("cannot read projects directory %q: %v", resolved, err))
}
- if err := f.Close(); err != nil {
- return nil, huma.Error400BadRequest(fmt.Sprintf("cannot read projects directory %q: %v", resolved, err))
+ if closeErr := f.Close(); closeErr != nil {
+ return nil, huma.Error400BadRequest(fmt.Sprintf("cannot read projects directory %q: %v", resolved, closeErr))
}
}
}
diff --git a/backend/internal/settings/handler_test.go b/backend/internal/settings/handler_test.go
index 184de83a7..4caca097b 100644
--- a/backend/internal/settings/handler_test.go
+++ b/backend/internal/settings/handler_test.go
@@ -62,7 +62,7 @@ func TestSettingsHandlerUpdateLocalEnvironmentRejectsUnreadableProjectsDirectory
t.Skip("test requires a non-root UID to trigger permission-denied on ReadDir")
}
- ctx := context.Background()
+ ctx := t.Context()
settingsService, err := newSettingsServiceForTestInternal(t, ctx, setupSettingsTestDB(t))
require.NoError(t, err)
originalDir := settingsService.GetSettingsConfig().ProjectsDirectory.Value
@@ -99,18 +99,18 @@ func TestSettingsHandlerRemoteWorkspaceSettingsVisibilityInternal(t *testing.T)
return json.Unmarshal(payload, output)
}
- settingsService, err := newSettingsServiceForTestInternal(t, context.Background(), setupSettingsTestDB(t))
+ settingsService, err := newSettingsServiceForTestInternal(t, t.Context(), setupSettingsTestDB(t))
require.NoError(t, err)
handler := &SettingsHandler{settingsService: settingsService, proxyRemoteJSON: proxy}
permissions := authz.NewPermissionSet()
permissions.AddEnv("env-remote", authz.PermSettingsRead)
- ctx := context.WithValue(context.Background(), middleware.ContextKeyUserPermissions, permissions)
+ ctx := context.WithValue(t.Context(), middleware.ContextKeyUserPermissions, permissions)
output, err := handler.GetSettings(ctx, &GetSettingsInput{EnvironmentID: "env-remote"})
require.NoError(t, err)
require.Equal(t, []settingstypes.PublicSetting{remoteSettings[0], remoteSettings[3], remoteSettings[4]}, output.Body)
- adminCtx := context.WithValue(context.Background(), middleware.ContextKeyUserPermissions, authz.SudoPermissionSet())
+ adminCtx := context.WithValue(t.Context(), middleware.ContextKeyUserPermissions, authz.SudoPermissionSet())
output, err = handler.GetSettings(adminCtx, &GetSettingsInput{EnvironmentID: "env-remote"})
require.NoError(t, err)
require.Equal(t, remoteSettings, output.Body)
diff --git a/backend/internal/settings/model.go b/backend/internal/settings/model.go
index d711d0503..b415e5c23 100644
--- a/backend/internal/settings/model.go
+++ b/backend/internal/settings/model.go
@@ -61,6 +61,7 @@ func (s SettingVariable) AsDurationSeconds() time.Duration {
return kit.Ternary(err != nil, 0, time.Duration(val)*time.Second)
}
+//nolint:lll // Reflection metadata must remain in single struct-tag literals.
type Settings struct {
// General category
ProjectsDirectory SettingVariable `key:"projectsDirectory,envOverride" meta:"label=Projects Directory;type=text;keywords=projects,directory,path,folder,location,storage,files,compose,docker-compose;category=internal;description=Configure where project files are stored"`
diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.go
index f057c8279..c1e105ac3 100644
--- a/backend/internal/settings/service.go
+++ b/backend/internal/settings/service.go
@@ -315,7 +315,16 @@ func DefaultSettingsConfig() *Settings {
func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *database.DB) (*Settings, error) {
if config.Load().UIConfigurationDisabled || config.Load().AgentMode {
- slog.DebugContext(ctx, "loadDatabaseSettingsInternal: using env path", "UIConfigurationDisabled", config.Load().UIConfigurationDisabled, "AgentMode", config.Load().AgentMode, "Environment", config.Load().Environment)
+ slog.DebugContext(
+ ctx,
+ "loadDatabaseSettingsInternal: using env path",
+ "UIConfigurationDisabled",
+ config.Load().UIConfigurationDisabled,
+ "AgentMode",
+ config.Load().AgentMode,
+ "Environment",
+ config.Load().Environment,
+ )
return s.loadDatabaseConfigFromEnv(ctx, db)
}
@@ -378,7 +387,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *dat
// debug: log each env name checked and whether a value exists
if val, ok, _ := utils.LookupEnvOrFile(envVarName); ok {
mask := "<empty>"
- if len(val) > 0 {
+ if val != "" {
mask = fmt.Sprintf("%d chars", len(val))
}
slog.DebugContext(ctx, "loadDatabaseConfigFromEnv: env override found", "key", key, "env", envVarName, "valueMasked", mask)
@@ -641,7 +650,16 @@ func (s *SettingsService) updateSettingsInternal(ctx context.Context, updates se
}
for _, field := range required {
if strings.TrimSpace(field.value) == "" {
- return settingsUpdateResultInternal{}, common.Classify(common.ErrValidation, &base.FieldError{Field: field.key, Err: fmt.Errorf("Enabling OIDC requires %s", field.key)}) //nolint:staticcheck // Preserve the existing error message.
+ return settingsUpdateResultInternal{}, common.Classify(
+ common.ErrValidation,
+ &base.FieldError{
+ Field: field.key,
+ Err: fmt.Errorf(
+ "enabling OIDC requires %s",
+ field.key,
+ ),
+ },
+ )
}
}
}
@@ -668,12 +686,12 @@ func (s *SettingsService) updateSettingsInternal(ctx context.Context, updates se
valuesToUpdate = append(valuesToUpdate, SettingVariable{Key: "trivyServerToken", Value: *updates.TrivyServerToken})
}
- if err := s.persistSettings(ctx, valuesToUpdate); err != nil {
- return settingsUpdateResultInternal{}, err
+ if persistSettingsErr := s.persistSettings(ctx, valuesToUpdate); persistSettingsErr != nil {
+ return settingsUpdateResultInternal{}, persistSettingsErr
}
- if err := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); err != nil {
- return settingsUpdateResultInternal{}, err
+ if refreshSettingsCacheErr := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); refreshSettingsCacheErr != nil {
+ return settingsUpdateResultInternal{}, refreshSettingsCacheErr
}
settingsCfg := s.GetSettingsConfig()
changes := make([]libarcane.SettingUpdate, 0, len(valuesToUpdate))
@@ -805,14 +823,14 @@ func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
- if err := tx.Create(&defaultSetting).Error; err != nil {
- return fmt.Errorf("failed to create default setting %s: %w", defaultSetting.Key, err)
+ if createDefaultSettingErr := tx.Create(&defaultSetting).Error; createDefaultSettingErr != nil {
+ return fmt.Errorf("failed to create default setting %s: %w", defaultSetting.Key, createDefaultSettingErr)
}
case err != nil:
return fmt.Errorf("failed to check for existing setting %s: %w", defaultSetting.Key, err)
case slices.Contains(retiredSettingValuesInternal[defaultSetting.Key], existing.Value):
- if err := tx.Model(&SettingVariable{}).Where("key = ?", defaultSetting.Key).Update("value", defaultSetting.Value).Error; err != nil {
- return fmt.Errorf("failed to replace retired default for setting %s: %w", defaultSetting.Key, err)
+ if replaceDefaultSettingErr := tx.Model(&SettingVariable{}).Where("key = ?", defaultSetting.Key).Update("value", defaultSetting.Value).Error; replaceDefaultSettingErr != nil {
+ return fmt.Errorf("failed to replace retired default for setting %s: %w", defaultSetting.Key, replaceDefaultSettingErr)
}
}
}
@@ -922,16 +940,16 @@ func (s *SettingsService) upsertEnvSetting(ctx context.Context, tx *gorm.DB, key
switch {
case errors.Is(err, gorm.ErrRecordNotFound):
newVar := SettingVariable{Key: key, Value: envVal}
- if err := tx.Create(&newVar).Error; err != nil {
- return fmt.Errorf("persist env setting %s: %w", key, err)
+ if createEnvSettingErr := tx.Create(&newVar).Error; createEnvSettingErr != nil {
+ return fmt.Errorf("persist env setting %s: %w", key, createEnvSettingErr)
}
slog.DebugContext(ctx, "Created setting from environment", "key", key)
case err != nil:
return fmt.Errorf("check setting %s: %w", key, err)
default:
if existing.Value != envVal {
- if err := tx.Model(&existing).Update("value", envVal).Error; err != nil {
- return fmt.Errorf("update env setting %s: %w", key, err)
+ if updateEnvSettingErr := tx.Model(&existing).Update("value", envVal).Error; updateEnvSettingErr != nil {
+ return fmt.Errorf("update env setting %s: %w", key, updateEnvSettingErr)
}
slog.DebugContext(ctx, "Updated setting from environment", "key", key)
}
@@ -1152,15 +1170,15 @@ func (s *SettingsService) ensureEncryptedKeyInternal(ctx context.Context, keyNam
}
if errors.Is(err, gorm.ErrRecordNotFound) {
- if err := tx.Create(&SettingVariable{Key: keyName, Value: encrypted}).Error; err != nil {
- return fmt.Errorf("failed to persist signing key: %w", err)
+ if createSigningKeyErr := tx.Create(&SettingVariable{Key: keyName, Value: encrypted}).Error; createSigningKeyErr != nil {
+ return fmt.Errorf("failed to persist signing key: %w", createSigningKeyErr)
}
return nil
}
- if err := tx.Model(&SettingVariable{}).
+ if updateSigningKeyErr := tx.Model(&SettingVariable{}).
Where("key = ?", keyName).
- Update("value", encrypted).Error; err != nil {
- return fmt.Errorf("failed to update signing key: %w", err)
+ Update("value", encrypted).Error; updateSigningKeyErr != nil {
+ return fmt.Errorf("failed to update signing key: %w", updateSigningKeyErr)
}
return nil
})
@@ -1206,11 +1224,11 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projec
return fmt.Errorf("failed to resolve relative path to absolute: %w", absErr)
}
slog.InfoContext(ctx, "Normalizing projects directory from relative to absolute path", "from", value, "to", absPath, "base", cwd)
- if err := s.updateSettingValueNoRefreshInternal(ctx, "projectsDirectory", absPath); err != nil {
- return fmt.Errorf("failed to update projectsDirectory: %w", err)
+ if updateSettingValueNoRefreshErr := s.updateSettingValueNoRefreshInternal(ctx, "projectsDirectory", absPath); updateSettingValueNoRefreshErr != nil {
+ return fmt.Errorf("failed to update projectsDirectory: %w", updateSettingValueNoRefreshErr)
}
- if err := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); err != nil {
- return err
+ if refreshSettingsCacheErr := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); refreshSettingsCacheErr != nil {
+ return refreshSettingsCacheErr
}
slog.InfoContext(ctx, "Successfully normalized projects directory")
s.publishSettingsChangesInternal([]libarcane.SettingUpdate{{Key: "projectsDirectory", Value: absPath}})
@@ -1253,11 +1271,11 @@ func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {
return fmt.Errorf("failed to resolve relative path to absolute: %w", absErr)
}
slog.InfoContext(ctx, "Normalizing builds directory from relative to absolute path", "from", value, "to", absPath, "base", cwd)
- if err := s.updateSettingValueNoRefreshInternal(ctx, buildsKey, absPath); err != nil {
- return fmt.Errorf("failed to update buildsDirectory: %w", err)
+ if updateSettingValueNoRefreshErr := s.updateSettingValueNoRefreshInternal(ctx, buildsKey, absPath); updateSettingValueNoRefreshErr != nil {
+ return fmt.Errorf("failed to update buildsDirectory: %w", updateSettingValueNoRefreshErr)
}
- if err := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); err != nil {
- return err
+ if refreshSettingsCacheErr := s.refreshSettingsCacheInternal(context.WithoutCancel(ctx)); refreshSettingsCacheErr != nil {
+ return refreshSettingsCacheErr
}
slog.InfoContext(ctx, "Successfully normalized builds directory")
s.publishSettingsChangesInternal([]libarcane.SettingUpdate{{Key: buildsKey, Value: absPath}})
diff --git a/backend/internal/settings/service_test.go b/backend/internal/settings/service_test.go
index dcdba8651..e85a4afe9 100644
--- a/backend/internal/settings/service_test.go
+++ b/backend/internal/settings/service_test.go
@@ -34,7 +34,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
t.Helper()
svc, err := NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -54,7 +54,7 @@ func waitForSettingsNotificationsInternal(t *testing.T, svc *SettingsService) {
}
func TestSettingsService_EnsureDefaultSettings_ReplacesRetiredDefaults(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -71,7 +71,7 @@ func TestSettingsService_EnsureDefaultSettings_ReplacesRetiredDefaults(t *testin
}
func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -89,10 +89,32 @@ func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {
require.Equal(t, count1, count2)
// Spot-check core and automation defaults exist with correct values
- for _, key := range []string{"authLocalEnabled", "projectsDirectory", "followProjectSymlinks", "autoUpdateExcludedContainers", "imageEventWatcherEnabled", "vulnerabilityScanEnabled", "vulnerabilityScanInterval", "toolsImageRegistry", "updateCheckRegistry", "trivyDbRegistry", "trivyNetwork", "trivySecurityOpts", "trivyPrivileged", "trivyResourceLimitsEnabled", "trivyCpuLimit", "trivyMemoryLimitMb", "trivyConcurrentScanContainers", "gitSyncMaxFiles", "gitSyncMaxTotalSizeMb", "gitSyncMaxBinarySizeMb", "lifecycleDefaultRunnerImage"} {
+ for _, key := range []string{
+ "authLocalEnabled",
+ "projectsDirectory",
+ "followProjectSymlinks",
+ "autoUpdateExcludedContainers",
+ "imageEventWatcherEnabled",
+ "vulnerabilityScanEnabled",
+ "vulnerabilityScanInterval",
+ "toolsImageRegistry",
+ "updateCheckRegistry",
+ "trivyDbRegistry",
+ "trivyNetwork",
+ "trivySecurityOpts",
+ "trivyPrivileged",
+ "trivyResourceLimitsEnabled",
+ "trivyCpuLimit",
+ "trivyMemoryLimitMb",
+ "trivyConcurrentScanContainers",
+ "gitSyncMaxFiles",
+ "gitSyncMaxTotalSizeMb",
+ "gitSyncMaxBinarySizeMb",
+ "lifecycleDefaultRunnerImage",
+ } {
var sv SettingVariable
- err := svc.db.WithContext(ctx).Where("key = ?", key).First(&sv).Error
- require.NoErrorf(t, err, "missing default key %s", key)
+ lookupSettingErr := svc.db.WithContext(ctx).Where("key = ?", key).First(&sv).Error
+ require.NoErrorf(t, lookupSettingErr, "missing default key %s", key)
switch key {
case "followProjectSymlinks":
@@ -138,7 +160,7 @@ func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {
}
func TestSettingsService_ImageEventWatcherSettingPersists(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -155,7 +177,7 @@ func TestSettingsService_ImageEventWatcherSettingPersists(t *testing.T) {
}
func TestSettingsService_GetSettings_UnknownKeysIgnored(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -168,7 +190,7 @@ func TestSettingsService_GetSettings_UnknownKeysIgnored(t *testing.T) {
}
func TestSettingsService_GetSettings_UsesCachedSnapshotWithoutDatabase(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -184,7 +206,7 @@ func TestSettingsService_GetSettings_UsesCachedSnapshotWithoutDatabase(t *testin
}
func TestSettingsService_AvatarMaxUploadSizeDefaultAndUpdate(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -205,7 +227,7 @@ func TestSettingsService_AvatarMaxUploadSizeDefaultAndUpdate(t *testing.T) {
}
func TestSettingsServiceUpdateSettingsRejectsOIDCIssuerChangeWithStoredSecretInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -224,7 +246,7 @@ func TestSettingsServiceUpdateSettingsRejectsOIDCIssuerChangeWithStoredSecretInt
}
func TestSettingsServiceUpdateSettingsAllowsOIDCIssuerChangeWhenClearingSecretInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -244,7 +266,7 @@ func TestSettingsServiceUpdateSettingsAllowsOIDCIssuerChangeWhenClearingSecretIn
}
func TestSettingsServiceUpdateSettingsRejectsEnablingOIDCWithoutSecretInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -262,7 +284,7 @@ func TestSettingsServiceUpdateSettingsRejectsEnablingOIDCWithoutSecretInternal(t
}
func TestSettingsServiceUpdateSettingsAllowsOIDCIssuerChangeWithReplacementSecretInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -289,7 +311,7 @@ func TestSettingsServiceUpdateSettingsAllowsOIDCIssuerChangeWithReplacementSecre
}
func TestSettingsServiceUpdateSettingsRejectsTrivyServerChangeWithStoredTokenInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -308,7 +330,7 @@ func TestSettingsServiceUpdateSettingsRejectsTrivyServerChangeWithStoredTokenInt
}
func TestSettingsServiceUpdateSettingsAllowsTrivyServerChangeWithReplacementTokenInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -328,7 +350,7 @@ func TestSettingsServiceUpdateSettingsAllowsTrivyServerChangeWithReplacementToke
}
func TestSettingsServiceUpdateSettingsAllowsClearingTrivyServerWithStoredTokenInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -347,7 +369,7 @@ func TestSettingsServiceUpdateSettingsAllowsClearingTrivyServerWithStoredTokenIn
}
func TestSettingsServiceUpdateSettingsAllowsTrivyServerChangeWithoutStoredTokenInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -364,7 +386,7 @@ func TestSettingsServiceUpdateSettingsAllowsTrivyServerChangeWithoutStoredTokenI
}
func TestSettingsService_PruneUnknownSettings_RemovesStaleKeys(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -389,7 +411,7 @@ func TestSettingsService_PruneUnknownSettings_RemovesStaleKeys(t *testing.T) {
}
func TestSettingsService_GetSettings_EnvOverride_OidcMergeAccounts(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
t.Setenv("OIDC_MERGE_ACCOUNTS", "true")
@@ -403,7 +425,7 @@ func TestSettingsService_GetSettings_EnvOverride_OidcMergeAccounts(t *testing.T)
}
func TestSettingsService_GetSettings_EnvOverride_TrivyScanTimeout(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
t.Setenv("TRIVY_SCAN_TIMEOUT", "1800")
@@ -417,7 +439,7 @@ func TestSettingsService_GetSettings_EnvOverride_TrivyScanTimeout(t *testing.T)
}
func TestSettingsService_GetSettings_EnvOverride_TrivyResourceLimits(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
t.Setenv("TRIVY_RESOURCE_LIMITS_ENABLED", "false")
t.Setenv("TRIVY_CPU_LIMIT", "2.5")
@@ -435,7 +457,7 @@ func TestSettingsService_GetSettings_EnvOverride_TrivyResourceLimits(t *testing.
}
func TestSettingsService_GetSettings_EnvOverride_TrivyNetwork(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
t.Setenv("TRIVY_NETWORK", "arcane-external")
@@ -449,7 +471,7 @@ func TestSettingsService_GetSettings_EnvOverride_TrivyNetwork(t *testing.T) {
}
func TestSettingsService_GetSettings_EnvOverride_FollowProjectSymlinks(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
t.Setenv("FOLLOW_PROJECT_SYMLINKS", "true")
@@ -463,7 +485,7 @@ func TestSettingsService_GetSettings_EnvOverride_FollowProjectSymlinks(t *testin
}
func TestSettingsService_GetSettings_EnvOverride_TrivyRuntimeSecurity(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
t.Setenv("TRIVY_SECURITY_OPTS", "label=disable,\nlabel=type:container_runtime_t")
t.Setenv("TRIVY_PRIVILEGED", "true")
@@ -479,7 +501,7 @@ func TestSettingsService_GetSettings_EnvOverride_TrivyRuntimeSecurity(t *testing
}
func TestSettingsService_GetStringSetting_EnvOverride_SwarmStackSourcesDirectory(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
t.Setenv("SWARM_STACK_SOURCES_DIRECTORY", "/mnt/swarm-from-env")
@@ -492,7 +514,7 @@ func TestSettingsService_GetStringSetting_EnvOverride_SwarmStackSourcesDirectory
}
func TestSettingsService_isEnvOverrideActiveInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
@@ -511,7 +533,7 @@ func TestSettingsService_isEnvOverrideActiveInternal(t *testing.T) {
}
func TestSettingsService_GetSetHelpers(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -533,7 +555,7 @@ func TestSettingsService_GetSetHelpers(t *testing.T) {
}
func TestSettingsService_UpdateSetting(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -546,7 +568,7 @@ func TestSettingsService_UpdateSetting(t *testing.T) {
}
func TestSettingsService_UpdateSettingRejectsInvalidCronBeforePersistence(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -560,7 +582,7 @@ func TestSettingsService_UpdateSettingRejectsInvalidCronBeforePersistence(t *tes
}
func TestSettingsService_UpdateSetting_RefreshesCachedSnapshot(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -576,7 +598,7 @@ func TestSettingsService_UpdateSetting_RefreshesCachedSnapshot(t *testing.T) {
}
func TestSettingsService_UpdateSettings_PruneModesDoNotTriggerScheduledPruneCallback(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -596,7 +618,7 @@ func TestSettingsService_UpdateSettings_PruneModesDoNotTriggerScheduledPruneCall
}
func TestSettingsService_UpdateSettings_ScheduledPruneScheduleTriggersCallback(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -664,8 +686,8 @@ func TestSettingsServiceActorPublishesSnapshotBeforeAsynchronousNotificationInte
require.Equal(t, "https://actor.example", <-callbackStarted)
select {
- case err := <-updateResult:
- require.NoError(t, err)
+ case updateErr := <-updateResult:
+ require.NoError(t, updateErr)
case <-time.After(time.Second):
require.FailNow(t, "settings update waited for notification callback")
}
@@ -676,8 +698,8 @@ func TestSettingsServiceActorPublishesSnapshotBeforeAsynchronousNotificationInte
secondUpdate <- updateErr
}()
select {
- case err := <-secondUpdate:
- require.NoError(t, err)
+ case secondUpdateErr := <-secondUpdate:
+ require.NoError(t, secondUpdateErr)
case <-time.After(time.Second):
require.FailNow(t, "settings subscriber blocked the next settings writer")
}
@@ -747,13 +769,13 @@ func TestSettingsServiceActorSerializesContainerExclusionUpdatesInternal(t *test
}
func BenchmarkSettingsService_GetSettings(b *testing.B) {
- ctx := context.Background()
+ ctx := b.Context()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
require.FailNowf(b, "benchmark database setup failed", "%v", err)
}
- if err := db.AutoMigrate(&SettingVariable{}); err != nil {
- require.FailNowf(b, "benchmark database migration failed", "%v", err)
+ if autoMigrateErr := db.AutoMigrate(&SettingVariable{}); autoMigrateErr != nil {
+ require.FailNowf(b, "benchmark database migration failed", "%v", autoMigrateErr)
}
settingsDB := &database.DB{DB: db}
svc, err := newSettingsServiceForTestInternal(b, ctx, settingsDB)
@@ -765,9 +787,9 @@ func BenchmarkSettingsService_GetSettings(b *testing.B) {
b.ResetTimer()
for b.Loop() {
- settingsCfg, err := svc.GetSettings(ctx)
- if err != nil {
- require.FailNowf(b, "benchmark GetSettings failed", "%v", err)
+ settingsCfg, getSettingsErr := svc.GetSettings(ctx)
+ if getSettingsErr != nil {
+ require.FailNowf(b, "benchmark GetSettings failed", "%v", getSettingsErr)
}
if settingsCfg == nil {
require.FailNow(b, "GetSettings returned nil settings")
@@ -776,7 +798,7 @@ func BenchmarkSettingsService_GetSettings(b *testing.B) {
}
func TestSettingsService_EnsureEncryptionKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -808,7 +830,7 @@ func TestSettingsService_EnsureEncryptionKey(t *testing.T) {
}
func TestSettingsService_LoadDatabaseSettings_ReloadsChanges(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -838,7 +860,7 @@ func TestSettingsService_LoadDatabaseSettings_UIConfigurationDisabled_Env(t *tes
c := config.Load()
c.UIConfigurationDisabled = true
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -852,7 +874,7 @@ func TestSettingsService_LoadDatabaseSettings_UIConfigurationDisabled_Env(t *tes
}
func TestSettingsService_UpdateSettings_RefreshesCache(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -881,7 +903,7 @@ func TestSettingsService_UpdateSettings_RefreshesCache(t *testing.T) {
func TestSettingsService_UpdateSettings_ReturnsEnvOverriddenValues(t *testing.T) {
t.Setenv("DOCKER_HOST", "tcp://env-docker:2375")
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -903,7 +925,7 @@ func TestSettingsService_UpdateSettings_ReturnsEnvOverriddenValues(t *testing.T)
}
func TestSettingsService_UpdateSettings_TimeoutCallbackIncludesTrivyScanTimeout(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -923,7 +945,7 @@ func TestSettingsService_UpdateSettings_TimeoutCallbackIncludesTrivyScanTimeout(
}
func TestSettingsService_UpdateSettings_TimeoutCallbackIncludesTrivyResourceLimits(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -949,7 +971,7 @@ func TestSettingsService_UpdateSettings_TimeoutCallbackIncludesTrivyResourceLimi
}
func TestSettingsService_UpdateSettings_TimeoutCallbackIncludesTrivyConcurrentScanContainers(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -969,7 +991,7 @@ func TestSettingsService_UpdateSettings_TimeoutCallbackIncludesTrivyConcurrentSc
}
func TestSettingsService_UpdateSettings_TrivyNetworkTriggersVulnerabilityCallback(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -987,7 +1009,7 @@ func TestSettingsService_UpdateSettings_TrivyNetworkTriggersVulnerabilityCallbac
}
func TestSettingsService_UpdateSettings_TrivyNetworkDoesNotTriggerTimeoutCallback(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1005,7 +1027,7 @@ func TestSettingsService_UpdateSettings_TrivyNetworkDoesNotTriggerTimeoutCallbac
}
func TestSettingsService_UpdateSettings_TrivyRuntimeSecurityTriggersVulnerabilityCallback(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1026,7 +1048,7 @@ func TestSettingsService_UpdateSettings_TrivyRuntimeSecurityTriggersVulnerabilit
}
func TestSettingsService_UpdateSettings_TrivyRuntimeSecurityDoesNotTriggerTimeoutCallback(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1050,7 +1072,7 @@ func TestSettingsService_LoadDatabaseSettings_InternalKeys_EnvMode(t *testing.T)
// Set env + disable flag
t.Setenv("UI_CONFIGURATION_DISABLED", "true")
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
// Pre-populate an internal setting in the DB
@@ -1070,7 +1092,7 @@ func TestSettingsService_LoadDatabaseSettings_InternalKeys_EnvMode(t *testing.T)
}
func TestSettingsService_NormalizeProjectsDirectory_ConvertsRelativeToAbsolute(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1093,7 +1115,7 @@ func TestSettingsService_NormalizeProjectsDirectory_ConvertsRelativeToAbsolute(t
}
func TestSettingsService_NormalizeProjectsDirectory_SkipsWhenEnvSet(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1112,7 +1134,7 @@ func TestSettingsService_NormalizeProjectsDirectory_SkipsWhenEnvSet(t *testing.T
}
func TestSettingsService_NormalizeProjectsDirectory_LeavesOtherPathsUnchanged(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1131,7 +1153,7 @@ func TestSettingsService_NormalizeProjectsDirectory_LeavesOtherPathsUnchanged(t
}
func TestSettingsService_NormalizeProjectsDirectory_HandlesNotFound(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1144,7 +1166,7 @@ func TestSettingsService_NormalizeProjectsDirectory_HandlesNotFound(t *testing.T
}
func TestSettingsService_NormalizeProjectsDirectory_UpdatesCacheAfterNormalization(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSettingsTestDB(t)
svc, err := newSettingsServiceForTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -1196,7 +1218,7 @@ func TestSettingsService_NormalizeProjectsDirectoryPublishesChangeInternal(t *te
// pointer (no per-call clone), env overrides win over database values, and
// an update rebuilds the snapshot while keeping the override applied.
func TestSettingsServiceEffectiveSnapshotMaterializedInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Setenv("PROJECTS_DIRECTORY", "/env/projects")
db := setupSettingsTestDB(t)
diff --git a/backend/internal/swarm/handler.go b/backend/internal/swarm/handler.go
index 8643f68d7..b1c4147fe 100644
--- a/backend/internal/swarm/handler.go
+++ b/backend/internal/swarm/handler.go
@@ -350,63 +350,777 @@ func RegisterSwarm(api huma.API, swarmSvc *SwarmService, environmentSvc *environ
cfg: cfg,
}
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/services", Summary: "List swarm services", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListServices)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-service", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Get swarm service", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetService)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "create-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services", Summary: "Create swarm service", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmServices, h.CreateService)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-swarm-service", Method: http.MethodPut, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Update swarm service", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmServices, h.UpdateService)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-service", Method: http.MethodDelete, Path: "/environments/{id}/swarm/services/{serviceId}", Summary: "Delete swarm service", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmServices, h.DeleteService)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-service-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/services/{serviceId}/tasks", Summary: "List tasks for a swarm service", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListServiceTasks)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "rollback-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/rollback", Summary: "Rollback a swarm service", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmServices, h.RollbackService)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "scale-swarm-service", Method: http.MethodPost, Path: "/environments/{id}/swarm/services/{serviceId}/scale", Summary: "Scale a swarm service", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmServices, h.ScaleService)
-
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-nodes", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes", Summary: "List swarm nodes", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListNodes)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-node", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Get swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetNode)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-node-agent-deployment", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Get swarm node agent deployment snippets", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.GetNodeAgentDeployment)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "reconcile-swarm-node-agents", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/agents/reconcile", Summary: "Reconcile swarm node agent bindings", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.ReconcileNodeAgents)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "put-swarm-node-agent-binding", Method: http.MethodPut, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Attach a visible environment to a swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.PutNodeAgentBinding)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-binding", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding", Summary: "Detach a visible environment from a swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.DeleteNodeAgentBinding)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node-agent-deployment", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment", Summary: "Remove a dedicated swarm node agent registration", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.DeleteNodeAgentDeployment)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-swarm-node", Method: http.MethodPatch, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Update swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.UpdateNode)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-node", Method: http.MethodDelete, Path: "/environments/{id}/swarm/nodes/{nodeId}", Summary: "Delete swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.DeleteNode)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "promote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/promote", Summary: "Promote swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.PromoteNode)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "demote-swarm-node", Method: http.MethodPost, Path: "/environments/{id}/swarm/nodes/{nodeId}/demote", Summary: "Demote swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmNodes, h.DemoteNode)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-node-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/nodes/{nodeId}/tasks", Summary: "List tasks for a swarm node", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListNodeTasks)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-node-identity", Method: http.MethodGet, Path: "/swarm/node-identity", Summary: "Get local swarm node identity", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetNodeIdentity)
-
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/tasks", Summary: "List swarm tasks", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListTasks)
-
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-stacks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks", Summary: "List swarm stacks", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListStacks)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "deploy-swarm-stack", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks", Summary: "Deploy swarm stack", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmStacks, h.DeployStack)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-stack", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Get swarm stack", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetStack)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-stack-source", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/source", Summary: "Get swarm stack source", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmStacks, h.GetStackSource)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-swarm-stack-source", Method: http.MethodPut, Path: "/environments/{id}/swarm/stacks/{name}/source", Summary: "Update swarm stack source", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmStacks, h.UpdateStackSource)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-stack", Method: http.MethodDelete, Path: "/environments/{id}/swarm/stacks/{name}", Summary: "Delete swarm stack", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmStacks, h.DeleteStack)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-stack-services", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/services", Summary: "List swarm stack services", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListStackServices)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-stack-tasks", Method: http.MethodGet, Path: "/environments/{id}/swarm/stacks/{name}/tasks", Summary: "List swarm stack tasks", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListStackTasks)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "render-swarm-stack-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/stacks/config/render", Summary: "Render/validate swarm stack config", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.RenderStackConfig)
-
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-status", Method: http.MethodGet, Path: "/environments/{id}/swarm/status", Summary: "Get swarm status", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetSwarmStatus)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-info", Method: http.MethodGet, Path: "/environments/{id}/swarm/info", Summary: "Get swarm info", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetSwarmInfo)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "init-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/init", Summary: "Initialize swarm", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmInit, h.InitSwarm)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "join-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/join", Summary: "Join swarm", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmJoin, h.JoinSwarm)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-join-candidates", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-candidates", Summary: "List environments available for Easy Join", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmJoin, h.GetJoinCandidates)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "join-swarm-environments", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-environments", Summary: "Join environments to a swarm", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmJoin, h.JoinEnvironments)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "leave-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/leave", Summary: "Leave swarm", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmLeave, h.LeaveSwarm)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "unlock-swarm", Method: http.MethodPost, Path: "/environments/{id}/swarm/unlock", Summary: "Unlock swarm", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmUnlock, h.UnlockSwarm)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-unlock-key", Method: http.MethodGet, Path: "/environments/{id}/swarm/unlock-key", Summary: "Get swarm unlock key", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmUnlock, h.GetUnlockKey)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-join-tokens", Method: http.MethodGet, Path: "/environments/{id}/swarm/join-tokens", Summary: "Get swarm join tokens", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmUnlock, h.GetJoinTokens)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "rotate-swarm-join-tokens", Method: http.MethodPost, Path: "/environments/{id}/swarm/join-tokens/rotate", Summary: "Rotate swarm join tokens", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmUnlock, h.RotateJoinTokens)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-swarm-spec", Method: http.MethodPut, Path: "/environments/{id}/swarm/spec", Summary: "Update swarm spec", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmSpec, h.UpdateSwarmSpec)
-
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-configs", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs", Summary: "List swarm configs", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListConfigs)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-config", Method: http.MethodGet, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Get swarm config", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetConfig)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "create-swarm-config", Method: http.MethodPost, Path: "/environments/{id}/swarm/configs", Summary: "Create swarm config", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmConfigs, h.CreateConfig)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-config", Method: http.MethodDelete, Path: "/environments/{id}/swarm/configs/{configId}", Summary: "Delete swarm config", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmConfigs, h.DeleteConfig)
-
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-swarm-secrets", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets", Summary: "List swarm secrets", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.ListSecrets)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-swarm-secret", Method: http.MethodGet, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Get swarm secret", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmRead, h.GetSecret)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "create-swarm-secret", Method: http.MethodPost, Path: "/environments/{id}/swarm/secrets", Summary: "Create swarm secret", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmSecrets, h.CreateSecret)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-swarm-secret", Method: http.MethodDelete, Path: "/environments/{id}/swarm/secrets/{secretId}", Summary: "Delete swarm secret", Tags: []string{"Swarm"}, Security: handlerutil.DefaultOperationSecurity()}, authz.PermSwarmSecrets, h.DeleteSecret)
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-services",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/services",
+ Summary: "List swarm services",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListServices,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-service",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/services/{serviceId}",
+ Summary: "Get swarm service",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetService,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "create-swarm-service",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/services",
+ Summary: "Create swarm service",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmServices,
+ h.CreateService,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "update-swarm-service",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/swarm/services/{serviceId}",
+ Summary: "Update swarm service",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmServices,
+ h.UpdateService,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-swarm-service",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/swarm/services/{serviceId}",
+ Summary: "Delete swarm service",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmServices,
+ h.DeleteService,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-service-tasks",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/services/{serviceId}/tasks",
+ Summary: "List tasks for a swarm service",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListServiceTasks,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "rollback-swarm-service",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/services/{serviceId}/rollback",
+ Summary: "Rollback a swarm service",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmServices,
+ h.RollbackService,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "scale-swarm-service",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/services/{serviceId}/scale",
+ Summary: "Scale a swarm service",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmServices,
+ h.ScaleService,
+ )
+
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-nodes",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/nodes",
+ Summary: "List swarm nodes",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListNodes,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-node",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}",
+ Summary: "Get swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetNode,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-node-agent-deployment",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment",
+ Summary: "Get swarm node agent deployment snippets",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.GetNodeAgentDeployment,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "reconcile-swarm-node-agents",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/nodes/agents/reconcile",
+ Summary: "Reconcile swarm node agent bindings",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.ReconcileNodeAgents,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "put-swarm-node-agent-binding",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding",
+ Summary: "Attach a visible environment to a swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.PutNodeAgentBinding,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-swarm-node-agent-binding",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/binding",
+ Summary: "Detach a visible environment from a swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.DeleteNodeAgentBinding,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-swarm-node-agent-deployment",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}/agent/deployment",
+ Summary: "Remove a dedicated swarm node agent registration",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.DeleteNodeAgentDeployment,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "update-swarm-node",
+ Method: http.MethodPatch,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}",
+ Summary: "Update swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.UpdateNode,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-swarm-node",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}",
+ Summary: "Delete swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.DeleteNode,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "promote-swarm-node",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}/promote",
+ Summary: "Promote swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.PromoteNode,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "demote-swarm-node",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}/demote",
+ Summary: "Demote swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmNodes,
+ h.DemoteNode,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-node-tasks",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/nodes/{nodeId}/tasks",
+ Summary: "List tasks for a swarm node",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListNodeTasks,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-node-identity",
+ Method: http.MethodGet,
+ Path: "/swarm/node-identity",
+ Summary: "Get local swarm node identity",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetNodeIdentity,
+ )
+
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-tasks",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/tasks",
+ Summary: "List swarm tasks",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListTasks,
+ )
+
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-stacks",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/stacks",
+ Summary: "List swarm stacks",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListStacks,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "deploy-swarm-stack",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/stacks",
+ Summary: "Deploy swarm stack",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmStacks,
+ h.DeployStack,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-stack",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/stacks/{name}",
+ Summary: "Get swarm stack",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetStack,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-stack-source",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/stacks/{name}/source",
+ Summary: "Get swarm stack source",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmStacks,
+ h.GetStackSource,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "update-swarm-stack-source",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/swarm/stacks/{name}/source",
+ Summary: "Update swarm stack source",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmStacks,
+ h.UpdateStackSource,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-swarm-stack",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/swarm/stacks/{name}",
+ Summary: "Delete swarm stack",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmStacks,
+ h.DeleteStack,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-stack-services",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/stacks/{name}/services",
+ Summary: "List swarm stack services",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListStackServices,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-stack-tasks",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/stacks/{name}/tasks",
+ Summary: "List swarm stack tasks",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListStackTasks,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "render-swarm-stack-config",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/stacks/config/render",
+ Summary: "Render/validate swarm stack config",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.RenderStackConfig,
+ )
+
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-status",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/status",
+ Summary: "Get swarm status",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetSwarmStatus,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-info",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/info",
+ Summary: "Get swarm info",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetSwarmInfo,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "init-swarm",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/init",
+ Summary: "Initialize swarm",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmInit,
+ h.InitSwarm,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "join-swarm",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/join",
+ Summary: "Join swarm",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmJoin,
+ h.JoinSwarm,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-join-candidates",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/join-candidates",
+ Summary: "List environments available for Easy Join",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmJoin,
+ h.GetJoinCandidates,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "join-swarm-environments",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/join-environments",
+ Summary: "Join environments to a swarm",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmJoin,
+ h.JoinEnvironments,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "leave-swarm",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/leave",
+ Summary: "Leave swarm",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmLeave,
+ h.LeaveSwarm,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "unlock-swarm",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/unlock",
+ Summary: "Unlock swarm",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmUnlock,
+ h.UnlockSwarm,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-unlock-key",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/unlock-key",
+ Summary: "Get swarm unlock key",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmUnlock,
+ h.GetUnlockKey,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-join-tokens",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/join-tokens",
+ Summary: "Get swarm join tokens",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmUnlock,
+ h.GetJoinTokens,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "rotate-swarm-join-tokens",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/join-tokens/rotate",
+ Summary: "Rotate swarm join tokens",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmUnlock,
+ h.RotateJoinTokens,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "update-swarm-spec",
+ Method: http.MethodPut,
+ Path: "/environments/{id}/swarm/spec",
+ Summary: "Update swarm spec",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmSpec,
+ h.UpdateSwarmSpec,
+ )
+
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-configs",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/configs",
+ Summary: "List swarm configs",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListConfigs,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-config",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/configs/{configId}",
+ Summary: "Get swarm config",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetConfig,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "create-swarm-config",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/configs",
+ Summary: "Create swarm config",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmConfigs,
+ h.CreateConfig,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-swarm-config",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/swarm/configs/{configId}",
+ Summary: "Delete swarm config",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmConfigs,
+ h.DeleteConfig,
+ )
+
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-swarm-secrets",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/secrets",
+ Summary: "List swarm secrets",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.ListSecrets,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-swarm-secret",
+ Method: http.MethodGet,
+ Path: "/environments/{id}/swarm/secrets/{secretId}",
+ Summary: "Get swarm secret",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmRead,
+ h.GetSecret,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "create-swarm-secret",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/swarm/secrets",
+ Summary: "Create swarm secret",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmSecrets,
+ h.CreateSecret,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-swarm-secret",
+ Method: http.MethodDelete,
+ Path: "/environments/{id}/swarm/secrets/{secretId}",
+ Summary: "Delete swarm secret",
+ Tags: []string{
+ "Swarm",
+ },
+ Security: handlerutil.DefaultOperationSecurity(),
+ },
+ authz.PermSwarmSecrets,
+ h.DeleteSecret,
+ )
}
// ListServices lists swarm services for an environment and returns a paginated response.
@@ -736,8 +1450,14 @@ func (h *SwarmHandler) PutNodeAgentBinding(ctx context.Context, input *PutSwarmN
if err != nil {
return nil, err
}
- if err := h.environmentService.DeleteSwarmNodeAgentDeployment(ctx, input.EnvironmentID, input.NodeID, &user.ID, &user.Username); err != nil {
- return nil, huma.Error500InternalServerError(err.Error())
+ if deleteSwarmNodeAgentDeploymentErr := h.environmentService.DeleteSwarmNodeAgentDeployment(
+ ctx,
+ input.EnvironmentID,
+ input.NodeID,
+ &user.ID,
+ &user.Username,
+ ); deleteSwarmNodeAgentDeploymentErr != nil {
+ return nil, huma.Error500InternalServerError(deleteSwarmNodeAgentDeploymentErr.Error())
}
}
@@ -762,8 +1482,14 @@ func (h *SwarmHandler) DeleteNodeAgentDeployment(ctx context.Context, input *Del
if err != nil {
return nil, err
}
- if err := h.environmentService.DeleteSwarmNodeAgentDeployment(ctx, input.EnvironmentID, input.NodeID, &user.ID, &user.Username); err != nil {
- return nil, huma.Error500InternalServerError(err.Error())
+ if deleteSwarmNodeAgentDeploymentErr := h.environmentService.DeleteSwarmNodeAgentDeployment(
+ ctx,
+ input.EnvironmentID,
+ input.NodeID,
+ &user.ID,
+ &user.Username,
+ ); deleteSwarmNodeAgentDeploymentErr != nil {
+ return nil, huma.Error500InternalServerError(deleteSwarmNodeAgentDeploymentErr.Error())
}
return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Dedicated swarm node agent registration removed"}}}, nil
}
@@ -1369,7 +2095,18 @@ func (h *SwarmHandler) RotateJoinTokens(ctx context.Context, input *RotateSwarmJ
return nil, mapSwarmServiceErrorInternal(err, "Failed to rotate swarm join tokens")
}
- h.auditSwarmMutation(ctx, input.EnvironmentID, "lifecycle.rotate_tokens", "swarm", "cluster", "cluster", map[string]any{"rotateWorker": input.Body.RotateWorkerToken, "rotateManager": input.Body.RotateManagerToken})
+ h.auditSwarmMutation(
+ ctx,
+ input.EnvironmentID,
+ "lifecycle.rotate_tokens",
+ "swarm",
+ "cluster",
+ "cluster",
+ map[string]any{
+ "rotateWorker": input.Body.RotateWorkerToken,
+ "rotateManager": input.Body.RotateManagerToken,
+ },
+ )
return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: "Swarm join tokens rotated successfully"}}}, nil
}
diff --git a/backend/internal/swarm/service_test.go b/backend/internal/swarm/service_test.go
index eaa5c9c28..3b4cc08b6 100644
--- a/backend/internal/swarm/service_test.go
+++ b/backend/internal/swarm/service_test.go
@@ -40,7 +40,7 @@ func newSettingsServiceForSwarmTestInternal(t testing.TB, ctx context.Context, d
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -116,7 +116,14 @@ func TestDescribeSwarmJoinFailureInternal(t *testing.T) {
require.Equal(t,
"failed to join swarm: Timeout was reached before node joined using [redacted]",
- describeSwarmJoinFailureInternal(statusErr(500, `{"title":"Internal Server Error","status":500,"detail":"failed to join swarm: Timeout was reached before node joined using `+token+`"}`), token),
+ describeSwarmJoinFailureInternal(
+ statusErr(
+ 500,
+ "{\"title\":\"Internal Server Error\",\"status\":500,\"detail\":\"failed to join swarm: Timeout was reached be"+
+ "fore node joined using "+token+`"}`,
+ ),
+ token,
+ ),
)
require.Equal(t, "legacy join failure", describeSwarmJoinFailureInternal(statusErr(400, `{"success":false,"error":"legacy join failure"}`), token))
require.Equal(t, "swarm join failed with HTTP 502 from the target agent", describeSwarmJoinFailureInternal(statusErr(502, "<html>bad gateway</html>"), token))
@@ -129,7 +136,7 @@ func TestDescribeSwarmJoinFailureInternal(t *testing.T) {
}
func TestSwarmService_FetchSwarmNodeIdentityViaEdgeInternal_UsesEnvironmentAccessToken(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSwarmServiceTestDBInternal(t)
settingsSvc, err := newSettingsServiceForSwarmTestInternal(t, ctx, db)
require.NoError(t, err)
@@ -196,7 +203,7 @@ func stubStackSourceUpdateDeployInternal(t *testing.T) *stackSourceDeployRecorde
}
func TestSwarmService_UpdateAndGetStackSource_UsesStoredFilesWithoutSwarmManager(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSwarmServiceTestDBInternal(t)
rootDir := t.TempDir()
t.Setenv("SWARM_STACK_SOURCES_DIRECTORY", rootDir)
@@ -260,7 +267,7 @@ func TestSwarmService_UpdateAndGetStackSource_UsesStoredFilesWithoutSwarmManager
}
func TestSwarmService_UpdateAndGetStackSource_RoundTripsOverride(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSwarmServiceTestDBInternal(t)
rootDir := t.TempDir()
t.Setenv("SWARM_STACK_SOURCES_DIRECTORY", rootDir)
@@ -300,7 +307,7 @@ func TestSwarmService_UpdateAndGetStackSource_RoundTripsOverride(t *testing.T) {
}
func TestSwarmService_UpdateStackSource_PrunesAndRestoresOnDeployFailure(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupSwarmServiceTestDBInternal(t)
rootDir := t.TempDir()
t.Setenv("SWARM_STACK_SOURCES_DIRECTORY", rootDir)
@@ -344,7 +351,7 @@ func TestSwarmService_UpdateStackSource_PrunesAndRestoresOnDeployFailure(t *test
}
func TestSwarmService_ScaleService_HandlesServiceModesInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
replicas := uint64(5)
maxConcurrent := uint64(2)
diff --git a/backend/internal/swarm/swarm.go b/backend/internal/swarm/swarm.go
index 28aecc59a..926d2fba0 100644
--- a/backend/internal/swarm/swarm.go
+++ b/backend/internal/swarm/swarm.go
@@ -297,8 +297,8 @@ func (s *SwarmService) enrichServiceNetworkDetailsInternal(
}
if detail.ConfigFrom != "" {
- configInspectResult, err := dockerClient.NetworkInspect(ctx, detail.ConfigFrom, dockerclient.NetworkInspectOptions{})
- if err == nil {
+ configInspectResult, networkInspectErr := dockerClient.NetworkInspect(ctx, detail.ConfigFrom, dockerclient.NetworkInspectOptions{})
+ if networkInspectErr == nil {
configNetwork := configInspectResult.Network
configDetail := &swarmtypes.ServiceNetworkConfigDetail{
Name: configNetwork.Name,
@@ -370,8 +370,8 @@ func (s *SwarmService) CreateService(ctx context.Context, req swarmtypes.Service
// Unmarshal spec from JSON
var spec swarm.ServiceSpec
- if err := json.Unmarshal(req.Spec, &spec); err != nil {
- return nil, fmt.Errorf("failed to parse service spec: %w", err)
+ if unmarshalErr := json.Unmarshal(req.Spec, &spec); unmarshalErr != nil {
+ return nil, fmt.Errorf("failed to parse service spec: %w", unmarshalErr)
}
optionsPayload := swarmtypes.ServiceCreateOptions{}
@@ -409,9 +409,9 @@ func (s *SwarmService) UpdateService(ctx context.Context, serviceID string, req
versionIndex := req.Version
if versionIndex == 0 {
- serviceResult, err := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})
- if err != nil {
- return nil, fmt.Errorf("failed to inspect swarm service: %w", err)
+ serviceResult, serviceInspectErr := dockerClient.ServiceInspect(ctx, serviceID, dockerclient.ServiceInspectOptions{})
+ if serviceInspectErr != nil {
+ return nil, fmt.Errorf("failed to inspect swarm service: %w", serviceInspectErr)
}
versionIndex = serviceResult.Service.Version.Index
}
@@ -451,8 +451,8 @@ func (s *SwarmService) RemoveService(ctx context.Context, serviceID string) erro
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.ServiceRemove(ctx, serviceID, dockerclient.ServiceRemoveOptions{}); err != nil {
- return fmt.Errorf("failed to remove swarm service: %w", err)
+ if _, serviceRemoveErr := dockerClient.ServiceRemove(ctx, serviceID, dockerclient.ServiceRemoveOptions{}); serviceRemoveErr != nil {
+ return fmt.Errorf("failed to remove swarm service: %w", serviceRemoveErr)
}
return nil
@@ -616,15 +616,15 @@ func (s *SwarmService) ReconcileNodeAgents(ctx context.Context, environmentID st
// BindNodeAgent verifies that a visible environment currently reports the
// requested node identity before persisting the binding.
func (s *SwarmService) BindNodeAgent(ctx context.Context, parentEnvironmentID, nodeID string, request swarmtypes.NodeAgentBindingRequest) (*environment.Environment, error) {
- environment, err := s.environmentService.GetEnvironmentByID(ctx, request.EnvironmentID)
+ localEnvironment, err := s.environmentService.GetEnvironmentByID(ctx, request.EnvironmentID)
if err != nil {
return nil, err
}
- if environment.Hidden {
+ if localEnvironment.Hidden {
return nil, errors.New("only visible environments can be attached")
}
- runtime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, environment)
+ runtime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, localEnvironment)
if runtime.identity == nil || !runtime.identity.SwarmActive {
return nil, errors.New("environment did not report an active swarm identity")
}
@@ -718,8 +718,8 @@ func (s *SwarmService) resolveNodeAgentCoverageInternal(ctx context.Context, env
return nil
})
}
- if err := g.Wait(); err != nil {
- return nil, err
+ if waitErr := g.Wait(); waitErr != nil {
+ return nil, waitErr
}
boundEnvsByNodeID := make(map[string][]environment.Environment, len(agentEnvs))
@@ -780,8 +780,8 @@ func (s *SwarmService) applyNodeAgentCoverageInternal(environmentID string, item
boundEnvs := coverage.boundEnvsByNodeID[nodeID]
if len(boundEnvs) > 0 {
- environment := preferredNodeAgentEnvironmentInternal(boundEnvs)
- item.Agent = s.buildNodeAgentStatusInternal(nodeID, &environment, coverage.runtimeByEnvID[environment.ID])
+ localEnvironment := preferredNodeAgentEnvironmentInternal(boundEnvs)
+ item.Agent = s.buildNodeAgentStatusInternal(nodeID, &localEnvironment, coverage.runtimeByEnvID[localEnvironment.ID])
return
}
@@ -1011,8 +1011,8 @@ func (s *SwarmService) joinEnvironmentInternal(
memberNodeIDs map[string]struct{},
) swarmtypes.SwarmJoinEnvironmentResult {
result := swarmtypes.SwarmJoinEnvironmentResult{EnvironmentID: target.EnvironmentID, State: swarmtypes.SwarmJoinEnvironmentResultFailed}
- environment, err := s.environmentService.GetEnvironmentByID(ctx, target.EnvironmentID)
- if err != nil || environment.Hidden || !environment.Enabled {
+ localEnvironment, err := s.environmentService.GetEnvironmentByID(ctx, target.EnvironmentID)
+ if err != nil || localEnvironment.Hidden || !localEnvironment.Enabled {
message := "target environment is unavailable"
if err != nil {
message = err.Error()
@@ -1021,7 +1021,7 @@ func (s *SwarmService) joinEnvironmentInternal(
return result
}
- runtime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, environment)
+ runtime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, localEnvironment)
if runtime.identity != nil && runtime.identity.SwarmActive {
nodeID := strings.TrimSpace(runtime.identity.SwarmNodeID)
if _, member := memberNodeIDs[nodeID]; !member {
@@ -1029,8 +1029,8 @@ func (s *SwarmService) joinEnvironmentInternal(
result.Error = &message
return result
}
- if _, err := s.environmentService.BindSwarmNodeEnvironment(ctx, managerEnvironmentID, nodeID, target.EnvironmentID, true); err != nil {
- message := err.Error()
+ if _, bindSwarmNodeEnvironmentErr := s.environmentService.BindSwarmNodeEnvironment(ctx, managerEnvironmentID, nodeID, target.EnvironmentID, true); bindSwarmNodeEnvironmentErr != nil {
+ message := bindSwarmNodeEnvironmentErr.Error()
result.Error = &message
return result
}
@@ -1060,8 +1060,8 @@ func (s *SwarmService) joinEnvironmentInternal(
var joinResponse struct {
Success bool `json:"success"`
}
- if err := s.environmentService.ProxyJSONRequest(ctx, target.EnvironmentID, http.MethodPost, "/api/environments/0/swarm/join", body, &joinResponse); err != nil {
- message := describeSwarmJoinFailureInternal(err, joinToken)
+ if proxyJSONRequestErr := s.environmentService.ProxyJSONRequest(ctx, target.EnvironmentID, http.MethodPost, "/api/environments/0/swarm/join", body, &joinResponse); proxyJSONRequestErr != nil {
+ message := describeSwarmJoinFailureInternal(proxyJSONRequestErr, joinToken)
result.Error = &message
return result
}
@@ -1073,10 +1073,10 @@ func (s *SwarmService) joinEnvironmentInternal(
for range 6 {
s.invalidateSwarmNodeIdentityInternal(target.EnvironmentID)
- verifiedRuntime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, environment)
+ verifiedRuntime := s.resolveSwarmNodeAgentRuntimeInternal(ctx, localEnvironment)
if verifiedRuntime.identity != nil && verifiedRuntime.identity.SwarmActive {
nodeID := strings.TrimSpace(verifiedRuntime.identity.SwarmNodeID)
- if _, err := s.GetNode(ctx, managerEnvironmentID, nodeID); err == nil {
+ if _, getNodeErr := s.GetNode(ctx, managerEnvironmentID, nodeID); getNodeErr == nil {
if _, bindErr := s.environmentService.BindSwarmNodeEnvironment(ctx, managerEnvironmentID, nodeID, target.EnvironmentID, true); bindErr == nil {
result.State = swarmtypes.SwarmJoinEnvironmentResultJoined
result.NodeID = &nodeID
@@ -1321,8 +1321,8 @@ func (s *SwarmService) DeployStack(ctx context.Context, environmentID string, re
return nil, err
}
- if err := s.upsertStackSourceInternal(ctx, environmentID, stackName, req.ComposeContent, req.OverrideContent, req.EnvContent, req.Files); err != nil {
- slog.WarnContext(ctx, "failed to persist swarm stack source", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", err)
+ if upsertStackSourceErr := s.upsertStackSourceInternal(ctx, environmentID, stackName, req.ComposeContent, req.OverrideContent, req.EnvContent, req.Files); upsertStackSourceErr != nil {
+ slog.WarnContext(ctx, "failed to persist swarm stack source", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", upsertStackSourceErr)
}
workingDir := req.WorkingDir
@@ -1337,7 +1337,7 @@ func (s *SwarmService) DeployStack(ctx context.Context, environmentID string, re
dockerClient,
)
- if err := libswarm.DeployStack(ctx, dockerClient, libswarm.StackDeployOptions{
+ if deployStackErr := libswarm.DeployStack(ctx, dockerClient, libswarm.StackDeployOptions{
Name: stackName,
ComposeContent: req.ComposeContent,
OverrideContent: req.OverrideContent,
@@ -1353,8 +1353,8 @@ func (s *SwarmService) DeployStack(ctx context.Context, environmentID string, re
ResolveImage: req.ResolveImage,
WorkingDir: workingDir,
PathMapper: pm,
- }); err != nil {
- return nil, classifySwarmStackErrorInternal(err)
+ }); deployStackErr != nil {
+ return nil, classifySwarmStackErrorInternal(deployStackErr)
}
return &swarmtypes.StackDeployResponse{Name: stackName}, nil
@@ -1391,9 +1391,9 @@ func (s *SwarmService) InitSwarm(ctx context.Context, req swarmtypes.SwarmInitRe
defaultAddrPool := make([]netip.Prefix, 0, len(req.DefaultAddrPool))
for _, raw := range req.DefaultAddrPool {
- prefix, err := netip.ParsePrefix(raw)
- if err != nil {
- return nil, fmt.Errorf("failed to parse default address pool %q: %w", raw, err)
+ prefix, parsePrefixErr := netip.ParsePrefix(raw)
+ if parsePrefixErr != nil {
+ return nil, fmt.Errorf("failed to parse default address pool %q: %w", raw, parsePrefixErr)
}
defaultAddrPool = append(defaultAddrPool, prefix.Masked())
}
@@ -1425,15 +1425,15 @@ func (s *SwarmService) JoinSwarm(ctx context.Context, req swarmtypes.SwarmJoinRe
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.SwarmJoin(ctx, dockerclient.SwarmJoinOptions{
+ if _, swarmJoinErr := dockerClient.SwarmJoin(ctx, dockerclient.SwarmJoinOptions{
ListenAddr: defaultSwarmListenAddrInternal(req.ListenAddr),
AdvertiseAddr: req.AdvertiseAddr,
DataPathAddr: req.DataPathAddr,
RemoteAddrs: req.RemoteAddrs,
JoinToken: req.JoinToken,
Availability: req.Availability,
- }); err != nil {
- return fmt.Errorf("failed to join swarm: %w", err)
+ }); swarmJoinErr != nil {
+ return fmt.Errorf("failed to join swarm: %w", swarmJoinErr)
}
s.persistSwarmEnabledStateInternal(ctx, true)
@@ -1451,8 +1451,8 @@ func (s *SwarmService) LeaveSwarm(ctx context.Context, req swarmtypes.SwarmLeave
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.SwarmLeave(ctx, dockerclient.SwarmLeaveOptions{Force: req.Force}); err != nil {
- return fmt.Errorf("failed to leave swarm: %w", err)
+ if _, swarmLeaveErr := dockerClient.SwarmLeave(ctx, dockerclient.SwarmLeaveOptions{Force: req.Force}); swarmLeaveErr != nil {
+ return fmt.Errorf("failed to leave swarm: %w", swarmLeaveErr)
}
s.persistSwarmEnabledStateInternal(ctx, false)
@@ -1470,8 +1470,8 @@ func (s *SwarmService) UnlockSwarm(ctx context.Context, req swarmtypes.SwarmUnlo
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.SwarmUnlock(ctx, dockerclient.SwarmUnlockOptions{Key: req.Key}); err != nil {
- return fmt.Errorf("failed to unlock swarm: %w", err)
+ if _, swarmUnlockErr := dockerClient.SwarmUnlock(ctx, dockerclient.SwarmUnlockOptions{Key: req.Key}); swarmUnlockErr != nil {
+ return fmt.Errorf("failed to unlock swarm: %w", swarmUnlockErr)
}
return nil
@@ -1538,13 +1538,13 @@ func (s *SwarmService) RotateSwarmJoinTokens(ctx context.Context, req swarmtypes
rotateManager = true
}
- if _, err := dockerClient.SwarmUpdate(ctx, dockerclient.SwarmUpdateOptions{
+ if _, swarmUpdateErr := dockerClient.SwarmUpdate(ctx, dockerclient.SwarmUpdateOptions{
Version: infoResult.Swarm.Version,
Spec: infoResult.Swarm.Spec,
RotateWorkerToken: rotateWorker,
RotateManagerToken: rotateManager,
- }); err != nil {
- return fmt.Errorf("failed to rotate swarm join tokens: %w", err)
+ }); swarmUpdateErr != nil {
+ return fmt.Errorf("failed to rotate swarm join tokens: %w", swarmUpdateErr)
}
return nil
@@ -1562,9 +1562,9 @@ func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.Swarm
version := req.Version
if version == 0 {
- infoResult, err := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})
- if err != nil {
- return fmt.Errorf("failed to inspect swarm: %w", err)
+ infoResult, swarmInspectErr := dockerClient.SwarmInspect(ctx, dockerclient.SwarmInspectOptions{})
+ if swarmInspectErr != nil {
+ return fmt.Errorf("failed to inspect swarm: %w", swarmInspectErr)
}
version = infoResult.Swarm.Version.Index
}
@@ -1574,14 +1574,14 @@ func (s *SwarmService) UpdateSwarmSpec(ctx context.Context, req swarmtypes.Swarm
return err
}
- if _, err := dockerClient.SwarmUpdate(ctx, dockerclient.SwarmUpdateOptions{
+ if _, swarmUpdateErr := dockerClient.SwarmUpdate(ctx, dockerclient.SwarmUpdateOptions{
Version: swarm.Version{Index: version},
Spec: spec,
RotateWorkerToken: req.RotateWorkerToken,
RotateManagerToken: req.RotateManagerToken,
RotateManagerUnlockKey: req.RotateManagerUnlockKey,
- }); err != nil {
- return fmt.Errorf("failed to update swarm spec: %w", err)
+ }); swarmUpdateErr != nil {
+ return fmt.Errorf("failed to update swarm spec: %w", swarmUpdateErr)
}
return nil
@@ -1640,8 +1640,8 @@ func (s *SwarmService) ScaleService(ctx context.Context, serviceID string, repli
}
service := serviceResult.Service
- if err := applySwarmServiceScaleInternal(&service.Spec.Mode, replicas); err != nil {
- return nil, err
+ if applySwarmServiceScaleErr := applySwarmServiceScaleInternal(&service.Spec.Mode, replicas); applySwarmServiceScaleErr != nil {
+ return nil, applySwarmServiceScaleErr
}
updateResult, err := dockerClient.ServiceUpdate(ctx, serviceID, dockerclient.ServiceUpdateOptions{
@@ -1699,11 +1699,11 @@ func (s *SwarmService) UpdateNode(ctx context.Context, nodeID string, req swarmt
spec.Availability = *req.Availability
}
- if _, err := dockerClient.NodeUpdate(ctx, nodeID, dockerclient.NodeUpdateOptions{
+ if _, nodeUpdateErr := dockerClient.NodeUpdate(ctx, nodeID, dockerclient.NodeUpdateOptions{
Version: swarm.Version{Index: version},
Spec: spec,
- }); err != nil {
- return fmt.Errorf("failed to update swarm node: %w", err)
+ }); nodeUpdateErr != nil {
+ return fmt.Errorf("failed to update swarm node: %w", nodeUpdateErr)
}
return nil
@@ -1719,8 +1719,8 @@ func (s *SwarmService) RemoveNode(ctx context.Context, nodeID string, force bool
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.NodeRemove(ctx, nodeID, dockerclient.NodeRemoveOptions{Force: force}); err != nil {
- return fmt.Errorf("failed to remove swarm node: %w", err)
+ if _, nodeRemoveErr := dockerClient.NodeRemove(ctx, nodeID, dockerclient.NodeRemoveOptions{Force: force}); nodeRemoveErr != nil {
+ return fmt.Errorf("failed to remove swarm node: %w", nodeRemoveErr)
}
return nil
@@ -1759,9 +1759,9 @@ func (s *SwarmService) GetStack(ctx context.Context, environmentID, stackName st
return nil, err
}
if len(services) == 0 {
- persisted, err := s.getPersistedStackSourceSummaryInternal(ctx, environmentID, stackName)
- if err != nil {
- return nil, kit.Ternary[error](cerrdefs.IsNotFound(err), cerrdefs.ErrNotFound, err)
+ persisted, getPersistedStackSourceSummaryErr := s.getPersistedStackSourceSummaryInternal(ctx, environmentID, stackName)
+ if getPersistedStackSourceSummaryErr != nil {
+ return nil, kit.Ternary[error](cerrdefs.IsNotFound(getPersistedStackSourceSummaryErr), cerrdefs.ErrNotFound, getPersistedStackSourceSummaryErr)
}
return &swarmtypes.StackInspect{
@@ -1837,9 +1837,9 @@ func (s *SwarmService) GetStackSource(ctx context.Context, environmentID, stackN
if relativePath == swarmStackComposeFilename || relativePath == swarmStackOverrideFilename || relativePath == swarmStackEnvFilename {
return nil
}
- content, err := acfs.ReadFile(ctx, stackSourceDir, entry.Path)
- if err != nil {
- return err
+ content, readFileErr := acfs.ReadFile(ctx, stackSourceDir, entry.Path)
+ if readFileErr != nil {
+ return readFileErr
}
files = append(files, swarmtypes.SyncFile{
RelativePath: relativePath,
@@ -1876,8 +1876,8 @@ func (s *SwarmService) UpdateStackSource(ctx context.Context, environmentID, sta
return nil, err
}
- if err := s.upsertStackSourceInternal(ctx, environmentID, stackName, req.ComposeContent, req.OverrideContent, req.EnvContent, req.Files); err != nil {
- return nil, err
+ if upsertStackSourceErr := s.upsertStackSourceInternal(ctx, environmentID, stackName, req.ComposeContent, req.OverrideContent, req.EnvContent, req.Files); upsertStackSourceErr != nil {
+ return nil, upsertStackSourceErr
}
// Saving an edited stack must behave like `docker stack deploy` (#3463):
@@ -1888,7 +1888,7 @@ func (s *SwarmService) UpdateStackSource(ctx context.Context, environmentID, sta
// resolution is per image and yields nothing unless a configured container
// registry matches the image host. Without it, a service added in the edit
// has no previous spec to fall back on and private images fail to pull.
- if _, err := deployStackAfterSourceUpdateInternal(s, ctx, environmentID, swarmtypes.StackDeployRequest{
+ if _, deployStackAfterSourceUpdateErr := deployStackAfterSourceUpdateInternal(s, ctx, environmentID, swarmtypes.StackDeployRequest{
Name: stackName,
ComposeContent: req.ComposeContent,
OverrideContent: req.OverrideContent,
@@ -1896,7 +1896,7 @@ func (s *SwarmService) UpdateStackSource(ctx context.Context, environmentID, sta
Files: req.Files,
Prune: true,
WithRegistryAuth: true,
- }); err != nil {
+ }); deployStackAfterSourceUpdateErr != nil {
// Roll back the persisted source so reads never return an edit that
// was never successfully deployed.
var restoreErr error
@@ -1908,7 +1908,7 @@ func (s *SwarmService) UpdateStackSource(ctx context.Context, environmentID, sta
if restoreErr != nil {
slog.WarnContext(ctx, "failed to restore swarm stack source after deploy failure", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", restoreErr)
}
- return nil, fmt.Errorf("failed to redeploy swarm stack from updated source: %w", err)
+ return nil, fmt.Errorf("failed to redeploy swarm stack from updated source: %w", deployStackAfterSourceUpdateErr)
}
return &swarmtypes.StackSource{
@@ -1940,12 +1940,12 @@ func (s *SwarmService) listPersistedStackSourcesInternal(ctx context.Context, en
continue
}
- summary, err := s.buildPersistedStackSourceSummaryInternal(ctx, filepath.Join(environmentDir, entry.Name), entry.Name)
- if err != nil {
- if cerrdefs.IsNotFound(err) {
+ summary, buildPersistedStackSourceSummaryErr := s.buildPersistedStackSourceSummaryInternal(ctx, filepath.Join(environmentDir, entry.Name), entry.Name)
+ if buildPersistedStackSourceSummaryErr != nil {
+ if cerrdefs.IsNotFound(buildPersistedStackSourceSummaryErr) {
continue
}
- return nil, err
+ return nil, buildPersistedStackSourceSummaryErr
}
stacks[summary.Name] = *summary
@@ -2017,21 +2017,21 @@ func (s *SwarmService) RemoveStack(ctx context.Context, environmentID, stackName
return err
}
if len(services) == 0 {
- if _, err := s.getPersistedStackSourceSummaryInternal(ctx, environmentID, stackName); err != nil {
- return kit.Ternary[error](cerrdefs.IsNotFound(err), cerrdefs.ErrNotFound, err)
+ if _, getPersistedStackSourceSummaryErr := s.getPersistedStackSourceSummaryInternal(ctx, environmentID, stackName); getPersistedStackSourceSummaryErr != nil {
+ return kit.Ternary[error](cerrdefs.IsNotFound(getPersistedStackSourceSummaryErr), cerrdefs.ErrNotFound, getPersistedStackSourceSummaryErr)
}
} else {
- if err := s.removeStackServicesInternal(ctx, dockerClient, services); err != nil {
- return err
+ if removeStackServicesErr := s.removeStackServicesInternal(ctx, dockerClient, services); removeStackServicesErr != nil {
+ return removeStackServicesErr
}
}
- if err := libswarm.RemoveStackResources(ctx, dockerClient, stackName); err != nil {
- return classifySwarmStackErrorInternal(err)
+ if removeStackResourcesErr := libswarm.RemoveStackResources(ctx, dockerClient, stackName); removeStackResourcesErr != nil {
+ return classifySwarmStackErrorInternal(removeStackResourcesErr)
}
- if err := s.deleteStackSourceInternal(ctx, environmentID, stackName); err != nil {
- slog.WarnContext(ctx, "failed to remove persisted swarm stack source", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", err)
+ if deleteStackSourceErr := s.deleteStackSourceInternal(ctx, environmentID, stackName); deleteStackSourceErr != nil {
+ slog.WarnContext(ctx, "failed to remove persisted swarm stack source", "environmentID", normalizeSwarmEnvironmentIDInternal(environmentID), "stackName", stackName, "error", deleteStackSourceErr)
}
return nil
@@ -2231,8 +2231,8 @@ func (s *SwarmService) RemoveConfig(ctx context.Context, configID string) error
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.ConfigRemove(ctx, configID, dockerclient.ConfigRemoveOptions{}); err != nil {
- return fmt.Errorf("failed to remove swarm config: %w", err)
+ if _, configRemoveErr := dockerClient.ConfigRemove(ctx, configID, dockerclient.ConfigRemoveOptions{}); configRemoveErr != nil {
+ return fmt.Errorf("failed to remove swarm config: %w", configRemoveErr)
}
return nil
@@ -2311,8 +2311,8 @@ func (s *SwarmService) RemoveSecret(ctx context.Context, secretID string) error
return fmt.Errorf("failed to connect to Docker: %w", err)
}
- if _, err := dockerClient.SecretRemove(ctx, secretID, dockerclient.SecretRemoveOptions{}); err != nil {
- return fmt.Errorf("failed to remove swarm secret: %w", err)
+ if _, secretRemoveErr := dockerClient.SecretRemove(ctx, secretID, dockerclient.SecretRemoveOptions{}); secretRemoveErr != nil {
+ return fmt.Errorf("failed to remove swarm secret: %w", secretRemoveErr)
}
return nil
@@ -2581,8 +2581,8 @@ func (s *SwarmService) upsertStackSourceInternal(ctx context.Context, environmen
if err != nil {
return fmt.Errorf("swarm stack source directory is outside its root: %w", err)
}
- if err := acfs.MkdirAll(ctx, rootDir, stackLogical, utils.DirPerm); err != nil {
- return fmt.Errorf("failed to create swarm stack source directory: %w", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, rootDir, stackLogical, utils.DirPerm); mkdirAllErr != nil {
+ return fmt.Errorf("failed to create swarm stack source directory: %w", mkdirAllErr)
}
syncFiles := make([]appfs.SyncFile, 0, len(files)+3)
@@ -2615,22 +2615,22 @@ func (s *SwarmService) upsertStackSourceInternal(ctx context.Context, environmen
}
existingFiles := make([]string, 0)
- if err := acfs.Walk(ctx, stackSourceDir, "/", func(entry acfstypes.Entry) error {
+ if walkErr := acfs.Walk(ctx, stackSourceDir, "/", func(entry acfstypes.Entry) error {
if entry.IsDirectory || entry.IsSymlink {
return nil
}
existingFiles = append(existingFiles, strings.TrimPrefix(entry.Path, "/"))
return nil
- }); err != nil {
- return fmt.Errorf("failed to inspect existing swarm stack files: %w", err)
+ }); walkErr != nil {
+ return fmt.Errorf("failed to inspect existing swarm stack files: %w", walkErr)
}
writtenFiles, err := appfs.WriteSyncedDirectory(ctx, rootDir, stackSourceDir, syncFiles)
if err != nil {
return fmt.Errorf("failed to write swarm stack files: %w", err)
}
- if err := appfs.CleanupRemovedFiles(ctx, rootDir, stackSourceDir, existingFiles, writtenFiles); err != nil {
- return fmt.Errorf("failed to remove stale swarm stack files: %w", err)
+ if cleanupRemovedFilesErr := appfs.CleanupRemovedFiles(ctx, rootDir, stackSourceDir, existingFiles, writtenFiles); cleanupRemovedFilesErr != nil {
+ return fmt.Errorf("failed to remove stale swarm stack files: %w", cleanupRemovedFilesErr)
}
return nil
@@ -2650,15 +2650,15 @@ func (s *SwarmService) deleteStackSourceInternal(ctx context.Context, environmen
if err != nil {
return fmt.Errorf("swarm stack source directory is outside its root: %w", err)
}
- if err := acfs.RemoveAll(ctx, rootDir, stackLogical); err != nil {
- return fmt.Errorf("failed to remove swarm stack source directory: %w", err)
+ if removeAllErr := acfs.RemoveAll(ctx, rootDir, stackLogical); removeAllErr != nil {
+ return fmt.Errorf("failed to remove swarm stack source directory: %w", removeAllErr)
}
// Best-effort cleanup of now-empty environment directory.
environmentDir := filepath.Dir(stackSourceDir)
if environmentDir != rootDir {
- if err := acfs.Remove(ctx, rootDir, path.Dir(stackLogical)); err != nil && !errors.Is(err, fs.ErrNotExist) {
- slog.DebugContext(ctx, "swarm stack source environment directory cleanup skipped", "dir", environmentDir, "error", err)
+ if removeErr := acfs.Remove(ctx, rootDir, path.Dir(stackLogical)); removeErr != nil && !errors.Is(removeErr, fs.ErrNotExist) {
+ slog.DebugContext(ctx, "swarm stack source environment directory cleanup skipped", "dir", environmentDir, "error", removeErr)
}
}
@@ -2763,8 +2763,8 @@ func (s *SwarmService) SyncSwarmEnabledState(ctx context.Context) error {
return nil
}
- if err := s.kvService.SetBool(ctx, KVKeySwarmEnabled, enabled); err != nil {
- return fmt.Errorf("persist swarm enabled state: %w", err)
+ if setBoolErr := s.kvService.SetBool(ctx, KVKeySwarmEnabled, enabled); setBoolErr != nil {
+ return fmt.Errorf("persist swarm enabled state: %w", setBoolErr)
}
return nil
@@ -2800,8 +2800,8 @@ func (s *SwarmService) buildServicePaginationConfigInternal() pagination.Config[
{Key: "image", Fn: func(a, b swarmtypes.ServiceSummary) int { return strings.Compare(a.Image, b.Image) }},
{Key: "mode", Fn: func(a, b swarmtypes.ServiceSummary) int { return strings.Compare(a.Mode, b.Mode) }},
{Key: "replicas", Fn: func(a, b swarmtypes.ServiceSummary) int {
- if cmp := compareUint64Internal(a.Replicas, b.Replicas); cmp != 0 {
- return cmp
+ if localCmp := compareUint64Internal(a.Replicas, b.Replicas); localCmp != 0 {
+ return localCmp
}
return compareUint64Internal(a.RunningReplicas, b.RunningReplicas)
}},
diff --git a/backend/internal/system/handler.go b/backend/internal/system/handler.go
index 5d8e8103f..a6055b29a 100644
--- a/backend/internal/system/handler.go
+++ b/backend/internal/system/handler.go
@@ -124,7 +124,16 @@ type UpdateAllStatusInput struct {
// RegisterSystem registers system management endpoints using Huma.
// WebSocket statistics endpoints live in api/ws.
-func RegisterSystem(api huma.API, dockerService *docker.DockerClientService, systemService *SystemService, upgradeService *SystemUpgradeService, environmentService *environment.EnvironmentService, cfg *config.Config, activityService *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
+func RegisterSystem(
+ api huma.API,
+ dockerService *docker.DockerClientService,
+ systemService *SystemService,
+ upgradeService *SystemUpgradeService,
+ environmentService *environment.EnvironmentService,
+ cfg *config.Config,
+ activityService *activity.ActivityService,
+ appCtx handlerutil.ActivityAppContext,
+) {
h := &SystemHandler{
dockerService: dockerService,
systemService: systemService,
@@ -301,7 +310,7 @@ func (h *SystemHandler) GetDockerInfo(ctx context.Context, input *GetDockerInfoI
// LXC guest has a smaller cgroup budget — apply those limits so the
// dashboard shows what Arcane's host actually has available.
if !cgroup.IsDockerContainer() {
- if cgroupLimits, err := cgroup.DetectLimits(); err == nil {
+ if cgroupLimits, detectLimitsErr := cgroup.DetectLimits(); detectLimitsErr == nil {
if limit := cgroupLimits.MemoryLimit; limit > 0 {
limitInt := limit
if memTotal == 0 || limitInt < memTotal {
diff --git a/backend/internal/system/module.go b/backend/internal/system/module.go
index d94738705..119bb44b5 100644
--- a/backend/internal/system/module.go
+++ b/backend/internal/system/module.go
@@ -23,7 +23,14 @@ type Module struct {
}
// New wires system routes around an existing service.
-func New(service *SystemService, dockerService *docker.DockerClientService, upgradeService *SystemUpgradeService, environmentService *environment.EnvironmentService, cfg *config.Config, activityService *activity.ActivityService) *Module {
+func New(
+ service *SystemService,
+ dockerService *docker.DockerClientService,
+ upgradeService *SystemUpgradeService,
+ environmentService *environment.EnvironmentService,
+ cfg *config.Config,
+ activityService *activity.ActivityService,
+) *Module {
return &Module{service: service, dockerService: dockerService, upgradeService: upgradeService, environmentService: environmentService, cfg: cfg, activityService: activityService}
}
diff --git a/backend/internal/system/prune_recovery.go b/backend/internal/system/prune_recovery.go
index 74e094c3b..f36768b8b 100644
--- a/backend/internal/system/prune_recovery.go
+++ b/backend/internal/system/prune_recovery.go
@@ -59,8 +59,17 @@ func (s *SystemService) PruneScheduled(ctx context.Context, environmentID string
if err != nil {
return fail(err)
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "prune_plan", ID: "prune-plan", Status: schedulertypes.Succeeded, RecoveryData: payload, ActivityID: prune.activityID}); err != nil {
- return fail(err)
+ if progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "prune_plan",
+ ID: "prune-plan",
+ Status: schedulertypes.Succeeded,
+ RecoveryData: payload,
+ ActivityID: prune.activityID,
+ },
+ ); progressErr != nil {
+ return fail(progressErr)
}
previous, _ := jobcontext.Run(ctx)
err = s.executePrunePlanInternal(ctx, plan, previous, result, false)
@@ -84,19 +93,19 @@ func (s *SystemService) preparePrunePlanInternal(ctx context.Context, req system
if err != nil {
return plan, err
}
- if err := s.selectPruneContainersInternal(&plan, usage); err != nil {
- return plan, err
+ if selectPruneContainersErr := s.selectPruneContainersInternal(&plan, usage); selectPruneContainersErr != nil {
+ return plan, selectPruneContainersErr
}
selectedContainers, imageRefs, volumeRefs := pruneSelectedReferencesInternal(plan.Resources, usage)
- if err := s.selectPruneImagesInternal(&plan, usage, imageRefs); err != nil {
- return plan, err
+ if selectPruneImagesErr := s.selectPruneImagesInternal(&plan, usage, imageRefs); selectPruneImagesErr != nil {
+ return plan, selectPruneImagesErr
}
selectPruneVolumesInternal(&plan, usage, volumeRefs)
- if err := s.selectPruneNetworksInternal(ctx, dockerClient, &plan, selectedContainers); err != nil {
- return plan, err
+ if selectPruneNetworksErr := s.selectPruneNetworksInternal(ctx, dockerClient, &plan, selectedContainers); selectPruneNetworksErr != nil {
+ return plan, selectPruneNetworksErr
}
- if err := s.selectPruneBuildCacheInternal(&plan, usage); err != nil {
- return plan, err
+ if selectPruneBuildCacheErr := s.selectPruneBuildCacheInternal(&plan, usage); selectPruneBuildCacheErr != nil {
+ return plan, selectPruneBuildCacheErr
}
return plan, nil
}
@@ -137,7 +146,16 @@ func (s *SystemService) selectPruneImagesInternal(plan *prunePlanInternal, usage
}
}
for _, item := range usage.Images.Items {
- if item.Containers > int64(imageRefs[item.ID]) || (req.Images.Mode == systemtypes.PruneImageModeDangling && len(item.RepoTags) > 0) || (!until.IsZero() && !time.Unix(item.Created, 0).Before(until)) {
+ if item.Containers > int64(
+ imageRefs[item.ID],
+ ) || (req.Images.Mode == systemtypes.PruneImageModeDangling && len(
+ item.RepoTags,
+ ) > 0) || (!until.IsZero() && !time.Unix(
+ item.Created,
+ 0,
+ ).Before(
+ until,
+ )) {
continue
}
plan.Resources = append(plan.Resources, pruneResourceInternal{Kind: "image", ID: item.ID, Size: item.Size, Names: slices.Clone(item.RepoTags)})
@@ -183,9 +201,9 @@ func (s *SystemService) selectPruneNetworksInternal(ctx context.Context, dockerC
if item.Name == "bridge" || item.Name == "host" || item.Name == "none" || item.Ingress || item.Scope != "local" || (!until.IsZero() && !item.Created.Before(until)) {
continue
}
- inspect, err := compat.NetworkInspectWithCompatibility(ctx, dockerClient, item.ID, client.NetworkInspectOptions{})
- if err != nil {
- return err
+ inspect, networkInspectWithCompatibilityErr := compat.NetworkInspectWithCompatibility(ctx, dockerClient, item.ID, client.NetworkInspectOptions{})
+ if networkInspectWithCompatibilityErr != nil {
+ return networkInspectWithCompatibilityErr
}
eligible := true
for id := range inspect.Network.Containers {
@@ -282,12 +300,12 @@ func (s *SystemService) executePrunePlanInternal(ctx context.Context, plan prune
if pruneTargetCompletedInternal(previous, target.ID) {
continue
}
- if err := jobcontext.Progress(ctx, target); err != nil {
- return err
+ if progressErr := jobcontext.Progress(ctx, target); progressErr != nil {
+ return progressErr
}
- eligible, exists, err := s.pruneResourceEligibleInternal(ctx, dockerClient, plan, resource)
- if err != nil {
- return err
+ eligible, exists, pruneResourceEligibleErr := s.pruneResourceEligibleInternal(ctx, dockerClient, plan, resource)
+ if pruneResourceEligibleErr != nil {
+ return pruneResourceEligibleErr
}
switch {
case !exists:
@@ -295,24 +313,24 @@ func (s *SystemService) executePrunePlanInternal(ctx context.Context, plan prune
case !eligible:
target.Status = schedulertypes.Skipped
default:
- err = s.removePruneResourceInternal(ctx, dockerClient, resource)
- if err != nil && !errdefs.IsNotFound(err) {
+ pruneResourceEligibleErr = s.removePruneResourceInternal(ctx, dockerClient, resource)
+ if pruneResourceEligibleErr != nil && !errdefs.IsNotFound(pruneResourceEligibleErr) {
target.Status = schedulertypes.Failed
- target.Message = err.Error()
+ target.Message = pruneResourceEligibleErr.Error()
result.Success = false
- result.Errors = append(result.Errors, err.Error())
+ result.Errors = append(result.Errors, pruneResourceEligibleErr.Error())
} else {
target.Status = schedulertypes.Succeeded
recordPrunedResourceInternal(resource, result)
}
}
- if err := jobcontext.Progress(ctx, target); err != nil {
- return err
+ if targetProgressErr := jobcontext.Progress(ctx, target); targetProgressErr != nil {
+ return targetProgressErr
}
}
if len(result.ImagesDeleted) > 0 {
- if err := s.imageUpdateService.DeleteRecordsForImages(ctx, result.ImagesDeleted); err != nil {
- return err
+ if deleteRecordsForImagesErr := s.imageUpdateService.DeleteRecordsForImages(ctx, result.ImagesDeleted); deleteRecordsForImagesErr != nil {
+ return deleteRecordsForImagesErr
}
}
return s.executePruneCacheInternal(ctx, dockerClient, plan, result, recovery)
@@ -432,12 +450,12 @@ func (s *SystemService) executePruneCacheInternal(ctx context.Context, dockerCli
func (s *SystemService) pruneResourceEligibleInternal(ctx context.Context, dockerClient *client.Client, plan prunePlanInternal, resource pruneResourceInternal) (eligible, exists bool, err error) {
if resource.Kind == "network" {
- inspected, err := compat.NetworkInspectWithCompatibility(ctx, dockerClient, resource.ID, client.NetworkInspectOptions{})
- if errdefs.IsNotFound(err) {
+ inspected, networkInspectWithCompatibilityErr := compat.NetworkInspectWithCompatibility(ctx, dockerClient, resource.ID, client.NetworkInspectOptions{})
+ if errdefs.IsNotFound(networkInspectWithCompatibilityErr) {
return false, false, nil
}
- if err != nil {
- return false, false, err
+ if networkInspectWithCompatibilityErr != nil {
+ return false, false, networkInspectWithCompatibilityErr
}
return len(inspected.Network.Containers) == 0 && !inspected.Network.Ingress, true, nil
}
@@ -495,7 +513,7 @@ func (s *SystemService) ReconcileScheduledPrune(ctx context.Context, previous sc
if prune.started.IsAbsent() {
return outcome, nil
}
- defer s.finishSystemPruneInternal(previous.EnvironmentID)
+ defer s.finishSystemPruneInternal(previous.EnvironmentID) //nolint:gocritic // The matching recovery target always returns before the loop advances.
result := &systemtypes.PruneAllResult{Success: true}
err := s.executePrunePlanInternal(ctx, plan, previous, result, true)
if err != nil {
@@ -510,8 +528,8 @@ func (s *SystemService) ReconcileScheduledPrune(ctx context.Context, previous sc
if !result.Success {
return schedulertypes.Outcome{Status: schedulertypes.Partial, Targets: previous.Outcome.Targets}, nil
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: "scheduled-prune", Status: schedulertypes.Succeeded}); err != nil {
- return outcome, err
+ if progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: "scheduled-prune", Status: schedulertypes.Succeeded}); progressErr != nil {
+ return outcome, progressErr
}
return schedulertypes.Outcome{Status: schedulertypes.Succeeded}, nil
}
diff --git a/backend/internal/system/system.go b/backend/internal/system/system.go
index 4be9add17..f2f4ef01a 100644
--- a/backend/internal/system/system.go
+++ b/backend/internal/system/system.go
@@ -276,7 +276,34 @@ func (s *SystemService) runSystemPruneInternal(ctx context.Context, req system.P
slog.ErrorContext(ctx, "Prune operations failed", "error", err)
}
- slog.InfoContext(ctx, "Selective prune operation completed", "success", result.Success, "containers_pruned", len(result.ContainersPruned), "images_deleted", len(result.ImagesDeleted), "volumes_deleted", len(result.VolumesDeleted), "networks_deleted", len(result.NetworksDeleted), "space_reclaimed", result.SpaceReclaimed, "error_count", len(result.Errors))
+ slog.InfoContext(
+ ctx,
+ "Selective prune operation completed",
+ "success",
+ result.Success,
+ "containers_pruned",
+ len(
+ result.ContainersPruned,
+ ),
+ "images_deleted",
+ len(
+ result.ImagesDeleted,
+ ),
+ "volumes_deleted",
+ len(
+ result.VolumesDeleted,
+ ),
+ "networks_deleted",
+ len(
+ result.NetworksDeleted,
+ ),
+ "space_reclaimed",
+ result.SpaceReclaimed,
+ "error_count",
+ len(
+ result.Errors,
+ ),
+ )
s.completeSystemPruneActivityInternal(ctx, activityID, result)
}
@@ -284,7 +311,7 @@ func (s *SystemService) startSystemPruneActivityInternal(ctx context.Context, en
if s.activityService == nil {
return ""
}
- activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
+ localActivity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
EnvironmentID: environmentID,
Type: activitytypes.TypeSystemPrune,
ResourceType: new("system"),
@@ -303,7 +330,7 @@ func (s *SystemService) startSystemPruneActivityInternal(ctx context.Context, en
slog.DebugContext(ctx, "failed to start system prune activity", "error", err)
return ""
}
- return activity.ID
+ return localActivity.ID
}
func (s *SystemService) appendSystemPruneActivityMessageInternal(ctx context.Context, activityID, message string, progress int) {
@@ -343,7 +370,20 @@ func (s *SystemService) completeSystemPruneActivityInternal(ctx context.Context,
}
}
-func (s *SystemService) performBatchContainerAction(ctx context.Context, containers []mobycontainer.Summary, actionName string, shouldProcess func(mobycontainer.Summary) bool, action func(context.Context, string) error) *containertypes.ActionResult {
+func (
+ s *SystemService,
+) performBatchContainerAction(
+ ctx context.Context,
+ containers []mobycontainer.Summary,
+ actionName string,
+ shouldProcess func(
+ mobycontainer.Summary,
+ ) bool,
+ action func(
+ context.Context,
+ string,
+ ) error,
+) *containertypes.ActionResult {
result := &containertypes.ActionResult{Success: true}
var mu sync.Mutex
@@ -465,7 +505,7 @@ func (s *SystemService) startSystemContainerActivityInternal(ctx context.Context
if s.activityService == nil {
return ""
}
- activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
+ localActivity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
EnvironmentID: environmentID,
Type: activityType,
ResourceType: new("system"),
@@ -478,7 +518,7 @@ func (s *SystemService) startSystemContainerActivityInternal(ctx context.Context
slog.DebugContext(ctx, "failed to start system container activity", "type", activityType, "error", err)
return ""
}
- return activity.ID
+ return localActivity.ID
}
func (s *SystemService) completeSystemContainerActivityInternal(ctx context.Context, activityID, successMessage string, result *containertypes.ActionResult) {
@@ -566,8 +606,8 @@ func (s *SystemService) pruneImagesInternal(ctx context.Context, options system.
}
}
- if err := s.imageUpdateService.DeleteRecordsForImages(ctx, idsToDelete); err != nil {
- slog.WarnContext(ctx, "Failed to delete image update records", "count", len(idsToDelete), "error", err.Error())
+ if deleteRecordsForImagesErr := s.imageUpdateService.DeleteRecordsForImages(ctx, idsToDelete); deleteRecordsForImagesErr != nil {
+ slog.WarnContext(ctx, "Failed to delete image update records", "count", len(idsToDelete), "error", deleteRecordsForImagesErr.Error())
}
result.ImagesDeleted = idsToDelete
diff --git a/backend/internal/system/upgrade_service.go b/backend/internal/system/upgrade_service.go
index 84f2d9715..c6d25477b 100644
--- a/backend/internal/system/upgrade_service.go
+++ b/backend/internal/system/upgrade_service.go
@@ -46,7 +46,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
)
-var upgradeLogNameInternal = regexp.MustCompile(`^arcane-upgrade-[0-9]+\.log$`)
+var upgradeLogNameInternal = regexp.MustCompile(`^arcane-upgrade-\d+\.log$`)
type SystemUpgradeService struct {
upgrading atomic.Bool
@@ -127,13 +127,13 @@ func (s *SystemUpgradeService) TriggerUpgradeAsync(ctx context.Context, user com
if err != nil {
return err
}
- settings := s.settingsService.GetSettingsConfig()
- runTimeout := timeouts.GetDuration(settings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull) + time.Minute
+ localSettings := s.settingsService.GetSettingsConfig()
+ runTimeout := timeouts.GetDuration(localSettings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull) + time.Minute
runCtx, cancel := context.WithTimeout(utils.ActivityRuntimeContext(ctx, nil), runTimeout)
go func() {
defer cancel()
- if _, err := s.runPreparedUpgradeInternal(runCtx, prepared); err != nil {
- slog.Error("Background self-upgrade failed", "error", err, "targetImage", prepared.targetImage)
+ if _, runPreparedUpgradeErr := s.runPreparedUpgradeInternal(runCtx, prepared); runPreparedUpgradeErr != nil {
+ slog.Error("Background self-upgrade failed", "error", runPreparedUpgradeErr, "targetImage", prepared.targetImage)
}
}()
return nil
@@ -192,8 +192,8 @@ func (s *SystemUpgradeService) prepareUpgradeInternal(ctx context.Context, user
"method": "cli",
"targetImage": targetImage,
}
- if err := s.eventService.LogUserEvent(ctx, event.EventTypeSystemUpgrade, user.ID, user.Username, metadata); err != nil {
- slog.Warn("Failed to log upgrade event", "error", err)
+ if logUserEventErr := s.eventService.LogUserEvent(ctx, event.EventTypeSystemUpgrade, user.ID, user.Username, metadata); logUserEventErr != nil {
+ slog.Warn("Failed to log upgrade event", "error", logUserEventErr)
}
return &preparedUpgradeInternal{
@@ -224,8 +224,8 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, p
// Pull the upgrader image first to ensure it exists
slog.Info("Pulling upgrader image", "image", upgraderImage)
- settings := s.settingsService.GetSettingsConfig()
- pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))
+ localSettings := s.settingsService.GetSettingsConfig()
+ pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(localSettings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))
defer pullCancel()
pullReader, err := dockerClient.ImagePull(pullCtx, upgraderImage, client.ImagePullOptions{})
@@ -236,9 +236,9 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, p
return "", fmt.Errorf("pull upgrader image: %w", err)
}
// Drain and validate the JSON stream to complete the pull.
- if err := dockerutils.RenderJSONMessageStream(pullReader, io.Discard); err != nil {
+ if renderJSONMessageStreamErr := dockerutils.RenderJSONMessageStream(pullReader, io.Discard); renderJSONMessageStreamErr != nil {
_ = pullReader.Close()
- return "", fmt.Errorf("failed to complete upgrader image pull: %w", err)
+ return "", fmt.Errorf("failed to complete upgrader image pull: %w", renderJSONMessageStreamErr)
}
if closeErr := pullReader.Close(); closeErr != nil {
slog.Warn("Failed to close upgrader image pull reader", "error", closeErr)
@@ -262,8 +262,8 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, p
return projects.GetHostPathForContainerPath(ctx, dockerClient, containerPath)
},
func() bool {
- _, err := cgroup.CurrentContainerID()
- return err == nil
+ _, currentContainerIDErr := cgroup.CurrentContainerID()
+ return currentContainerIDErr == nil
},
func(ctx context.Context, inspect *container.InspectResponse, dockerHost string) string {
return dockerutils.SelectDockerHostReachableNetworkMode(ctx, dockerClient, inspect, dockerHost)
@@ -333,9 +333,9 @@ func (s *SystemUpgradeService) runPreparedUpgradeInternal(ctx context.Context, p
}
// Start the upgrader container - it will run the upgrade and auto-remove
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})
- return "", fmt.Errorf("start upgrader container: %w", err)
+ return "", fmt.Errorf("start upgrader container: %w", containerStartErr)
}
slog.Info("Upgrade container started", "upgraderId", resp.ID[:12], "upgraderName", upgraderName)
@@ -423,12 +423,12 @@ func resolveSelfUpgradeTargetImageInternal(currentImageRef string, info *version
return "", errors.New("image is digest-pinned but no newest digest could be resolved; refusing an upgrade that could not move it")
}
targetDigest := digest.Digest(newestDigest)
- if err := targetDigest.Validate(); err != nil {
- return "", fmt.Errorf("resolved newest digest %q is not a valid digest: %w", newestDigest, err)
+ if validateErr := targetDigest.Validate(); validateErr != nil {
+ return "", fmt.Errorf("resolved newest digest %q is not a valid digest: %w", newestDigest, validateErr)
}
- withDigest, err := ref.WithDigest(named, targetDigest)
- if err != nil {
- return "", fmt.Errorf("build target reference for %q: %w", named.Name(), err)
+ withDigest, withDigestErr := ref.WithDigest(named, targetDigest)
+ if withDigestErr != nil {
+ return "", fmt.Errorf("build target reference for %q: %w", named.Name(), withDigestErr)
}
return withDigest.String(), nil
}
@@ -689,8 +689,8 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user common.U
job.Status = EnvironmentUpdateJobStatusRunning
job.Results = append(EnvironmentUpdateResults{managerResult}, remoteResults...)
- if err := s.db.WithContext(ctx).Create(job).Error; err != nil {
- return nil, fmt.Errorf("create update-all job: %w", err)
+ if createUpgradeJobErr := s.db.WithContext(ctx).Create(job).Error; createUpgradeJobErr != nil {
+ return nil, fmt.Errorf("create update-all job: %w", createUpgradeJobErr)
}
slog.InfoContext(ctx, "Update-all started; upgrading agents first", "jobId", job.ID, "user", user.Username)
@@ -787,16 +787,16 @@ func (s *SystemUpgradeService) runAgentsPhaseInternal(ctx context.Context, jobID
// the row currently being processed.
idx := upsertPendingResultInternal(job, remote.ID, remote.Name)
job.Results[idx].Status = EnvironmentUpdateResultStatusUpdating
- if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {
- slog.WarnContext(ctx, "update-all: failed to persist updating status", "jobId", job.ID, "environmentId", remote.ID, "error", err)
+ if persistUpdateAllJobErr := s.persistUpdateAllJobInternal(ctx, job); persistUpdateAllJobErr != nil {
+ slog.WarnContext(ctx, "update-all: failed to persist updating status", "jobId", job.ID, "environmentId", remote.ID, "error", persistUpdateAllJobErr)
}
result := job.Results[idx]
s.upgradeAgentInternal(ctx, env, remote.ID, &result)
job.Results[idx] = result
- if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {
- slog.WarnContext(ctx, "update-all: failed to persist progress", "jobId", job.ID, "environmentId", remote.ID, "error", err)
+ if saveRemoteProgressErr := s.persistUpdateAllJobInternal(ctx, job); saveRemoteProgressErr != nil {
+ slog.WarnContext(ctx, "update-all: failed to persist progress", "jobId", job.ID, "environmentId", remote.ID, "error", saveRemoteProgressErr)
}
}
@@ -811,8 +811,8 @@ func (s *SystemUpgradeService) runAgentsPhaseInternal(ctx context.Context, jobID
}
}
job.Status = EnvironmentUpdateJobStatusPendingRestart
- if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {
- slog.WarnContext(ctx, "update-all: failed to persist pending_restart before manager upgrade", "jobId", job.ID, "error", err)
+ if savePendingRestartErr := s.persistUpdateAllJobInternal(ctx, job); savePendingRestartErr != nil {
+ slog.WarnContext(ctx, "update-all: failed to persist pending_restart before manager upgrade", "jobId", job.ID, "error", savePendingRestartErr)
}
// Snapshot whether the manager was already on the newest image BEFORE triggering:
@@ -967,17 +967,17 @@ func (s *SystemUpgradeService) waitForUpgraderExitInternal(ctx context.Context,
return upgraderExitCodeLostInternal, 0
}
return upgraderExitSucceededInternal, 0
- case err, ok := <-wait.Error:
+ case waitUpgraderErr, ok := <-wait.Error:
// The upgrader runs with AutoRemove, so a fast run can be gone before the wait
// is acknowledged. It exited, but the code went with it — a failed upgrade must
// not be mistaken for a clean no-op, so report the ambiguity rather than a code.
- if cerrdefs.IsNotFound(err) {
+ if cerrdefs.IsNotFound(waitUpgraderErr) {
return upgraderExitCodeLostInternal, 0
}
- if !ok || err == nil {
+ if !ok || waitUpgraderErr == nil {
slog.WarnContext(ctx, "update-all: upgrader wait ended without a status", "upgraderId", upgraderID)
} else {
- slog.WarnContext(ctx, "update-all: failed waiting for upgrader container", "upgraderId", upgraderID, "error", err)
+ slog.WarnContext(ctx, "update-all: failed waiting for upgrader container", "upgraderId", upgraderID, "error", waitUpgraderErr)
}
return upgraderExitUnobservedInternal, 0
case <-waitCtx.Done():
@@ -1041,9 +1041,9 @@ func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *en
var triggerBody []byte
if managerInfo := s.versionService.GetAppVersionInfo(ctx); managerInfo != nil {
if newest := strings.TrimSpace(managerInfo.NewestVersion); newest != "" {
- body, err := json.Marshal(TriggerUpgradeBody{TargetVersion: newest})
- if err != nil {
- slog.WarnContext(ctx, "update-all: failed to marshal trigger body", "environmentId", envID, "error", err)
+ body, marshalErr := json.Marshal(TriggerUpgradeBody{TargetVersion: newest})
+ if marshalErr != nil {
+ slog.WarnContext(ctx, "update-all: failed to marshal trigger body", "environmentId", envID, "error", marshalErr)
} else {
info.NewestVersion = newest
triggerBody = body
@@ -1061,9 +1061,9 @@ func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *en
result.Error = truncateUpdateAllErrorInternal(err)
return
}
- if err := resp.RequireSuccess(); err != nil {
+ if requireSuccessErr := resp.RequireSuccess(); requireSuccessErr != nil {
result.Status = EnvironmentUpdateResultStatusFailed
- result.Error = truncateUpdateAllErrorInternal(err)
+ result.Error = truncateUpdateAllErrorInternal(requireSuccessErr)
return
}
@@ -1359,7 +1359,11 @@ func (s *SystemUpgradeService) PruneUpgradeLogs(ctx context.Context, dataDir str
if err != nil {
return 0, fmt.Errorf("open upgrade log directory: %w", err)
}
- defer root.Close()
+ defer func() {
+ if closeErr := root.Close(); closeErr != nil {
+ slog.WarnContext(ctx, "Failed to close upgrade log directory", "error", closeErr)
+ }
+ }()
entries, err := fs.ReadDir(root.FS(), ".")
if err != nil {
return 0, fmt.Errorf("read upgrade log directory: %w", err)
@@ -1369,26 +1373,26 @@ func (s *SystemUpgradeService) PruneUpgradeLogs(ctx context.Context, dataDir str
removed := 0
var failures []error
for _, entry := range entries {
- if err := ctx.Err(); err != nil {
- return removed, errors.Join(append(failures, err)...)
+ if cancellationErr := ctx.Err(); cancellationErr != nil {
+ return removed, errors.Join(append(failures, cancellationErr)...)
}
if !upgradeLogNameInternal.MatchString(entry.Name()) {
continue
}
- info, err := root.Lstat(entry.Name())
- if errors.Is(err, os.ErrNotExist) {
+ info, lstatErr := root.Lstat(entry.Name())
+ if errors.Is(lstatErr, os.ErrNotExist) {
continue
}
- if err != nil {
- failures = append(failures, fmt.Errorf("inspect upgrade log %s: %w", entry.Name(), err))
+ if lstatErr != nil {
+ failures = append(failures, fmt.Errorf("inspect upgrade log %s: %w", entry.Name(), lstatErr))
continue
}
if !info.Mode().IsRegular() || !info.ModTime().Before(cutoff) {
continue
}
- if err := root.Remove(entry.Name()); err != nil {
- if !errors.Is(err, os.ErrNotExist) {
- failures = append(failures, fmt.Errorf("remove upgrade log %s: %w", entry.Name(), err))
+ if removeErr := root.Remove(entry.Name()); removeErr != nil {
+ if !errors.Is(removeErr, os.ErrNotExist) {
+ failures = append(failures, fmt.Errorf("remove upgrade log %s: %w", entry.Name(), removeErr))
}
continue
}
diff --git a/backend/internal/system/upgrade_service_test.go b/backend/internal/system/upgrade_service_test.go
index 91356e8ee..c6817e524 100644
--- a/backend/internal/system/upgrade_service_test.go
+++ b/backend/internal/system/upgrade_service_test.go
@@ -130,7 +130,7 @@ func TestSystemUpgradeService_UpgradeInProgressError(t *testing.T) {
err := common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress"))
require.Equal(t, "an upgrade is already in progress", err.Error())
- require.True(t, errors.Is(err, common.ErrUpgradeInProgress))
+ require.ErrorIs(t, err, common.ErrUpgradeInProgress)
}
// TestSystemUpgradeService_AtomicOperations tests atomic.Bool operations
@@ -173,7 +173,7 @@ func TestResolveSystemUpgraderRuntimeOptionsInternal_TCPDockerHost(t *testing.T)
}
containerEnv, mounts, networkMode, err := ResolveUpgraderRuntimeOptions(
- context.Background(),
+ t.Context(),
"tcp://docker-socket-proxy:2375",
currentContainer,
nil,
@@ -188,7 +188,7 @@ func TestResolveSystemUpgraderRuntimeOptionsInternal_TCPDockerHost(t *testing.T)
func TestResolveSystemUpgraderRuntimeOptionsInternal_UnixDockerHost(t *testing.T) {
containerEnv, mounts, networkMode, err := ResolveUpgraderRuntimeOptions(
- context.Background(),
+ t.Context(),
"unix:///var/run/docker.sock",
nil,
func(context.Context, string) (string, error) {
@@ -211,7 +211,7 @@ func TestResolveSystemUpgraderRuntimeOptionsInternal_UnixDockerHost(t *testing.T
func TestResolveSystemUpgraderRuntimeOptionsInternal_DefaultDockerHost(t *testing.T) {
containerEnv, mounts, _, err := ResolveUpgraderRuntimeOptions(
- context.Background(),
+ t.Context(),
"",
nil,
func(context.Context, string) (string, error) {
@@ -233,7 +233,7 @@ func TestResolveSystemUpgraderRuntimeOptionsInternal_DefaultDockerHost(t *testin
func TestResolveSystemUpgraderRuntimeOptionsInternal_UnixDockerHostResolutionError(t *testing.T) {
_, _, _, err := ResolveUpgraderRuntimeOptions(
- context.Background(),
+ t.Context(),
"unix:///var/run/docker.sock",
nil,
func(context.Context, string) (string, error) {
diff --git a/backend/internal/system/upgrade_update_all_test.go b/backend/internal/system/upgrade_update_all_test.go
index 258029ab5..d343c1669 100644
--- a/backend/internal/system/upgrade_update_all_test.go
+++ b/backend/internal/system/upgrade_update_all_test.go
@@ -1,7 +1,6 @@
package system
import (
- "context"
"testing"
"time"
@@ -136,7 +135,7 @@ func TestUpsertPendingResult(t *testing.T) {
}
func TestUpdateAllFailedJobMarksUpdatingResultsFailed(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
gormDB, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
@@ -185,7 +184,7 @@ func TestUpdateAllFailedJobMarksUpdatingResultsFailed(t *testing.T) {
// running and skips the recreate. The pending_restart job must then be finalized in
// place, because no next boot is coming to do it.
func TestUpdateAllFinalizesUpToDateManagerWithoutRestart(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
gormDB, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
@@ -289,7 +288,7 @@ func TestAgentAlreadyOnTarget(t *testing.T) {
// phase already ran before the restart: resume must finalize the manager's own row
// and complete the job, NOT re-run the agents phase.
func TestResumeUpdateAllFinalizesManagerWithoutRerunningAgents(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
gormDB, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
require.NoError(t, err)
diff --git a/backend/internal/systembackup/background.go b/backend/internal/systembackup/background.go
index 13595fe55..04fb4cae4 100644
--- a/backend/internal/systembackup/background.go
+++ b/backend/internal/systembackup/background.go
@@ -38,11 +38,31 @@ func (s *SystemBackupService) StartBackup(ctx context.Context, user common.User,
return nil, err
}
activityID, workCtx := activitylib.StartHandlerActivity(ctx, s.activityService, "0", activitytypes.TypeResourceAction, "system_backup", "arcane", "Arcane", &user,
- "Creating system backup", "Creating Arcane system backup", database.JSON{"action": "create_system_backup", "backupId": prepared.run.ID, "destination": prepared.run.Destination, "s3DestinationId": prepared.run.S3DestinationID, "policyId": prepared.run.PolicyID}, false)
+ "Creating system backup", "Creating Arcane system backup", database.JSON{
+ "action": "create_system_backup",
+ "backupId": prepared.run.ID,
+ "destination": prepared.run.Destination,
+ "s3DestinationId": prepared.run.S3DestinationID,
+ "policyId": prepared.run.PolicyID,
+ }, false)
finish := func(runErr error) {
defer lease.Release(ctx)
if runErr != nil {
- if saveErr := s.db.WithContext(context.WithoutCancel(workCtx)).Model(&SystemBackupRun{}).Where("id = ?", prepared.run.ID).Updates(map[string]any{"status": SystemBackupStatusFailed, "error": runErr.Error()}).Error; saveErr != nil {
+ if saveErr := s.db.WithContext(
+ context.WithoutCancel(
+ workCtx,
+ ),
+ ).Model(
+ &SystemBackupRun{},
+ ).Where(
+ "id = ?",
+ prepared.run.ID,
+ ).Updates(
+ map[string]any{
+ "status": SystemBackupStatusFailed,
+ "error": runErr.Error(),
+ },
+ ).Error; saveErr != nil {
runErr = errors.Join(runErr, fmt.Errorf("save backup failure: %w", saveErr))
}
}
@@ -61,9 +81,33 @@ func (s *SystemBackupService) StartBackup(ctx context.Context, user common.User,
finish(keyErr)
return nil, keyErr
}
- payload, err := json.Marshal(manualSystemBackupInternal{Checkpoint: systemBackupRecoveryInternal{BackupID: prepared.run.ID, LocalEnabled: prepared.localEnabled, S3Enabled: prepared.s3Enabled}, EncryptedKey: encryptedKey, ActivityID: activityID, UserID: user.ID})
+ payload, err := json.Marshal(
+ manualSystemBackupInternal{
+ Checkpoint: systemBackupRecoveryInternal{
+ BackupID: prepared.run.ID,
+ LocalEnabled: prepared.localEnabled,
+ S3Enabled: prepared.s3Enabled,
+ },
+ EncryptedKey: encryptedKey,
+ ActivityID: activityID,
+ UserID: user.ID,
+ },
+ )
if err == nil {
- err = s.engine.SubmitDurableRun(workCtx, backuptypes.DurableRunCommand{Kind: "system", RunID: prepared.run.ID, ActivityID: activityID, Payload: payload, UserID: user.ID, EnvironmentID: "0", Permission: authz.PermSystemBackupsManage, RequestedWithKey: keyID}, lease)
+ err = s.engine.SubmitDurableRun(
+ workCtx,
+ backuptypes.DurableRunCommand{
+ Kind: "system",
+ RunID: prepared.run.ID,
+ ActivityID: activityID,
+ Payload: payload,
+ UserID: user.ID,
+ EnvironmentID: "0",
+ Permission: authz.PermSystemBackupsManage,
+ RequestedWithKey: keyID,
+ },
+ lease,
+ )
}
if err != nil {
finish(err)
@@ -95,7 +139,18 @@ func (s *SystemBackupService) StartSystemVolumeBackups(ctx context.Context, user
names[i] = candidate.Name
}
activityID, workCtx := activitylib.StartHandlerActivity(ctx, s.activityService, "0", activitytypes.TypeResourceAction, "system_backup", "volumes", "Volumes", &user,
- "Backing up volumes", "Creating system-managed volume backups", database.JSON{"action": "run_system_volume_backups", "policyId": policy.ID, "volumeNames": names, "matched": len(candidates), "succeeded": 0, "failed": 0, "skipped": 0, "failures": []backuptypes.SystemVolumeBackupFailure{}}, false)
+ "Backing up volumes", "Creating system-managed volume backups", database.JSON{
+ "action": "run_system_volume_backups",
+ "policyId": policy.ID,
+ "volumeNames": names,
+ "matched": len(
+ candidates,
+ ),
+ "succeeded": 0,
+ "failed": 0,
+ "skipped": 0,
+ "failures": []backuptypes.SystemVolumeBackupFailure{},
+ }, false)
if activityID == "" {
lease.Release(ctx)
return nil, errors.New("failed to create system-managed volume backup activity")
@@ -107,7 +162,20 @@ func (s *SystemBackupService) StartSystemVolumeBackups(ctx context.Context, user
keyID, _ := ctx.Value(middleware.ContextKeyApiKeyID).(string)
payload, err := json.Marshal(manualSystemVolumesInternal{Policy: policy, ManualPolicy: manualPolicy, Candidates: candidates, ActivityID: activityID, UserID: user.ID})
if err == nil {
- err = s.engine.SubmitDurableRun(workCtx, backuptypes.DurableRunCommand{Kind: "system-volumes", RunID: activityID, ActivityID: activityID, Payload: payload, UserID: user.ID, EnvironmentID: "0", Permission: authz.PermSystemBackupsManage, RequestedWithKey: keyID}, lease)
+ err = s.engine.SubmitDurableRun(
+ workCtx,
+ backuptypes.DurableRunCommand{
+ Kind: "system-volumes",
+ RunID: activityID,
+ ActivityID: activityID,
+ Payload: payload,
+ UserID: user.ID,
+ EnvironmentID: "0",
+ Permission: authz.PermSystemBackupsManage,
+ RequestedWithKey: keyID,
+ },
+ lease,
+ )
}
if err != nil {
@@ -117,7 +185,14 @@ func (s *SystemBackupService) StartSystemVolumeBackups(ctx context.Context, user
return &backuptypes.BackupRunAccepted{ActivityID: activityID, Status: "running"}, nil
}
-func (s *SystemBackupService) updateSystemVolumeProgressInternal(ctx context.Context, activityID, policyID string, candidates []backuptypes.SystemVolumeBackupOption, result *backuptypes.SystemVolumeBackupRunResult) {
+func (
+ s *SystemBackupService,
+) updateSystemVolumeProgressInternal(
+ ctx context.Context,
+ activityID, policyID string,
+ candidates []backuptypes.SystemVolumeBackupOption,
+ result *backuptypes.SystemVolumeBackupRunResult,
+) {
if activityID == "" {
return
}
@@ -163,13 +238,13 @@ func (s *SystemBackupService) reconcileBackupInternal(ctx context.Context, previ
if !admitted {
return outcome, nil
}
- defer lease.Release(ctx)
+ defer lease.Release(ctx) //nolint:gocritic // The matching recovery target always returns before the loop advances.
key := ""
if len(suppliedKeys) > 0 {
key = suppliedKeys[0]
}
- if err := s.resumeBackupInternal(ctx, previous, &run, checkpoint, key); err != nil {
- return outcome, err
+ if resumeBackupErr := s.resumeBackupInternal(ctx, previous, &run, checkpoint, key); resumeBackupErr != nil {
+ return outcome, resumeBackupErr
}
}
target.Status = schedulertypes.Succeeded
@@ -204,7 +279,21 @@ func systemBackupRemoteAttemptedInternal(previous schedulertypes.Run, runID stri
return false
}
-func (s *SystemBackupService) observeBackupSnapshotsInternal(ctx context.Context, dockerClient *client.Client, previous schedulertypes.Run, run *SystemBackupRun, checkpoint systemBackupRecoveryInternal, key string) (backup.Snapshot, backup.Repository, backup.Repository, error) {
+func (
+ s *SystemBackupService,
+) observeBackupSnapshotsInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ previous schedulertypes.Run,
+ run *SystemBackupRun,
+ checkpoint systemBackupRecoveryInternal,
+ key string,
+) (
+ backup.Snapshot,
+ backup.Repository,
+ backup.Repository,
+ error,
+) {
var staged backup.Snapshot
var remote backup.Repository
local, err := s.localRepositoryInternal(ctx, dockerClient, false)
@@ -230,9 +319,9 @@ func (s *SystemBackupService) observeBackupSnapshotsInternal(ctx context.Context
}
attempted := (stageAttempted && staged.ID == "") || systemBackupRemoteAttemptedInternal(previous, run.ID)
if attempted || run.RemoteSnapshotID != "" {
- snapshot, found, err := s.engine.FindRunSnapshot(ctx, dockerClient, remote, key, run.ID, run.RemoteSnapshotID)
- if err != nil {
- return staged, local, remote, err
+ snapshot, found, findRunSnapshotErr := s.engine.FindRunSnapshot(ctx, dockerClient, remote, key, run.ID, run.RemoteSnapshotID)
+ if findRunSnapshotErr != nil {
+ return staged, local, remote, findRunSnapshotErr
}
if found {
run.RemoteSnapshotID = snapshot.ID
@@ -244,7 +333,17 @@ func (s *SystemBackupService) observeBackupSnapshotsInternal(ctx context.Context
return staged, local, remote, nil
}
-func (s *SystemBackupService) finishRecoveredDestinationsInternal(ctx context.Context, dockerClient *client.Client, run *SystemBackupRun, checkpoint systemBackupRecoveryInternal, key string, staged backup.Snapshot, local, remote backup.Repository) error {
+func (
+ s *SystemBackupService,
+) finishRecoveredDestinationsInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ run *SystemBackupRun,
+ checkpoint systemBackupRecoveryInternal,
+ key string,
+ staged backup.Snapshot,
+ local, remote backup.Repository,
+) error {
if checkpoint.LocalEnabled && staged.ID == "" && run.RemoteSnapshotID != "" {
var err error
staged, err = s.engine.Replicate(ctx, dockerClient, remote, run.RemoteSnapshotID, local, key, "arcane-system-recovery", backup.RunSnapshotTag(run.ID))
@@ -288,8 +387,8 @@ func (s *SystemBackupService) resumeBackupInternal(ctx context.Context, previous
if err != nil {
return err
}
- if err := s.finishRecoveredDestinationsInternal(ctx, dockerClient, run, checkpoint, key, staged, local, remote); err != nil {
- return err
+ if finishRecoveredDestinationsErr := s.finishRecoveredDestinationsInternal(ctx, dockerClient, run, checkpoint, key, staged, local, remote); finishRecoveredDestinationsErr != nil {
+ return finishRecoveredDestinationsErr
}
run.Status, run.Error = SystemBackupStatusSucceeded, ""
return s.db.WithContext(ctx).Save(run).Error
@@ -312,8 +411,8 @@ type manualSystemVolumesInternal struct {
func (s *SystemBackupService) executeDurableBackupInternal(ctx context.Context, runID string, payload []byte, interrupted bool) (err error) {
var command manualSystemBackupInternal
- if err = json.Unmarshal(payload, &command); err != nil {
- return err
+ if decodeErr := json.Unmarshal(payload, &command); decodeErr != nil {
+ return decodeErr
}
defer func() {
if ctx.Err() == nil {
@@ -325,8 +424,8 @@ func (s *SystemBackupService) executeDurableBackupInternal(ctx context.Context,
}
}()
var run SystemBackupRun
- if err = s.db.WithContext(ctx).Where("id = ?", command.Checkpoint.BackupID).First(&run).Error; err != nil {
- return err
+ if loadBackupErr := s.db.WithContext(ctx).Where("id = ?", command.Checkpoint.BackupID).First(&run).Error; loadBackupErr != nil {
+ return loadBackupErr
}
if run.Status == SystemBackupStatusSucceeded {
return nil
@@ -358,8 +457,17 @@ func (s *SystemBackupService) executeDurableBackupInternal(ctx context.Context,
if err != nil {
return err
}
- if err = jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "system_backup", ID: runID, Status: schedulertypes.Running, RecoveryData: checkpoint, ActivityID: command.ActivityID}); err != nil {
- return err
+ if progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "system_backup",
+ ID: runID,
+ Status: schedulertypes.Running,
+ RecoveryData: checkpoint,
+ ActivityID: command.ActivityID,
+ },
+ ); progressErr != nil {
+ return progressErr
}
_, err = s.executeBackupInternal(ctx, &preparedSystemBackupInternal{run: &run, recoveryKey: key, localEnabled: command.Checkpoint.LocalEnabled, s3Enabled: command.Checkpoint.S3Enabled})
return err
@@ -367,8 +475,8 @@ func (s *SystemBackupService) executeDurableBackupInternal(ctx context.Context,
func (s *SystemBackupService) executeDurableVolumeBackupsInternal(ctx context.Context, runID string, payload []byte, interrupted bool) (err error) {
var command manualSystemVolumesInternal
- if err = json.Unmarshal(payload, &command); err != nil {
- return err
+ if decodeErr := json.Unmarshal(payload, &command); decodeErr != nil {
+ return decodeErr
}
defer func() {
if ctx.Err() == nil {
diff --git a/backend/internal/systembackup/handler.go b/backend/internal/systembackup/handler.go
index b62f3ba5f..3bda75e75 100644
--- a/backend/internal/systembackup/handler.go
+++ b/backend/internal/systembackup/handler.go
@@ -121,23 +121,263 @@ type DiscoverSystemBackupsInput struct {
func RegisterSystemBackups(api huma.API, service *SystemBackupService, activityService *activity.ActivityService, appCtx handlerutil.ActivityAppContext) {
h := &SystemBackupHandler{service: service, activity: activityService, appCtx: appCtx.Context()}
adminOnly := middleware.RequireGlobalAdmin(api)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-system-backups", Method: http.MethodGet, Path: "/backups", Summary: "List Arcane system backups", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.List)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-backup-history", Method: http.MethodGet, Path: "/backups/history", Summary: "List unified backup history", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.ListHistory)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-system-volume-backup-config", Method: http.MethodGet, Path: "/backups/volumes/config", Summary: "Get system-managed volume backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.GetSystemVolumeConfig)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-system-volume-backup-config", Method: http.MethodPut, Path: "/backups/volumes/config", Summary: "Update system-managed volume backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.UpdateSystemVolumeConfig)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "list-system-volume-backup-options", Method: http.MethodGet, Path: "/backups/volumes/options", Summary: "List volumes available to system-managed backups", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.ListSystemVolumeOptions)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "run-system-volume-backups", DefaultStatus: http.StatusAccepted, Method: http.MethodPost, Path: "/backups/volumes/run", Summary: "Run system-managed volume backups", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.RunSystemVolumeBackups)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "get-system-backup-policies", Method: http.MethodGet, Path: "/backups/policies", Summary: "Get Arcane system backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.GetPolicies)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "update-system-backup-policies", Method: http.MethodPut, Path: "/backups/policies", Summary: "Update Arcane system backup policies", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.UpdatePolicies)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "generate-system-backup-recovery-key", Method: http.MethodPost, Path: "/backups/recovery-key/generate", Summary: "Generate an Arcane system backup recovery key", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRecoveryKey, h.GenerateRecoveryKey)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "set-system-backup-recovery-key", Method: http.MethodPut, Path: "/backups/recovery-key", Summary: "Configure Arcane system backup recovery key", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRecoveryKey, h.SetRecoveryKey)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "create-system-backup", DefaultStatus: http.StatusAccepted, Method: http.MethodPost, Path: "/backups", Summary: "Create Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.Create)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "discover-system-backups", Method: http.MethodPost, Path: "/backups/discover", Summary: "Discover Arcane system backups in S3", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.Discover)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "restore-system-backup", Method: http.MethodPost, Path: "/backups/{id}/restore", Summary: "Restore Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRestore, h.Restore)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "browse-system-backup-files", Method: http.MethodPost, Path: "/backups/{id}/files/browse", Summary: "Browse project files in an Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRead, h.BrowseFiles)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "restore-system-backup-files", Method: http.MethodPost, Path: "/backups/{id}/restore-files", Summary: "Restore project files from an Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsRestore, h.RestoreFiles)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "upload-system-backup", Method: http.MethodPost, Path: "/backups/{id}/upload", Summary: "Upload Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.Upload)
- middleware.RegisterWithPermission(api, huma.Operation{OperationID: "delete-system-backup", Method: http.MethodDelete, Path: "/backups/{id}", Summary: "Delete Arcane system backup", Tags: []string{"System Backups"}, Middlewares: adminOnly}, authz.PermSystemBackupsManage, h.Delete)
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-system-backups",
+ Method: http.MethodGet,
+ Path: "/backups",
+ Summary: "List Arcane system backups",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRead,
+ h.List,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-backup-history",
+ Method: http.MethodGet,
+ Path: "/backups/history",
+ Summary: "List unified backup history",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRead,
+ h.ListHistory,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-system-volume-backup-config",
+ Method: http.MethodGet,
+ Path: "/backups/volumes/config",
+ Summary: "Get system-managed volume backup policies",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRead,
+ h.GetSystemVolumeConfig,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "update-system-volume-backup-config",
+ Method: http.MethodPut,
+ Path: "/backups/volumes/config",
+ Summary: "Update system-managed volume backup policies",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsManage,
+ h.UpdateSystemVolumeConfig,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "list-system-volume-backup-options",
+ Method: http.MethodGet,
+ Path: "/backups/volumes/options",
+ Summary: "List volumes available to system-managed backups",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRead,
+ h.ListSystemVolumeOptions,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "run-system-volume-backups",
+ DefaultStatus: http.StatusAccepted,
+ Method: http.MethodPost,
+ Path: "/backups/volumes/run",
+ Summary: "Run system-managed volume backups",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsManage,
+ h.RunSystemVolumeBackups,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "get-system-backup-policies",
+ Method: http.MethodGet,
+ Path: "/backups/policies",
+ Summary: "Get Arcane system backup policies",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRead,
+ h.GetPolicies,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "update-system-backup-policies",
+ Method: http.MethodPut,
+ Path: "/backups/policies",
+ Summary: "Update Arcane system backup policies",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsManage,
+ h.UpdatePolicies,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "generate-system-backup-recovery-key",
+ Method: http.MethodPost,
+ Path: "/backups/recovery-key/generate",
+ Summary: "Generate an Arcane system backup recovery key",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRecoveryKey,
+ h.GenerateRecoveryKey,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "set-system-backup-recovery-key",
+ Method: http.MethodPut,
+ Path: "/backups/recovery-key",
+ Summary: "Configure Arcane system backup recovery key",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRecoveryKey,
+ h.SetRecoveryKey,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "create-system-backup",
+ DefaultStatus: http.StatusAccepted,
+ Method: http.MethodPost,
+ Path: "/backups",
+ Summary: "Create Arcane system backup",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsManage,
+ h.Create,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "discover-system-backups",
+ Method: http.MethodPost,
+ Path: "/backups/discover",
+ Summary: "Discover Arcane system backups in S3",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsManage,
+ h.Discover,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "restore-system-backup",
+ Method: http.MethodPost,
+ Path: "/backups/{id}/restore",
+ Summary: "Restore Arcane system backup",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRestore,
+ h.Restore,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "browse-system-backup-files",
+ Method: http.MethodPost,
+ Path: "/backups/{id}/files/browse",
+ Summary: "Browse project files in an Arcane system backup",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRead,
+ h.BrowseFiles,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "restore-system-backup-files",
+ Method: http.MethodPost,
+ Path: "/backups/{id}/restore-files",
+ Summary: "Restore project files from an Arcane system backup",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsRestore,
+ h.RestoreFiles,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "upload-system-backup",
+ Method: http.MethodPost,
+ Path: "/backups/{id}/upload",
+ Summary: "Upload Arcane system backup",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsManage,
+ h.Upload,
+ )
+ middleware.RegisterWithPermission(
+ api,
+ huma.Operation{
+ OperationID: "delete-system-backup",
+ Method: http.MethodDelete,
+ Path: "/backups/{id}",
+ Summary: "Delete Arcane system backup",
+ Tags: []string{
+ "System Backups",
+ },
+ Middlewares: adminOnly,
+ },
+ authz.PermSystemBackupsManage,
+ h.Delete,
+ )
}
func (h *SystemBackupHandler) ListHistory(ctx context.Context, input *ListBackupHistoryInput) (*handlerutil.Page[backuptypes.HistoryEntry], error) {
@@ -404,5 +644,17 @@ func (h *SystemBackupHandler) Delete(ctx context.Context, input *DeleteSystemBac
}
func messageOutputInternal(message, activityID string) *handlerutil.Out[base.MessageResponse] {
- return &handlerutil.Out[base.MessageResponse]{Body: base.ApiResponse[base.MessageResponse]{Success: true, Data: base.MessageResponse{Message: message, ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()}}}
+ return &handlerutil.Out[base.MessageResponse]{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: message,
+ ActivityID: mo.EmptyableToOption(
+ strings.TrimSpace(
+ activityID,
+ ),
+ ).ToPointer(),
+ },
+ },
+ }
}
diff --git a/backend/internal/systembackup/service.go b/backend/internal/systembackup/service.go
index 0f99a19b9..e558ce3b7 100644
--- a/backend/internal/systembackup/service.go
+++ b/backend/internal/systembackup/service.go
@@ -83,7 +83,17 @@ type SystemBackupService struct {
jobs *entityjobs.Registry
}
-func NewSystemBackupService(db *database.DB, dockerService *docker.DockerClientService, volumeService *volume.VolumeService, engine *backup.Engine, s3Destinations *s3domain.S3DestinationService, activityService *activity.ActivityService, settingsService *settings.SettingsService, cfg *config.Config, recoveryKeys *backup.RecoveryKeyStore) *SystemBackupService {
+func NewSystemBackupService(
+ db *database.DB,
+ dockerService *docker.DockerClientService,
+ volumeService *volume.VolumeService,
+ engine *backup.Engine,
+ s3Destinations *s3domain.S3DestinationService,
+ activityService *activity.ActivityService,
+ settingsService *settings.SettingsService,
+ cfg *config.Config,
+ recoveryKeys *backup.RecoveryKeyStore,
+) *SystemBackupService {
service := &SystemBackupService{
db: db, dockerService: dockerService, volumeService: volumeService, engine: engine,
s3Destinations: s3Destinations, activityService: activityService, settingsService: settingsService, config: cfg,
@@ -199,8 +209,8 @@ func (s *SystemBackupService) writeManifestInternal(ctx context.Context, backupI
if err != nil {
return fmt.Errorf("failed to encode recovery manifest: %w", err)
}
- if err := os.WriteFile(layout.manifestPathInternal(), data, 0o600); err != nil {
- return fmt.Errorf("failed to write recovery manifest: %w", err)
+ if writeFileErr := os.WriteFile(layout.manifestPathInternal(), data, 0o600); writeFileErr != nil {
+ return fmt.Errorf("failed to write recovery manifest: %w", writeFileErr)
}
return nil
}
@@ -247,7 +257,17 @@ func (s *SystemBackupService) recoveryKeyInternal(ctx context.Context, supplied
// resolveBackupPlanInternal resolves which destinations a run targets, from
// either the policy or the request's destination enum.
-func (s *SystemBackupService) resolveBackupPlanInternal(ctx context.Context, request backuptypes.CreateSystemBackupRequest) (localEnabled, s3Enabled bool, destinationID string, destination backuptypes.SystemBackupDestination, err error) {
+func (
+ s *SystemBackupService,
+) resolveBackupPlanInternal(
+ ctx context.Context,
+ request backuptypes.CreateSystemBackupRequest,
+) (
+ localEnabled, s3Enabled bool,
+ destinationID string,
+ destination backuptypes.SystemBackupDestination,
+ err error,
+) {
destinationID = strings.TrimSpace(request.S3DestinationID)
if request.PolicyID != "" {
policy, policyErr := s.loadPolicyInternal(ctx, request.PolicyID)
@@ -297,7 +317,19 @@ func (s *SystemBackupService) CreateBackup(ctx context.Context, user common.User
return s.createBackupInternal(ctx, trigger, request)
}
-func (s *SystemBackupService) createStagedSystemRecoverySnapshotInternal(ctx context.Context, dockerClient *client.Client, recoveryKey, backupID, destinationID string, localEnabled, s3Enabled bool) (backup.Snapshot, backup.Repository, bool, error) {
+func (
+ s *SystemBackupService,
+) createStagedSystemRecoverySnapshotInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ recoveryKey, backupID, destinationID string,
+ localEnabled, s3Enabled bool,
+) (
+ backup.Snapshot,
+ backup.Repository,
+ bool,
+ error,
+) {
localRepository, err := s.localRepositoryInternal(ctx, dockerClient, false)
var snapshot backup.Snapshot
if err == nil {
@@ -358,8 +390,8 @@ func (s *SystemBackupService) prepareBackupInternal(ctx context.Context, trigger
}
run := &SystemBackupRun{CreatedAt: time.Now().UTC(), Status: SystemBackupStatusRunning, Trigger: trigger, Destination: destination, S3DestinationID: destinationID, PolicyID: request.PolicyID}
run.ID = "system-" + uuid.New().String()
- if err := s.db.WithContext(ctx).Create(run).Error; err != nil {
- return nil, err
+ if createBackupRunErr := s.db.WithContext(ctx).Create(run).Error; createBackupRunErr != nil {
+ return nil, createBackupRunErr
}
checkpoint, err := json.Marshal(systemBackupRecoveryInternal{BackupID: run.ID, LocalEnabled: localEnabled, S3Enabled: s3Enabled})
if err == nil {
@@ -381,8 +413,8 @@ func (s *SystemBackupService) executeBackupInternal(ctx context.Context, prepare
if err != nil {
return run, err
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: run.ID + ":stage", Status: schedulertypes.Running}); err != nil {
- return run, err
+ if progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: run.ID + ":stage", Status: schedulertypes.Running}); progressErr != nil {
+ return run, progressErr
}
stagedSnapshot, stagingRepository, directRemote, err := s.createStagedSystemRecoverySnapshotInternal(
ctx, dockerClient, recoveryKey, run.ID, destinationID, localEnabled, s3Enabled,
@@ -390,13 +422,21 @@ func (s *SystemBackupService) executeBackupInternal(ctx context.Context, prepare
if err != nil {
return run, err
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: run.ID + ":stage", Status: schedulertypes.Succeeded, Message: stagedSnapshot.ID}); err != nil {
- return run, err
+ if startDestinationProgressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "backup_destination",
+ ID: run.ID + ":stage",
+ Status: schedulertypes.Succeeded,
+ Message: stagedSnapshot.ID,
+ },
+ ); startDestinationProgressErr != nil {
+ return run, startDestinationProgressErr
}
if directRemote {
run.RemoteSnapshotID, run.Size = stagedSnapshot.ID, stagedSnapshot.Size
- if err := s.db.WithContext(ctx).Save(run).Error; err != nil {
- return run, err
+ if saveDisabledBackupErr := s.db.WithContext(ctx).Save(run).Error; saveDisabledBackupErr != nil {
+ return run, saveDisabledBackupErr
}
return run, nil
}
@@ -416,16 +456,24 @@ func (s *SystemBackupService) executeBackupInternal(ctx context.Context, prepare
}()
if localEnabled {
run.LocalSnapshotID, run.Size = stagedSnapshot.ID, stagedSnapshot.Size
- if err := s.db.WithContext(ctx).Save(run).Error; err != nil {
- return run, err
+ if saveLocalBackupErr := s.db.WithContext(ctx).Save(run).Error; saveLocalBackupErr != nil {
+ return run, saveLocalBackupErr
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: run.ID + ":local", Status: schedulertypes.Succeeded, Message: stagedSnapshot.ID}); err != nil {
- return run, err
+ if localDestinationProgressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "backup_destination",
+ ID: run.ID + ":local",
+ Status: schedulertypes.Succeeded,
+ Message: stagedSnapshot.ID,
+ },
+ ); localDestinationProgressErr != nil {
+ return run, localDestinationProgressErr
}
}
if s3Enabled {
- if err := s.replicateBackupInternal(ctx, dockerClient, prepared, localRepository, stagedSnapshot); err != nil {
- return run, err
+ if replicateBackupErr := s.replicateBackupInternal(ctx, dockerClient, prepared, localRepository, stagedSnapshot); replicateBackupErr != nil {
+ return run, replicateBackupErr
}
}
return run, nil
@@ -449,7 +497,15 @@ func (s *SystemBackupService) completeBackupInternal(ctx context.Context, run *S
return err
}
-func (s *SystemBackupService) replicateBackupInternal(ctx context.Context, dockerClient *client.Client, prepared *preparedSystemBackupInternal, localRepository backup.Repository, stagedSnapshot backup.Snapshot) error {
+func (
+ s *SystemBackupService,
+) replicateBackupInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ prepared *preparedSystemBackupInternal,
+ localRepository backup.Repository,
+ stagedSnapshot backup.Snapshot,
+) error {
run := prepared.run
remoteRepository, repoErr := s.remoteRepositoryInternal(ctx, run.S3DestinationID)
if repoErr != nil {
@@ -458,7 +514,18 @@ func (s *SystemBackupService) replicateBackupInternal(ctx context.Context, docke
if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: run.ID + ":remote", Status: schedulertypes.Running}); err != nil {
return err
}
- remoteSnapshot, replicateErr := s.engine.Replicate(ctx, dockerClient, localRepository, stagedSnapshot.ID, remoteRepository, prepared.recoveryKey, "arcane-system-recovery", backup.RunSnapshotTag(run.ID))
+ remoteSnapshot, replicateErr := s.engine.Replicate(
+ ctx,
+ dockerClient,
+ localRepository,
+ stagedSnapshot.ID,
+ remoteRepository,
+ prepared.recoveryKey,
+ "arcane-system-recovery",
+ backup.RunSnapshotTag(
+ run.ID,
+ ),
+ )
if replicateErr != nil {
return fmt.Errorf("failed to create S3 system recovery snapshot: %w", replicateErr)
}
@@ -469,20 +536,28 @@ func (s *SystemBackupService) replicateBackupInternal(ctx context.Context, docke
if err := s.db.WithContext(ctx).Save(run).Error; err != nil {
return err
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: run.ID + ":remote", Status: schedulertypes.Succeeded, Message: remoteSnapshot.ID}); err != nil {
+ if err := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "backup_destination",
+ ID: run.ID + ":remote",
+ Status: schedulertypes.Succeeded,
+ Message: remoteSnapshot.ID,
+ },
+ ); err != nil {
return err
}
return nil
}
func (s *SystemBackupService) ListBackups(ctx context.Context, params pagination.QueryParams) ([]backuptypes.SystemBackupRun, pagination.Response, error) {
- var runs []SystemBackupRun
+ var localRuns []SystemBackupRun
query := s.db.WithContext(ctx).Model(&SystemBackupRun{})
if term := strings.TrimSpace(params.Search); term != "" {
pattern := "%" + term + "%"
query = query.Where("status LIKE ? OR trigger LIKE ? OR destination LIKE ? OR error LIKE ?", pattern, pattern, pattern, pattern)
}
- response, err := pagination.PaginateAndSortDB(params, query, &runs)
+ response, err := pagination.PaginateAndSortDB(params, query, &localRuns)
if err != nil {
return nil, pagination.Response{}, fmt.Errorf("failed to list system backups: %w", err)
}
@@ -493,11 +568,11 @@ func (s *SystemBackupService) ListBackups(ctx context.Context, params pagination
}
}
remoteAvailable := backup.RemoteSnapshotChecker(ctx, s.s3Destinations, "arcane-system-recovery")
- result := make([]backuptypes.SystemBackupRun, len(runs))
- for i := range runs {
- runs[i].S3DestinationName = names[runs[i].S3DestinationID].Name
- result[i] = runs[i].ToDTO()
- result[i].RemoteAvailable = remoteAvailable(runs[i].S3DestinationID, runs[i].RemoteSnapshotID)
+ result := make([]backuptypes.SystemBackupRun, len(localRuns))
+ for i := range localRuns {
+ localRuns[i].S3DestinationName = names[localRuns[i].S3DestinationID].Name
+ result[i] = localRuns[i].ToDTO()
+ result[i].RemoteAvailable = remoteAvailable(localRuns[i].S3DestinationID, localRuns[i].RemoteSnapshotID)
}
return result, response, nil
}
@@ -588,7 +663,16 @@ func (session systemBackupSnapshotSessionInternal) inspectReadableSnapshotIntern
return systemBackupSnapshotInternal{systemBackupSnapshotLocationInternal: location, layout: layout}, nil
}
-func (session systemBackupSnapshotSessionInternal) firstReadableSnapshotInternal(ctx context.Context, locations []systemBackupSnapshotLocationInternal, setupErr error) (systemBackupSnapshotInternal, error) {
+func (
+ session systemBackupSnapshotSessionInternal,
+) firstReadableSnapshotInternal(
+ ctx context.Context,
+ locations []systemBackupSnapshotLocationInternal,
+ setupErr error,
+) (
+ systemBackupSnapshotInternal,
+ error,
+) {
inspectErr := setupErr
for _, location := range locations {
snapshot, err := session.inspectReadableSnapshotInternal(ctx, location)
@@ -629,7 +713,17 @@ func (session systemBackupSnapshotSessionInternal) inspectProjectManifestInterna
return snapshot, nil
}
-func (session systemBackupSnapshotSessionInternal) availableProjectSnapshotsInternal(ctx context.Context, locations []systemBackupSnapshotLocationInternal, setupErr error, firstOnly bool) ([]systemBackupSnapshotInternal, error) {
+func (
+ session systemBackupSnapshotSessionInternal,
+) availableProjectSnapshotsInternal(
+ ctx context.Context,
+ locations []systemBackupSnapshotLocationInternal,
+ setupErr error,
+ firstOnly bool,
+) (
+ []systemBackupSnapshotInternal,
+ error,
+) {
snapshots := make([]systemBackupSnapshotInternal, 0, len(locations))
inspectErr := setupErr
for _, location := range locations {
@@ -734,7 +828,16 @@ func (s *SystemBackupService) BrowseBackupFiles(ctx context.Context, id, recover
// openSafetySnapshotInternal resolves the safety run's snapshot in the same
// repository the restore reads from and indexes the project paths it holds.
-func (session systemBackupSnapshotSessionInternal) openSafetySnapshotInternal(ctx context.Context, source systemBackupSnapshotInternal, safetyRun *SystemBackupRun) (systemBackupSafetySnapshotInternal, error) {
+func (
+ session systemBackupSnapshotSessionInternal,
+) openSafetySnapshotInternal(
+ ctx context.Context,
+ source systemBackupSnapshotInternal,
+ safetyRun *SystemBackupRun,
+) (
+ systemBackupSafetySnapshotInternal,
+ error,
+) {
location := source.systemBackupSnapshotLocationInternal
location.name = "safety"
if source.destination == backuptypes.SystemBackupDestinationS3 {
@@ -763,7 +866,14 @@ func removeProjectFileInternal(ctx context.Context, projectsDirectory, selectedP
return acfs.RemoveAll(ctx, projectsDirectory, selectedPath)
}
-func (session systemBackupSnapshotSessionInternal) restoreEntryInternal(ctx context.Context, snapshots []systemBackupSnapshotInternal, selected backuptypes.BackupFileEntry, destination projectsRestoreDestinationInternal) error {
+func (
+ session systemBackupSnapshotSessionInternal,
+) restoreEntryInternal(
+ ctx context.Context,
+ snapshots []systemBackupSnapshotInternal,
+ selected backuptypes.BackupFileEntry,
+ destination projectsRestoreDestinationInternal,
+) error {
var restoreErr error
for _, snapshot := range snapshots {
if !snapshotContainsProjectEntryInternal(snapshot, selected) {
@@ -820,7 +930,14 @@ func safetySnapshotContainsPathInternal(safety systemBackupSafetySnapshotInterna
return false
}
-func (session systemBackupSnapshotSessionInternal) rollbackInternal(ctx context.Context, safety systemBackupSafetySnapshotInternal, selected []backuptypes.BackupFileEntry, destination projectsRestoreDestinationInternal) error {
+func (
+ session systemBackupSnapshotSessionInternal,
+) rollbackInternal(
+ ctx context.Context,
+ safety systemBackupSafetySnapshotInternal,
+ selected []backuptypes.BackupFileEntry,
+ destination projectsRestoreDestinationInternal,
+) error {
var rollbackErr error
for _, selectedEntry := range slices.Backward(selected) {
if !safetySnapshotContainsPathInternal(safety, selectedEntry.Path) {
@@ -845,7 +962,15 @@ func (session systemBackupSnapshotSessionInternal) rollbackInternal(ctx context.
return rollbackErr
}
-func (session systemBackupSnapshotSessionInternal) restoreSelectedInternal(ctx context.Context, snapshots []systemBackupSnapshotInternal, safety systemBackupSafetySnapshotInternal, selected []backuptypes.BackupFileEntry, destination projectsRestoreDestinationInternal) error {
+func (
+ session systemBackupSnapshotSessionInternal,
+) restoreSelectedInternal(
+ ctx context.Context,
+ snapshots []systemBackupSnapshotInternal,
+ safety systemBackupSafetySnapshotInternal,
+ selected []backuptypes.BackupFileEntry,
+ destination projectsRestoreDestinationInternal,
+) error {
restored := make([]backuptypes.BackupFileEntry, 0, len(selected))
for _, selectedEntry := range selected {
if err := session.restoreEntryInternal(ctx, snapshots, selectedEntry, destination); err != nil {
@@ -951,10 +1076,10 @@ func (s *SystemBackupService) DeleteBackup(ctx context.Context, id, recoveryKey
}
// deleteRunsInternal forgets snapshots grouped by repository under the caller's run lease.
-func (s *SystemBackupService) deleteRunsInternal(ctx context.Context, runs []*SystemBackupRun, recoveryKey string, includeRemote bool) error {
+func (s *SystemBackupService) deleteRunsInternal(ctx context.Context, localRuns2 []*SystemBackupRun, recoveryKey string, includeRemote bool) error {
var localRuns []*SystemBackupRun
remoteGroups := make(map[string][]*SystemBackupRun)
- for _, run := range runs {
+ for _, run := range localRuns2 {
if run.LocalSnapshotID != "" {
localRuns = append(localRuns, run)
}
@@ -979,10 +1104,10 @@ func (s *SystemBackupService) deleteRunsInternal(ctx context.Context, runs []*Sy
for destinationID, group := range remoteGroups {
deleteErr = errors.Join(deleteErr, s.forgetRemoteSnapshotsInternal(ctx, dockerClient, key, destinationID, group))
}
- for _, run := range runs {
+ for _, run := range localRuns2 {
if run.LocalSnapshotID == "" && run.RemoteSnapshotID == "" {
- if err := s.db.WithContext(ctx).Delete(run).Error; err != nil {
- deleteErr = errors.Join(deleteErr, fmt.Errorf("failed to delete system backup record: %w", err))
+ if deleteBackupRunErr := s.db.WithContext(ctx).Delete(run).Error; deleteBackupRunErr != nil {
+ deleteErr = errors.Join(deleteErr, fmt.Errorf("failed to delete system backup record: %w", deleteBackupRunErr))
}
continue
}
@@ -993,12 +1118,12 @@ func (s *SystemBackupService) deleteRunsInternal(ctx context.Context, runs []*Sy
return deleteErr
}
-func (s *SystemBackupService) forgetLocalSnapshotsInternal(ctx context.Context, dockerClient *client.Client, key string, runs []*SystemBackupRun) error {
- if len(runs) == 0 {
+func (s *SystemBackupService) forgetLocalSnapshotsInternal(ctx context.Context, dockerClient *client.Client, key string, localRuns []*SystemBackupRun) error {
+ if len(localRuns) == 0 {
return nil
}
- snapshotIDs := make([]string, len(runs))
- for index, run := range runs {
+ snapshotIDs := make([]string, len(localRuns))
+ for index, run := range localRuns {
snapshotIDs[index] = run.LocalSnapshotID
}
repository, repoErr := s.localRepositoryInternal(ctx, dockerClient, false)
@@ -1008,15 +1133,15 @@ func (s *SystemBackupService) forgetLocalSnapshotsInternal(ctx context.Context,
if repoErr != nil {
return fmt.Errorf("failed to delete local snapshots: %w", repoErr)
}
- for _, run := range runs {
+ for _, run := range localRuns {
run.LocalSnapshotID = ""
}
return nil
}
-func (s *SystemBackupService) forgetRemoteSnapshotsInternal(ctx context.Context, dockerClient *client.Client, key, destinationID string, runs []*SystemBackupRun) error {
- snapshotIDs := make([]string, len(runs))
- for index, run := range runs {
+func (s *SystemBackupService) forgetRemoteSnapshotsInternal(ctx context.Context, dockerClient *client.Client, key, destinationID string, localRuns []*SystemBackupRun) error {
+ snapshotIDs := make([]string, len(localRuns))
+ for index, run := range localRuns {
snapshotIDs[index] = run.RemoteSnapshotID
}
repository, repoErr := s.remoteRepositoryInternal(ctx, destinationID)
@@ -1026,7 +1151,7 @@ func (s *SystemBackupService) forgetRemoteSnapshotsInternal(ctx context.Context,
if repoErr != nil {
return fmt.Errorf("failed to delete S3 snapshots: %w", repoErr)
}
- for _, run := range runs {
+ for _, run := range localRuns {
run.RemoteSnapshotID, run.S3DestinationID = "", ""
}
return nil
@@ -1050,10 +1175,10 @@ func (s *SystemBackupService) DiscoverRemoteBackups(ctx context.Context, request
return 0, fmt.Errorf("failed to open system recovery repository: %w", err)
}
var knownIDs []string
- if err := s.db.WithContext(ctx).Model(&SystemBackupRun{}).
+ if loadSnapshotIDsErr := s.db.WithContext(ctx).Model(&SystemBackupRun{}).
Where("s3_destination_id = ? AND remote_snapshot_id <> ''", request.S3DestinationID).
- Pluck("remote_snapshot_id", &knownIDs).Error; err != nil {
- return 0, err
+ Pluck("remote_snapshot_id", &knownIDs).Error; loadSnapshotIDsErr != nil {
+ return 0, loadSnapshotIDsErr
}
known := make(map[string]struct{}, len(knownIDs))
for _, id := range knownIDs {
@@ -1077,8 +1202,8 @@ func (s *SystemBackupService) DiscoverRemoteBackups(ctx context.Context, request
RemoteSnapshotID: snapshot.ID, S3DestinationID: request.S3DestinationID,
}
run.ID = fmt.Sprintf("remote-%s-%s", request.S3DestinationID, snapshot.ID)
- if err := s.db.WithContext(ctx).Create(run).Error; err != nil {
- return created, fmt.Errorf("failed to save discovered system backup: %w", err)
+ if createDiscoveredBackupErr := s.db.WithContext(ctx).Create(run).Error; createDiscoveredBackupErr != nil {
+ return created, fmt.Errorf("failed to save discovered system backup: %w", createDiscoveredBackupErr)
}
created++
}
@@ -1129,8 +1254,8 @@ func (s *SystemBackupService) UploadBackup(ctx context.Context, id string, reque
}
run.RemoteSnapshotID, run.S3DestinationID = snapshot.ID, request.S3DestinationID
run.Destination = backuptypes.SystemBackupDestinationLocalS3
- if err := s.db.WithContext(ctx).Save(run).Error; err != nil {
- return nil, fmt.Errorf("failed to save uploaded system backup: %w", err)
+ if saveUploadedBackupErr := s.db.WithContext(ctx).Save(run).Error; saveUploadedBackupErr != nil {
+ return nil, fmt.Errorf("failed to save uploaded system backup: %w", saveUploadedBackupErr)
}
return run, nil
}
@@ -1218,8 +1343,8 @@ func (s *SystemBackupService) RestoreBackup(ctx context.Context, id, recoveryKey
return fmt.Errorf("encode recovery request: %w", err)
}
requestFile := path.Join("/app/data", systemRecoveryRequestName)
- if err := os.WriteFile(requestFile, requestData, 0o600); err != nil {
- return fmt.Errorf("write recovery request: %w", err)
+ if writeFileErr := os.WriteFile(requestFile, requestData, 0o600); writeFileErr != nil {
+ return fmt.Errorf("write recovery request: %w", writeFileErr)
}
cleanupRequest := true
defer func() {
@@ -1231,7 +1356,10 @@ func (s *SystemBackupService) RestoreBackup(ctx context.Context, id, recoveryKey
func(ctx context.Context, containerPath string) (string, error) {
return projects.GetHostPathForContainerPath(ctx, dockerClient, containerPath)
},
- func() bool { _, err := cgroup.CurrentContainerID(); return err == nil },
+ func() bool {
+ _, currentContainerIDErr := cgroup.CurrentContainerID()
+ return currentContainerIDErr == nil
+ },
func(ctx context.Context, inspect *containertypes.InspectResponse, dockerHost string) string {
return dockerutil.SelectDockerHostReachableNetworkMode(ctx, dockerClient, inspect, dockerHost)
},
@@ -1269,9 +1397,9 @@ func (s *SystemBackupService) RestoreBackup(ctx context.Context, id, recoveryKey
if err != nil {
return fmt.Errorf("create recovery helper container: %w", err)
}
- if _, err := dockerClient.ContainerStart(ctx, created.ID, client.ContainerStartOptions{}); err != nil {
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, created.ID, client.ContainerStartOptions{}); containerStartErr != nil {
_, _ = dockerClient.ContainerRemove(ctx, created.ID, client.ContainerRemoveOptions{Force: true})
- return fmt.Errorf("start recovery helper container: %w", err)
+ return fmt.Errorf("start recovery helper container: %w", containerStartErr)
}
cleanupRequest = false
return nil
@@ -1337,28 +1465,28 @@ func (s *SystemBackupService) SetRecoveryKey(ctx context.Context, recoveryKey st
}
if configured {
if current, keyErr := s.recoveryKeyInternal(ctx, ""); keyErr == nil && current != recoveryKey {
- var runs int64
- if err := s.db.WithContext(ctx).Model(&SystemBackupRun{}).Count(&runs).Error; err != nil {
- return nil, err
+ var localRuns int64
+ if countLocalBackupsErr := s.db.WithContext(ctx).Model(&SystemBackupRun{}).Count(&localRuns).Error; countLocalBackupsErr != nil {
+ return nil, countLocalBackupsErr
}
- if runs > 0 {
+ if localRuns > 0 {
return nil, errors.New("delete the existing system backups before replacing the recovery key; they can only be opened with the current key")
}
var volumeBackups int64
- if err := s.db.WithContext(ctx).Model(&volume.VolumeBackup{}).Where("format = ?", volume.VolumeBackupFormatRustic).Count(&volumeBackups).Error; err != nil {
- return nil, err
+ if countVolumeBackupsErr := s.db.WithContext(ctx).Model(&volume.VolumeBackup{}).Where("format = ?", volume.VolumeBackupFormatRustic).Count(&volumeBackups).Error; countVolumeBackupsErr != nil {
+ return nil, countVolumeBackupsErr
}
if volumeBackups > 0 {
return nil, errors.New("delete the existing volume backups before replacing the recovery key; they can only be opened with the current key")
}
}
}
- if err := s.recoveryKeys.Set(ctx, recoveryKey); err != nil {
- return nil, err
+ if setErr := s.recoveryKeys.Set(ctx, recoveryKey); setErr != nil {
+ return nil, setErr
}
if s.volumeService != nil {
- if err := s.volumeService.MigrateRepositoryPasswords(ctx); err != nil {
- slog.WarnContext(ctx, "failed to re-key volume backup repositories to the recovery key", "error", err.Error())
+ if migrateRepositoryPasswordsErr := s.volumeService.MigrateRepositoryPasswords(ctx); migrateRepositoryPasswordsErr != nil {
+ slog.WarnContext(ctx, "failed to re-key volume backup repositories to the recovery key", "error", migrateRepositoryPasswordsErr.Error())
}
}
return &backuptypes.SystemBackupRecoveryKeyStatus{Configured: true}, nil
@@ -1433,8 +1561,8 @@ func (s *SystemBackupService) UpdatePolicies(ctx context.Context, updates []back
Unregister: s.jobs.Unregister,
Reschedule: s.rescheduleSystemBackupPolicyInternal,
}
- if err := reconcile.Run(ctx, updates); err != nil {
- return nil, err
+ if runErr := reconcile.Run(ctx, updates); runErr != nil {
+ return nil, runErr
}
return s.GetPolicies(ctx)
}
@@ -1540,9 +1668,9 @@ func (s *SystemBackupService) rescheduleSystemBackupPolicyInternal(ctx context.C
return outcome, err
}
if current != nil && current.RetentionCount > 0 {
- if err := s.applyRetentionInternal(ctx, current.ID, current.RetentionCount, current.S3Enabled); err != nil {
+ if applyRetentionErr := s.applyRetentionInternal(ctx, current.ID, current.RetentionCount, current.S3Enabled); applyRetentionErr != nil {
outcome.Status = schedulertypes.Partial
- return outcome, err
+ return outcome, applyRetentionErr
}
}
return outcome, nil
@@ -1585,11 +1713,11 @@ func (s *SystemBackupService) applyRetentionInternal(ctx context.Context, policy
return ErrSystemBackupAlreadyRunning
}
defer lease.Release(ctx)
- var runs []*SystemBackupRun
- if err := s.db.WithContext(ctx).Where("id IN ?", expired).Find(&runs).Error; err != nil {
- return err
+ var localRuns []*SystemBackupRun
+ if loadExpiredBackupsErr := s.db.WithContext(ctx).Where("id IN ?", expired).Find(&localRuns).Error; loadExpiredBackupsErr != nil {
+ return loadExpiredBackupsErr
}
- return s.deleteRunsInternal(ctx, runs, "", includeRemote)
+ return s.deleteRunsInternal(ctx, localRuns, "", includeRemote)
}
func (s *SystemBackupService) disableMissingS3Internal(ctx context.Context, policy *SystemBackupPolicy) (bool, error) {
@@ -1740,7 +1868,10 @@ func (s *SystemBackupService) backupSourceLayoutInternal(ctx context.Context, do
var (
errProjectsOutsideDataInternal = errors.New("the backup-time projects directory is outside Arcane's system backup data")
- errProjectsNotInBackupInternal = errors.New("this system backup does not include the projects directory because it was created before Arcane backed up separately mounted projects; create a new system backup to restore project files")
+ errProjectsNotInBackupInternal = errors.New(
+ "this system backup does not include the projects directory because it was created before Arcane " +
+ "backed up separately mounted projects; create a new system backup to restore project files",
+ )
manifestCandidateRootsInternal = []string{snapshotDataPath, "/", "/app/data"}
)
@@ -1994,7 +2125,16 @@ func (s *SystemBackupService) projectsRestoreDestinationInternal(ctx context.Con
// and projects into the current container layout. Projects get their own
// stage unless the snapshot already holds them at their current place under
// the data root.
-func restoreStagesInternal(mounts []containertypes.MountPoint, dataDirectory, projectsDirectory string, repository recoverytypes.RestoreRepository, snapshotID string, layout snapshotLayoutInternal) ([]recoverytypes.RestoreStage, error) {
+func restoreStagesInternal(
+ mounts []containertypes.MountPoint,
+ dataDirectory, projectsDirectory string,
+ repository recoverytypes.RestoreRepository,
+ snapshotID string,
+ layout snapshotLayoutInternal,
+) (
+ []recoverytypes.RestoreStage,
+ error,
+) {
separate := layout.projectsIncludedInternal() && !layout.projectsCoveredByDataInternal(dataDirectory, projectsDirectory)
if separate && layout.projectsPath == layout.dataPath {
return nil, fmt.Errorf("the backup keeps projects in Arcane's data directory; set the projects directory to %s before a full restore, or restore individual project files instead", dataDirectory)
diff --git a/backend/internal/systembackup/service_test.go b/backend/internal/systembackup/service_test.go
index 8ee5043bd..00787c685 100644
--- a/backend/internal/systembackup/service_test.go
+++ b/backend/internal/systembackup/service_test.go
@@ -3,7 +3,6 @@ package systembackup
import (
"context"
"encoding/json/v2"
- "errors"
"net/http"
"net/http/httptest"
"os"
@@ -87,16 +86,16 @@ func TestSystemBackupPoliciesRegisterIndependentJobs(t *testing.T) {
jobs: entityjobs.New("system-backup:", backup.SystemAdmissionScope),
}
scheduler := &systemBackupPolicySchedulerInternal{jobs: make(map[string]schedulertypes.Job)}
- require.NoError(t, service.SetScheduler(context.Background(), scheduler, newSystemBackupAdmissionGateForTestInternal(t)))
+ require.NoError(t, service.SetScheduler(t.Context(), scheduler, newSystemBackupAdmissionGateForTestInternal(t)))
- status, err := service.SetRecoveryKey(context.Background(), "QWERTY-ABCDEF-234567-GHIJKL-MNOPQR-STUVWX-YZ2345-ZXCVBN")
+ status, err := service.SetRecoveryKey(t.Context(), "QWERTY-ABCDEF-234567-GHIJKL-MNOPQR-STUVWX-YZ2345-ZXCVBN")
require.NoError(t, err)
require.True(t, status.Configured)
- storedKey, err := service.recoveryKeyInternal(context.Background(), "")
+ storedKey, err := service.recoveryKeyInternal(t.Context(), "")
require.NoError(t, err)
require.Equal(t, "QWERTY-ABCDEF-234567-GHIJKL-MNOPQR-STUVWX-YZ2345-ZXCVBN", storedKey)
- collection, err := service.UpdatePolicies(context.Background(), []backuptypes.UpdateSystemBackupPolicy{
+ collection, err := service.UpdatePolicies(t.Context(), []backuptypes.UpdateSystemBackupPolicy{
{Enabled: true, Schedule: "0 0 2 * * *", RetentionCount: 5, LocalEnabled: true},
{Enabled: true, Schedule: "0 0 14 * * *", RetentionCount: 30, LocalEnabled: true},
})
@@ -106,7 +105,7 @@ func TestSystemBackupPoliciesRegisterIndependentJobs(t *testing.T) {
require.Len(t, scheduler.jobs, 2)
firstID := collection.Policies[0].ID
- collection, err = service.UpdatePolicies(context.Background(), []backuptypes.UpdateSystemBackupPolicy{{
+ collection, err = service.UpdatePolicies(t.Context(), []backuptypes.UpdateSystemBackupPolicy{{
ID: firstID, Enabled: true, Schedule: "0 */30 * * * *", RetentionCount: 9, LocalEnabled: true,
}})
require.NoError(t, err)
@@ -132,8 +131,8 @@ func TestSystemBackupPoliciesRegisterIndependentJobs(t *testing.T) {
require.NoError(t, gormDB.Create(policy).Error)
require.NoError(t, gormDB.Model(policy).Update("local_enabled", local).Error)
service.rescheduleSystemBackupPolicyInternal(t.Context(), policy)
- disabled, err := service.disableMissingS3Internal(t.Context(), policy)
- require.NoError(t, err)
+ disabled, disableMissingS3Err := service.disableMissingS3Internal(t.Context(), policy)
+ require.NoError(t, disableMissingS3Err)
require.True(t, disabled)
require.NoError(t, gormDB.First(policy, "id = ?", policy.ID).Error)
require.Equal(t, local, policy.Enabled)
@@ -152,7 +151,7 @@ func TestSystemBackupPolicyRequiresConfiguredRecoveryKeyWhenEnabled(t *testing.T
recoveryKeys: backup.NewRecoveryKeyStore(&database.DB{DB: gormDB}),
}
- _, err = service.UpdatePolicies(context.Background(), []backuptypes.UpdateSystemBackupPolicy{{
+ _, err = service.UpdatePolicies(t.Context(), []backuptypes.UpdateSystemBackupPolicy{{
Enabled: true, Schedule: "0 0 2 * * *", RetentionCount: 7, LocalEnabled: true,
}})
require.ErrorContains(t, err, "configure a recovery key")
@@ -166,7 +165,7 @@ func TestRecoveryEnvironmentInternalIncludesRuntimeSecrets(t *testing.T) {
OidcClientSecret: "oidc-secret",
FilePerm: 0o640,
}
- environment := (&SystemBackupService{config: cfg}).recoveryEnvironmentInternal(context.Background())
+ environment := (&SystemBackupService{config: cfg}).recoveryEnvironmentInternal(t.Context())
require.Equal(t, "jwt-secret", environment["JWT_SECRET"])
require.Equal(t, "encryption-secret", environment["ENCRYPTION_KEY"])
require.Equal(t, "admin-key", environment["ADMIN_STATIC_API_KEY"])
@@ -416,8 +415,8 @@ func TestProjectsSnapshotPathInternal(t *testing.T) {
func TestProjectsDirectoryInternalUsesContainerPathOfMapping(t *testing.T) {
service := &SystemBackupService{config: &config.Config{ProjectsDirectory: "/app/data/projects:/host/projects"}}
- require.Equal(t, "/app/data/projects", service.projectsDirectoryInternal(context.Background()))
- require.Equal(t, "/app/data/projects:/host/projects", service.projectsSettingInternal(context.Background()))
+ require.Equal(t, "/app/data/projects", service.projectsDirectoryInternal(t.Context()))
+ require.Equal(t, "/app/data/projects:/host/projects", service.projectsSettingInternal(t.Context()))
}
func TestSourceMountsInternal(t *testing.T) {
@@ -449,7 +448,7 @@ func TestWriteManifestInternalRecordsVersionTwoLayout(t *testing.T) {
dataDirectory := t.TempDir()
service := &SystemBackupService{config: &config.Config{DatabaseURL: "file:" + filepath.Join(dataDirectory, "arcane.db"), ProjectsDirectory: "/srv/projects"}}
layout := backupSourceLayoutInternal{dataDirectory: dataDirectory, projectsDirectory: "/srv/projects", databaseName: "arcane.db", projectsPath: "/projects"}
- require.NoError(t, service.writeManifestInternal(context.Background(), "backup-1", layout))
+ require.NoError(t, service.writeManifestInternal(t.Context(), "backup-1", layout))
data, err := os.ReadFile(filepath.Join(dataDirectory, systemRecoveryManifestName))
require.NoError(t, err)
var manifest recoverytypes.Manifest
@@ -501,7 +500,24 @@ func TestRestoreStagesInternal(t *testing.T) {
layout := snapshotLayoutInternal{dataPath: "/data", projectsPath: "/data/projects", databaseName: "arcane.db"}
stages, err := restoreStagesInternal(mounts, "/app/data", "/app/data/projects", repository, "snap", layout)
require.NoError(t, err)
- require.Equal(t, []recoverytypes.RestoreStage{{Repository: repository, SnapshotID: "snap", SourcePath: "/data", Target: recoverytypes.RestoreTarget{Mounts: []mounttypes.Mount{dataVolume, nested}, Path: "/restore"}}}, stages)
+ require.Equal(
+ t,
+ []recoverytypes.RestoreStage{
+ {
+ Repository: repository,
+ SnapshotID: "snap",
+ SourcePath: "/data",
+ Target: recoverytypes.RestoreTarget{
+ Mounts: []mounttypes.Mount{
+ dataVolume,
+ nested,
+ },
+ Path: "/restore",
+ },
+ },
+ },
+ stages,
+ )
})
t.Run("external projects restore separately", func(t *testing.T) {
layout := snapshotLayoutInternal{dataPath: "/data", projectsPath: "/projects", databaseName: "arcane.db"}
@@ -511,7 +527,20 @@ func TestRestoreStagesInternal(t *testing.T) {
require.Equal(t, "/data", stages[0].SourcePath)
require.Equal(t, []mounttypes.Mount{dataVolume, nested}, stages[0].Target.Mounts)
require.Equal(t, "/projects", stages[1].SourcePath)
- require.Equal(t, recoverytypes.RestoreTarget{Mounts: []mounttypes.Mount{{Type: mounttypes.TypeBind, Source: "/host/external", Target: "/restore-projects"}}, Path: "/restore-projects"}, stages[1].Target)
+ require.Equal(
+ t,
+ recoverytypes.RestoreTarget{
+ Mounts: []mounttypes.Mount{
+ {
+ Type: mounttypes.TypeBind,
+ Source: "/host/external",
+ Target: "/restore-projects",
+ },
+ },
+ Path: "/restore-projects",
+ },
+ stages[1].Target,
+ )
})
t.Run("changed projects directory excludes the nested mount from the data stage", func(t *testing.T) {
layout := snapshotLayoutInternal{dataPath: "/", projectsPath: "/projects", databaseName: "arcane.db"}
@@ -525,13 +554,39 @@ func TestRestoreStagesInternal(t *testing.T) {
require.NoError(t, err)
require.Len(t, stages, 2)
require.Equal(t, []mounttypes.Mount{dataVolume}, stages[0].Target.Mounts)
- require.Equal(t, recoverytypes.RestoreTarget{Mounts: []mounttypes.Mount{{Type: mounttypes.TypeBind, Source: "/host/nested", Target: "/restore-projects"}}, Path: "/restore-projects"}, stages[1].Target)
+ require.Equal(
+ t,
+ recoverytypes.RestoreTarget{
+ Mounts: []mounttypes.Mount{
+ {
+ Type: mounttypes.TypeBind,
+ Source: "/host/nested",
+ Target: "/restore-projects",
+ },
+ },
+ Path: "/restore-projects",
+ },
+ stages[1].Target,
+ )
stages, err = restoreStagesInternal(mounts, "/app/data", "/app/data/custom/projects", repository, "snap", external)
require.NoError(t, err)
require.Len(t, stages, 2)
require.Equal(t, []mounttypes.Mount{dataVolume, nested}, stages[0].Target.Mounts)
- require.Equal(t, recoverytypes.RestoreTarget{Mounts: []mounttypes.Mount{{Type: mounttypes.TypeVolume, Source: "arcane-data", Target: "/restore-projects"}}, Path: "/restore-projects/custom/projects"}, stages[1].Target)
+ require.Equal(
+ t,
+ recoverytypes.RestoreTarget{
+ Mounts: []mounttypes.Mount{
+ {
+ Type: mounttypes.TypeVolume,
+ Source: "arcane-data",
+ Target: "/restore-projects",
+ },
+ },
+ Path: "/restore-projects/custom/projects",
+ },
+ stages[1].Target,
+ )
})
t.Run("version 1 backup without projects restores data only", func(t *testing.T) {
layout := snapshotLayoutInternal{dataPath: "/app/data", databaseName: "arcane.db"}
@@ -561,10 +616,9 @@ func TestSafetySnapshotContainsPathInternal(t *testing.T) {
require.True(t, safetySnapshotContainsPathInternal(safety, "demo"))
require.True(t, safetySnapshotContainsPathInternal(safety, "demo/compose.yaml"))
require.False(t, safetySnapshotContainsPathInternal(safety, "other"))
- require.ErrorContains(t, removeProjectFileInternal(context.Background(), t.TempDir(), ""), "refusing to remove")
+ require.ErrorContains(t, removeProjectFileInternal(t.Context(), t.TempDir(), ""), "refusing to remove")
}
func TestLegacyLayoutOmittedProjectsIsActionable(t *testing.T) {
- require.True(t, errors.Is(errProjectsNotInBackupInternal, errProjectsNotInBackupInternal))
require.Contains(t, errProjectsNotInBackupInternal.Error(), "create a new system backup")
}
diff --git a/backend/internal/systembackup/snapshot.go b/backend/internal/systembackup/snapshot.go
index f728f97cc..4d70cece2 100644
--- a/backend/internal/systembackup/snapshot.go
+++ b/backend/internal/systembackup/snapshot.go
@@ -17,7 +17,17 @@ import (
)
// snapshotWithStagedDatabaseInternal archives a consistent database without blocking actor leases during the upload.
-func (s *SystemBackupService) snapshotWithStagedDatabaseInternal(ctx context.Context, dockerClient *client.Client, repository backup.Repository, recoveryKey, backupID string) (backup.Snapshot, error) {
+func (
+ s *SystemBackupService,
+) snapshotWithStagedDatabaseInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ repository backup.Repository,
+ recoveryKey, backupID string,
+) (
+ backup.Snapshot,
+ error,
+) {
layout, err := s.backupSourceLayoutInternal(ctx, dockerClient)
if err != nil {
return backup.Snapshot{}, err
@@ -34,8 +44,8 @@ func (s *SystemBackupService) snapshotWithStagedDatabaseInternal(ctx context.Con
databasePath := filepath.Join(layout.dataDirectory, layout.databaseName)
stagedDatabase := filepath.Join(stage, layout.databaseName)
snapshotDatabase := filepath.Join(snapshotDataPath, layout.databaseName)
- if err := s.writeManifestInternal(ctx, backupID, layout); err != nil {
- return backup.Snapshot{}, err
+ if writeManifestErr := s.writeManifestInternal(ctx, backupID, layout); writeManifestErr != nil {
+ return backup.Snapshot{}, writeManifestErr
}
defer func() { _ = os.Remove(layout.manifestPathInternal()) }()
layout.excludes = []string{
@@ -46,8 +56,8 @@ func (s *SystemBackupService) snapshotWithStagedDatabaseInternal(ctx context.Con
if err != nil {
return backup.Snapshot{}, err
}
- if err := stageSystemDatabaseInternal(ctx, sqlDB, databasePath, stagedDatabase); err != nil {
- return backup.Snapshot{}, err
+ if stageSystemDatabaseErr := stageSystemDatabaseInternal(ctx, sqlDB, databasePath, stagedDatabase); stageSystemDatabaseErr != nil {
+ return backup.Snapshot{}, stageSystemDatabaseErr
}
mounts, inContainer, err := currentMountsInternal(ctx, dockerClient)
if err != nil {
@@ -106,9 +116,9 @@ func snapshotSourceFilesInternal(ctx context.Context, layout backupSourceLayoutI
return nil
}
for _, excluded := range layout.excludes {
- matched, err := filepath.Match(excluded, relative)
- if err != nil {
- return err
+ matched, matchErr := filepath.Match(excluded, relative)
+ if matchErr != nil {
+ return matchErr
}
if !matched {
continue
@@ -156,16 +166,16 @@ func stageSystemDatabaseInternal(ctx context.Context, db *sql.DB, databasePath,
if err != nil {
return err
}
- if _, err := db.ExecContext(ctx, "VACUUM INTO ?", stagedDatabase); err != nil {
- return fmt.Errorf("stage Arcane database: %w", err)
+ if _, execContextErr := db.ExecContext(ctx, "VACUUM INTO ?", stagedDatabase); execContextErr != nil {
+ return fmt.Errorf("stage Arcane database: %w", execContextErr)
}
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
- if err := os.Chown(stagedDatabase, int(stat.Uid), int(stat.Gid)); err != nil {
- return fmt.Errorf("preserve staged database ownership: %w", err)
+ if chownErr := os.Chown(stagedDatabase, int(stat.Uid), int(stat.Gid)); chownErr != nil {
+ return fmt.Errorf("preserve staged database ownership: %w", chownErr)
}
}
- if err := os.Chmod(stagedDatabase, info.Mode()); err != nil {
- return fmt.Errorf("preserve staged database permissions: %w", err)
+ if chmodErr := os.Chmod(stagedDatabase, info.Mode()); chmodErr != nil {
+ return fmt.Errorf("preserve staged database permissions: %w", chmodErr)
}
return nil
}
diff --git a/backend/internal/systembackup/system_volume.go b/backend/internal/systembackup/system_volume.go
index 7ce079933..7891bcd49 100644
--- a/backend/internal/systembackup/system_volume.go
+++ b/backend/internal/systembackup/system_volume.go
@@ -30,7 +30,12 @@ const (
systemVolumeBackupJobPrefix = "volumes:"
defaultSystemVolumeSchedule = "0 0 2 * * *"
- backupHistoryUnionInternal = `SELECT id, size, created_at, status, trigger, destination, '' AS format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, 'system' AS type, 'system' AS resource_type, 'Arcane' AS resource_name FROM system_backup_runs UNION ALL SELECT id, size, created_at, status, trigger, destination, format, local_snapshot_id, remote_snapshot_id, s3_destination_id, policy_id, error, CASE WHEN policy_id LIKE 'system-volume:%' THEN 'system' ELSE 'volume' END AS type, 'volume' AS resource_type, volume_name AS resource_name FROM volume_backups`
+ backupHistoryUnionInternal = "SELECT id, size, created_at, status, trigger, destination, '' AS format, local_snapshot_id, " +
+ "remote_snapshot_id, s3_destination_id, policy_id, error, 'system' AS type, 'system' AS " +
+ "resource_type, 'Arcane' AS resource_name FROM system_backup_runs UNION ALL SELECT id, size, " +
+ "created_at, status, trigger, destination, format, local_snapshot_id, remote_snapshot_id, " +
+ "s3_destination_id, policy_id, error, CASE WHEN policy_id LIKE 'system-volume:%' THEN 'system' ELSE " +
+ "'volume' END AS type, 'volume' AS resource_type, volume_name AS resource_name FROM volume_backups"
)
func (s *SystemBackupService) loadSystemVolumeBackupPoliciesInternal() (*backuptypes.SystemVolumeBackupPolicyCollection, error) {
@@ -160,8 +165,8 @@ func (s *SystemBackupService) UpdateSystemVolumeBackupConfig(ctx context.Context
},
Reschedule: s.rescheduleSystemVolumeBackupInternal,
}
- if err := reconcile.Run(ctx, updates); err != nil {
- return nil, err
+ if runErr := reconcile.Run(ctx, updates); runErr != nil {
+ return nil, runErr
}
return s.GetSystemVolumeBackupConfig(ctx)
}
@@ -257,7 +262,10 @@ func (s *SystemBackupService) resolveSystemVolumeRunPolicyInternal(ctx context.C
return *policy, false, nil
}
custom := request.Custom
- if custom != nil && custom.Destination != backuptypes.SystemBackupDestinationLocal && custom.Destination != backuptypes.SystemBackupDestinationS3 && custom.Destination != backuptypes.SystemBackupDestinationLocalS3 {
+ if custom != nil &&
+ custom.Destination != backuptypes.SystemBackupDestinationLocal &&
+ custom.Destination != backuptypes.SystemBackupDestinationS3 &&
+ custom.Destination != backuptypes.SystemBackupDestinationLocalS3 {
return backuptypes.SystemVolumeBackupPolicy{}, false, errors.New("destination must be local, s3, or local_s3")
}
policy, err := s.normalizeSystemVolumePolicyUpdateInternal(ctx, customSystemVolumePolicyInternal(custom))
@@ -271,7 +279,16 @@ type preparedSystemVolumeBackupInternal struct {
lease *runs.Lease
}
-func (s *SystemBackupService) runSystemVolumeBackupsInternal(ctx context.Context, request backuptypes.RunSystemVolumeBackupsRequest, trigger volume.VolumeBackupTrigger) (*backuptypes.SystemVolumeBackupRunResult, error) {
+func (
+ s *SystemBackupService,
+) runSystemVolumeBackupsInternal(
+ ctx context.Context,
+ request backuptypes.RunSystemVolumeBackupsRequest,
+ trigger volume.VolumeBackupTrigger,
+) (
+ *backuptypes.SystemVolumeBackupRunResult,
+ error,
+) {
prepared, err := s.prepareSystemVolumeBackupsInternal(ctx, request)
if err != nil {
return nil, err
@@ -281,8 +298,16 @@ func (s *SystemBackupService) runSystemVolumeBackupsInternal(ctx context.Context
if err != nil {
return nil, err
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_plan", ID: "system-volume-plan", Status: schedulertypes.Succeeded, RecoveryData: frozen}); err != nil {
- return nil, err
+ if progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "backup_plan",
+ ID: "system-volume-plan",
+ Status: schedulertypes.Succeeded,
+ RecoveryData: frozen,
+ },
+ ); progressErr != nil {
+ return nil, progressErr
}
return s.executeSystemVolumeBackupsInternal(ctx, prepared.policy, prepared.manualPolicy, prepared.candidates, trigger, "")
}
@@ -311,7 +336,19 @@ func (s *SystemBackupService) prepareSystemVolumeBackupsInternal(ctx context.Con
return &preparedSystemVolumeBackupInternal{policy: policyConfig, manualPolicy: manualPolicy, candidates: candidates, lease: lease}, nil
}
-func (s *SystemBackupService) executeSystemVolumeBackupsInternal(ctx context.Context, policyConfig backuptypes.SystemVolumeBackupPolicy, manualPolicy bool, candidates []backuptypes.SystemVolumeBackupOption, trigger volume.VolumeBackupTrigger, activityID string) (result *backuptypes.SystemVolumeBackupRunResult, err error) {
+func (
+ s *SystemBackupService,
+) executeSystemVolumeBackupsInternal(
+ ctx context.Context,
+ policyConfig backuptypes.SystemVolumeBackupPolicy,
+ manualPolicy bool,
+ candidates []backuptypes.SystemVolumeBackupOption,
+ trigger volume.VolumeBackupTrigger,
+ activityID string,
+) (
+ result *backuptypes.SystemVolumeBackupRunResult,
+ err error,
+) {
result = &backuptypes.SystemVolumeBackupRunResult{
Matched: len(candidates), Failures: make([]backuptypes.SystemVolumeBackupFailure, 0),
}
@@ -333,8 +370,8 @@ func (s *SystemBackupService) executeSystemVolumeBackupsInternal(ctx context.Con
result.Skipped++
continue
}
- if err := ctx.Err(); err != nil {
- return result, err
+ if cancellationErr := ctx.Err(); cancellationErr != nil {
+ return result, cancellationErr
}
s.updateSystemVolumeProgressInternal(ctx, activityID, policyConfig.ID, candidates, result)
overridden, policyErr := s.volumeService.HasEnabledBackupPolicy(ctx, candidate.Name)
@@ -344,8 +381,8 @@ func (s *SystemBackupService) executeSystemVolumeBackupsInternal(ctx context.Con
continue
}
if overridden {
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: candidate.Name, Status: schedulertypes.Skipped}); err != nil {
- return result, err
+ if skipProgressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: candidate.Name, Status: schedulertypes.Skipped}); skipProgressErr != nil {
+ return result, skipProgressErr
}
result.Skipped++
continue
@@ -409,7 +446,20 @@ func (s *SystemBackupService) runScheduledSystemVolumeBackupInternal(ctx context
slog.ErrorContext(ctx, "Scheduled system-managed volume backups failed", "policyId", policyID, "error", err)
return schedulertypes.Outcome{}, err
}
- slog.InfoContext(ctx, "Scheduled system-managed volume backups completed", "policyId", policyID, "matched", result.Matched, "succeeded", result.Succeeded, "failed", result.Failed, "skipped", result.Skipped)
+ slog.InfoContext(
+ ctx,
+ "Scheduled system-managed volume backups completed",
+ "policyId",
+ policyID,
+ "matched",
+ result.Matched,
+ "succeeded",
+ result.Succeeded,
+ "failed",
+ result.Failed,
+ "skipped",
+ result.Skipped,
+ )
outcome := schedulertypes.Outcome{Status: schedulertypes.Succeeded}
if remoteDisabled {
outcome.Message = backup.RemoteDisabledMessage
@@ -460,7 +510,17 @@ func (s *SystemBackupService) ListBackupHistory(ctx context.Context, params pagi
query := s.db.WithContext(ctx).Table("(?) AS backup_history", s.db.Raw(backupHistoryUnionInternal))
if term := strings.TrimSpace(params.Search); term != "" {
pattern := "%" + term + "%"
- query = query.Where("id LIKE ? OR status LIKE ? OR trigger LIKE ? OR destination LIKE ? OR COALESCE(error, '') LIKE ? OR resource_name LIKE ? OR resource_type LIKE ? OR type LIKE ?", pattern, pattern, pattern, pattern, pattern, pattern, pattern, pattern)
+ query = query.Where("id LIKE ? OR status LIKE ? OR trigger LIKE ? OR destination LIKE ? OR COALESCE(error, '') LIKE ? OR "+
+ "resource_name LIKE ? OR resource_type LIKE ? OR type LIKE ?",
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ )
}
query = pagination.ApplyFilter(query, "type", params.Filters["type"])
if params.Sort == "" {
@@ -535,8 +595,8 @@ func (s *SystemBackupService) disableMissingVolumeS3Internal(ctx context.Context
} else {
current.Enabled = false
}
- if err := s.saveSystemVolumeBackupPoliciesInternal(ctx, collection.Policies); err != nil {
- return false, err
+ if saveSystemVolumeBackupPoliciesErr := s.saveSystemVolumeBackupPoliciesInternal(ctx, collection.Policies); saveSystemVolumeBackupPoliciesErr != nil {
+ return false, saveSystemVolumeBackupPoliciesErr
}
*policy = *current
s.rescheduleSystemVolumeBackupInternal(ctx, policy)
diff --git a/backend/internal/systembackup/system_volume_test.go b/backend/internal/systembackup/system_volume_test.go
index 4702e2159..6b9d80515 100644
--- a/backend/internal/systembackup/system_volume_test.go
+++ b/backend/internal/systembackup/system_volume_test.go
@@ -1,7 +1,6 @@
package systembackup
import (
- "context"
"testing"
"time"
@@ -78,7 +77,7 @@ func TestListBackupHistoryClassifiesAndFiltersOrigins(t *testing.T) {
}).Error)
service := &SystemBackupService{db: &database.DB{DB: gormDB}}
- systemRows, page, err := service.ListBackupHistory(context.Background(), pagination.QueryParams{
+ systemRows, page, err := service.ListBackupHistory(t.Context(), pagination.QueryParams{
Sort: "createdAt", Order: pagination.SortDesc, Limit: 20,
Filters: map[string]string{"type": "system"},
})
@@ -89,7 +88,7 @@ func TestListBackupHistoryClassifiesAndFiltersOrigins(t *testing.T) {
require.Equal(t, "app-data", systemRows[0].ResourceName)
require.Equal(t, "volume", systemRows[0].ResourceType)
- volumeRows, page, err := service.ListBackupHistory(context.Background(), pagination.QueryParams{
+ volumeRows, page, err := service.ListBackupHistory(t.Context(), pagination.QueryParams{
Search: "cache", Sort: "createdAt", Order: pagination.SortDesc, Limit: 1,
Filters: map[string]string{"type": "volume"},
})
diff --git a/backend/internal/template/handler.go b/backend/internal/template/handler.go
index e4025605b..f5f1b84a5 100644
--- a/backend/internal/template/handler.go
+++ b/backend/internal/template/handler.go
@@ -643,7 +643,7 @@ func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplat
}
var registry templatetypes.RemoteRegistry
- if err := json.Unmarshal(body, &registry); err != nil {
+ if unmarshalErr := json.Unmarshal(body, &registry); unmarshalErr != nil {
return nil, huma.Error502BadGateway("Invalid JSON response")
}
diff --git a/backend/internal/template/service.go b/backend/internal/template/service.go
index 519ec08b9..7b77483c0 100644
--- a/backend/internal/template/service.go
+++ b/backend/internal/template/service.go
@@ -177,8 +177,8 @@ func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params p
items := make([]tmpl.Template, 0, len(templates))
for _, t := range templates {
var dtoItem tmpl.Template
- if err := mapping.MapStruct(&t, &dtoItem); err != nil {
- slog.WarnContext(ctx, "failed to map template to DTO", "error", err, "templateID", t.ID)
+ if mapStructErr := mapping.MapStruct(&t, &dtoItem); mapStructErr != nil {
+ slog.WarnContext(ctx, "failed to map template to DTO", "error", mapStructErr, "templateID", t.ID)
continue
}
items = append(items, dtoItem)
@@ -261,17 +261,29 @@ func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*ComposeT
// silently returned empty.
if strings.HasPrefix(id, remoteIDPrefix+":") {
slog.InfoContext(ctx, "remote template not in cache, forcing registry refresh", "templateID", id, "cacheSize", len(templates))
- templates, refreshErr := s.remoteTemplatesInternal(ctx, true)
+ localTemplates, refreshErr := s.remoteTemplatesInternal(ctx, true)
if refreshErr != nil {
return nil, fmt.Errorf("template %q not found and registry refresh failed: %w", id, refreshErr)
}
- if found := s.lookupRemoteTemplateInternal(templates, id); found != nil {
+ if found := s.lookupRemoteTemplateInternal(localTemplates, id); found != nil {
return found, nil
}
- return nil, common.Classify(common.ErrTemplateNotFound, fmt.Errorf("Template not found: %w", fmt.Errorf("template %q not found in any registered registry (cache size=%d after refresh)", id, len(templates)))) //nolint:staticcheck // Preserve the existing error message.
- }
-
- return nil, common.Classify(common.ErrTemplateNotFound, errors.New("Template not found")) //nolint:staticcheck // Preserve the existing error message.
+ return nil, common.Classify(
+ common.ErrTemplateNotFound,
+ fmt.Errorf(
+ "template not found: %w",
+ fmt.Errorf(
+ "template %q not found in any registered registry (cache size=%d after refresh)",
+ id,
+ len(
+ localTemplates,
+ ),
+ ),
+ ),
+ )
+ }
+
+ return nil, common.Classify(common.ErrTemplateNotFound, errors.New("template not found"))
}
func (s *TemplateService) lookupRemoteTemplateInternal(templates []ComposeTemplate, id string) *ComposeTemplate {
@@ -310,7 +322,7 @@ func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updates
var existing ComposeTemplate
if err := tx.Where("id = ?", id).First(&existing).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
- return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found")) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(common.ErrTemplateNotFound, errors.New("template not found"))
}
return fmt.Errorf("failed to find template: %w", err)
}
@@ -336,7 +348,7 @@ func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {
var existing ComposeTemplate
if err := tx.Where("id = ?", id).First(&existing).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
- return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found")) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(common.ErrTemplateNotFound, errors.New("template not found"))
}
return fmt.Errorf("failed to find template: %w", err)
}
@@ -351,15 +363,15 @@ func (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {
}
templatePath := filepath.Join(baseDir, existing.Name)
- if entry, err := acfs.Stat(ctx, baseDir, "/"+existing.Name, false); err == nil && entry.IsDirectory {
- if _, err := projects.DetectComposeFile(ctx, "", templatePath); err == nil {
- if err := acfs.RemoveAll(ctx, baseDir, entry.Path); err != nil {
- return fmt.Errorf("failed to delete template directory: %w", err)
+ if entry, statErr := acfs.Stat(ctx, baseDir, "/"+existing.Name, false); statErr == nil && entry.IsDirectory {
+ if _, detectComposeFileErr := projects.DetectComposeFile(ctx, "", templatePath); detectComposeFileErr == nil {
+ if removeAllErr := acfs.RemoveAll(ctx, baseDir, entry.Path); removeAllErr != nil {
+ return fmt.Errorf("failed to delete template directory: %w", removeAllErr)
}
}
}
- if err := tx.Delete(&existing).Error; err != nil {
- return fmt.Errorf("failed to delete template: %w", err)
+ if deleteTemplateErr := tx.Delete(&existing).Error; deleteTemplateErr != nil {
+ return fmt.Errorf("failed to delete template: %w", deleteTemplateErr)
}
return nil
})
@@ -595,16 +607,16 @@ func (s *TemplateService) loadRemoteTemplatesInternal(ctx context.Context, gener
g.Go(func() (workerErr error) {
defer utils.RecoverToError(&workerErr, "template worker")
- remoteTemplates, err := s.fetchRegistryTemplatesInternal(groupCtx, &reg, generation)
- if err != nil {
- slog.WarnContext(groupCtx, "failed to fetch templates from registry", "registry", reg.Name, "url", reg.URL, "error", err)
+ remoteTemplates, fetchRegistryTemplatesErr := s.fetchRegistryTemplatesInternal(groupCtx, &reg, generation)
+ if fetchRegistryTemplatesErr != nil {
+ slog.WarnContext(groupCtx, "failed to fetch templates from registry", "registry", reg.Name, "url", reg.URL, "error", fetchRegistryTemplatesErr)
s.registryMu.Lock()
if generation == s.remoteGeneration.Load() {
- s.registryErrors[reg.ID] = err.Error()
+ s.registryErrors[reg.ID] = fetchRegistryTemplatesErr.Error()
}
s.registryMu.Unlock()
mu.Lock()
- fetchErrors = append(fetchErrors, fmt.Errorf("registry %q: %w", reg.Name, err))
+ fetchErrors = append(fetchErrors, fmt.Errorf("registry %q: %w", reg.Name, fetchRegistryTemplatesErr))
mu.Unlock()
return nil // Don't fail the whole group if one registry fails
}
@@ -627,8 +639,8 @@ func (s *TemplateService) loadRemoteTemplatesInternal(ctx context.Context, gener
})
}
- if err := g.Wait(); err != nil {
- return nil, err
+ if waitErr := g.Wait(); waitErr != nil {
+ return nil, waitErr
}
if generation != s.remoteGeneration.Load() {
return nil, errRemoteCacheInvalidatedInternal
@@ -707,8 +719,8 @@ func (s *TemplateService) fetchRegistryTemplatesInternal(ctx context.Context, re
}
var regDTO tmpl.RemoteRegistry
- if err := json.Unmarshal(body, &regDTO); err != nil {
- return nil, fmt.Errorf("parse registry JSON: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &regDTO); unmarshalErr != nil {
+ return nil, fmt.Errorf("parse registry JSON: %w", unmarshalErr)
}
templates := make([]ComposeTemplate, 0, len(regDTO.Templates))
@@ -739,8 +751,8 @@ func (s *TemplateService) fetchRegistryManifest(ctx context.Context, url string)
return nil, err
}
var reg tmpl.RemoteRegistry
- if err := json.Unmarshal(body, &reg); err != nil {
- return nil, fmt.Errorf("failed to parse registry JSON: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &reg); unmarshalErr != nil {
+ return nil, fmt.Errorf("failed to parse registry JSON: %w", unmarshalErr)
}
if reg.Name == "" || len(reg.Templates) == 0 {
return nil, errors.New("invalid registry manifest: missing required fields (name, templates)")
@@ -880,7 +892,7 @@ func (s *TemplateService) newSafeRequestInternal(ctx context.Context, method, ra
}
}
- req, err := http.NewRequestWithContext(ctx, method, parsedURL.String(), nil)
+ req, err := http.NewRequestWithContext(ctx, method, parsedURL.String(), http.NoBody)
if err != nil {
return nil, nil, fmt.Errorf("failed to create request for %s: %w", rawURL, err)
}
@@ -914,9 +926,9 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remot
return fmt.Errorf("failed to check existing template: %w", err)
} else if err == nil {
// Existing template found
- composeContent, envContent, err := s.FetchTemplateContent(ctx, remoteTemplate)
- if err != nil {
- return fmt.Errorf("failed to fetch template content for existing local template: %w", err)
+ composeContent, envContent, fetchTemplateContentErr := s.FetchTemplateContent(ctx, remoteTemplate)
+ if fetchTemplateContentErr != nil {
+ return fmt.Errorf("failed to fetch template content for existing local template: %w", fetchTemplateContentErr)
}
envPtr, werr := projects.WriteTemplateFiles(composePath, envPath, composeContent, envContent)
@@ -928,8 +940,8 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remot
existing.EnvContent = envPtr
existing.Metadata = cloneTemplateMetadata(remoteTemplate.Metadata)
- if err := tx.Save(&existing).Error; err != nil {
- return fmt.Errorf("failed to update existing local template: %w", err)
+ if updateLocalTemplateErr := tx.Save(&existing).Error; updateLocalTemplateErr != nil {
+ return fmt.Errorf("failed to update existing local template: %w", updateLocalTemplateErr)
}
resultTemplate = &existing
return nil
@@ -959,8 +971,8 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remot
Metadata: cloneTemplateMetadata(remoteTemplate.Metadata),
}
- if err := tx.Create(localTemplate).Error; err != nil {
- return fmt.Errorf("failed to save local template: %w", err)
+ if createLocalTemplateErr := tx.Create(localTemplate).Error; createLocalTemplateErr != nil {
+ return fmt.Errorf("failed to save local template: %w", createLocalTemplateErr)
}
resultTemplate = localTemplate
return nil
@@ -1125,8 +1137,8 @@ func (s *TemplateService) syncFilesystemTemplatesInternal(ctx context.Context) e
if !ent.IsDirectory {
continue
}
- if err := s.processFolderEntry(ctx, dir, ent.Name); err != nil {
- slog.WarnContext(ctx, "failed to read folder template", "folder", ent.Name, "error", err)
+ if processFolderEntryErr := s.processFolderEntry(ctx, dir, ent.Name); processFolderEntryErr != nil {
+ slog.WarnContext(ctx, "failed to read folder template", "folder", ent.Name, "error", processFolderEntryErr)
}
}
diff --git a/backend/internal/template/service_test.go b/backend/internal/template/service_test.go
index 2c839de68..f4c725d4c 100644
--- a/backend/internal/template/service_test.go
+++ b/backend/internal/template/service_test.go
@@ -2,7 +2,6 @@ package template
import (
"context"
- "fmt"
"net"
"net/http"
"net/http/httptest"
@@ -71,7 +70,7 @@ func makePublicTestClient(t *testing.T, server *httptest.Server) (*http.Client,
return []net.IP{net.ParseIP("93.184.216.34")}, nil
}
- baseURL := fmt.Sprintf("http://templates.example.test:%s", parsedURL.Port())
+ baseURL := "http://templates.example.test:" + parsedURL.Port()
return client, lookupIP, baseURL
}
@@ -152,7 +151,7 @@ services:
Enabled: true,
}
- templates, err := service.fetchRegistryTemplatesInternal(context.Background(), registry, service.remoteGeneration.Load())
+ templates, err := service.fetchRegistryTemplatesInternal(t.Context(), registry, service.remoteGeneration.Load())
require.NoError(t, err)
require.Len(t, templates, 2)
require.NotNil(t, templates[0].Metadata)
@@ -161,7 +160,7 @@ services:
require.Nil(t, templates[1].Metadata.IconURL)
require.EqualValues(t, 1, composeHits.Load())
- cachedTemplates, err := service.fetchRegistryTemplatesInternal(context.Background(), registry, service.remoteGeneration.Load())
+ cachedTemplates, err := service.fetchRegistryTemplatesInternal(t.Context(), registry, service.remoteGeneration.Load())
require.NoError(t, err)
require.Len(t, cachedTemplates, 2)
require.NotNil(t, cachedTemplates[0].Metadata)
@@ -194,7 +193,7 @@ services:
client, lookupIP, baseURL := makePublicTestClient(t, server)
settingsSvc := minimalSettingsServiceForTest(t)
- require.NoError(t, settingsSvc.UpdateSetting(context.Background(), "templatesDirectory", filepath.Join(tempDir, "templates")))
+ require.NoError(t, settingsSvc.UpdateSetting(t.Context(), "templatesDirectory", filepath.Join(tempDir, "templates")))
service := &TemplateService{
db: setupTemplateServiceTestDB(t),
@@ -218,7 +217,7 @@ services:
},
}
- downloaded, err := service.DownloadTemplate(context.Background(), remoteTemplate)
+ downloaded, err := service.DownloadTemplate(t.Context(), remoteTemplate)
require.NoError(t, err)
require.NotNil(t, downloaded)
require.False(t, downloaded.IsRemote)
@@ -227,7 +226,7 @@ services:
require.Equal(t, "https://cdn.example/download.png", *downloaded.Metadata.IconURL)
var stored ComposeTemplate
- require.NoError(t, service.db.WithContext(context.Background()).First(&stored, "id = ?", downloaded.ID).Error)
+ require.NoError(t, service.db.WithContext(t.Context()).First(&stored, "id = ?", downloaded.ID).Error)
require.NotNil(t, stored.Metadata)
require.NotNil(t, stored.Metadata.IconURL)
require.Equal(t, "https://cdn.example/download.png", *stored.Metadata.IconURL)
@@ -257,9 +256,9 @@ func TestGetAllTemplatesPaginated_FiltersByType(t *testing.T) {
IsRemote: false,
},
}
- require.NoError(t, db.WithContext(context.Background()).Create(&localTemplates).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(&localTemplates).Error)
- service := NewTemplateService(context.Background(), db, http.DefaultClient, nil)
+ service := NewTemplateService(t.Context(), db, http.DefaultClient, nil)
service.remoteCache.Set(service.remoteGeneration.Load(), []ComposeTemplate{
{
ID: "remote-one", CreatedAt: now, UpdatedAt: &now,
@@ -283,7 +282,7 @@ func TestGetAllTemplatesPaginated_FiltersByType(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- templates, _, err := service.GetAllTemplatesPaginated(context.Background(), pagination.QueryParams{
+ templates, _, err := service.GetAllTemplatesPaginated(t.Context(), pagination.QueryParams{
Start: 0, Limit: 20,
Filters: map[string]string{"type": tt.typeFilter},
})
@@ -308,7 +307,7 @@ func TestFetchRaw_BlocksUnsafeRemoteURL(t *testing.T) {
registryFetchMeta: make(map[string]*registryFetchMeta),
}
- _, err := service.FetchRaw(context.Background(), "http://127.0.0.1:8080/registry.json")
+ _, err := service.FetchRaw(t.Context(), "http://127.0.0.1:8080/registry.json")
require.Error(t, err)
require.ErrorIs(t, err, common.ErrUnsafeRemoteURL)
}
@@ -327,7 +326,7 @@ services:
`), 0o644))
settingsSvc := minimalSettingsServiceForTest(t)
- require.NoError(t, settingsSvc.UpdateSetting(context.Background(), "templatesDirectory", templatesRoot))
+ require.NoError(t, settingsSvc.UpdateSetting(t.Context(), "templatesDirectory", templatesRoot))
service := &TemplateService{
db: setupTemplateServiceTestDB(t),
@@ -336,10 +335,10 @@ services:
registryFetchMeta: make(map[string]*registryFetchMeta),
}
- require.NoError(t, service.syncFilesystemTemplatesInternal(context.Background()))
+ require.NoError(t, service.syncFilesystemTemplatesInternal(t.Context()))
var stored ComposeTemplate
- require.NoError(t, service.db.WithContext(context.Background()).First(&stored, "name = ?", "example").Error)
+ require.NoError(t, service.db.WithContext(t.Context()).First(&stored, "name = ?", "example").Error)
require.NotNil(t, stored.Metadata)
require.NotNil(t, stored.Metadata.IconURL)
require.Equal(t, "https://cdn.example/local.png", *stored.Metadata.IconURL)
@@ -387,20 +386,20 @@ func TestGetTemplate_ForceRefreshesRemoteCacheOnMiss(t *testing.T) {
URL: baseURL + "/registry.json",
Enabled: true,
}
- require.NoError(t, db.WithContext(context.Background()).Create(registry).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(registry).Error)
settingsSvc := minimalSettingsServiceForTest(t)
// Point templates+projects directories at tempDir so sync calls don't try to
// touch the real /app filesystem during tests.
- require.NoError(t, settingsSvc.UpdateSetting(context.Background(), "templatesDirectory", filepath.Join(tempDir, "templates")))
- require.NoError(t, settingsSvc.UpdateSetting(context.Background(), "projectsDirectory", filepath.Join(tempDir, "projects")))
+ require.NoError(t, settingsSvc.UpdateSetting(t.Context(), "templatesDirectory", filepath.Join(tempDir, "templates")))
+ require.NoError(t, settingsSvc.UpdateSetting(t.Context(), "projectsDirectory", filepath.Join(tempDir, "projects")))
- service := NewTemplateService(context.Background(), db, client, settingsSvc)
+ service := NewTemplateService(t.Context(), db, client, settingsSvc)
service.lookupIP = lookupIP
service.safeHTTPClient = service.newSafeHTTPClientInternal()
// Cache starts empty; GetTemplate for a remote ID should force a refresh and find the template.
- got, err := service.GetTemplate(context.Background(), "remote:reg-1:affine")
+ got, err := service.GetTemplate(t.Context(), "remote:reg-1:affine")
require.NoError(t, err)
require.NotNil(t, got)
require.True(t, got.IsRemote)
@@ -408,7 +407,7 @@ func TestGetTemplate_ForceRefreshesRemoteCacheOnMiss(t *testing.T) {
require.GreaterOrEqual(t, registryHits.Load(), int32(1), "registry should be fetched at least once")
// Unknown remote ID still surfaces a clear error after the forced refresh.
- _, err = service.GetTemplate(context.Background(), "remote:reg-1:does-not-exist")
+ _, err = service.GetTemplate(t.Context(), "remote:reg-1:does-not-exist")
require.Error(t, err)
require.Contains(t, err.Error(), "not found")
}
@@ -418,7 +417,7 @@ func minimalSettingsServiceForTest(t *testing.T) *settings.SettingsService {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))
- svc, err := newSettingsServiceForTestInternal(t, context.Background(), &database.DB{DB: db})
+ svc, err := newSettingsServiceForTestInternal(t, t.Context(), &database.DB{DB: db})
require.NoError(t, err)
return svc
}
@@ -427,7 +426,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
diff --git a/backend/internal/updater/actors.go b/backend/internal/updater/actors.go
index 15632b237..13d297260 100644
--- a/backend/internal/updater/actors.go
+++ b/backend/internal/updater/actors.go
@@ -26,7 +26,24 @@ type singleUpdateActorInternal struct{ service *UpdaterService }
func (s *UpdaterService) RegisterActors(runtime *francis.Runtime) error {
s.singleUpdates = runtime.Service()
- return runtime.RegisterActor(singleUpdateTypeInternal, func(_ string, _ *actor.Service) actor.Actor { return &singleUpdateActorInternal{service: s} }, local.WithCapacityGroup("jobs", 4), local.WithCompletedJobRetention(7*24*time.Hour))
+ return runtime.RegisterActor(
+ singleUpdateTypeInternal,
+ func(
+ _ string,
+ _ *actor.Service,
+ ) actor.Actor {
+ return &singleUpdateActorInternal{
+ service: s,
+ }
+ },
+ local.WithCapacityGroup(
+ "jobs",
+ 4,
+ ),
+ local.WithCompletedJobRetention(
+ 7*24*time.Hour,
+ ),
+ )
}
// Start repairs persisted single-container delivery intents until shutdown.
@@ -100,8 +117,8 @@ func (s *UpdaterService) dispatchSingleInternal(ctx context.Context, state arcan
}
// A terminal transport record cannot prove the durable business outcome.
// Its replacement reconciles the saved effect before doing any further work.
- if err := s.singleUpdates.DeleteJob(ctx, singleUpdateTypeInternal, "single-container", id); err != nil {
- return err
+ if deleteJobErr := s.singleUpdates.DeleteJob(ctx, singleUpdateTypeInternal, "single-container", id); deleteJobErr != nil {
+ return deleteJobErr
}
_, _, err = s.singleUpdates.Dispatch(ctx, singleUpdateTypeInternal, "single-container", "update", state.Command, actor.WithIdempotencyKey(state.Command.ActivityID))
return err
@@ -115,11 +132,11 @@ func (s *UpdaterService) repairSinglesInternal(ctx context.Context) error {
}
for _, entry := range page.States {
var state arcaneupdater.SingleUpdateState
- if err := entry.Data.Decode(&state); err != nil {
- return err
+ if decodeErr := entry.Data.Decode(&state); decodeErr != nil {
+ return decodeErr
}
- if err := s.repairSingleInternal(ctx, state); err != nil {
- return err
+ if repairSingleErr := s.repairSingleInternal(ctx, state); repairSingleErr != nil {
+ return repairSingleErr
}
}
cursor = page.AfterID()
@@ -181,12 +198,12 @@ func (a *singleUpdateActorInternal) Job(ctx context.Context, _ string, data acto
}
defer release()
var command arcaneupdater.SingleUpdateCommand
- if err := data.Decode(&command); err != nil {
- return errors.Join(err, actor.ErrJobPermanentFailure)
+ if decodeErr := data.Decode(&command); decodeErr != nil {
+ return errors.Join(decodeErr, actor.ErrJobPermanentFailure)
}
var state arcaneupdater.SingleUpdateState
- if err := s.singleUpdates.GetState(ctx, singleUpdateStateTypeInternal, command.ActivityID, &state); err != nil {
- return err
+ if getStateErr := s.singleUpdates.GetState(ctx, singleUpdateStateTypeInternal, command.ActivityID, &state); getStateErr != nil {
+ return getStateErr
}
if state.Status == "completed" || state.Status == "needs_attention" {
return nil
@@ -194,8 +211,8 @@ func (a *singleUpdateActorInternal) Job(ctx context.Context, _ string, data acto
if state.Command != command {
return actor.ErrJobPermanentFailure
}
- if err := s.authorizeSingleInternal(ctx, command); err != nil {
- return s.failSingleInternal(ctx, &state, err.Error())
+ if authorizeSingleErr := s.authorizeSingleInternal(ctx, command); authorizeSingleErr != nil {
+ return s.failSingleInternal(ctx, &state, authorizeSingleErr.Error())
}
ctx = s.trackActivityInternal(ctx, command.ActivityID)
canceled, err := s.awaitSingleActivityInternal(ctx, lifetime, &state)
@@ -291,7 +308,18 @@ func (s *UpdaterService) prepareSingleTargetInternal(ctx context.Context, state
return false, err
}
if confirmed {
- result := &arcaneupdater.Result{Updated: 1, Items: []arcaneupdater.ResourceResult{{ResourceID: state.Target.ContainerID, ResourceName: state.Target.ContainerName, ResourceType: "container", Status: arcaneupdater.StatusUpdated, UpdateApplied: true}}}
+ result := &arcaneupdater.Result{
+ Updated: 1,
+ Items: []arcaneupdater.ResourceResult{
+ {
+ ResourceID: state.Target.ContainerID,
+ ResourceName: state.Target.ContainerName,
+ ResourceType: "container",
+ Status: arcaneupdater.StatusUpdated,
+ UpdateApplied: true,
+ },
+ },
+ }
return true, s.completeSingleInternal(ctx, state, result, nil)
}
if !unchanged {
@@ -343,8 +371,8 @@ func (s *UpdaterService) ActiveUpdateActivityIDs(ctx context.Context) ([]string,
}
for _, entry := range page.States {
var state arcaneupdater.SingleUpdateState
- if err := entry.Data.Decode(&state); err != nil {
- return nil, err
+ if decodeErr := entry.Data.Decode(&state); decodeErr != nil {
+ return nil, decodeErr
}
ids = append(ids, state.Command.ActivityID)
}
diff --git a/backend/internal/updater/recovery.go b/backend/internal/updater/recovery.go
index de8f38846..3f1b7c7c8 100644
--- a/backend/internal/updater/recovery.go
+++ b/backend/internal/updater/recovery.go
@@ -78,7 +78,20 @@ func (s *UpdaterService) RecordUpdateRun(ctx context.Context, result updater.Res
if evidenceErr != nil {
progressMessage = evidenceErr.Error()
}
- progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: result.ResourceID, ResourceType: string(result.ResourceType), Status: status, Message: progressMessage, ActivityID: activityIDFromContextInternal(ctx)})
+ progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ID: result.ResourceID,
+ ResourceType: string(
+ result.ResourceType,
+ ),
+ Status: status,
+ Message: progressMessage,
+ ActivityID: activityIDFromContextInternal(
+ ctx,
+ ),
+ },
+ )
err := errors.Join(recordErr, progressErr, evidenceErr)
if progress, ok := ctx.Value(updateProgressKeyInternal{}).(*updateProgressInternal); ok && err != nil {
progress.mu.Lock()
@@ -130,7 +143,19 @@ func (p *updateProgressInternal) completeBatchInternal(ctx context.Context, opti
status = schedulertypes.NeedsAttention
}
if selfTriggered {
- err = errors.Join(err, jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: selfID, ResourceType: "container", Status: schedulertypes.NeedsAttention, ActivityID: activityID, Message: "Self-update completion requires review"}))
+ err = errors.Join(
+ err,
+ jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ID: selfID,
+ ResourceType: "container",
+ Status: schedulertypes.NeedsAttention,
+ ActivityID: activityID,
+ Message: "Self-update completion requires review",
+ },
+ ),
+ )
status = schedulertypes.NeedsAttention
err = errors.Join(err, errors.New("self-update was triggered but completion requires review"))
}
@@ -210,12 +235,23 @@ func (s *UpdaterService) freezePendingInternal(ctx context.Context) (context.Con
if err != nil {
return ctx, err
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: "auto-update", ResourceType: "update-batch", Status: schedulertypes.Running, RecoveryData: raw, ActivityID: activityIDFromContextInternal(ctx)}); err != nil {
- return ctx, err
+ if progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ID: "auto-update",
+ ResourceType: "update-batch",
+ Status: schedulertypes.Running,
+ RecoveryData: raw,
+ ActivityID: activityIDFromContextInternal(
+ ctx,
+ ),
+ },
+ ); progressErr != nil {
+ return ctx, progressErr
}
for _, target := range plan.Targets {
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: target.ContainerID, ResourceType: "container", Status: schedulertypes.Queued}); err != nil {
- return ctx, err
+ if queuedProgressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: target.ContainerID, ResourceType: "container", Status: schedulertypes.Queued}); queuedProgressErr != nil {
+ return ctx, queuedProgressErr
}
}
return context.WithValue(ctx, frozenPendingKeyInternal{}, &plan), nil
@@ -245,9 +281,9 @@ func (s *UpdaterService) buildFrozenPlanInternal(ctx context.Context, records []
if record.ContainerID == "" && refs.NormalizeImageUpdateRef(candidate.Image) != refs.NormalizeImageUpdateRef(record.ImageRef()) {
continue
}
- target, selected, err := s.freezeRecordTargetInternal(ctx, record, candidate.ID)
- if err != nil {
- return plan, err
+ target, selected, freezeRecordTargetErr := s.freezeRecordTargetInternal(ctx, record, candidate.ID)
+ if freezeRecordTargetErr != nil {
+ return plan, freezeRecordTargetErr
}
plan.Records = append(plan.Records, selected)
plan.Targets = append(plan.Targets, *target)
@@ -294,7 +330,15 @@ func (s *UpdaterService) freezeContainerInternal(ctx context.Context, id string)
return nil, err
}
inspected := result.Container
- target := &arcaneupdater.FrozenUpdateTarget{ContainerID: inspected.ID, ContainerName: strings.TrimPrefix(inspected.Name, "/"), BaselineImageID: inspected.Image, BaselineRestartCount: inspected.RestartCount}
+ target := &arcaneupdater.FrozenUpdateTarget{
+ ContainerID: inspected.ID,
+ ContainerName: strings.TrimPrefix(
+ inspected.Name,
+ "/",
+ ),
+ BaselineImageID: inspected.Image,
+ BaselineRestartCount: inspected.RestartCount,
+ }
if inspected.State != nil {
target.BaselineStartedAt = inspected.State.StartedAt
}
@@ -341,8 +385,8 @@ func (s *UpdaterService) prepareSinglePullInternal(ctx context.Context, imageRef
return "", err
}
target.DesiredDigest = digest
- if err := single.Persist(); err != nil {
- return "", err
+ if persistErr := single.Persist(); persistErr != nil {
+ return "", persistErr
}
}
if refs.NormalizeImageUpdateRef(target.DesiredImageRef) != refs.NormalizeImageUpdateRef(imageRef) {
@@ -365,8 +409,8 @@ func prepareBatchPullInternal(ctx context.Context, imageRef string, plan *frozen
return "", errors.New("conflicting frozen digests for one image reference")
}
immutable = selected
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: target.ContainerID, ResourceType: "container", Status: schedulertypes.Running}); err != nil {
- return "", err
+ if progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: target.ContainerID, ResourceType: "container", Status: schedulertypes.Running}); progressErr != nil {
+ return "", progressErr
}
}
if immutable == "" {
@@ -389,8 +433,8 @@ func (s *UpdaterService) confirmFrozenTargetInternal(ctx context.Context, target
immutable, imageErr := immutableImageInternal(target)
desiredID := ""
if imageErr == nil {
- image, err := dockerClient.ImageInspect(ctx, immutable)
- if err == nil {
+ image, imageInspectErr := dockerClient.ImageInspect(ctx, immutable)
+ if imageInspectErr == nil {
desiredID = image.ID
}
}
@@ -405,22 +449,28 @@ func (s *UpdaterService) confirmFrozenTargetInternal(ctx context.Context, target
if !named {
continue
}
- result, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, candidate.ID, client.ContainerInspectOptions{})
- if err != nil {
- return false, false, err
+ result, containerInspectWithCompatibilityErr := compat.ContainerInspectWithCompatibility(ctx, dockerClient, candidate.ID, client.ContainerInspectOptions{})
+ if containerInspectWithCompatibilityErr != nil {
+ return false, false, containerInspectWithCompatibilityErr
}
inspected := result.Container
if inspected.Config == nil {
return false, false, nil
}
labels := inspected.Config.Labels
- if labels["com.docker.compose.project"] != target.ComposeProject || labels["com.docker.compose.service"] != target.ComposeService || labels["com.docker.compose.container-number"] != target.ComposeNumber {
+ if labels["com.docker.compose.project"] != target.ComposeProject ||
+ labels["com.docker.compose.service"] != target.ComposeService ||
+ labels["com.docker.compose.container-number"] != target.ComposeNumber {
return false, false, nil
}
if desiredID != "" && inspected.Image == desiredID {
return true, false, nil
}
- unchanged := inspected.ID == target.ContainerID && inspected.Image == target.BaselineImageID && inspected.RestartCount == target.BaselineRestartCount && inspected.State != nil && inspected.State.StartedAt == target.BaselineStartedAt
+ unchanged := inspected.ID == target.ContainerID &&
+ inspected.Image == target.BaselineImageID &&
+ inspected.RestartCount == target.BaselineRestartCount &&
+ inspected.State != nil &&
+ inspected.State.StartedAt == target.BaselineStartedAt
return false, unchanged, nil
}
return false, false, nil
@@ -437,8 +487,8 @@ func (s *UpdaterService) ReconcilePending(ctx context.Context, run schedulertype
found := false
for _, target := range run.Outcome.Targets {
if target.ID == "auto-update" && len(target.RecoveryData) > 0 {
- if err := json.Unmarshal(target.RecoveryData, &plan); err != nil {
- return schedulertypes.Outcome{Status: schedulertypes.Failed}, err
+ if unmarshalErr := json.Unmarshal(target.RecoveryData, &plan); unmarshalErr != nil {
+ return schedulertypes.Outcome{Status: schedulertypes.Failed}, unmarshalErr
}
found = true
}
@@ -452,13 +502,21 @@ func (s *UpdaterService) ReconcilePending(ctx context.Context, run schedulertype
if frozenTargetSettledInternal(run, target.ContainerID) {
continue
}
- confirmed, unchanged, err := s.confirmFrozenTargetInternal(ctx, target)
- if err != nil {
- return schedulertypes.Outcome{Status: schedulertypes.Waiting}, err
+ confirmed, unchanged, confirmFrozenTargetErr := s.confirmFrozenTargetInternal(ctx, target)
+ if confirmFrozenTargetErr != nil {
+ return schedulertypes.Outcome{Status: schedulertypes.Waiting}, confirmFrozenTargetErr
}
if confirmed {
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ID: target.ContainerID, ResourceType: "container", Status: schedulertypes.Succeeded, Message: "Frozen desired image confirmed after restart"}); err != nil {
- return schedulertypes.Outcome{}, err
+ if progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ID: target.ContainerID,
+ ResourceType: "container",
+ Status: schedulertypes.Succeeded,
+ Message: "Frozen desired image confirmed after restart",
+ },
+ ); progressErr != nil {
+ return schedulertypes.Outcome{}, progressErr
}
continue
}
@@ -470,9 +528,9 @@ func (s *UpdaterService) ReconcilePending(ctx context.Context, run schedulertype
remaining.Records = appendFrozenRecordInternal(remaining.Records, plan.Records, target.ContainerID)
}
if len(remaining.Records) > 0 {
- result, err := s.ApplyPending(context.WithValue(ctx, frozenPendingKeyInternal{}, &remaining), arcaneupdater.Options{})
- if err != nil || result == nil || result.Failed > 0 {
- return schedulertypes.Outcome{Status: schedulertypes.Failed, Message: "Frozen update recovery could not confirm completion"}, err
+ result, applyPendingErr := s.ApplyPending(context.WithValue(ctx, frozenPendingKeyInternal{}, &remaining), arcaneupdater.Options{})
+ if applyPendingErr != nil || result == nil || result.Failed > 0 {
+ return schedulertypes.Outcome{Status: schedulertypes.Failed, Message: "Frozen update recovery could not confirm completion"}, applyPendingErr
}
}
status := schedulertypes.Succeeded
diff --git a/backend/internal/updater/recovery_test.go b/backend/internal/updater/recovery_test.go
index e932b2f62..52f0b2161 100644
--- a/backend/internal/updater/recovery_test.go
+++ b/backend/internal/updater/recovery_test.go
@@ -14,6 +14,7 @@ import (
arcaneupdater "github.com/getarcaneapp/arcane/types/v2/updater"
"github.com/moby/moby/api/types/container"
image "github.com/moby/moby/api/types/image"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/getarcaneapp/arcane/backend/v2/internal/activity"
@@ -26,23 +27,84 @@ import (
func TestFrozenTargetsPreserveAllSelectedContainers(t *testing.T) {
db := setupProjectTestDBInternal(t)
digest := "sha256:desired"
- require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "shared-image", Repository: "registry.example.com/app", Tag: "latest", HasUpdate: true, LatestDigest: &digest}).Error)
+ require.NoError(
+ t,
+ db.Create(&imageupdate.ImageUpdateRecord{
+ ID: "shared-image",
+ Repository: "registry.example.com/app",
+ Tag: "latest",
+ HasUpdate: true,
+ LatestDigest: &digest,
+ }).Error,
+ )
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/containers/json") {
- require.NoError(t, json.MarshalWrite(w, []container.Summary{{ID: "a", Names: []string{"/a"}, Image: "registry.example.com/app:latest"}, {ID: "b", Names: []string{"/b"}, Image: "registry.example.com/app:latest"}}))
+ if !assert.NoError(
+ t,
+ json.MarshalWrite(
+ w,
+ []container.Summary{
+ {
+ ID: "a",
+ Names: []string{"/a"},
+ Image: "registry.example.com/app:latest",
+ },
+ {
+ ID: "b",
+ Names: []string{"/b"},
+ Image: "registry.example.com/app:latest",
+ },
+ },
+ ),
+ ) {
+ return
+ }
return
}
for _, id := range []string{"a", "b"} {
if strings.HasSuffix(r.URL.Path, "/containers/"+id+"/json") {
- require.NoError(t, json.MarshalWrite(w, container.InspectResponse{ID: id, Name: "/" + id, Image: "sha256:old", Config: &container.Config{Image: "registry.example.com/app:latest"}, State: &container.State{StartedAt: "baseline"}}))
+ if !assert.NoError(
+ t,
+ json.MarshalWrite(
+ w,
+ container.InspectResponse{
+ ID: id,
+ Name: "/" + id,
+ Image: "sha256:old",
+ Config: &container.Config{Image: "registry.example.com/app:latest"},
+ State: &container.State{StartedAt: "baseline"},
+ },
+ ),
+ ) {
+ return
+ }
return
}
}
http.NotFound(w, r)
}))
defer server.Close()
- svc, err := NewUpdaterService(db, nil, (&docker.DockerClientService{}).WithClient(newTestDockerClientInternal(t, server)), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ svc, err := NewUpdaterService(
+ db,
+ nil,
+ (&docker.DockerClientService{}).WithClient(newTestDockerClientInternal(
+ t,
+ server,
+ )),
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ )
require.NoError(t, err)
var evidence []byte
ctx := jobcontext.WithExecution(t.Context(), schedulertypes.Run{ID: "run"}, func(target schedulertypes.TargetOutcome) error {
@@ -75,19 +137,66 @@ func TestFrozenTargetConfirmsReplacementAndRejectsUnknownEffect(t *testing.T) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.MarshalWrite(w, []container.Summary{{ID: test.id, Names: []string{"/app"}}}))
+ if !assert.NoError(t, json.MarshalWrite(w, []container.Summary{{ID: test.id, Names: []string{"/app"}}})) {
+ return
+ }
case strings.Contains(r.URL.Path, "/images/"):
- require.NoError(t, json.MarshalWrite(w, image.InspectResponse{ID: "sha256:desired"}))
+ if !assert.NoError(t, json.MarshalWrite(w, image.InspectResponse{ID: "sha256:desired"})) {
+ return
+ }
case strings.Contains(r.URL.Path, "/containers/"):
- require.NoError(t, json.MarshalWrite(w, container.InspectResponse{ID: test.id, Name: "/app", Image: test.image, Config: &container.Config{}, State: &container.State{StartedAt: "baseline"}}))
+ if !assert.NoError(
+ t,
+ json.MarshalWrite(
+ w,
+ container.InspectResponse{
+ ID: test.id,
+ Name: "/app",
+ Image: test.image,
+ Config: &container.Config{},
+ State: &container.State{StartedAt: "baseline"},
+ },
+ ),
+ ) {
+ return
+ }
default:
http.NotFound(w, r)
}
}))
defer server.Close()
- svc, err := NewUpdaterService(nil, nil, (&docker.DockerClientService{}).WithClient(newTestDockerClientInternal(t, server)), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ svc, err := NewUpdaterService(
+ nil,
+ nil,
+ (&docker.DockerClientService{}).WithClient(newTestDockerClientInternal(
+ t,
+ server,
+ )),
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ )
require.NoError(t, err)
- confirmed, unchanged, err := svc.confirmFrozenTargetInternal(t.Context(), arcaneupdater.FrozenUpdateTarget{ContainerID: "old", ContainerName: "app", BaselineImageID: "sha256:baseline", BaselineStartedAt: "baseline", DesiredImageRef: "registry.example.com/app:latest", DesiredDigest: "sha256:desired"})
+ confirmed, unchanged, err := svc.confirmFrozenTargetInternal(
+ t.Context(),
+ arcaneupdater.FrozenUpdateTarget{
+ ContainerID: "old",
+ ContainerName: "app",
+ BaselineImageID: "sha256:baseline",
+ BaselineStartedAt: "baseline",
+ DesiredImageRef: "registry.example.com/app:latest",
+ DesiredDigest: "sha256:desired",
+ },
+ )
require.NoError(t, err)
require.Equal(t, test.confirmed, confirmed)
require.Equal(t, test.unchanged, unchanged)
@@ -102,10 +211,22 @@ func TestSingleUpdateRepairsAcceptedIntentBeforeDispatch(t *testing.T) {
require.NoError(t, svc.RegisterActors(runtime))
francistest.Start(t, runtime)
command := arcaneupdater.SingleUpdateCommand{ContainerID: "missing", ActivityID: "accepted"}
- require.NoError(t, runtime.Service().SetState(t.Context(), singleUpdateStateTypeInternal, command.ActivityID, arcaneupdater.SingleUpdateState{Command: command, Status: "queued"}, nil))
+ require.NoError(
+ t,
+ runtime.Service().SetState(
+ t.Context(),
+ singleUpdateStateTypeInternal,
+ command.ActivityID,
+ arcaneupdater.SingleUpdateState{
+ Command: command,
+ Status: "queued",
+ },
+ nil,
+ ),
+ )
require.NoError(t, svc.Start(t.Context()))
t.Cleanup(func() {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), time.Second)
defer cancel()
require.NoError(t, svc.Stop(ctx))
})
@@ -126,23 +247,61 @@ func TestSingleUpdatePersistsSuccessfulActivity(t *testing.T) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.MarshalWrite(w, []container.Summary{{ID: "app", Names: []string{"/app"}, Image: immutableRef, State: "running"}}))
+ if !assert.NoError(t, json.MarshalWrite(w, []container.Summary{{ID: "app", Names: []string{"/app"}, Image: immutableRef, State: "running"}})) {
+ return
+ }
case strings.HasSuffix(r.URL.Path, "/containers/app/json"):
- require.NoError(t, json.MarshalWrite(w, container.InspectResponse{ID: "app", Name: "/app", Image: "sha256:baseline", Config: &container.Config{Image: immutableRef}, State: &container.State{StartedAt: "baseline", Running: true}}))
+ if !assert.NoError(
+ t,
+ json.MarshalWrite(
+ w,
+ container.InspectResponse{
+ ID: "app",
+ Name: "/app",
+ Image: "sha256:baseline",
+ Config: &container.Config{Image: immutableRef},
+ State: &container.State{
+ StartedAt: "baseline",
+ Running: true,
+ },
+ },
+ ),
+ ) {
+ return
+ }
default:
http.NotFound(w, r)
}
}))
defer server.Close()
activityService := activity.NewActivityService(db, nil)
- svc, err := NewUpdaterService(db, nil, (&docker.DockerClientService{}).WithClient(newTestDockerClientInternal(t, server)), nil, nil, nil, nil, nil, nil, nil, activityService, nil, nil, nil, nil)
+ svc, err := NewUpdaterService(
+ db,
+ nil,
+ (&docker.DockerClientService{}).WithClient(newTestDockerClientInternal(
+ t,
+ server,
+ )),
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ nil,
+ activityService,
+ nil,
+ nil,
+ nil,
+ nil,
+ )
require.NoError(t, err)
runtime := francistest.New(t)
require.NoError(t, svc.RegisterActors(runtime))
francistest.Start(t, runtime)
require.NoError(t, svc.Start(t.Context()))
t.Cleanup(func() {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), time.Second)
defer cancel()
require.NoError(t, svc.Stop(ctx))
})
@@ -153,8 +312,8 @@ func TestSingleUpdatePersistsSuccessfulActivity(t *testing.T) {
if runtime.Service().GetState(t.Context(), singleUpdateStateTypeInternal, accepted.ID, &state) != nil || state.Status != "completed" {
return false
}
- detail, err := activityService.GetActivityDetail(t.Context(), "0", accepted.ID, 1)
- return err == nil && detail.Activity.Status == activitytypes.StatusSuccess
+ detail, getActivityDetailErr := activityService.GetActivityDetail(t.Context(), "0", accepted.ID, 1)
+ return getActivityDetailErr == nil && detail.Activity.Status == activitytypes.StatusSuccess
}, 3*time.Second, 10*time.Millisecond)
detail, err := activityService.GetActivityDetail(t.Context(), "0", accepted.ID, 1)
require.NoError(t, err)
diff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.go
index a6cadf970..e8774b09b 100644
--- a/backend/internal/updater/service.go
+++ b/backend/internal/updater/service.go
@@ -97,14 +97,14 @@ type selfUpgradeServiceInternal interface {
// NewUpdaterService constructs the Arcane updater facade.
func NewUpdaterService(
db *database.DB,
- settings *settings.SettingsService,
- docker *docker.DockerClientService,
+ localSettings *settings.SettingsService,
+ localDocker *docker.DockerClientService,
projects *projectpkg.ProjectService,
imageUpdates *imageupdate.ImageUpdateService,
registries *registry.ContainerRegistryService,
events *event.EventService,
imageSvc *image.ImageService,
- notifications *notification.NotificationService,
+ localNotifications *notification.NotificationService,
upgrade selfUpgradeServiceInternal,
activityService *activity.ActivityService,
cfg *config.Config,
@@ -116,14 +116,14 @@ func NewUpdaterService(
config: cfg, coordinator: coordinator, admission: admission, roles: roles,
deps: updaterDependenciesInternal{
DB: db,
- Docker: docker,
- Settings: settings,
+ Docker: localDocker,
+ Settings: localSettings,
Projects: projects,
ImagePuller: imageSvc,
ImageUpdates: imageUpdates,
RegistryDigestResolver: registries,
Events: events,
- Notifications: notifications,
+ Notifications: localNotifications,
SelfUpgrade: upgrade,
Activity: activityService,
SystemUser: common.SystemUser,
@@ -229,8 +229,8 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, options arcaneupdater
// Bounded slot wait: an unbounded wait behind other long-running runs
// would strand the queued activity row (the completion defer above
// flips it to failed on timeout instead).
- if err = s.deps.Activity.AwaitActivitySlotBounded(ctx, activityID, "0"); err != nil {
- return out, err
+ if slotErr := s.deps.Activity.AwaitActivitySlotBounded(ctx, activityID, "0"); slotErr != nil {
+ return out, slotErr
}
}
@@ -251,8 +251,8 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, options arcaneupdater
s.appendAutoUpdateActivityMessageInternal(ctx, activityID, "Planning pending updates", "Planning updates", 5)
if len(options.ResourceIds) > 0 {
- if err = s.applyScopedUpdatesInternal(runCtx, options, out); err != nil {
- return out, err
+ if applyErr := s.applyScopedUpdatesInternal(runCtx, options, out); applyErr != nil {
+ return out, applyErr
}
} else {
moduleResult, engineErr := s.engineInternal().ApplyPending(runCtx, moduleOptionsFromUpdaterOptionsInternal(options))
@@ -307,8 +307,8 @@ func (s *UpdaterService) applyScopedUpdatesInternal(ctx context.Context, options
var engineErrs []error
for _, containerID := range containerIDs {
target := schedulertypes.TargetOutcome{ID: containerID, ResourceType: "container", Status: schedulertypes.Running}
- if err := jobcontext.Progress(ctx, target); err != nil {
- return err
+ if progressErr := jobcontext.Progress(ctx, target); progressErr != nil {
+ return progressErr
}
moduleResult, engineErr := s.engineInternal().UpdateContainer(ctx, containerID, engineOpts)
target.Status = schedulertypes.NeedsAttention
@@ -339,8 +339,8 @@ func (s *UpdaterService) applyScopedUpdatesInternal(ctx context.Context, options
target.Status = schedulertypes.Failed
target.Message = engineErr.Error()
}
- if err := jobcontext.Progress(ctx, target); err != nil {
- return errors.Join(err, errors.Join(engineErrs...))
+ if progressErr2 := jobcontext.Progress(ctx, target); progressErr2 != nil {
+ return errors.Join(progressErr2, errors.Join(engineErrs...))
}
}
s.logResultItemsInternal(ctx, out)
@@ -457,13 +457,13 @@ func (s *UpdaterService) containerIDsForImagesInternal(ctx context.Context, imag
// UpdateSingleContainer updates a single container by ID to the latest available image.
func (s *UpdaterService) UpdateSingleContainer(ctx context.Context, containerID string) (out *arcaneupdater.Result, err error) {
- activity, workCtx, err := s.startSingleContainerUpdateActivityInternal(ctx, containerID, true)
+ localActivity, workCtx, err := s.startSingleContainerUpdateActivityInternal(ctx, containerID, true)
if err != nil {
return nil, err
}
activityID := ""
- if activity != nil {
- activityID = activity.ID
+ if localActivity != nil {
+ activityID = localActivity.ID
}
defer func() {
s.finishSingleContainerUpdateInternal(workCtx, activityID, out, err)
@@ -477,20 +477,20 @@ func (s *UpdaterService) AcceptSingleContainerUpdate(ctx context.Context, contai
if s.deps.Activity == nil || s.singleUpdates == nil {
return nil, errors.New("asynchronous container updates unavailable")
}
- activity, workCtx, err := s.startSingleContainerUpdateActivityInternal(ctx, containerID, false)
+ localActivity, workCtx, err := s.startSingleContainerUpdateActivityInternal(ctx, containerID, false)
if err != nil {
return nil, err
}
- command := singleUpdateCommandInternal(ctx, containerID, activity.ID)
+ command := singleUpdateCommandInternal(ctx, containerID, localActivity.ID)
state := arcaneupdater.SingleUpdateState{Command: command, Status: "queued"}
- if err := s.singleUpdates.SetState(workCtx, singleUpdateStateTypeInternal, activity.ID, state, nil); err != nil {
- s.finishSingleContainerUpdateInternal(workCtx, activity.ID, nil, err)
- return nil, fmt.Errorf("persist container update: %w", err)
+ if setStateErr := s.singleUpdates.SetState(workCtx, singleUpdateStateTypeInternal, localActivity.ID, state, nil); setStateErr != nil {
+ s.finishSingleContainerUpdateInternal(workCtx, localActivity.ID, nil, setStateErr)
+ return nil, fmt.Errorf("persist container update: %w", setStateErr)
}
- if err := s.dispatchSingleInternal(workCtx, state); err != nil {
- s.loggerInternal().WarnContext(workCtx, "container update dispatch deferred", "activityId", activity.ID, "error", err)
+ if dispatchSingleErr := s.dispatchSingleInternal(workCtx, state); dispatchSingleErr != nil {
+ s.loggerInternal().WarnContext(workCtx, "container update dispatch deferred", "activityId", localActivity.ID, "error", dispatchSingleErr)
}
- return activity, nil
+ return localActivity, nil
}
func (s *UpdaterService) runSingleContainerUpdateInternal(ctx context.Context, containerID, activityID string) (out *arcaneupdater.Result, err error) {
@@ -504,8 +504,8 @@ func (s *UpdaterService) runSingleContainerUpdateInternal(ctx context.Context, c
out = &arcaneupdater.Result{Items: []arcaneupdater.ResourceResult{}, ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()}
ctx = contextWithActivityIDInternal(ctx, activityID)
if s.deps.Activity != nil && activityID != "" {
- if err := s.deps.Activity.AwaitActivitySlotBounded(ctx, activityID, "0"); err != nil {
- return out, err
+ if awaitActivitySlotBoundedErr := s.deps.Activity.AwaitActivitySlotBounded(ctx, activityID, "0"); awaitActivitySlotBoundedErr != nil {
+ return out, awaitActivitySlotBoundedErr
}
}
@@ -521,8 +521,8 @@ func (s *UpdaterService) runSingleContainerUpdateInternal(ctx context.Context, c
s.updateMu.Lock()
defer s.updateMu.Unlock()
- if err := ctx.Err(); err != nil {
- return out, err
+ if errErr := ctx.Err(); errErr != nil {
+ return out, errErr
}
// The caller picked this container, so the autoUpdateExcludedContainers
@@ -612,8 +612,8 @@ func autoUpdateEventTitleInternal(phase string, metadata database.JSON) string {
case "start":
return "Auto-update run started"
case "image_pull", "image":
- image := cmp.Or(kit.ToString(metadata["imageNew"]), kit.ToString(metadata["imageOld"]))
- return kit.Ternary(image != "", "Auto-update: image pull "+image, "Auto-update: image pull")
+ localImage := cmp.Or(kit.ToString(metadata["imageNew"]), kit.ToString(metadata["imageOld"]))
+ return kit.Ternary(localImage != "", "Auto-update: image pull "+localImage, "Auto-update: image pull")
case "image_prune":
imageID := kit.ToString(metadata["imageId"])
return kit.Ternary(imageID != "", "Auto-update: image prune "+imageID, "Auto-update: image prune")
@@ -662,18 +662,18 @@ func (s *UpdaterService) PullImage(ctx context.Context, imageRef string, progres
defer cancelPull()
if s.deps.Projects != nil {
- resolved, err := s.deps.Projects.ResolveRegistryCredentials(pullCtx)
- if err != nil {
- return fmt.Errorf("resolve registry credentials: %w", err)
+ resolved, resolveRegistryCredentialsErr := s.deps.Projects.ResolveRegistryCredentials(pullCtx)
+ if resolveRegistryCredentialsErr != nil {
+ return fmt.Errorf("resolve registry credentials: %w", resolveRegistryCredentialsErr)
}
- if err := s.deps.ImagePuller.PullImage(pullCtx, pulledRef, writer, s.deps.SystemUser, resolved); err != nil {
- return err
+ if pullImageErr := s.deps.ImagePuller.PullImage(pullCtx, pulledRef, writer, s.deps.SystemUser, resolved); pullImageErr != nil {
+ return pullImageErr
}
return s.tagFrozenPullInternal(pullCtx, pulledRef, imageRef)
}
- if err := s.deps.ImagePuller.PullImage(pullCtx, pulledRef, writer, s.deps.SystemUser, nil); err != nil {
- return err
+ if pullImageErr2 := s.deps.ImagePuller.PullImage(pullCtx, pulledRef, writer, s.deps.SystemUser, nil); pullImageErr2 != nil {
+ return pullImageErr2
}
return s.tagFrozenPullInternal(pullCtx, pulledRef, imageRef)
}
@@ -806,27 +806,27 @@ func (s *UpdaterService) markSelfUpdateTriggeredInternal(ctx context.Context, ta
// auto-update run (see withBatchedNotificationsInternal); buffered entries are
// flushed as one batched notification when the run completes. Outside a run it
// sends the legacy per-container notification immediately.
-func (s *UpdaterService) Notify(ctx context.Context, notification updater.Notification) error {
+func (s *UpdaterService) Notify(ctx context.Context, localNotification updater.Notification) error {
if s == nil || s.deps.Notifications == nil {
return nil
}
if buffer := batchedContainerUpdatesFromContextInternal(ctx); buffer != nil {
buffer.Lock()
buffer.entries = append(buffer.entries, notifications.ContainerUpdateBatchEntry{
- ContainerName: notification.ContainerName,
- ImageRef: notification.ImageRef,
- OldDigest: notification.OldImage,
- NewDigest: notification.NewImage,
+ ContainerName: localNotification.ContainerName,
+ ImageRef: localNotification.ImageRef,
+ OldDigest: localNotification.OldImage,
+ NewDigest: localNotification.NewImage,
})
buffer.Unlock()
return nil
}
return s.deps.Notifications.SendContainerUpdateNotification(
ctx,
- notification.ContainerName,
- notification.ImageRef,
- notification.OldImage,
- notification.NewImage,
+ localNotification.ContainerName,
+ localNotification.ImageRef,
+ localNotification.OldImage,
+ localNotification.NewImage,
)
}
@@ -936,7 +936,7 @@ func (s *UpdaterService) startAutoUpdateActivityInternal(ctx context.Context, dr
if s.deps.Activity == nil {
return ""
}
- activity, err := s.deps.Activity.StartActivity(ctx, activitylib.StartRequest{
+ localActivity, err := s.deps.Activity.StartActivity(ctx, activitylib.StartRequest{
EnvironmentID: "0",
Type: activitytypes.TypeAutoUpdate,
Queue: true,
@@ -950,7 +950,7 @@ func (s *UpdaterService) startAutoUpdateActivityInternal(ctx context.Context, dr
slog.DebugContext(ctx, "failed to start auto-update activity", "error", err)
return ""
}
- return activity.ID
+ return localActivity.ID
}
func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.Context, containerID string, tracked bool) (*activitytypes.Activity, context.Context, error) {
@@ -1324,9 +1324,9 @@ func (s *UpdaterService) CollectUsedImages(ctx context.Context) (map[string]stru
}
errs = append(errs, err)
s.loggerInternal().DebugContext(ctx, "collectUsedImages: docker connection unavailable", "error", err)
- } else if err := s.collectUsedImagesFromContainersInternal(ctx, dcli, out); err != nil {
- errs = append(errs, err)
- s.loggerInternal().DebugContext(ctx, "collectUsedImages: failed collecting from containers", "error", err)
+ } else if collectUsedImagesFromContainersErr := s.collectUsedImagesFromContainersInternal(ctx, dcli, out); collectUsedImagesFromContainersErr != nil {
+ errs = append(errs, collectUsedImagesFromContainersErr)
+ s.loggerInternal().DebugContext(ctx, "collectUsedImages: failed collecting from containers", "error", collectUsedImagesFromContainersErr)
} else {
successfulSources++
}
diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.go
index d9690270c..bca17a3a7 100644
--- a/backend/internal/updater/service_test.go
+++ b/backend/internal/updater/service_test.go
@@ -118,8 +118,8 @@ type fakeProjectUpdaterInternal struct {
}
func (f *fakeProjectUpdaterInternal) ProjectByComposeName(_ context.Context, composeName string) (updater.ComposeProject, error) {
- if project, ok := f.projects[composeName]; ok {
- return project, nil
+ if localProject, ok := f.projects[composeName]; ok {
+ return localProject, nil
}
return updater.ComposeProject{}, errors.New("project not found")
}
@@ -238,7 +238,7 @@ func (m *mockSystemUpgradeServiceInternal) TriggerUpgradeViaCLI(_ context.Contex
}
func TestUpdaterService_ApplyPendingNoRecordsInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDBInternal(t)
svc, svcErr := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
require.NoError(t, svcErr)
@@ -257,14 +257,24 @@ func TestUpdaterService_ApplyPendingNoRecordsInternal(t *testing.T) {
assert.Zero(t, result.Skipped)
assert.Zero(t, result.Failed)
assert.Empty(t, result.Items)
- ctx = jobcontext.WithExecution(context.Background(), schedulertypes.Run{AttemptCount: 1}, func(schedulertypes.TargetOutcome) error { return errors.New("checkpoint unavailable") })
+ ctx = jobcontext.WithExecution(t.Context(), schedulertypes.Run{AttemptCount: 1}, func(schedulertypes.TargetOutcome) error { return errors.New("checkpoint unavailable") })
_, err = svc.ApplyPending(ctx, arcaneupdater.Options{DryRun: true})
require.ErrorContains(t, err, "checkpoint unavailable")
var outcomeErr *schedulertypes.OutcomeError
require.ErrorAs(t, err, &outcomeErr)
assert.Equal(t, schedulertypes.NeedsAttention, outcomeErr.Outcome.Status)
checkpoints = nil
- ctx = jobcontext.WithExecution(context.Background(), schedulertypes.Run{AttemptCount: 1}, func(target schedulertypes.TargetOutcome) error { checkpoints = append(checkpoints, target); return nil })
+ ctx = jobcontext.WithExecution(
+ t.Context(),
+ schedulertypes.Run{AttemptCount: 1},
+ func(target schedulertypes.TargetOutcome) error {
+ checkpoints = append(
+ checkpoints,
+ target,
+ )
+ return nil
+ },
+ )
svc.engine = nil
require.Panics(t, func() { _, _ = svc.ApplyPending(ctx, arcaneupdater.Options{}) })
require.NotEmpty(t, checkpoints)
@@ -312,7 +322,7 @@ func TestUpdaterService_ResultFromModulePreservesRestartedInternal(t *testing.T)
}
func TestUpdaterService_TriggerSelfUpdateViaCLIInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("server label triggers upgrade with system user", func(t *testing.T) {
mockUpgrade := &mockSystemUpgradeServiceInternal{}
@@ -410,7 +420,7 @@ func TestUpdaterService_StatusTrackingInternal(t *testing.T) {
}
func TestUpdaterService_DockerClientAdapterInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("active engine updates correlate before the stop event is recorded", func(t *testing.T) {
events := event.NewEventService(nil, nil, nil)
svc, err := NewUpdaterService(nil, nil, nil, nil, nil, nil, events, nil, nil, nil, nil, nil, nil, nil, nil)
@@ -449,7 +459,7 @@ func TestUpdaterService_DockerClientAdapterInternal(t *testing.T) {
}
func TestUpdaterService_PullImageAdapterInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("missing image service returns unavailable error", func(t *testing.T) {
svc, svcErr := NewUpdaterService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
@@ -514,7 +524,7 @@ func TestUpdaterService_PullImageAdapterInternal(t *testing.T) {
}
func TestUpdaterService_PendingImageUpdatesAdapterInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDBInternal(t)
latest := "1.2.4"
currentDigest := "sha256:1111111111111111111111111111111111111111111111111111111111111111"
@@ -569,7 +579,9 @@ func newEmptyContainerListDockerServiceInternal(t *testing.T) *docker.DockerClie
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/containers/json") {
- require.NoError(t, json.MarshalWrite(w, []container.Summary{}))
+ if !assert.NoError(t, json.MarshalWrite(w, []container.Summary{})) {
+ return
+ }
return
}
http.NotFound(w, r)
@@ -590,7 +602,7 @@ func TestUpdaterService_PendingImageUpdatesAbortsWhenNotificationEligibilityUnre
require.NoError(t, err)
require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:pending", Repository: "test/repo", Tag: "latest", HasUpdate: true}).Error)
- records, err := svc.PendingImageUpdates(context.Background())
+ records, err := svc.PendingImageUpdates(t.Context())
require.ErrorContains(t, err, "flush pending update notifications")
require.Nil(t, records)
var reloaded imageupdate.ImageUpdateRecord
@@ -603,7 +615,7 @@ func TestUpdaterService_PendingImageUpdatesAbortsWhenNotificationEligibilityUnre
// notification_sent, so an "Updates Available" notification pending at consumption
// time was silently lost. PendingImageUpdates must flush it before the engine runs.
func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDBInternal(t)
require.NoError(t, db.AutoMigrate(&imageupdate.ImageUpdateRecord{}, &notification.NotificationSettings{}))
@@ -650,7 +662,7 @@ func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(t
// leaves notification_sent false (preserves the #3079 "don't mark when nothing
// delivered" semantics).
func TestUpdaterService_PendingImageUpdatesNoProvidersLeavesUnnotifiedInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDBInternal(t)
require.NoError(t, db.AutoMigrate(&imageupdate.ImageUpdateRecord{}, &notification.NotificationSettings{}))
@@ -677,7 +689,7 @@ func TestUpdaterService_PendingImageUpdatesNoProvidersLeavesUnnotifiedInternal(t
}
func TestUpdaterService_RecordUpdateRunAdapterInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDBInternal(t)
require.NoError(t, db.AutoMigrate(&AutoUpdateRecord{}))
svc, svcErr := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
@@ -718,7 +730,7 @@ func TestUpdaterService_RecordUpdateRunAdapterInternal(t *testing.T) {
}
func TestUpdaterService_RecordUpdateRunAppendsActivityMessageInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupProjectTestDBInternal(t)
require.NoError(t, db.AutoMigrate(&AutoUpdateRecord{}, &activity.Activity{}, &activity.ActivityMessage{}))
activityService := activity.NewActivityService(db, nil)
@@ -732,8 +744,14 @@ func TestUpdaterService_RecordUpdateRunAppendsActivityMessageInternal(t *testing
wantMessage string
}{
{
- name: "failed with reason",
- result: updater.ResourceResult{ResourceID: "c1", ResourceName: "sonarr", ResourceType: updater.ResourceTypeContainer, Status: updater.StatusFailed, Error: "pull failed: unexpected EOF"},
+ name: "failed with reason",
+ result: updater.ResourceResult{
+ ResourceID: "c1",
+ ResourceName: "sonarr",
+ ResourceType: updater.ResourceTypeContainer,
+ Status: updater.StatusFailed,
+ Error: "pull failed: unexpected EOF",
+ },
wantLevel: activitytypes.MessageLevelError,
wantMessage: "sonarr: pull failed: unexpected EOF",
},
@@ -744,14 +762,26 @@ func TestUpdaterService_RecordUpdateRunAppendsActivityMessageInternal(t *testing
wantMessage: "dozzle: failed",
},
{
- name: "updated includes image change",
- result: updater.ResourceResult{ResourceID: "c3", ResourceName: "maintainerr", ResourceType: updater.ResourceTypeContainer, Status: updater.StatusUpdated, OldImage: "sha256:old", NewImage: "ghcr.io/maintainerr/maintainerr:latest"},
+ name: "updated includes image change",
+ result: updater.ResourceResult{
+ ResourceID: "c3",
+ ResourceName: "maintainerr",
+ ResourceType: updater.ResourceTypeContainer,
+ Status: updater.StatusUpdated,
+ OldImage: "sha256:old",
+ NewImage: "ghcr.io/maintainerr/maintainerr:latest",
+ },
wantLevel: activitytypes.MessageLevelInfo,
wantMessage: "maintainerr: updated (sha256:old -> ghcr.io/maintainerr/maintainerr:latest)",
},
{
- name: "skipped unnamed uses resource id and reason",
- result: updater.ResourceResult{ResourceID: "arcane-id", ResourceType: updater.ResourceTypeContainer, Status: updater.StatusSkipped, Error: "container excluded by settings"},
+ name: "skipped unnamed uses resource id and reason",
+ result: updater.ResourceResult{
+ ResourceID: "arcane-id",
+ ResourceType: updater.ResourceTypeContainer,
+ Status: updater.StatusSkipped,
+ Error: "container excluded by settings",
+ },
wantLevel: activitytypes.MessageLevelInfo,
wantMessage: "arcane-id: skipped (container excluded by settings)",
},
@@ -799,7 +829,7 @@ func TestUpdaterService_AcceptSingleContainerUpdateUsesQueuedActivityInternal(t
}()
<-started
- requestCtx, cancelRequest := context.WithCancel(context.Background())
+ requestCtx, cancelRequest := context.WithCancel(t.Context())
workCtx := utils.ActivityRuntimeContext(requestCtx, t.Context())
type acceptedInternal struct {
activity *activitytypes.Activity
@@ -821,7 +851,7 @@ func TestUpdaterService_AcceptSingleContainerUpdateUsesQueuedActivityInternal(t
require.Equal(t, activitytypes.StatusQueued, item.Status)
cancelRequest()
if cancelActivity {
- _, err = activityService.CancelActivity(context.Background(), "0", item.ID, "test")
+ _, err = activityService.CancelActivity(t.Context(), "0", item.ID, "test")
require.NoError(t, err)
}
releaseOnce.Do(func() { close(release) })
@@ -845,7 +875,7 @@ func TestUpdaterService_AcceptSingleContainerUpdateFailureFinalizesInternal(t *t
require.NoError(t, svc.RegisterActors(runtime))
// A service whose host has not started rejects durable dispatch.
- accepted, err := svc.AcceptSingleContainerUpdate(context.Background(), "container-1")
+ accepted, err := svc.AcceptSingleContainerUpdate(t.Context(), "container-1")
require.Nil(t, accepted)
require.ErrorContains(t, err, "persist container update")
var saved activity.Activity
@@ -854,7 +884,7 @@ func TestUpdaterService_AcceptSingleContainerUpdateFailureFinalizesInternal(t *t
unmigrated := setupProjectTestDBInternal(t)
svc.deps.Activity = activity.NewActivityService(unmigrated, nil)
- accepted, err = svc.AcceptSingleContainerUpdate(context.Background(), "container-2")
+ accepted, err = svc.AcceptSingleContainerUpdate(t.Context(), "container-2")
require.Nil(t, accepted)
require.ErrorContains(t, err, "start container update activity")
}
@@ -866,11 +896,63 @@ func TestUpdaterService_SingleContainerActivityResultMessagesInternal(t *testing
wantStatus activitytypes.Status
wantMessage string
}{
- {name: "updated", result: &arcaneupdater.Result{Updated: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusUpdated), ResourceName: "web"}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container updated"},
- {name: "restarted", result: &arcaneupdater.Result{Restarted: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusRestarted), ResourceName: "web"}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container updated"},
- {name: "skipped", result: &arcaneupdater.Result{Skipped: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusSkipped), Error: "immutable image reference"}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container update skipped: immutable image reference"},
- {name: "already current", result: &arcaneupdater.Result{Checked: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusUpToDate)}}}, wantStatus: activitytypes.StatusSuccess, wantMessage: "Container already current"},
- {name: "failed", result: &arcaneupdater.Result{Failed: 1, Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusFailed), Error: "pull failed"}}}, wantStatus: activitytypes.StatusFailed, wantMessage: "pull failed"},
+ {
+ name: "updated",
+ result: &arcaneupdater.Result{
+ Updated: 1,
+ Items: []arcaneupdater.ResourceResult{{
+ Status: string(updater.StatusUpdated),
+ ResourceName: "web",
+ }},
+ },
+ wantStatus: activitytypes.StatusSuccess,
+ wantMessage: "Container updated",
+ },
+ {
+ name: "restarted",
+ result: &arcaneupdater.Result{
+ Restarted: 1,
+ Items: []arcaneupdater.ResourceResult{{
+ Status: string(updater.StatusRestarted),
+ ResourceName: "web",
+ }},
+ },
+ wantStatus: activitytypes.StatusSuccess,
+ wantMessage: "Container updated",
+ },
+ {
+ name: "skipped",
+ result: &arcaneupdater.Result{
+ Skipped: 1,
+ Items: []arcaneupdater.ResourceResult{{
+ Status: string(updater.StatusSkipped),
+ Error: "immutable image reference",
+ }},
+ },
+ wantStatus: activitytypes.StatusSuccess,
+ wantMessage: "Container update skipped: immutable image reference",
+ },
+ {
+ name: "already current",
+ result: &arcaneupdater.Result{
+ Checked: 1,
+ Items: []arcaneupdater.ResourceResult{{Status: string(updater.StatusUpToDate)}},
+ },
+ wantStatus: activitytypes.StatusSuccess,
+ wantMessage: "Container already current",
+ },
+ {
+ name: "failed",
+ result: &arcaneupdater.Result{
+ Failed: 1,
+ Items: []arcaneupdater.ResourceResult{{
+ Status: string(updater.StatusFailed),
+ Error: "pull failed",
+ }},
+ },
+ wantStatus: activitytypes.StatusFailed,
+ wantMessage: "pull failed",
+ },
} {
t.Run(tt.name, func(t *testing.T) {
db := setupProjectTestDBInternal(t)
@@ -878,7 +960,14 @@ func TestUpdaterService_SingleContainerActivityResultMessagesInternal(t *testing
activityService := activity.NewActivityService(db, nil)
svc, err := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, activityService, nil, nil, nil, nil)
require.NoError(t, err)
- started, err := activityService.StartActivity(t.Context(), activitylib.StartRequest{EnvironmentID: "0", Type: activitytypes.TypeAutoUpdate, Metadata: database.JSON{"containerID": "old-id"}})
+ started, err := activityService.StartActivity(
+ t.Context(),
+ activitylib.StartRequest{
+ EnvironmentID: "0",
+ Type: activitytypes.TypeAutoUpdate,
+ Metadata: database.JSON{"containerID": "old-id"},
+ },
+ )
require.NoError(t, err)
svc.finishSingleContainerUpdateInternal(t.Context(), started.ID, tt.result, nil)
var saved activity.Activity
@@ -891,7 +980,7 @@ func TestUpdaterService_SingleContainerActivityResultMessagesInternal(t *testing
}
func TestUpdaterService_ApplyPending_ProjectFailureDoesNotBlockOtherProjectsInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
oldRefFailed := "registry.example.com/team/fail:1.0.0"
newRefFailed := "registry.example.com/team/fail:1.0.1"
@@ -946,7 +1035,15 @@ func TestUpdaterService_ApplyPending_ProjectFailureDoesNotBlockOtherProjectsInte
}
inspectByID := map[string]container.InspectResponse{
- "container-success-new": {ID: "container-success-new", Image: newImageIDUpdated, Config: &container.Config{Image: newRefUpdated, Labels: updatedLabels}, State: &container.State{Running: true}},
+ "container-success-new": {
+ ID: "container-success-new",
+ Image: newImageIDUpdated,
+ Config: &container.Config{
+ Image: newRefUpdated,
+ Labels: updatedLabels,
+ },
+ State: &container.State{Running: true},
+ },
"container-fail": {
ID: "container-fail",
Image: oldImageIDFailed,
@@ -1060,7 +1157,7 @@ func TestUpdaterService_ApplyPending_ProjectFailureDoesNotBlockOtherProjectsInte
}
func TestUpdaterService_ApplyPending_RoutesLegacyArcaneServerThroughSelfUpgradeInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
oldRef := "ghcr.io/getarcaneapp/arcane:1.0.0"
newRef := "ghcr.io/getarcaneapp/arcane:1.0.1"
@@ -1151,7 +1248,15 @@ func TestUpdaterService_ApplyPending_RoutesLegacyArcaneServerThroughSelfUpgradeI
})
svc.engine = engine
- ctx = context.WithValue(ctx, frozenPendingKeyInternal{}, &frozenUpdatePlanInternal{Targets: []arcaneupdater.FrozenUpdateTarget{{ContainerID: "arcane-container", DesiredImageRef: newRef, DesiredDigest: "sha256:desired"}}})
+ ctx = context.WithValue(
+ ctx,
+ frozenPendingKeyInternal{},
+ &frozenUpdatePlanInternal{Targets: []arcaneupdater.FrozenUpdateTarget{{
+ ContainerID: "arcane-container",
+ DesiredImageRef: newRef,
+ DesiredDigest: "sha256:desired",
+ }}},
+ )
ctx = jobcontext.WithExecution(ctx, schedulertypes.Run{AttemptCount: 1}, nil)
result, err := svc.ApplyPending(ctx, arcaneupdater.Options{})
require.ErrorContains(t, err, "self-update was triggered")
@@ -1207,20 +1312,20 @@ func TestPullableImageRefInternal(t *testing.T) {
// Test fixtures shared by this package's tests.
// createTestPullRegistryInternal inserts an enabled generic registry with an encrypted token.
-func createTestPullRegistryInternal(t *testing.T, db *database.DB, url, username, token string) {
+func createTestPullRegistryInternal(t *testing.T, db *database.DB, localUrl, username, token string) {
t.Helper()
encryptedToken, err := crypto.Encrypt(token)
require.NoError(t, err)
reg := &registry.ContainerRegistry{
- URL: url,
+ URL: localUrl,
Username: username,
Token: encryptedToken,
Enabled: true,
RegistryType: registry.RegistryTypeGeneric,
}
- require.NoError(t, db.WithContext(context.Background()).Create(reg).Error)
+ require.NoError(t, db.WithContext(t.Context()).Create(reg).Error)
}
// decodeRegistryAuthInternal decodes a base64 X-Registry-Auth header.
@@ -1321,8 +1426,26 @@ func TestUpdaterService_ScopedPendingRecordsIsolationInternal(t *testing.T) {
imageRef := "registry.example.com/team/app:1.2.3"
stored := []imageupdate.ImageUpdateRecord{
{ID: "shared-image", Repository: "registry.example.com/team/app", Tag: "1.2.3", HasUpdate: true, UpdateType: imageupdate.UpdateTypeDigest},
- {ID: "container::tag-a", ContainerID: "tag-a", ImageID: "shared-image", Repository: "registry.example.com/team/app", Tag: "1.2.3", HasUpdate: true, UpdateType: imageupdate.UpdateTypeTag, LatestVersion: new("1.3.0")},
- {ID: "container::tag-b", ContainerID: "tag-b", ImageID: "shared-image", Repository: "registry.example.com/team/app", Tag: "1.2.3", HasUpdate: true, UpdateType: imageupdate.UpdateTypeTag, LatestVersion: new("1.2.4")},
+ {
+ ID: "container::tag-a",
+ ContainerID: "tag-a",
+ ImageID: "shared-image",
+ Repository: "registry.example.com/team/app",
+ Tag: "1.2.3",
+ HasUpdate: true,
+ UpdateType: imageupdate.UpdateTypeTag,
+ LatestVersion: new("1.3.0"),
+ },
+ {
+ ID: "container::tag-b",
+ ContainerID: "tag-b",
+ ImageID: "shared-image",
+ Repository: "registry.example.com/team/app",
+ Tag: "1.2.3",
+ HasUpdate: true,
+ UpdateType: imageupdate.UpdateTypeTag,
+ LatestVersion: new("1.2.4"),
+ },
}
require.NoError(t, db.Create(&stored).Error)
containers := []container.Summary{
@@ -1403,13 +1526,40 @@ func (projectCheckRegistryInternal) ImageDigest(context.Context, string) (string
func TestUpdaterProjectChecksWithoutContainersInternal(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- require.Contains(t, r.URL.Path, "/images/", "project checks must not need containers")
+ if !assert.Contains(t, r.URL.Path, "/images/", "project checks must not need containers") {
+ return
+ }
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.MarshalWrite(w, dockertypesimage.InspectResponse{ID: "sha256:" + strings.Repeat("a", 64), RepoDigests: []string{"alpine@sha256:" + strings.Repeat("a", 64)}}))
+ if !assert.NoError(
+ t,
+ json.MarshalWrite(
+ w,
+ dockertypesimage.InspectResponse{
+ ID: "sha256:" + strings.Repeat(
+ "a",
+ 64,
+ ),
+ RepoDigests: []string{"alpine@sha256:" + strings.Repeat(
+ "a",
+ 64,
+ )},
+ },
+ ),
+ ) {
+ return
+ }
}))
defer server.Close()
puller := &fakeImagePullerInternal{}
- engine, err := updater.New(updater.Config{DockerClientProvider: fakeDockerClientProviderInternal{client: newTestDockerClientInternal(t, server)}, RegistryTagLister: projectCheckRegistryInternal{}, RegistryDigestResolver: projectCheckRegistryInternal{}, ImagePuller: puller})
+ engine, err := updater.New(updater.Config{
+ DockerClientProvider: fakeDockerClientProviderInternal{client: newTestDockerClientInternal(
+ t,
+ server,
+ )},
+ RegistryTagLister: projectCheckRegistryInternal{},
+ RegistryDigestResolver: projectCheckRegistryInternal{},
+ ImagePuller: puller,
+ })
require.NoError(t, err)
service := &UpdaterService{engine: engine}
for _, metadata := range []bool{false, true} {
@@ -1421,13 +1571,25 @@ func TestUpdaterProjectChecksWithoutContainersInternal(t *testing.T) {
{"second", "=3.20.2", "3.20.2", true},
{"control", "=3.20.0", "3.20.0", false},
} {
- config := composetypes.ServiceConfig{Name: tt.name, Image: "alpine:3.20.0", Labels: map[string]string{labels.LabelUpdateConstraint: tt.constraint}}
+ localConfig := composetypes.ServiceConfig{Name: tt.name, Image: "alpine:3.20.0", Labels: map[string]string{labels.LabelUpdateConstraint: tt.constraint}}
if metadata {
- model, loadErr := projectspkg.LoadComposeProjectFromContent(t.Context(), projecttypes.ComposeContentOptions{ProjectName: "metadata", WorkingDir: t.TempDir(), ComposeContent: fmt.Sprintf("x-arcane:\n updater:\n strategy: auto\nservices:\n %s:\n image: alpine:3.20.0\n x-arcane:\n updater:\n constraint: %q\n", tt.name, tt.constraint)})
+ model, loadErr := projectspkg.LoadComposeProjectFromContent(
+ t.Context(),
+ projecttypes.ComposeContentOptions{
+ ProjectName: "metadata",
+ WorkingDir: t.TempDir(),
+ ComposeContent: fmt.Sprintf(
+ "x-arcane:\n updater:\n strategy: auto\nservices:\n %s:\n image: alpine:3.20.0\n x-arcane:\n "+
+ " updater:\n constraint: %q\n",
+ tt.name,
+ tt.constraint,
+ ),
+ },
+ )
require.NoError(t, loadErr)
- config = model.Services[tt.name]
+ localConfig = model.Services[tt.name]
}
- record := service.checkProjectServiceInternal(t.Context(), "project", config)
+ record := service.checkProjectServiceInternal(t.Context(), "project", localConfig)
require.Nil(t, record.LastError)
require.Equal(t, tt.available, record.HasUpdate)
require.Equal(t, tt.target, *record.LatestVersion)
diff --git a/backend/internal/updater/tag_updates.go b/backend/internal/updater/tag_updates.go
index e4e0e263c..cbf322155 100644
--- a/backend/internal/updater/tag_updates.go
+++ b/backend/internal/updater/tag_updates.go
@@ -136,22 +136,31 @@ func (s *UpdaterService) CheckProjectUpdates(ctx context.Context, projectID stri
}
records = append(records, s.checkProjectServiceInternal(ctx, projectID, service))
}
- if err := s.deps.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := tx.Where("project_id = ?", projectID).Delete(&imageupdate.ImageUpdateRecord{}).Error; err != nil {
- return err
+ if transactionErr := s.deps.DB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if deleteProjectUpdatesErr := tx.Where("project_id = ?", projectID).Delete(&imageupdate.ImageUpdateRecord{}).Error; deleteProjectUpdatesErr != nil {
+ return deleteProjectUpdatesErr
}
if len(records) == 0 {
return nil
}
return tx.Create(&records).Error
- }); err != nil {
- return nil, fmt.Errorf("save project update checks: %w", err)
+ }); transactionErr != nil {
+ return nil, fmt.Errorf("save project update checks: %w", transactionErr)
}
return project.BuildConfiguredUpdateInfo(projectID, details.Services, nil, records), nil
}
func (s *UpdaterService) checkProjectServiceInternal(ctx context.Context, projectID string, service composetypes.ServiceConfig) imageupdate.ImageUpdateRecord {
- record := imageupdate.ImageUpdateRecord{ID: "project::" + projectID + "::" + service.Name, ProjectID: projectID, ServiceName: service.Name, PolicyKey: imageref.UpdatePolicyKey(service.Image, service.Labels), CheckTime: time.Now().UTC()}
+ record := imageupdate.ImageUpdateRecord{
+ ID: "project::" + projectID + "::" + service.Name,
+ ProjectID: projectID,
+ ServiceName: service.Name,
+ PolicyKey: imageref.UpdatePolicyKey(
+ service.Image,
+ service.Labels,
+ ),
+ CheckTime: time.Now().UTC(),
+ }
parsed, err := refs.NormalizeReference(service.Image)
if err != nil {
record.LastError = new(err.Error())
diff --git a/backend/internal/upload/service_test.go b/backend/internal/upload/service_test.go
index b0f828799..a92978203 100644
--- a/backend/internal/upload/service_test.go
+++ b/backend/internal/upload/service_test.go
@@ -35,16 +35,16 @@ func TestSessionChunkRoundTrip(t *testing.T) {
t.Fatalf("TotalChunks = %d, want 3", session.TotalChunks)
}
- if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 3, payload[:chunkSize]); !errors.Is(err, common.ErrUploadChunkInvalid) {
- t.Fatalf("out-of-range chunk error = %v, want ErrUploadChunkInvalid", err)
+ if _, writeChunkErr := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 3, payload[:chunkSize]); !errors.Is(writeChunkErr, common.ErrUploadChunkInvalid) {
+ t.Fatalf("out-of-range chunk error = %v, want ErrUploadChunkInvalid", writeChunkErr)
}
- if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 2, payload[:chunkSize]); !errors.Is(err, common.ErrUploadChunkInvalid) {
- t.Fatalf("wrong-length chunk error = %v, want ErrUploadChunkInvalid", err)
+ if _, writeChunkErr2 := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 2, payload[:chunkSize]); !errors.Is(writeChunkErr2, common.ErrUploadChunkInvalid) {
+ t.Fatalf("wrong-length chunk error = %v, want ErrUploadChunkInvalid", writeChunkErr2)
}
// Chunks arrive out of order; the session stays resumable in between.
- if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 2, payload[2*chunkSize:]); err != nil {
- t.Fatalf("WriteChunk(2): %v", err)
+ if _, writeChunkErr3 := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 2, payload[2*chunkSize:]); writeChunkErr3 != nil {
+ t.Fatalf("WriteChunk(2): %v", writeChunkErr3)
}
updated, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 0, payload[:chunkSize])
if err != nil {
@@ -53,15 +53,15 @@ func TestSessionChunkRoundTrip(t *testing.T) {
if got := updated.ReceivedChunks; len(got) != 2 || got[0] != 0 || got[1] != 2 || updated.Complete {
t.Fatalf("session after partial upload = %+v", updated)
}
- if _, _, _, err := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID); !errors.Is(err, common.ErrUploadSessionIncomplete) {
- t.Fatalf("incomplete Consume error = %v, want ErrUploadSessionIncomplete", err)
+ if _, _, _, consumeErr := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID); !errors.Is(consumeErr, common.ErrUploadSessionIncomplete) {
+ t.Fatalf("incomplete Consume error = %v, want ErrUploadSessionIncomplete", consumeErr)
}
- if _, err := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 1, payload[chunkSize:2*chunkSize]); err != nil {
- t.Fatalf("WriteChunk(1): %v", err)
+ if _, writeChunkErr4 := service.WriteChunk(ctx, uploadtypes.KindBuildWorkspace, session.ID, 1, payload[chunkSize:2*chunkSize]); writeChunkErr4 != nil {
+ t.Fatalf("WriteChunk(1): %v", writeChunkErr4)
}
- if _, _, _, err := service.Consume(ctx, uploadtypes.KindImage, session.ID); !errors.Is(err, common.ErrUploadKindMismatch) {
- t.Fatalf("wrong-kind Consume error = %v, want ErrUploadKindMismatch", err)
+ if _, _, _, consumeErr2 := service.Consume(ctx, uploadtypes.KindImage, session.ID); !errors.Is(consumeErr2, common.ErrUploadKindMismatch) {
+ t.Fatalf("wrong-kind Consume error = %v, want ErrUploadKindMismatch", consumeErr2)
}
file, consumed, cleanup, err := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID)
@@ -72,8 +72,8 @@ func TestSessionChunkRoundTrip(t *testing.T) {
t.Fatalf("consumed session = %+v", consumed)
}
// Sessions are single-use: a concurrent second consumer must not see it.
- if _, _, _, err := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID); !errors.Is(err, common.ErrUploadSessionNotFound) {
- t.Fatalf("second Consume error = %v, want ErrUploadSessionNotFound", err)
+ if _, _, _, consumeErr3 := service.Consume(ctx, uploadtypes.KindBuildWorkspace, session.ID); !errors.Is(consumeErr3, common.ErrUploadSessionNotFound) {
+ t.Fatalf("second Consume error = %v, want ErrUploadSessionNotFound", consumeErr3)
}
assembled, err := io.ReadAll(file)
if err != nil {
@@ -83,8 +83,8 @@ func TestSessionChunkRoundTrip(t *testing.T) {
t.Fatalf("assembled file differs from input (%d vs %d bytes)", len(assembled), len(payload))
}
cleanup()
- if _, err := os.Stat(filepath.Join(service.root, session.ID)); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("session dir still present after cleanup: %v", err)
+ if _, statErr := os.Stat(filepath.Join(service.root, session.ID)); !errors.Is(statErr, os.ErrNotExist) {
+ t.Fatalf("session dir still present after cleanup: %v", statErr)
}
}
@@ -114,7 +114,7 @@ func TestIngestSessionCreatesCompleteSession(t *testing.T) {
t.Fatalf("assembled = %q, want %q", assembled, payload)
}
- if _, err := service.IngestSession(ctx, uploadtypes.KindBuildWorkspace, "short.bin", 10, bytes.NewReader([]byte("abc"))); err == nil {
+ if _, ingestSessionErr := service.IngestSession(ctx, uploadtypes.KindBuildWorkspace, "short.bin", 10, bytes.NewReader([]byte("abc"))); ingestSessionErr == nil {
t.Fatal("IngestSession with short source unexpectedly succeeded")
}
}
@@ -130,8 +130,8 @@ func TestPurgeExpiredSessionsRemovesOnlyStaleSessions(t *testing.T) {
// Expiry is idle-based: backdate every mtime the purge inspects.
idle := time.Now().Add(-48 * time.Hour)
for _, name := range []string{"", "meta.json", "data"} {
- if err := os.Chtimes(filepath.Join(service.root, stale.ID, name), idle, idle); err != nil {
- t.Fatalf("backdate stale session: %v", err)
+ if chtimesErr := os.Chtimes(filepath.Join(service.root, stale.ID, name), idle, idle); chtimesErr != nil {
+ t.Fatalf("backdate stale session: %v", chtimesErr)
}
}
fresh, err := service.CreateSession(ctx, uploadtypes.KindBuildWorkspace, uploadtypes.CreateSessionRequest{Filename: "fresh.bin", Size: 1})
@@ -146,10 +146,10 @@ func TestPurgeExpiredSessionsRemovesOnlyStaleSessions(t *testing.T) {
if removed != 1 {
t.Fatalf("removed = %d, want 1", removed)
}
- if _, err := service.GetSession(ctx, uploadtypes.KindBuildWorkspace, stale.ID); !errors.Is(err, common.ErrUploadSessionNotFound) {
- t.Fatalf("stale session error = %v, want ErrUploadSessionNotFound", err)
+ if _, getSessionErr := service.GetSession(ctx, uploadtypes.KindBuildWorkspace, stale.ID); !errors.Is(getSessionErr, common.ErrUploadSessionNotFound) {
+ t.Fatalf("stale session error = %v, want ErrUploadSessionNotFound", getSessionErr)
}
- if _, err := service.GetSession(ctx, uploadtypes.KindBuildWorkspace, fresh.ID); err != nil {
- t.Fatalf("fresh session should survive purge: %v", err)
+ if _, getSessionErr2 := service.GetSession(ctx, uploadtypes.KindBuildWorkspace, fresh.ID); getSessionErr2 != nil {
+ t.Fatalf("fresh session should survive purge: %v", getSessionErr2)
}
}
diff --git a/backend/internal/upload/upload.go b/backend/internal/upload/upload.go
index 4cc7e6963..ccdeeb064 100644
--- a/backend/internal/upload/upload.go
+++ b/backend/internal/upload/upload.go
@@ -108,13 +108,13 @@ func (s *UploadService) CreateSession(ctx context.Context, kind string, request
ReceivedChunks: []int{},
CreatedAt: time.Now().UTC(),
}
- if err := acfs.Write(ctx, s.root, path.Join(sessionDir, sessionDataFilename), nil, acfs.WriteOptions{Mode: 0o600}); err != nil {
+ if writeErr := acfs.Write(ctx, s.root, path.Join(sessionDir, sessionDataFilename), nil, acfs.WriteOptions{Mode: 0o600}); writeErr != nil {
_ = acfs.RemoveAll(ctx, s.root, sessionDir)
- return nil, fmt.Errorf("create upload session data file: %w", err)
+ return nil, fmt.Errorf("create upload session data file: %w", writeErr)
}
- if err := s.writeMetaInternal(ctx, session); err != nil {
+ if writeMetaErr := s.writeMetaInternal(ctx, session); writeMetaErr != nil {
_ = acfs.RemoveAll(ctx, s.root, sessionDir)
- return nil, err
+ return nil, writeMetaErr
}
return session, nil
}
@@ -136,7 +136,7 @@ func (s *UploadService) loadMetaInternal(ctx context.Context, kind, uploadID str
return nil, fmt.Errorf("%w: %s", common.ErrUploadSessionNotFound, uploadID)
}
var session uploadtypes.Session
- if err := json.Unmarshal(payload, &session); err != nil {
+ if unmarshalErr := json.Unmarshal(payload, &session); unmarshalErr != nil {
return nil, fmt.Errorf("%w: corrupt session metadata", common.ErrUploadSessionNotFound)
}
if session.Kind != kind {
@@ -152,8 +152,8 @@ func (s *UploadService) writeMetaInternal(ctx context.Context, session *uploadty
if err != nil {
return fmt.Errorf("encode upload session metadata: %w", err)
}
- if err := acfs.Write(ctx, s.root, path.Join("/", session.ID, sessionMetaFilename), payload, acfs.WriteOptions{Mode: 0o600}); err != nil {
- return fmt.Errorf("write upload session metadata: %w", err)
+ if writeErr := acfs.Write(ctx, s.root, path.Join("/", session.ID, sessionMetaFilename), payload, acfs.WriteOptions{Mode: 0o600}); writeErr != nil {
+ return fmt.Errorf("write upload session metadata: %w", writeErr)
}
return nil
}
@@ -182,13 +182,13 @@ func (s *UploadService) WriteChunk(ctx context.Context, kind, uploadID string, i
if err != nil {
return nil, err
}
- if err := acfs.WriteAt(ctx, s.root, dataPath, int64(index)*session.ChunkSize, data); err != nil {
- return nil, fmt.Errorf("write chunk %d: %w", index, err)
+ if writeAtErr := acfs.WriteAt(ctx, s.root, dataPath, int64(index)*session.ChunkSize, data); writeAtErr != nil {
+ return nil, fmt.Errorf("write chunk %d: %w", index, writeAtErr)
}
if position, found := slices.BinarySearch(session.ReceivedChunks, index); !found {
session.ReceivedChunks = slices.Insert(session.ReceivedChunks, position, index)
- if err := s.writeMetaInternal(ctx, session); err != nil {
- return nil, err
+ if writeMetaErr := s.writeMetaInternal(ctx, session); writeMetaErr != nil {
+ return nil, writeMetaErr
}
}
return session, nil
@@ -222,16 +222,16 @@ func (s *UploadService) IngestSession(ctx context.Context, kind, filename string
if err != nil {
return nil, err
}
- if _, err := acfs.WriteFrom(ctx, s.root, path.Join("/", session.ID, sessionDataFilename), source, size, 0o600); err != nil {
+ if _, writeFromErr := acfs.WriteFrom(ctx, s.root, path.Join("/", session.ID, sessionDataFilename), source, size, 0o600); writeFromErr != nil {
_ = acfs.RemoveAll(ctx, s.root, path.Join("/", session.ID))
- return nil, fmt.Errorf("write uploaded file: %w", err)
+ return nil, fmt.Errorf("write uploaded file: %w", writeFromErr)
}
for index := range session.TotalChunks {
session.ReceivedChunks = append(session.ReceivedChunks, index)
}
- if err := s.writeMetaInternal(ctx, session); err != nil {
+ if writeMetaErr := s.writeMetaInternal(ctx, session); writeMetaErr != nil {
_ = acfs.RemoveAll(ctx, s.root, path.Join("/", session.ID))
- return nil, err
+ return nil, writeMetaErr
}
return session, nil
}
@@ -263,9 +263,9 @@ func (s *UploadService) Consume(ctx context.Context, kind, uploadID string) (io.
_ = file.Close()
return nil, nil, nil, fmt.Errorf("%w: assembled size %d does not match declared size %d", common.ErrUploadSessionIncomplete, size, session.Size)
}
- if err := acfs.Remove(ctx, s.root, path.Join("/", uploadID, sessionMetaFilename)); err != nil {
+ if removeErr := acfs.Remove(ctx, s.root, path.Join("/", uploadID, sessionMetaFilename)); removeErr != nil {
_ = file.Close()
- return nil, nil, nil, fmt.Errorf("mark upload session consumed: %w", err)
+ return nil, nil, nil, fmt.Errorf("mark upload session consumed: %w", removeErr)
}
cleanup := func() {
_ = file.Close()
diff --git a/backend/internal/user/handler.go b/backend/internal/user/handler.go
index d874ba26b..a53ec5d8e 100644
--- a/backend/internal/user/handler.go
+++ b/backend/internal/user/handler.go
@@ -178,8 +178,8 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*
input.Body.Email = normalizedEmail
passwordPolicy := h.passwordPolicyInternal(ctx)
- if err := validation.ValidatePasswordPolicy(input.Body.Password, passwordPolicy); err != nil {
- return nil, handlerutil.Error400BadRequestWithType(err.Error(), validation.PasswordPolicyProblemType(passwordPolicy))
+ if validatePasswordPolicyErr := validation.ValidatePasswordPolicy(input.Body.Password, passwordPolicy); validatePasswordPolicyErr != nil {
+ return nil, handlerutil.Error400BadRequestWithType(validatePasswordPolicyErr.Error(), validation.PasswordPolicyProblemType(passwordPolicy))
}
hashedPassword, err := h.userService.HashPassword(input.Body.Password)
@@ -255,9 +255,9 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
input.Body.Email = normalizedEmail
if input.Body.Username != nil {
- normalizedUsername, err := normalizeUsernameInternal(*input.Body.Username)
- if err != nil {
- return nil, huma.Error400BadRequest(err.Error())
+ normalizedUsername, normalizeUsernameErr := normalizeUsernameInternal(*input.Body.Username)
+ if normalizeUsernameErr != nil {
+ return nil, huma.Error400BadRequest(normalizeUsernameErr.Error())
}
userModel.Username = normalizedUsername
}
@@ -283,11 +283,11 @@ func (h *UserHandler) UpdateUser(ctx context.Context, input *UpdateUserInput) (*
if input.Body.Password != nil && *input.Body.Password != "" {
passwordPolicy := h.passwordPolicyInternal(ctx)
- if err := validation.ValidatePasswordPolicy(*input.Body.Password, passwordPolicy); err != nil {
- return nil, handlerutil.Error400BadRequestWithType(err.Error(), validation.PasswordPolicyProblemType(passwordPolicy))
+ if validatePasswordPolicyErr := validation.ValidatePasswordPolicy(*input.Body.Password, passwordPolicy); validatePasswordPolicyErr != nil {
+ return nil, handlerutil.Error400BadRequestWithType(validatePasswordPolicyErr.Error(), validation.PasswordPolicyProblemType(passwordPolicy))
}
- hashedPassword, err := h.userService.HashPassword(*input.Body.Password)
- if err != nil {
+ hashedPassword, hashPasswordErr := h.userService.HashPassword(*input.Body.Password)
+ if hashPasswordErr != nil {
return nil, huma.Error500InternalServerError("Failed to hash password")
}
userModel.PasswordHash = hashedPassword
diff --git a/backend/internal/user/service.go b/backend/internal/user/service.go
index 133459bc3..0401ab34c 100644
--- a/backend/internal/user/service.go
+++ b/backend/internal/user/service.go
@@ -135,29 +135,29 @@ func (s *UserService) ValidatePassword(encodedHash, password string) error {
return nil
}
-func (s *UserService) CreateUser(ctx context.Context, user *common.User) (*common.User, error) {
- if err := normalization.Normalize(user); err != nil {
+func (s *UserService) CreateUser(ctx context.Context, localUser *common.User) (*common.User, error) {
+ if err := normalization.Normalize(localUser); err != nil {
return nil, err
}
- username, err := normalizeUsernameInternal(user.Username)
+ username, err := normalizeUsernameInternal(localUser.Username)
if err != nil {
return nil, err
}
- user.Username = username
+ localUser.Username = username
err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- if err := tx.Create(user).Error; err != nil {
- if isDuplicateKeyErrorInternal(tx, err) {
+ if createUserErr := tx.Create(localUser).Error; createUserErr != nil {
+ if isDuplicateKeyErrorInternal(tx, createUserErr) {
return ErrUsernameTaken
}
- return fmt.Errorf("failed to create user: %w", err)
+ return fmt.Errorf("failed to create user: %w", createUserErr)
}
return nil
})
if err != nil {
return nil, err
}
- return user, nil
+ return localUser, nil
}
func (s *UserService) GetUserByUsername(ctx context.Context, username string) (*common.User, error) {
@@ -268,15 +268,15 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gorm
// UpdateUser persists the given user. actorPerms identifies the caller
// performing the change; authenticated global-admin callers must also be
// present in ctx. Pass nil for internal service-to-service calls.
-func (s *UserService) UpdateUser(ctx context.Context, user *common.User, actorPerms *authz.PermissionSet) (*common.User, error) {
- if err := normalization.Normalize(user); err != nil {
+func (s *UserService) UpdateUser(ctx context.Context, localUser *common.User, actorPerms *authz.PermissionSet) (*common.User, error) {
+ if err := normalization.Normalize(localUser); err != nil {
return nil, err
}
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- if err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, user.ID); err != nil {
+ if err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, localUser.ID); err != nil {
return err
}
- if err := tx.Save(user).Error; err != nil {
+ if err := tx.Save(localUser).Error; err != nil {
if isDuplicateKeyErrorInternal(tx, err) {
return ErrUsernameTaken
}
@@ -287,7 +287,7 @@ func (s *UserService) UpdateUser(ctx context.Context, user *common.User, actorPe
if err != nil {
return nil, err
}
- return user, nil
+ return localUser, nil
}
func normalizeUsernameInternal(username string) (string, error) {
@@ -308,8 +308,8 @@ func isDuplicateKeyErrorInternal(db *gorm.DB, err error) bool {
// SetPassword hashes and persists a new password for the given user and clears
// the first-login password-change requirement for trusted internal callers.
-func (s *UserService) SetPassword(ctx context.Context, user *common.User, password string) (*common.User, error) {
- if user == nil {
+func (s *UserService) SetPassword(ctx context.Context, localUser *common.User, password string) (*common.User, error) {
+ if localUser == nil {
return nil, errors.New("user is nil")
}
@@ -318,20 +318,20 @@ func (s *UserService) SetPassword(ctx context.Context, user *common.User, passwo
return nil, fmt.Errorf("failed to hash password: %w", err)
}
- user.PasswordHash = hashedPassword
- user.RequiresPasswordChange = false
- return s.UpdateUser(ctx, user, nil)
+ localUser.PasswordHash = hashedPassword
+ localUser.RequiresPasswordChange = false
+ return s.UpdateUser(ctx, localUser, nil)
}
// SetPasswordAndRevokeSessionsExcept atomically sets a new password, clears
// the first-login password-change requirement, and revokes every session for
// the user except exceptSessionID. Pass an empty exceptSessionID to revoke all
// sessions. This is for trusted internal callers.
-func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, user *common.User, password, exceptSessionID string) (*common.User, error) {
- if user == nil {
+func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, localUser *common.User, password, exceptSessionID string) (*common.User, error) {
+ if localUser == nil {
return nil, errors.New("user is nil")
}
- if strings.TrimSpace(user.ID) == "" {
+ if strings.TrimSpace(localUser.ID) == "" {
return nil, common.ErrUserNotFound
}
@@ -342,19 +342,19 @@ func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, us
var updatedUser common.User
err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
- Where("id = ?", user.ID).
- First(&updatedUser).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
+ if loadPasswordResetUserErr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
+ Where("id = ?", localUser.ID).
+ First(&updatedUser).Error; loadPasswordResetUserErr != nil {
+ if errors.Is(loadPasswordResetUserErr, gorm.ErrRecordNotFound) {
return common.ErrUserNotFound
}
- return fmt.Errorf("failed to load user for password reset: %w", err)
+ return fmt.Errorf("failed to load user for password reset: %w", loadPasswordResetUserErr)
}
updatedUser.PasswordHash = hashedPassword
updatedUser.RequiresPasswordChange = false
- if err := tx.Save(&updatedUser).Error; err != nil {
- return fmt.Errorf("failed to update user password: %w", err)
+ if updatePasswordErr := tx.Save(&updatedUser).Error; updatePasswordErr != nil {
+ return fmt.Errorf("failed to update user password: %w", updatePasswordErr)
}
return session.RevokeAllUserSessionsExceptInDB(ctx, tx, updatedUser.ID, exceptSessionID)
})
@@ -362,8 +362,8 @@ func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, us
return nil, err
}
- *user = updatedUser
- return user, nil
+ *localUser = updatedUser
+ return localUser, nil
}
// AttachOidcSubjectTransactional safely links an OIDC subject to the given user inside a DB transaction.
@@ -463,8 +463,8 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {
PasswordHash: hashedPassword,
RequiresPasswordChange: true,
}
- if err := tx.Create(userModel).Error; err != nil {
- return fmt.Errorf("failed to create default admin user: %w", err)
+ if createAdminUserErr := tx.Create(userModel).Error; createAdminUserErr != nil {
+ return fmt.Errorf("failed to create default admin user: %w", createAdminUserErr)
}
adminUserID = userModel.ID
slog.InfoContext(ctx, "👑 Default admin user created!")
@@ -523,8 +523,8 @@ func (s *UserService) grantDefaultAdminRoleInternal(ctx context.Context, adminUs
RoleID: authz.BuiltInRoleAdmin,
EnvironmentID: nil,
})
- if err := s.roleService.SetUserAssignments(ctx, adminUserID, manual); err != nil {
- return fmt.Errorf("failed to grant default admin global role: %w", err)
+ if setUserAssignmentsErr := s.roleService.SetUserAssignments(ctx, adminUserID, manual); setUserAssignmentsErr != nil {
+ return fmt.Errorf("failed to grant default admin global role: %w", setUserAssignmentsErr)
}
slog.InfoContext(ctx, "Default admin granted global Admin role assignment", "user_id", adminUserID)
return nil
@@ -544,9 +544,9 @@ func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *aut
return err
}
if ps != nil && ps.IsGlobalAdmin() {
- remaining, err := s.roleService.CountGlobalAdminsExcludingUser(ctx, id)
- if err != nil {
- return err
+ remaining, countGlobalAdminsExcludingUserErr := s.roleService.CountGlobalAdminsExcludingUser(ctx, id)
+ if countGlobalAdminsExcludingUserErr != nil {
+ return countGlobalAdminsExcludingUserErr
}
if remaining == 0 {
return ErrCannotRemoveLastAdmin
@@ -761,8 +761,8 @@ func (s *UserService) GetAvatar(ctx context.Context, userID string) ([]byte, str
return nil, "", nil
}
var avatar UserAvatar
- if err := s.db.DB.WithContext(ctx).Where("user_id = ?", userID).First(&avatar).Error; err != nil {
- return nil, "", kit.Ternary(errors.Is(err, gorm.ErrRecordNotFound), nil, err)
+ if loadAvatarErr := s.db.DB.WithContext(ctx).Where("user_id = ?", userID).First(&avatar).Error; loadAvatarErr != nil {
+ return nil, "", kit.Ternary(errors.Is(loadAvatarErr, gorm.ErrRecordNotFound), nil, loadAvatarErr)
}
return avatar.Data, avatar.MimeType, nil
}
diff --git a/backend/internal/user/service_test.go b/backend/internal/user/service_test.go
index 5852899a7..e3ea59e6a 100644
--- a/backend/internal/user/service_test.go
+++ b/backend/internal/user/service_test.go
@@ -37,8 +37,19 @@ func setupAuthServiceTestDBInternal(t *testing.T) *database.DB {
require.NoError(t, db.Exec("CREATE UNIQUE INDEX idx_users_username_unique ON users(username)").Error)
// environments and api_keys live in packages that import this one; the
// in-package tests only need the tables to exist.
- require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS environments (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, api_url text, status text, enabled numeric, is_edge numeric, hidden numeric, last_seen datetime, last_edge_transport text, access_token text, api_key_id text, parent_environment_id text, swarm_node_id text)").Error)
- require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, description text, key_hash text, key_prefix text, kind text, user_id text, environment_id text, managed_by text, expires_at datetime, last_used_at datetime)").Error)
+ require.NoError(
+ t,
+ db.Exec("CREATE TABLE IF NOT EXISTS environments (id text PRIMARY KEY, created_at datetime, updated_at dateti"+
+ "me, name text, api_url text, status text, enabled numeric, is_edge numeric, hidden numeric, last_see"+
+ "n datetime, last_edge_transport text, access_token text, api_key_id text, parent_environment_id text"+
+ ", swarm_node_id text)").Error,
+ )
+ require.NoError(
+ t,
+ db.Exec("CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY, created_at datetime, updated_at datetime, "+
+ "name text, description text, key_hash text, key_prefix text, kind text, user_id text, environment_id"+
+ " text, managed_by text, expires_at datetime, last_used_at datetime)").Error,
+ )
return &database.DB{DB: db}
}
@@ -47,15 +58,15 @@ func setupAuthServiceTestDBInternal(t *testing.T) *database.DB {
func setupUserAndRoleServices(t *testing.T) (*UserService, *role.RoleService) {
t.Helper()
db := setupAuthServiceTestDBInternal(t)
- role := role.NewRoleService(db)
- require.NoError(t, role.EnsureBuiltInRoles(context.Background()))
- userRecord := NewUserService(db, role)
- return userRecord, role
+ localRole := role.NewRoleService(db)
+ require.NoError(t, localRole.EnsureBuiltInRoles(t.Context()))
+ userRecord := NewUserService(db, localRole)
+ return userRecord, localRole
}
func createTestUser(t *testing.T, svc *UserService, id, username string) *common.User {
t.Helper()
- created, err := svc.CreateUser(context.Background(), &common.User{
+ created, err := svc.CreateUser(t.Context(), &common.User{
ID: id,
Username: username,
})
@@ -66,14 +77,14 @@ func createTestUser(t *testing.T, svc *UserService, id, username string) *common
// grantGlobalAdmin assigns the built-in Admin role globally to the user.
func grantGlobalAdmin(t *testing.T, roleSvc *role.RoleService, userID string) {
t.Helper()
- require.NoError(t, roleSvc.SetUserAssignments(context.Background(), userID, []role.UserRoleAssignment{
+ require.NoError(t, roleSvc.SetUserAssignments(t.Context(), userID, []role.UserRoleAssignment{
{RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},
}))
}
func TestDeleteUserRejectsDeletingOnlyAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -88,11 +99,11 @@ func TestDeleteUserRejectsDeletingOnlyAdmin(t *testing.T) {
func TestSetPasswordUpdatesHashAndClearsPasswordChangeRequirement(t *testing.T) {
userSvc, _ := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
oldHash, err := userSvc.HashPassword("old-password")
require.NoError(t, err)
- user, err := userSvc.CreateUser(ctx, &common.User{
+ localUser, err := userSvc.CreateUser(ctx, &common.User{
ID: "password-user",
Username: "password-user",
PasswordHash: oldHash,
@@ -100,10 +111,10 @@ func TestSetPasswordUpdatesHashAndClearsPasswordChangeRequirement(t *testing.T)
})
require.NoError(t, err)
- _, err = userSvc.SetPassword(ctx, user, "new-password")
+ _, err = userSvc.SetPassword(ctx, localUser, "new-password")
require.NoError(t, err)
- updated, err := userSvc.GetUserByID(ctx, user.ID)
+ updated, err := userSvc.GetUserByID(ctx, localUser.ID)
require.NoError(t, err)
require.NoError(t, userSvc.ValidatePassword(updated.PasswordHash, "new-password"))
require.Error(t, userSvc.ValidatePassword(updated.PasswordHash, "old-password"))
@@ -112,7 +123,7 @@ func TestSetPasswordUpdatesHashAndClearsPasswordChangeRequirement(t *testing.T)
func TestDeleteUserAllowsDeletingNonAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -127,7 +138,7 @@ func TestDeleteUserAllowsDeletingNonAdmin(t *testing.T) {
func TestDeleteUserAllowsDeletingAdminWhenAnotherAdminExists(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
adminToDelete := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, adminToDelete.ID)
@@ -143,7 +154,7 @@ func TestDeleteUserAllowsDeletingAdminWhenAnotherAdminExists(t *testing.T) {
func TestListUsersPaginatedSetsCanDeleteFromGlobalAdminCount(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
lastAdmin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, lastAdmin.ID)
@@ -181,7 +192,7 @@ func TestListUsersPaginatedSetsCanDeleteFromGlobalAdminCount(t *testing.T) {
func TestDeleteUserRejectsDeletingOnlyCustomAllPermissionsAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
customAdmin := createTestUser(t, userSvc, "custom-admin", "custom-admin")
customRole, err := roleSvc.CreateRole(ctx, "Custom Admin", nil, authz.AllPermissions())
@@ -209,7 +220,7 @@ func TestDeleteUserRejectsDeletingOnlyCustomAllPermissionsAdmin(t *testing.T) {
func TestUserProfileValidationAndPersistence(t *testing.T) {
userSvc, _ := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
u := createTestUser(t, userSvc, "user-1", " fontuser ")
require.Equal(t, "fontuser", u.Username)
@@ -243,7 +254,7 @@ func TestUserProfileValidationAndPersistence(t *testing.T) {
func TestUserDtoExposesLastLogin(t *testing.T) {
userSvc, _ := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
u := createTestUser(t, userSvc, "user-1", "last-login-user")
@@ -266,7 +277,7 @@ func TestUserDtoExposesLastLogin(t *testing.T) {
func TestUpdateUserPersistsTimeFormatAndMapsToDto(t *testing.T) {
userSvc, _ := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
u := createTestUser(t, userSvc, "user-1", "time-format-user")
require.Equal(t, user.TimeFormatAuto, u.TimeFormat)
@@ -294,7 +305,7 @@ func TestUpdateUserPersistsTimeFormatAndMapsToDto(t *testing.T) {
func TestUpdateUserRejectsNonAdminActorEditingAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -318,7 +329,7 @@ func TestUpdateUserRejectsNonAdminActorEditingAdmin(t *testing.T) {
func TestUpdateUserAllowsGlobalAdminActorEditingAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -335,7 +346,7 @@ func TestUpdateUserAllowsGlobalAdminActorEditingAdmin(t *testing.T) {
func TestUpdateUserAllowsNonAdminActorEditingNonAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -356,7 +367,7 @@ func TestUpdateUserAllowsNonAdminActorEditingNonAdmin(t *testing.T) {
func TestUpdateUserAllowsSelfEditByNonAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -371,7 +382,7 @@ func TestUpdateUserAllowsSelfEditByNonAdmin(t *testing.T) {
func TestDeleteUserRejectsNonAdminActorDeletingAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -398,7 +409,7 @@ func TestDeleteUserRejectsNonAdminActorDeletingAdmin(t *testing.T) {
func TestDeleteUserAllowsGlobalAdminActorDeletingAdmin(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "arcane")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -413,7 +424,7 @@ func TestDeleteUserAllowsGlobalAdminActorDeletingAdmin(t *testing.T) {
func TestCreateDefaultAdminDoesNotPromoteRenamedArcaneUser(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
admin := createTestUser(t, userSvc, "admin-1", "boss")
grantGlobalAdmin(t, roleSvc, admin.ID)
@@ -428,7 +439,7 @@ func TestCreateDefaultAdminDoesNotPromoteRenamedArcaneUser(t *testing.T) {
func TestCreateDefaultAdminRecoversArcaneUserWhenNoGlobalAdminExists(t *testing.T) {
userSvc, roleSvc := setupUserAndRoleServices(t)
- ctx := context.Background()
+ ctx := t.Context()
orphan := createTestUser(t, userSvc, "user-1", "arcane")
@@ -443,7 +454,7 @@ func TestCreateDefaultAdminRecoversArcaneUserWhenNoGlobalAdminExists(t *testing.
func TestUserDisplayNameNormalization(t *testing.T) {
svc := NewUserService(setupAuthServiceTestDBInternal(t), nil)
- ctx := context.Background()
+ ctx := t.Context()
created, err := svc.CreateUser(ctx, &common.User{ID: "normalized", Username: " Jose\u0301 ", Email: new(" Jose\[email protected] "), DisplayName: new(" Jose\u0301 ")})
require.NoError(t, err)
require.Equal(t, "Jose\u0301", created.Username)
diff --git a/backend/internal/variable/service_test.go b/backend/internal/variable/service_test.go
index 002c36832..6c230e3e0 100644
--- a/backend/internal/variable/service_test.go
+++ b/backend/internal/variable/service_test.go
@@ -3,7 +3,6 @@ package variable
import (
"context"
"encoding/json"
- "errors"
"fmt"
"io"
"net/http"
@@ -35,7 +34,7 @@ func newSettingsServiceForVariableTestInternal(t testing.TB, ctx context.Context
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
@@ -65,9 +64,9 @@ func setupVariableServiceTest(t *testing.T) (*VariableService, *database.DB, str
projectsDir := t.TempDir()
dbWrap := &database.DB{DB: db}
- settingsSvc, err := newSettingsServiceForVariableTestInternal(t, context.Background(), dbWrap)
+ settingsSvc, err := newSettingsServiceForVariableTestInternal(t, t.Context(), dbWrap)
require.NoError(t, err)
- require.NoError(t, settingsSvc.UpdateSetting(context.Background(), "projectsDirectory", projectsDir))
+ require.NoError(t, settingsSvc.UpdateSetting(t.Context(), "projectsDirectory", projectsDir))
service := NewVariableService(dbWrap, nil, settingsSvc, kv.NewKVService(dbWrap))
return service, dbWrap, projectsDir
@@ -86,7 +85,7 @@ func createVariableTestEnvironment(t *testing.T, db *database.DB, id string) {
func TestCreateVariable_SecretEncryptedAtRestAndRedactedOnList(t *testing.T) {
service, db, _ := setupVariableServiceTest(t)
- ctx := context.Background()
+ ctx := t.Context()
created, err := service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
Key: "API_TOKEN",
@@ -113,8 +112,8 @@ func TestCreateVariable_SecretEncryptedAtRestAndRedactedOnList(t *testing.T) {
func TestUpdateVariable_OmittedSecretValuePreservesCiphertextAndRedactsResponse(t *testing.T) {
service, db, _ := setupVariableServiceTest(t)
- ctx := context.Background()
- created := createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+ ctx := t.Context()
+ created := createMaterializedSecretVariableInternal(t, service)
var before GlobalVariable
require.NoError(t, db.WithContext(ctx).First(&before, "id = ?", created.ID).Error)
@@ -139,13 +138,13 @@ func TestUpdateVariable_OmittedSecretValuePreservesCiphertextAndRedactsResponse(
func TestUpdateVariable_SecretToPlainRequiresReplacementValue(t *testing.T) {
service, db, _ := setupVariableServiceTest(t)
- ctx := context.Background()
- created := createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+ ctx := t.Context()
+ created := createMaterializedSecretVariableInternal(t, service)
plain := false
_, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{IsSecret: &plain})
require.Error(t, err)
- require.True(t, errors.Is(err, common.ErrGlobalVariableSecretValueRequired))
+ require.ErrorIs(t, err, common.ErrGlobalVariableSecretValueRequired)
replacement := "public-value"
updated, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{
@@ -164,7 +163,7 @@ func TestUpdateVariable_SecretToPlainRequiresReplacementValue(t *testing.T) {
func TestResolveEffectiveVariables_EnvScopedOverridesAllEnv(t *testing.T) {
service, db, _ := setupVariableServiceTest(t)
- ctx := context.Background()
+ ctx := t.Context()
createVariableTestEnvironment(t, db, "env-a")
createVariableTestEnvironment(t, db, "env-b")
@@ -187,7 +186,7 @@ func TestResolveEffectiveVariables_EnvScopedOverridesAllEnv(t *testing.T) {
_, err = service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
Key: "NO_SCOPE", Value: "x", AllEnvironments: false, EnvironmentIDs: []string{},
})
- require.True(t, errors.Is(err, common.ErrGlobalVariableScopeRequired), "expected GlobalVariableScopeRequiredError, got %v", err)
+ require.ErrorIs(t, err, common.ErrGlobalVariableScopeRequired, "expected GlobalVariableScopeRequiredError, got %v", err)
forA, err := service.resolveEffectiveVariablesInternal(ctx, "env-a")
require.NoError(t, err)
@@ -201,10 +200,10 @@ func TestResolveEffectiveVariables_EnvScopedOverridesAllEnv(t *testing.T) {
func TestWriteLocalEnvFile_RejectsNewlineInjectionKey(t *testing.T) {
service, _, projectsDir := setupVariableServiceTest(t)
- err := service.WriteLocalEnvFile(context.Background(), []envtypes.Variable{
+ err := service.WriteLocalEnvFile(t.Context(), []envtypes.Variable{
{Key: "BENIGN\nINJECTED", Value: "x"},
})
- require.True(t, errors.Is(err, common.ErrInvalidEnvKey), "expected InvalidEnvKeyError, got %v", err)
+ require.ErrorIs(t, err, common.ErrInvalidEnvKey, "expected InvalidEnvKeyError, got %v", err)
_, statErr := os.Stat(filepath.Join(projectsDir, ".env.global"))
require.True(t, os.IsNotExist(statErr), ".env.global must not be written on validation failure")
@@ -215,7 +214,7 @@ func TestWriteLocalEnvFile_PreservesExistingFileMode(t *testing.T) {
t.Skip("file mode bits are not represented on Windows FS")
}
service, _, projectsDir := setupVariableServiceTest(t)
- ctx := context.Background()
+ ctx := t.Context()
envPath := filepath.Join(projectsDir, ".env.global")
require.NoError(t, service.WriteLocalEnvFile(ctx, []envtypes.Variable{{Key: "A", Value: "1"}}))
@@ -235,7 +234,7 @@ func TestWriteLocalEnvFile_PreservesExistingFileMode(t *testing.T) {
func TestSyncEnvironment_LocalWritesEnvGlobalFile(t *testing.T) {
service, _, projectsDir := setupVariableServiceTest(t)
- ctx := context.Background()
+ ctx := t.Context()
_, err := service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
Key: "DB_PASSWORD", Value: "hunter2", IsSecret: true, AllEnvironments: true,
@@ -303,9 +302,9 @@ func TestSyncEnvironment_DirectMaterializesSecretsThroughAgentRoute(t *testing.T
environmentService := environment.NewEnvironmentService(db, nil, nil, nil, service.settingsService, nil)
service.proxyEnvironmentJSON = environmentService.ProxyJSONRequest
service.listEnabledEnvironmentIDs = environmentService.ListEnabledEnvironmentIDs
- createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+ createMaterializedSecretVariableInternal(t, service)
- require.NoError(t, service.SyncEnvironment(context.Background(), "env-direct"))
+ require.NoError(t, service.SyncEnvironment(t.Context(), "env-direct"))
requestMu.Lock()
captured := append([]capturedVariableSyncRequestInternal(nil), requests...)
requestMu.Unlock()
@@ -345,20 +344,20 @@ func TestSyncEnvironment_EdgeMaterializesSecretsThroughAgentRoute(t *testing.T)
}
return json.Unmarshal([]byte(`{"success":true,"data":{"message":"updated"}}`), response)
}
- createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")
+ createMaterializedSecretVariableInternal(t, service)
- require.NoError(t, service.SyncEnvironment(context.Background(), "env-edge"))
+ require.NoError(t, service.SyncEnvironment(t.Context(), "env-edge"))
requestMu.Lock()
captured := append([]capturedVariableSyncRequestInternal(nil), requests...)
requestMu.Unlock()
requireMaterializationRequestsInternal(t, captured, token)
}
-func createMaterializedSecretVariableInternal(t *testing.T, service *VariableService, key, value string) *envtypes.GlobalVariable {
+func createMaterializedSecretVariableInternal(t *testing.T, service *VariableService) *envtypes.GlobalVariable {
t.Helper()
- created, err := service.CreateVariable(context.Background(), envtypes.CreateGlobalVariableRequest{
- Key: key,
- Value: value,
+ created, err := service.CreateVariable(t.Context(), envtypes.CreateGlobalVariableRequest{
+ Key: "API_TOKEN",
+ Value: "super-secret",
IsSecret: true,
AllEnvironments: true,
})
diff --git a/backend/internal/variable/variable.go b/backend/internal/variable/variable.go
index d47f3b13d..37e5045ef 100644
--- a/backend/internal/variable/variable.go
+++ b/backend/internal/variable/variable.go
@@ -85,7 +85,7 @@ func NewVariableService(db *database.DB, environmentService *environment.Environ
func (s *VariableService) ListVariables(ctx context.Context) ([]env.GlobalVariable, error) {
variables, err := s.loadVariablesInternal(ctx)
if err != nil {
- return nil, fmt.Errorf("Failed to retrieve global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.
+ return nil, fmt.Errorf("failed to retrieve global variables: %w", err)
}
result := make([]env.GlobalVariable, 0, len(variables))
@@ -98,7 +98,7 @@ func (s *VariableService) ListVariables(ctx context.Context) ([]env.GlobalVariab
func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlobalVariableRequest) (*env.GlobalVariable, error) {
key := strings.TrimSpace(req.Key)
if !envKeyPattern.MatchString(key) {
- return nil, common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key)) //nolint:staticcheck // Preserve the existing error message.
+ return nil, common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))
}
envIDs, err := s.normalizeScopeInternal(ctx, req.AllEnvironments, req.EnvironmentIDs)
@@ -110,7 +110,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlob
value := req.Value
if req.IsSecret {
if value, err = crypto.Encrypt(value); err != nil {
- return nil, fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.
+ return nil, fmt.Errorf("failed to update global variables: %w", err)
}
}
@@ -122,11 +122,11 @@ func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlob
}
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := s.validateScopeConflictInternal(tx, key, "", allEnvironments, envIDs); err != nil {
- return err
+ if validateScopeConflictErr := s.validateScopeConflictInternal(tx, key, "", allEnvironments, envIDs); validateScopeConflictErr != nil {
+ return validateScopeConflictErr
}
- if err := tx.Omit("Environments").Create(&variable).Error; err != nil {
- return fmt.Errorf("failed to create global variable: %w", err)
+ if createVariableErr := tx.Omit("Environments").Create(&variable).Error; createVariableErr != nil {
+ return fmt.Errorf("failed to create global variable: %w", createVariableErr)
}
return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)
})
@@ -143,16 +143,16 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req env
var variable GlobalVariable
if err := s.db.WithContext(ctx).Preload("Environments").First(&variable, "id = ?", id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found")) //nolint:staticcheck // Preserve the existing error message.
+ return nil, common.Classify(common.ErrGlobalVariableNotFound, errors.New("global variable not found"))
}
- return nil, fmt.Errorf("Failed to retrieve global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.
+ return nil, fmt.Errorf("failed to retrieve global variables: %w", err)
}
key := variable.Key
if req.Key != nil {
key = strings.TrimSpace(*req.Key)
if !envKeyPattern.MatchString(key) {
- return nil, common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key)) //nolint:staticcheck // Preserve the existing error message.
+ return nil, common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))
}
}
@@ -177,11 +177,11 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req env
variable.AllEnvironments = allEnvironments
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := s.validateScopeConflictInternal(tx, key, variable.ID, allEnvironments, envIDs); err != nil {
- return err
+ if validateScopeConflictErr := s.validateScopeConflictInternal(tx, key, variable.ID, allEnvironments, envIDs); validateScopeConflictErr != nil {
+ return validateScopeConflictErr
}
- if err := tx.Omit("Environments").Save(&variable).Error; err != nil {
- return fmt.Errorf("failed to update global variable: %w", err)
+ if updateVariableErr := tx.Omit("Environments").Save(&variable).Error; updateVariableErr != nil {
+ return fmt.Errorf("failed to update global variable: %w", updateVariableErr)
}
return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)
})
@@ -199,7 +199,12 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req env
// made readable without a replacement value (revealing the stored one).
func resolveUpdatedValueInternal(variable *GlobalVariable, reqValue *string, isSecret bool) (string, error) {
if variable.IsSecret && !isSecret && reqValue == nil {
- return "", common.Classify(common.ErrGlobalVariableSecretValueRequired, errors.New("A new value is required when making a secret variable readable")) //nolint:staticcheck // Preserve the existing error message.
+ return "", common.Classify(
+ common.ErrGlobalVariableSecretValueRequired,
+ errors.New(
+ "a new value is required when making a secret variable readable",
+ ),
+ )
}
switch {
@@ -209,14 +214,14 @@ func resolveUpdatedValueInternal(variable *GlobalVariable, reqValue *string, isS
}
encrypted, err := crypto.Encrypt(*reqValue)
if err != nil {
- return "", fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.
+ return "", fmt.Errorf("failed to update global variables: %w", err)
}
return encrypted, nil
case isSecret && !variable.IsSecret:
// Readable value becoming secret keeps its current plaintext, encrypted.
encrypted, err := crypto.Encrypt(variable.Value)
if err != nil {
- return "", fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.
+ return "", fmt.Errorf("failed to update global variables: %w", err)
}
return encrypted, nil
default:
@@ -255,7 +260,7 @@ func (s *VariableService) DeleteVariable(ctx context.Context, id string) error {
return fmt.Errorf("failed to delete global variable: %w", result.Error)
}
if result.RowsAffected == 0 {
- return common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found")) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(common.ErrGlobalVariableNotFound, errors.New("global variable not found"))
}
return tx.Exec("DELETE FROM global_variable_environments WHERE global_variable_id = ?", id).Error
})
@@ -289,10 +294,10 @@ func (s *VariableService) resolveEffectiveVariablesInternal(ctx context.Context,
}
value := variable.Value
if variable.IsSecret {
- decrypted, err := crypto.Decrypt(value)
- if err != nil {
+ decrypted, decryptErr := crypto.Decrypt(value)
+ if decryptErr != nil {
slog.WarnContext(ctx, "Failed to decrypt global variable for sync; skipping",
- "variable_id", variable.ID, "key", variable.Key, "error", err)
+ "variable_id", variable.ID, "key", variable.Key, "error", decryptErr)
continue
}
value = decrypted
@@ -531,8 +536,8 @@ func (s *VariableService) ReadLocalEnvFile(ctx context.Context) ([]env.Variable,
})
}
- if err := scanner.Err(); err != nil {
- return nil, fmt.Errorf("error reading global variables file: %w", err)
+ if readVariablesErr := scanner.Err(); readVariablesErr != nil {
+ return nil, fmt.Errorf("error reading global variables file: %w", readVariablesErr)
}
return vars, nil
@@ -547,8 +552,8 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Vari
// The data directory is the confinement root for the write, so it is created
// through os before acfs opens it.
projectsDirectory := filepath.Dir(envPath)
- if err := os.MkdirAll(projectsDirectory, utils.DirPerm); err != nil {
- return fmt.Errorf("failed to create projects directory: %w", err)
+ if mkdirAllErr := os.MkdirAll(projectsDirectory, utils.DirPerm); mkdirAllErr != nil {
+ return fmt.Errorf("failed to create projects directory: %w", mkdirAllErr)
}
var builder strings.Builder
@@ -562,14 +567,14 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Vari
key := strings.TrimSpace(v.Key)
if !envKeyPattern.MatchString(key) {
- return common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("Invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key)) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(common.ErrInvalidEnvKey, fmt.Errorf("invalid env key %q (must match [A-Za-z_][A-Za-z0-9_]*)", key))
}
// Preserve intentional whitespace inside the quoted value.
value := v.Value
if strings.ContainsAny(value, " \t\n\r#") {
- value = fmt.Sprintf(`"%s"`, strings.ReplaceAll(value, `"`, `\"`))
+ value = `"` + strings.ReplaceAll(value, `"`, `\"`) + `"`
}
_, _ = fmt.Fprintf(&builder, "%s=%s\n", key, value)
@@ -579,8 +584,8 @@ func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Vari
if entry, statErr := acfs.Stat(ctx, projectsDirectory, "/"+projects.GlobalEnvFileName, false); statErr == nil {
mode = os.FileMode(entry.UnixMode).Perm()
}
- if err := acfs.Write(ctx, projectsDirectory, "/"+projects.GlobalEnvFileName, []byte(builder.String()), acfs.WriteOptions{Mode: mode, InPlace: true}); err != nil {
- return fmt.Errorf("failed to write global variables file: %w", err)
+ if writeErr := acfs.Write(ctx, projectsDirectory, "/"+projects.GlobalEnvFileName, []byte(builder.String()), acfs.WriteOptions{Mode: mode, InPlace: true}); writeErr != nil {
+ return fmt.Errorf("failed to write global variables file: %w", writeErr)
}
slog.InfoContext(ctx, "Updated global variables",
@@ -611,8 +616,8 @@ func (s *VariableService) ImportLegacyLocalEnvFile(ctx context.Context) error {
if err != nil {
return err
}
- if err := s.importVariablesInternal(ctx, vars, ""); err != nil {
- return err
+ if importVariablesErr := s.importVariablesInternal(ctx, vars, ""); importVariablesErr != nil {
+ return importVariablesErr
}
return s.kvService.SetBool(ctx, flag, true)
@@ -636,12 +641,12 @@ func (s *VariableService) importRemoteLegacyVarsOnceInternal(ctx context.Context
Success bool `json:"success"`
Data []env.Variable `json:"data"`
}
- if err := s.proxyEnvironmentJSON(ctx, envID, http.MethodGet, agentVariablesPath, nil, &out); err != nil {
- return err
+ if proxyEnvironmentJSONErr := s.proxyEnvironmentJSON(ctx, envID, http.MethodGet, agentVariablesPath, nil, &out); proxyEnvironmentJSONErr != nil {
+ return proxyEnvironmentJSONErr
}
- if err := s.importVariablesInternal(ctx, out.Data, envID); err != nil {
- return err
+ if importVariablesErr := s.importVariablesInternal(ctx, out.Data, envID); importVariablesErr != nil {
+ return importVariablesErr
}
return s.kvService.SetBool(ctx, flag, true)
@@ -678,17 +683,17 @@ func (s *VariableService) importVariablesInternal(ctx context.Context, vars []en
Value: entry.Value,
AllEnvironments: scopeEnvID == "",
}
- err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
- if err := tx.Omit("Environments").Create(&variable).Error; err != nil {
- return err
+ transactionErr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if createImportedVariableErr := tx.Omit("Environments").Create(&variable).Error; createImportedVariableErr != nil {
+ return createImportedVariableErr
}
if scopeEnvID == "" {
return nil
}
return replaceVariableScopeRowsInternal(tx, variable.ID, []string{scopeEnvID})
})
- if err != nil {
- return fmt.Errorf("failed to import legacy variable %q: %w", key, err)
+ if transactionErr != nil {
+ return fmt.Errorf("failed to import legacy variable %q: %w", key, transactionErr)
}
covered[key] = true
slog.InfoContext(ctx, "Imported legacy global variable", "key", key, "environment_id", scopeEnvID)
@@ -726,15 +731,20 @@ func (s *VariableService) normalizeScopeInternal(ctx context.Context, allEnviron
// An explicitly specific scope with no environments must not silently
// widen to all environments.
if len(unique) == 0 {
- return nil, common.Classify(common.ErrGlobalVariableScopeRequired, errors.New("At least one environment is required when a variable is not scoped to all environments")) //nolint:staticcheck // Preserve the existing error message.
+ return nil, common.Classify(
+ common.ErrGlobalVariableScopeRequired,
+ errors.New(
+ "at least one environment is required when a variable is not scoped to all environments",
+ ),
+ )
}
var count int64
if err := s.db.WithContext(ctx).Model(&environment.Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil {
- return nil, fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.
+ return nil, fmt.Errorf("failed to update global variables: %w", err)
}
if count != int64(len(unique)) {
- return nil, errors.New("Failed to update global variables: one or more environments do not exist") //nolint:staticcheck // Preserve the existing error message.
+ return nil, errors.New("failed to update global variables: one or more environments do not exist")
}
return unique, nil
}
@@ -757,12 +767,24 @@ func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key, exclud
continue
}
if allEnvironments {
- return common.Classify(common.ErrGlobalVariableConflict, fmt.Errorf("A variable named %q already exists for an overlapping environment scope", key)) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrGlobalVariableConflict,
+ fmt.Errorf(
+ "a variable named %q already exists for an overlapping environment scope",
+ key,
+ ),
+ )
}
otherIDs := scopedEnvironmentIDsInternal(other.Environments)
for _, id := range envIDs {
if slices.Contains(otherIDs, id) {
- return common.Classify(common.ErrGlobalVariableConflict, fmt.Errorf("A variable named %q already exists for an overlapping environment scope", key)) //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(
+ common.ErrGlobalVariableConflict,
+ fmt.Errorf(
+ "a variable named %q already exists for an overlapping environment scope",
+ key,
+ ),
+ )
}
}
}
@@ -787,7 +809,7 @@ func wrapVariableMutationErrorInternal(err error) error {
if err == nil || errors.Is(err, common.ErrGlobalVariableConflict) || errors.Is(err, common.ErrGlobalVariableNotFound) || errors.Is(err, common.ErrInvalidEnvKey) {
return err
}
- return fmt.Errorf("Failed to update global variables: %w", err) //nolint:staticcheck // Preserve the existing error message.
+ return fmt.Errorf("failed to update global variables: %w", err)
}
func scopedEnvironmentIDsInternal(environments []environment.Environment) []string {
diff --git a/backend/internal/version/service.go b/backend/internal/version/service.go
index 2e558a735..8205387c4 100644
--- a/backend/internal/version/service.go
+++ b/backend/internal/version/service.go
@@ -58,7 +58,15 @@ type VersionService struct {
streamHub *agg.Hub[version.StreamEvent]
}
-func NewVersionService(httpClient *http.Client, disabled bool, appVersion, revision string, containerRegistryService *registry.ContainerRegistryService, dockerService *docker.DockerClientService, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService) *VersionService {
+func NewVersionService(
+ httpClient *http.Client,
+ disabled bool,
+ appVersion, revision string,
+ containerRegistryService *registry.ContainerRegistryService,
+ dockerService *docker.DockerClientService,
+ imageUpdateService *imageupdate.ImageUpdateService,
+ settingsService *settings.SettingsService,
+) *VersionService {
if httpClient == nil {
httpClient = http.DefaultClient
}
@@ -74,7 +82,7 @@ func NewVersionService(httpClient *http.Client, disabled bool, appVersion, revis
streamHub: agg.NewHub[version.StreamEvent](),
}
loader := func(_ []struct{}) (map[struct{}]latestRelease, error) {
- ctx, cancel := context.WithTimeout(context.Background(), defaultRequestTimeout)
+ ctx, cancel := context.WithTimeout(context.Background(), defaultRequestTimeout) //nolint:forbidigo // Cache revalidation runs independently of request cancellation.
defer cancel()
release, err := service.fetchLatestReleaseInternal(ctx)
if err != nil {
@@ -103,7 +111,7 @@ func (s *VersionService) getLatestReleaseInternal(_ context.Context) (latestRele
}
func (s *VersionService) fetchLatestReleaseInternal(ctx context.Context) (latestRelease, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, versionCheckURL, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, versionCheckURL, http.NoBody)
if err != nil {
return latestRelease{}, fmt.Errorf("create GitHub request: %w", err)
}
@@ -123,8 +131,8 @@ func (s *VersionService) fetchLatestReleaseInternal(ctx context.Context) (latest
Body string `json:"body"`
PublishedAt string `json:"published_at"`
}
- if err := json.UnmarshalRead(resp.Body, &payload); err != nil {
- return latestRelease{}, fmt.Errorf("decode payload: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &payload); unmarshalReadErr != nil {
+ return latestRelease{}, fmt.Errorf("decode payload: %w", unmarshalReadErr)
}
if payload.TagName == "" {
return latestRelease{}, errors.New("GitHub API returned empty tag name")
@@ -181,12 +189,12 @@ func (s *VersionService) normalizeVersion(ver string) string {
return ver
}
-func (s *VersionService) ReleaseURL(version string) string {
- if strings.TrimSpace(version) == "" {
+func (s *VersionService) ReleaseURL(localVersion string) string {
+ if strings.TrimSpace(localVersion) == "" {
return "https://github.com/getarcaneapp/arcane/releases/latest"
}
- return "https://github.com/getarcaneapp/arcane/releases/tag/" + kit.EnsurePrefix(version, "v")
+ return "https://github.com/getarcaneapp/arcane/releases/tag/" + kit.EnsurePrefix(localVersion, "v")
}
func (s *VersionService) GetVersionInformation(ctx context.Context, currentVersion string) (*version.Check, error) {
@@ -462,8 +470,8 @@ func (s *VersionService) extractImageDetails(ctx context.Context, dockerClient *
// Extract digest and repository from first RepoDigest using reference library
for _, repoDigest := range imageInspect.RepoDigests {
- named, err := ref.ParseNormalizedNamed(repoDigest)
- if err != nil {
+ named, parseNormalizedNamedErr := ref.ParseNormalizedNamed(repoDigest)
+ if parseNormalizedNamedErr != nil {
continue
}
if digested, ok := named.(ref.Digested); ok {
diff --git a/backend/internal/version/service_test.go b/backend/internal/version/service_test.go
index 03435f6f2..388586c2e 100644
--- a/backend/internal/version/service_test.go
+++ b/backend/internal/version/service_test.go
@@ -1,7 +1,6 @@
package version
import (
- "context"
"encoding/json"
"fmt"
"io"
@@ -37,7 +36,7 @@ import (
)
func TestVersionService_GetAppVersionInfoDoesNotUseStoredDigestUpdateForSemverBuildInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
const (
@@ -134,7 +133,7 @@ func TestVersionService_GetAppVersionInfoDoesNotUseStoredDigestUpdateForSemverBu
func TestVersionService_GetAppVersionInfoDisplaysSemverNextVersion(t *testing.T) {
svc := NewVersionService(nil, true, "2.4.0-next.2", "2c3e44a10ddda540d7e19fc2a876c931fc33a426", nil, nil, nil, nil)
- info := svc.GetAppVersionInfo(context.Background())
+ info := svc.GetAppVersionInfo(t.Context())
require.NotNil(t, info)
assert.Equal(t, "v2.4.0-next.2", info.DisplayVersion)
@@ -144,7 +143,7 @@ func TestVersionService_GetAppVersionInfoDisplaysSemverNextVersion(t *testing.T)
func TestVersionService_GetAppVersionInfoPreservesDevVersionInternal(t *testing.T) {
svc := NewVersionService(nil, true, "dev", "unknown", nil, nil, nil, nil)
- info := svc.GetAppVersionInfo(context.Background())
+ info := svc.GetAppVersionInfo(t.Context())
require.NotNil(t, info)
assert.Equal(t, "dev", info.CurrentVersion)
@@ -258,7 +257,7 @@ func newNextChannelDockerServerInternal(t *testing.T, containerID, imageID, repo
}
func TestVersionService_GetAppVersionInfoNextChannelUsesImageLabelInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
const (
@@ -324,7 +323,7 @@ func TestVersionService_GetAppVersionInfoNextChannelUsesImageLabelInternal(t *te
}
func TestVersionService_GetAppVersionInfoNextChannelLabelFailureFallsBackToDigestInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupImageUpdateTestDB(t)
const (
@@ -377,7 +376,7 @@ func TestVersionService_GetAppVersionInfoSuppressesOlderStableForPrereleaseInter
// still drop the older stable tag rather than showing a backwards arrow.
svc := NewVersionService(httpClient, false, "2.8.0-rc.1", "revision", nil, nil, nil, nil)
- info := svc.GetAppVersionInfo(context.Background())
+ info := svc.GetAppVersionInfo(t.Context())
require.NotNil(t, info)
assert.False(t, info.UpdateAvailable)
diff --git a/backend/internal/volume/backup.go b/backend/internal/volume/backup.go
index 9c4a353c8..49cc16930 100644
--- a/backend/internal/volume/backup.go
+++ b/backend/internal/volume/backup.go
@@ -200,7 +200,18 @@ func (s *VolumeService) ensureBackupVolumeInternal(ctx context.Context) error {
return nil
}
-func (s *VolumeService) stopRunningContainersForBackupInternal(ctx context.Context, dockerClient *client.Client, volumeName string, user common.User, refuseArcaneWriters bool) ([]container.Summary, error) {
+func (
+ s *VolumeService,
+) stopRunningContainersForBackupInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ volumeName string,
+ user common.User,
+ refuseArcaneWriters bool,
+) (
+ []container.Summary,
+ error,
+) {
if s.containerService == nil {
return nil, errors.New("container service is unavailable")
}
@@ -240,9 +251,9 @@ func (s *VolumeService) stopRunningContainersForBackupInternal(ctx context.Conte
stopped := make([]container.Summary, 0, len(containerIDs))
for _, containerID := range containerIDs {
candidate := containersByID[containerID]
- if err := s.containerService.StopContainer(ctx, containerID, user); err != nil {
+ if stopContainerErr := s.containerService.StopContainer(ctx, containerID, user); stopContainerErr != nil {
stillStopped, restartErr := s.startContainersAfterBackupInternal(context.WithoutCancel(ctx), dockerClient, stopped, user)
- return stillStopped, errors.Join(fmt.Errorf("failed to stop container %s before volume backup: %w", containerID, err), restartErr)
+ return stillStopped, errors.Join(fmt.Errorf("failed to stop container %s before volume backup: %w", containerID, stopContainerErr), restartErr)
}
stopped = append(stopped, candidate)
}
@@ -327,14 +338,39 @@ func (s *VolumeService) startContainersAfterBackupInternal(ctx context.Context,
}
func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName string, params pagination.QueryParams) ([]VolumeBackup, pagination.Response, error) {
- slog.DebugContext(ctx, "volume service: list backups paginated", "volume", volumeName, "search", params.Search, "sort", params.Sort, "order", params.Order, "start", params.Start, "limit", params.Limit)
+ slog.DebugContext(
+ ctx,
+ "volume service: list backups paginated",
+ "volume",
+ volumeName,
+ "search",
+ params.Search,
+ "sort",
+ params.Sort,
+ "order",
+ params.Order,
+ "start",
+ params.Start,
+ "limit",
+ params.Limit,
+ )
var backups []VolumeBackup
query := s.db.WithContext(ctx).Model(&VolumeBackup{}).Where("volume_name = ?", volumeName)
query = applyBackupManagementFilterInternal(query, params.Filters["type"])
if params.Search != "" {
pattern := "%" + params.Search + "%"
- query = query.Where("id LIKE ? OR status LIKE ? OR trigger LIKE ? OR destination LIKE ? OR COALESCE(local_snapshot_id, '') LIKE ? OR COALESCE(remote_snapshot_id, '') LIKE ? OR COALESCE(error, '') LIKE ?", pattern, pattern, pattern, pattern, pattern, pattern, pattern)
+ query = query.Where(
+ "id LIKE ? OR status LIKE ? OR trigger LIKE ? OR destination LIKE ? OR COALESCE(local_snapshot_id, "+
+ "'') LIKE ? OR COALESCE(remote_snapshot_id, '') LIKE ? OR COALESCE(error, '') LIKE ?",
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ pattern,
+ )
}
var totalItems int64
@@ -584,7 +620,18 @@ type backupPlanInternal struct {
destination volumetypes.BackupDestination
}
-func (s *VolumeService) resolveBackupPlanInternal(ctx context.Context, volumeName string, trigger VolumeBackupTrigger, request volumetypes.CreateBackupRequest, suppliedPolicy *VolumeBackupPolicy) (backupPlanInternal, error) {
+func (
+ s *VolumeService,
+) resolveBackupPlanInternal(
+ ctx context.Context,
+ volumeName string,
+ trigger VolumeBackupTrigger,
+ request volumetypes.CreateBackupRequest,
+ suppliedPolicy *VolumeBackupPolicy,
+) (
+ backupPlanInternal,
+ error,
+) {
destination := request.Destination
if destination != "" && destination != volumetypes.BackupDestinationLocal && destination != volumetypes.BackupDestinationS3 && destination != volumetypes.BackupDestinationLocalS3 {
return backupPlanInternal{}, errors.New("invalid volume backup destination")
@@ -647,7 +694,19 @@ func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, use
}
// CreateSystemManagedBackup runs the existing volume backup workflow with a transient centralized policy.
-func (s *VolumeService) CreateSystemManagedBackup(ctx context.Context, volumeName string, user common.User, trigger VolumeBackupTrigger, policyID string, policy backuptypes.UpdateBackupPolicy) (*VolumeBackup, error) {
+func (
+ s *VolumeService,
+) CreateSystemManagedBackup(
+ ctx context.Context,
+ volumeName string,
+ user common.User,
+ trigger VolumeBackupTrigger,
+ policyID string,
+ policy backuptypes.UpdateBackupPolicy,
+) (
+ *VolumeBackup,
+ error,
+) {
if !strings.HasPrefix(policyID, backuptypes.SystemVolumePolicyPrefix) {
return nil, errors.New("invalid system-managed volume backup policy id")
}
@@ -703,11 +762,19 @@ func (s *VolumeService) prepareBackupInternal(ctx context.Context, volumeName st
),
}
entry.ID = fmt.Sprintf("%s-%d-%s", volumeName, time.Now().UnixNano(), uuid.New().String()[:8])
- if err := s.db.WithContext(ctx).Create(entry).Error; err != nil {
+ if createBackupErr := s.db.WithContext(ctx).Create(entry).Error; createBackupErr != nil {
lease.Release(ctx)
- return nil, nil, err
- }
- checkpoint, err := json.Marshal(volumeBackupRecoveryInternal{BackupID: entry.ID, LocalEnabled: plan.localEnabled, S3Enabled: plan.s3Enabled, S3DestinationID: plan.s3DestinationID, Policy: plan.policy})
+ return nil, nil, createBackupErr
+ }
+ checkpoint, err := json.Marshal(
+ volumeBackupRecoveryInternal{
+ BackupID: entry.ID,
+ LocalEnabled: plan.localEnabled,
+ S3Enabled: plan.s3Enabled,
+ S3DestinationID: plan.s3DestinationID,
+ Policy: plan.policy,
+ },
+ )
if err == nil {
err = jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "volume_backup", ID: volumeName, Status: schedulertypes.Running, RecoveryData: checkpoint})
}
@@ -743,8 +810,8 @@ func (s *VolumeService) executeBackupInternal(ctx context.Context, entry *Volume
if workspaceLock.service != s || workspaceLock.volumeName != volumeName {
defer s.workspaceLocks.Lock(volumeName)()
}
- if err := ctx.Err(); err != nil {
- return err
+ if cancellationErr := ctx.Err(); cancellationErr != nil {
+ return cancellationErr
}
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
@@ -766,13 +833,13 @@ func (s *VolumeService) executeBackupInternal(ctx context.Context, entry *Volume
}
}
if plan.localEnabled && entry.LocalSnapshotID == "" {
- if err := s.createLocalBackupSnapshotInternal(ctx, dockerClient, entry); err != nil {
- return err
+ if createLocalBackupSnapshotErr := s.createLocalBackupSnapshotInternal(ctx, dockerClient, entry); createLocalBackupSnapshotErr != nil {
+ return createLocalBackupSnapshotErr
}
}
if plan.s3Enabled && entry.RemoteSnapshotID == "" {
- if err := s.createRemoteBackupSnapshotInternal(ctx, dockerClient, entry, plan); err != nil {
- return err
+ if createRemoteBackupSnapshotErr := s.createRemoteBackupSnapshotInternal(ctx, dockerClient, entry, plan); createRemoteBackupSnapshotErr != nil {
+ return createRemoteBackupSnapshotErr
}
}
if containersStopped {
@@ -809,17 +876,39 @@ func (s *VolumeService) createLocalBackupSnapshotInternal(ctx context.Context, d
if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: entry.ID + ":local", Status: schedulertypes.Running}); err != nil {
return err
}
- localSnapshot, err := s.engine.CreateSnapshot(ctx, dockerClient, repository, password, entry.VolumeName, backup.RootSnapshotInput(volumeSourceMountInternal(entry.VolumeName), backup.RunSnapshotTag(entry.ID)))
+ localSnapshot, err := s.engine.CreateSnapshot(
+ ctx,
+ dockerClient,
+ repository,
+ password,
+ entry.VolumeName,
+ backup.RootSnapshotInput(
+ volumeSourceMountInternal(
+ entry.VolumeName,
+ ),
+ backup.RunSnapshotTag(
+ entry.ID,
+ ),
+ ),
+ )
if err != nil {
return fmt.Errorf("failed to create local Rustic snapshot: %w", err)
}
entry.LocalSnapshotID = localSnapshot.ID
entry.Size = localSnapshot.Size
- if err := s.db.WithContext(ctx).Save(entry).Error; err != nil {
- return err
- }
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: entry.ID + ":local", Status: schedulertypes.Succeeded, Message: localSnapshot.ID}); err != nil {
- return err
+ if saveLocalBackupErr := s.db.WithContext(ctx).Save(entry).Error; saveLocalBackupErr != nil {
+ return saveLocalBackupErr
+ }
+ if progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "backup_destination",
+ ID: entry.ID + ":local",
+ Status: schedulertypes.Succeeded,
+ Message: localSnapshot.ID,
+ },
+ ); progressErr != nil {
+ return progressErr
}
return nil
}
@@ -834,8 +923,8 @@ func (s *VolumeService) createRemoteBackupSnapshotInternal(ctx context.Context,
if passwordErr != nil {
return passwordErr
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: entry.ID + ":remote", Status: schedulertypes.Running}); err != nil {
- return err
+ if progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: entry.ID + ":remote", Status: schedulertypes.Running}); progressErr != nil {
+ return progressErr
}
var remoteSnapshot backup.Snapshot
if plan.localEnabled {
@@ -845,7 +934,21 @@ func (s *VolumeService) createRemoteBackupSnapshotInternal(ctx context.Context,
}
remoteSnapshot, err = s.engine.Replicate(ctx, dockerClient, localRepository, entry.LocalSnapshotID, remoteRepository, password, entry.VolumeName, backup.RunSnapshotTag(entry.ID))
} else {
- remoteSnapshot, err = s.engine.CreateSnapshot(ctx, dockerClient, remoteRepository, password, entry.VolumeName, backup.RootSnapshotInput(volumeSourceMountInternal(entry.VolumeName), backup.RunSnapshotTag(entry.ID)))
+ remoteSnapshot, err = s.engine.CreateSnapshot(
+ ctx,
+ dockerClient,
+ remoteRepository,
+ password,
+ entry.VolumeName,
+ backup.RootSnapshotInput(
+ volumeSourceMountInternal(
+ entry.VolumeName,
+ ),
+ backup.RunSnapshotTag(
+ entry.ID,
+ ),
+ ),
+ )
}
if err != nil {
return fmt.Errorf("failed to create S3 Rustic snapshot: %w", err)
@@ -854,11 +957,19 @@ func (s *VolumeService) createRemoteBackupSnapshotInternal(ctx context.Context,
if entry.Size == 0 {
entry.Size = remoteSnapshot.Size
}
- if err := s.db.WithContext(ctx).Save(entry).Error; err != nil {
- return err
+ if saveRemoteBackupErr := s.db.WithContext(ctx).Save(entry).Error; saveRemoteBackupErr != nil {
+ return saveRemoteBackupErr
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "backup_destination", ID: entry.ID + ":remote", Status: schedulertypes.Succeeded, Message: remoteSnapshot.ID}); err != nil {
- return err
+ if remoteDestinationProgressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "backup_destination",
+ ID: entry.ID + ":remote",
+ Status: schedulertypes.Succeeded,
+ Message: remoteSnapshot.ID,
+ },
+ ); remoteDestinationProgressErr != nil {
+ return remoteDestinationProgressErr
}
return nil
}
@@ -887,8 +998,8 @@ func (s *VolumeService) UploadBackup(ctx context.Context, backupID, s3Destinatio
}
defer lease.Release(ctx)
// Reload under the lease: a delete may have raced the first read.
- if err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; err != nil {
- return nil, err
+ if loadUploadBackupErr := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; loadUploadBackupErr != nil {
+ return nil, loadUploadBackupErr
}
if entry.Status != VolumeBackupStatusSucceeded || entry.LocalSnapshotID == "" {
return nil, errors.New("only successful local volume backups can be uploaded")
@@ -902,7 +1013,7 @@ func (s *VolumeService) UploadBackup(ctx context.Context, backupID, s3Destinatio
if s.s3Destinations == nil {
return nil, errors.New("S3 backup destinations are unavailable")
}
- if _, err := s.s3Destinations.Configuration(ctx, s3DestinationID); err != nil {
+ if _, configurationErr := s.s3Destinations.Configuration(ctx, s3DestinationID); configurationErr != nil {
return nil, errors.New("select a valid S3 destination for the upload")
}
dockerClient, err := s.dockerService.GetClient(ctx)
@@ -928,8 +1039,8 @@ func (s *VolumeService) UploadBackup(ctx context.Context, backupID, s3Destinatio
entry.RemoteSnapshotID = snapshot.ID
entry.S3DestinationID = s3DestinationID
entry.Destination = volumetypes.BackupDestinationLocalS3
- if err := s.db.WithContext(ctx).Save(&entry).Error; err != nil {
- return nil, fmt.Errorf("failed to save uploaded volume backup: %w", err)
+ if saveUploadedBackupErr := s.db.WithContext(ctx).Save(&entry).Error; saveUploadedBackupErr != nil {
+ return nil, fmt.Errorf("failed to save uploaded volume backup: %w", saveUploadedBackupErr)
}
return &entry,
nil
@@ -988,8 +1099,8 @@ func (s *VolumeService) deleteRusticBackupsInternal(ctx context.Context, entries
}
for _, entry := range entries {
if entry.LocalSnapshotID == "" && entry.RemoteSnapshotID == "" {
- if err := s.db.WithContext(ctx).Delete(entry).Error; err != nil {
- deleteErr = errors.Join(deleteErr, fmt.Errorf("failed to delete volume backup record: %w", err))
+ if deleteBackupErr := s.db.WithContext(ctx).Delete(entry).Error; deleteBackupErr != nil {
+ deleteErr = errors.Join(deleteErr, fmt.Errorf("failed to delete volume backup record: %w", deleteBackupErr))
continue
}
s.logBackupDeleteEventInternal(ctx, entry.VolumeName, entry.ID, user)
@@ -1063,15 +1174,27 @@ func (s *VolumeService) logBackupDeleteEventInternal(ctx context.Context, volume
if actingUser == nil {
actingUser = &common.SystemUser
}
- if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupDelete, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", database.JSON{"action": "backup_delete", "backup_id": backupID}); logErr != nil {
+ if logErr := s.eventService.LogVolumeEvent(
+ ctx,
+ event.EventTypeVolumeBackupDelete,
+ volumeName,
+ volumeName,
+ actingUser.ID,
+ actingUser.Username,
+ "0",
+ database.JSON{
+ "action": "backup_delete",
+ "backup_id": backupID,
+ },
+ ); logErr != nil {
slog.WarnContext(ctx, "could not log volume backup delete event", "volume", volumeName, "error", logErr)
}
}
func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupID string, user common.User) (err error) {
var entry VolumeBackup
- if err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; err != nil {
- return err
+ if loadRestoreBackupErr := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; loadRestoreBackupErr != nil {
+ return loadRestoreBackupErr
}
if entry.VolumeName != volumeName {
return errors.New("backup does not belong to volume")
@@ -1128,11 +1251,25 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupID
}
}
if entry.Format == VolumeBackupFormatArchive {
- if err := s.restoreArchiveBackupInternal(ctx, dockerClient, volumeName, backupID); err != nil {
- return err
- }
- } else if err := s.engine.RestoreSnapshot(ctx, dockerClient, repository, password, snapshotID, mount.Mount{Type: mount.TypeVolume, Source: volumeName, Target: "/volume"}, backup.RestoreOptions{DeleteExtra: true}); err != nil {
- return fmt.Errorf("failed to restore Rustic snapshot: %w", err)
+ if restoreArchiveBackupErr := s.restoreArchiveBackupInternal(ctx, dockerClient, volumeName, backupID); restoreArchiveBackupErr != nil {
+ return restoreArchiveBackupErr
+ }
+ } else if restoreSnapshotErr := s.engine.RestoreSnapshot(
+ ctx,
+ dockerClient,
+ repository,
+ password,
+ snapshotID,
+ mount.Mount{
+ Type: mount.TypeVolume,
+ Source: volumeName,
+ Target: "/volume",
+ },
+ backup.RestoreOptions{
+ DeleteExtra: true,
+ },
+ ); restoreSnapshotErr != nil {
+ return fmt.Errorf("failed to restore Rustic snapshot: %w", restoreSnapshotErr)
}
if containersStopped {
stopped, err = s.startContainersAfterBackupInternal(context.WithoutCancel(ctx), dockerClient, stopped, user)
@@ -1181,8 +1318,8 @@ func (s *VolumeService) BrowseBackupFiles(ctx context.Context, backupID, request
return nil, pagination.Response{}, fmt.Errorf("%w: %w", common.ErrInvalidBackupSelection, err)
}
var entry VolumeBackup
- if err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; err != nil {
- return nil, pagination.Response{}, err
+ if loadBrowseBackupErr := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; loadBrowseBackupErr != nil {
+ return nil, pagination.Response{}, loadBrowseBackupErr
}
entries, err := s.backupFileEntriesInternal(ctx, &entry, listPath, recursive)
if err != nil {
@@ -1242,7 +1379,19 @@ type volumeBackupRestoreSelectionInternal struct {
globalRoot bool
}
-func (s *VolumeService) resolveVolumeBackupRestoreSelectionInternal(ctx context.Context, dockerClient *client.Client, entry *VolumeBackup, repository backup.Repository, snapshotID string, selection backuptypes.RestoreSelection) (volumeBackupRestoreSelectionInternal, error) {
+func (
+ s *VolumeService,
+) resolveVolumeBackupRestoreSelectionInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ entry *VolumeBackup,
+ repository backup.Repository,
+ snapshotID string,
+ selection backuptypes.RestoreSelection,
+) (
+ volumeBackupRestoreSelectionInternal,
+ error,
+) {
if selection.SelectAll && strings.TrimSpace(selection.Search) == "" {
if _, err := backupbrowser.NormalizeSelection(selection, []backuptypes.BackupFileEntry{{Path: "", IsDirectory: true}}); err != nil {
return volumeBackupRestoreSelectionInternal{}, fmt.Errorf("%w: %w", common.ErrInvalidBackupSelection, err)
@@ -1274,7 +1423,17 @@ func (s *VolumeService) resolveVolumeBackupRestoreSelectionInternal(ctx context.
return resolved, nil
}
-func (s *VolumeService) restoreVolumeBackupSelectionInternal(ctx context.Context, dockerClient *client.Client, volumeName, backupID string, entry *VolumeBackup, repository backup.Repository, snapshotID string, selection volumeBackupRestoreSelectionInternal) error {
+func (
+ s *VolumeService,
+) restoreVolumeBackupSelectionInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ volumeName, backupID string,
+ entry *VolumeBackup,
+ repository backup.Repository,
+ snapshotID string,
+ selection volumeBackupRestoreSelectionInternal,
+) error {
if entry.Format == VolumeBackupFormatArchive {
if selection.globalRoot {
return s.restoreArchiveBackupInternal(ctx, dockerClient, volumeName, backupID)
@@ -1288,8 +1447,8 @@ func (s *VolumeService) restoreVolumeBackupSelectionInternal(ctx context.Context
}
target := mount.Mount{Type: mount.TypeVolume, Source: volumeName, Target: "/volume"}
if selection.globalRoot {
- if err := s.engine.RestoreSnapshot(ctx, dockerClient, repository, password, snapshotID, target, backup.RestoreOptions{DeleteExtra: true}); err != nil {
- return fmt.Errorf("failed to restore Rustic snapshot: %w", err)
+ if restoreSnapshotErr := s.engine.RestoreSnapshot(ctx, dockerClient, repository, password, snapshotID, target, backup.RestoreOptions{DeleteExtra: true}); restoreSnapshotErr != nil {
+ return fmt.Errorf("failed to restore Rustic snapshot: %w", restoreSnapshotErr)
}
return nil
}
@@ -1299,8 +1458,8 @@ func (s *VolumeService) restoreVolumeBackupSelectionInternal(ctx context.Context
sourcePath += "/"
}
options := backup.RestoreOptions{DeleteExtra: selectedEntry.IsDirectory, SourcePath: sourcePath, DestinationPath: path.Join(target.Target, selectedEntry.Path)}
- if err := s.engine.RestoreSnapshot(ctx, dockerClient, repository, password, snapshotID, target, options); err != nil {
- return fmt.Errorf("failed to restore %s from Rustic snapshot: %w", selectedEntry.Path, err)
+ if restoreSelectedEntryErr := s.engine.RestoreSnapshot(ctx, dockerClient, repository, password, snapshotID, target, options); restoreSelectedEntryErr != nil {
+ return fmt.Errorf("failed to restore %s from Rustic snapshot: %w", selectedEntry.Path, restoreSelectedEntryErr)
}
}
return nil
@@ -1308,8 +1467,8 @@ func (s *VolumeService) restoreVolumeBackupSelectionInternal(ctx context.Context
func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backupID string, selection backuptypes.RestoreSelection, user common.User) (err error) {
var entry VolumeBackup
- if err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; err != nil {
- return err
+ if loadFileBackupErr := s.db.WithContext(ctx).Where("id = ?", backupID).First(&entry).Error; loadFileBackupErr != nil {
+ return loadFileBackupErr
}
if entry.VolumeName != volumeName {
return errors.New("backup does not belong to volume")
@@ -1351,8 +1510,17 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, back
if err != nil {
return fmt.Errorf("failed to create pre-restore backup: %w", err)
}
- if err := s.restoreVolumeBackupSelectionInternal(ctx, dockerClient, volumeName, backupID, &entry, repository, snapshotID, resolvedSelection); err != nil {
- return err
+ if restoreVolumeBackupSelectionErr := s.restoreVolumeBackupSelectionInternal(
+ ctx,
+ dockerClient,
+ volumeName,
+ backupID,
+ &entry,
+ repository,
+ snapshotID,
+ resolvedSelection,
+ ); restoreVolumeBackupSelectionErr != nil {
+ return restoreVolumeBackupSelectionErr
}
if containersStopped {
stopped, err = s.startContainersAfterBackupInternal(context.WithoutCancel(ctx), dockerClient, stopped, user)
@@ -1361,7 +1529,16 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, back
return err
}
}
- metadata := database.JSON{"action": "backup_restore_files", "backup_id": backupID, "pre_restore_backupId": preBackup.ID, "paths_count": len(resolvedSelection.entries), "select_all": selection.SelectAll, "search": selection.Search}
+ metadata := database.JSON{
+ "action": "backup_restore_files",
+ "backup_id": backupID,
+ "pre_restore_backupId": preBackup.ID,
+ "paths_count": len(
+ resolvedSelection.entries,
+ ),
+ "select_all": selection.SelectAll,
+ "search": selection.Search,
+ }
if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupRestoreFiles, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {
slog.WarnContext(ctx, "could not log volume backup restore files event", "volume", volumeName, "error", logErr)
}
@@ -1437,15 +1614,29 @@ func (s *VolumeService) downloadRusticBackupInternal(ctx context.Context, entry
return nil, 0, err
}
scratchVolume := "arcane-rustic-download-" + uuid.New().String()
- if _, err := dockerClient.VolumeCreate(ctx, client.VolumeCreateOptions{Name: scratchVolume, Labels: volumehelper.Labels()}); err != nil {
- return nil, 0, fmt.Errorf("failed to create download scratch volume: %w", err)
+ if _, volumeCreateErr := dockerClient.VolumeCreate(ctx, client.VolumeCreateOptions{Name: scratchVolume, Labels: volumehelper.Labels()}); volumeCreateErr != nil {
+ return nil, 0, fmt.Errorf("failed to create download scratch volume: %w", volumeCreateErr)
}
removeScratch := func() {
_, _ = dockerClient.VolumeRemove(context.WithoutCancel(ctx), scratchVolume, client.VolumeRemoveOptions{Force: true})
}
- if err := s.engine.RestoreSnapshot(ctx, dockerClient, repository, password, entry.LocalSnapshotID, mount.Mount{Type: mount.TypeVolume, Source: scratchVolume, Target: "/volume"}, backup.RestoreOptions{DeleteExtra: true}); err != nil {
+ if restoreSnapshotErr := s.engine.RestoreSnapshot(
+ ctx,
+ dockerClient,
+ repository,
+ password,
+ entry.LocalSnapshotID,
+ mount.Mount{
+ Type: mount.TypeVolume,
+ Source: scratchVolume,
+ Target: "/volume",
+ },
+ backup.RestoreOptions{
+ DeleteExtra: true,
+ },
+ ); restoreSnapshotErr != nil {
removeScratch()
- return nil, 0, fmt.Errorf("failed to restore Rustic snapshot for download: %w", err)
+ return nil, 0, fmt.Errorf("failed to restore Rustic snapshot for download: %w", restoreSnapshotErr)
}
helperImage, err := s.getVolumeHelperImageInternal(ctx, dockerClient)
if err != nil {
@@ -1463,9 +1654,9 @@ func (s *VolumeService) downloadRusticBackupInternal(ctx context.Context, entry
removeScratch()
}
archivePath := "/tmp/" + entry.ID + ".tar.gz"
- if _, _, err := s.execInContainerInternal(ctx, containerID, "", []string{"tar", "-czf", archivePath, "-C", "/volume", "."}); err != nil {
+ if _, _, execInContainerErr := s.execInContainerInternal(ctx, containerID, "", []string{"tar", "-czf", archivePath, "-C", "/volume", "."}); execInContainerErr != nil {
cleanup()
- return nil, 0, fmt.Errorf("failed to package Rustic snapshot for download: %w", err)
+ return nil, 0, fmt.Errorf("failed to package Rustic snapshot for download: %w", execInContainerErr)
}
return volumehelper.DownloadFileFromContainer(ctx, dockerClient, containerID, archivePath, cleanup)
}
@@ -1503,9 +1694,9 @@ func (s *VolumeService) createBackupTempContainerWithMountInternal(ctx context.C
return "", nil, fmt.Errorf("failed to create backup temp container: %w", err)
}
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
_, _ = dockerClient.ContainerRemove(ctx, resp.ID, volumehelper.RemoveOptions())
- return "", nil, fmt.Errorf("failed to start backup temp container: %w", err)
+ return "", nil, fmt.Errorf("failed to start backup temp container: %w", containerStartErr)
}
cleanup := func() {
@@ -1592,7 +1783,13 @@ func (s *VolumeService) restoreArchiveBackupInternal(ctx context.Context, docker
Cmd: []string{
"sh",
"-c",
- fmt.Sprintf("set -e; tmp=$(mktemp -d /volume/.restore_tmp.XXXXXX); tar -tzf /backups/%s >/dev/null; tar -xzf /backups/%s -C \"$tmp\"; find /volume -mindepth 1 -maxdepth 1 -not -path \"$tmp\" -exec rm -rf -- {} +; find \"$tmp\" -mindepth 1 -maxdepth 1 -exec mv -- {} /volume/ \\;; rmdir \"$tmp\"", filename, filename),
+ fmt.Sprintf(
+ "set -e; tmp=$(mktemp -d /volume/.restore_tmp.XXXXXX); tar -tzf /backups/%s >/dev/null; tar -xzf "+
+ "/backups/%s -C \"$tmp\"; find /volume -mindepth 1 -maxdepth 1 -not -path \"$tmp\" -exec rm -rf -- {} +; "+
+ "find \"$tmp\" -mindepth 1 -maxdepth 1 -exec mv -- {} /volume/ \\;; rmdir \"$tmp\"",
+ filename,
+ filename,
+ ),
},
Labels: volumehelper.Labels(),
}
@@ -1609,15 +1806,15 @@ func (s *VolumeService) restoreArchiveBackupInternal(ctx context.Context, docker
defer func() {
_, _ = dockerClient.ContainerRemove(context.WithoutCancel(ctx), resp.ID, volumehelper.RemoveOptions())
}()
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
- return fmt.Errorf("failed to start restore container: %w", err)
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
+ return fmt.Errorf("failed to start restore container: %w", containerStartErr)
}
waitResult := dockerClient.ContainerWait(ctx, resp.ID, client.ContainerWaitOptions{Condition: container.WaitConditionNotRunning})
var waitBody container.WaitResponse
select {
- case err := <-waitResult.Error:
- if err != nil {
- return err
+ case waitHelperErr := <-waitResult.Error:
+ if waitHelperErr != nil {
+ return waitHelperErr
}
case waitBody = <-waitResult.Result:
}
@@ -1718,8 +1915,8 @@ func (s *VolumeService) restoreArchiveBackupFilesInternal(ctx context.Context, d
defer func() {
_, _ = dockerClient.ContainerRemove(context.WithoutCancel(ctx), resp.ID, volumehelper.RemoveOptions())
}()
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
- return fmt.Errorf("failed to start restore container: %w", err)
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
+ return fmt.Errorf("failed to start restore container: %w", containerStartErr)
}
stderr, err := s.restoreBackupFilesInContainerInternal(ctx, resp.ID, filename, cleanedPaths)
if err != nil {
@@ -1738,9 +1935,9 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,
if err != nil {
return fmt.Errorf("invalid archive: %w", err)
}
- if _, err := tar.NewReader(gzr).Next(); err != nil {
+ if _, nextErr := tar.NewReader(gzr).Next(); nextErr != nil {
_ = gzr.Close()
- return fmt.Errorf("invalid archive: %w", err)
+ return fmt.Errorf("invalid archive: %w", nextErr)
}
_ = gzr.Close()
@@ -1775,8 +1972,8 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,
slog.DebugContext(ctx, "volume service: restore temp dir stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))
}
- if _, err := archive.Seek(0, io.SeekStart); err != nil {
- return fmt.Errorf("failed to read uploaded archive: %w", err)
+ if _, seekErr := archive.Seek(0, io.SeekStart); seekErr != nil {
+ return fmt.Errorf("failed to read uploaded archive: %w", seekErr)
}
_, err = dockerClient.CopyToContainer(ctx, containerID, client.CopyToContainerOptions{
DestinationPath: tmpDir,
@@ -1896,9 +2093,9 @@ func (s *VolumeService) UpdateBackupPolicies(ctx context.Context, volumeName str
UpdateID: func(update volumetypes.UpdateBackupPolicy) string { return update.ID },
New: func() VolumeBackupPolicy { return VolumeBackupPolicy{VolumeName: volumeName} },
Build: func(ctx context.Context, policy *VolumeBackupPolicy, update volumetypes.UpdateBackupPolicy) error {
- normalized, err := backup.ValidatePolicyUpdate(ctx, "volume", update, s.s3Destinations)
- if err != nil {
- return err
+ normalized, validatePolicyUpdateErr := backup.ValidatePolicyUpdate(ctx, "volume", update, s.s3Destinations)
+ if validatePolicyUpdateErr != nil {
+ return validatePolicyUpdateErr
}
update = normalized
policy.Enabled, policy.Schedule, policy.RetentionCount = update.Enabled, update.Schedule, update.RetentionCount
@@ -1909,8 +2106,8 @@ func (s *VolumeService) UpdateBackupPolicies(ctx context.Context, volumeName str
Unregister: s.jobs.Unregister,
Reschedule: s.rescheduleVolumeBackupPolicyInternal,
}
- if err := reconcile.Run(ctx, updates); err != nil {
- return nil, err
+ if runErr := reconcile.Run(ctx, updates); runErr != nil {
+ return nil, runErr
}
return s.GetBackupPolicies(ctx, volumeName)
}
@@ -1921,8 +2118,8 @@ func (s *VolumeService) applyVolumeBackupRetentionInternal(ctx context.Context,
return err
}
var entries []*VolumeBackup
- if err := s.db.WithContext(ctx).Where("id IN ?", expired).Find(&entries).Error; err != nil {
- return err
+ if loadExpiredBackupsErr := s.db.WithContext(ctx).Where("id IN ?", expired).Find(&entries).Error; loadExpiredBackupsErr != nil {
+ return loadExpiredBackupsErr
}
return s.deleteRusticBackupsInternal(ctx, entries, nil, includeRemote)
}
@@ -2039,8 +2236,8 @@ func (s *VolumeService) removeVolumeBackupPolicyInternal(ctx context.Context, vo
for i := range policies {
s.jobs.Unregister(ctx, policies[i].ID)
}
- if err := s.db.WithContext(ctx).Where("volume_name = ?", volumeName).Delete(&VolumeBackupPolicy{}).Error; err != nil {
- slog.WarnContext(ctx, "Failed to delete volume backup policy", "volume", volumeName, "error", err)
+ if deleteBackupPolicyErr := s.db.WithContext(ctx).Where("volume_name = ?", volumeName).Delete(&VolumeBackupPolicy{}).Error; deleteBackupPolicyErr != nil {
+ slog.WarnContext(ctx, "Failed to delete volume backup policy", "volume", volumeName, "error", deleteBackupPolicyErr)
}
}
@@ -2094,10 +2291,10 @@ func (s *VolumeService) DiscoverRemoteBackups(ctx context.Context, destinationID
return 0, nil, fmt.Errorf("failed to list volume backup repositories: %w", err)
}
var knownIDs []string
- if err := s.db.WithContext(ctx).Model(&VolumeBackup{}).
+ if loadSnapshotIDsErr := s.db.WithContext(ctx).Model(&VolumeBackup{}).
Where("s3_destination_id = ? AND remote_snapshot_id <> ''", destinationID).
- Pluck("remote_snapshot_id", &knownIDs).Error; err != nil {
- return 0, nil, err
+ Pluck("remote_snapshot_id", &knownIDs).Error; loadSnapshotIDsErr != nil {
+ return 0, nil, loadSnapshotIDsErr
}
known := make(map[string]struct{}, len(knownIDs))
for _, id := range knownIDs {
@@ -2129,8 +2326,8 @@ func (s *VolumeService) DiscoverRemoteBackups(ctx context.Context, destinationID
continue
}
known[snapshot.ID] = struct{}{}
- if err := s.db.WithContext(ctx).Create(entry).Error; err != nil {
- return created, failures, fmt.Errorf("failed to save discovered volume backup: %w", err)
+ if createDiscoveredBackupErr := s.db.WithContext(ctx).Create(entry).Error; createDiscoveredBackupErr != nil {
+ return created, failures, fmt.Errorf("failed to save discovered volume backup: %w", createDiscoveredBackupErr)
}
created++
}
@@ -2183,14 +2380,14 @@ func (s *VolumeService) MigrateRepositoryPasswords(ctx context.Context) error {
}
repositories := []backup.Repository{local}
if s.s3Destinations != nil {
- destinations, err := s.s3Destinations.ListS3DestinationsByID(ctx)
- if err != nil {
- return fmt.Errorf("failed to list S3 destinations for re-key: %w", err)
+ destinations, listS3DestinationsByIDErr := s.s3Destinations.ListS3DestinationsByID(ctx)
+ if listS3DestinationsByIDErr != nil {
+ return fmt.Errorf("failed to list S3 destinations for re-key: %w", listS3DestinationsByIDErr)
}
for destinationID := range destinations {
- remote, err := s.remoteRusticRepositoryInternal(ctx, destinationID)
- if err != nil {
- return err
+ remote, remoteRusticRepositoryErr := s.remoteRusticRepositoryInternal(ctx, destinationID)
+ if remoteRusticRepositoryErr != nil {
+ return remoteRusticRepositoryErr
}
repositories = append(repositories, remote)
}
diff --git a/backend/internal/volume/backup_management_test.go b/backend/internal/volume/backup_management_test.go
index 135e0cb00..9e8d6f9f9 100644
--- a/backend/internal/volume/backup_management_test.go
+++ b/backend/internal/volume/backup_management_test.go
@@ -1,7 +1,6 @@
package volume
import (
- "context"
"encoding/json/v2"
"testing"
"time"
@@ -32,7 +31,7 @@ func TestListBackupsPaginatedByManagementTypeInternal(t *testing.T) {
}
service := &VolumeService{db: &database.DB{DB: gormDB}}
- systemRows, page, err := service.ListBackupsPaginated(context.Background(), "app", pagination.QueryParams{
+ systemRows, page, err := service.ListBackupsPaginated(t.Context(), "app", pagination.QueryParams{
Filters: map[string]string{"type": "system"},
})
require.NoError(t, err)
@@ -40,7 +39,7 @@ func TestListBackupsPaginatedByManagementTypeInternal(t *testing.T) {
require.Len(t, systemRows, 1)
require.Equal(t, backuptypes.ManagementTypeSystem, systemRows[0].Type)
- volumeRows, page, err := service.ListBackupsPaginated(context.Background(), "app", pagination.QueryParams{
+ volumeRows, page, err := service.ListBackupsPaginated(t.Context(), "app", pagination.QueryParams{
Filters: map[string]string{"type": "volume"},
})
require.NoError(t, err)
diff --git a/backend/internal/volume/backup_run.go b/backend/internal/volume/backup_run.go
index 9f26ac586..c1f2d1a42 100644
--- a/backend/internal/volume/backup_run.go
+++ b/backend/internal/volume/backup_run.go
@@ -40,9 +40,35 @@ func (s *VolumeService) StartBackup(ctx context.Context, environmentID, volumeNa
entry.ActivityID = &activityID
accepted := entry.ToDTO()
keyID, _ := ctx.Value(middleware.ContextKeyApiKeyID).(string)
- payload, err := json.Marshal(manualVolumeBackupInternal{Checkpoint: volumeBackupRecoveryInternal{BackupID: entry.ID, LocalEnabled: plan.localEnabled, S3Enabled: plan.s3Enabled, S3DestinationID: plan.s3DestinationID, Policy: plan.policy}, VolumeName: volumeName, UserID: user.ID, ActivityID: activityID})
+ payload, err := json.Marshal(
+ manualVolumeBackupInternal{
+ Checkpoint: volumeBackupRecoveryInternal{
+ BackupID: entry.ID,
+ LocalEnabled: plan.localEnabled,
+ S3Enabled: plan.s3Enabled,
+ S3DestinationID: plan.s3DestinationID,
+ Policy: plan.policy,
+ },
+ VolumeName: volumeName,
+ UserID: user.ID,
+ ActivityID: activityID,
+ },
+ )
if err == nil {
- err = s.engine.SubmitDurableRun(workCtx, backuptypes.DurableRunCommand{Kind: "volume", RunID: entry.ID, ActivityID: activityID, Payload: payload, UserID: user.ID, EnvironmentID: environmentID, Permission: authz.PermVolumesBackup, RequestedWithKey: keyID}, lease)
+ err = s.engine.SubmitDurableRun(
+ workCtx,
+ backuptypes.DurableRunCommand{
+ Kind: "volume",
+ RunID: entry.ID,
+ ActivityID: activityID,
+ Payload: payload,
+ UserID: user.ID,
+ EnvironmentID: environmentID,
+ Permission: authz.PermVolumesBackup,
+ RequestedWithKey: keyID,
+ },
+ lease,
+ )
}
if err != nil {
lease.Release(ctx)
@@ -91,9 +117,9 @@ func (s *VolumeService) ReconcileBackup(ctx context.Context, previous schedulert
if !admitted {
return outcome, nil
}
- defer lease.Release(ctx)
- if err := s.resumeBackupInternal(ctx, previous, &entry, checkpoint); err != nil {
- return outcome, err
+ defer lease.Release(ctx) //nolint:gocritic // The matching recovery target always returns before the loop advances.
+ if resumeBackupErr := s.resumeBackupInternal(ctx, previous, &entry, checkpoint); resumeBackupErr != nil {
+ return outcome, resumeBackupErr
}
}
target.Status = schedulertypes.Succeeded
@@ -122,7 +148,19 @@ func (s *VolumeService) recoverSnapshotInternal(ctx context.Context, dockerClien
return s.engine.FindRunSnapshot(ctx, dockerClient, repository, password, entry.ID, snapshotID)
}
-func (s *VolumeService) observeBackupDestinationsInternal(ctx context.Context, dockerClient *client.Client, previous schedulertypes.Run, entry *VolumeBackup, checkpoint volumeBackupRecoveryInternal) (backup.Repository, backup.Repository, error) {
+func (
+ s *VolumeService,
+) observeBackupDestinationsInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ previous schedulertypes.Run,
+ entry *VolumeBackup,
+ checkpoint volumeBackupRecoveryInternal,
+) (
+ backup.Repository,
+ backup.Repository,
+ error,
+) {
var local, remote backup.Repository
var err error
if checkpoint.LocalEnabled {
@@ -131,9 +169,9 @@ func (s *VolumeService) observeBackupDestinationsInternal(ctx context.Context, d
return local, remote, err
}
if entry.LocalSnapshotID != "" || backupDestinationAttemptedInternal(previous, entry.ID, "local") {
- snapshot, found, err := s.recoverSnapshotInternal(ctx, dockerClient, local, entry, entry.LocalSnapshotID)
- if err != nil {
- return local, remote, err
+ snapshot, found, recoverSnapshotErr := s.recoverSnapshotInternal(ctx, dockerClient, local, entry, entry.LocalSnapshotID)
+ if recoverSnapshotErr != nil {
+ return local, remote, recoverSnapshotErr
}
if found {
entry.LocalSnapshotID, entry.Size = snapshot.ID, snapshot.Size
@@ -146,9 +184,9 @@ func (s *VolumeService) observeBackupDestinationsInternal(ctx context.Context, d
return local, remote, err
}
if entry.RemoteSnapshotID != "" || backupDestinationAttemptedInternal(previous, entry.ID, "remote") {
- snapshot, found, err := s.recoverSnapshotInternal(ctx, dockerClient, remote, entry, entry.RemoteSnapshotID)
- if err != nil {
- return local, remote, err
+ snapshot, found, recoverSnapshotErr2 := s.recoverSnapshotInternal(ctx, dockerClient, remote, entry, entry.RemoteSnapshotID)
+ if recoverSnapshotErr2 != nil {
+ return local, remote, recoverSnapshotErr2
}
if found {
entry.RemoteSnapshotID = snapshot.ID
@@ -171,20 +209,26 @@ func (s *VolumeService) resumeBackupInternal(ctx context.Context, previous sched
return err
}
if checkpoint.LocalEnabled && entry.LocalSnapshotID == "" && entry.RemoteSnapshotID != "" {
- password, err := s.volumeBackupPasswordInternal(ctx, dockerClient, remote)
- if err != nil {
- return err
+ password, volumeBackupPasswordErr := s.volumeBackupPasswordInternal(ctx, dockerClient, remote)
+ if volumeBackupPasswordErr != nil {
+ return volumeBackupPasswordErr
}
- snapshot, err := s.engine.Replicate(ctx, dockerClient, remote, entry.RemoteSnapshotID, local, password, entry.VolumeName, backup.RunSnapshotTag(entry.ID))
- if err != nil {
- return err
+ snapshot, volumeBackupPasswordErr := s.engine.Replicate(ctx, dockerClient, remote, entry.RemoteSnapshotID, local, password, entry.VolumeName, backup.RunSnapshotTag(entry.ID))
+ if volumeBackupPasswordErr != nil {
+ return volumeBackupPasswordErr
}
entry.LocalSnapshotID = snapshot.ID
}
- if err := s.db.WithContext(ctx).Save(entry).Error; err != nil {
- return err
+ if operationErr := s.db.WithContext(ctx).Save(entry).Error; operationErr != nil {
+ return operationErr
+ }
+ plan := backupPlanInternal{
+ localEnabled: checkpoint.LocalEnabled,
+ s3Enabled: checkpoint.S3Enabled,
+ s3DestinationID: checkpoint.S3DestinationID,
+ policy: checkpoint.Policy,
+ destination: entry.Destination,
}
- plan := backupPlanInternal{localEnabled: checkpoint.LocalEnabled, s3Enabled: checkpoint.S3Enabled, s3DestinationID: checkpoint.S3DestinationID, policy: checkpoint.Policy, destination: entry.Destination}
err = s.executeBackupInternal(ctx, entry, common.SystemUser, plan)
return s.completeBackupInternal(ctx, entry, err)
}
@@ -198,8 +242,8 @@ type manualVolumeBackupInternal struct {
func (s *VolumeService) executeDurableBackupInternal(ctx context.Context, runID string, payload []byte, interrupted bool) (err error) {
var command manualVolumeBackupInternal
- if err = json.Unmarshal(payload, &command); err != nil {
- return err
+ if decodeErr := json.Unmarshal(payload, &command); decodeErr != nil {
+ return decodeErr
}
defer func() {
if ctx.Err() == nil {
@@ -211,8 +255,8 @@ func (s *VolumeService) executeDurableBackupInternal(ctx context.Context, runID
}
}()
var entry VolumeBackup
- if err = s.db.WithContext(ctx).Where("id = ?", command.Checkpoint.BackupID).First(&entry).Error; err != nil {
- return err
+ if loadBackupErr := s.db.WithContext(ctx).Where("id = ?", command.Checkpoint.BackupID).First(&entry).Error; loadBackupErr != nil {
+ return loadBackupErr
}
if entry.Status == VolumeBackupStatusSucceeded {
@@ -239,18 +283,33 @@ func (s *VolumeService) executeDurableBackupInternal(ctx context.Context, runID
defer lease.Release(ctx)
user := common.SystemUser
if command.UserID != "" && command.UserID != "agent" {
- if err = s.db.WithContext(ctx).Where("id = ?", command.UserID).First(&user).Error; err != nil {
- return err
+ if loadUserErr := s.db.WithContext(ctx).Where("id = ?", command.UserID).First(&user).Error; loadUserErr != nil {
+ return loadUserErr
}
}
checkpoint, err := json.Marshal(command.Checkpoint)
if err != nil {
return err
}
- if err = jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "volume_backup", ID: command.VolumeName, Status: schedulertypes.Running, RecoveryData: checkpoint, ActivityID: command.ActivityID}); err != nil {
- return err
+ if progressErr := jobcontext.Progress(
+ ctx,
+ schedulertypes.TargetOutcome{
+ ResourceType: "volume_backup",
+ ID: command.VolumeName,
+ Status: schedulertypes.Running,
+ RecoveryData: checkpoint,
+ ActivityID: command.ActivityID,
+ },
+ ); progressErr != nil {
+ return progressErr
+ }
+ plan := backupPlanInternal{
+ localEnabled: command.Checkpoint.LocalEnabled,
+ s3Enabled: command.Checkpoint.S3Enabled,
+ s3DestinationID: command.Checkpoint.S3DestinationID,
+ policy: command.Checkpoint.Policy,
+ destination: entry.Destination,
}
- plan := backupPlanInternal{localEnabled: command.Checkpoint.LocalEnabled, s3Enabled: command.Checkpoint.S3Enabled, s3DestinationID: command.Checkpoint.S3DestinationID, policy: command.Checkpoint.Policy, destination: entry.Destination}
err = s.executeBackupInternal(ctx, &entry, user, plan)
if ctx.Err() != nil {
return ctx.Err()
diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.go
index 9b4d35be9..4643df339 100644
--- a/backend/internal/volume/handler.go
+++ b/backend/internal/volume/handler.go
@@ -240,7 +240,15 @@ type UploadBackupInput struct {
}
// RegisterVolumes registers volume management routes using Huma.
-func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, volumeService *VolumeService, activityService *activity.ActivityService, environmentService *environment.EnvironmentService, uploadService *upload.UploadService, appCtx handlerutil.ActivityAppContext) {
+func RegisterVolumes(
+ api huma.API,
+ dockerService *docker.DockerClientService,
+ volumeService *VolumeService,
+ activityService *activity.ActivityService,
+ environmentService *environment.EnvironmentService,
+ uploadService *upload.UploadService,
+ appCtx handlerutil.ActivityAppContext,
+) {
h := &VolumeHandler{
volumeService: volumeService,
dockerService: dockerService,
@@ -471,7 +479,9 @@ func RegisterVolumes(api huma.API, dockerService *docker.DockerClientService, vo
Method: http.MethodPost,
Path: "/environments/{id}/volumes/{volumeName}/backups/upload",
Summary: "Upload and restore volume backup",
- Description: "Restore a volume from a complete chunked upload session containing a tar.gz backup archive. multipart/form-data bodies are still accepted for backward compatibility; that form is deprecated and will be removed in a future release.",
+ Description: "Restore a volume from a complete chunked upload session containing a tar.gz backup archive. " +
+ "multipart/form-data bodies are still accepted for backward compatibility; that form is deprecated " +
+ "and will be removed in a future release.",
Tags: []string{"Volume Backup"},
Security: handlerutil.DefaultOperationSecurity(),
Middlewares: upload.LegacyMultipartMiddleware(api, h.uploadService, uploadtypes.KindVolumeBackup),
@@ -505,7 +515,15 @@ func (h *VolumeHandler) GetBackupPolicy(ctx context.Context, input *GetVolumeBac
return nil, huma.Error500InternalServerError("environment service not available")
}
remotePath := fmt.Sprintf("/api/environments/0/volumes/%s/backup-policy", url.PathEscape(input.VolumeName))
- response, err := handlerutil.RemoteJSONProxy(h.environmentService.ProxyJSONRequest).JSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](ctx, input.EnvironmentID, http.MethodGet, remotePath, nil)
+ response, err := handlerutil.RemoteJSONProxy(
+ h.environmentService.ProxyJSONRequest,
+ ).JSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](
+ ctx,
+ input.EnvironmentID,
+ http.MethodGet,
+ remotePath,
+ nil,
+ )
if err != nil {
return nil, err
}
@@ -565,7 +583,15 @@ func (h *VolumeHandler) UpdateBackupPolicy(ctx context.Context, input *UpdateVol
}
remotePath := fmt.Sprintf("/api/environments/0/volumes/%s/backup-policy", url.PathEscape(input.VolumeName))
var proxyErr error
- remoteResponse, proxyErr = handlerutil.RemoteJSONProxy(h.environmentService.ProxyJSONRequest).JSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](activityCtx, input.EnvironmentID, http.MethodPut, remotePath, input.Body)
+ remoteResponse, proxyErr = handlerutil.RemoteJSONProxy(
+ h.environmentService.ProxyJSONRequest,
+ ).JSON[base.ApiResponse[volumetypes.BackupPolicyCollection]](
+ activityCtx,
+ input.EnvironmentID,
+ http.MethodPut,
+ remotePath,
+ input.Body,
+ )
if proxyErr != nil {
errorStatus = http.StatusBadGateway
}
diff --git a/backend/internal/volume/helper_container.go b/backend/internal/volume/helper_container.go
index f66e43a74..e1c4079ac 100644
--- a/backend/internal/volume/helper_container.go
+++ b/backend/internal/volume/helper_container.go
@@ -52,8 +52,8 @@ func (s *VolumeService) requireVolumeHelperACFSInternal(ctx context.Context, vol
return fmt.Errorf("%s: %w", "volume workspace requires an ACFS-capable tools image: "+strings.TrimSpace(stderr), err)
}
var response acfstypes.VersionResponse
- if err := json.Unmarshal([]byte(stdout), &response); err != nil {
- return fmt.Errorf("parse ACFS tools-image capability: %w", err)
+ if unmarshalErr := json.Unmarshal([]byte(stdout), &response); unmarshalErr != nil {
+ return fmt.Errorf("parse ACFS tools-image capability: %w", unmarshalErr)
}
if response.Protocol < acfstypes.ProtocolVersion {
return fmt.Errorf("volume workspace requires ACFS protocol %d, tools image provides protocol %d", acfstypes.ProtocolVersion, response.Protocol)
@@ -120,7 +120,7 @@ func (s *VolumeService) getVolumeHelperImageInternal(ctx context.Context, docker
toolsImage := s.toolsImageInternal()
- if _, err := dockerClient.ImageInspect(ctx, toolsImage); err == nil {
+ if _, imageInspectErr := dockerClient.ImageInspect(ctx, toolsImage); imageInspectErr == nil {
slog.InfoContext(ctx, "volume service: helper image strategy selected", "strategy", "tools-local", "image", toolsImage)
return toolsImage, nil
}
@@ -159,9 +159,9 @@ func (s *VolumeService) acquireVolumeHelperInternal(ctx context.Context, volumeN
// acquire gap is racy against the reaper, so retry a resolve whose helper
// was reaped before this caller could take its hold.
for range 3 {
- containerID, err := s.resolveHelperInternal(ctx, dockerClient, volumeName)
- if err != nil {
- return "", nil, err
+ containerID, resolveHelperErr := s.resolveHelperInternal(ctx, dockerClient, volumeName)
+ if resolveHelperErr != nil {
+ return "", nil, resolveHelperErr
}
if release, ok := s.acquireHelperInternal(volumeName, containerID); ok {
return containerID, release, nil
@@ -279,8 +279,8 @@ func (s *VolumeService) startHelperContainerInternal(ctx context.Context, docker
return "", nil, fmt.Errorf("failed to create temp container: %w", err)
}
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
- startErr := fmt.Errorf("failed to start temp container: %w", err)
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
+ startErr := fmt.Errorf("failed to start temp container: %w", containerStartErr)
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeouts.DefaultDockerAPI)
defer cancel()
if _, cleanupErr := dockerClient.ContainerRemove(cleanupCtx, resp.ID, volumehelper.RemoveOptions()); cleanupErr != nil && !cerrdefs.IsNotFound(cleanupErr) {
@@ -358,8 +358,8 @@ func (s *VolumeService) CleanupHelperContainers(ctx context.Context) {
s.helperMu.Unlock()
for _, containerID := range helperIDs {
- if _, err := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); err != nil {
- slog.WarnContext(ctx, "failed to remove helper container", "container_id", containerID, "error", err.Error())
+ if _, containerRemoveErr := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); containerRemoveErr != nil {
+ slog.WarnContext(ctx, "failed to remove helper container", "container_id", containerID, "error", containerRemoveErr.Error())
}
}
}
@@ -383,8 +383,8 @@ func (s *VolumeService) ReapIdleHelpers(ctx context.Context, idleTimeout time.Du
removed := 0
for _, containerID := range staleIDs {
- if _, err := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); err != nil {
- slog.WarnContext(ctx, "failed to remove idle helper container", "container_id", containerID, "error", err.Error())
+ if _, containerRemoveErr := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); containerRemoveErr != nil {
+ slog.WarnContext(ctx, "failed to remove idle helper container", "container_id", containerID, "error", containerRemoveErr.Error())
continue
}
removed++
@@ -439,8 +439,8 @@ func (s *VolumeService) StopHelper(ctx context.Context, volumeName string) error
return nil
}
- if _, err := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); err != nil {
- return fmt.Errorf("failed to remove helper container: %w", err)
+ if _, containerRemoveErr := dockerClient.ContainerRemove(ctx, containerID, volumehelper.RemoveOptions()); containerRemoveErr != nil {
+ return fmt.Errorf("failed to remove helper container: %w", containerRemoveErr)
}
return nil
@@ -478,13 +478,13 @@ func (s *VolumeService) CleanupOrphanedVolumeHelpers(ctx context.Context) (int,
continue
}
- if _, err := dockerClient.ContainerRemove(ctx, c.ID, volumehelper.RemoveOptions()); err != nil {
+ if _, containerRemoveErr := dockerClient.ContainerRemove(ctx, c.ID, volumehelper.RemoveOptions()); containerRemoveErr != nil {
slog.WarnContext(
ctx,
"volume service: failed to remove orphaned volume helper container",
"container_id", c.ID,
"container_names", c.Names,
- "error", err.Error(),
+ "error", containerRemoveErr.Error(),
)
continue
}
diff --git a/backend/internal/volume/listing.go b/backend/internal/volume/listing.go
index 2a74c188c..aa0939417 100644
--- a/backend/internal/volume/listing.go
+++ b/backend/internal/volume/listing.go
@@ -342,7 +342,22 @@ func (s *VolumeService) ListBackupVolumeOptions(ctx context.Context) ([]backupty
func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params pagination.QueryParams, includeInternal bool) ([]volumetypes.Volume, pagination.Response, volumetypes.UsageCounts, error) {
startedAt := time.Now()
- slog.DebugContext(ctx, "volume service: list volumes paginated", "search", params.Search, "sort", params.Sort, "order", params.Order, "start", params.Start, "limit", params.Limit, "include_internal", includeInternal)
+ slog.DebugContext(
+ ctx,
+ "volume service: list volumes paginated",
+ "search",
+ params.Search,
+ "sort",
+ params.Sort,
+ "order",
+ params.Order,
+ "start",
+ params.Start,
+ "limit",
+ params.Limit,
+ "include_internal",
+ includeInternal,
+ )
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
return nil, pagination.Response{}, volumetypes.UsageCounts{}, fmt.Errorf("failed to connect to Docker: %w", err)
@@ -366,13 +381,13 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, params paginat
defer cancel()
go func(ctx context.Context) {
- volListBody, err := dockerClient.VolumeList(ctx, client.VolumeListOptions{})
- volChan <- volumeListResult{volumes: volListBody.Items, err: err}
+ volListBody, volumeListErr := dockerClient.VolumeList(ctx, client.VolumeListOptions{})
+ volChan <- volumeListResult{volumes: volListBody.Items, err: volumeListErr}
}(apiCtx)
go func(ctx context.Context) {
- containerMap, err := s.buildVolumeContainerMapInternal(ctx)
- containerChan <- containerMapResult{containerMap: containerMap, err: err}
+ containerMap, buildVolumeContainerMapErr := s.buildVolumeContainerMapInternal(ctx)
+ containerChan <- containerMapResult{containerMap: containerMap, err: buildVolumeContainerMapErr}
}(apiCtx)
// Wait for both results
diff --git a/backend/internal/volume/module.go b/backend/internal/volume/module.go
index 914d66b38..2ee577c46 100644
--- a/backend/internal/volume/module.go
+++ b/backend/internal/volume/module.go
@@ -22,7 +22,13 @@ type Module struct {
}
// New wires volume routes around an existing service.
-func New(service *VolumeService, dockerService *docker.DockerClientService, activityService *activity.ActivityService, environmentService *environment.EnvironmentService, uploadService *upload.UploadService) *Module {
+func New(
+ service *VolumeService,
+ dockerService *docker.DockerClientService,
+ activityService *activity.ActivityService,
+ environmentService *environment.EnvironmentService,
+ uploadService *upload.UploadService,
+) *Module {
return &Module{service: service, dockerService: dockerService, activityService: activityService, environmentService: environmentService, uploadService: uploadService}
}
diff --git a/backend/internal/volume/rename.go b/backend/internal/volume/rename.go
index 9516db4b8..1b05377a3 100644
--- a/backend/internal/volume/rename.go
+++ b/backend/internal/volume/rename.go
@@ -61,31 +61,31 @@ func (s *VolumeService) RenameVolume(ctx context.Context, oldName, newName strin
s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "plan", err)
return nil, err
}
- if err := migration.Apply(ctx); err != nil {
- if cerrdefs.IsInvalidArgument(err) {
- err = common.Classify(common.ErrBadRequest, err)
+ if applyErr := migration.Apply(ctx); applyErr != nil {
+ if cerrdefs.IsInvalidArgument(applyErr) {
+ applyErr = common.Classify(common.ErrBadRequest, applyErr)
}
- s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "apply", err)
- return nil, err
+ s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "apply", applyErr)
+ return nil, applyErr
}
- if err := s.renameVolumeMetadataInternal(ctx, oldName, newName); err != nil {
+ if renameVolumeMetadataErr := s.renameVolumeMetadataInternal(ctx, oldName, newName); renameVolumeMetadataErr != nil {
rollbackErr := migration.Rollback(ctx)
- combinedErr := errors.Join(fmt.Errorf("rename volume metadata: %w", err), rollbackErr)
+ combinedErr := errors.Join(fmt.Errorf("rename volume metadata: %w", renameVolumeMetadataErr), rollbackErr)
s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "metadata", combinedErr)
return nil, combinedErr
}
if committer, ok := migration.(volumetypes.Committer); ok {
- if err := committer.Commit(ctx); err != nil {
- if _, ok := errors.AsType[*volumetypes.SourceCleanupError](err); ok {
+ if commitErr := committer.Commit(ctx); commitErr != nil {
+ if _, localOk := errors.AsType[*volumetypes.SourceCleanupError](commitErr); localOk {
// The copy and metadata are committed; only removing the source
// failed, so the rename itself succeeded.
- slog.WarnContext(ctx, "volume renamed but source volume could not be removed", "oldVolume", oldName, "newVolume", newName, "error", err.Error())
+ slog.WarnContext(ctx, "volume renamed but source volume could not be removed", "oldVolume", oldName, "newVolume", newName, "error", commitErr.Error())
} else {
metadataErr := s.renameVolumeMetadataInternal(ctx, newName, oldName)
rollbackErr := migration.Rollback(ctx)
- combinedErr := errors.Join(err, metadataErr, rollbackErr)
+ combinedErr := errors.Join(commitErr, metadataErr, rollbackErr)
s.logVolumeRenameErrorInternal(ctx, oldName, newName, user, "commit", combinedErr)
return nil, combinedErr
}
diff --git a/backend/internal/volume/service.go b/backend/internal/volume/service.go
index 4af9e07c7..83bdfad6d 100644
--- a/backend/internal/volume/service.go
+++ b/backend/internal/volume/service.go
@@ -75,7 +75,19 @@ type volumeWorkspaceLockContextInternal struct {
const internalVolumePruneFilterValue = libarcane.InternalResourceLabel + "=true"
-func NewVolumeService(db *database.DB, dockerService *docker.DockerClientService, eventService *event.EventService, activityService *activity.ActivityService, settingsService *settings.SettingsService, containerService *container.ContainerService, imageService *image.ImageService, engine *backup.Engine, s3Destinations *s3domain.S3DestinationService, cfg *config.Config, recoveryKeys *backup.RecoveryKeyStore) *VolumeService {
+func NewVolumeService(
+ db *database.DB,
+ dockerService *docker.DockerClientService,
+ eventService *event.EventService,
+ activityService *activity.ActivityService,
+ settingsService *settings.SettingsService,
+ containerService *container.ContainerService,
+ imageService *image.ImageService,
+ engine *backup.Engine,
+ s3Destinations *s3domain.S3DestinationService,
+ cfg *config.Config,
+ recoveryKeys *backup.RecoveryKeyStore,
+) *VolumeService {
slog.Debug("volume service: new")
backupVolumeName := ""
encryptionKey := ""
@@ -130,8 +142,8 @@ func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*volu
}
vol := volResult.Volume
- settings := s.settingsService.GetSettingsConfig()
- usageCtx, usageCancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.DockerAPITimeout.AsInt(), timeouts.DefaultDockerAPI))
+ localSettings := s.settingsService.GetSettingsConfig()
+ usageCtx, usageCancel := context.WithTimeout(ctx, timeouts.GetDuration(localSettings.DockerAPITimeout.AsInt(), timeouts.DefaultDockerAPI))
defer usageCancel()
if usageVolumes, ok := dockerutil.GetVolumeUsageDataStaleWhileRevalidate(usageCtx, dockerClient).Get(); ok {
for _, uv := range usageVolumes {
@@ -176,7 +188,22 @@ func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeC
defer s.eventService.BeginDockerResourceSuppressionWindow("volume", created.Volume.Name, created.Volume.Name)()
vol, err := dockerClient.VolumeInspect(ctx, created.Volume.Name, client.VolumeInspectOptions{})
if err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", created.Volume.Name, created.Volume.Name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver, "step": "inspect"})
+ s.eventService.LogErrorEvent(
+ ctx,
+ event.EventTypeVolumeError,
+ "volume",
+ created.Volume.Name,
+ created.Volume.Name,
+ user.ID,
+ user.Username,
+ "0",
+ err,
+ database.JSON{
+ "action": "create",
+ "driver": options.Driver,
+ "step": "inspect",
+ },
+ )
return nil, fmt.Errorf("failed to inspect created volume: %w", err)
}
@@ -209,11 +236,11 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force boo
}
defer s.eventService.BeginDockerResourceSuppressionWindow("volume", name, name)()
- if _, err := dockerClient.VolumeRemove(ctx, name, client.VolumeRemoveOptions{
+ if _, volumeRemoveErr := dockerClient.VolumeRemove(ctx, name, client.VolumeRemoveOptions{
Force: force,
- }); err != nil {
- s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})
- return fmt.Errorf("failed to remove volume: %w", err)
+ }); volumeRemoveErr != nil {
+ s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", volumeRemoveErr, database.JSON{"action": "delete", "force": force})
+ return fmt.Errorf("failed to remove volume: %w", volumeRemoveErr)
}
metadata := database.JSON{
diff --git a/backend/internal/volume/service_test.go b/backend/internal/volume/service_test.go
index 61b39f696..a3b4302b7 100644
--- a/backend/internal/volume/service_test.go
+++ b/backend/internal/volume/service_test.go
@@ -18,6 +18,7 @@ import (
"github.com/moby/moby/api/types/mount"
"github.com/moby/moby/api/types/volume"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.getarcane.app/sys/crypto"
"gorm.io/gorm"
@@ -83,10 +84,10 @@ func TestValidateVolumeHelperSupportInternalOnlyInspectsVolume(t *testing.T) {
}))
t.Cleanup(server.Close)
- dockerService := docker.NewDockerClientService(context.Background(), nil, nil, nil).WithClient(newVolumeServiceTestDockerClientInternal(t, server))
+ dockerService := docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newVolumeServiceTestDockerClientInternal(t, server))
service := &VolumeService{dockerService: dockerService}
- require.NoError(t, service.validateVolumeHelperSupportInternal(context.Background(), "workspace-volume"))
+ require.NoError(t, service.validateVolumeHelperSupportInternal(t.Context(), "workspace-volume"))
require.Equal(t, []string{"GET /v1.41/volumes/workspace-volume"}, requests)
}
@@ -134,13 +135,13 @@ func TestCreateTempContainerInternalReusesWritableHelper(t *testing.T) {
t.Cleanup(server.Close)
service := &VolumeService{
- dockerService: docker.NewDockerClientService(context.Background(), nil, nil, nil).WithClient(newVolumeServiceTestDockerClientInternal(t, server)),
+ dockerService: docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newVolumeServiceTestDockerClientInternal(t, server)),
helperByVolume: make(map[string]*volumeHelper),
}
- firstID, releaseFirst, err := service.acquireVolumeHelperInternal(context.Background(), "workspace-volume")
+ firstID, releaseFirst, err := service.acquireVolumeHelperInternal(t.Context(), "workspace-volume")
require.NoError(t, err)
- secondID, releaseSecond, err := service.acquireVolumeHelperInternal(context.Background(), "workspace-volume")
+ secondID, releaseSecond, err := service.acquireVolumeHelperInternal(t.Context(), "workspace-volume")
require.NoError(t, err)
require.Equal(t, "helper-1", firstID)
@@ -467,7 +468,7 @@ func TestResolveBackupStorageMountFromMountsInternal(t *testing.T) {
func TestResolveBackupStorageMountInternalFallsBackToNamedVolume(t *testing.T) {
svc := &VolumeService{backupVolumeName: "arcane-backups"}
- got := svc.resolveBackupStorageMountInternal(context.Background(), nil, "/backups", true)
+ got := svc.resolveBackupStorageMountInternal(t.Context(), nil, "/backups", true)
require.Equal(t, backupStorageModeNamedVolumeFallback, got.mode)
require.Equal(t, mount.TypeVolume, got.mount.Type)
require.Equal(t, "arcane-backups", got.mount.Source)
@@ -649,9 +650,9 @@ func TestVolumeBackupPolicy_UpdateRegistersIndependentJobsAndSettings(t *testing
scheduler := &volumeBackupPolicySchedulerInternal{jobs: make(map[string]schedulertypes.Job)}
service := &VolumeService{db: db, jobs: entityjobs.New("volume-backup:", backup.VolumeAdmissionScope)}
gate := newVolumeAdmissionForTestInternal(t)
- require.NoError(t, service.SetScheduler(context.Background(), scheduler, gate))
+ require.NoError(t, service.SetScheduler(t.Context(), scheduler, gate))
- collection, err := service.UpdateBackupPolicies(context.Background(), "app-data", []volumetypes.UpdateBackupPolicy{
+ collection, err := service.UpdateBackupPolicies(t.Context(), "app-data", []volumetypes.UpdateBackupPolicy{
{Enabled: true, Schedule: "0 */15 * * * *", RetentionCount: 5, StopContainers: true, LocalEnabled: true},
{Enabled: true, Schedule: "0 0 2 * * *", RetentionCount: 30, LocalEnabled: true},
})
@@ -663,7 +664,7 @@ func TestVolumeBackupPolicy_UpdateRegistersIndependentJobsAndSettings(t *testing
require.Len(t, scheduler.jobs, 2)
firstID := collection.Policies[0].ID
- collection, err = service.UpdateBackupPolicies(context.Background(), "app-data", []volumetypes.UpdateBackupPolicy{{
+ collection, err = service.UpdateBackupPolicies(t.Context(), "app-data", []volumetypes.UpdateBackupPolicy{{
ID: firstID, Schedule: "0 */30 * * * *", RetentionCount: 9, LocalEnabled: true,
}})
require.NoError(t, err)
@@ -685,7 +686,7 @@ func TestVolumeBackupPolicy_GetReturnsLastRunForEachPolicy(t *testing.T) {
require.NoError(t, gormDB.Create(&VolumeBackup{VolumeName: "app-data", PolicyID: second.ID, Status: VolumeBackupStatusFailed}).Error)
service := &VolumeService{db: &database.DB{DB: gormDB}}
- collection, err := service.GetBackupPolicies(context.Background(), "app-data")
+ collection, err := service.GetBackupPolicies(t.Context(), "app-data")
require.NoError(t, err)
require.Len(t, collection.Policies, 2)
require.Equal(t, "succeeded", collection.Policies[0].LastRun.Status)
@@ -708,7 +709,7 @@ func TestVolumeBackupPolicy_RetentionIgnoresFailedRuns(t *testing.T) {
}).Error)
service := &VolumeService{db: &database.DB{DB: gormDB}}
- require.NoError(t, service.applyVolumeBackupRetentionInternal(context.Background(), policyID, 1, true))
+ require.NoError(t, service.applyVolumeBackupRetentionInternal(t.Context(), policyID, 1, true))
var backups []VolumeBackup
require.NoError(t, gormDB.Order("created_at ASC").Find(&backups).Error)
@@ -722,7 +723,7 @@ func TestVolumeBackup_ValidationErrors(t *testing.T) {
require.NoError(t, err)
require.NoError(t, gormDB.AutoMigrate(&VolumeBackupPolicy{}))
service := &VolumeService{db: &database.DB{DB: gormDB}}
- ctx := context.Background()
+ ctx := t.Context()
_, err = service.UpdateBackupPolicies(ctx, "app-data", []volumetypes.UpdateBackupPolicy{{Schedule: "not a cron", LocalEnabled: true}})
require.ErrorContains(t, err, "invalid volume backup schedule")
@@ -759,18 +760,20 @@ func TestVolumeBackupPolicy_ScheduledRunCreatesActivity(t *testing.T) {
}
// Holding the volume's admission lease makes the scheduled run fail with
// "already running", which still must record a failed activity.
- lease, admitted, err := engine.TryAcquireRun(context.Background(), backup.VolumeAdmissionScope, policy.VolumeName)
+ lease, admitted, err := engine.TryAcquireRun(t.Context(), backup.VolumeAdmissionScope, policy.VolumeName)
require.NoError(t, err)
require.True(t, admitted)
defer lease.Release(t.Context())
- service.runScheduledBackupInternal(context.Background(), policy.ID)
+ outcome, scheduledBackupErr := service.runScheduledBackupInternal(t.Context(), policy.ID)
+ require.NoError(t, scheduledBackupErr)
+ require.Equal(t, schedulertypes.Skipped, outcome.Status)
- var activity activity.Activity
- require.NoError(t, gormDB.Where("resource_type = ?", "volume_backup").First(&activity).Error)
- require.Equal(t, activitytypes.StatusFailed, activity.Status)
- require.Equal(t, "scheduled_volume_backup", activity.Metadata["action"])
- require.Equal(t, policy.Schedule, activity.Metadata["schedule"])
+ var backupActivity activity.Activity
+ require.NoError(t, gormDB.Where("resource_type = ?", "volume_backup").First(&backupActivity).Error)
+ require.Equal(t, activitytypes.StatusFailed, backupActivity.Status)
+ require.Equal(t, "scheduled_volume_backup", backupActivity.Metadata["action"])
+ require.Equal(t, policy.Schedule, backupActivity.Metadata["schedule"])
}
func TestVolumeBackupPolicy_UpdateUsesSelectedS3Destination(t *testing.T) {
@@ -798,7 +801,7 @@ func TestVolumeBackupPolicy_UpdateUsesSelectedS3Destination(t *testing.T) {
s3Destinations: s3domain.NewS3DestinationService(db, nil),
jobs: entityjobs.New("volume-backup:", backup.VolumeAdmissionScope),
}
- collection, err := service.UpdateBackupPolicies(context.Background(), "app-data", []volumetypes.UpdateBackupPolicy{{
+ collection, err := service.UpdateBackupPolicies(t.Context(), "app-data", []volumetypes.UpdateBackupPolicy{{
Schedule: "0 0 2 * * *",
RetentionCount: 7,
S3Enabled: true,
@@ -843,7 +846,7 @@ func TestVolumeBackup_ListResolvesDestinationName(t *testing.T) {
}).Error)
service := &VolumeService{db: db, s3Destinations: s3domain.NewS3DestinationService(db, nil)}
- backups, _, err := service.ListBackupsPaginated(context.Background(), "app-data", pagination.QueryParams{})
+ backups, _, err := service.ListBackupsPaginated(t.Context(), "app-data", pagination.QueryParams{})
require.NoError(t, err)
require.Len(t, backups, 1)
require.Equal(t, volumetypes.BackupDestinationLocalS3, backups[0].Destination)
@@ -876,7 +879,7 @@ func TestVolumeBackupContainerLifecycleStopsAndRestartsOnlyRunningContainersUsin
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{ID: "uses-volume", Mounts: []container.MountPoint{{Type: mount.TypeVolume, Name: "app-data"}}},
{ID: "other-volume", Mounts: []container.MountPoint{{Type: mount.TypeVolume, Name: "other-data"}}},
{ID: "arcane", Labels: map[string]string{"com.getarcaneapp.arcane": "true"}, Mounts: []container.MountPoint{{Type: mount.TypeVolume, Name: "app-data"}}},
@@ -898,12 +901,12 @@ func TestVolumeBackupContainerLifecycleStopsAndRestartsOnlyRunningContainersUsin
service, dockerClient := setupVolumeBackupLifecycleTestInternal(t, serverHandler)
actor := common.User{ID: "user-1", Username: "tester"}
- stopped, err := service.stopRunningContainersForBackupInternal(context.Background(), dockerClient, "app-data", actor, false)
+ stopped, err := service.stopRunningContainersForBackupInternal(t.Context(), dockerClient, "app-data", actor, false)
require.NoError(t, err)
require.Len(t, stopped, 1)
require.Equal(t, "uses-volume", stopped[0].ID)
- remaining, err := service.startContainersAfterBackupInternal(context.Background(), dockerClient, stopped, actor)
+ remaining, err := service.startContainersAfterBackupInternal(t.Context(), dockerClient, stopped, actor)
require.NoError(t, err)
require.Empty(t, remaining)
require.Equal(t, []string{"stop:uses-volume", "start:uses-volume"}, operations)
@@ -916,7 +919,7 @@ func TestVolumeBackupContainerLifecycleRollsBackStoppedContainersOnStopFailure(t
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/containers/json"):
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{ID: "first", Mounts: []container.MountPoint{{Type: mount.TypeVolume, Name: "app-data"}}},
{ID: "second", Mounts: []container.MountPoint{{Type: mount.TypeVolume, Name: "app-data"}}},
}))
@@ -942,7 +945,7 @@ func TestVolumeBackupContainerLifecycleRollsBackStoppedContainersOnStopFailure(t
service, dockerClient := setupVolumeBackupLifecycleTestInternal(t, serverHandler)
actor := common.User{ID: "user-1", Username: "tester"}
- stillStopped, err := service.stopRunningContainersForBackupInternal(context.Background(), dockerClient, "app-data", actor, false)
+ stillStopped, err := service.stopRunningContainersForBackupInternal(t.Context(), dockerClient, "app-data", actor, false)
require.ErrorContains(t, err, "failed to stop container second")
require.Empty(t, stillStopped)
require.Equal(t, []string{"stop:first", "stop:second", "start:first"}, operations)
@@ -961,7 +964,7 @@ func TestVolumeBackupContainerLifecycleWaitsForRunningComposeReplacement(t *test
call := listCalls
mu.Unlock()
if call == 1 {
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{
ID: "old-id",
Names: []string{"/old-name"},
@@ -973,10 +976,10 @@ func TestVolumeBackupContainerLifecycleWaitsForRunningComposeReplacement(t *test
return
}
if call == 2 {
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
return
}
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
+ assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{
{
ID: "new-id",
Names: []string{"/new-name"},
@@ -1002,12 +1005,12 @@ func TestVolumeBackupContainerLifecycleWaitsForRunningComposeReplacement(t *test
service, dockerClient := setupVolumeBackupLifecycleTestInternal(t, serverHandler)
actor := common.User{ID: "user-1", Username: "tester"}
- stopped, err := service.stopRunningContainersForBackupInternal(context.Background(), dockerClient, "app-data", actor, false)
+ stopped, err := service.stopRunningContainersForBackupInternal(t.Context(), dockerClient, "app-data", actor, false)
require.NoError(t, err)
require.Len(t, stopped, 1)
require.Equal(t, "old-id", stopped[0].ID)
- remaining, err := service.startContainersAfterBackupInternal(context.Background(), dockerClient, stopped, actor)
+ remaining, err := service.startContainersAfterBackupInternal(t.Context(), dockerClient, stopped, actor)
require.NoError(t, err)
require.Empty(t, remaining)
require.Equal(t, []string{"stop:old-id"}, operations)
@@ -1024,8 +1027,8 @@ func TestBackupPolicyDestinationLookupFailureInternal(t *testing.T) {
if drop {
require.NoError(t, db.Migrator().DropTable(&s3domain.S3Destination{}))
}
- collection, err := service.GetBackupPolicies(t.Context(), "app-data")
- require.NoError(t, err)
+ collection, getBackupPoliciesErr := service.GetBackupPolicies(t.Context(), "app-data")
+ require.NoError(t, getBackupPoliciesErr)
require.Len(t, collection.Policies, 1)
require.False(t, collection.S3Available)
require.Empty(t, collection.Policies[0].S3DestinationName)
diff --git a/backend/internal/volume/workspace.go b/backend/internal/volume/workspace.go
index cc161760f..63c3dd202 100644
--- a/backend/internal/volume/workspace.go
+++ b/backend/internal/volume/workspace.go
@@ -61,8 +61,8 @@ func (s *VolumeService) GetVolumeWorkspace(ctx context.Context, volumeName strin
return nil, err
}
defer cleanup()
- if err := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); err != nil {
- return nil, err
+ if requireVolumeHelperACFSErr := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); requireVolumeHelperACFSErr != nil {
+ return nil, requireVolumeHelperACFSErr
}
slog.DebugContext(ctx, "volume workspace helper acquired", "volume", volumeName, "container_id", containerID, "duration", time.Since(helperStartedAt))
@@ -71,7 +71,22 @@ func (s *VolumeService) GetVolumeWorkspace(ctx context.Context, volumeName strin
if err != nil {
return nil, err
}
- slog.DebugContext(ctx, "volume workspace tree scan completed", "volume", volumeName, "file_count", len(workspace.Files), "truncated", workspace.FileTreeTruncated, "duration", time.Since(scanStartedAt))
+ slog.DebugContext(
+ ctx,
+ "volume workspace tree scan completed",
+ "volume",
+ volumeName,
+ "file_count",
+ len(
+ workspace.Files,
+ ),
+ "truncated",
+ workspace.FileTreeTruncated,
+ "duration",
+ time.Since(
+ scanStartedAt,
+ ),
+ )
return workspace, nil
}
@@ -241,8 +256,8 @@ func (s *VolumeService) GetVolumeWorkspaceFile(ctx context.Context, volumeName,
return nil, err
}
defer cleanup()
- if err := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); err != nil {
- return nil, err
+ if requireVolumeHelperACFSErr := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); requireVolumeHelperACFSErr != nil {
+ return nil, requireVolumeHelperACFSErr
}
stdout, stderr, err := s.execInContainerInternal(ctx, containerID, "", []string{
"acfs", "stat", "--root", "/volume", "--path", "/" + rel,
@@ -251,8 +266,8 @@ func (s *VolumeService) GetVolumeWorkspaceFile(ctx context.Context, volumeName,
return nil, classifyVolumeWorkspaceExecErrorInternal(err, stderr, "inspect volume workspace file")
}
var statResponse acfstypes.StatResponse
- if err := json.Unmarshal([]byte(stdout), &statResponse); err != nil {
- return nil, fmt.Errorf("parse volume workspace stat: %w", err)
+ if unmarshalErr := json.Unmarshal([]byte(stdout), &statResponse); unmarshalErr != nil {
+ return nil, fmt.Errorf("parse volume workspace stat: %w", unmarshalErr)
}
if statResponse.Version != acfstypes.ProtocolVersion {
return nil, fmt.Errorf("unsupported acfs protocol %d", statResponse.Version)
@@ -314,9 +329,9 @@ func (s *VolumeService) DownloadVolumeWorkspaceFile(ctx context.Context, volumeN
cleanup()
unlock()
}
- if err := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); err != nil {
+ if requireVolumeHelperACFSErr := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); requireVolumeHelperACFSErr != nil {
cleanupAndUnlock()
- return nil, 0, err
+ return nil, 0, requireVolumeHelperACFSErr
}
return s.startVolumeWorkspaceReadInternal(ctx, containerID, rel, 0, cleanupAndUnlock)
}
@@ -603,7 +618,18 @@ tar -cf "$archive" "./$entry"
printf 'present\0'`
)
-func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName string, manifest volumetypes.WorkspaceUpdateManifest, uploads map[int][]byte, user common.User) (*workspacetypes.Workspace, error) {
+func (
+ s *VolumeService,
+) UpdateVolumeWorkspace(
+ ctx context.Context,
+ volumeName string,
+ manifest volumetypes.WorkspaceUpdateManifest,
+ uploads map[int][]byte,
+ user common.User,
+) (
+ *workspacetypes.Workspace,
+ error,
+) {
totalStartedAt := time.Now()
defer func() {
slog.DebugContext(ctx, "volume workspace update completed", "volume", volumeName, "file_change_count", len(manifest.FileChanges), "total_duration", time.Since(totalStartedAt))
@@ -638,8 +664,8 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName st
return nil, err
}
defer cleanup()
- if err := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); err != nil {
- return nil, err
+ if requireVolumeHelperACFSErr := s.requireVolumeHelperACFSInternal(ctx, volumeName, containerID); requireVolumeHelperACFSErr != nil {
+ return nil, requireVolumeHelperACFSErr
}
slog.DebugContext(ctx, "volume workspace mutation helper acquired", "volume", volumeName, "container_id", containerID, "dedicated", needsBackups, "duration", time.Since(helperStartedAt))
@@ -648,9 +674,24 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName st
if err != nil {
return nil, err
}
- slog.DebugContext(ctx, "volume workspace revision tree scan completed", "volume", volumeName, "file_count", len(current.Files), "truncated", current.FileTreeTruncated, "duration", time.Since(revisionScanStartedAt))
- if err := validateVolumeWorkspaceRevisionInternal(manifest.FileTreeRevision, current.FileTreeRevision); err != nil {
- return nil, err
+ slog.DebugContext(
+ ctx,
+ "volume workspace revision tree scan completed",
+ "volume",
+ volumeName,
+ "file_count",
+ len(
+ current.Files,
+ ),
+ "truncated",
+ current.FileTreeTruncated,
+ "duration",
+ time.Since(
+ revisionScanStartedAt,
+ ),
+ )
+ if validateVolumeWorkspaceRevisionErr := validateVolumeWorkspaceRevisionInternal(manifest.FileTreeRevision, current.FileTreeRevision); validateVolumeWorkspaceRevisionErr != nil {
+ return nil, validateVolumeWorkspaceRevisionErr
}
stagingStartedAt := time.Now()
@@ -671,8 +712,8 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName st
return nil, common.Classify(common.ErrVolumeWorkspaceBadRequest, err)
}
for _, relativePath := range scope {
- if err := s.validateVolumeWorkspacePathInternal(ctx, containerID, relativePath, true); err != nil {
- return nil, err
+ if validateVolumeWorkspacePathErr := s.validateVolumeWorkspacePathInternal(ctx, containerID, relativePath, true); validateVolumeWorkspacePathErr != nil {
+ return nil, validateVolumeWorkspacePathErr
}
}
backup, err := s.backupVolumeWorkspaceScopeInternal(ctx, containerID, scope)
@@ -682,7 +723,7 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName st
slog.DebugContext(ctx, "volume workspace backup completed", "volume", volumeName, "scope_count", len(scope), "duration", time.Since(backupStartedAt))
applyStartedAt := time.Now()
- if err := s.applyVolumeWorkspaceChangesInternal(
+ if applyVolumeWorkspaceChangesErr := s.applyVolumeWorkspaceChangesInternal(
ctx,
dockerClient,
containerID,
@@ -691,8 +732,8 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName st
stagedFiles,
identity,
func() error { return s.restoreVolumeWorkspaceScopeInternal(ctx, containerID, backup) },
- ); err != nil {
- return nil, err
+ ); applyVolumeWorkspaceChangesErr != nil {
+ return nil, applyVolumeWorkspaceChangesErr
}
slog.DebugContext(ctx, "volume workspace changes applied", "volume", volumeName, "file_change_count", len(manifest.FileChanges), "duration", time.Since(applyStartedAt))
@@ -701,7 +742,22 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName st
if err != nil {
return nil, err
}
- slog.DebugContext(ctx, "volume workspace final tree scan completed", "volume", volumeName, "file_count", len(workspace.Files), "truncated", workspace.FileTreeTruncated, "duration", time.Since(finalScanStartedAt))
+ slog.DebugContext(
+ ctx,
+ "volume workspace final tree scan completed",
+ "volume",
+ volumeName,
+ "file_count",
+ len(
+ workspace.Files,
+ ),
+ "truncated",
+ workspace.FileTreeTruncated,
+ "duration",
+ time.Since(
+ finalScanStartedAt,
+ ),
+ )
if s.eventService != nil {
metadata := database.JSON{"action": "workspace_update", "fileChangeCount": len(manifest.FileChanges)}
@@ -768,7 +824,16 @@ func (s *VolumeService) resolveVolumeWorkspaceWriteIdentityInternal(ctx context.
// Consumers disagree; picking either would depend on Docker's list order, so defer to
// the volume root's owner instead.
if identity.execUser != parsed.execUser {
- slog.WarnContext(ctx, "volume consumers declare conflicting users; using volume root owner for workspace writes", "volume", volumeName, "identity", identity.execUser, "conflicting_identity", parsed.execUser)
+ slog.WarnContext(
+ ctx,
+ "volume consumers declare conflicting users; using volume root owner for workspace writes",
+ "volume",
+ volumeName,
+ "identity",
+ identity.execUser,
+ "conflicting_identity",
+ parsed.execUser,
+ )
identity = volumeWorkspaceWriteIdentityInternal{}
break
}
@@ -801,7 +866,19 @@ type volumeWorkspaceStagedContentInternal struct {
size int64
}
-func (s *VolumeService) stageVolumeWorkspaceChangesInternal(ctx context.Context, dockerClient *client.Client, containerID string, changes []volumetypes.WorkspaceFileChange, uploads map[int][]byte, identity volumeWorkspaceWriteIdentityInternal) (map[int]volumeWorkspaceStagedFileInternal, error) {
+func (
+ s *VolumeService,
+) stageVolumeWorkspaceChangesInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerID string,
+ changes []volumetypes.WorkspaceFileChange,
+ uploads map[int][]byte,
+ identity volumeWorkspaceWriteIdentityInternal,
+) (
+ map[int]volumeWorkspaceStagedFileInternal,
+ error,
+) {
if _, _, err := s.execInContainerInternal(ctx, containerID, "", []string{"sh", "-c", "rm -rf -- /tmp/arcane-workspace && mkdir -p -- /tmp/arcane-workspace"}); err != nil {
return nil, fmt.Errorf("prepare volume workspace staging directory: %w", err)
}
@@ -904,12 +981,12 @@ func (s *VolumeService) executeVolumeWorkspaceACFSBatchInternal(
return fmt.Errorf("encode volume workspace apply manifest: %w", err)
}
manifestName := fmt.Sprintf("manifest-%d.json", startIndex)
- if err := s.copyVolumeWorkspaceFilesToContainerInternal(ctx, dockerClient, containerID, []volumeWorkspaceStagedContentInternal{{
+ if copyVolumeWorkspaceFilesToContainerErr := s.copyVolumeWorkspaceFilesToContainerInternal(ctx, dockerClient, containerID, []volumeWorkspaceStagedContentInternal{{
name: manifestName,
content: io.NopCloser(bytes.NewReader(manifestContent)),
size: int64(len(manifestContent)),
- }}, identity); err != nil {
- return err
+ }}, identity); copyVolumeWorkspaceFilesToContainerErr != nil {
+ return copyVolumeWorkspaceFilesToContainerErr
}
stdout, stderr, err := s.execInContainerInternal(ctx, containerID, identity.execUser, []string{
@@ -919,8 +996,8 @@ func (s *VolumeService) executeVolumeWorkspaceACFSBatchInternal(
return classifyVolumeWorkspaceExecErrorInternal(err, stderr, "apply volume workspace changes")
}
var response acfstypes.ApplyResponse
- if err := json.Unmarshal([]byte(stdout), &response); err != nil {
- return fmt.Errorf("parse volume workspace apply response: %w", err)
+ if unmarshalErr := json.Unmarshal([]byte(stdout), &response); unmarshalErr != nil {
+ return fmt.Errorf("parse volume workspace apply response: %w", unmarshalErr)
}
if response.Version != acfstypes.ProtocolVersion || response.Applied != len(applyChanges) {
return errors.New("invalid volume workspace apply response")
@@ -1016,7 +1093,15 @@ func validateVolumeWorkspaceFileChangeInternal(change volumetypes.WorkspaceFileC
return nil
}
-func (s *VolumeService) copyVolumeWorkspaceFilesToContainerInternal(ctx context.Context, dockerClient *client.Client, containerID string, contents []volumeWorkspaceStagedContentInternal, identity volumeWorkspaceWriteIdentityInternal) error {
+func (
+ s *VolumeService,
+) copyVolumeWorkspaceFilesToContainerInternal(
+ ctx context.Context,
+ dockerClient *client.Client,
+ containerID string,
+ contents []volumeWorkspaceStagedContentInternal,
+ identity volumeWorkspaceWriteIdentityInternal,
+) error {
pipeReader, pipeWriter := io.Pipe()
archiveDone := make(chan error, 1)
go func() {
@@ -1073,8 +1158,8 @@ func (s *VolumeService) createVolumeWorkspaceMutationContainerInternal(ctx conte
if err != nil {
return "", nil, fmt.Errorf("create volume workspace helper: %w", err)
}
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
- startErr := fmt.Errorf("start volume workspace helper: %w", err)
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
+ startErr := fmt.Errorf("start volume workspace helper: %w", containerStartErr)
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), timeouts.DefaultDockerAPI)
defer cancel()
if _, cleanupErr := dockerClient.ContainerRemove(cleanupCtx, resp.ID, volumehelper.RemoveOptions()); cleanupErr != nil && !cerrdefs.IsNotFound(cleanupErr) {
@@ -1097,9 +1182,9 @@ func volumeWorkspaceBackupScopeInternal(changes []volumetypes.WorkspaceFileChang
paths = append(paths, rel)
switch change.Operation {
case volumetypes.FileOpRename:
- newName, err := kit.ValidateFileName(change.NewName)
- if err != nil {
- return nil, err
+ newName, validateFileNameErr := kit.ValidateFileName(change.NewName)
+ if validateFileNameErr != nil {
+ return nil, validateFileNameErr
}
paths = append(paths, path.Join(path.Dir(rel), newName))
case volumetypes.FileOpMove:
@@ -1223,8 +1308,8 @@ func (s *VolumeService) restoreVolumeWorkspaceFileInternal(ctx context.Context,
return common.Classify(common.ErrVolumeWorkspaceNotFound, err)
}
var backup VolumeBackup
- if err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {
- return common.Classify(common.ErrVolumeWorkspaceNotFound, err)
+ if loadBackupErr := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; loadBackupErr != nil {
+ return common.Classify(common.ErrVolumeWorkspaceNotFound, loadBackupErr)
}
if backup.VolumeName != volumeName {
return common.Classify(common.ErrVolumeWorkspaceForbidden, errors.New("backup does not belong to volume"))
diff --git a/backend/internal/volume/workspace_handler.go b/backend/internal/volume/workspace_handler.go
index 30c81db2f..3c5a6af0c 100644
--- a/backend/internal/volume/workspace_handler.go
+++ b/backend/internal/volume/workspace_handler.go
@@ -46,8 +46,32 @@ func registerVolumeWorkspaceRoutesInternal(api huma.API, h *VolumeHandler) {
basePath := "/environments/{id}/volumes/{volumeName}/workspace"
tag := "Volume Workspace"
handlerutil.RegisterSecured(api, handlerutil.Operation("get-volume-workspace", http.MethodGet, basePath, "Get volume workspace", "", tag), authz.PermVolumesRead, h.GetVolumeWorkspace)
- handlerutil.RegisterSecured(api, handlerutil.Operation("get-volume-workspace-file", http.MethodGet, basePath+"/file", "Get volume workspace file", "", tag), authz.PermVolumesRead, h.GetVolumeWorkspaceFile)
- handlerutil.RegisterSecured(api, handlerutil.Operation("download-volume-workspace-file", http.MethodGet, basePath+"/file/download", "Download volume workspace file", "", tag), authz.PermVolumesRead, h.DownloadVolumeWorkspaceFile)
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "get-volume-workspace-file",
+ http.MethodGet,
+ basePath+"/file",
+ "Get volume workspace file",
+ "",
+ tag,
+ ),
+ authz.PermVolumesRead,
+ h.GetVolumeWorkspaceFile,
+ )
+ handlerutil.RegisterSecured(
+ api,
+ handlerutil.Operation(
+ "download-volume-workspace-file",
+ http.MethodGet,
+ basePath+"/file/download",
+ "Download volume workspace file",
+ "",
+ tag,
+ ),
+ authz.PermVolumesRead,
+ h.DownloadVolumeWorkspaceFile,
+ )
updateOperation := handlerutil.Operation("update-volume-workspace", http.MethodPut, basePath, "Update volume workspace", "", tag)
updateOperation.RequestBody = handlerutil.WorkspaceMultipartRequestBody("JSON encoded volume workspace manifest")
handlerutil.RegisterSecured(api, updateOperation, authz.PermVolumesRead, h.UpdateVolumeWorkspace)
@@ -111,8 +135,8 @@ func (h *VolumeHandler) UpdateVolumeWorkspace(ctx context.Context, input *Update
if err != nil {
return nil, err
}
- if err := requireVolumeWorkspacePermissionsInternal(ctx, input.EnvironmentID, manifest.FileChanges); err != nil {
- return nil, err
+ if requireVolumeWorkspacePermissionsErr := requireVolumeWorkspacePermissionsInternal(ctx, input.EnvironmentID, manifest.FileChanges); requireVolumeWorkspacePermissionsErr != nil {
+ return nil, requireVolumeWorkspacePermissionsErr
}
maxFileSizeBytes := workspacepkg.MaxFileSizeBytes(workspacepkg.DefaultMaxFileSizeMB)
if h.volumeService != nil && h.volumeService.workspaceMaxFileSizeBytes > 0 {
diff --git a/backend/internal/volume/workspace_handler_test.go b/backend/internal/volume/workspace_handler_test.go
index 488ecaa1f..2fda6c095 100644
--- a/backend/internal/volume/workspace_handler_test.go
+++ b/backend/internal/volume/workspace_handler_test.go
@@ -19,16 +19,16 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"
)
-func volumeWorkspacePermissionContextInternal(environmentID string, permissions ...string) context.Context {
+func volumeWorkspacePermissionContextInternal(t *testing.T, environmentID string, permissions ...string) context.Context {
permissionSet := authz.NewPermissionSet()
permissionSet.AddEnv(environmentID, permissions...)
- return context.WithValue(context.Background(), middleware.ContextKeyUserPermissions, permissionSet)
+ return context.WithValue(t.Context(), middleware.ContextKeyUserPermissions, permissionSet)
}
func TestUploadAndRestoreReturnsNotFoundForUnknownSession(t *testing.T) {
h := &VolumeHandler{volumeService: &VolumeService{}, uploadService: upload.NewUploadService(nil)}
- ctx := context.WithValue(context.Background(), common.CurrentUserContextKey{}, &common.User{ID: "u-1"})
+ ctx := context.WithValue(t.Context(), common.CurrentUserContextKey{}, &common.User{ID: "u-1"})
_, err := h.UploadAndRestore(ctx, &UploadAndRestoreInput{
EnvironmentID: "0",
@@ -66,23 +66,23 @@ func TestRequireVolumeWorkspacePermissionsInternal(t *testing.T) {
remove := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpDelete}}
restore := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpRestoreFile}}
- require.Error(t, requireVolumeWorkspacePermissionsInternal(context.Background(), environmentID, create))
+ require.Error(t, requireVolumeWorkspacePermissionsInternal(t.Context(), environmentID, create))
require.NoError(t, requireVolumeWorkspacePermissionsInternal(
- volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesUpload), environmentID, create,
+ volumeWorkspacePermissionContextInternal(t, environmentID, authz.PermVolumesUpload), environmentID, create,
))
require.Error(t, requireVolumeWorkspacePermissionsInternal(
- volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesUpload), environmentID, rename,
+ volumeWorkspacePermissionContextInternal(t, environmentID, authz.PermVolumesUpload), environmentID, rename,
))
require.NoError(t, requireVolumeWorkspacePermissionsInternal(
- volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesUpload, authz.PermVolumesDelete), environmentID, rename,
+ volumeWorkspacePermissionContextInternal(t, environmentID, authz.PermVolumesUpload, authz.PermVolumesDelete), environmentID, rename,
))
require.NoError(t, requireVolumeWorkspacePermissionsInternal(
- volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesDelete), environmentID, remove,
+ volumeWorkspacePermissionContextInternal(t, environmentID, authz.PermVolumesDelete), environmentID, remove,
))
require.NoError(t, requireVolumeWorkspacePermissionsInternal(
- volumeWorkspacePermissionContextInternal(environmentID, authz.PermVolumesBackup), environmentID, restore,
+ volumeWorkspacePermissionContextInternal(t, environmentID, authz.PermVolumesBackup), environmentID, restore,
))
require.Error(t, requireVolumeWorkspacePermissionsInternal(
- volumeWorkspacePermissionContextInternal("env-2", authz.PermVolumesUpload), environmentID, create,
+ volumeWorkspacePermissionContextInternal(t, "env-2", authz.PermVolumesUpload), environmentID, create,
))
}
diff --git a/backend/internal/volume/workspace_test.go b/backend/internal/volume/workspace_test.go
index a1e741634..7b5679775 100644
--- a/backend/internal/volume/workspace_test.go
+++ b/backend/internal/volume/workspace_test.go
@@ -65,31 +65,31 @@ func writeDockerExecAttachResponseInternal(t *testing.T, w http.ResponseWriter,
return
}
defer func() { _ = connection.Close() }()
- if _, err := fmt.Fprint(buffer, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n"); err != nil {
- t.Errorf("write Docker exec response headers: %v", err)
+ if _, fprintErr := fmt.Fprint(buffer, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n"); fprintErr != nil {
+ t.Errorf("write Docker exec response headers: %v", fprintErr)
return
}
if stdout != "" {
header := make([]byte, 8)
header[0] = 1
binary.BigEndian.PutUint32(header[4:], uint32(len(stdout)))
- if _, err := buffer.Write(header); err != nil {
- t.Errorf("write Docker exec stream header: %v", err)
+ if _, writeErr := buffer.Write(header); writeErr != nil {
+ t.Errorf("write Docker exec stream header: %v", writeErr)
return
}
- if _, err := buffer.WriteString(stdout); err != nil {
- t.Errorf("write Docker exec stream: %v", err)
+ if _, writeStringErr := buffer.WriteString(stdout); writeStringErr != nil {
+ t.Errorf("write Docker exec stream: %v", writeStringErr)
return
}
}
- if err := buffer.Flush(); err != nil {
- t.Errorf("flush Docker exec response: %v", err)
+ if flushErr := buffer.Flush(); flushErr != nil {
+ t.Errorf("flush Docker exec response: %v", flushErr)
}
}
func TestUpdateVolumeWorkspaceValidationFailureReturnsNoWorkspace(t *testing.T) {
workspace, err := (&VolumeService{}).UpdateVolumeWorkspace(
- context.Background(),
+ t.Context(),
"volume",
volumetypes.WorkspaceUpdateManifest{},
nil,
@@ -133,7 +133,7 @@ func TestVolumeWorkspaceReadsWaitForMutationLock(t *testing.T) {
readDone := make(chan error, 1)
go func() {
close(readStarted)
- readDone <- read(context.Background(), service)
+ readDone <- read(t.Context(), service)
}()
<-readStarted
@@ -212,7 +212,7 @@ func TestDownloadVolumeWorkspaceFileHoldsReadLockUntilClosed(t *testing.T) {
"workspace-volume": {id: "helper", lastUsedAt: time.Now(), protocol: acfstypes.ProtocolVersion},
},
}
- reader, size, err := service.DownloadVolumeWorkspaceFile(context.Background(), "workspace-volume", "file.txt")
+ reader, size, err := service.DownloadVolumeWorkspaceFile(t.Context(), "workspace-volume", "file.txt")
require.NoError(t, err)
require.EqualValues(t, 7, size)
@@ -245,9 +245,9 @@ func TestVolumeWorkspaceFileContentResponseInternal(t *testing.T) {
require.False(t, above.Editable)
require.Equal(t, workspacetypes.FileReadOnlyTooLarge, above.ReadOnlyReason)
- binary, err := volumeWorkspaceFileContentResponseInternal("data.bin", "regular", 2, []byte{0xff, 0x00}, maxFileSizeBytes)
+ binaryContent, err := volumeWorkspaceFileContentResponseInternal("data.bin", "regular", 2, []byte{0xff, 0x00}, maxFileSizeBytes)
require.NoError(t, err)
- require.Equal(t, workspacetypes.FileReadOnlyBinary, binary.ReadOnlyReason)
+ require.Equal(t, workspacetypes.FileReadOnlyBinary, binaryContent.ReadOnlyReason)
special, err := volumeWorkspaceFileContentResponseInternal("pipe", "special", 0, nil, maxFileSizeBytes)
require.NoError(t, err)
@@ -437,7 +437,7 @@ func TestStageVolumeWorkspaceChangesClearsAndCopiesContentsInOneArchive(t *testi
service := &VolumeService{dockerService: docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(dockerClient)}
firstUpload := 0
secondUpload := 1
- firstStaged, err := service.stageVolumeWorkspaceChangesInternal(context.Background(), dockerClient, "helper", []volumetypes.WorkspaceFileChange{
+ firstStaged, err := service.stageVolumeWorkspaceChangesInternal(t.Context(), dockerClient, "helper", []volumetypes.WorkspaceFileChange{
{UploadIndex: &firstUpload},
{},
{UploadIndex: &secondUpload},
@@ -446,7 +446,22 @@ func TestStageVolumeWorkspaceChangesClearsAndCopiesContentsInOneArchive(t *testi
require.Equal(t, volumeWorkspaceStagedFileInternal{path: "/tmp/arcane-workspace/change-0", size: 5}, firstStaged[0])
require.Equal(t, volumeWorkspaceStagedFileInternal{path: "/tmp/arcane-workspace/change-2", size: 0}, firstStaged[2])
- secondStaged, err := service.stageVolumeWorkspaceChangesInternal(context.Background(), dockerClient, "helper", []volumetypes.WorkspaceFileChange{{UploadIndex: &firstUpload}}, map[int][]byte{0: []byte("second")}, volumeWorkspaceWriteIdentityInternal{})
+ secondStaged, err := service.stageVolumeWorkspaceChangesInternal(
+ t.Context(),
+ dockerClient,
+ "helper",
+ []volumetypes.WorkspaceFileChange{
+ {
+ UploadIndex: &firstUpload,
+ },
+ },
+ map[int][]byte{
+ 0: []byte(
+ "second",
+ ),
+ },
+ volumeWorkspaceWriteIdentityInternal{},
+ )
require.NoError(t, err)
require.Equal(t, volumeWorkspaceStagedFileInternal{path: "/tmp/arcane-workspace/change-0", size: 6}, secondStaged[0])
@@ -520,8 +535,8 @@ func TestVolumeWorkspaceWritesUseRuntimeIdentity(t *testing.T) {
return
}
archiveHeaders = append(archiveHeaders, header)
- if _, err := io.Copy(io.Discard, tarReader); err != nil {
- t.Errorf("read staging archive content: %v", err)
+ if _, copyErr := io.Copy(io.Discard, tarReader); copyErr != nil {
+ t.Errorf("read staging archive content: %v", copyErr)
return
}
}
@@ -537,9 +552,9 @@ func TestVolumeWorkspaceWritesUseRuntimeIdentity(t *testing.T) {
identity := volumeWorkspaceWriteIdentityFromConfigUserInternal("1000:1000")
uploadIndex := 0
changes := []volumetypes.WorkspaceFileChange{{Operation: volumetypes.FileOpCreateFile, RelativePath: "config.txt", UploadIndex: &uploadIndex}}
- stagedFiles, err := service.stageVolumeWorkspaceChangesInternal(context.Background(), dockerClient, "helper", changes, map[int][]byte{0: []byte("content")}, identity)
+ stagedFiles, err := service.stageVolumeWorkspaceChangesInternal(t.Context(), dockerClient, "helper", changes, map[int][]byte{0: []byte("content")}, identity)
require.NoError(t, err)
- require.NoError(t, service.executeVolumeWorkspaceACFSBatchInternal(context.Background(), dockerClient, "helper", changes, stagedFiles, 0, identity))
+ require.NoError(t, service.executeVolumeWorkspaceACFSBatchInternal(t.Context(), dockerClient, "helper", changes, stagedFiles, 0, identity))
require.Len(t, execRequests, 2)
require.Empty(t, execRequests[0].user)
@@ -606,7 +621,7 @@ func TestUpdateVolumeWorkspaceRejectsStaleRevisionBeforeStaging(t *testing.T) {
helperByVolume: make(map[string]*volumeHelper),
}
uploadIndex := 0
- workspace, err := service.UpdateVolumeWorkspace(context.Background(), "workspace-volume", volumetypes.WorkspaceUpdateManifest{
+ workspace, err := service.UpdateVolumeWorkspace(t.Context(), "workspace-volume", volumetypes.WorkspaceUpdateManifest{
FileTreeRevision: "stale",
FileChanges: []volumetypes.WorkspaceFileChange{{
Operation: volumetypes.FileOpCreateFile,
@@ -670,7 +685,7 @@ func TestCreateVolumeWorkspaceMutationContainerUsesDedicatedBackupHelper(t *test
},
}
- containerID, cleanup, err := service.createVolumeWorkspaceMutationContainerInternal(context.Background(), "workspace-volume", true)
+ containerID, cleanup, err := service.createVolumeWorkspaceMutationContainerInternal(t.Context(), "workspace-volume", true)
require.NoError(t, err)
require.Equal(t, "restore-helper", containerID)
require.Equal(t, 1, createCalls)
@@ -693,12 +708,12 @@ func TestVolumeWorkspaceScriptsAgainstToolsImage(t *testing.T) {
dockerPath, err := exec.LookPath("docker")
require.NoError(t, err)
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)
defer cancel()
runDocker := func(args ...string) string {
t.Helper()
- output, err := exec.CommandContext(ctx, dockerPath, args...).CombinedOutput()
- require.NoErrorf(t, err, "docker %s\n%s", strings.Join(args, " "), output)
+ output, combinedOutputErr := exec.CommandContext(ctx, dockerPath, args...).CombinedOutput()
+ require.NoErrorf(t, combinedOutputErr, "docker %s\n%s", strings.Join(args, " "), output)
return string(output)
}
runInVolume := func(volumeName, outerScript string, args ...string) string {
@@ -711,7 +726,7 @@ func TestVolumeWorkspaceScriptsAgainstToolsImage(t *testing.T) {
volumeName := "arcane-workspace-test-" + strconv.FormatInt(time.Now().UnixNano(), 10)
runDocker("volume", "create", volumeName)
t.Cleanup(func() {
- cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)
+ cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(t.Context()), 30*time.Second)
defer cleanupCancel()
_, _ = exec.CommandContext(cleanupCtx, dockerPath, "volume", "rm", volumeName).CombinedOutput()
})
@@ -734,7 +749,10 @@ acfs apply --root /volume --staging /tmp/staging --manifest manifest.json >/dev/
runInVolume(volumeName, `set -e
mkdir -p /tmp/staging
printf updated > /tmp/staging/change-0
-printf '%s' '{"changes":[{"operation":"update_file","path":"/nested/a.txt","stagedName":"change-0","size":7},{"operation":"rename","path":"/nested/a.txt","targetPath":"/nested/b.txt"},{"operation":"create_folder","path":"/dest"},{"operation":"move","path":"/nested/b.txt","targetPath":"/dest/b.txt"}],"version":2}' > /tmp/staging/manifest.json
+printf '%s' \
+ '{"changes":[{"operation":"update_file","path":"/nested/a.txt","stagedName":"change-0","size":7},{"op' \
+ 'eration":"rename","path":"/nested/a.txt","targetPath":"/nested/b.txt"},{"operation":"create_folder",' \
+ '"path":"/dest"},{"operation":"move","path":"/nested/b.txt","targetPath":"/dest/b.txt"}],"version":2}' > /tmp/staging/manifest.json
acfs apply --root /volume --staging /tmp/staging --manifest manifest.json >/dev/null`)
require.Equal(t, "updated", runInVolume(volumeName, `head -c 7 /volume/dest/b.txt`))
diff --git a/backend/internal/vulnerability/handler.go b/backend/internal/vulnerability/handler.go
index ca439d072..a497529ba 100644
--- a/backend/internal/vulnerability/handler.go
+++ b/backend/internal/vulnerability/handler.go
@@ -528,8 +528,8 @@ func (h *VulnerabilityHandler) ExportVulnerabilities(ctx context.Context, input
Body: func(humaCtx huma.Context) {
humaCtx.SetHeader("Content-Type", "text/csv; charset=utf-8")
humaCtx.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
- if err := WriteVulnerabilitiesCSV(humaCtx.BodyWriter(), items); err != nil {
- slog.ErrorContext(ctx, "failed to stream vulnerability export", "error", err)
+ if writeVulnerabilitiesCSVErr := WriteVulnerabilitiesCSV(humaCtx.BodyWriter(), items); writeVulnerabilitiesCSVErr != nil {
+ slog.ErrorContext(ctx, "failed to stream vulnerability export", "error", writeVulnerabilitiesCSVErr)
}
},
}, nil
diff --git a/backend/internal/vulnerability/service_test.go b/backend/internal/vulnerability/service_test.go
index 2404190e2..fa57534c2 100644
--- a/backend/internal/vulnerability/service_test.go
+++ b/backend/internal/vulnerability/service_test.go
@@ -3,7 +3,6 @@ package vulnerability
import (
"context"
"encoding/json"
- "errors"
"fmt"
"net/http"
"net/http/httptest"
@@ -15,6 +14,7 @@ import (
"github.com/getarcaneapp/arcane/types/v2/vulnerability"
"github.com/libtnb/sqlite"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
@@ -121,7 +121,8 @@ func TestBuildTrivyContainerResourcesInternal_CustomLimits(t *testing.T) {
}
dockerClient, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.41"), client.WithHTTPClient(httpClient))
require.NoError(t, err)
- defer dockerClient.Close()
+ clientToClose := dockerClient
+ t.Cleanup(func() { require.NoError(t, clientToClose.Close()) })
svc := &VulnerabilityService{settingsService: settingsSvc}
ctx := t.Context()
if tc.expired {
@@ -153,134 +154,7 @@ func TestBuildTrivyContainerResourcesInternal_CustomLimits(t *testing.T) {
}
for _, quotaSupported := range []bool{true, false} {
- t.Run(fmt.Sprintf("persistent capabilities quota=%t", quotaSupported), func(t *testing.T) {
- settingsSvc, db := featureSettingsInternal(t)
- require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
- store := kv.NewKVService(db)
- require.NoError(t, settingsSvc.SetBoolSetting(t.Context(), "trivyResourceLimitsEnabled", true))
- require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "trivyCpuLimit", "2.5"))
- require.NoError(t, settingsSvc.SetIntSetting(t.Context(), "trivyMemoryLimitMb", 2048))
- var status, requests atomic.Int32
- status.Store(http.StatusOK)
- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
- requests.Add(1)
- if code := int(status.Load()); code != http.StatusOK {
- http.Error(w, "info unavailable", code)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- if _, err := fmt.Fprintf(w, `{"CPUCfsQuota":%t,"CPUSet":true,"NCPU":4}`, quotaSupported); err != nil {
- t.Errorf("write Docker info: %v", err)
- }
- }))
- defer server.Close()
- dockerClient, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.41"))
- require.NoError(t, err)
- defer dockerClient.Close()
- svc := &VulnerabilityService{settingsService: settingsSvc, kvService: store}
- first, firstCPUSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- require.True(t, apply)
- require.Equal(t, int32(1), requests.Load())
- if quotaSupported {
- require.Equal(t, int64(2_500_000_000), first.NanoCPUs)
- require.Empty(t, firstCPUSet)
- } else {
- require.Zero(t, first.NanoCPUs)
- require.Equal(t, "0-1", firstCPUSet)
- }
-
- // A new service instance reuses persisted capabilities without calling Docker.
- svc = &VulnerabilityService{settingsService: settingsSvc, kvService: kv.NewKVService(db)}
- status.Store(http.StatusForbidden)
- cached, cpuSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- require.True(t, apply)
- require.Equal(t, first, cached)
- require.Equal(t, firstCPUSet, cpuSet)
- require.Equal(t, int32(1), requests.Load())
-
- // Cache capabilities, not the configured limit.
- require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "trivyCpuLimit", "0.5"))
- cached, cpuSet, _, err = svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- if quotaSupported {
- require.Equal(t, int64(500_000_000), cached.NanoCPUs)
- } else {
- require.Equal(t, "0", cpuSet)
- }
- require.Equal(t, int32(1), requests.Load())
-
- entries, err := store.ListByPrefix(t.Context(), "trivy:cpu-capabilities:v1:")
- require.NoError(t, err)
- require.Len(t, entries, 1)
- var expired trivyCPUCapabilitiesInternal
- require.NoError(t, json.Unmarshal([]byte(entries[0].Value), &expired))
- expired.FetchedAt = time.Now().Add(-2 * trivyCPUCapabilitiesCacheTTL)
- payload, err := json.Marshal(expired)
- require.NoError(t, err)
- require.NoError(t, store.Set(t.Context(), entries[0].Key, string(payload)))
- stale, staleCPUSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- require.True(t, apply)
- require.Equal(t, cached, stale)
- require.Equal(t, cpuSet, staleCPUSet)
- require.Equal(t, int32(2), requests.Load())
-
- status.Store(http.StatusOK)
- _, _, _, err = svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- require.Equal(t, int32(3), requests.Load())
- raw, found, err := store.Get(t.Context(), entries[0].Key)
- require.NoError(t, err)
- require.True(t, found)
- var refreshed trivyCPUCapabilitiesInternal
- require.NoError(t, json.Unmarshal([]byte(raw), &refreshed))
- require.True(t, refreshed.FetchedAt.After(expired.FetchedAt))
-
- status.Store(http.StatusInternalServerError)
- otherServer := httptest.NewServer(server.Config.Handler)
- defer otherServer.Close()
- for _, endpoint := range []struct{ host, version string }{
- {server.URL, "1.42"},
- {otherServer.URL, "1.41"},
- } {
- otherClient, err := client.New(client.WithHost(endpoint.host), client.WithAPIVersion(endpoint.version))
- require.NoError(t, err)
- defer otherClient.Close()
- fallback, cpuSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), otherClient)
- require.NoError(t, err)
- require.True(t, apply)
- require.Equal(t, int64(500_000_000), fallback.NanoCPUs)
- require.Empty(t, cpuSet)
- require.Equal(t, int64(2_147_483_648), fallback.Memory)
- }
-
- require.NoError(t, store.Set(t.Context(), entries[0].Key, "invalid JSON"))
- fallback, cpuSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- require.True(t, apply)
- require.Equal(t, int64(500_000_000), fallback.NanoCPUs)
- require.Empty(t, cpuSet)
- require.Equal(t, int64(2_147_483_648), fallback.Memory)
- require.Equal(t, int64(2_147_483_648), fallback.MemorySwap)
-
- // Cache storage failures must not prevent a live lookup or a safe fallback.
- require.NoError(t, db.Migrator().DropTable(&kv.KVEntry{}))
- status.Store(http.StatusOK)
- live, liveCPUSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- require.True(t, apply)
- require.Equal(t, cached, live)
- require.Equal(t, staleCPUSet, liveCPUSet)
- status.Store(http.StatusInternalServerError)
- fallback, cpuSet, apply, err = svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
- require.NoError(t, err)
- require.True(t, apply)
- require.Equal(t, int64(500_000_000), fallback.NanoCPUs)
- require.Empty(t, cpuSet)
- require.Equal(t, int64(2_147_483_648), fallback.Memory)
- })
+ t.Run(fmt.Sprintf("persistent capabilities quota=%t", quotaSupported), func(t *testing.T) { assertPersistentTrivyCapabilitiesInternal(t, quotaSupported) })
}
}
@@ -360,7 +234,7 @@ func setupVulnerabilityScanTestDB(t *testing.T) *database.DB {
}
func TestSaveScanResult_FixableCountsOSPackagesOnly(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -387,13 +261,13 @@ func TestVulnerabilityService_ListVulnerabilities_NoScanReturnsNotFound(t *testi
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
- _, _, err := svc.ListVulnerabilities(context.Background(), "sha256:unknown", pagination.QueryParams{Limit: 20})
+ _, _, err := svc.ListVulnerabilities(t.Context(), "sha256:unknown", pagination.QueryParams{Limit: 20})
- require.True(t, errors.Is(err, common.ErrVulnerabilityScanNotFound))
+ require.ErrorIs(t, err, common.ErrVulnerabilityScanNotFound)
}
func TestVulnerabilityService_DeleteScanResultsByImageIDs(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -415,7 +289,7 @@ func TestVulnerabilityService_DeleteScanResultsByImageIDs(t *testing.T) {
}
func TestVulnerabilityService_DeleteScanResultsByImageIDs_EmptyInput(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -466,7 +340,7 @@ func TestSeverityCountColumnsForFilterInternal(t *testing.T) {
func TestApplyListAllVulnerabilityRecordPrefiltersInternal_NoPossibleMatches(t *testing.T) {
db := setupVulnerabilityScanTestDB(t)
- base := db.WithContext(context.Background()).Model(&VulnerabilityScanRecord{})
+ base := db.WithContext(t.Context()).Model(&VulnerabilityScanRecord{})
_, ok := applyListAllVulnerabilityRecordPrefiltersInternal(base, map[string]string{"severity": "not-a-severity"}).Get()
require.False(t, ok)
@@ -482,7 +356,7 @@ func TestApplyListAllVulnerabilityRecordPrefiltersInternal_NoPossibleMatches(t *
}
func TestVulnerabilityService_ListAllVulnerabilities_FiltersIgnoredInline(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -530,7 +404,7 @@ func TestVulnerabilityService_ListAllVulnerabilities_FiltersIgnoredInline(t *tes
}
func TestVulnerabilityService_ListAllVulnerabilityImageOptions_SeverityFilter(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -554,7 +428,7 @@ func TestVulnerabilityService_ListAllVulnerabilityImageOptions_SeverityFilter(t
}
func TestVulnerabilityService_ListAllVulnerabilityImageOptions_InvalidSeverityAndNoFilter(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -582,7 +456,7 @@ func TestVulnerabilityService_ListAllVulnerabilityImageOptions_InvalidSeverityAn
// indexed-sum fast path and the blob-decode path for images with ignore rows
// produce the same count the old full-decode implementation did.
func TestVulnerabilityService_ActionableCountExcludingIgnored(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -606,8 +480,36 @@ func TestVulnerabilityService_ActionableCountExcludingIgnored(t *testing.T) {
require.NoError(t, err)
records := []VulnerabilityScanRecord{
- {ID: "sha256:img-a", ImageName: "nginx:latest", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 2, HighCount: 1, MediumCount: 1, TotalCount: 4, Vulnerabilities: database.StringSlice{string(rawVulnsA)}},
- {ID: "sha256:img-b", ImageName: "redis:7", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 1, HighCount: 1, MediumCount: 1, TotalCount: 3, Vulnerabilities: database.StringSlice{string(rawVulnsB)}},
+ {
+ ID: "sha256:img-a",
+ ImageName: "nginx:latest",
+ Status: ScanStatusCompleted,
+ ScanTime: now,
+ CriticalCount: 2,
+ HighCount: 1,
+ MediumCount: 1,
+ TotalCount: 4,
+ Vulnerabilities: database.StringSlice{
+ string(
+ rawVulnsA,
+ ),
+ },
+ },
+ {
+ ID: "sha256:img-b",
+ ImageName: "redis:7",
+ Status: ScanStatusCompleted,
+ ScanTime: now,
+ CriticalCount: 1,
+ HighCount: 1,
+ MediumCount: 1,
+ TotalCount: 3,
+ Vulnerabilities: database.StringSlice{
+ string(
+ rawVulnsB,
+ ),
+ },
+ },
{ID: "sha256:img-failed", ImageName: "failed:latest", Status: ScanStatusFailed, ScanTime: now, CriticalCount: 9, HighCount: 9, TotalCount: 18},
}
for i := range records {
@@ -645,7 +547,7 @@ func TestVulnerabilityService_ActionableCountExcludingIgnored(t *testing.T) {
// GrandTotalItems reflects every non-ignored CVE, and the page is sliced
// from the sorted matches.
func TestVulnerabilityService_ListAllVulnerabilities_PagesAndCountsWithInlineFilters(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupVulnerabilityScanTestDB(t)
svc := &VulnerabilityService{db: db}
@@ -766,7 +668,19 @@ func TestVulnerabilityService_GetRiskOverview(t *testing.T) {
// The highlighted fix is the highest-priority fixable occurrence: the KEV in db:16, not the unfixable copy in web.
require.NotNil(t, overview.ScoreDriver)
- require.Equal(t, vulnerability.RiskScoreDriver{VulnerabilityID: "CVE-2024-0002", ImageName: "db:16", PkgName: "curl", FixedVersion: "8.1.0", Exposure: vulnerability.ImageExposureUnknown, KnownExploited: true, Risk: 10}, *overview.ScoreDriver)
+ require.Equal(
+ t,
+ vulnerability.RiskScoreDriver{
+ VulnerabilityID: "CVE-2024-0002",
+ ImageName: "db:16",
+ PkgName: "curl",
+ FixedVersion: "8.1.0",
+ Exposure: vulnerability.ImageExposureUnknown,
+ KnownExploited: true,
+ Risk: 10,
+ },
+ *overview.ScoreDriver,
+ )
require.Len(t, overview.RiskiestFindings, 3, "findings are deduplicated by CVE")
kev := overview.RiskiestFindings[0]
@@ -859,7 +773,19 @@ func TestVulnerabilityService_SyncThreatIntel(t *testing.T) {
vulns = append(vulns, vulnerability.Vulnerability{VulnerabilityID: fmt.Sprintf("CVE-2024-%04d", i), PkgName: "pkg", Severity: vulnerability.SeverityMedium})
}
vulns = append(vulns, vulnerability.Vulnerability{VulnerabilityID: "GHSA-abcd", PkgName: "pkg", Severity: vulnerability.SeverityLow})
- require.NoError(t, svc.saveScanResult(t.Context(), &vulnerability.ScanResult{ImageID: "sha256:big", ImageName: "big:1", Status: vulnerability.ScanStatusCompleted, ScanTime: time.Now(), Vulnerabilities: vulns}))
+ require.NoError(
+ t,
+ svc.saveScanResult(
+ t.Context(),
+ &vulnerability.ScanResult{
+ ImageID: "sha256:big",
+ ImageName: "big:1",
+ Status: vulnerability.ScanStatusCompleted,
+ ScanTime: time.Now(),
+ Vulnerabilities: vulns,
+ },
+ ),
+ )
require.NoError(t, db.Create(&VulnerabilityThreatIntel{CVEID: "CVE-2019-DELISTED", KnownExploited: true, KEVDueDate: "2020-01-01"}).Error)
var kevRequests, epssRequests atomic.Int32
@@ -869,11 +795,15 @@ func TestVulnerabilityService_SyncThreatIntel(t *testing.T) {
case "/kev":
kevRequests.Add(1)
_, err := w.Write([]byte(`{"vulnerabilities":[{"cveID":"CVE-2024-0001","dateAdded":"2024-01-02","dueDate":"2024-01-23","knownRansomwareCampaignUse":"Known"}]}`))
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
case "/epss":
epssRequests.Add(1)
ids := strings.Split(r.URL.Query().Get("cve"), ",")
- require.LessOrEqual(t, len(ids), epssBatchMaxIDs)
+ if !assert.LessOrEqual(t, len(ids), epssBatchMaxIDs) {
+ return
+ }
data := make([]map[string]string, 0, len(ids))
for _, id := range ids {
if strings.HasPrefix(id, "GHSA") {
@@ -885,9 +815,13 @@ func TestVulnerabilityService_SyncThreatIntel(t *testing.T) {
data = append(data, map[string]string{"cve": id, "epss": "0.25", "percentile": "0.9"})
}
raw, err := json.Marshal(map[string]any{"data": data})
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
_, err = w.Write(raw)
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
default:
w.WriteHeader(http.StatusNotFound)
}
@@ -925,3 +859,133 @@ func TestVulnerabilityService_SyncThreatIntel(t *testing.T) {
require.NoError(t, svc.SyncThreatIntel(t.Context(), true))
require.EqualValues(t, 1, kevRequests.Load(), "disabled intel makes no requests")
}
+
+func assertPersistentTrivyCapabilitiesInternal(t *testing.T, quotaSupported bool) {
+ t.Helper()
+ settingsSvc, db := featureSettingsInternal(t)
+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))
+ store := kv.NewKVService(db)
+ require.NoError(t, settingsSvc.SetBoolSetting(t.Context(), "trivyResourceLimitsEnabled", true))
+ require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "trivyCpuLimit", "2.5"))
+ require.NoError(t, settingsSvc.SetIntSetting(t.Context(), "trivyMemoryLimitMb", 2048))
+ var status, requests atomic.Int32
+ status.Store(http.StatusOK)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ requests.Add(1)
+ if code := int(status.Load()); code != http.StatusOK {
+ http.Error(w, "info unavailable", code)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ if _, err := fmt.Fprintf(w, `{"CPUCfsQuota":%t,"CPUSet":true,"NCPU":4}`, quotaSupported); err != nil {
+ t.Errorf("write Docker info: %v", err)
+ }
+ }))
+ defer server.Close()
+ dockerClient, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.41"))
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, dockerClient.Close()) })
+ svc := &VulnerabilityService{settingsService: settingsSvc, kvService: store}
+ first, firstCPUSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ require.True(t, apply)
+ require.Equal(t, int32(1), requests.Load())
+ if quotaSupported {
+ require.Equal(t, int64(2_500_000_000), first.NanoCPUs)
+ require.Empty(t, firstCPUSet)
+ } else {
+ require.Zero(t, first.NanoCPUs)
+ require.Equal(t, "0-1", firstCPUSet)
+ }
+
+ // A new service instance reuses persisted capabilities without calling Docker.
+ svc = &VulnerabilityService{settingsService: settingsSvc, kvService: kv.NewKVService(db)}
+ status.Store(http.StatusForbidden)
+ cached, cpuSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ require.True(t, apply)
+ require.Equal(t, first, cached)
+ require.Equal(t, firstCPUSet, cpuSet)
+ require.Equal(t, int32(1), requests.Load())
+
+ // Cache capabilities, not the configured limit.
+ require.NoError(t, settingsSvc.SetStringSetting(t.Context(), "trivyCpuLimit", "0.5"))
+ cached, cpuSet, _, err = svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ if quotaSupported {
+ require.Equal(t, int64(500_000_000), cached.NanoCPUs)
+ } else {
+ require.Equal(t, "0", cpuSet)
+ }
+ require.Equal(t, int32(1), requests.Load())
+
+ entries, err := store.ListByPrefix(t.Context(), "trivy:cpu-capabilities:v1:")
+ require.NoError(t, err)
+ require.Len(t, entries, 1)
+ var expired trivyCPUCapabilitiesInternal
+ require.NoError(t, json.Unmarshal([]byte(entries[0].Value), &expired))
+ expired.FetchedAt = time.Now().Add(-2 * trivyCPUCapabilitiesCacheTTL)
+ payload, err := json.Marshal(expired)
+ require.NoError(t, err)
+ require.NoError(t, store.Set(t.Context(), entries[0].Key, string(payload)))
+ stale, staleCPUSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ require.True(t, apply)
+ require.Equal(t, cached, stale)
+ require.Equal(t, cpuSet, staleCPUSet)
+ require.Equal(t, int32(2), requests.Load())
+
+ status.Store(http.StatusOK)
+ _, _, _, err = svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ require.Equal(t, int32(3), requests.Load())
+ raw, found, err := store.Get(t.Context(), entries[0].Key)
+ require.NoError(t, err)
+ require.True(t, found)
+ var refreshed trivyCPUCapabilitiesInternal
+ require.NoError(t, json.Unmarshal([]byte(raw), &refreshed))
+ require.True(t, refreshed.FetchedAt.After(expired.FetchedAt))
+
+ status.Store(http.StatusInternalServerError)
+ otherServer := httptest.NewServer(server.Config.Handler)
+ defer otherServer.Close()
+ for _, endpoint := range []struct{ host, version string }{
+ {server.URL, "1.42"},
+ {otherServer.URL, "1.41"},
+ } {
+ otherClient, newErr := client.New(client.WithHost(endpoint.host), client.WithAPIVersion(endpoint.version))
+ require.NoError(t, newErr)
+ t.Cleanup(func() { require.NoError(t, otherClient.Close()) })
+ fallback, fallbackCPUSet, fallbackApply, newErr := svc.getTrivyContainerResourceOptionsInternal(t.Context(), otherClient)
+ require.NoError(t, newErr)
+ require.True(t, fallbackApply)
+ require.Equal(t, int64(500_000_000), fallback.NanoCPUs)
+ require.Empty(t, fallbackCPUSet)
+ require.Equal(t, int64(2_147_483_648), fallback.Memory)
+ }
+
+ require.NoError(t, store.Set(t.Context(), entries[0].Key, "invalid JSON"))
+ fallback, cpuSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ require.True(t, apply)
+ require.Equal(t, int64(500_000_000), fallback.NanoCPUs)
+ require.Empty(t, cpuSet)
+ require.Equal(t, int64(2_147_483_648), fallback.Memory)
+ require.Equal(t, int64(2_147_483_648), fallback.MemorySwap)
+
+ // Cache storage failures must not prevent a live lookup or a safe fallback.
+ require.NoError(t, db.Migrator().DropTable(&kv.KVEntry{}))
+ status.Store(http.StatusOK)
+ live, liveCPUSet, apply, err := svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ require.True(t, apply)
+ require.Equal(t, cached, live)
+ require.Equal(t, staleCPUSet, liveCPUSet)
+ status.Store(http.StatusInternalServerError)
+ fallback, cpuSet, apply, err = svc.getTrivyContainerResourceOptionsInternal(t.Context(), dockerClient)
+ require.NoError(t, err)
+ require.True(t, apply)
+ require.Equal(t, int64(500_000_000), fallback.NanoCPUs)
+ require.Empty(t, cpuSet)
+ require.Equal(t, int64(2_147_483_648), fallback.Memory)
+}
diff --git a/backend/internal/vulnerability/vulnerability.go b/backend/internal/vulnerability/vulnerability.go
index 8618a7699..4727df2df 100644
--- a/backend/internal/vulnerability/vulnerability.go
+++ b/backend/internal/vulnerability/vulnerability.go
@@ -61,7 +61,18 @@ type VulnerabilityService struct {
}
// NewVulnerabilityService creates a new VulnerabilityService instance
-func NewVulnerabilityService(db *database.DB, cfg *config.Config, dockerService *docker.DockerClientService, eventService *event.EventService, settingsService *settings.SettingsService, notificationService *notification.NotificationService, activityService *activity.ActivityService, registryService *registry.ContainerRegistryService, kvService *kv.KVService, httpClient *http.Client) *VulnerabilityService {
+func NewVulnerabilityService(
+ db *database.DB,
+ cfg *config.Config,
+ dockerService *docker.DockerClientService,
+ eventService *event.EventService,
+ settingsService *settings.SettingsService,
+ notificationService *notification.NotificationService,
+ activityService *activity.ActivityService,
+ registryService *registry.ContainerRegistryService,
+ kvService *kv.KVService,
+ httpClient *http.Client,
+) *VulnerabilityService {
return &VulnerabilityService{
db: db,
config: cfg,
diff --git a/backend/internal/vulnerability/vulnerability_export_test.go b/backend/internal/vulnerability/vulnerability_export_test.go
index c953c938d..f9fef2af6 100644
--- a/backend/internal/vulnerability/vulnerability_export_test.go
+++ b/backend/internal/vulnerability/vulnerability_export_test.go
@@ -11,15 +11,48 @@ import (
func TestWriteVulnerabilitiesCSV(t *testing.T) {
items := []vulnerability.VulnerabilityWithImage{
- {VulnerabilityID: "CVE-2026-0001", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.1", Severity: vulnerability.SeverityHigh, ImageID: "img-1", ImageName: "example/security:latest"},
+ {
+ VulnerabilityID: "CVE-2026-0001",
+ PkgName: "openssl",
+ InstalledVersion: "3.0.0",
+ FixedVersion: "3.0.1",
+ Severity: vulnerability.SeverityHigh,
+ ImageID: "img-1",
+ ImageName: "example/security:latest",
+ },
{VulnerabilityID: "CVE-2026-0002", PkgName: "libc, glibc", Severity: vulnerability.SeverityHigh, ImageID: "sha256:fallback"},
- {VulnerabilityID: "CVE-2026-0003", PkgName: `pkg "quoted"`, InstalledVersion: "ünïcødé", FixedVersion: "line1\nline2", Severity: vulnerability.SeverityHigh, ImageID: "img-1", ImageName: "example/security:latest", Ignored: true},
- {VulnerabilityID: `=HYPERLINK("https://evil.example")`, PkgName: "+sum", InstalledVersion: "-1", FixedVersion: "@cmd", Severity: vulnerability.SeverityHigh, ImageID: "img-1", ImageName: "example/security:latest"},
+ {
+ VulnerabilityID: "CVE-2026-0003",
+ PkgName: `pkg "quoted"`,
+ InstalledVersion: "ünïcødé",
+ FixedVersion: "line1\nline2",
+ Severity: vulnerability.SeverityHigh,
+ ImageID: "img-1",
+ ImageName: "example/security:latest",
+ Ignored: true,
+ },
+ {
+ VulnerabilityID: `=HYPERLINK("https://evil.example")`,
+ PkgName: "+sum",
+ InstalledVersion: "-1",
+ FixedVersion: "@cmd",
+ Severity: vulnerability.SeverityHigh,
+ ImageID: "img-1",
+ ImageName: "example/security:latest",
+ },
}
var buf bytes.Buffer
require.NoError(t, WriteVulnerabilitiesCSV(&buf, seqInternal(items)))
- require.Equal(t, "\ufeffCVE,Severity,Package,Installed Version,Fixed Version,Image,Ignored\r\nCVE-2026-0001,HIGH,openssl,3.0.0,3.0.1,example/security:latest,false\r\nCVE-2026-0002,HIGH,\"libc, glibc\",,,sha256:fallback,false\r\nCVE-2026-0003,HIGH,\"pkg \"\"quoted\"\"\",ünïcødé,\"line1\r\nline2\",example/security:latest,true\r\n\"'=HYPERLINK(\"\"https://evil.example\"\")\",HIGH,'+sum,'-1,'@cmd,example/security:latest,false\r\n", buf.String())
+ require.Equal(
+ t,
+ "\ufeffCVE,Severity,Package,Installed Version,Fixed Version,Image,Ignored\r\nCVE-2026-0001,HIGH,openssl,3.0."+
+ "0,3.0.1,example/security:latest,false\r\nCVE-2026-0002,HIGH,\"libc, "+
+ "glibc\",,,sha256:fallback,false\r\nCVE-2026-0003,HIGH,\"pkg "+
+ "\"\"quoted\"\"\",ünïcødé,\"line1\r\nline2\",example/security:latest,true\r\n\"'=HYPERLINK(\"\"https://evil.example"+
+ "\"\")\",HIGH,'+sum,'-1,'@cmd,example/security:latest,false\r\n",
+ buf.String(),
+ )
buf.Reset()
require.NoError(t, WriteVulnerabilitiesCSV(&buf, seqInternal(nil)))
diff --git a/backend/internal/vulnerability/vulnerability_feature_test.go b/backend/internal/vulnerability/vulnerability_feature_test.go
index f8022d47b..c448dbc97 100644
--- a/backend/internal/vulnerability/vulnerability_feature_test.go
+++ b/backend/internal/vulnerability/vulnerability_feature_test.go
@@ -30,7 +30,7 @@ func featureSettingsInternal(t *testing.T) (*settings.SettingsService, *database
db := &database.DB{DB: gdb}
svc, err := settings.NewSettingsService(t.Context(), db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
require.NoError(t, err)
return svc, db
@@ -87,7 +87,7 @@ func TestVulnerabilityFeatureDisabledWhileWaitingForSlot(t *testing.T) {
defer server.Close()
dockerClient, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.41"))
require.NoError(t, err)
- defer dockerClient.Close()
+ t.Cleanup(func() { require.NoError(t, dockerClient.Close()) })
svc := &VulnerabilityService{settingsService: settingsSvc, dockerService: &docker.DockerClientService{Client: dockerClient}}
_, release, err := svc.acquireTrivyScanSlotInternal(t.Context(), "active-image", false)
require.NoError(t, err)
@@ -99,11 +99,11 @@ func TestVulnerabilityFeatureDisabledWhileWaitingForSlot(t *testing.T) {
started := make(chan struct{})
go func() {
close(started)
- _, done, err := svc.acquireTrivyScanSlotInternal(t.Context(), tt.queuedImage, true)
+ _, done, acquireTrivyScanSlotErr := svc.acquireTrivyScanSlotInternal(t.Context(), tt.queuedImage, true)
if done != nil {
done()
}
- result <- err
+ result <- acquireTrivyScanSlotErr
}()
<-started
require.NoError(t, settingsSvc.SetBoolSetting(t.Context(), features.VulnerabilityManagementSettingKey, false))
@@ -115,8 +115,8 @@ func TestVulnerabilityFeatureDisabledWhileWaitingForSlot(t *testing.T) {
require.Len(t, svc.trivyScanSlots, tt.slots-1)
release()
select {
- case err := <-result:
- require.ErrorIs(t, err, common.ErrFeatureDisabled)
+ case scanErr := <-result:
+ require.ErrorIs(t, scanErr, common.ErrFeatureDisabled)
case <-time.After(time.Second):
t.Fatal("queued scan did not return after the active scan released its resources")
}
diff --git a/backend/internal/vulnerability/vulnerability_ignores.go b/backend/internal/vulnerability/vulnerability_ignores.go
index bf8bf3dc5..22cbd1ae4 100644
--- a/backend/internal/vulnerability/vulnerability_ignores.go
+++ b/backend/internal/vulnerability/vulnerability_ignores.go
@@ -87,8 +87,8 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID st
CreatedBy: payload.CreatedBy,
}
- if err := s.db.WithContext(ctx).Create(ignore).Error; err != nil {
- return nil, fmt.Errorf("failed to create ignore record: %w", err)
+ if createIgnoreErr := s.db.WithContext(ctx).Create(ignore).Error; createIgnoreErr != nil {
+ return nil, fmt.Errorf("failed to create ignore record: %w", createIgnoreErr)
}
slog.InfoContext(ctx, "vulnerability ignored",
@@ -158,7 +158,14 @@ func (s *VulnerabilityService) BulkIgnoreVulnerabilities(ctx context.Context, en
params := bulkFilterParamsInternal(filters, false)
_, q := s.listAllVulnerabilitiesQueryInternal(ctx, tx, envID, &params)
var targets []VulnerabilityScanItem
- if err := q.Distinct("vulnerability_scan_items.image_id", "vulnerability_scan_items.vulnerability_id", "vulnerability_scan_items.pkg_name", "vulnerability_scan_items.installed_version").Scan(&targets).Error; err != nil {
+ if err := q.Distinct(
+ "vulnerability_scan_items.image_id",
+ "vulnerability_scan_items.vulnerability_id",
+ "vulnerability_scan_items.pkg_name",
+ "vulnerability_scan_items.installed_version",
+ ).Scan(
+ &targets,
+ ).Error; err != nil {
return fmt.Errorf("failed to resolve vulnerabilities to ignore: %w", err)
}
if len(targets) == 0 {
diff --git a/backend/internal/vulnerability/vulnerability_ignores_test.go b/backend/internal/vulnerability/vulnerability_ignores_test.go
index 3de593447..40634681f 100644
--- a/backend/internal/vulnerability/vulnerability_ignores_test.go
+++ b/backend/internal/vulnerability/vulnerability_ignores_test.go
@@ -1,7 +1,6 @@
package vulnerability
import (
- "context"
"encoding/json"
"fmt"
"testing"
@@ -22,7 +21,20 @@ func seedBulkIgnoreFixtureInternal(t *testing.T, db *database.DB, svc *Vulnerabi
for i := range 45 {
severity := kit.Ternary(i%3 == 0, vulnerability.SeverityHigh, vulnerability.SeverityLow)
fixed := kit.Ternary(i%2 == 0, "2.0.0", "")
- nginx = append(nginx, vulnerability.Vulnerability{VulnerabilityID: fmt.Sprintf("CVE-N-%03d", i), PkgName: "libnginx", InstalledVersion: "1.0.0", FixedVersion: fixed, Severity: severity, Title: "nginx finding"})
+ nginx = append(
+ nginx,
+ vulnerability.Vulnerability{
+ VulnerabilityID: fmt.Sprintf(
+ "CVE-N-%03d",
+ i,
+ ),
+ PkgName: "libnginx",
+ InstalledVersion: "1.0.0",
+ FixedVersion: fixed,
+ Severity: severity,
+ Title: "nginx finding",
+ },
+ )
}
redis := []vulnerability.Vulnerability{
{VulnerabilityID: "CVE-R-1", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.1", Severity: vulnerability.SeverityCritical, Title: "openssl overflow"},
@@ -46,18 +58,18 @@ func seedBulkIgnoreFixtureInternal(t *testing.T, db *database.DB, svc *Vulnerabi
Vulnerabilities: database.StringSlice{string(raw)},
}).Error)
}
- svc.BackfillScanItems(context.Background())
+ svc.BackfillScanItems(t.Context())
}
func activeCountInternal(t *testing.T, svc *VulnerabilityService, envID string) int64 {
t.Helper()
- _, page, err := svc.ListAllVulnerabilities(context.Background(), envID, pagination.QueryParams{Start: 0, Limit: 20})
+ _, page, err := svc.ListAllVulnerabilities(t.Context(), envID, pagination.QueryParams{Start: 0, Limit: 20})
require.NoError(t, err)
return page.TotalItems
}
func TestBulkIgnoreVulnerabilities_AllMatchingHonorsFilters(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
for _, tc := range []struct {
name string
@@ -88,7 +100,11 @@ func TestBulkIgnoreVulnerabilities_AllMatchingHonorsFilters(t *testing.T) {
var actionableIgnored int64
require.NoError(t, db.Model(&VulnerabilityIgnore{}).
- Joins("JOIN vulnerability_scan_items ON vulnerability_scan_items.image_id = vulnerability_ignores.image_id AND vulnerability_scan_items.vulnerability_id = vulnerability_ignores.vulnerability_id AND vulnerability_scan_items.pkg_name = vulnerability_ignores.pkg_name AND vulnerability_scan_items.installed_version = vulnerability_ignores.installed_version").
+ Joins("JOIN vulnerability_scan_items ON vulnerability_scan_items.image_id = vulnerability_ignores.image_id "+
+ "AND vulnerability_scan_items.vulnerability_id = vulnerability_ignores.vulnerability_id AND "+
+ "vulnerability_scan_items.pkg_name = vulnerability_ignores.pkg_name AND "+
+ "vulnerability_scan_items.installed_version = vulnerability_ignores.installed_version",
+ ).
Where("vulnerability_scan_items.severity IN ?", []string{"CRITICAL", "HIGH"}).
Count(&actionableIgnored).Error)
after, err := svc.ActionableCountExcludingIgnored(ctx)
diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.go
index 2e9e472e8..f60b9e375 100644
--- a/backend/internal/vulnerability/vulnerability_query.go
+++ b/backend/internal/vulnerability/vulnerability_query.go
@@ -49,8 +49,8 @@ func (s *VulnerabilityService) GetScanResult(ctx context.Context, envID, imageID
cveIDs = append(cveIDs, vulns[i].VulnerabilityID)
}
var rows []VulnerabilityThreatIntel
- if err := s.db.WithContext(ctx).Where("cve_id IN ?", cveIDs).Find(&rows).Error; err != nil {
- slog.WarnContext(ctx, "failed to load threat intel for image insights", "error", err)
+ if loadThreatIntelErr := s.db.WithContext(ctx).Where("cve_id IN ?", cveIDs).Find(&rows).Error; loadThreatIntelErr != nil {
+ slog.WarnContext(ctx, "failed to load threat intel for image insights", "error", loadThreatIntelErr)
}
for _, row := range rows {
intel[row.CVEID] = vuln.ThreatIntel{KnownExploited: row.KnownExploited, EPSS: row.EPSSScore}
@@ -80,7 +80,7 @@ func (s *VulnerabilityService) loadScanResultInternal(ctx context.Context, image
result := s.convertRecordToResult(&record)
var reportCount int64
- if err := s.db.WithContext(ctx).Model(&VulnerabilityReportRecord{}).Where("image_id = ?", record.ID).Count(&reportCount).Error; err == nil {
+ if countReportsErr := s.db.WithContext(ctx).Model(&VulnerabilityReportRecord{}).Where("image_id = ?", record.ID).Count(&reportCount).Error; countReportsErr == nil {
result.HasReport = reportCount > 0
}
return result, nil
@@ -315,7 +315,13 @@ func (s *VulnerabilityService) ActionableCountExcludingIgnored(ctx context.Conte
countQuery = countQuery.Where("vulnerability_scan_items.image_id IN ?", currentImageIDs)
}
var count int64
- err := countQuery.Where("NOT EXISTS (SELECT 1 FROM vulnerability_ignores WHERE vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version)").
+ err := countQuery.Where(
+ "NOT EXISTS (SELECT 1 FROM vulnerability_ignores WHERE vulnerability_ignores.image_id = " +
+ "vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = " +
+ "vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = " +
+ "vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = " +
+ "vulnerability_scan_items.installed_version)",
+ ).
Count(&count).Error
if err != nil {
return 0, fmt.Errorf("failed to count actionable vulnerabilities: %w", err)
@@ -344,7 +350,14 @@ func scanItemsQueryInternal(ctx context.Context, db *gorm.DB, envID string, only
query := db.WithContext(ctx).
Model(&VulnerabilityScanItem{}).
Joins("JOIN vulnerability_scans ON vulnerability_scans.id = vulnerability_scan_items.image_id AND vulnerability_scans.status = ?", ScanStatusCompleted).
- Joins("LEFT JOIN vulnerability_ignores ON vulnerability_ignores.environment_id = ? AND vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version", envID)
+ Joins(
+ "LEFT JOIN vulnerability_ignores ON vulnerability_ignores.environment_id = ? AND "+
+ "vulnerability_ignores.image_id = vulnerability_scan_items.image_id AND "+
+ "vulnerability_ignores.vulnerability_id = vulnerability_scan_items.vulnerability_id AND "+
+ "vulnerability_ignores.pkg_name = vulnerability_scan_items.pkg_name AND "+
+ "vulnerability_ignores.installed_version = vulnerability_scan_items.installed_version",
+ envID,
+ )
if onlyIgnored {
query = query.Where("vulnerability_ignores.id IS NOT NULL")
} else {
@@ -381,7 +394,12 @@ func (s *VulnerabilityService) listAllVulnerabilitiesQueryInternal(ctx context.C
q = q.Where("("+strings.Join(clauses, " OR ")+")", args...)
}
q = pagination.ApplyLikeSearch(q, strings.ToLower(params.Search),
- "(LOWER(vulnerability_scan_items.vulnerability_id) LIKE ? OR LOWER(vulnerability_scan_items.pkg_name) LIKE ? OR LOWER(vulnerability_scan_items.installed_version) LIKE ? OR LOWER(vulnerability_scan_items.fixed_version) LIKE ? OR LOWER(vulnerability_scan_items.title) LIKE ? OR LOWER(vulnerability_scans.image_name) LIKE ? OR LOWER(vulnerability_scan_items.image_id) LIKE ?)")
+ "(LOWER(vulnerability_scan_items.vulnerability_id) LIKE ? OR "+
+ "LOWER(vulnerability_scan_items.pkg_name) LIKE ? OR "+
+ "LOWER(vulnerability_scan_items.installed_version) LIKE ? OR "+
+ "LOWER(vulnerability_scan_items.fixed_version) LIKE ? OR LOWER(vulnerability_scan_items.title) LIKE "+
+ "? OR LOWER(vulnerability_scans.image_name) LIKE ? OR LOWER(vulnerability_scan_items.image_id) LIKE "+
+ "?)")
if col, ok := listAllVulnerabilitySortColumnsInternal[params.Sort]; ok {
q = q.Order(clause.OrderByColumn{Column: clause.Column{Name: col, Raw: true}, Desc: strings.EqualFold(string(params.Order), "desc")})
}
@@ -431,7 +449,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID
}
if row.Details != nil && *row.Details != "" {
var details vulnerabilityScanItemDetailsInternal
- if err := json.Unmarshal([]byte(*row.Details), &details); err == nil {
+ if unmarshalErr := json.Unmarshal([]byte(*row.Details), &details); unmarshalErr == nil {
item.Description = details.Description
item.References = details.References
item.CVSS = details.CVSS
@@ -466,8 +484,8 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID
for rows.Next() {
var row vulnerabilityScanItemRowInternal
- if err := q.ScanRows(rows, &row); err != nil {
- yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", err))
+ if scanRowsErr := q.ScanRows(rows, &row); scanRowsErr != nil {
+ yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", scanRowsErr))
return
}
item := vulnerability.VulnerabilityWithImage{
@@ -488,8 +506,8 @@ func (s *VulnerabilityService) ExportVulnerabilities(ctx context.Context, envID
return
}
}
- if err := rows.Err(); err != nil {
- yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", err))
+ if iterateExportRowsErr := rows.Err(); iterateExportRowsErr != nil {
+ yield(vulnerability.VulnerabilityWithImage{}, fmt.Errorf("failed to export vulnerabilities: %w", iterateExportRowsErr))
}
}, nil
}
@@ -1039,12 +1057,12 @@ func (s *VulnerabilityService) GetRiskOverview(ctx context.Context, envID string
now := s.riskNowInternal()
today := now.Format(riskDateLayout)
var snapshots []VulnerabilityRiskSnapshot
- if err := s.db.WithContext(ctx).
+ if loadSnapshotsErr := s.db.WithContext(ctx).
Where("scoring_version = ?", vuln.ScoringVersion).
Where("snapshot_date >= ?", now.AddDate(0, 0, -(riskTrendDays-1)).Format(riskDateLayout)).
Order("snapshot_date ASC").
- Find(&snapshots).Error; err != nil {
- return nil, fmt.Errorf("failed to load risk snapshots: %w", err)
+ Find(&snapshots).Error; loadSnapshotsErr != nil {
+ return nil, fmt.Errorf("failed to load risk snapshots: %w", loadSnapshotsErr)
}
deltaDay := now.AddDate(0, 0, -riskDeltaDays).Format(riskDateLayout)
@@ -1097,8 +1115,8 @@ func WriteVulnerabilitiesCSV(w io.Writer, items iter.Seq2[vulnerability.Vulnerab
for j, value := range record {
record[j] = kit.Ternary(value != "" && strings.ContainsRune("=+-@\t\r", rune(value[0])), "'"+value, value)
}
- if err := writer.Write(record); err != nil {
- return fmt.Errorf("failed to write csv: %w", err)
+ if writeErr := writer.Write(record); writeErr != nil {
+ return fmt.Errorf("failed to write csv: %w", writeErr)
}
}
writer.Flush()
diff --git a/backend/internal/vulnerability/vulnerability_scan.go b/backend/internal/vulnerability/vulnerability_scan.go
index f5adae375..8e18a3c9a 100644
--- a/backend/internal/vulnerability/vulnerability_scan.go
+++ b/backend/internal/vulnerability/vulnerability_scan.go
@@ -52,11 +52,11 @@ func (s *VulnerabilityService) getScanPhaseInternal(imageID string) vulnerabilit
return ""
}
- if typed, ok := phase.(vulnerability.ScanPhase); ok {
+ if typed, localOk := phase.(vulnerability.ScanPhase); localOk {
return typed
}
- if str, ok := phase.(string); ok {
+ if str, localOk2 := phase.(string); localOk2 {
return vulnerability.ScanPhase(str)
}
@@ -319,7 +319,7 @@ func (s *VulnerabilityService) startVulnerabilityScanActivityInternal(ctx contex
return ""
}
- activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
+ scanActivity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{
EnvironmentID: envID,
Type: activitytypes.TypeVulnerabilityScan,
ResourceType: new("image"),
@@ -334,7 +334,7 @@ func (s *VulnerabilityService) startVulnerabilityScanActivityInternal(ctx contex
slog.WarnContext(ctx, "failed to create vulnerability scan activity", "error", err, "imageId", imageID)
return ""
}
- return activity.ID
+ return scanActivity.ID
}
func (s *VulnerabilityService) updateVulnerabilityScanActivityInternal(ctx context.Context, activityID string, phase vulnerability.ScanPhase, progress int, message string) {
@@ -541,8 +541,15 @@ func (s *VulnerabilityService) sendScheduledVulnerabilitySummaryInternal(
summaryDate := time.Now().UTC().Format("2006-01-02")
payload := notification.VulnerabilityNotificationPayload{
- CVEID: "Daily Summary - " + summaryDate,
- Severity: fmt.Sprintf("Critical:%d High:%d Medium:%d Low:%d Unknown:%d", summary.severityCounts["CRITICAL"], summary.severityCounts["HIGH"], summary.severityCounts["MEDIUM"], summary.severityCounts["LOW"], summary.severityCounts["UNKNOWN"]),
+ CVEID: "Daily Summary - " + summaryDate,
+ Severity: fmt.Sprintf(
+ "Critical:%d High:%d Medium:%d Low:%d Unknown:%d",
+ summary.severityCounts["CRITICAL"],
+ summary.severityCounts["HIGH"],
+ summary.severityCounts["MEDIUM"],
+ summary.severityCounts["LOW"],
+ summary.severityCounts["UNKNOWN"],
+ ),
ImageName: fmt.Sprintf("%d image(s) scanned, %d with fixable vulnerabilities", scanned, summary.imagesWithFixable),
FixedVersion: fmt.Sprintf("%d fixable vulnerability record(s)", summary.totalFixable),
}
@@ -561,8 +568,8 @@ func (s *VulnerabilityService) sendScheduledVulnerabilitySummaryInternal(
// the overhead of creating/destroying a container per scan. The caller-supplied
// user is recorded in the event log.
func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string, user common.User, force bool) (scanned, failed int, err error) {
- if err := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); err != nil {
- return 0, 0, err
+ if requireFeatureErr := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); requireFeatureErr != nil {
+ return 0, 0, requireFeatureErr
}
images, err := s.dockerService.ListImages(ctx)
if err != nil {
diff --git a/backend/internal/vulnerability/vulnerability_store.go b/backend/internal/vulnerability/vulnerability_store.go
index 2381b48c1..2e3efb160 100644
--- a/backend/internal/vulnerability/vulnerability_store.go
+++ b/backend/internal/vulnerability/vulnerability_store.go
@@ -81,10 +81,10 @@ func (s *VulnerabilityService) BackfillScanItems(ctx context.Context) {
if err != nil || len(items) == 0 {
continue
}
- if err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
+ if withTxErr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
return tx.CreateInBatches(items, scanItemInsertBatchSizeInternal).Error
- }); err != nil {
- slog.WarnContext(ctx, "failed to backfill vulnerability scan items", "error", err, "image_id", record.ID)
+ }); withTxErr != nil {
+ slog.WarnContext(ctx, "failed to backfill vulnerability scan items", "error", withTxErr, "image_id", record.ID)
}
}
return nil
@@ -165,8 +165,8 @@ func (s *VulnerabilityService) ImportLegacyReportFiles(ctx context.Context) {
}
var scans []VulnerabilityScanRecord
- if err := s.db.WithContext(ctx).Select("id", "fixable_count").Find(&scans).Error; err != nil {
- slog.WarnContext(ctx, "failed to list scan records for report import", "error", err)
+ if listScansErr := s.db.WithContext(ctx).Select("id", "fixable_count").Find(&scans).Error; listScansErr != nil {
+ slog.WarnContext(ctx, "failed to list scan records for report import", "error", listScansErr)
return
}
@@ -174,8 +174,8 @@ func (s *VulnerabilityService) ImportLegacyReportFiles(ctx context.Context) {
s.importLegacyReportInternal(ctx, &scans[i], rootDir, logical)
}
- if err := acfs.RemoveAll(ctx, rootDir, logical); err != nil {
- slog.WarnContext(ctx, "failed to remove legacy vulnerability report directory", "error", err)
+ if removeAllErr := acfs.RemoveAll(ctx, rootDir, logical); removeAllErr != nil {
+ slog.WarnContext(ctx, "failed to remove legacy vulnerability report directory", "error", removeAllErr)
}
}
@@ -194,11 +194,11 @@ func (s *VulnerabilityService) importLegacyReportInternal(ctx context.Context, s
return
}
record := VulnerabilityReportRecord{ImageID: scan.ID, Data: string(data)}
- if err := s.db.WithContext(ctx).Clauses(clause.OnConflict{
+ if importReportErr := s.db.WithContext(ctx).Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "image_id"}},
UpdateAll: true,
- }).Create(&record).Error; err != nil {
- slog.WarnContext(ctx, "failed to import legacy vulnerability report", "imageId", scan.ID, "error", err)
+ }).Create(&record).Error; importReportErr != nil {
+ slog.WarnContext(ctx, "failed to import legacy vulnerability report", "imageId", scan.ID, "error", importReportErr)
return
}
if scan.FixableCount == nil {
@@ -214,8 +214,8 @@ func (s *VulnerabilityService) importLegacyReportInternal(ctx context.Context, s
}
}
}
- if err := s.db.WithContext(ctx).Model(&VulnerabilityScanRecord{}).Where("id = ?", scan.ID).Update("fixable_count", count).Error; err != nil {
- slog.WarnContext(ctx, "failed to backfill fixable vulnerability count", "imageId", scan.ID, "error", err)
+ if updateFixableCountErr := s.db.WithContext(ctx).Model(&VulnerabilityScanRecord{}).Where("id = ?", scan.ID).Update("fixable_count", count).Error; updateFixableCountErr != nil {
+ slog.WarnContext(ctx, "failed to backfill fixable vulnerability count", "imageId", scan.ID, "error", updateFixableCountErr)
}
}
}
@@ -460,8 +460,8 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulne
if err != nil {
return err
}
- if err := tx.CreateInBatches(items, scanItemInsertBatchSizeInternal).Error; err != nil {
- return fmt.Errorf("failed to store scan items: %w", err)
+ if storeItemsErr := tx.CreateInBatches(items, scanItemInsertBatchSizeInternal).Error; storeItemsErr != nil {
+ return fmt.Errorf("failed to store scan items: %w", storeItemsErr)
}
return nil
})
@@ -540,8 +540,8 @@ func (s *VulnerabilityService) loadThreatIntelStateInternal(ctx context.Context)
if err != nil || !ok {
return state
}
- if err := json.Unmarshal([]byte(raw), &state); err != nil {
- slog.WarnContext(ctx, "failed to decode threat intel state", "error", err)
+ if unmarshalErr := json.Unmarshal([]byte(raw), &state); unmarshalErr != nil {
+ slog.WarnContext(ctx, "failed to decode threat intel state", "error", unmarshalErr)
}
return state
}
@@ -586,7 +586,7 @@ func (s *VulnerabilityService) SyncThreatIntel(ctx context.Context, force bool)
// syncKEVInternal replaces the stored KEV flags with the current catalog and returns the feed ETag.
func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string) (string, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.kevFeedURL, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.kevFeedURL, http.NoBody)
if err != nil {
return "", fmt.Errorf("failed to build KEV request: %w", err)
}
@@ -613,8 +613,8 @@ func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string)
Ransomware string `json:"knownRansomwareCampaignUse"`
} `json:"vulnerabilities"`
}
- if err := json.UnmarshalRead(io.LimitReader(resp.Body, kevFeedMaxBytes), &feed); err != nil {
- return "", fmt.Errorf("failed to decode KEV catalog: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(io.LimitReader(resp.Body, kevFeedMaxBytes), &feed); unmarshalReadErr != nil {
+ return "", fmt.Errorf("failed to decode KEV catalog: %w", unmarshalReadErr)
}
now := time.Now()
@@ -635,18 +635,18 @@ func (s *VulnerabilityService) syncKEVInternal(ctx context.Context, etag string)
// The catalog only grows, so an empty or much smaller feed is a bad response; keep the cached flags.
var cached int64
- if err := s.db.WithContext(ctx).Model(&VulnerabilityThreatIntel{}).Where("known_exploited = ?", true).Count(&cached).Error; err != nil {
- return "", fmt.Errorf("failed to count cached KEV entries: %w", err)
+ if countCachedKEVErr := s.db.WithContext(ctx).Model(&VulnerabilityThreatIntel{}).Where("known_exploited = ?", true).Count(&cached).Error; countCachedKEVErr != nil {
+ return "", fmt.Errorf("failed to count cached KEV entries: %w", countCachedKEVErr)
}
if len(rows) == 0 || int64(len(rows)) < cached/2 {
return "", fmt.Errorf("KEV catalog looks incomplete (%d entries, %d cached); keeping cached data", len(rows), cached)
}
err = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- if err := tx.Model(&VulnerabilityThreatIntel{}).Where("known_exploited = ?", true).Updates(map[string]any{
+ if updateKEVErr := tx.Model(&VulnerabilityThreatIntel{}).Where("known_exploited = ?", true).Updates(map[string]any{
"known_exploited": false, "kev_date_added": "", "kev_due_date": "", "kev_ransomware": false, "updated_at": now,
- }).Error; err != nil {
- return err
+ }).Error; updateKEVErr != nil {
+ return updateKEVErr
}
return tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "cve_id"}},
@@ -697,7 +697,7 @@ func (s *VulnerabilityService) syncEPSSInternal(ctx context.Context) error {
func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveIDs []string) error {
var resp *http.Response
for attempt := 0; ; attempt++ {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.epssAPIURL+"?cve="+strings.Join(cveIDs, ","), nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.epssAPIURL+"?cve="+strings.Join(cveIDs, ","), http.NoBody)
if err != nil {
return fmt.Errorf("failed to build EPSS request: %w", err)
}
@@ -708,11 +708,11 @@ func (s *VulnerabilityService) fetchEPSSBatchInternal(ctx context.Context, cveID
if resp.StatusCode != http.StatusTooManyRequests || attempt > 0 {
break
}
- if err := resp.Body.Close(); err != nil {
- slog.WarnContext(ctx, "failed to close rate-limited EPSS response", "error", err)
+ if closeErr := resp.Body.Close(); closeErr != nil {
+ slog.WarnContext(ctx, "failed to close rate-limited EPSS response", "error", closeErr)
}
wait := epssMaxRetryAfter
- if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
+ if seconds, atoiErr := strconv.Atoi(resp.Header.Get("Retry-After")); atoiErr == nil {
wait = min(time.Duration(seconds)*time.Second, epssMaxRetryAfter)
}
select {
@@ -812,15 +812,36 @@ func (s *VulnerabilityService) RecordRiskSnapshot(ctx context.Context) error {
UpdatedAt: &now,
}
return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
- if err := tx.Clauses(clause.OnConflict{
- Columns: []clause.Column{{Name: "snapshot_date"}},
- DoUpdates: clause.AssignmentColumns([]string{"scoring_version", "risk_score", "risk_band", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "findings_count", "known_exploited_count", "overdue_known_exploited_count", "high_epss_count", "exposed_critical_high_count", "fixable_count", "images_scanned", "images_total", "scored_images", "updated_at"}),
- }).Create(&snapshot).Error; err != nil {
- return fmt.Errorf("failed to store risk snapshot: %w", err)
- }
- if err := tx.Where("snapshot_date < ?", now.AddDate(0, 0, -riskSnapshotRetentionDays).Format(riskDateLayout)).
- Delete(&VulnerabilityRiskSnapshot{}).Error; err != nil {
- return fmt.Errorf("failed to prune risk snapshots: %w", err)
+ if storeSnapshotErr := tx.Clauses(clause.OnConflict{
+ Columns: []clause.Column{{Name: "snapshot_date"}},
+ DoUpdates: clause.AssignmentColumns(
+ []string{
+ "scoring_version",
+ "risk_score",
+ "risk_band",
+ "critical_count",
+ "high_count",
+ "medium_count",
+ "low_count",
+ "unknown_count",
+ "findings_count",
+ "known_exploited_count",
+ "overdue_known_exploited_count",
+ "high_epss_count",
+ "exposed_critical_high_count",
+ "fixable_count",
+ "images_scanned",
+ "images_total",
+ "scored_images",
+ "updated_at",
+ },
+ ),
+ }).Create(&snapshot).Error; storeSnapshotErr != nil {
+ return fmt.Errorf("failed to store risk snapshot: %w", storeSnapshotErr)
+ }
+ if pruneSnapshotsErr := tx.Where("snapshot_date < ?", now.AddDate(0, 0, -riskSnapshotRetentionDays).Format(riskDateLayout)).
+ Delete(&VulnerabilityRiskSnapshot{}).Error; pruneSnapshotsErr != nil {
+ return fmt.Errorf("failed to prune risk snapshots: %w", pruneSnapshotsErr)
}
return nil
})
diff --git a/backend/internal/vulnerability/vulnerability_trivy.go b/backend/internal/vulnerability/vulnerability_trivy.go
index 2833bc6a1..282e71444 100644
--- a/backend/internal/vulnerability/vulnerability_trivy.go
+++ b/backend/internal/vulnerability/vulnerability_trivy.go
@@ -40,8 +40,8 @@ type trivyRuntimeSecurityInternal struct {
// A nil release without an error means the scan must wait in the queue.
func (s *VulnerabilityService) acquireTrivyScanSlotInternal(ctx context.Context, imageID string, wait bool) (slotID int, release func(), err error) {
- if err := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); err != nil {
- return 0, nil, err
+ if requireFeatureErr := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); requireFeatureErr != nil {
+ return 0, nil, requireFeatureErr
}
var unlock func()
if imageID != "" {
@@ -74,13 +74,13 @@ func (s *VulnerabilityService) acquireTrivyScanSlotInternal(ctx context.Context,
return 0, nil, nil
}
}
- if err := ctx.Err(); err != nil {
+ if cancellationErr := ctx.Err(); cancellationErr != nil {
slotCh <- slotID
- return 0, nil, err
+ return 0, nil, cancellationErr
}
- if err := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); err != nil {
+ if scanFeatureErr := s.settingsService.RequireFeature(ctx, features.VulnerabilityManagement); scanFeatureErr != nil {
slotCh <- slotID
- return 0, nil, err
+ return 0, nil, scanFeatureErr
}
return slotID, func() {
slotCh <- slotID
@@ -284,7 +284,17 @@ func (s *VulnerabilityService) createBatchTrivyContainer(ctx context.Context, sc
// execTrivyScanInContainer runs a trivy scan for a single image inside an
// already-running container via docker exec.
-func (s *VulnerabilityService) execTrivyScanInContainer(ctx context.Context, containerID, imageName, imageID, scannerVersion string, slotID int, files map[string][]byte) (*vulnerability.ScanResult, error) {
+func (
+ s *VulnerabilityService,
+) execTrivyScanInContainer(
+ ctx context.Context,
+ containerID, imageName, imageID, scannerVersion string,
+ slotID int,
+ files map[string][]byte,
+) (
+ *vulnerability.ScanResult,
+ error,
+) {
dockerClient, err := s.dockerService.GetClient(ctx)
if err != nil {
return nil, fmt.Errorf("failed to connect to Docker: %w", err)
@@ -466,7 +476,7 @@ func (s *VulnerabilityService) GetTrivyVersion(ctx context.Context) string {
return ""
}
- if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})
return ""
}
@@ -507,8 +517,8 @@ func (s *VulnerabilityService) GetTrivyVersion(ctx context.Context) string {
waitResult := dockerClient.ContainerWait(ctx, resp.ID, client.ContainerWaitOptions{Condition: containertypes.WaitConditionNotRunning})
var waitResp containertypes.WaitResponse
select {
- case err := <-waitResult.Error:
- if err != nil {
+ case waitErr := <-waitResult.Error:
+ if waitErr != nil {
return ""
}
case waitResp = <-waitResult.Result:
@@ -516,7 +526,7 @@ func (s *VulnerabilityService) GetTrivyVersion(ctx context.Context) string {
closeLogs()
- if err := dockerutils.WaitStdCopy(logDone); err != nil {
+ if waitStdCopyErr := dockerutils.WaitStdCopy(logDone); waitStdCopyErr != nil {
return ""
}
@@ -613,8 +623,8 @@ func (s *VulnerabilityService) resolveTrivyRuntimeOptionsInternal(ctx context.Co
return projects.GetHostPathForContainerPath(ctx, dockerClient, containerPath)
},
func() bool {
- _, err := cgroup.CurrentContainerID()
- return err == nil
+ _, currentContainerIDErr := cgroup.CurrentContainerID()
+ return currentContainerIDErr == nil
},
)
if err != nil {
@@ -673,7 +683,7 @@ func (s *VulnerabilityService) ensureTrivyImageInternal(ctx context.Context) (st
}
scannerImage := s.getTrivyImageRef()
- if _, err := dockerClient.ImageInspect(ctx, scannerImage); err == nil {
+ if _, imageInspectErr := dockerClient.ImageInspect(ctx, scannerImage); imageInspectErr == nil {
return scannerImage, nil
}
@@ -692,9 +702,9 @@ func (s *VulnerabilityService) ensureTrivyImageInternal(ctx context.Context) (st
}
return "", fmt.Errorf("pull scanner image %s: %w", scannerImage, err)
}
- if err := dockerutils.RenderJSONMessageStream(pullReader, io.Discard); err != nil {
+ if renderJSONMessageStreamErr := dockerutils.RenderJSONMessageStream(pullReader, io.Discard); renderJSONMessageStreamErr != nil {
_ = pullReader.Close()
- return "", fmt.Errorf("failed to complete scanner image pull: %w", err)
+ return "", fmt.Errorf("failed to complete scanner image pull: %w", renderJSONMessageStreamErr)
}
_ = pullReader.Close()
@@ -707,7 +717,7 @@ func (s *VulnerabilityService) ensureTrivyCacheVolumeInternal(ctx context.Contex
return "", err
}
- if _, err := dockerClient.VolumeInspect(ctx, trivyCacheVolumeName, client.VolumeInspectOptions{}); err == nil {
+ if _, volumeInspectErr := dockerClient.VolumeInspect(ctx, trivyCacheVolumeName, client.VolumeInspectOptions{}); volumeInspectErr == nil {
return trivyCacheVolumeName, nil
}
@@ -825,10 +835,10 @@ func (s *VulnerabilityService) createAndStartTrivyContainerInternal(
return "", fmt.Errorf("failed to create container: %w", err)
}
- if err := vuln.CopyFilesToContainer(ctx, dockerClient, resp.ID, vuln.ContainerFilesDir, files); err != nil {
+ if copyFilesToContainerErr := vuln.CopyFilesToContainer(ctx, dockerClient, resp.ID, vuln.ContainerFilesDir, files); copyFilesToContainerErr != nil {
if files[vuln.TrivyConfigFile] != nil || files[vuln.TrivyIgnoreFile] != nil {
vuln.RemoveContainer(ctx, dockerClient, resp.ID, "failed to cleanup trivy container after file copy failure")
- return "", fmt.Errorf("failed to copy scan files into container: %w", err)
+ return "", fmt.Errorf("failed to copy scan files into container: %w", copyFilesToContainerErr)
}
// DOCKER_CONFIG may still point at the target directory. When the
// config file is absent, Trivy falls back to anonymous registry access.
@@ -836,26 +846,26 @@ func (s *VulnerabilityService) createAndStartTrivyContainerInternal(
"failed to inject registry credentials into trivy container; continuing anonymously",
"scope", scope,
"containerId", resp.ID,
- "error", err,
+ "error", copyFilesToContainerErr,
)
}
startCtx, startCancel := context.WithTimeout(ctx, timeouts.GetDuration(0, timeouts.DefaultDockerAPI))
defer startCancel()
- if _, err := dockerClient.ContainerStart(startCtx, resp.ID, client.ContainerStartOptions{}); err != nil {
+ if _, containerStartErr := dockerClient.ContainerStart(startCtx, resp.ID, client.ContainerStartOptions{}); containerStartErr != nil {
stdoutLog, stderrLog := vuln.ReadStartupLogs(ctx, dockerClient, resp.ID)
slog.WarnContext(ctx,
"failed to start trivy container",
"scope", scope,
"containerId", resp.ID,
- "error", err,
+ "error", containerStartErr,
"stdout", stdoutLog,
"stderr", stderrLog,
)
vuln.RemoveContainer(ctx, dockerClient, resp.ID, "failed to cleanup trivy container after start failure")
- return "", fmt.Errorf("failed to start container: %w", err)
+ return "", fmt.Errorf("failed to start container: %w", containerStartErr)
}
return resp.ID, nil
@@ -944,23 +954,31 @@ func buildTrivyContainerResourcesInternal(cfg *settings.Settings) mo.Option[cont
return mo.Some(resources)
}
-func (s *VulnerabilityService) runTrivyContainer(
+type trivyContainerResultInternal struct {
+ stdoutFile *os.File
+ stderrFile *os.File
+ duration int64
+ statusCode int64
+ containerID string
+}
+
+func (s *VulnerabilityService) runTrivyContainerInternal(
ctx context.Context,
dockerClient *client.Client,
imageID string,
config *containertypes.Config,
hostConfig *containertypes.HostConfig,
files map[string][]byte,
-) (*os.File, *os.File, int64, int64, string, error) {
+) (trivyContainerResultInternal, error) {
stdoutFile, err := vuln.CreateLogTempFile("trivy-stdout-*")
if err != nil {
- return nil, nil, 0, 0, "", fmt.Errorf("failed to create trivy stdout temp file: %w", err)
+ return trivyContainerResultInternal{}, fmt.Errorf("failed to create trivy stdout temp file: %w", err)
}
stderrFile, err := vuln.CreateLogTempFile("trivy-stderr-*")
if err != nil {
vuln.CleanupLogTempFiles(ctx, stdoutFile)
- return nil, nil, 0, 0, "", fmt.Errorf("failed to create trivy stderr temp file: %w", err)
+ return trivyContainerResultInternal{}, fmt.Errorf("failed to create trivy stderr temp file: %w", err)
}
success := false
@@ -974,7 +992,7 @@ func (s *VulnerabilityService) runTrivyContainer(
containerID, err = s.createAndStartTrivyContainerInternal(ctx, dockerClient, "single-scan", config, hostConfig, files)
if err != nil {
- return nil, nil, 0, 0, "", fmt.Errorf("failed to prepare trivy scan container: %w", err)
+ return trivyContainerResultInternal{}, fmt.Errorf("failed to prepare trivy scan container: %w", err)
}
slog.DebugContext(ctx, "started trivy scan container", "containerId", containerID)
@@ -988,7 +1006,7 @@ func (s *VulnerabilityService) runTrivyContainer(
})
if err != nil {
logsCancel()
- return nil, nil, 0, 0, "", fmt.Errorf("failed to stream trivy logs: %w", err)
+ return trivyContainerResultInternal{}, fmt.Errorf("failed to stream trivy logs: %w", err)
}
var closeLogsOnce sync.Once
@@ -1015,7 +1033,7 @@ func (s *VulnerabilityService) runTrivyContainer(
if logErr := dockerutils.WaitStdCopy(logDone); logErr != nil {
slog.DebugContext(ctx, "trivy log stream ended with error while handling wait failure", "error", logErr)
}
- return nil, nil, 0, 0, "", err
+ return trivyContainerResultInternal{}, err
}
// Wait for the log copy goroutine to complete naturally. On some Docker
@@ -1035,20 +1053,23 @@ func (s *VulnerabilityService) runTrivyContainer(
case logErr := <-logDone:
closeLogs() // clean up context / connection
if logErr != nil && !dockerutils.IsExpectedStreamEndError(logErr) {
- return nil, nil, 0, 0, "", fmt.Errorf("failed to read trivy logs: %w", logErr)
+ return trivyContainerResultInternal{}, fmt.Errorf("failed to read trivy logs: %w", logErr)
}
case <-logDrainTimer.C:
// Stream did not close on its own; force-close so the goroutine exits.
slog.DebugContext(ctx, "trivy log stream did not close after container exit; force-closing", "containerId", containerID)
closeLogs()
if logErr := dockerutils.WaitStdCopy(logDone); logErr != nil {
- return nil, nil, 0, 0, "", fmt.Errorf("failed to read trivy logs: %w", logErr)
+ return trivyContainerResultInternal{}, fmt.Errorf("failed to read trivy logs: %w", logErr)
}
}
duration := time.Since(startTime).Milliseconds()
success = true
- return stdoutFile, stderrFile, duration, statusCode, containerID, nil
+ return trivyContainerResultInternal{
+ stdoutFile: stdoutFile, stderrFile: stderrFile, duration: duration,
+ statusCode: statusCode, containerID: containerID,
+ }, nil
}
func (s *VulnerabilityService) waitForTrivyContainer(
@@ -1142,38 +1163,38 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner
)
s.setScanPhaseInternal(imageID, vulnerability.ScanPhaseCreatingContainer)
- stdoutFile, stderrFile, duration, statusCode, containerID, err := s.runTrivyContainer(ctx, dockerClient, imageID, config, hostConfig, files)
+ containerResult, err := s.runTrivyContainerInternal(ctx, dockerClient, imageID, config, hostConfig, files)
if err != nil {
return nil, err
}
- defer vuln.CleanupLogTempFiles(ctx, stdoutFile, stderrFile)
- defer vuln.RemoveContainer(ctx, dockerClient, containerID, "failed to cleanup trivy scan container")
+ defer vuln.CleanupLogTempFiles(ctx, containerResult.stdoutFile, containerResult.stderrFile)
+ defer vuln.RemoveContainer(ctx, dockerClient, containerResult.containerID, "failed to cleanup trivy scan container")
- if statusCode != 0 {
- errMsg := vuln.ReadTempFileExcerpt(stderrFile)
+ if containerResult.statusCode != 0 {
+ errMsg := vuln.ReadTempFileExcerpt(containerResult.stderrFile)
if errMsg == "" {
- errMsg = vuln.ReadTempFileExcerpt(stdoutFile)
+ errMsg = vuln.ReadTempFileExcerpt(containerResult.stdoutFile)
}
if errMsg == "" {
- errMsg = fmt.Sprintf("exit status %d", statusCode)
+ errMsg = fmt.Sprintf("exit status %d", containerResult.statusCode)
}
slog.WarnContext(ctx,
"trivy scan diagnostics",
"image", imageName,
"imageId", imageID,
"reason", "container non-zero exit",
- "exitCode", statusCode,
- "stdoutBytes", vuln.TempFileSize(stdoutFile),
- "stderrBytes", vuln.TempFileSize(stderrFile),
+ "exitCode", containerResult.statusCode,
+ "stdoutBytes", vuln.TempFileSize(containerResult.stdoutFile),
+ "stderrBytes", vuln.TempFileSize(containerResult.stderrFile),
)
- return nil, vuln.FormatExitError(statusCode, errMsg, imageName)
+ return nil, vuln.FormatExitError(containerResult.statusCode, errMsg, imageName)
}
- trivyOutput, outputErr := vuln.ReadOutputFromContainerFile(ctx, dockerClient, containerID, outputPath)
+ trivyOutput, outputErr := vuln.ReadOutputFromContainerFile(ctx, dockerClient, containerResult.containerID, outputPath)
if outputErr != nil {
slog.WarnContext(ctx,
"failed to read trivy output file from single-scan container; falling back to stdout parsing",
- "containerId", containerID,
+ "containerId", containerResult.containerID,
"outputPath", outputPath,
"error", outputErr,
)
@@ -1183,19 +1204,19 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner
if len(trivyOutput) > 0 {
trivyReport, err = vuln.DecodeReportFromBytes(trivyOutput)
} else {
- trivyReport, err = vuln.DecodeReportFromFile(stdoutFile)
+ trivyReport, err = vuln.DecodeReportFromFile(containerResult.stdoutFile)
}
if err != nil {
if errors.Is(err, io.EOF) {
- errMsg := cmp.Or(vuln.ReadTempFileExcerpt(stderrFile), "trivy scan produced no output")
+ errMsg := cmp.Or(vuln.ReadTempFileExcerpt(containerResult.stderrFile), "trivy scan produced no output")
slog.WarnContext(ctx,
"trivy scan diagnostics",
"image", imageName,
"imageId", imageID,
"reason", "container empty output",
- "exitCode", statusCode,
- "stdoutBytes", vuln.TempFileSize(stdoutFile),
- "stderrBytes", vuln.TempFileSize(stderrFile),
+ "exitCode", containerResult.statusCode,
+ "stdoutBytes", vuln.TempFileSize(containerResult.stdoutFile),
+ "stderrBytes", vuln.TempFileSize(containerResult.stderrFile),
)
return nil, fmt.Errorf("trivy scan failed: %s", errMsg)
}
@@ -1205,31 +1226,31 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner
"image", imageName,
"imageId", imageID,
"reason", "container parse error",
- "exitCode", statusCode,
- "stdoutBytes", vuln.TempFileSize(stdoutFile),
- "stderrBytes", vuln.TempFileSize(stderrFile),
+ "exitCode", containerResult.statusCode,
+ "stdoutBytes", vuln.TempFileSize(containerResult.stdoutFile),
+ "stderrBytes", vuln.TempFileSize(containerResult.stderrFile),
)
return nil, fmt.Errorf("failed to parse trivy output: %w", err)
}
if trivyReport == nil {
- errMsg := cmp.Or(vuln.ReadTempFileExcerpt(stderrFile), "trivy scan produced no output")
+ errMsg := cmp.Or(vuln.ReadTempFileExcerpt(containerResult.stderrFile), "trivy scan produced no output")
slog.WarnContext(ctx,
"trivy scan diagnostics",
"image", imageName,
"imageId", imageID,
"reason", "container nil report",
- "exitCode", statusCode,
- "stdoutBytes", vuln.TempFileSize(stdoutFile),
- "stderrBytes", vuln.TempFileSize(stderrFile),
+ "exitCode", containerResult.statusCode,
+ "stdoutBytes", vuln.TempFileSize(containerResult.stdoutFile),
+ "stderrBytes", vuln.TempFileSize(containerResult.stderrFile),
)
return nil, fmt.Errorf("trivy scan failed: %s", errMsg)
}
// Convert Trivy report to our ScanResult format
- result := vulnerability.ConvertTrivyReportToScanResult(trivyReport, imageID, time.Now(), duration)
+ result := vulnerability.ConvertTrivyReportToScanResult(trivyReport, imageID, time.Now(), containerResult.duration)
result.ScannerVersion = s.GetTrivyVersion(ctx)
- result.HasReport = s.persistRawTrivyReportInternal(ctx, imageID, trivyOutput, stdoutFile)
+ result.HasReport = s.persistRawTrivyReportInternal(ctx, imageID, trivyOutput, containerResult.stdoutFile)
totalVulnerabilities := 0
if result.Summary != nil {
totalVulnerabilities = result.Summary.Total
@@ -1239,7 +1260,7 @@ func (s *VulnerabilityService) runTrivyScanInternal(ctx context.Context, scanner
"trivy scan finished",
"imageId", imageID,
"imageName", imageName,
- "durationMs", duration,
+ "durationMs", containerResult.duration,
"status", result.Status,
"vulnerabilities", totalVulnerabilities,
)
@@ -1262,8 +1283,8 @@ func (s *VulnerabilityService) getTrivyCPUCapabilitiesInternal(ctx context.Conte
if err != nil {
slog.WarnContext(ctx, "failed to read cached Trivy CPU capabilities", "error", err)
} else if found {
- if err := json.Unmarshal([]byte(raw), &cached); err != nil || cached.FetchedAt.IsZero() {
- slog.WarnContext(ctx, "ignoring invalid cached Trivy CPU capabilities", "error", err)
+ if unmarshalErr := json.Unmarshal([]byte(raw), &cached); unmarshalErr != nil || cached.FetchedAt.IsZero() {
+ slog.WarnContext(ctx, "ignoring invalid cached Trivy CPU capabilities", "error", unmarshalErr)
cached = trivyCPUCapabilitiesInternal{}
} else if age := time.Since(cached.FetchedAt); age >= 0 && age < trivyCPUCapabilitiesCacheTTL {
return cached, nil
@@ -1292,12 +1313,12 @@ func (s *VulnerabilityService) getTrivyCPUCapabilitiesInternal(ctx context.Conte
FetchedAt: time.Now().UTC(),
}
if s.kvService != nil {
- payload, err := json.Marshal(capabilities)
- if err == nil {
- err = s.kvService.Set(ctx, key, string(payload))
+ payload, marshalErr := json.Marshal(capabilities)
+ if marshalErr == nil {
+ marshalErr = s.kvService.Set(ctx, key, string(payload))
}
- if err != nil {
- slog.WarnContext(ctx, "failed to cache Trivy CPU capabilities", "error", err)
+ if marshalErr != nil {
+ slog.WarnContext(ctx, "failed to cache Trivy CPU capabilities", "error", marshalErr)
}
}
return capabilities, nil
diff --git a/backend/internal/webhook/webhook.go b/backend/internal/webhook/webhook.go
index 2df0e178c..0ad75f177 100644
--- a/backend/internal/webhook/webhook.go
+++ b/backend/internal/webhook/webhook.go
@@ -69,7 +69,15 @@ type WebhookService struct {
environmentService *environment.EnvironmentService
}
-func NewWebhookService(db *database.DB, containerService *container.ContainerService, updaterService *updater.UpdaterService, projectService *project.ProjectService, gitOpsSyncService *gitops.GitOpsSyncService, eventService *event.EventService, environmentService *environment.EnvironmentService) *WebhookService {
+func NewWebhookService(
+ db *database.DB,
+ containerService *container.ContainerService,
+ updaterService *updater.UpdaterService,
+ projectService *project.ProjectService,
+ gitOpsSyncService *gitops.GitOpsSyncService,
+ eventService *event.EventService,
+ environmentService *environment.EnvironmentService,
+) *WebhookService {
return &WebhookService{
db: db,
containerService: containerService,
@@ -260,8 +268,8 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, ac
s.tokenWriteMu.Lock()
defer s.tokenWriteMu.Unlock()
- if err := s.db.WithContext(ctx).Create(wh).Error; err != nil {
- return nil, "", fmt.Errorf("failed to create webhook: %w", err)
+ if createWebhookErr := s.db.WithContext(ctx).Create(wh).Error; createWebhookErr != nil {
+ return nil, "", fmt.Errorf("failed to create webhook: %w", createWebhookErr)
}
s.tokenMu.Lock()
@@ -354,25 +362,25 @@ func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, w
name, err := s.containerService.GetContainerNameByID(ctx, wh.TargetID)
return kit.Ternary(err != nil, "", name)
case WebhookTargetTypeProject:
- var project project.Project
+ var localProject project.Project
if err := s.db.WithContext(ctx).
Select("name").
Where("id = ?", wh.TargetID).
- First(&project).Error; err != nil {
+ First(&localProject).Error; err != nil {
return ""
}
- return project.Name
+ return localProject.Name
case WebhookTargetTypeUpdater:
return "Environment updater"
case WebhookTargetTypeGitOps:
- var sync project.GitOpsSync
+ var localSync project.GitOpsSync
if err := s.db.WithContext(ctx).
Select("name").
Where("id = ? AND environment_id = ?", wh.TargetID, wh.EnvironmentID).
- First(&sync).Error; err != nil {
+ First(&localSync).Error; err != nil {
return ""
}
- return sync.Name
+ return localSync.Name
default:
return ""
}
@@ -447,8 +455,8 @@ func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID st
return nil, fmt.Errorf("failed to get webhook: %w", err)
}
- if err := s.db.WithContext(ctx).Model(&wh).Update("enabled", enabled).Error; err != nil {
- return nil, fmt.Errorf("failed to update webhook: %w", err)
+ if updateWebhookErr := s.db.WithContext(ctx).Model(&wh).Update("enabled", enabled).Error; updateWebhookErr != nil {
+ return nil, fmt.Errorf("failed to update webhook: %w", updateWebhookErr)
}
if s.eventService != nil {
@@ -481,10 +489,10 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) er
// Narrow by prefix first (indexed), then verify hash
var candidates []Webhook
- if err := s.db.WithContext(ctx).
+ if findWebhookErr := s.db.WithContext(ctx).
Where("token_prefix = ?", prefix).
- Find(&candidates).Error; err != nil {
- return fmt.Errorf("failed to look up webhook: %w", err)
+ Find(&candidates).Error; findWebhookErr != nil {
+ return fmt.Errorf("failed to look up webhook: %w", findWebhookErr)
}
hash := kit.SHA256Hex(rawToken)
@@ -518,9 +526,9 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) er
slog.ErrorContext(execCtx, "webhook action panicked", "webhookID", wh.ID, "webhookName", wh.Name, "actionType", actionType, "error", panicErr)
}
}()
- if _, err := s.executeWebhookActionInternal(execCtx, wh, actionType); err != nil {
+ if _, executeWebhookActionErr := s.executeWebhookActionInternal(execCtx, wh, actionType); executeWebhookActionErr != nil {
// Action failures are recorded as error events by wrapWebhookActionErrorInternal.
- slog.ErrorContext(execCtx, "webhook action failed", "webhookID", wh.ID, "webhookName", wh.Name, "actionType", actionType, "error", err)
+ slog.ErrorContext(execCtx, "webhook action failed", "webhookID", wh.ID, "webhookName", wh.Name, "actionType", actionType, "error", executeWebhookActionErr)
return
}
s.logWebhookEventInternal(execCtx, wh, actionType, event.EventSeveritySuccess, "")
@@ -614,14 +622,14 @@ func (s *WebhookService) executeRemoteWebhookActionInternal(ctx context.Context,
var result *updatertypes.Result
if wantResult {
var out base.ApiResponse[*updatertypes.Result]
- if err := s.environmentService.ProxyJSONRequest(ctx, wh.EnvironmentID, method, path, nil, &out); err != nil {
- return nil, s.wrapWebhookActionErrorInternal(ctx, wh, wh.TargetType, actionType, err)
+ if proxyJSONRequestErr := s.environmentService.ProxyJSONRequest(ctx, wh.EnvironmentID, method, path, nil, &out); proxyJSONRequestErr != nil {
+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, wh.TargetType, actionType, proxyJSONRequestErr)
}
result = out.Data
} else {
var out base.ApiResponse[any]
- if err := s.environmentService.ProxyJSONRequest(ctx, wh.EnvironmentID, method, path, nil, &out); err != nil {
- return nil, s.wrapWebhookActionErrorInternal(ctx, wh, wh.TargetType, actionType, err)
+ if proxyServiceActionErr := s.environmentService.ProxyJSONRequest(ctx, wh.EnvironmentID, method, path, nil, &out); proxyServiceActionErr != nil {
+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, wh.TargetType, actionType, proxyServiceActionErr)
}
}
@@ -636,29 +644,29 @@ func (s *WebhookService) executeContainerWebhookActionInternal(ctx context.Conte
switch actionType {
case WebhookActionTypeUpdate:
- result, err := s.updaterService.UpdateSingleContainer(ctx, containerID)
- if err != nil {
- return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)
+ result, updateSingleContainerErr := s.updaterService.UpdateSingleContainer(ctx, containerID)
+ if updateSingleContainerErr != nil {
+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, updateSingleContainerErr)
}
return result, nil
case WebhookActionTypeStart:
- if err := s.containerService.StartContainer(ctx, containerID, common.SystemUser); err != nil {
- return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)
+ if startContainerErr := s.containerService.StartContainer(ctx, containerID, common.SystemUser); startContainerErr != nil {
+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, startContainerErr)
}
return nil, nil
case WebhookActionTypeStop:
- if err := s.containerService.StopContainer(ctx, containerID, common.SystemUser); err != nil {
- return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)
+ if stopContainerErr := s.containerService.StopContainer(ctx, containerID, common.SystemUser); stopContainerErr != nil {
+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, stopContainerErr)
}
return nil, nil
case WebhookActionTypeRestart:
- if err := s.containerService.RestartContainer(ctx, containerID, common.SystemUser); err != nil {
- return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)
+ if restartContainerErr := s.containerService.RestartContainer(ctx, containerID, common.SystemUser); restartContainerErr != nil {
+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, restartContainerErr)
}
return nil, nil
case WebhookActionTypeRedeploy:
- if _, err := s.containerService.RedeployContainer(ctx, containerID, common.SystemUser); err != nil {
- return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)
+ if _, redeployContainerErr := s.containerService.RedeployContainer(ctx, containerID, common.SystemUser); redeployContainerErr != nil {
+ return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, redeployContainerErr)
}
return nil, nil
default:
diff --git a/backend/internal/webhook/webhook_test.go b/backend/internal/webhook/webhook_test.go
index 8a1fa782f..fb93bf976 100644
--- a/backend/internal/webhook/webhook_test.go
+++ b/backend/internal/webhook/webhook_test.go
@@ -62,7 +62,7 @@ func newTestWebhookService(db *database.DB) *WebhookService {
func fetchWebhook(t *testing.T, db *database.DB, id string) Webhook {
t.Helper()
var wh Webhook
- require.NoError(t, db.WithContext(context.Background()).Where("id = ?", id).First(&wh).Error)
+ require.NoError(t, db.WithContext(t.Context()).Where("id = ?", id).First(&wh).Error)
return wh
}
@@ -134,7 +134,7 @@ func TestParseWebhookPrefix_LeadingWhitespaceStripped(t *testing.T) {
}
func TestIsKnownToken_StoredIdentity(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
wh, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})
@@ -164,7 +164,7 @@ func TestIsKnownToken_StoredIdentity(t *testing.T) {
}
func TestKnownTokenRateLimit_ExhaustedIPDoesNotBlockFirstUse(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
_, first, err := svc.CreateWebhook(ctx, "first", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})
@@ -183,7 +183,7 @@ func TestKnownTokenRateLimit_ExhaustedIPDoesNotBlockFirstUse(t *testing.T) {
router.Use(middleware.PerTokenRateLimitForPaths([]string{"/trigger/:token"}, 1, 1, svc.IsKnownToken))
router.POST("/trigger/:token", func(c *echo.Context) error { return c.NoContent(http.StatusAccepted) })
request := func(token string) int {
- req := httptest.NewRequest(http.MethodPost, "/trigger/"+token, nil)
+ req := httptest.NewRequest(http.MethodPost, "/trigger/"+token, http.NoBody)
req.RemoteAddr = "192.0.2.10:4000"
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
@@ -202,7 +202,7 @@ func TestKnownTokenRateLimit_ExhaustedIPDoesNotBlockFirstUse(t *testing.T) {
}
func TestLoadTokenHashes_FailurePreservesIndex(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
_, raw, err := svc.CreateWebhook(ctx, "known", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})
@@ -217,12 +217,15 @@ func TestLoadTokenHashes_FailurePreservesIndex(t *testing.T) {
}
func TestKnownTokenIndex_ConcurrentReloadAndCRUD(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
svc := newTestWebhookService(setupWebhookServiceTestDB(t))
var workers sync.WaitGroup
workers.Go(func() {
for range 30 {
- assert.NoError(t, svc.LoadTokenHashes(ctx))
+ if err := svc.LoadTokenHashes(ctx); err != nil {
+ t.Errorf("reload token hashes: %v", err)
+ return
+ }
svc.IsKnownToken("arc_wh_unknown")
}
})
@@ -239,7 +242,7 @@ func TestKnownTokenIndex_ConcurrentReloadAndCRUD(t *testing.T) {
// --- CreateWebhook ---
func TestCreateWebhook_TokenNotStoredInPlaintext(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -253,7 +256,7 @@ func TestCreateWebhook_TokenNotStoredInPlaintext(t *testing.T) {
}
func TestCreateWebhook_PrefixMatchesToken(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -270,7 +273,7 @@ func TestCreateWebhook_PrefixMatchesToken(t *testing.T) {
}
func TestCreateWebhook_InvalidTargetTypeRejected(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -279,7 +282,7 @@ func TestCreateWebhook_InvalidTargetTypeRejected(t *testing.T) {
}
func TestCreateWebhook_EmptyTargetIDRejectedForNonUpdaterTypes(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -294,7 +297,7 @@ func TestCreateWebhook_EmptyTargetIDRejectedForNonUpdaterTypes(t *testing.T) {
}
func TestCreateWebhook_InvalidActionTypeRejected(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -303,7 +306,7 @@ func TestCreateWebhook_InvalidActionTypeRejected(t *testing.T) {
}
func TestCreateWebhook_EmptyActionTypeDefaultsPerTarget(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -317,7 +320,7 @@ func TestCreateWebhook_EmptyActionTypeDefaultsPerTarget(t *testing.T) {
}
func TestCreateWebhook_EmptyTargetIDAcceptedForUpdaterType(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -327,7 +330,7 @@ func TestCreateWebhook_EmptyTargetIDAcceptedForUpdaterType(t *testing.T) {
}
func TestCreateWebhook_ContainerTypeAccepted(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -338,7 +341,7 @@ func TestCreateWebhook_ContainerTypeAccepted(t *testing.T) {
}
func TestCreateWebhook_ProjectTypeAccepted(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -349,7 +352,7 @@ func TestCreateWebhook_ProjectTypeAccepted(t *testing.T) {
}
func TestCreateWebhook_UpdaterTypeAccepted(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -360,7 +363,7 @@ func TestCreateWebhook_UpdaterTypeAccepted(t *testing.T) {
}
func TestCreateWebhook_GitOpsTypeAccepted(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -371,7 +374,7 @@ func TestCreateWebhook_GitOpsTypeAccepted(t *testing.T) {
}
func TestCreateWebhook_EnabledByDefault(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -381,7 +384,7 @@ func TestCreateWebhook_EnabledByDefault(t *testing.T) {
}
func TestCreateWebhook_UniqueTokensEachCall(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -396,7 +399,7 @@ func TestCreateWebhook_UniqueTokensEachCall(t *testing.T) {
// --- ListWebhooks ---
func TestListWebhooks_ScopedToEnvironment(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -412,7 +415,7 @@ func TestListWebhooks_ScopedToEnvironment(t *testing.T) {
}
func TestListWebhooks_EmptyForUnknownEnvironment(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -422,7 +425,7 @@ func TestListWebhooks_EmptyForUnknownEnvironment(t *testing.T) {
}
func TestListWebhookSummaries_ResolvesTargetNames(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -454,7 +457,7 @@ func TestListWebhookSummaries_ResolvesTargetNames(t *testing.T) {
}
func TestListWebhookSummaries_DefaultsLegacyActionType(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -479,7 +482,7 @@ func TestListWebhookSummaries_DefaultsLegacyActionType(t *testing.T) {
// --- GetWebhookByID ---
func TestGetWebhookByID_ReturnsCorrectWebhook(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -492,7 +495,7 @@ func TestGetWebhookByID_ReturnsCorrectWebhook(t *testing.T) {
}
func TestGetWebhookByID_NotFoundForWrongEnvironment(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -504,7 +507,7 @@ func TestGetWebhookByID_NotFoundForWrongEnvironment(t *testing.T) {
}
func TestGetWebhookByID_NotFoundForUnknownID(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -515,7 +518,7 @@ func TestGetWebhookByID_NotFoundForUnknownID(t *testing.T) {
// --- DeleteWebhook ---
func TestDeleteWebhook_RemovesRecord(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -529,7 +532,7 @@ func TestDeleteWebhook_RemovesRecord(t *testing.T) {
}
func TestDeleteWebhook_NotFoundForWrongEnvironment(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -545,7 +548,7 @@ func TestDeleteWebhook_NotFoundForWrongEnvironment(t *testing.T) {
}
func TestDeleteWebhook_NotFoundForUnknownID(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -556,7 +559,7 @@ func TestDeleteWebhook_NotFoundForUnknownID(t *testing.T) {
// --- UpdateWebhook ---
func TestUpdateWebhook_DisableAndEnable(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -574,7 +577,7 @@ func TestUpdateWebhook_DisableAndEnable(t *testing.T) {
}
func TestUpdateWebhook_NotFoundForWrongEnvironment(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -586,7 +589,7 @@ func TestUpdateWebhook_NotFoundForWrongEnvironment(t *testing.T) {
}
func TestUpdateWebhook_NotFoundForUnknownID(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -597,7 +600,7 @@ func TestUpdateWebhook_NotFoundForUnknownID(t *testing.T) {
// --- TriggerByToken ---
func TestTriggerByToken_InvalidFormat(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -606,7 +609,7 @@ func TestTriggerByToken_InvalidFormat(t *testing.T) {
}
func TestTriggerByToken_NotFound(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -617,7 +620,7 @@ func TestTriggerByToken_NotFound(t *testing.T) {
}
func TestTriggerByToken_WrongHash_NotFound(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -637,7 +640,7 @@ func TestTriggerByToken_WrongHash_NotFound(t *testing.T) {
}
func TestTriggerByToken_DisabledWebhook(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -651,7 +654,7 @@ func TestTriggerByToken_DisabledWebhook(t *testing.T) {
}
func TestTriggerByToken_UnknownTargetType_ReturnsInvalidType(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -696,7 +699,7 @@ func insertWebhookDirect(t *testing.T, ctx context.Context, db *database.DB, raw
}
func TestTriggerByToken_AcceptsImmediatelyAndRecordsTriggerTime(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db) // action services are nil; the async action fails, acceptance must not
@@ -712,7 +715,7 @@ func TestTriggerByToken_AcceptsImmediatelyAndRecordsTriggerTime(t *testing.T) {
}
func TestTriggerByToken_DoesNotUpdateLastTriggeredAtOnError(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
@@ -727,7 +730,7 @@ func TestTriggerByToken_DoesNotUpdateLastTriggeredAtOnError(t *testing.T) {
}
func TestTriggerByToken_UnknownActionType_ReturnsInvalidAction(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.go
index 13bb83acc..cd50e0a1c 100644
--- a/backend/pkg/authz/access_policy.go
+++ b/backend/pkg/authz/access_policy.go
@@ -92,8 +92,28 @@ var accessSurfacesInternal = []AccessSurface{
routeSurfaceInternal("route.events", "/events", "Events", AccessScopeModeGlobalOnly, []string{PermEventsRead}, 110),
routeSurfaceInternal("route.activities", "", "Activities", AccessScopeModeAnyEffectiveScope, []string{PermActivitiesRead}, 0),
allOfRouteSurfaceInternal("route.oidc-role-mappings", "", "OIDC Role Mappings", AllPermissions()),
- routeSurfaceInternal("route.customize.templates.create", "/customize/templates/create", "Create template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
- routeSurfaceInternal("route.customize.templates.default", "/customize/templates/default", "Default template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
+ routeSurfaceInternal("route.customize.templates.create",
+ "/customize/templates/create",
+ "Create template",
+ AccessScopeModeGlobalOnly,
+ []string{
+ PermCustomizeManage,
+ PermTemplatesList,
+ PermTemplatesRead,
+ },
+ 0),
+
+ routeSurfaceInternal("route.customize.templates.default",
+ "/customize/templates/default",
+ "Default template",
+ AccessScopeModeGlobalOnly,
+ []string{
+ PermCustomizeManage,
+ PermTemplatesList,
+ PermTemplatesRead,
+ },
+ 0),
+
routeSurfaceInternal("route.customize.templates.detail", "/customize/templates/{id}", "Template", AccessScopeModeGlobalOnly, []string{PermCustomizeManage, PermTemplatesList, PermTemplatesRead}, 0),
allOfRouteSurfaceInternal("route.customize.registries.browse", "/customize/registries/{id}", "Registry browser", []string{PermRegistriesRead, PermRegistriesBrowse}),
diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.go
index cba8a2087..4a20e711f 100644
--- a/backend/pkg/authz/catalog.go
+++ b/backend/pkg/authz/catalog.go
@@ -201,7 +201,13 @@ var permissionCatalog = []PermissionCatalogResource{
{"update", PermGitOpsUpdate, "Update", ""},
{"delete", PermGitOpsDelete, "Delete", ""},
{"sync", PermGitOpsSync, "Trigger sync", ""},
- {"lifecycle", PermGitOpsLifecycle, "Configure pre-deploy hooks", "Create or modify a sync's pre-deploy lifecycle hook, which runs an arbitrary container with host bind mounts and env on every sync"},
+ {
+ "lifecycle",
+ PermGitOpsLifecycle,
+ "Configure pre-deploy hooks",
+ "Create or modify a sync's pre-deploy lifecycle hook, which runs an arbitrary container with host bind mounts and env on every sync",
+ },
+
{"backup", PermGitOpsBackup, "Back up to Git", "View a project's Git backup preview and history, and manage the backup together with the matching sync permission (create, update, sync, delete)"},
}},
{"webhooks", "Webhooks", PermissionScopeEnv, []PermissionCatalogAction{
diff --git a/backend/pkg/authz/permission_matcher_huma.go b/backend/pkg/authz/permission_matcher_huma.go
index 859ecd58a..245edb5f6 100644
--- a/backend/pkg/authz/permission_matcher_huma.go
+++ b/backend/pkg/authz/permission_matcher_huma.go
@@ -44,7 +44,7 @@ func (m *PermissionMatcher) CollectFromHumaAPI(humaAPI huma.API) {
if op == nil {
continue
}
- if perm, ok := requiredPermissionInternal(op).Get(); ok {
+ if perm, localOk := requiredPermissionInternal(op).Get(); localOk {
m.Add(method, suffix, perm)
continue
}
diff --git a/backend/pkg/authz/permission_set.go b/backend/pkg/authz/permission_set.go
index e8946d600..817d967ac 100644
--- a/backend/pkg/authz/permission_set.go
+++ b/backend/pkg/authz/permission_set.go
@@ -31,7 +31,7 @@ func (ps *PermissionSet) Allows(perm, envID string) bool {
return false
}
if env, ok := ps.PerEnv[envID]; ok {
- if _, ok := env[perm]; ok {
+ if _, localOk := env[perm]; localOk {
return true
}
}
diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.go
index 39bf3016e..8bf880a4f 100644
--- a/backend/pkg/authz/permissions.go
+++ b/backend/pkg/authz/permissions.go
@@ -332,7 +332,21 @@ func BuiltInEditorPermissions() []string {
PermS3DestinationsList, PermS3DestinationsRead,
PermEventsRead,
// Full env-scoped Docker management
- PermContainersList, PermContainersRead, PermContainersLogs, PermContainersCreate, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersEdit, PermContainersKill, PermContainersPause, PermContainersDelete, PermContainersExec, PermContainersAutoUpdate,
+ PermContainersList,
+ PermContainersRead,
+ PermContainersLogs,
+ PermContainersCreate,
+ PermContainersStart,
+ PermContainersStop,
+ PermContainersRestart,
+ PermContainersRedeploy,
+ PermContainersEdit,
+ PermContainersKill,
+ PermContainersPause,
+ PermContainersDelete,
+ PermContainersExec,
+ PermContainersAutoUpdate,
+
PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsCreate, PermProjectsUpdate, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart, PermProjectsDelete, PermProjectsArchive,
PermImagesList, PermImagesRead, PermImagesPull, PermImagesPush, PermImagesBuild, PermImagesTag, PermImagesCommit, PermImagesPrune, PermImagesDelete, PermImagesUpload, PermImagesPatch,
PermVolumesList, PermVolumesRead, PermVolumesCreate, PermVolumesRename, PermVolumesDelete, PermVolumesPrune, PermVolumesUpload, PermVolumesBackup,
@@ -359,7 +373,17 @@ func BuiltInDeployerPermissions() []string {
PermTemplatesList, PermTemplatesRead,
PermVariablesRead,
PermEventsRead,
- PermContainersList, PermContainersRead, PermContainersLogs, PermContainersStart, PermContainersStop, PermContainersRestart, PermContainersRedeploy, PermContainersEdit, PermContainersKill, PermContainersPause,
+ PermContainersList,
+ PermContainersRead,
+ PermContainersLogs,
+ PermContainersStart,
+ PermContainersStop,
+ PermContainersRestart,
+ PermContainersRedeploy,
+ PermContainersEdit,
+ PermContainersKill,
+ PermContainersPause,
+
PermProjectsList, PermProjectsRead, PermProjectsLogs, PermProjectsDeploy, PermProjectsDown, PermProjectsRestart,
PermImagesList, PermImagesRead, PermImagesPull, PermImagesTag, PermImagesCommit,
PermVolumesList, PermVolumesRead,
diff --git a/backend/pkg/dockerutil/exec.go b/backend/pkg/dockerutil/exec.go
index 988290b0f..50e525a52 100644
--- a/backend/pkg/dockerutil/exec.go
+++ b/backend/pkg/dockerutil/exec.go
@@ -67,8 +67,8 @@ func ExecInContainer(ctx context.Context, dockerClient *client.Client, container
defer stopClose()
copyErr := WaitStdCopy(StartStdCopy(attachResp.Reader, stdout, stderr))
- if err := ctx.Err(); err != nil {
- return 0, fmt.Errorf("failed to read exec output: %w", err)
+ if errErr := ctx.Err(); errErr != nil {
+ return 0, fmt.Errorf("failed to read exec output: %w", errErr)
}
if copyErr != nil {
return 0, fmt.Errorf("failed to read exec output: %w", copyErr)
diff --git a/backend/pkg/dockerutil/log_stream.go b/backend/pkg/dockerutil/log_stream.go
index fb9b2408b..a6c83bc30 100644
--- a/backend/pkg/dockerutil/log_stream.go
+++ b/backend/pkg/dockerutil/log_stream.go
@@ -123,14 +123,14 @@ func ReadAllLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- string
}
if stdoutBuf.Len() > 0 {
- if err := readLogLinesInternal(ctx, strings.NewReader(stdoutBuf.String()), logsChan, ""); err != nil {
- return err
+ if readLogLinesErr := readLogLinesInternal(ctx, strings.NewReader(stdoutBuf.String()), logsChan, ""); readLogLinesErr != nil {
+ return readLogLinesErr
}
}
if stderrBuf.Len() > 0 {
- if err := readLogLinesInternal(ctx, strings.NewReader(stderrBuf.String()), logsChan, "[STDERR] "); err != nil {
- return err
+ if readLogLinesErr2 := readLogLinesInternal(ctx, strings.NewReader(stderrBuf.String()), logsChan, "[STDERR] "); readLogLinesErr2 != nil {
+ return readLogLinesErr2
}
}
@@ -146,7 +146,7 @@ func readLogLinesInternal(ctx context.Context, reader io.Reader, logsChan chan<-
}
line, err := bufferedReader.ReadString('\n')
- if len(line) > 0 {
+ if line != "" {
trimmed := strings.TrimRight(line, "\r\n")
if trimmed != "" {
if prefix != "" {
diff --git a/backend/pkg/dockerutil/log_stream_test.go b/backend/pkg/dockerutil/log_stream_test.go
index e1deaa6c6..fd7837e2c 100644
--- a/backend/pkg/dockerutil/log_stream_test.go
+++ b/backend/pkg/dockerutil/log_stream_test.go
@@ -93,7 +93,7 @@ func TestStreamMultiplexedLogsContextCancelDoesNotDeadlock(t *testing.T) {
writeDockerLogFrameInternal(t, &stream, 1, "line 3\n")
logsChan := make(chan string, 1)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
done := make(chan error, 1)
@@ -117,7 +117,7 @@ func TestStreamMultiplexedLogsContextCancelDoesNotDeadlock(t *testing.T) {
func TestReadAllLogsContextCancelClosesReader(t *testing.T) {
logsChan := make(chan string, 1)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
reader := &blockingReadCloserInternal{readStarted: make(chan struct{}), closeCalled: make(chan struct{})}
diff --git a/backend/pkg/dockerutil/mount_utils_test.go b/backend/pkg/dockerutil/mount_utils_test.go
index 0e5acfbf2..849c880c6 100644
--- a/backend/pkg/dockerutil/mount_utils_test.go
+++ b/backend/pkg/dockerutil/mount_utils_test.go
@@ -252,7 +252,7 @@ func TestMountForEnclosingPath(t *testing.T) {
enclosing, relative = MountForEnclosingPath(mounts, "/app/data", "/restore")
require.Equal(t, "arcane-data", enclosing.Source)
- require.Equal(t, "", relative)
+ require.Empty(t, relative)
enclosing, _ = MountForEnclosingPath(mounts, "/app/data/tmp/x", "/restore")
require.Nil(t, enclosing)
diff --git a/backend/pkg/dockerutil/network_utils_test.go b/backend/pkg/dockerutil/network_utils_test.go
index 620b9b74b..8fe689120 100644
--- a/backend/pkg/dockerutil/network_utils_test.go
+++ b/backend/pkg/dockerutil/network_utils_test.go
@@ -1,7 +1,6 @@
package docker
import (
- "context"
"net/http"
"net/http/httptest"
"strings"
@@ -65,7 +64,9 @@ func TestSelectDockerHostReachableNetworkMode(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/containers/json") {
- _, _ = w.Write([]byte(`[{"Id":"proxy1","Names":["/myproj-socket-proxy-1"],"Labels":{"com.docker.compose.service":"socket-proxy"},"State":"running","NetworkSettings":{"Networks":{"myproj_socket-proxy-net":{"Aliases":["socket-proxy"]}}}}]`))
+ _, _ = w.Write([]byte("[{\"Id\":\"proxy1\",\"Names\":[\"/myproj-socket-proxy-1\"],\"Labels\":{\"com.docker.compose.service\":\"socket-pr" +
+ "oxy\"},\"State\":\"running\",\"NetworkSettings\":{\"Networks\":{\"myproj_socket-proxy-net\":{\"Aliases\":[\"socket" +
+ "-proxy\"]}}}}]"))
return
}
w.WriteHeader(http.StatusOK)
@@ -79,12 +80,12 @@ func TestSelectDockerHostReachableNetworkMode(t *testing.T) {
defer func() { _ = dockerClient.Close() }()
t.Run("prefers shared network with the DOCKER_HOST container", func(t *testing.T) {
- got := SelectDockerHostReachableNetworkMode(context.Background(), dockerClient, inspect, "tcp://socket-proxy:2375")
+ got := SelectDockerHostReachableNetworkMode(t.Context(), dockerClient, inspect, "tcp://socket-proxy:2375")
require.Equal(t, "myproj_socket-proxy-net", got)
})
t.Run("falls back to auto heuristic when nothing matches", func(t *testing.T) {
- got := SelectDockerHostReachableNetworkMode(context.Background(), dockerClient, inspect, "tcp://unknown-host:2375")
+ got := SelectDockerHostReachableNetworkMode(t.Context(), dockerClient, inspect, "tcp://unknown-host:2375")
require.Equal(t, "cloudflare-tunnel", got)
})
}
diff --git a/backend/pkg/dockerutil/render_test.go b/backend/pkg/dockerutil/render_test.go
index 81acc906e..80e6fa997 100644
--- a/backend/pkg/dockerutil/render_test.go
+++ b/backend/pkg/dockerutil/render_test.go
@@ -10,7 +10,8 @@ import (
func TestRenderJSONMessageStream(t *testing.T) {
t.Run("renders docker CLI text for pull messages", func(t *testing.T) {
- stream := strings.NewReader("{\"status\":\"Pulling from library/nginx\",\"id\":\"stable-alpine\"}\n{\"status\":\"Pull complete\",\"id\":\"abc123\"}\n{\"status\":\"Status: Downloaded newer image for nginx:stable-alpine\"}\n")
+ stream := strings.NewReader("{\"status\":\"Pulling from library/nginx\",\"id\":\"stable-alpine\"}\n{\"status\":\"Pull complete\",\"id\":\"abc123\"" +
+ "}\n{\"status\":\"Status: Downloaded newer image for nginx:stable-alpine\"}\n")
var out strings.Builder
{
diff --git a/backend/pkg/dockerutil/volume_utils_test.go b/backend/pkg/dockerutil/volume_utils_test.go
index 6294bf967..99b4c31d3 100644
--- a/backend/pkg/dockerutil/volume_utils_test.go
+++ b/backend/pkg/dockerutil/volume_utils_test.go
@@ -34,7 +34,7 @@ func TestVolumeUsageCacheBehaviorInternal(t *testing.T) {
firstResult := make(chan error, 1)
go func() {
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
_, err := GetVolumeUsageData(ctx, dockerClient)
firstResult <- err
@@ -46,7 +46,7 @@ func TestVolumeUsageCacheBehaviorInternal(t *testing.T) {
require.FailNow(t, "volume usage refresh did not start")
}
- waiterCtx, waiterCancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ waiterCtx, waiterCancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer waiterCancel()
waiterStartedAt := time.Now()
_, err := GetVolumeUsageData(waiterCtx, dockerClient)
@@ -80,7 +80,7 @@ func TestVolumeUsageCacheBehaviorInternal(t *testing.T) {
}
})
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
_, err := GetVolumeUsageData(ctx, dockerClient)
require.NoError(t, err)
@@ -123,7 +123,7 @@ func TestVolumeUsageCacheBehaviorInternal(t *testing.T) {
writeVolumeUsageResponseInternal(t, w, "host-b", 2)
})
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
_, err := GetVolumeUsageData(ctx, clientA)
require.NoError(t, err)
diff --git a/backend/pkg/fswatch/watcher.go b/backend/pkg/fswatch/watcher.go
index 386c33840..97d17dc5b 100644
--- a/backend/pkg/fswatch/watcher.go
+++ b/backend/pkg/fswatch/watcher.go
@@ -372,8 +372,8 @@ func (fw *Watcher) addExistingDirectoriesRecursiveInternal(path, logicalPath str
continue
}
childLogicalPath := filepath.Join(logicalPath, entry.Name())
- if err := fw.addExistingDirectoriesRecursiveInternal(childPath, childLogicalPath, ancestors); err != nil {
- return err
+ if addExistingDirectoriesRecursiveErr := fw.addExistingDirectoriesRecursiveInternal(childPath, childLogicalPath, ancestors); addExistingDirectoriesRecursiveErr != nil {
+ return addExistingDirectoriesRecursiveErr
}
}
@@ -501,8 +501,8 @@ func (fw *Watcher) reconnectInternal(ctx context.Context) bool {
if err == nil {
fw.watcher = watcher
fw.watchAliases = make(map[string]string)
- if err := fw.addExistingDirectories(fw.watchedPath); err != nil {
- slog.WarnContext(ctx, "Some filesystem subscriptions could not be restored", "error", err)
+ if addExistingDirectoriesErr := fw.addExistingDirectories(fw.watchedPath); addExistingDirectoriesErr != nil {
+ slog.WarnContext(ctx, "Some filesystem subscriptions could not be restored", "error", addExistingDirectoriesErr)
}
// Changes while disconnected need a full reconciliation.
fw.notifyChangesInternal(ctx, []string{fw.watchedPath})
diff --git a/backend/pkg/gitutil/git.go b/backend/pkg/gitutil/git.go
index 2541baa38..6effd6b3f 100644
--- a/backend/pkg/gitutil/git.go
+++ b/backend/pkg/gitutil/git.go
@@ -122,30 +122,30 @@ type AuthConfig struct {
}
// getAuthInternal returns the appropriate transport.AuthMethod.
-func (c *Client) getAuthInternal(url string, config AuthConfig) (transport.AuthMethod, error) {
- switch config.AuthType {
+func (c *Client) getAuthInternal(url string, localConfig AuthConfig) (transport.AuthMethod, error) {
+ switch localConfig.AuthType {
case "http":
- if config.Token != "" {
+ if localConfig.Token != "" {
return &githttp.BasicAuth{
- Username: config.Username,
- Password: config.Token,
+ Username: localConfig.Username,
+ Password: localConfig.Token,
}, nil
}
return nil, nil
case "ssh":
- if config.SSHKey != "" {
+ if localConfig.SSHKey != "" {
endpoint, err := transport.NewEndpoint(url)
if err != nil {
return nil, fmt.Errorf("failed to parse SSH repository URL: %w", err)
}
username := cmp.Or(endpoint.User, "git")
- publicKeys, err := ssh.NewPublicKeys(username, []byte(config.SSHKey), "")
+ publicKeys, err := ssh.NewPublicKeys(username, []byte(localConfig.SSHKey), "")
if err != nil {
return nil, fmt.Errorf("failed to create ssh auth: %w", err)
}
// Configure host key verification based on mode
- hostKeyCallback, err := c.getSSHHostKeyCallback(config.SSHHostKeyVerification)
+ hostKeyCallback, err := c.getSSHHostKeyCallback(localConfig.SSHHostKeyVerification)
if err != nil {
return nil, fmt.Errorf("failed to configure SSH host key verification: %w", err)
}
@@ -195,12 +195,12 @@ func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error)
// Create the file if it doesn't exist
if _, err := os.Stat(knownHostsPath); os.IsNotExist(err) {
- file, err := os.OpenFile(knownHostsPath, os.O_CREATE|os.O_WRONLY, 0o600)
- if err != nil {
- return nil, fmt.Errorf("failed to create known_hosts file: %w", err)
+ file, openFileErr := os.OpenFile(knownHostsPath, os.O_CREATE|os.O_WRONLY, 0o600)
+ if openFileErr != nil {
+ return nil, fmt.Errorf("failed to create known_hosts file: %w", openFileErr)
}
- if err := file.Close(); err != nil {
- slog.Warn("Failed to close known_hosts file", "path", knownHostsPath, "error", err)
+ if closeErr := file.Close(); closeErr != nil {
+ slog.Warn("Failed to close known_hosts file", "path", knownHostsPath, "error", closeErr)
}
}
@@ -213,23 +213,23 @@ func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error)
// Check if the host is already known
if existingCallback != nil {
- err := existingCallback(hostname, remote, key)
- if err == nil {
+ existingCallbackErr := existingCallback(hostname, remote, key)
+ if existingCallbackErr == nil {
return nil // Host key matches
}
// Check if it's a "key mismatch" error vs "unknown host"
- if keyErr, ok := errors.AsType[*knownhosts.KeyError](err); ok && len(keyErr.Want) > 0 {
+ if keyErr, ok := errors.AsType[*knownhosts.KeyError](existingCallbackErr); ok && len(keyErr.Want) > 0 {
// Host is known but key doesn't match - this is a security concern
- return fmt.Errorf("host key mismatch for %s (possible MITM attack): %w", hostname, err)
+ return fmt.Errorf("host key mismatch for %s (possible MITM attack): %w", hostname, existingCallbackErr)
}
// Otherwise, host is unknown - we'll add it
}
// Add the new host key to known_hosts
- if err := addHostKey(knownHostsPath, hostname, key); err != nil {
+ if addHostKeyErr := addHostKey(knownHostsPath, hostname, key); addHostKeyErr != nil {
// Log the error but don't fail - still allow the connection
// The host key just won't be remembered for next time
- slog.Warn("Failed to save host key", "hostname", hostname, "error", err)
+ slog.Warn("Failed to save host key", "hostname", hostname, "error", addHostKeyErr)
}
return nil
@@ -243,8 +243,8 @@ func getKnownHostsPath() string {
func getKnownHostsPathInternal(getenv func(string) string, stat func(string) (os.FileInfo, error), userHomeDir func() (string, error)) string {
// Check environment variable first
- if path := getenv("SSH_KNOWN_HOSTS"); path != "" {
- return path
+ if localPath := getenv("SSH_KNOWN_HOSTS"); localPath != "" {
+ return localPath
}
// Prefer Arcane's writable persistent data directory when it is available,
@@ -270,8 +270,8 @@ func addHostKey(knownHostsPath, hostname string, key gossh.PublicKey) (err error
// Acquire exclusive lock to prevent concurrent writes
fileLock := flock.New(knownHostsPath)
- if err := fileLock.Lock(); err != nil {
- return fmt.Errorf("failed to acquire lock on known_hosts file: %w", err)
+ if lockErr := fileLock.Lock(); lockErr != nil {
+ return fmt.Errorf("failed to acquire lock on known_hosts file: %w", lockErr)
}
defer func() {
if unlockErr := fileLock.Unlock(); unlockErr != nil && err == nil {
@@ -292,8 +292,8 @@ func addHostKey(knownHostsPath, hostname string, key gossh.PublicKey) (err error
}
}()
- if _, err := file.WriteString(line + "\n"); err != nil {
- return fmt.Errorf("failed to write to known_hosts file: %w", err)
+ if _, writeStringErr := file.WriteString(line + "\n"); writeStringErr != nil {
+ return fmt.Errorf("failed to write to known_hosts file: %w", writeStringErr)
}
return nil
@@ -526,8 +526,8 @@ func (c *Client) BrowseTree(ctx context.Context, repoPath, targetPath string) ([
var nodes []gitops.FileTreeNode
for _, child := range entries {
- if err := ctx.Err(); err != nil {
- return nil, err
+ if errErr := ctx.Err(); errErr != nil {
+ return nil, errErr
}
// Skip .git directory
if child.Name == ".git" {
@@ -579,8 +579,8 @@ func (c *Client) PurgeScratchDirs(ctx context.Context, maxAge time.Duration) (in
removed := 0
for _, entry := range entries {
- if err := ctx.Err(); err != nil {
- return removed, err
+ if errErr := ctx.Err(); errErr != nil {
+ return removed, errErr
}
entryPath := filepath.Join(root, entry.Name())
if !entry.IsDir() || !strings.HasPrefix(entry.Name(), cloneScratchPrefix) {
diff --git a/backend/pkg/gitutil/git_test.go b/backend/pkg/gitutil/git_test.go
index 39e448ea7..7d5d5b3ce 100644
--- a/backend/pkg/gitutil/git_test.go
+++ b/backend/pkg/gitutil/git_test.go
@@ -1,7 +1,6 @@
package git
import (
- "context"
"errors"
"net"
"os"
@@ -226,8 +225,8 @@ func TestCreateAcceptNewHostKeyCallback(t *testing.T) {
{
// Verify directory was created
- _, err := os.Stat(filepath.Dir(knownHostsPath))
- assert.False(t, os.IsNotExist(err),
+ _, statErr := os.Stat(filepath.Dir(knownHostsPath))
+ assert.False(t, os.IsNotExist(statErr),
"expected known_hosts directory to be created")
}
})
@@ -389,7 +388,7 @@ func TestWalkDirectory_BasicWalk(t *testing.T) {
writeFileInternal(t, tmpDir, "file2.txt", []byte("another file"))
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -407,13 +406,13 @@ func TestWalkDirectory_PreservesExecutableBit(t *testing.T) {
writeFileInternal(t, tmpDir, "scripts/hook.sh", []byte("#!/bin/sh\necho hi\n"))
writeFileInternal(t, tmpDir, "README.md", []byte("readme"))
{
- err := os.Chmod(filepath.Join(tmpDir, "scripts/hook.sh"), 0o755)
+ err := os.Chmod(filepath.Join(tmpDir, "scripts", "hook.sh"), 0o755)
require.NoError(t, err,
"chmod: %v", err)
}
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -432,8 +431,8 @@ func TestWalkDirectory_PreservesExecutableBit(t *testing.T) {
"expected scripts/hook.sh to be reported Executable, got false")
{
- readme, ok := byPath["README.md"]
- assert.False(t, ok && readme.Executable,
+ readme, localOk := byPath["README.md"]
+ assert.False(t, localOk && readme.Executable,
"expected README.md to not be Executable")
}
}
@@ -447,7 +446,7 @@ func TestWalkDirectory_MaxFilesLimit(t *testing.T) {
writeFileInternal(t, tmpDir, "d.txt", []byte("d"))
client := NewClient("")
- _, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 3, 0, 0)
+ _, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 3, 0, 0)
require.Error(t, err,
"expected error for file count limit, got nil")
@@ -465,7 +464,7 @@ func TestWalkDirectory_MaxFilesUnlimited(t *testing.T) {
writeFileInternal(t, tmpDir, "d.txt", []byte("d"))
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -481,7 +480,7 @@ func TestWalkDirectory_MaxTotalSizeLimit(t *testing.T) {
writeFileInternal(t, tmpDir, "big2.txt", []byte(strings.Repeat("y", 40)))
client := NewClient("")
- _, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 50, 0)
+ _, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 50, 0)
require.Error(t, err,
"expected error for total size limit, got nil")
@@ -497,7 +496,7 @@ func TestWalkDirectory_MaxTotalSizeUnlimited(t *testing.T) {
writeFileInternal(t, tmpDir, "big2.txt", []byte(strings.Repeat("y", 500)))
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -514,7 +513,7 @@ func TestWalkDirectory_MaxBinarySizeSkips(t *testing.T) {
writeFileInternal(t, tmpDir, "data.bin", binaryContent)
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 5)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 0, 5)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -530,7 +529,7 @@ func TestWalkDirectory_MaxBinarySizeUnlimited(t *testing.T) {
writeFileInternal(t, tmpDir, "data.bin", binaryContent)
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -548,7 +547,7 @@ func TestWalkDirectory_LargeTextFileNotSkippedByBinaryLimit(t *testing.T) {
writeFileInternal(t, tmpDir, "notes.txt", []byte(strings.Repeat("plain text\n", 32)))
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "compose.yaml", 0, 0, 16)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "compose.yaml", 0, 0, 16)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -566,7 +565,7 @@ func TestWalkDirectory_ComposeInSubdirectory(t *testing.T) {
writeFileInternal(t, tmpDir, "subdir/dynamic_config.yml", []byte("http:\n routers: {}\n"))
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "subdir/docker-compose.yml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "subdir/docker-compose.yml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -596,7 +595,7 @@ func TestWalkDirectory_NestedSiblingFile(t *testing.T) {
writeFileInternal(t, tmpDir, "subdir/config/dynamic_config.yml", []byte("tls:\n certificates: []\n"))
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "subdir/docker-compose.yml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "subdir/docker-compose.yml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -626,7 +625,7 @@ func TestWalkDirectory_SpecialCharsInPath(t *testing.T) {
writeFileInternal(t, tmpDir, "traefik (nl10)/config/dynamic_config.yml", []byte("http:\n middlewares: {}\n"))
client := NewClient("")
- result, err := client.WalkDirectory(context.Background(), tmpDir, "traefik (nl10)/docker-compose.yml", 0, 0, 0)
+ result, err := client.WalkDirectory(t.Context(), tmpDir, "traefik (nl10)/docker-compose.yml", 0, 0, 0)
require.NoError(t, err,
"unexpected error: %v", err)
@@ -699,7 +698,7 @@ func generateTestPublicKeyVariant(t *testing.T) gossh.PublicKey {
}
func TestPurgeScratchDirs(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
workDir := t.TempDir()
client := NewClient(workDir)
@@ -721,8 +720,8 @@ func TestPurgeScratchDirs(t *testing.T) {
_, err = os.Stat(staleDir)
require.ErrorIs(t, err, os.ErrNotExist, "stale clone dir should be removed")
for _, p := range []string{freshDir, keepDir, scratchFile} {
- _, err := os.Stat(p)
- assert.NoError(t, err, "must be kept by the age-cutoff purge: %s", p)
+ _, statErr := os.Stat(p)
+ require.NoError(t, statErr, "must be kept by the age-cutoff purge: %s", p)
}
removed, err = client.PurgeScratchDirs(ctx, 0)
@@ -732,14 +731,14 @@ func TestPurgeScratchDirs(t *testing.T) {
_, err = os.Stat(freshDir)
require.ErrorIs(t, err, os.ErrNotExist, "boot sweep should remove fresh clone dirs")
for _, p := range []string{keepDir, scratchFile} {
- _, err := os.Stat(p)
- assert.NoError(t, err, "boot sweep must keep non-scratch entries: %s", p)
+ _, statErr2 := os.Stat(p)
+ require.NoError(t, statErr2, "boot sweep must keep non-scratch entries: %s", p)
}
t.Run("missing work dir is not an error", func(t *testing.T) {
- removed, err := NewClient(filepath.Join(t.TempDir(), "missing")).PurgeScratchDirs(ctx, 0)
- require.NoError(t, err)
- assert.Equal(t, 0, removed)
+ localRemoved, purgeErr := NewClient(filepath.Join(t.TempDir(), "missing")).PurgeScratchDirs(ctx, 0)
+ require.NoError(t, purgeErr)
+ assert.Equal(t, 0, localRemoved)
})
}
diff --git a/backend/pkg/gitutil/git_write.go b/backend/pkg/gitutil/git_write.go
index 0f2a653cf..81f9d2349 100644
--- a/backend/pkg/gitutil/git_write.go
+++ b/backend/pkg/gitutil/git_write.go
@@ -87,8 +87,8 @@ func CollectFiles(ctx context.Context, root string, selection []string, opts Col
return nil, fmt.Errorf("%s is a symbolic link: %w", selected, ErrSelectionInvalid)
}
if !entry.IsDirectory {
- if err := c.addInternal(ctx, entry); err != nil {
- return nil, err
+ if addErr := c.addInternal(ctx, entry); addErr != nil {
+ return nil, addErr
}
continue
}
@@ -170,16 +170,16 @@ func ParseSigningKey(armored, passphrase string) (*openpgp.Entity, error) {
if passphrase == "" {
return nil, errors.New("signing key is protected by a passphrase")
}
- if err := entity.PrivateKey.Decrypt([]byte(passphrase)); err != nil {
- return nil, fmt.Errorf("signing key passphrase is incorrect: %w", err)
+ if decryptErr := entity.PrivateKey.Decrypt([]byte(passphrase)); decryptErr != nil {
+ return nil, fmt.Errorf("signing key passphrase is incorrect: %w", decryptErr)
}
}
for _, subkey := range entity.Subkeys {
if subkey.PrivateKey == nil || !subkey.PrivateKey.Encrypted {
continue
}
- if err := subkey.PrivateKey.Decrypt([]byte(passphrase)); err != nil {
- return nil, fmt.Errorf("signing key passphrase is incorrect: %w", err)
+ if decryptErr2 := subkey.PrivateKey.Decrypt([]byte(passphrase)); decryptErr2 != nil {
+ return nil, fmt.Errorf("signing key passphrase is incorrect: %w", decryptErr2)
}
}
return entity, nil
@@ -257,13 +257,13 @@ func (c *Client) initEmptyCheckoutInternal(url, branch string) (*WriteCheckout,
_ = os.RemoveAll(repoPath)
return nil, fmt.Errorf("failed to initialize checkout: %w", err)
}
- if _, err := repo.CreateRemote(&config.RemoteConfig{Name: "origin", URLs: []string{url}}); err != nil {
+ if _, createRemoteErr := repo.CreateRemote(&config.RemoteConfig{Name: "origin", URLs: []string{url}}); createRemoteErr != nil {
_ = os.RemoveAll(repoPath)
- return nil, fmt.Errorf("failed to configure remote: %w", err)
+ return nil, fmt.Errorf("failed to configure remote: %w", createRemoteErr)
}
- if err := repo.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName(branch))); err != nil {
+ if setReferenceErr := repo.Storer.SetReference(plumbing.NewSymbolicReference(plumbing.HEAD, plumbing.NewBranchReferenceName(branch))); setReferenceErr != nil {
_ = os.RemoveAll(repoPath)
- return nil, fmt.Errorf("failed to select branch: %w", err)
+ return nil, fmt.Errorf("failed to select branch: %w", setReferenceErr)
}
return &WriteCheckout{RepoPath: repoPath, Branch: branch, url: url, repo: repo}, nil
}
@@ -283,9 +283,9 @@ func (c *Client) checkoutNewBranchInternal(ctx context.Context, url, branch stri
_ = c.Cleanup(repoPath)
return nil, fmt.Errorf("failed to open worktree: %w", err)
}
- if err := worktree.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName(branch), Create: true}); err != nil {
+ if checkoutErr := worktree.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName(branch), Create: true}); checkoutErr != nil {
_ = c.Cleanup(repoPath)
- return nil, fmt.Errorf("failed to create branch %s: %w", branch, err)
+ return nil, fmt.Errorf("failed to create branch %s: %w", branch, checkoutErr)
}
return &WriteCheckout{RepoPath: repoPath, Branch: branch, url: url, repo: repo}, nil
}
@@ -302,8 +302,8 @@ func (c *Client) CommitAndPush(ctx context.Context, checkout *WriteCheckout, req
if err != nil {
return "", false, fmt.Errorf("failed to open worktree: %w", err)
}
- if err := stageCommitFilesInternal(ctx, checkout, worktree, req); err != nil {
- return "", false, err
+ if stageCommitFilesErr := stageCommitFilesInternal(ctx, checkout, worktree, req); stageCommitFilesErr != nil {
+ return "", false, stageCommitFilesErr
}
signature := &object.Signature{Name: req.AuthorName, Email: req.AuthorEmail, When: time.Now()}
@@ -314,8 +314,8 @@ func (c *Client) CommitAndPush(ctx context.Context, checkout *WriteCheckout, req
}
return "", false, fmt.Errorf("failed to commit: %w", err)
}
- if err := c.pushBranchInternal(ctx, checkout, hash.String(), auth); err != nil {
- return "", false, err
+ if pushBranchErr := c.pushBranchInternal(ctx, checkout, hash.String(), auth); pushBranchErr != nil {
+ return "", false, pushBranchErr
}
checkout.HeadCommit = hash.String()
checkout.BranchExists = true
@@ -373,11 +373,11 @@ func (c *Client) pushBranchInternal(ctx context.Context, checkout *WriteCheckout
if authMethod != nil {
pushOptions.Auth = authMethod
}
- if err := checkout.repo.PushContext(ctx, pushOptions); err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
- if isPushRejectedInternal(err) {
- return fmt.Errorf("%s: %w", err.Error(), ErrPushRejected)
+ if pushContextErr := checkout.repo.PushContext(ctx, pushOptions); pushContextErr != nil && !errors.Is(pushContextErr, git.NoErrAlreadyUpToDate) {
+ if isPushRejectedInternal(pushContextErr) {
+ return fmt.Errorf("%s: %w", pushContextErr.Error(), ErrPushRejected)
}
- return fmt.Errorf("failed to push: %w", err)
+ return fmt.Errorf("failed to push: %w", pushContextErr)
}
remoteHead, exists, err := c.RemoteBranchHead(ctx, checkout.url, checkout.Branch, auth)
@@ -438,19 +438,19 @@ func (c *Client) DirectoryHistory(ctx context.Context, repoPath, directory strin
entries := make([]HistoryEntry, 0, max(limit, 0))
for {
- if err := ctx.Err(); err != nil {
- return nil, err
+ if errErr := ctx.Err(); errErr != nil {
+ return nil, errErr
}
- commit, err := iter.Next()
- if err != nil {
- if errors.Is(err, io.EOF) {
+ commit, nextErr := iter.Next()
+ if nextErr != nil {
+ if errors.Is(nextErr, io.EOF) {
break
}
- return nil, fmt.Errorf("failed to iterate history: %w", err)
+ return nil, fmt.Errorf("failed to iterate history: %w", nextErr)
}
- files, err := commitDirectoryFilesInternal(commit, prefix)
- if err != nil {
- return nil, err
+ files, nextErr := commitDirectoryFilesInternal(commit, prefix)
+ if nextErr != nil {
+ return nil, nextErr
}
entries = append(entries, historyEntryInternal(commit, files))
if limit > 0 && len(entries) >= limit {
@@ -494,9 +494,9 @@ func (c *Client) CommitDiff(ctx context.Context, repoPath, commitHash, directory
continue
}
files = append(files, relative)
- single, err := commitFilePatchInternal(commit, name)
- if err != nil {
- return HistoryEntry{}, nil, err
+ single, commitFilePatchErr := commitFilePatchInternal(commit, name)
+ if commitFilePatchErr != nil {
+ return HistoryEntry{}, nil, commitFilePatchErr
}
diffs = append(diffs, FileDiff{Path: relative, Patch: single})
}
@@ -599,9 +599,9 @@ func commitFilePatchInternal(commit *object.Commit, name string) (string, error)
if change.From.Name != name && change.To.Name != name {
continue
}
- patch, err := change.Patch()
- if err != nil {
- return "", fmt.Errorf("failed to build patch for %s: %w", name, err)
+ patch, patchErr := change.Patch()
+ if patchErr != nil {
+ return "", fmt.Errorf("failed to build patch for %s: %w", name, patchErr)
}
return patch.String(), nil
}
diff --git a/backend/pkg/gitutil/git_write_test.go b/backend/pkg/gitutil/git_write_test.go
index a125f4efc..47c30099c 100644
--- a/backend/pkg/gitutil/git_write_test.go
+++ b/backend/pkg/gitutil/git_write_test.go
@@ -2,7 +2,6 @@ package git
import (
"context"
- "errors"
"os"
"path/filepath"
"sync"
@@ -161,12 +160,12 @@ func TestDirectoryHistoryAndCommitDiff(t *testing.T) {
target := filepath.Join(repoPath, filepath.FromSlash(name))
require.NoError(t, os.MkdirAll(filepath.Dir(target), 0o755))
require.NoError(t, os.WriteFile(target, []byte(content), 0o644))
- _, err := worktree.Add(name)
- require.NoError(t, err)
+ _, addErr := worktree.Add(name)
+ require.NoError(t, addErr)
}
signature := &object.Signature{Name: "Arcane", Email: "arcane@localhost", When: time.Now()}
- hash, err := worktree.Commit(message, &gogit.CommitOptions{Author: signature, Committer: signature})
- require.NoError(t, err)
+ hash, commitErr := worktree.Commit(message, &gogit.CommitOptions{Author: signature, Committer: signature})
+ require.NoError(t, commitErr)
return hash.String()
}
@@ -204,5 +203,5 @@ func TestDirectoryHistory_LimitsAndMissingHead(t *testing.T) {
_, _, err = gitClient.CommitDiff(ctx, repoPath, "0000000000000000000000000000000000000000", "backups/app")
require.Error(t, err)
- assert.False(t, errors.Is(err, context.Canceled))
+ assert.NotErrorIs(t, err, context.Canceled)
}
diff --git a/backend/pkg/libarcane/activity/writer_test.go b/backend/pkg/libarcane/activity/writer_test.go
index 33bbec54f..bcc4001e0 100644
--- a/backend/pkg/libarcane/activity/writer_test.go
+++ b/backend/pkg/libarcane/activity/writer_test.go
@@ -48,7 +48,7 @@ func (f failingWriter) Write(_ []byte) (int, error) {
func TestWriterContinuesActivityCaptureWhenResponseWriterFailsInternal(t *testing.T) {
appender := &recordingAppender{}
- writer := NewWriter(context.Background(), appender, "activity-1", failingWriter{}, "Pulling image")
+ writer := NewWriter(t.Context(), appender, "activity-1", failingWriter{}, "Pulling image")
n, err := writer.Write([]byte("Downloading layer\n"))
require.NoError(t, err)
@@ -66,7 +66,7 @@ func TestWriterContinuesActivityCaptureWhenResponseWriterFailsInternal(t *testin
func TestWriterRecordsLogAndErrorFramesVerbatimInternal(t *testing.T) {
appender := &recordingAppender{}
- writer := NewWriter(context.Background(), appender, "activity-1", io.Discard, "Deploying project")
+ writer := NewWriter(t.Context(), appender, "activity-1", io.Discard, "Deploying project")
_, err := writer.Write([]byte("{\"log\":\"Container web-1 Created\"}\n{\"error\":\"Error response from daemon: conflict\"}\n"))
require.NoError(t, err)
@@ -103,7 +103,7 @@ func (g *gatedAppender) AppendMessages(ctx context.Context, activityID string, r
// AppendMessages call, in order, rather than one call per line.
func TestWriterBatchesQueuedLinesIntoOneAppendInternal(t *testing.T) {
appender := &gatedAppender{started: make(chan struct{}), release: make(chan struct{})}
- writer := NewWriter(context.Background(), appender, "activity-1", io.Discard, "Pulling image")
+ writer := NewWriter(t.Context(), appender, "activity-1", io.Discard, "Pulling image")
_, err := writer.Write([]byte("layer 0\n"))
require.NoError(t, err)
@@ -116,8 +116,8 @@ func TestWriterBatchesQueuedLinesIntoOneAppendInternal(t *testing.T) {
// The drain goroutine is stalled inside the first append; everything
// written now queues up behind it.
for i := 1; i < 10; i++ {
- _, err := writer.Write(fmt.Appendf(nil, "layer %d\n", i))
- require.NoError(t, err)
+ _, writeErr := writer.Write(fmt.Appendf(nil, "layer %d\n", i))
+ require.NoError(t, writeErr)
}
close(appender.release)
@@ -134,7 +134,7 @@ func TestWriterBatchesQueuedLinesIntoOneAppendInternal(t *testing.T) {
}
func TestWriterReturnsWrappedWriteErrorWithoutActivityInternal(t *testing.T) {
- writer := NewWriter(context.Background(), nil, "", failingWriter{}, "Pulling image")
+ writer := NewWriter(t.Context(), nil, "", failingWriter{}, "Pulling image")
_, err := writer.Write([]byte("Downloading layer\n"))
require.ErrorContains(t, err, "client disconnected")
@@ -151,7 +151,7 @@ var (
// queue before exiting, since the lines queued at cancellation are usually
// the ones explaining it.
func TestWriterPersistsQueuedLinesAfterCancelInternal(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
appender := &gatedAppender{started: make(chan struct{}), release: make(chan struct{})}
writer := NewWriter(ctx, appender, "activity-1", io.Discard, "Pulling image")
@@ -166,8 +166,8 @@ func TestWriterPersistsQueuedLinesAfterCancelInternal(t *testing.T) {
// The drain goroutine is stalled inside the first append; these queue up
// behind it and are still pending when the context is cancelled.
for i := 1; i < 10; i++ {
- _, err := writer.Write(fmt.Appendf(nil, "layer %d\n", i))
- require.NoError(t, err)
+ _, writeErr := writer.Write(fmt.Appendf(nil, "layer %d\n", i))
+ require.NoError(t, writeErr)
}
cancel()
close(appender.release)
diff --git a/backend/pkg/libarcane/edge/client.go b/backend/pkg/libarcane/edge/client.go
index 7d4e2d56d..2dbfbf132 100644
--- a/backend/pkg/libarcane/edge/client.go
+++ b/backend/pkg/libarcane/edge/client.go
@@ -508,8 +508,8 @@ func (c *TunnelClient) serveTunnelSessionInternal(ctx context.Context, conn Tunn
workers.Go(func() { c.heartbeatLoop(connCtx, conn) })
- if err := c.messageLoop(connCtx, conn, &workers); err != nil {
- return fmt.Errorf("%w: %w", errEstablishedTunnelSessionEnded, err)
+ if messageLoopErr := c.messageLoop(connCtx, conn, &workers); messageLoopErr != nil {
+ return fmt.Errorf("%w: %w", errEstablishedTunnelSessionEnded, messageLoopErr)
}
return nil
}
@@ -710,8 +710,8 @@ func (c *TunnelClient) handleCommandRequest(ctx context.Context, conn TunnelConn
recorder := newCommandResponseRecorderInternal(msg.ID, msg.Command, conn)
c.handler.ServeHTTP(recorder, req)
- if err := recorder.Close(); err != nil {
- slog.WarnContext(reqCtx, "Failed to finalize command response", "id", msg.ID, "command", msg.Command, "error", err)
+ if closeErr := recorder.Close(); closeErr != nil {
+ slog.WarnContext(reqCtx, "Failed to finalize command response", "id", msg.ID, "command", msg.Command, "error", closeErr)
}
}
@@ -806,8 +806,8 @@ func (c *TunnelClient) handleRequest(ctx context.Context, conn TunnelConnection,
Body: rw.body.Bytes(),
}
- if err := conn.Send(resp); err != nil {
- slog.ErrorContext(reqCtx, "Failed to send response", "id", msg.ID, "error", err)
+ if sendErr := conn.Send(resp); sendErr != nil {
+ slog.ErrorContext(reqCtx, "Failed to send response", "id", msg.ID, "error", sendErr)
} else {
slog.DebugContext(reqCtx, "Sent tunneled response", "id", msg.ID, "status", rw.statusCode)
}
@@ -836,8 +836,8 @@ func (c *TunnelClient) handleRequestStreaming(ctx context.Context, conn TunnelCo
recorder := newStreamingResponseRecorder(msg.ID, conn)
c.handler.ServeHTTP(recorder, req)
- if err := recorder.Close(); err != nil {
- slog.WarnContext(reqCtx, "Failed to finalize streamed response", "id", msg.ID, "error", err)
+ if closeErr := recorder.Close(); closeErr != nil {
+ slog.WarnContext(reqCtx, "Failed to finalize streamed response", "id", msg.ID, "error", closeErr)
}
}
@@ -1033,7 +1033,7 @@ func (c *TunnelClient) closeAllStreams() {
if !ok {
return true
}
- if stream, ok := value.(*activeWSStream); ok {
+ if stream, localOk := value.(*activeWSStream); localOk {
c.closeWebSocketStream(streamID, stream)
}
return true
@@ -1055,8 +1055,8 @@ func (c *TunnelClient) startLocalWebSocketReadLoop(ctx, streamCtx context.Contex
return
}
- if err := c.sendWebSocketData(stream.conn, streamID, int(msgType), data); err != nil {
- slog.DebugContext(ctx, "Failed to send WebSocket data to manager", "error", err)
+ if sendWebSocketDataErr := c.sendWebSocketData(stream.conn, streamID, int(msgType), data); sendWebSocketDataErr != nil {
+ slog.DebugContext(ctx, "Failed to send WebSocket data to manager", "error", sendWebSocketDataErr)
return
}
}
diff --git a/backend/pkg/libarcane/edge/client_test.go b/backend/pkg/libarcane/edge/client_test.go
index 7af6efae0..9da64aaf9 100644
--- a/backend/pkg/libarcane/edge/client_test.go
+++ b/backend/pkg/libarcane/edge/client_test.go
@@ -5,7 +5,6 @@ import (
"context"
"encoding/json"
"errors"
- "fmt"
"io"
"log/slog"
"maps"
@@ -117,8 +116,8 @@ func TestTunnelClient_WebSocketProxy(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- mt, data, err := conn.Read(r.Context())
- if err != nil {
+ mt, data, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
// Echo
@@ -207,8 +206,8 @@ func TestTunnelClient_WebSocket_ReconnectClosesStreams(t *testing.T) {
}
defer func() { _ = conn.CloseNow() }()
for {
- mt, data, err := conn.Read(r.Context())
- if err != nil {
+ mt, data, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
_ = conn.Write(r.Context(), mt, append([]byte("local echo: "), data...))
@@ -230,7 +229,7 @@ func TestTunnelClient_WebSocket_ReconnectClosesStreams(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
// Every connection registers first.
- if _, _, err := conn.Read(r.Context()); err != nil {
+ if _, _, readErr := conn.Read(r.Context()); readErr != nil {
return
}
registerResp, _ := json.Marshal(&TunnelMessage{
@@ -381,8 +380,8 @@ func TestTunnelClient_InternalHelpers(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- _, _, err := conn.Read(r.Context())
- if err != nil {
+ _, _, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
}
@@ -677,7 +676,7 @@ func TestTunnelClient_HandleRequest_GRPCConfigWithWebSocketConnUsesNonStreamingR
conn := &capturingTunnelConnForHandleRequest{}
client.conn.Store(&connBox{conn: conn})
- client.handleRequest(context.Background(), conn, &TunnelMessage{
+ client.handleRequest(t.Context(), conn, &TunnelMessage{
ID: "req-fallback-1",
Type: MessageTypeRequest,
Method: http.MethodGet,
@@ -695,7 +694,7 @@ func TestTunnelClient_HeartbeatLoop_ClosesConnectionOnSendFailure(t *testing.T)
client := &TunnelClient{
heartbeatInterval: 5 * time.Millisecond,
}
- ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond)
defer cancel()
client.heartbeatLoop(ctx, conn)
@@ -848,7 +847,7 @@ func (s *stallingTunnelService) Connect(stream grpc.BidiStreamingServer[tunnelpb
}
func TestTunnelClient_GRPC_EndToEnd(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
envID := "env-e2e-grpc-1"
GetRegistry().Unregister(envID)
@@ -904,9 +903,9 @@ func TestTunnelClient_GRPC_EndToEnd(t *testing.T) {
proxyCtx, proxyCancel := context.WithTimeout(ctx, 5*time.Second)
defer proxyCancel()
- status, headers, body, err := ProxyRequest(proxyCtx, tunnel, http.MethodGet, "/api/health", "", map[string]string{"Accept": "text/plain"}, nil)
+ localStatus, headers, body, err := ProxyRequest(proxyCtx, tunnel, http.MethodGet, "/api/health", "", map[string]string{"Accept": "text/plain"}, nil)
require.NoError(t, err)
- assert.Equal(t, http.StatusOK, status)
+ assert.Equal(t, http.StatusOK, localStatus)
assert.Equal(t, "text/plain", headers["Content-Type"])
assert.Equal(t, "ok-from-agent", string(body))
@@ -918,7 +917,7 @@ func TestTunnelClient_GRPC_EndToEnd(t *testing.T) {
}
func TestTunnelClient_GRPC_ChunkedRequestBodyEndToEnd(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
envID := "env-e2e-grpc-chunked-body"
GetRegistry().Unregister(envID)
@@ -966,9 +965,9 @@ func TestTunnelClient_GRPC_ChunkedRequestBodyEndToEnd(t *testing.T) {
}, 5*time.Second, 20*time.Millisecond)
require.Contains(t, tunnel.Capabilities, tunnelCapabilityChunkedRequest)
- status, _, body, err := ProxyRequest(ctx, tunnel, http.MethodPost, "/api/environments/0/images/upload", "", nil, wantBody)
+ localStatus, _, body, err := ProxyRequest(ctx, tunnel, http.MethodPost, "/api/environments/0/images/upload", "", nil, wantBody)
require.NoError(t, err)
- assert.Equal(t, http.StatusOK, status)
+ assert.Equal(t, http.StatusOK, localStatus)
assert.Equal(t, "uploaded", string(body))
}
@@ -1053,13 +1052,13 @@ func TestTunnelClient_connectAndServeGRPC_EmptyManagerAddress(t *testing.T) {
AgentToken: "valid-token",
}, http.NotFoundHandler())
- err := client.connectAndServeGRPC(context.Background())
+ err := client.connectAndServeGRPC(t.Context())
require.Error(t, err)
assert.Contains(t, err.Error(), "manager gRPC address is empty")
}
func TestTunnelClient_connectAndServeGRPC_RegistrationRejected(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
envID := "env-e2e-grpc-reject-1"
GetRegistry().Unregister(envID)
@@ -1097,7 +1096,7 @@ func TestTunnelClient_connectAndServeGRPC_RegistrationRejected(t *testing.T) {
}
func TestTunnelClient_connectAndServeGRPC_TimesOutWithoutRegisterResponse(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
service := &stallingTunnelService{}
@@ -1122,7 +1121,7 @@ func TestTunnelClient_connectAndServeGRPC_TimesOutWithoutRegisterResponse(t *tes
}
func TestTunnelClient_awaitRegistrationInternal_ClosesConnOnContextDone(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
conn := newBlockingRegistrationConnInternal()
@@ -1139,7 +1138,7 @@ func TestTunnelClient_awaitRegistrationInternal_ClosesConnOnContextDone(t *testi
}
func TestTunnelClient_awaitRegistrationInternal_ClosesAttemptConnWhenClientConnChanges(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
firstConn := newBlockingRegistrationConnInternal()
@@ -1188,7 +1187,7 @@ func TestTunnelClient_awaitRegistrationInternal_ClosesAttemptConnWhenClientConnC
}
func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
envID := "env-e2e-grpc-ws-1"
GetRegistry().Unregister(envID)
@@ -1242,15 +1241,15 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- mt, data, err := conn.Read(r.Context())
- if err != nil {
+ mt, data, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
select {
case receivedMsgCh <- string(data):
default:
}
- if err := conn.Write(r.Context(), mt, append([]byte("local echo: "), data...)); err != nil {
+ if writeErr := conn.Write(r.Context(), mt, append([]byte("local echo: "), data...)); writeErr != nil {
return
}
}
@@ -1344,7 +1343,7 @@ func TestTunnelClient_GRPC_WebSocketProxyEndToEnd(t *testing.T) {
}
func TestTunnelClient_connectAndServe_WebSocketConfigFallsBackToWebSocket(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
wsConnectedCh := make(chan struct{}, 1)
@@ -1399,7 +1398,7 @@ func TestTunnelClient_managedTunnelTransports_AutoEnablesGRPCAndWebSocket(t *tes
}
func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCUnavailable(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
managerURL, wsConnectedCh, stopManager := startTestWebSocketTunnelManagerInternal(t, ctx)
@@ -1436,7 +1435,7 @@ func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCUnavailabl
}
func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCSetupHangs(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
grpcAddr, stopGRPC := startHangingTCPServerInternal(t, ctx)
@@ -1474,7 +1473,7 @@ func TestTunnelClient_connectAndServe_AutoFallsBackToWebSocketWhenGRPCSetupHangs
}
func TestTunnelClient_connectAndServe_GRPCDoesNotFallbackToWebSocket(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
managerURL, wsConnectedCh, stopManager := startTestWebSocketTunnelManagerInternal(t, ctx)
@@ -1501,7 +1500,7 @@ func TestTunnelClient_connectAndServe_GRPCDoesNotFallbackToWebSocket(t *testing.
}
func TestTunnelClient_connectAndServe_OpensGRPCWhenAvailable(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
envID := "env-auto-poll-grpc"
@@ -1568,7 +1567,7 @@ func startTestWebSocketTunnelManagerInternal(t *testing.T, ctx context.Context)
}
defer func() { _ = conn.CloseNow() }()
- if _, _, err := conn.Read(r.Context()); err != nil {
+ if _, _, readErr := conn.Read(r.Context()); readErr != nil {
return
}
@@ -1581,7 +1580,7 @@ func startTestWebSocketTunnelManagerInternal(t *testing.T, ctx context.Context)
if err != nil {
return
}
- if err := conn.Write(r.Context(), websocket.MessageText, registerResp); err != nil {
+ if writeErr := conn.Write(r.Context(), websocket.MessageText, registerResp); writeErr != nil {
return
}
@@ -1616,8 +1615,8 @@ func startHangingTCPServerInternal(t *testing.T, ctx context.Context) (string, f
go func() {
defer close(done)
for {
- conn, err := lis.Accept()
- if err != nil {
+ conn, acceptErr := lis.Accept()
+ if acceptErr != nil {
return
}
go func() {
@@ -1693,7 +1692,7 @@ func startTestTunnelServiceOnAPIPathInternal(t *testing.T, ctx context.Context,
}()
cleanup := func() {
- shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ shutdownCtx, shutdownCancel := context.WithTimeout(t.Context(), 5*time.Second)
defer shutdownCancel()
_ = httpServer.Shutdown(shutdownCtx)
grpcServer.Stop()
@@ -1758,8 +1757,8 @@ func TestTunnelClient_connectAndServe_AutoDoesNotFallbackWhenEstablishedGRPCSess
require.NoError(t, tunnel.CloseWithReason("manager restart"))
select {
- case err := <-errCh:
- require.ErrorIs(t, err, errEstablishedTunnelSessionEnded)
+ case operationErr := <-errCh:
+ require.ErrorIs(t, operationErr, errEstablishedTunnelSessionEnded)
case <-time.After(3 * time.Second):
require.FailNow(t, "expected dropped gRPC session to return instead of falling back to websocket")
}
@@ -1774,7 +1773,7 @@ func TestTunnelClient_connectAndServe_AutoDoesNotFallbackWhenEstablishedGRPCSess
}
func TestTunnelClient_connectAndServePoll_OpensGRPCWhenRequired(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
defer cancel()
envID := "env-poll-grpc"
@@ -1831,7 +1830,7 @@ func TestTunnelClient_connectAndServePoll_OpensGRPCWhenRequired(t *testing.T) {
}
func TestTunnelClient_connectAndServePoll_OpensWebSocketWhenRequired(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond)
defer cancel()
var pollCount atomic.Int32
@@ -1855,7 +1854,7 @@ func TestTunnelClient_connectAndServePoll_OpensWebSocketWhenRequired(t *testing.
}
defer func() { _ = conn.CloseNow() }()
- if _, _, err := conn.Read(r.Context()); err != nil {
+ if _, _, readErr := conn.Read(r.Context()); readErr != nil {
return
}
registerResp, err := json.Marshal(&TunnelMessage{
@@ -1867,7 +1866,7 @@ func TestTunnelClient_connectAndServePoll_OpensWebSocketWhenRequired(t *testing.
if err != nil {
return
}
- if err := conn.Write(r.Context(), websocket.MessageText, registerResp); err != nil {
+ if writeErr := conn.Write(r.Context(), websocket.MessageText, registerResp); writeErr != nil {
return
}
@@ -1928,13 +1927,13 @@ func TestTunnelClient_pollTunnelControlInternal_UsesConfiguredHTTPClient(t *test
client := NewTunnelClient(&Config{AgentToken: "valid-token"}, http.NotFoundHandler())
httpClient := &http.Client{Transport: rewriteTransport}
- resp, err := client.pollTunnelControlInternal(context.Background(), httpClient, "http://127.0.0.1:1/api/tunnel/poll", false)
+ resp, err := client.pollTunnelControlInternal(t.Context(), httpClient, "http://127.0.0.1:1/api/tunnel/poll", false)
require.NoError(t, err)
assert.Equal(t, TunnelStatusIdle, resp.Status)
assert.Equal(t, 1, resp.PollIntervalSeconds)
assert.NotSame(t, http.DefaultClient, httpClient)
- defaultReq, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "http://127.0.0.1:1/api/tunnel/poll", nil)
+ defaultReq, err := http.NewRequestWithContext(t.Context(), http.MethodPost, "http://127.0.0.1:1/api/tunnel/poll", http.NoBody)
require.NoError(t, err)
_, err = http.DefaultClient.Do(defaultReq)
require.Error(t, err)
@@ -1942,7 +1941,7 @@ func TestTunnelClient_pollTunnelControlInternal_UsesConfiguredHTTPClient(t *test
}
func TestTunnelClient_connectAndServePoll_DoesNotOpenWebSocketWhenIdle(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 200*time.Millisecond)
defer cancel()
wsConnectedCh := make(chan struct{}, 1)
@@ -1987,7 +1986,7 @@ func TestTunnelClient_connectAndServePoll_DoesNotOpenWebSocketWhenIdle(t *testin
}
func TestTunnelClient_connectAndServePoll_RetriesAfterTransientPollError(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
var pollCount atomic.Int32
@@ -2016,7 +2015,7 @@ func TestTunnelClient_connectAndServePoll_RetriesAfterTransientPollError(t *test
}
defer func() { _ = conn.CloseNow() }()
- if _, _, err := conn.Read(r.Context()); err != nil {
+ if _, _, readErr := conn.Read(r.Context()); readErr != nil {
return
}
registerResp, err := json.Marshal(&TunnelMessage{
@@ -2028,7 +2027,7 @@ func TestTunnelClient_connectAndServePoll_RetriesAfterTransientPollError(t *test
if err != nil {
return
}
- if err := conn.Write(r.Context(), websocket.MessageText, registerResp); err != nil {
+ if writeErr := conn.Write(r.Context(), websocket.MessageText, registerResp); writeErr != nil {
return
}
@@ -2072,7 +2071,7 @@ func TestTunnelClient_stopPollManagedSessionInternal_DeadlineExceededReturnsTime
done: make(chan error),
}
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
err := (&TunnelClient{}).stopPollManagedSessionInternal(ctx, session)
@@ -2092,17 +2091,17 @@ func TestTunnelClient_syncPollManagedSessionInternal_IdleUsesBoundedStopTimeout(
done: make(chan error),
}
- nextSession, err := (&TunnelClient{}).syncPollManagedSessionInternal(context.Background(), session, TunnelStatusIdle)
+ nextSession, err := (&TunnelClient{}).syncPollManagedSessionInternal(t.Context(), session, TunnelStatusIdle)
require.Same(t, session, nextSession)
require.Error(t, err)
require.EqualError(t, err, "timed out waiting for poll-managed websocket session to stop")
- fencedSession, err := (&TunnelClient{}).syncPollManagedSessionInternal(context.Background(), nextSession, TunnelStatusRequired)
+ fencedSession, err := (&TunnelClient{}).syncPollManagedSessionInternal(t.Context(), nextSession, TunnelStatusRequired)
require.NoError(t, err)
require.Same(t, session, fencedSession)
started := time.Now()
- stillDraining, err := (&TunnelClient{}).syncPollManagedSessionInternal(context.Background(), nextSession, TunnelStatusIdle)
+ stillDraining, err := (&TunnelClient{}).syncPollManagedSessionInternal(t.Context(), nextSession, TunnelStatusIdle)
require.NoError(t, err)
require.Same(t, session, stillDraining)
require.Less(t, time.Since(started), defaultPollManagedSessionStopTimeout)
@@ -2165,7 +2164,7 @@ func startTestPollAndGRPCManagerInternal(t *testing.T, ctx context.Context, serv
}()
cleanup := func() {
- shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
+ shutdownCtx, shutdownCancel := context.WithTimeout(t.Context(), 5*time.Second)
defer shutdownCancel()
_ = httpServer.Shutdown(shutdownCtx)
grpcServer.Stop()
@@ -2179,7 +2178,7 @@ type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
if f == nil {
- return nil, fmt.Errorf("round tripper is nil")
+ return nil, errors.New("round tripper is nil")
}
return f(req)
}
@@ -2195,7 +2194,7 @@ func TestTunnelClient_InternalRequestSkipsSlogEcho(t *testing.T) {
conn := &capturingTunnelConnForHandleRequest{}
client.conn.Store(&connBox{conn: conn})
- client.handleRequest(context.Background(), conn, &TunnelMessage{
+ client.handleRequest(t.Context(), conn, &TunnelMessage{
ID: "req-legacy",
Type: MessageTypeRequest,
Method: http.MethodGet,
@@ -2214,7 +2213,7 @@ func TestTunnelClient_InternalRequestSkipsSlogEcho(t *testing.T) {
conn := &fakeTunnelConn{}
client.conn.Store(&connBox{conn: conn})
- client.handleRequestStreaming(context.Background(), conn, &TunnelMessage{
+ client.handleRequestStreaming(t.Context(), conn, &TunnelMessage{
ID: "req-stream",
Type: MessageTypeRequest,
Method: http.MethodGet,
@@ -2395,7 +2394,7 @@ func TestConnectAndServeWebSocket_CancelUnblocksMessageLoop(t *testing.T) {
close(registered)
// Go silent: keep reading so the socket stays open.
for {
- if _, _, err := conn.Read(r.Context()); err != nil {
+ if _, _, readErr := conn.Read(r.Context()); readErr != nil {
return
}
}
diff --git a/backend/pkg/libarcane/edge/client_transport_grpc.go b/backend/pkg/libarcane/edge/client_transport_grpc.go
index 4c147201b..6544c4ea5 100644
--- a/backend/pkg/libarcane/edge/client_transport_grpc.go
+++ b/backend/pkg/libarcane/edge/client_transport_grpc.go
@@ -70,8 +70,8 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {
}
defer func() { _ = conn.Close() }()
- if err := c.waitForGRPCReadyInternal(ctx, conn); err != nil {
- return fmt.Errorf("manager gRPC endpoint is not ready: %w", err)
+ if waitForGRPCReadyErr := c.waitForGRPCReadyInternal(ctx, conn); waitForGRPCReadyErr != nil {
+ return fmt.Errorf("manager gRPC endpoint is not ready: %w", waitForGRPCReadyErr)
}
// metadata.New lowercases the keys itself.
@@ -85,13 +85,16 @@ func (c *TunnelClient) connectAndServeGRPC(ctx context.Context) error {
return fmt.Errorf("failed to open tunnel stream: %w", err)
}
- if err := c.serveTunnelSessionInternal(ctx, NewGRPCAgentTunnelConn(stream, streamCancel), managerAddr); err != nil {
- if errors.Is(err, errTunnelRegistrationTimeout) {
+ if serveTunnelSessionErr := c.serveTunnelSessionInternal(ctx, NewGRPCAgentTunnelConn(stream, streamCancel), managerAddr); serveTunnelSessionErr != nil {
+ if errors.Is(serveTunnelSessionErr, errTunnelRegistrationTimeout) {
// The channel already reached Ready, so TCP/TLS works but gRPC
// framing was never answered end to end.
- return fmt.Errorf("%s: %w", "manager accepted the TCP/TLS connection but never answered gRPC tunnel registration; if a reverse proxy (Traefik/Pangolin/Nginx) fronts the manager, it is likely not forwarding gRPC (HTTP/2 with trailers) on /api/tunnel/connect", err)
+ return fmt.Errorf("%s: %w",
+ "manager accepted the TCP/TLS connection but never answered gRPC tunnel registration; "+
+ "if a reverse proxy (Traefik/Pangolin/Nginx) fronts the manager, it is likely not forwarding gRPC (HTTP/2 with trailers) on /api/tunnel/connect",
+ serveTunnelSessionErr)
}
- return err
+ return serveTunnelSessionErr
}
return nil
}
diff --git a/backend/pkg/libarcane/edge/client_transport_grpc_test.go b/backend/pkg/libarcane/edge/client_transport_grpc_test.go
index 0507fbc6c..2adf58aad 100644
--- a/backend/pkg/libarcane/edge/client_transport_grpc_test.go
+++ b/backend/pkg/libarcane/edge/client_transport_grpc_test.go
@@ -24,7 +24,7 @@ import (
func TestGRPCTunnel_RequestResponse(t *testing.T) {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-1"
GetRegistry().Unregister(envID)
@@ -66,9 +66,9 @@ func TestGRPCTunnel_RequestResponse(t *testing.T) {
agentErrCh := make(chan error, 1)
go func() {
- msg, err := stream.Recv()
- if err != nil {
- agentErrCh <- err
+ msg, recvErr := stream.Recv()
+ if recvErr != nil {
+ agentErrCh <- recvErr
return
}
@@ -78,10 +78,10 @@ func TestGRPCTunnel_RequestResponse(t *testing.T) {
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ if sendErr := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
CommandId: req.GetCommandId(),
- }}}); err != nil {
- agentErrCh <- err
+ }}}); sendErr != nil {
+ agentErrCh <- sendErr
return
}
@@ -112,7 +112,7 @@ func TestGRPCTunnel_RequestResponse(t *testing.T) {
func TestGRPCTunnel_RequestResponseStreamingChunks(t *testing.T) {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-stream-1"
GetRegistry().Unregister(envID)
@@ -152,9 +152,9 @@ func TestGRPCTunnel_RequestResponseStreamingChunks(t *testing.T) {
agentErrCh := make(chan error, 1)
go func() {
- msg, err := stream.Recv()
- if err != nil {
- agentErrCh <- err
+ msg, recvErr := stream.Recv()
+ if recvErr != nil {
+ agentErrCh <- recvErr
return
}
@@ -164,28 +164,28 @@ func TestGRPCTunnel_RequestResponseStreamingChunks(t *testing.T) {
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ if sendErr := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
CommandId: req.GetCommandId(),
- }}}); err != nil {
- agentErrCh <- err
+ }}}); sendErr != nil {
+ agentErrCh <- sendErr
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandOutput{CommandOutput: &tunnelpb.CommandOutput{
+ if sendErr2 := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandOutput{CommandOutput: &tunnelpb.CommandOutput{
CommandId: req.GetCommandId(),
Data: []byte("hello "),
Sequence: 0,
- }}}); err != nil {
- agentErrCh <- err
+ }}}); sendErr2 != nil {
+ agentErrCh <- sendErr2
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandOutput{CommandOutput: &tunnelpb.CommandOutput{
+ if sendErr3 := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandOutput{CommandOutput: &tunnelpb.CommandOutput{
CommandId: req.GetCommandId(),
Data: []byte("world"),
Sequence: 1,
- }}}); err != nil {
- agentErrCh <- err
+ }}}); sendErr3 != nil {
+ agentErrCh <- sendErr3
return
}
@@ -219,7 +219,7 @@ func TestGRPCTunnel_RequestResponseStreamingChunks(t *testing.T) {
func TestGRPCTunnel_MetadataAuthFallback(t *testing.T) {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-md-1"
GetRegistry().Unregister(envID)
@@ -266,7 +266,7 @@ func TestGRPCTunnel_MetadataAuthFallback(t *testing.T) {
func TestGRPCTunnel_MetadataAPIKeyFallback(t *testing.T) {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-md-api-key-1"
GetRegistry().Unregister(envID)
@@ -312,7 +312,7 @@ func TestGRPCTunnel_MetadataAPIKeyFallback(t *testing.T) {
func TestGRPCTunnel_InvalidTokenRejected(t *testing.T) {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-invalid-token-1"
GetRegistry().Unregister(envID)
@@ -342,8 +342,8 @@ func TestGRPCTunnel_InvalidTokenRejected(t *testing.T) {
stream, err := client.Connect(testGRPCOutgoingContextInternal(ctx, "invalid-token"))
require.NoError(t, err)
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: "invalid-token"}}}); err != nil {
- require.ErrorIs(t, err, io.EOF)
+ if sendErr := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_Register{Register: &tunnelpb.RegisterRequest{AgentToken: "invalid-token"}}}); sendErr != nil {
+ require.ErrorIs(t, sendErr, io.EOF)
}
_, err = stream.Recv()
@@ -357,7 +357,7 @@ func TestGRPCTunnel_InvalidTokenRejected(t *testing.T) {
func TestGRPCTunnel_FirstMessageMustBeRegister(t *testing.T) {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-first-msg-1"
GetRegistry().Unregister(envID)
@@ -401,7 +401,7 @@ func TestGRPCTunnel_FirstMessageMustBeRegister(t *testing.T) {
func TestGRPCTunnel_RegisterMessageRequiredOnEOF(t *testing.T) {
t.Helper()
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-eof-first-msg-1"
GetRegistry().Unregister(envID)
diff --git a/backend/pkg/libarcane/edge/client_transport_poll.go b/backend/pkg/libarcane/edge/client_transport_poll.go
index f17721bb9..6a52bf1c6 100644
--- a/backend/pkg/libarcane/edge/client_transport_poll.go
+++ b/backend/pkg/libarcane/edge/client_transport_poll.go
@@ -53,37 +53,37 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultPollManagedSessionStopTimeout)
defer cancel()
- if err := c.stopPollManagedSessionInternal(shutdownCtx, session); err != nil {
- slog.WarnContext(ctx, "Failed to stop poll-managed websocket session during shutdown", "error", err)
+ if stopPollManagedSessionErr := c.stopPollManagedSessionInternal(shutdownCtx, session); stopPollManagedSessionErr != nil {
+ slog.WarnContext(ctx, "Failed to stop poll-managed websocket session during shutdown", "error", stopPollManagedSessionErr)
}
}()
for {
- var err error
- session, err = consumePollManagedSessionInternal(session)
- if err != nil {
- return err
+ var operationErr error
+ session, operationErr = consumePollManagedSessionInternal(session)
+ if operationErr != nil {
+ return operationErr
}
if ctx.Err() != nil {
return ctx.Err()
}
- status, err := c.pollTunnelControlInternal(ctx, httpClient, pollURL, session != nil)
- if err != nil {
+ status, operationErr := c.pollTunnelControlInternal(ctx, httpClient, pollURL, session != nil)
+ if operationErr != nil {
if ctx.Err() != nil {
return ctx.Err()
}
retryInterval := retryBackoff.NextBackOff()
slog.WarnContext(ctx, "Poll control request failed, retrying after interval",
- "error", err,
+ "error", operationErr,
"interval", retryInterval,
)
- session, err = waitForNextPollCycleInternal(ctx, session, retryInterval)
- if err != nil {
- return err
+ session, operationErr = waitForNextPollCycleInternal(ctx, session, retryInterval)
+ if operationErr != nil {
+ return operationErr
}
continue
}
@@ -96,17 +96,17 @@ func (c *TunnelClient) connectAndServePoll(ctx context.Context) error {
retryBackoff.InitialInterval = interval
retryBackoff.Reset()
- session, err = c.syncPollManagedSessionInternal(ctx, session, status.Status)
- if err != nil {
- if !errors.Is(err, errPollManagedSessionStopTimeout) {
- return err
+ session, operationErr = c.syncPollManagedSessionInternal(ctx, session, status.Status)
+ if operationErr != nil {
+ if !errors.Is(operationErr, errPollManagedSessionStopTimeout) {
+ return operationErr
}
- slog.WarnContext(ctx, "Poll-managed tunnel is still draining; replacement remains fenced", "error", err)
+ slog.WarnContext(ctx, "Poll-managed tunnel is still draining; replacement remains fenced", "error", operationErr)
}
- session, err = waitForNextPollCycleInternal(ctx, session, interval)
- if err != nil {
- return err
+ session, operationErr = waitForNextPollCycleInternal(ctx, session, interval)
+ if operationErr != nil {
+ return operationErr
}
}
}
@@ -220,8 +220,8 @@ func (c *TunnelClient) pollTunnelControlInternal(ctx context.Context, httpClient
}
var pollResp TunnelPollResponse
- if err := json.UnmarshalRead(resp.Body, &pollResp); err != nil {
- return nil, fmt.Errorf("failed to decode poll response: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &pollResp); unmarshalReadErr != nil {
+ return nil, fmt.Errorf("failed to decode poll response: %w", unmarshalReadErr)
}
return &pollResp, nil
}
diff --git a/backend/pkg/libarcane/edge/command_client.go b/backend/pkg/libarcane/edge/command_client.go
index b5d3383e6..298a1edc6 100644
--- a/backend/pkg/libarcane/edge/command_client.go
+++ b/backend/pkg/libarcane/edge/command_client.go
@@ -81,21 +81,21 @@ func (c *CommandClient) Execute(ctx context.Context, tunnel *AgentTunnel, req *C
msg.Metadata = map[string]string{bodyTransferMetadataKey: transferID}
}
- if err := tunnel.Conn.Send(msg); err != nil {
- return nil, fmt.Errorf("tunnel request failed: %w", err)
+ if sendErr := tunnel.Conn.Send(msg); sendErr != nil {
+ return nil, fmt.Errorf("tunnel request failed: %w", sendErr)
}
if chunkRequestBody {
transferID := msg.Metadata[bodyTransferMetadataKey]
for sequence, offset := int64(0), 0; offset < len(req.Body); sequence++ {
end := min(offset+defaultCommandChunkSize, len(req.Body))
- if err := tunnel.Conn.Send(&TunnelMessage{
+ if sendErr2 := tunnel.Conn.Send(&TunnelMessage{
ID: transferID,
Type: MessageTypeFileChunk,
Body: req.Body[offset:end],
Sequence: sequence,
EOF: end == len(req.Body),
- }); err != nil {
- return nil, fmt.Errorf("tunnel request body transfer failed: %w", err)
+ }); sendErr2 != nil {
+ return nil, fmt.Errorf("tunnel request body transfer failed: %w", sendErr2)
}
offset = end
}
diff --git a/backend/pkg/libarcane/edge/commands_test.go b/backend/pkg/libarcane/edge/commands_test.go
index b0ee1aef3..6d3dc5c2a 100644
--- a/backend/pkg/libarcane/edge/commands_test.go
+++ b/backend/pkg/libarcane/edge/commands_test.go
@@ -1,7 +1,6 @@
package edge
import (
- "context"
"net/http"
"testing"
@@ -24,16 +23,47 @@ func TestResolveEdgeCommandName(t *testing.T) {
{name: "container edit", method: "POST", path: "/api/environments/0/containers/abc/edit", command: "container.edit", shouldHit: true},
{name: "container edit config wrong method", method: "POST", path: "/api/environments/0/containers/abc/edit-config", command: "container.edit_config", shouldHit: false},
{name: "container edit wrong method", method: "GET", path: "/api/environments/0/containers/abc/edit", command: "container.edit", shouldHit: false},
- {name: "container edit config stream rejected", method: "GET", path: "/api/environments/0/containers/abc/edit-config", stream: true, command: "container.edit_config", shouldHit: false},
+ {
+ name: "container edit config stream rejected",
+ method: "GET",
+ path: "/api/environments/0/containers/abc/edit-config",
+ stream: true,
+ command: "container.edit_config",
+ shouldHit: false,
+ },
{name: "container edit stream rejected", method: "POST", path: "/api/environments/0/containers/abc/edit", stream: true, command: "container.edit", shouldHit: false},
{name: "container start", method: "POST", path: "/api/environments/0/containers/abc/start", command: "container.start", shouldHit: true},
- {name: "volume workspace download", method: "GET", path: "/api/environments/0/volumes/data/workspace/file/download?relativePath=notes/readme.txt", command: "volume.workspace.download", shouldHit: true},
+ {
+ name: "volume workspace download",
+ method: "GET",
+ path: "/api/environments/0/volumes/data/workspace/file/download?relativePath=notes/readme.txt",
+ command: "volume.workspace.download",
+ shouldHit: true,
+ },
{name: "volume workspace list", method: "GET", path: "/api/environments/0/volumes/data/workspace", command: "volume.workspace.list", shouldHit: true},
- {name: "volume workspace read file", method: "GET", path: "/api/environments/0/volumes/data/workspace/file?relativePath=notes/readme.txt", command: "volume.workspace.read_file", shouldHit: true},
+ {
+ name: "volume workspace read file",
+ method: "GET",
+ path: "/api/environments/0/volumes/data/workspace/file?relativePath=notes/readme.txt",
+ command: "volume.workspace.read_file",
+ shouldHit: true,
+ },
{name: "volume workspace update", method: "PUT", path: "/api/environments/0/volumes/data/workspace", command: "volume.workspace.update", shouldHit: true},
{name: "project workspace list", method: "GET", path: "/api/environments/0/projects/p1/workspace", command: "project.workspace.list", shouldHit: true},
- {name: "project workspace read file", method: "GET", path: "/api/environments/0/projects/p1/workspace/file?relativePath=notes/readme.txt", command: "project.workspace.read_file", shouldHit: true},
- {name: "project workspace download", method: "GET", path: "/api/environments/0/projects/p1/workspace/file/download?relativePath=notes/readme.txt", command: "project.workspace.download", shouldHit: true},
+ {
+ name: "project workspace read file",
+ method: "GET",
+ path: "/api/environments/0/projects/p1/workspace/file?relativePath=notes/readme.txt",
+ command: "project.workspace.read_file",
+ shouldHit: true,
+ },
+ {
+ name: "project workspace download",
+ method: "GET",
+ path: "/api/environments/0/projects/p1/workspace/file/download?relativePath=notes/readme.txt",
+ command: "project.workspace.download",
+ shouldHit: true,
+ },
{name: "project workspace update", method: "PUT", path: "/api/environments/0/projects/p1/workspace", command: "project.workspace.update", shouldHit: true},
{name: "build workspace browse retained", method: "GET", path: "/api/environments/0/builds/browse", command: "build_workspace.browse.list", shouldHit: true},
{name: "legacy project files absent", method: "GET", path: "/api/environments/0/projects/p1/files", shouldHit: false},
@@ -95,7 +125,7 @@ func TestCollectCommandResponse(t *testing.T) {
pending.ResponseCh <- &TunnelMessage{ID: "cmd-1", Type: MessageTypeCommandComplete, Status: 200, Headers: map[string]string{"Content-Type": "text/plain"}, Body: []byte("world")}
require.NoError(t, tunnel.CloseWithReason(""))
- status, headers, body, err := collectCommandResponseInternal(context.Background(), tunnel, pending, "")
+ status, headers, body, err := collectCommandResponseInternal(t.Context(), tunnel, pending, "")
require.NoError(t, err)
require.Equal(t, 200, status)
require.Equal(t, "text/plain", headers["Content-Type"])
diff --git a/backend/pkg/libarcane/edge/poll_control.go b/backend/pkg/libarcane/edge/poll_control.go
index 1f4259369..fedefccd5 100644
--- a/backend/pkg/libarcane/edge/poll_control.go
+++ b/backend/pkg/libarcane/edge/poll_control.go
@@ -259,9 +259,9 @@ func (s *TunnelServer) HandlePoll(c *echo.Context) error {
)
return c.JSON(http.StatusUnauthorized, map[string]any{"error": "invalid agent token"})
}
- if err := s.requireRequestCertificateIdentityInternal(req, envID); err != nil {
- slog.WarnContext(ctx, "Rejected edge poll request with mismatched client certificate", "environment_id", envID, "error", err)
- return c.JSON(http.StatusUnauthorized, map[string]any{"error": err.Error()})
+ if requireRequestCertificateIdentityErr := s.requireRequestCertificateIdentityInternal(req, envID); requireRequestCertificateIdentityErr != nil {
+ slog.WarnContext(ctx, "Rejected edge poll request with mismatched client certificate", "environment_id", envID, "error", requireRequestCertificateIdentityErr)
+ return c.JSON(http.StatusUnauthorized, map[string]any{"error": requireRequestCertificateIdentityErr.Error()})
}
pollInterval := DefaultTunnelPollInterval
diff --git a/backend/pkg/libarcane/edge/proxy.go b/backend/pkg/libarcane/edge/proxy.go
index 88eacc16b..9698a4a70 100644
--- a/backend/pkg/libarcane/edge/proxy.go
+++ b/backend/pkg/libarcane/edge/proxy.go
@@ -71,8 +71,8 @@ func collectCommandResponseInternal(ctx context.Context, tunnel *AgentTunnel, pe
}
return 0, nil, nil, fmt.Errorf("edge tunnel closed while waiting for response: %w", ErrTunnelConnectionClosed)
case err := <-pending.failureCh:
- if done, status, headers, body, err := state.drainTerminalResponseInternal(pending.ResponseCh, method); done {
- return status, headers, body, err
+ if done, status, headers, body, drainTerminalResponseErr := state.drainTerminalResponseInternal(pending.ResponseCh, method); done {
+ return status, headers, body, drainTerminalResponseErr
}
return 0, nil, nil, err
case incoming, ok := <-pending.ResponseCh:
diff --git a/backend/pkg/libarcane/edge/proxy_test.go b/backend/pkg/libarcane/edge/proxy_test.go
index f5260155d..ca3918e7c 100644
--- a/backend/pkg/libarcane/edge/proxy_test.go
+++ b/backend/pkg/libarcane/edge/proxy_test.go
@@ -33,8 +33,8 @@ func setupMockAgentServer(t *testing.T, handler func(*TunnelMessage) *TunnelMess
defer func() { _ = conn.CloseNow() }()
for {
- _, data, err := conn.Read(r.Context())
- if err != nil {
+ _, data, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
@@ -58,8 +58,8 @@ func setupMockAgentServer(t *testing.T, handler func(*TunnelMessage) *TunnelMess
// We need a loop to read responses from the tunnel and dispatch them to pending
go func() {
for {
- msg, err := tunnel.Conn.Receive()
- if err != nil {
+ msg, receiveErr := tunnel.Conn.Receive()
+ if receiveErr != nil {
return
}
if req, ok := tunnel.Pending.Load(msg.ID); ok {
@@ -85,7 +85,7 @@ func TestProxyRequest(t *testing.T) {
defer server.Close()
defer func() { _ = tunnel.CloseWithReason("") }()
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
defer cancel()
status, headers, body, err := ProxyRequest(ctx, tunnel, http.MethodGet, "/api/health", "", nil, nil)
@@ -123,7 +123,7 @@ func TestProxyHTTPRequest(t *testing.T) {
}
func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-grpc-proxy-http-1"
GetRegistry().Unregister(envID)
@@ -163,9 +163,9 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
agentErrCh := make(chan error, 1)
go func() {
- msg, err := stream.Recv()
- if err != nil {
- agentErrCh <- err
+ msg, recvErr := stream.Recv()
+ if recvErr != nil {
+ agentErrCh <- recvErr
return
}
@@ -200,10 +200,10 @@ func TestProxyHTTPRequest_GRPCTunnel(t *testing.T) {
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ if sendErr := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
CommandId: req.GetCommandId(),
- }}}); err != nil {
- agentErrCh <- err
+ }}}); sendErr != nil {
+ agentErrCh <- sendErr
return
}
@@ -255,7 +255,7 @@ func TestDoRequest(t *testing.T) {
registry.Register("env-do-req", tunnel)
defer registry.Unregister("env-do-req")
- ctx := context.Background()
+ ctx := t.Context()
status, body, err := DoRequest(ctx, "env-do-req", "GET", "/api/health", nil)
require.NoError(t, err)
@@ -264,7 +264,7 @@ func TestDoRequest(t *testing.T) {
}
func TestDoRequest_NoTunnel(t *testing.T) {
- _, _, err := DoRequest(context.Background(), "non-existent", "GET", "/", nil)
+ _, _, err := DoRequest(t.Context(), "non-existent", "GET", "/", nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "no active tunnel")
}
@@ -274,7 +274,7 @@ func TestCommandRequestFailsWhenTunnelCloses(t *testing.T) {
errCh := make(chan error, 1)
go func() {
- _, err := DefaultCommandClient.Execute(context.Background(), tunnel, &CommandRequest{
+ _, err := DefaultCommandClient.Execute(t.Context(), tunnel, &CommandRequest{
Method: http.MethodGet,
Path: "/api/health",
})
@@ -456,7 +456,7 @@ func TestHandleRequest_SetsHostField(t *testing.T) {
conn := &capturingTunnelConnForHandleRequest{}
client.conn.Store(&connBox{conn: conn})
- client.handleRequest(context.Background(), conn, &TunnelMessage{
+ client.handleRequest(t.Context(), conn, &TunnelMessage{
ID: "req-host-1",
Type: MessageTypeRequest,
Method: http.MethodGet,
@@ -488,7 +488,7 @@ func TestHandleRequest_ForwardsBody(t *testing.T) {
conn := &capturingTunnelConnForHandleRequest{}
client.conn.Store(&connBox{conn: conn})
- client.handleRequest(context.Background(), conn, &TunnelMessage{
+ client.handleRequest(t.Context(), conn, &TunnelMessage{
ID: "req-body-1",
Type: MessageTypeRequest,
Method: http.MethodPost,
@@ -521,7 +521,7 @@ func TestHandleRequest_NoBrowserHeadersInTunnelMessage(t *testing.T) {
client.conn.Store(&connBox{conn: conn})
// Simulate an old manager that doesn't strip Origin
- client.handleRequest(context.Background(), conn, &TunnelMessage{
+ client.handleRequest(t.Context(), conn, &TunnelMessage{
ID: "req-origin-1",
Type: MessageTypeRequest,
Method: http.MethodPost,
@@ -597,8 +597,8 @@ func TestProxyHTTPRequest_BodyPreservation_WebSocket(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- _, data, err := conn.Read(r.Context())
- if err != nil {
+ _, data, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
@@ -630,8 +630,8 @@ func TestProxyHTTPRequest_BodyPreservation_WebSocket(t *testing.T) {
go func() {
for {
- msg, err := tunnel.Conn.Receive()
- if err != nil {
+ msg, receiveErr := tunnel.Conn.Receive()
+ if receiveErr != nil {
return
}
if req, ok := tunnel.Pending.Load(msg.ID); ok {
diff --git a/backend/pkg/libarcane/edge/registry.go b/backend/pkg/libarcane/edge/registry.go
index ad03c473c..776c633a3 100644
--- a/backend/pkg/libarcane/edge/registry.go
+++ b/backend/pkg/libarcane/edge/registry.go
@@ -114,14 +114,21 @@ func (r *TunnelRegistry) Register(envID string, tunnel *AgentTunnel) {
slog.Error("Failed to register edge agent tunnel", "environment_id", envID, "error", "tunnel is required")
return
}
- previous, err := r.tunnels.ApplyTyped(context.Background(), "register edge tunnel", func(tunnels map[string]*AgentTunnel) (*AgentTunnel, bool, error) {
- if r.stopped.Load() {
- return nil, false, errors.New("edge tunnel registry stopped")
- }
- previous := tunnels[envID]
- tunnels[envID] = tunnel
- return previous, true, nil
- })
+ //nolint:forbidigo // Legacy registry operation has no caller context and only mutates in-memory state.
+ previous,
+ err := r.tunnels.ApplyTyped(context.Background(),
+ "register edge tunnel",
+ func(tunnels map[string]*AgentTunnel) (*AgentTunnel,
+ bool,
+ error,
+ ) {
+ if r.stopped.Load() {
+ return nil, false, errors.New("edge tunnel registry stopped")
+ }
+ previous := tunnels[envID]
+ tunnels[envID] = tunnel
+ return previous, true, nil
+ })
if err != nil {
slog.Error("Failed to register edge agent tunnel", "environment_id", envID, "error", err)
return
@@ -191,7 +198,7 @@ func (r *TunnelRegistry) RegisterSession(ctx context.Context, tunnel *AgentTunne
// Unregister removes a tunnel from the registry
func (r *TunnelRegistry) Unregister(envID string) {
- tunnel, removed, err := r.tunnels.Remove(context.Background(), "unregister edge tunnel", envID)
+ tunnel, removed, err := r.tunnels.Remove(context.Background(), "unregister edge tunnel", envID) //nolint:forbidigo // Legacy registry operation has no caller context and only mutates in-memory state.
if err != nil {
slog.Error("Failed to unregister edge agent tunnel", "environment_id", envID, "error", err)
return
diff --git a/backend/pkg/libarcane/edge/registry_test.go b/backend/pkg/libarcane/edge/registry_test.go
index b1c098d12..206afdeaa 100644
--- a/backend/pkg/libarcane/edge/registry_test.go
+++ b/backend/pkg/libarcane/edge/registry_test.go
@@ -207,11 +207,11 @@ func TestTunnelRegistryPublishesReplacementBeforeClosingPreviousInternal(t *test
replacement.AgentInstance = "agent-a"
registered := make(chan bool, 1)
go func() {
- accepted, _, _, registerErr := registry.RegisterSession(t.Context(), replacement, TunnelStaleTimeout)
+ localAccepted, _, _, registerErr := registry.RegisterSession(t.Context(), replacement, TunnelStaleTimeout)
if !assert.NoError(t, registerErr) {
return
}
- registered <- accepted
+ registered <- localAccepted
}()
select {
@@ -225,7 +225,7 @@ func TestTunnelRegistryPublishesReplacementBeforeClosingPreviousInternal(t *test
close(previousConn.releaseClose)
require.True(t, <-registered)
- stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
require.NoError(t, registry.Stop(stopCtx))
}
@@ -233,7 +233,7 @@ func TestTunnelRegistryPublishesReplacementBeforeClosingPreviousInternal(t *test
func TestTunnelRegistryRejectsRegistrationAfterStopInternal(t *testing.T) {
registry := NewTunnelRegistry()
- stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
require.NoError(t, registry.Stop(stopCtx))
diff --git a/backend/pkg/libarcane/edge/remenv_test.go b/backend/pkg/libarcane/edge/remenv_test.go
index 544c34f6b..0a1f86ce5 100644
--- a/backend/pkg/libarcane/edge/remenv_test.go
+++ b/backend/pkg/libarcane/edge/remenv_test.go
@@ -100,12 +100,12 @@ func TestCopyRequestHeaders_SkipsExpectedHeaders(t *testing.T) {
func TestSetAuthHeader_ForwardsAPIKeyAndAuthorization(t *testing.T) {
e := echo.New()
w := httptest.NewRecorder()
- req0 := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req0 := httptest.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req0.Header.Set(HeaderAPIKey, "api-token")
req0.Header.Set(HeaderAuthorization, "Bearer auth")
c := e.NewContext(req0, w)
- req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://remote", nil)
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://remote", http.NoBody)
require.NoError(t, err)
SetAuthHeader(req, c)
@@ -116,11 +116,11 @@ func TestSetAuthHeader_ForwardsAPIKeyAndAuthorization(t *testing.T) {
func TestSetAuthHeader_UsesCookieTokenWhenNoAuthorization(t *testing.T) {
e := echo.New()
w := httptest.NewRecorder()
- req0 := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req0 := httptest.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req0.AddCookie(&http.Cookie{Name: "token", Value: "cookie-token"})
c := e.NewContext(req0, w)
- req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://remote", nil)
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://remote", http.NoBody)
require.NoError(t, err)
SetAuthHeader(req, c)
@@ -128,7 +128,7 @@ func TestSetAuthHeader_UsesCookieTokenWhenNoAuthorization(t *testing.T) {
}
func TestSetAgentToken(t *testing.T) {
- req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://remote", nil)
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://remote", http.NoBody)
require.NoError(t, err)
SetAgentToken(req, nil)
@@ -142,7 +142,7 @@ func TestSetAgentToken(t *testing.T) {
}
func TestSetForwardedHeaders(t *testing.T) {
- req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "http://remote", nil)
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://remote", http.NoBody)
require.NoError(t, err)
SetForwardedHeaders(req, "1.2.3.4", "example.com")
@@ -204,7 +204,7 @@ func TestGetSkipHeaders_ContainsExpectedEntries(t *testing.T) {
func TestBuildWebSocketHeaders_UsesAuthorizationHeaderAndAddsAgentToken(t *testing.T) {
e := echo.New()
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req := httptest.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set(HeaderAPIKey, "api-key")
req.Header.Set(HeaderAuthorization, "Bearer auth")
req.Header.Set(HeaderCookie, "session=abc")
@@ -222,7 +222,7 @@ func TestBuildWebSocketHeaders_UsesAuthorizationHeaderAndAddsAgentToken(t *testi
func TestBuildWebSocketHeaders_UsesCookieTokenAsBearer(t *testing.T) {
e := echo.New()
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req := httptest.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.AddCookie(&http.Cookie{Name: "token", Value: "cookie-token"})
c := e.NewContext(req, w)
@@ -233,7 +233,7 @@ func TestBuildWebSocketHeaders_UsesCookieTokenAsBearer(t *testing.T) {
func TestBuildWebSocketHeaders_ForwardsCookieHeaderWhenNoAuthPresent(t *testing.T) {
e := echo.New()
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
+ req := httptest.NewRequest(http.MethodGet, "http://example.com", http.NoBody)
req.Header.Set(HeaderCookie, "session=abc")
c := e.NewContext(req, w)
@@ -275,15 +275,15 @@ func newTestRemenvClientInternal(timeout time.Duration) *remenv.Client {
return nil
}
- return fmt.Errorf("edge agent is not connected (no active tunnel)")
+ return errors.New("edge agent is not connected (no active tunnel)")
},
DoFunc: func(ctx context.Context, envID, method, path string, headers map[string]string, body []byte) (*remenv.Response, error) {
tunnel, ok := GetRegistry().Get(envID).Get()
if !ok {
- return nil, fmt.Errorf("no active tunnel for environment %s", envID)
+ return nil, errors.New("no active tunnel for environment " + envID)
}
if tunnel.Conn.IsClosed() {
- return nil, fmt.Errorf("tunnel for environment %s is closed", envID)
+ return nil, errors.New("tunnel for environment " + envID + " is closed")
}
statusCode, respHeaders, respBody, err := ProxyRequest(ctx, tunnel, method, path, "", headers, body)
@@ -319,7 +319,7 @@ func TestRemenvClient_EdgeWithTunnel(t *testing.T) {
client := newTestRemenvClientInternal(1 * time.Second)
- resp, err := client.Do(context.Background(), remenv.Request{
+ resp, err := client.Do(t.Context(), remenv.Request{
EnvironmentID: envID,
IsEdge: true,
Method: http.MethodGet,
@@ -336,7 +336,7 @@ func TestRemenvClient_EdgeWithTunnel(t *testing.T) {
func TestRemenvClient_EdgeNoTunnel(t *testing.T) {
client := newTestRemenvClientInternal(1 * time.Second)
- _, err := client.Do(context.Background(), remenv.Request{
+ _, err := client.Do(t.Context(), remenv.Request{
EnvironmentID: "env-edge-missing",
IsEdge: true,
Method: http.MethodGet,
@@ -350,7 +350,7 @@ func TestRemenvClient_EdgeNoTunnel(t *testing.T) {
}
func TestRemenvClient_EdgeWithGRPCTunnel(t *testing.T) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
envID := "env-edge-grpc-1"
GetRegistry().Unregister(envID)
@@ -390,9 +390,9 @@ func TestRemenvClient_EdgeWithGRPCTunnel(t *testing.T) {
agentErrCh := make(chan error, 1)
go func() {
- msg, err := stream.Recv()
- if err != nil {
- agentErrCh <- err
+ msg, recvErr := stream.Recv()
+ if recvErr != nil {
+ agentErrCh <- recvErr
return
}
@@ -423,10 +423,10 @@ func TestRemenvClient_EdgeWithGRPCTunnel(t *testing.T) {
return
}
- if err := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
+ if sendErr := stream.Send(&tunnelpb.AgentMessage{Payload: &tunnelpb.AgentMessage_CommandAck{CommandAck: &tunnelpb.CommandAck{
CommandId: req.GetCommandId(),
- }}}); err != nil {
- agentErrCh <- err
+ }}}); sendErr != nil {
+ agentErrCh <- sendErr
return
}
diff --git a/backend/pkg/libarcane/edge/server.go b/backend/pkg/libarcane/edge/server.go
index 37c158bc9..71fd72b34 100644
--- a/backend/pkg/libarcane/edge/server.go
+++ b/backend/pkg/libarcane/edge/server.go
@@ -168,8 +168,8 @@ func (s *TunnelServer) HandleConnect(c *echo.Context) error {
_ = tunnelConn.Close()
return nil
}
- if err := s.requireRequestCertificateIdentityInternal(req, envID); err != nil {
- slog.WarnContext(ctx, "Rejected websocket edge tunnel with mismatched client certificate", "environment_id", envID, "error", err)
+ if requireRequestCertificateIdentityErr := s.requireRequestCertificateIdentityInternal(req, envID); requireRequestCertificateIdentityErr != nil {
+ slog.WarnContext(ctx, "Rejected websocket edge tunnel with mismatched client certificate", "environment_id", envID, "error", requireRequestCertificateIdentityErr)
_ = tunnelConn.Send(&TunnelMessage{Type: MessageTypeRegisterResponse, Accepted: false, Error: "client certificate does not match environment"})
_ = tunnelConn.Close()
return nil
@@ -243,8 +243,8 @@ func (s *TunnelServer) HandleMTLSEnroll(c *echo.Context) error {
return c.JSON(http.StatusNotFound, map[string]any{"error": "edge mTLS enrollment assets unavailable"})
}
assets.Reenrolled = previouslyEnrolled
- if err := recordManagerMTLSEnrollmentInternal(s.cfg, envID, now); err != nil {
- slog.ErrorContext(ctx, "Failed to record edge mTLS enrollment state", "environment_id", envID, "error", err)
+ if recordManagerMTLSEnrollmentErr := recordManagerMTLSEnrollmentInternal(s.cfg, envID, now); recordManagerMTLSEnrollmentErr != nil {
+ slog.ErrorContext(ctx, "Failed to record edge mTLS enrollment state", "environment_id", envID, "error", recordManagerMTLSEnrollmentErr)
return c.JSON(http.StatusInternalServerError, map[string]any{"error": "failed to record edge mTLS enrollment state"})
}
if assets.Reenrolled {
@@ -282,8 +282,8 @@ func (s *TunnelServer) Connect(stream grpc.BidiStreamingServer[tunnelpb.AgentMes
if !ok || envID == "" {
return status.Error(codes.Unauthenticated, "authenticated environment is missing from stream context")
}
- if err := s.requireCertificateIdentityFromContextInternal(ctx, envID); err != nil {
- return status.Error(codes.Unauthenticated, err.Error())
+ if requireCertificateIdentityFromContextErr := s.requireCertificateIdentityFromContextInternal(ctx, envID); requireCertificateIdentityFromContextErr != nil {
+ return status.Error(codes.Unauthenticated, requireCertificateIdentityFromContextErr.Error())
}
managerConn := NewGRPCManagerTunnelConn(stream)
@@ -416,7 +416,7 @@ func (s *TunnelServer) manageConnectedTunnel(ctx, callbackCtx context.Context, t
// learns what this manager supports (older agents ignore extra strings).
capabilities := kit.Unique(append(slices.Clone(tunnel.Capabilities), tunnelCapabilityProtoParity, tunnelCapabilityChunkedRequest))
- if err := tunnel.Conn.Send(&TunnelMessage{
+ if sendErr := tunnel.Conn.Send(&TunnelMessage{
Type: MessageTypeRegisterResponse,
Accepted: true,
EnvironmentID: tunnel.EnvironmentID,
@@ -424,8 +424,8 @@ func (s *TunnelServer) manageConnectedTunnel(ctx, callbackCtx context.Context, t
SecurityMode: tunnel.SecurityMode,
Capabilities: capabilities,
DrainPrevious: drainPrevious,
- }); err != nil {
- slog.WarnContext(ctx, "Failed to send register response", "environment_id", tunnel.EnvironmentID, "error", err)
+ }); sendErr != nil {
+ slog.WarnContext(ctx, "Failed to send register response", "environment_id", tunnel.EnvironmentID, "error", sendErr)
_ = tunnel.CloseWithReason("")
removed, active := s.registry.UnregisterCurrent(callbackCtx, tunnel.EnvironmentID, tunnel)
if removed && !active {
@@ -637,8 +637,8 @@ func (s *TunnelServer) authStreamInterceptorInternal() grpc.StreamServerIntercep
if err != nil {
return status.Error(codes.Unauthenticated, "invalid agent token")
}
- if err := s.requireCertificateIdentityFromContextInternal(ss.Context(), envID); err != nil {
- return status.Error(codes.Unauthenticated, err.Error())
+ if requireCertificateIdentityFromContextErr := s.requireCertificateIdentityFromContextInternal(ss.Context(), envID); requireCertificateIdentityFromContextErr != nil {
+ return status.Error(codes.Unauthenticated, requireCertificateIdentityFromContextErr.Error())
}
ctx := context.WithValue(ss.Context(), resolvedEnvironmentIDKey{}, envID)
diff --git a/backend/pkg/libarcane/edge/server_test.go b/backend/pkg/libarcane/edge/server_test.go
index d593f9af0..26ce4a991 100644
--- a/backend/pkg/libarcane/edge/server_test.go
+++ b/backend/pkg/libarcane/edge/server_test.go
@@ -319,7 +319,7 @@ func TestTunnelConnectRouteRegistration(t *testing.T) {
// Verify route exists (simplistic check by trying to hit it)
w := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", http.NoBody)
router.ServeHTTP(w, req)
// Plain HTTP requests hit the route but fail the websocket upgrade;
@@ -346,7 +346,7 @@ func TestTunnelServer_HandleMTLSEnroll(t *testing.T) {
router := echo.New()
router.POST("/enroll", server.HandleMTLSEnroll)
- req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req := httptest.NewRequest(http.MethodPost, "/enroll", http.NoBody)
req.Header.Set(HeaderAgentToken, "valid-token")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
@@ -386,7 +386,7 @@ func TestTunnelServer_HandleMTLSEnroll_ServesCachedAssetsDuringCooldown(t *testi
router := echo.New()
router.POST("/enroll", server.HandleMTLSEnroll)
- req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req := httptest.NewRequest(http.MethodPost, "/enroll", http.NoBody)
req.Header.Set(HeaderAgentToken, "valid-token")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
@@ -396,7 +396,7 @@ func TestTunnelServer_HandleMTLSEnroll_ServesCachedAssetsDuringCooldown(t *testi
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &firstResp))
require.Len(t, firstResp.Files, 3)
- req = httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req = httptest.NewRequest(http.MethodPost, "/enroll", http.NoBody)
req.Header.Set(HeaderAgentToken, "valid-token")
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
@@ -429,7 +429,7 @@ func TestTunnelServer_HandleMTLSEnroll_AllowsRepeatAfterCooldownAndMarksReenroll
router := echo.New()
router.POST("/enroll", server.HandleMTLSEnroll)
- req := httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req := httptest.NewRequest(http.MethodPost, "/enroll", http.NoBody)
req.Header.Set(HeaderAgentToken, "valid-token")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
@@ -441,7 +441,7 @@ func TestTunnelServer_HandleMTLSEnroll_AllowsRepeatAfterCooldownAndMarksReenroll
oldEnrollment := time.Now().Add(-(managerMTLSReenrollCooldown + time.Minute)).UTC().Format(time.RFC3339Nano) + "\n"
require.NoError(t, os.WriteFile(markerPath, []byte(oldEnrollment), 0o600))
- req = httptest.NewRequest(http.MethodPost, "/enroll", nil)
+ req = httptest.NewRequest(http.MethodPost, "/enroll", http.NoBody)
req.Header.Set(HeaderAgentToken, "valid-token")
w = httptest.NewRecorder()
router.ServeHTTP(w, req)
@@ -451,7 +451,7 @@ func TestTunnelServer_HandleMTLSEnroll_AllowsRepeatAfterCooldownAndMarksReenroll
func TestTunnelServer_CleanupLoop(t *testing.T) {
server := NewTunnelServerWithRegistry(GetRegistry(), nil, nil)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
// Run cleanup loop
go server.StartCleanupLoop(ctx)
@@ -469,7 +469,7 @@ func TestTunnelServer_resolveEnvironment_TrimsToken(t *testing.T) {
return "env-trimmed", nil
}, nil)
- envID, err := server.resolveEnvironment(context.Background(), " valid-token ")
+ envID, err := server.resolveEnvironment(t.Context(), " valid-token ")
require.NoError(t, err)
assert.Equal(t, "env-trimmed", envID)
assert.Equal(t, "valid-token", resolvedToken)
@@ -478,7 +478,7 @@ func TestTunnelServer_resolveEnvironment_TrimsToken(t *testing.T) {
func TestTunnelServer_resolveEnvironment_Errors(t *testing.T) {
t.Run("missing resolver", func(t *testing.T) {
server := NewTunnelServerWithRegistry(GetRegistry(), nil, nil)
- _, err := server.resolveEnvironment(context.Background(), "token")
+ _, err := server.resolveEnvironment(t.Context(), "token")
require.Error(t, err)
assert.Contains(t, err.Error(), "edge resolver is not configured")
})
@@ -488,7 +488,7 @@ func TestTunnelServer_resolveEnvironment_Errors(t *testing.T) {
return "env", nil
}, nil)
- _, err := server.resolveEnvironment(context.Background(), " ")
+ _, err := server.resolveEnvironment(t.Context(), " ")
require.Error(t, err)
assert.Contains(t, err.Error(), "agent token required")
})
@@ -496,7 +496,7 @@ func TestTunnelServer_resolveEnvironment_Errors(t *testing.T) {
func TestTokenFromMetadata(t *testing.T) {
t.Run("prefers agent token and trims whitespace", func(t *testing.T) {
- ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
+ ctx := metadata.NewIncomingContext(t.Context(), metadata.Pairs(
strings.ToLower(HeaderAgentToken), " agent-token ",
strings.ToLower(HeaderAPIKey), "api-token",
))
@@ -505,7 +505,7 @@ func TestTokenFromMetadata(t *testing.T) {
})
t.Run("falls back to api key", func(t *testing.T) {
- ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(
+ ctx := metadata.NewIncomingContext(t.Context(), metadata.Pairs(
strings.ToLower(HeaderAPIKey), "api-token",
))
@@ -513,7 +513,7 @@ func TestTokenFromMetadata(t *testing.T) {
})
t.Run("returns empty when metadata missing", func(t *testing.T) {
- assert.Empty(t, tokenFromMetadataInternal(context.Background()))
+ assert.Empty(t, tokenFromMetadataInternal(t.Context()))
})
}
@@ -568,7 +568,7 @@ func TestTunnelServer_HandleEventCallback(t *testing.T) {
deliveryTimer := time.NewTimer(streamDeliveryTimeout)
deliveryTimer.Stop()
defer deliveryTimer.Stop()
- server.handleTunnelMessage(context.Background(), tunnel, &TunnelMessage{
+ server.handleTunnelMessage(t.Context(), tunnel, &TunnelMessage{
Type: MessageTypeEvent,
Event: &TunnelEvent{
Type: "container.start",
@@ -639,7 +639,7 @@ func TestTunnelServer_ManageConnectedTunnel_RegistersBeforeSendingGRPCRegisterRe
}
tunnel := NewAgentTunnelWithConn(envID, conn)
- server.manageConnectedTunnel(context.Background(), context.Background(), tunnel)
+ server.manageConnectedTunnel(t.Context(), t.Context(), tunnel)
_, ok := server.registry.Get(envID).Get()
assert.False(t, ok)
@@ -650,14 +650,14 @@ func TestTunnelServer_ManageConnectedTunnel_UnregistersAfterConnectionContextCan
server := NewTunnelServerWithRegistry(registry, nil, nil)
tunnel := NewAgentTunnelWithConn("env-cancelled-disconnect", &registerResponseOrderConn{recvErr: context.Canceled})
- connectionCtx, cancelConnection := context.WithCancel(context.Background())
+ connectionCtx, cancelConnection := context.WithCancel(t.Context())
cancelConnection()
server.manageConnectedTunnel(connectionCtx, context.WithoutCancel(connectionCtx), tunnel)
_, ok := registry.Get(tunnel.EnvironmentID).Get()
require.False(t, ok)
- stopCtx, cancelStop := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancelStop := context.WithTimeout(t.Context(), time.Second)
defer cancelStop()
require.NoError(t, registry.Stop(stopCtx))
}
diff --git a/backend/pkg/libarcane/edge/tls.go b/backend/pkg/libarcane/edge/tls.go
index 4a9563b3b..8612091e3 100644
--- a/backend/pkg/libarcane/edge/tls.go
+++ b/backend/pkg/libarcane/edge/tls.go
@@ -130,8 +130,8 @@ func PrepareManagerMTLSAssetsWithContext(ctx context.Context, cfg *Config) error
return err
}
- if _, _, _, err := ensureManagerCAInternal(ctx, assetsDir); err != nil {
- return err
+ if _, _, _, ensureManagerCAErr := ensureManagerCAInternal(ctx, assetsDir); ensureManagerCAErr != nil {
+ return ensureManagerCAErr
}
cfg.EdgeMTLSCAFile = filepath.Join(assetsDir, generatedMTLSCACertFileName)
@@ -167,8 +167,8 @@ func AvailableManagerMTLSCAPath(cfg *Config) (string, error) {
}
// os.* rather than acfs: the assets dir may be user-configured to anywhere on
// the host, so no confinement root handle is in scope for this probe.
- if _, err := os.Stat(caPath); err != nil {
- return "", fmt.Errorf("stat edge mTLS CA: %w", err)
+ if _, statErr := os.Stat(caPath); statErr != nil {
+ return "", fmt.Errorf("stat edge mTLS CA: %w", statErr)
}
return caPath, nil
}
@@ -272,10 +272,10 @@ func managerMTLSEnrollmentMarkerPathInternal(cfg *Config, envID string) (string,
return filepath.Join(assetsDir, generatedClientMTLSSubdir, safeEnvID, generatedMTLSEnrolledName), nil
}
-func readMTLSEnrollmentMarkerInternal(path string) (time.Time, error) {
+func readMTLSEnrollmentMarkerInternal(localPath string) (time.Time, error) {
// Path-only helper; callers derive the path from the assets root, kept on
// os.* with the other path-only readers.
- content, err := os.ReadFile(path)
+ content, err := os.ReadFile(localPath)
if err != nil {
return time.Time{}, err
}
@@ -285,7 +285,7 @@ func readMTLSEnrollmentMarkerInternal(path string) (time.Time, error) {
}
enrolledAt, err := time.Parse(time.RFC3339Nano, trimmed)
if err != nil {
- return time.Time{}, fmt.Errorf("failed to parse edge mTLS enrollment marker %s: %w", path, err)
+ return time.Time{}, fmt.Errorf("failed to parse edge mTLS enrollment marker %s: %w", localPath, err)
}
return enrolledAt, nil
}
@@ -325,8 +325,8 @@ func EnsureAgentMTLSAssets(ctx context.Context, cfg *Config) error {
needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())
if !needsEnrollment {
if !fileExistsInternal(filepath.Join(assetsDir, generatedMTLSEnrolledName)) {
- if err := acfs.Write(ctx, assetsDir, "/"+generatedMTLSEnrolledName, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), acfs.WriteOptions{Mode: 0o600}); err != nil {
- return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)
+ if writeErr := acfs.Write(ctx, assetsDir, "/"+generatedMTLSEnrolledName, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), acfs.WriteOptions{Mode: 0o600}); writeErr != nil {
+ return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", writeErr)
}
}
setAgentMTLSAssetPathsInternal(cfg, assetsDir)
@@ -335,12 +335,12 @@ func EnsureAgentMTLSAssets(ctx context.Context, cfg *Config) error {
slog.WarnContext(ctx, "Existing edge mTLS assets need renewal; enrolling new assets", "reason", reason, "cert_path", certPath)
}
- if err := enrollAgentMTLSAssetsInternal(ctx, cfg, assetsDir, certPath, keyPath); err != nil {
+ if enrollAgentMTLSAssetsErr := enrollAgentMTLSAssetsInternal(ctx, cfg, assetsDir, certPath, keyPath); enrollAgentMTLSAssetsErr != nil {
if NormalizeEdgeMTLSMode(cfg.EdgeMTLSMode) != EdgeMTLSModeRequired {
- slog.WarnContext(ctx, "Edge mTLS enrollment failed; proceeding without client certificate", "error", err)
+ slog.WarnContext(ctx, "Edge mTLS enrollment failed; proceeding without client certificate", "error", enrollAgentMTLSAssetsErr)
return nil
}
- return err
+ return enrollAgentMTLSAssetsErr
}
return nil
}
@@ -362,7 +362,7 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,
return fmt.Errorf("failed to configure edge mTLS enrollment client: %w", err)
}
- req, err := http.NewRequestWithContext(ctx, http.MethodPost, managerBaseURL+"/api/tunnel/mtls/enroll", nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, managerBaseURL+"/api/tunnel/mtls/enroll", http.NoBody)
if err != nil {
return fmt.Errorf("failed to create edge mTLS enrollment request: %w", err)
}
@@ -382,8 +382,8 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,
}
var enrollResp enrollMTLSResponse
- if err := json.UnmarshalRead(io.LimitReader(resp.Body, maxEnrollResponseBytes), &enrollResp); err != nil {
- return fmt.Errorf("failed to decode edge mTLS enrollment response: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(io.LimitReader(resp.Body, maxEnrollResponseBytes), &enrollResp); unmarshalReadErr != nil {
+ return fmt.Errorf("failed to decode edge mTLS enrollment response: %w", unmarshalReadErr)
}
if len(enrollResp.Files) == 0 {
return errors.New("edge mTLS enrollment response did not include any files")
@@ -391,21 +391,21 @@ func enrollAgentMTLSAssetsInternal(ctx context.Context, cfg *Config, assetsDir,
// The assets dir is the confinement root for the writes below, so it is
// created through os before acfs opens it.
- if err := os.MkdirAll(assetsDir, utils.DirPerm); err != nil {
- return fmt.Errorf("failed to create edge mTLS asset dir: %w", err)
+ if mkdirAllErr := os.MkdirAll(assetsDir, utils.DirPerm); mkdirAllErr != nil {
+ return fmt.Errorf("failed to create edge mTLS asset dir: %w", mkdirAllErr)
}
for _, file := range enrollResp.Files {
perm := kit.Ternary(strings.TrimSpace(file.Permissions) == "0600", 0o600, utils.FilePerm)
- if err := acfs.Write(ctx, assetsDir, "/"+filepath.Base(file.Name), []byte(file.Content), acfs.WriteOptions{Mode: perm}); err != nil {
- return fmt.Errorf("failed to write edge mTLS asset %s: %w", file.Name, err)
+ if writeErr := acfs.Write(ctx, assetsDir, "/"+filepath.Base(file.Name), []byte(file.Content), acfs.WriteOptions{Mode: perm}); writeErr != nil {
+ return fmt.Errorf("failed to write edge mTLS asset %s: %w", file.Name, writeErr)
}
}
needsEnrollment, reason := agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath, time.Now())
if needsEnrollment {
return fmt.Errorf("edge mTLS enrollment wrote unusable assets: %s", reason)
}
- if err := acfs.Write(ctx, assetsDir, "/"+generatedMTLSEnrolledName, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), acfs.WriteOptions{Mode: 0o600}); err != nil {
- return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", err)
+ if writeErr2 := acfs.Write(ctx, assetsDir, "/"+generatedMTLSEnrolledName, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), acfs.WriteOptions{Mode: 0o600}); writeErr2 != nil {
+ return fmt.Errorf("failed to write edge mTLS enrollment marker: %w", writeErr2)
}
setAgentMTLSAssetPathsInternal(cfg, assetsDir)
@@ -764,15 +764,15 @@ func ensureManagerCAInternal(ctx context.Context, assetsDir string) (string, str
return "", "", false, fmt.Errorf("failed to create CA certificate: %w", err)
}
- if err := writePEMFileInternal(caCertPath, "CERTIFICATE", certDER, utils.FilePerm); err != nil {
- return "", "", false, err
+ if writePEMFileErr := writePEMFileInternal(caCertPath, "CERTIFICATE", certDER, utils.FilePerm); writePEMFileErr != nil {
+ return "", "", false, writePEMFileErr
}
caKeyDER, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return "", "", false, fmt.Errorf("failed to marshal CA private key: %w", err)
}
- if err := writeCAKeyFileInternal(caKeyPath, caKeyDER); err != nil {
- return "", "", false, err
+ if writeCAKeyFileErr := writeCAKeyFileInternal(caKeyPath, caKeyDER); writeCAKeyFileErr != nil {
+ return "", "", false, writeCAKeyFileErr
}
slog.Info("generated edge mTLS CA", "cert_path", caCertPath)
@@ -820,8 +820,8 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envN
safeEnvID := generatedAssetNameSanitizer.ReplaceAllString(strings.TrimSpace(envID), "_")
clientDir := filepath.Join(assetsDir, generatedClientMTLSSubdir, safeEnvID)
- if err := acfs.MkdirAll(ctx, assetsDir, path.Join("/", generatedClientMTLSSubdir, safeEnvID), utils.DirPerm); err != nil {
- return "", "", false, fmt.Errorf("failed to create client cert dir: %w", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, assetsDir, path.Join("/", generatedClientMTLSSubdir, safeEnvID), utils.DirPerm); mkdirAllErr != nil {
+ return "", "", false, fmt.Errorf("failed to create client cert dir: %w", mkdirAllErr)
}
unlock, err := lockEdgeMTLSPathInternal(ctx, clientDir, ".client.lock")
if err != nil {
@@ -836,7 +836,7 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envN
if fileExistsInternal(clientCertPath) && fileExistsInternal(clientKeyPath) {
// The URI SAN is the stable edge identity. Common Name is display metadata
// for newly issued certs only, so environment renames must not rotate keys.
- if err := validateGeneratedClientCertificateInternal(clientCertPath, clientKeyPath, "", expectedURISAN); err == nil {
+ if validateGeneratedClientCertificateErr := validateGeneratedClientCertificateInternal(clientCertPath, clientKeyPath, "", expectedURISAN); validateGeneratedClientCertificateErr == nil {
return clientCertPath, clientKeyPath, false, nil
}
_ = acfs.Remove(ctx, clientDir, "/"+generatedMTLSClientCertName)
@@ -858,8 +858,8 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envN
return "", "", false, fmt.Errorf("failed to create client certificate: %w", err)
}
- if err := writePEMFileInternal(clientCertPath, "CERTIFICATE", certDER, utils.FilePerm); err != nil {
- return "", "", false, err
+ if writePEMFileErr := writePEMFileInternal(clientCertPath, "CERTIFICATE", certDER, utils.FilePerm); writePEMFileErr != nil {
+ return "", "", false, writePEMFileErr
}
// P-384 leaves keep the SEC1 framing so agents from before the ML-DSA
// migration can still parse keys issued during a rolling upgrade.
@@ -874,8 +874,8 @@ func ensureClientCertificateInternal(ctx context.Context, assetsDir, envID, envN
if err != nil {
return "", "", false, fmt.Errorf("failed to marshal client private key: %w", err)
}
- if err := writePEMFileInternal(clientKeyPath, keyPEMType, clientKeyDER, 0o600); err != nil {
- return "", "", false, err
+ if writePEMFileErr2 := writePEMFileInternal(clientKeyPath, keyPEMType, clientKeyDER, 0o600); writePEMFileErr2 != nil {
+ return "", "", false, writePEMFileErr2
}
return clientCertPath, clientKeyPath, true, nil
@@ -940,8 +940,8 @@ func validateGeneratedCAInternal(certPath, keyPath string) error {
if !cert.IsCA {
return errors.New("generated CA certificate is not a CA")
}
- if err := validateGeneratedKeyTypeInternal(cert.PublicKey, "generated CA certificate"); err != nil {
- return err
+ if validateGeneratedKeyTypeErr := validateGeneratedKeyTypeInternal(cert.PublicKey, "generated CA certificate"); validateGeneratedKeyTypeErr != nil {
+ return validateGeneratedKeyTypeErr
}
keyPEM, err := readCAKeyPEMInternal(keyPath)
if err != nil {
@@ -951,8 +951,8 @@ func validateGeneratedCAInternal(certPath, keyPath string) error {
if err != nil {
return err
}
- if err := validateCertificateKeyPairInternal(cert, privateKey, "generated CA"); err != nil {
- return err
+ if validateCertificateKeyPairErr := validateCertificateKeyPairInternal(cert, privateKey, "generated CA"); validateCertificateKeyPairErr != nil {
+ return validateCertificateKeyPairErr
}
return nil
}
@@ -972,15 +972,15 @@ func validateGeneratedClientCertificateInternal(certPath, keyPath, expectedCommo
if expectedURISAN != nil && !certificateHasURISANInternal(cert, expectedURISAN) {
return fmt.Errorf("generated client certificate URI SAN does not match expected %s", expectedURISAN.String())
}
- if err := validateGeneratedKeyTypeInternal(cert.PublicKey, "generated client certificate"); err != nil {
- return err
+ if validateGeneratedKeyTypeErr := validateGeneratedKeyTypeInternal(cert.PublicKey, "generated client certificate"); validateGeneratedKeyTypeErr != nil {
+ return validateGeneratedKeyTypeErr
}
privateKey, err := readPrivateKeyInternal(keyPath)
if err != nil {
return err
}
- if err := validateCertificateKeyPairInternal(cert, privateKey, "generated client"); err != nil {
- return err
+ if validateCertificateKeyPairErr := validateCertificateKeyPairInternal(cert, privateKey, "generated client"); validateCertificateKeyPairErr != nil {
+ return validateCertificateKeyPairErr
}
return nil
}
@@ -1014,8 +1014,8 @@ func agentMTLSAssetsNeedEnrollmentInternal(certPath, keyPath string, now time.Ti
if err != nil {
return true, err.Error()
}
- if err := validateCertificateKeyPairInternal(cert, privateKey, "edge mTLS client"); err != nil {
- return true, err.Error()
+ if validateCertificateKeyPairErr := validateCertificateKeyPairInternal(cert, privateKey, "edge mTLS client"); validateCertificateKeyPairErr != nil {
+ return true, validateCertificateKeyPairErr.Error()
}
if now.IsZero() {
now = time.Now()
@@ -1095,32 +1095,32 @@ func parsePrivateKeyPEMInternal(pemBytes []byte, label string) (crypto.Signer, e
return key, nil
}
-func readCertificateInternal(path string) (*x509.Certificate, error) {
+func readCertificateInternal(localPath string) (*x509.Certificate, error) {
// os.* rather than acfs: callers pass both generated-asset paths and
// user-configured absolute cert paths, so no single confinement root exists.
- pemBytes, err := os.ReadFile(path)
+ pemBytes, err := os.ReadFile(localPath)
if err != nil {
- return nil, fmt.Errorf("failed to read certificate %s: %w", path, err)
+ return nil, fmt.Errorf("failed to read certificate %s: %w", localPath, err)
}
block, _ := pem.Decode(pemBytes)
if block == nil {
- return nil, fmt.Errorf("failed to parse certificate PEM %s", path)
+ return nil, fmt.Errorf("failed to parse certificate PEM %s", localPath)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
- return nil, fmt.Errorf("failed to parse certificate %s: %w", path, err)
+ return nil, fmt.Errorf("failed to parse certificate %s: %w", localPath, err)
}
return cert, nil
}
-func readPrivateKeyInternal(path string) (crypto.Signer, error) {
+func readPrivateKeyInternal(localPath string) (crypto.Signer, error) {
// os.* rather than acfs: callers pass both generated-asset paths and
// user-configured absolute key paths, so no single confinement root exists.
- pemBytes, err := os.ReadFile(path)
+ pemBytes, err := os.ReadFile(localPath)
if err != nil {
- return nil, fmt.Errorf("failed to read private key %s: %w", path, err)
+ return nil, fmt.Errorf("failed to read private key %s: %w", localPath, err)
}
- return parsePrivateKeyPEMInternal(pemBytes, path)
+ return parsePrivateKeyPEMInternal(pemBytes, localPath)
}
func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func(), error) {
@@ -1136,15 +1136,15 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func()
for {
unlock, held := managerCALocks.TryLock(lockPath)
if !held {
- if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {
- return nil, err
+ if waitForEdgeMTLSLockPollErr := waitForEdgeMTLSLockPollInternal(ctx); waitForEdgeMTLSLockPollErr != nil {
+ return nil, waitForEdgeMTLSLockPollErr
}
continue
}
// os.* rather than acfs, here and in the stale-lock helpers below: acfs
// has no exclusive-create (O_EXCL) lockfile API.
- file, err := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
- if err == nil {
+ file, openFileErr := os.OpenFile(lockPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
+ if openFileErr == nil {
_, _ = fmt.Fprintf(file, "%d %s\n", os.Getpid(), time.Now().UTC().Format(time.RFC3339Nano))
_ = file.Close()
return func() {
@@ -1152,9 +1152,9 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func()
unlock()
}, nil
}
- if !os.IsExist(err) {
+ if !os.IsExist(openFileErr) {
unlock()
- return nil, fmt.Errorf("failed to acquire edge mTLS CA lock: %w", err)
+ return nil, fmt.Errorf("failed to acquire edge mTLS CA lock: %w", openFileErr)
}
if time.Now().After(deadline) {
if removeStaleEdgeMTLSLockInternal(lockPath) {
@@ -1169,8 +1169,8 @@ func lockEdgeMTLSPathInternal(ctx context.Context, dir, lockName string) (func()
return nil, fmt.Errorf("timed out waiting for edge mTLS CA lock %s", lockPath)
}
unlock()
- if err := waitForEdgeMTLSLockPollInternal(ctx); err != nil {
- return nil, err
+ if waitForEdgeMTLSLockPollErr2 := waitForEdgeMTLSLockPollInternal(ctx); waitForEdgeMTLSLockPollErr2 != nil {
+ return nil, waitForEdgeMTLSLockPollErr2
}
}
}
@@ -1243,19 +1243,19 @@ func edgeMTLSLockPIDAliveInternal(pid int) bool {
return err == nil || errors.Is(err, syscall.EPERM)
}
-func writePEMFileInternal(path, blockType string, bytes []byte, perm os.FileMode) error {
- pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: bytes})
+func writePEMFileInternal(localPath, blockType string, derBytes []byte, perm os.FileMode) error {
+ pemBytes := pem.EncodeToMemory(&pem.Block{Type: blockType, Bytes: derBytes})
if pemBytes == nil {
- return fmt.Errorf("failed to encode PEM file %s", path)
+ return fmt.Errorf("failed to encode PEM file %s", localPath)
}
- return atomic.WriteFile(path, pemBytes, perm)
+ return atomic.WriteFile(localPath, pemBytes, perm)
}
var caKeyEncryptInternal = libcrypto.Encrypt
// writeCAKeyFileInternal writes the edge CA private key to disk using envelope
// encryption via libcrypto.
-func writeCAKeyFileInternal(path string, derBytes []byte) error {
+func writeCAKeyFileInternal(localPath string, derBytes []byte) error {
pemBytes := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: derBytes})
if pemBytes == nil {
return errors.New("failed to encode CA private key to PEM")
@@ -1269,36 +1269,36 @@ func writeCAKeyFileInternal(path string, derBytes []byte) error {
return errors.New("failed to encrypt edge mTLS CA private key: encrypted payload is empty")
}
- return atomic.WriteFile(path, []byte(caKeyEncryptedPrefix+ciphertext), 0o600)
+ return atomic.WriteFile(localPath, []byte(caKeyEncryptedPrefix+ciphertext), 0o600)
}
// readCAKeyPEMInternal returns the plain PEM bytes of the edge CA private key,
// reading a libcrypto-envelope-encrypted file written by writeCAKeyFileInternal.
// os.* rather than acfs: callers pass paths derived from a possibly
// user-configured assets dir, so no confinement root handle is in scope.
-func readCAKeyPEMInternal(path string) ([]byte, error) {
- raw, err := os.ReadFile(path)
+func readCAKeyPEMInternal(localPath string) ([]byte, error) {
+ raw, err := os.ReadFile(localPath)
if err != nil {
- return nil, fmt.Errorf("failed to read CA private key %s: %w", path, err)
+ return nil, fmt.Errorf("failed to read CA private key %s: %w", localPath, err)
}
trimmed := strings.TrimSpace(string(raw))
if !strings.HasPrefix(trimmed, caKeyEncryptedPrefix) {
- return nil, fmt.Errorf("CA private key %s is not in the expected encrypted envelope format", path)
+ return nil, fmt.Errorf("CA private key %s is not in the expected encrypted envelope format", localPath)
}
ciphertext := strings.TrimPrefix(trimmed, caKeyEncryptedPrefix)
plaintext, err := libcrypto.Decrypt(ciphertext)
if err != nil {
- return nil, fmt.Errorf("failed to decrypt CA private key %s: %w", path, err)
+ return nil, fmt.Errorf("failed to decrypt CA private key %s: %w", localPath, err)
}
return []byte(plaintext), nil
}
-func fileExistsInternal(path string) bool {
- if strings.TrimSpace(path) == "" {
+func fileExistsInternal(localPath string) bool {
+ if strings.TrimSpace(localPath) == "" {
return false
}
// os.* rather than acfs: callers probe both generated-asset paths and
// user-configured absolute paths, so no single confinement root exists.
- info, err := os.Stat(path)
+ info, err := os.Stat(localPath)
return err == nil && !info.IsDir()
}
diff --git a/backend/pkg/libarcane/edge/tls_test.go b/backend/pkg/libarcane/edge/tls_test.go
index 079bbf44f..b2de181f4 100644
--- a/backend/pkg/libarcane/edge/tls_test.go
+++ b/backend/pkg/libarcane/edge/tls_test.go
@@ -21,6 +21,7 @@ import (
"time"
certgen "github.com/getarcaneapp/arcane/cli/v2/pkg/generate"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
kit "go.getarcane.app/kit/pkg"
libcrypto "go.getarcane.app/sys/crypto"
@@ -57,7 +58,7 @@ func TestPrepareManagerMTLSAssetsWithContext(t *testing.T) {
AppURL: "https://manager.example.com",
}
- require.NoError(t, PrepareManagerMTLSAssetsWithContext(context.Background(), cfg))
+ require.NoError(t, PrepareManagerMTLSAssetsWithContext(t.Context(), cfg))
require.NotEmpty(t, cfg.EdgeMTLSCAFile)
require.FileExists(t, cfg.EdgeMTLSCAFile)
}
@@ -69,7 +70,7 @@ func TestGenerateManagerClientMTLSAssetsWithContext(t *testing.T) {
AppURL: "https://manager.example.com",
}
- assets, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), cfg, "env-123", "Lab Server")
+ assets, err := GenerateManagerClientMTLSAssetsWithContext(t.Context(), cfg, "env-123", "Lab Server")
require.NoError(t, err)
require.NotNil(t, assets)
require.Empty(t, cfg.EdgeMTLSCAFile)
@@ -113,7 +114,7 @@ func TestGeneratedClientCertificate_IncludesSANs(t *testing.T) {
AppURL: "https://manager.example.com",
}
- assets, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), cfg, "env-abc", "Lab Server")
+ assets, err := GenerateManagerClientMTLSAssetsWithContext(t.Context(), cfg, "env-abc", "Lab Server")
require.NoError(t, err)
require.NotNil(t, assets)
@@ -153,7 +154,7 @@ func TestEnsureAgentMTLSAssets_RejectsPlainHTTPEnrollment(t *testing.T) {
EdgeMTLSAssetsDir: t.TempDir(),
}
- err := EnsureAgentMTLSAssets(context.Background(), cfg)
+ err := EnsureAgentMTLSAssets(t.Context(), cfg)
require.Error(t, err)
require.Contains(t, err.Error(), "MANAGER_API_URL to use https for certificate enrollment")
}
@@ -179,7 +180,7 @@ func TestEnsureAgentMTLSAssets_LimitsEnrollmentErrorBody(t *testing.T) {
EdgeMTLSAssetsDir: t.TempDir(),
}
- err := EnsureAgentMTLSAssets(context.Background(), cfg)
+ err := EnsureAgentMTLSAssets(t.Context(), cfg)
require.Error(t, err)
require.Contains(t, err.Error(), "edge mTLS enrollment failed with status 500")
require.LessOrEqual(t, len(err.Error()), maxEnrollResponseBytes+128)
@@ -189,7 +190,7 @@ func TestEnsureAgentMTLSAssets_UsesDownloadedCAPathWhenPresent(t *testing.T) {
assetsDir := t.TempDir()
caPath := filepath.Join(assetsDir, generatedMTLSCACertFileName)
- generated, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), &Config{
+ generated, err := GenerateManagerClientMTLSAssetsWithContext(t.Context(), &Config{
EdgeMTLSMode: EdgeMTLSModeRequired,
EdgeMTLSAssetsDir: t.TempDir(),
AppURL: "https://manager.example.com",
@@ -208,7 +209,7 @@ func TestEnsureAgentMTLSAssets_UsesDownloadedCAPathWhenPresent(t *testing.T) {
EdgeMTLSAssetsDir: assetsDir,
}
- require.NoError(t, EnsureAgentMTLSAssets(context.Background(), cfg))
+ require.NoError(t, EnsureAgentMTLSAssets(t.Context(), cfg))
require.NotEmpty(t, cfg.EdgeMTLSCertFile)
require.NotEmpty(t, cfg.EdgeMTLSKeyFile)
require.FileExists(t, cfg.EdgeMTLSCertFile)
@@ -289,7 +290,7 @@ func TestValidateManagerMTLSConfig_DoesNotRequireArcaneTLSTermination(t *testing
}))
assetsDir := t.TempDir()
- caPath, _, _, err := ensureManagerCAInternal(context.Background(), assetsDir)
+ caPath, _, _, err := ensureManagerCAInternal(t.Context(), assetsDir)
require.NoError(t, err)
err = ValidateManagerMTLSConfig(&Config{
@@ -329,7 +330,7 @@ func TestTunnelServerRequiredMTLS_AllowsHTTPRequestsWithoutVisibleTLSState(t *te
AppURL: "https://manager.example.com",
})
- req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", http.NoBody)
require.NoError(t, server.requireRequestCertificateIdentityInternal(req, "env-a"))
}
@@ -337,7 +338,7 @@ func TestTunnelServerRequiredMTLS_RejectsDirectTLSWithoutVerifiedClientCertifica
server := NewTunnelServerWithRegistry(GetRegistry(), nil, nil)
server.SetConfig(&Config{EdgeMTLSMode: EdgeMTLSModeRequired})
- req := httptest.NewRequest(http.MethodGet, "https://manager.example.com/api/tunnel/connect", nil)
+ req := httptest.NewRequest(http.MethodGet, "https://manager.example.com/api/tunnel/connect", http.NoBody)
req.TLS = &tls.ConnectionState{}
require.ErrorContains(t, server.requireRequestCertificateIdentityInternal(req, "env-a"), "verified edge mTLS client certificate is required")
@@ -353,14 +354,14 @@ func TestTunnelServerRequiredMTLS_DetectsOnlyDirectTLSForRequestSecurityMode(t *
})
cert := &x509.Certificate{}
- req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", http.NoBody)
req.TLS = &tls.ConnectionState{
PeerCertificates: []*x509.Certificate{cert},
VerifiedChains: [][]*x509.Certificate{{cert}},
}
require.Equal(t, "mtls", requestSecurityModeInternal(req))
- req = httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", nil)
+ req = httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", http.NoBody)
req.Header.Set("X-SSL-Client-Verify", "SUCCESS")
require.Equal(t, "token", requestSecurityModeInternal(req))
require.NoError(t, server.requireRequestCertificateIdentityInternal(req, "env-a"))
@@ -381,7 +382,7 @@ func TestTunnelServerRequiredMTLS_IgnoresProxyVerificationHeaders(t *testing.T)
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", nil)
+ req := httptest.NewRequest(http.MethodGet, "/api/tunnel/connect", http.NoBody)
req.Header.Set("X-SSL-Client-Verify", tt.value)
require.Equal(t, "token", requestSecurityModeInternal(req))
@@ -394,16 +395,16 @@ func TestTunnelServerRequiredMTLS_AllowsGRPCContextsWithoutVisibleTLSState(t *te
server.SetConfig(&Config{EdgeMTLSMode: EdgeMTLSModeRequired})
t.Run("missing peer", func(t *testing.T) {
- require.NoError(t, server.requireCertificateIdentityFromContextInternal(context.Background(), "env-a"))
+ require.NoError(t, server.requireCertificateIdentityFromContextInternal(t.Context(), "env-a"))
})
t.Run("non tls peer", func(t *testing.T) {
- ctx := peer.NewContext(context.Background(), &peer.Peer{AuthInfo: testAuthInfo{}})
+ ctx := peer.NewContext(t.Context(), &peer.Peer{AuthInfo: testAuthInfo{}})
require.NoError(t, server.requireCertificateIdentityFromContextInternal(ctx, "env-a"))
})
t.Run("direct tls without verified client certificate", func(t *testing.T) {
- ctx := peer.NewContext(context.Background(), &peer.Peer{AuthInfo: credentials.TLSInfo{}})
+ ctx := peer.NewContext(t.Context(), &peer.Peer{AuthInfo: credentials.TLSInfo{}})
require.ErrorContains(t, server.requireCertificateIdentityFromContextInternal(ctx, "env-a"), "verified edge mTLS client certificate is required")
})
@@ -411,7 +412,7 @@ func TestTunnelServerRequiredMTLS_AllowsGRPCContextsWithoutVisibleTLSState(t *te
uriSAN, err := url.Parse("spiffe://manager.example.com/edge/env-a")
require.NoError(t, err)
cert := &x509.Certificate{URIs: []*url.URL{uriSAN}}
- ctx := peer.NewContext(context.Background(), &peer.Peer{AuthInfo: credentials.TLSInfo{State: tls.ConnectionState{
+ ctx := peer.NewContext(t.Context(), &peer.Peer{AuthInfo: credentials.TLSInfo{State: tls.ConnectionState{
PeerCertificates: []*x509.Certificate{cert},
VerifiedChains: [][]*x509.Certificate{{cert}},
}}})
@@ -426,7 +427,7 @@ func TestTunnelServerRequiredMTLS_AllowsGRPCContextsWithoutVisibleTLSState(t *te
func TestAgentMTLSAssetsNeedEnrollmentInternal_RenewsExpiredCertificate(t *testing.T) {
assetsDir := t.TempDir()
- assets, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), &Config{
+ assets, err := GenerateManagerClientMTLSAssetsWithContext(t.Context(), &Config{
EdgeMTLSMode: EdgeMTLSModeRequired,
EdgeMTLSAssetsDir: t.TempDir(),
AppURL: "https://manager.example.com",
@@ -451,7 +452,7 @@ func TestAgentMTLSAssetsNeedEnrollmentInternal_RenewsExpiredCertificate(t *testi
func TestValidateGeneratedClientCertificateInternal_RejectsMismatchedKeyPair(t *testing.T) {
assetsDir := t.TempDir()
- clientCertPath, _, _, err := ensureClientCertificateInternal(context.Background(), assetsDir, "env-123", "Lab Server", "https://manager.example.com")
+ clientCertPath, _, _, err := ensureClientCertificateInternal(t.Context(), assetsDir, "env-123", "Lab Server", "https://manager.example.com")
require.NoError(t, err)
replacementKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
@@ -475,13 +476,13 @@ func TestValidateGeneratedClientCertificateInternal_RejectsMismatchedKeyPair(t *
func TestEnsureClientCertificateInternal_PreservesCertificateWhenEnvironmentNameChanges(t *testing.T) {
assetsDir := t.TempDir()
- clientCertPath, _, _, err := ensureClientCertificateInternal(context.Background(), assetsDir, "env-123", "", "https://manager.example.com")
+ clientCertPath, _, _, err := ensureClientCertificateInternal(t.Context(), assetsDir, "env-123", "", "https://manager.example.com")
require.NoError(t, err)
originalPEM, err := os.ReadFile(clientCertPath)
require.NoError(t, err)
- clientCertPath, _, _, err = ensureClientCertificateInternal(context.Background(), assetsDir, "env-123", "Lab Server", "https://manager.example.com")
+ clientCertPath, _, _, err = ensureClientCertificateInternal(t.Context(), assetsDir, "env-123", "Lab Server", "https://manager.example.com")
require.NoError(t, err)
updatedPEM, err := os.ReadFile(clientCertPath)
@@ -500,7 +501,7 @@ func TestCAKey_EncryptedOnDiskWhenCryptoInitialized(t *testing.T) {
initEdgeTestCrypto(t)
assetsDir := t.TempDir()
- caCertPath, caKeyPath, _, err := ensureManagerCAInternal(context.Background(), assetsDir)
+ caCertPath, caKeyPath, _, err := ensureManagerCAInternal(t.Context(), assetsDir)
require.NoError(t, err)
require.FileExists(t, caCertPath)
require.FileExists(t, caKeyPath)
@@ -517,7 +518,7 @@ func TestCAKey_EncryptedOnDiskWhenCryptoInitialized(t *testing.T) {
_, err = x509.ParsePKCS8PrivateKey(block.Bytes)
require.NoError(t, err)
- clientCertPath, clientKeyPath, _, err := ensureClientCertificateInternal(context.Background(), assetsDir, "env-round", "Round Trip", "https://manager.example.com")
+ clientCertPath, clientKeyPath, _, err := ensureClientCertificateInternal(t.Context(), assetsDir, "env-round", "Round Trip", "https://manager.example.com")
require.NoError(t, err)
require.FileExists(t, clientCertPath)
require.FileExists(t, clientKeyPath)
@@ -543,11 +544,11 @@ func TestCAKey_EncryptionFailureReturnsError(t *testing.T) {
func TestLockEdgeMTLSPathInternal_ReturnsOnContextCancellation(t *testing.T) {
assetsDir := t.TempDir()
- unlock, err := lockEdgeMTLSPathInternal(context.Background(), assetsDir, ".ca.lock")
+ unlock, err := lockEdgeMTLSPathInternal(t.Context(), assetsDir, ".ca.lock")
require.NoError(t, err)
defer unlock()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
cancel()
_, err = lockEdgeMTLSPathInternal(ctx, assetsDir, ".ca.lock")
@@ -617,7 +618,7 @@ func TestGeneratedMLDSAAssets_HandshakeWithVerifiedClientCertificate(t *testing.
EdgeMTLSAssetsDir: assetsDir,
AppURL: "https://manager.example.com",
}
- _, err := GenerateManagerClientMTLSAssetsWithContext(context.Background(), cfg, "env-hs", "Handshake")
+ _, err := GenerateManagerClientMTLSAssetsWithContext(t.Context(), cfg, "env-hs", "Handshake")
require.NoError(t, err)
caCertPath := filepath.Join(assetsDir, "ca.crt")
@@ -663,7 +664,7 @@ func TestGeneratedMLDSAAssets_HandshakeWithVerifiedClientCertificate(t *testing.
listener, err := tls.Listen("tcp", "127.0.0.1:0", serverTLS)
require.NoError(t, err)
- defer listener.Close()
+ defer func() { assert.NoError(t, listener.Close()) }()
type handshakeResult struct {
state tls.ConnectionState
@@ -671,15 +672,15 @@ func TestGeneratedMLDSAAssets_HandshakeWithVerifiedClientCertificate(t *testing.
}
resultCh := make(chan handshakeResult, 1)
go func() {
- conn, err := listener.Accept()
- if err != nil {
- resultCh <- handshakeResult{err: err}
+ conn, acceptErr := listener.Accept()
+ if acceptErr != nil {
+ resultCh <- handshakeResult{err: acceptErr}
return
}
- defer conn.Close()
+ defer func() { assert.NoError(t, conn.Close()) }()
tlsConn := conn.(*tls.Conn)
- if err := tlsConn.Handshake(); err != nil {
- resultCh <- handshakeResult{err: err}
+ if handshakeErr := tlsConn.Handshake(); handshakeErr != nil {
+ resultCh <- handshakeResult{err: handshakeErr}
return
}
resultCh <- handshakeResult{state: tlsConn.ConnectionState()}
@@ -687,7 +688,7 @@ func TestGeneratedMLDSAAssets_HandshakeWithVerifiedClientCertificate(t *testing.
conn, err := tls.Dial("tcp", listener.Addr().String(), clientTLS)
require.NoError(t, err)
- defer conn.Close()
+ defer func() { assert.NoError(t, conn.Close()) }()
require.Equal(t, uint16(tls.VersionTLS13), conn.ConnectionState().Version)
result := <-resultCh
diff --git a/backend/pkg/libarcane/edge/transport_test.go b/backend/pkg/libarcane/edge/transport_test.go
index f4f31032c..ad9cc221d 100644
--- a/backend/pkg/libarcane/edge/transport_test.go
+++ b/backend/pkg/libarcane/edge/transport_test.go
@@ -216,7 +216,7 @@ func BenchmarkEdgeTunnelProxyRequest(b *testing.B) {
func runProxyRequestBenchmark(b *testing.B, tunnel *AgentTunnel, payloadSize int) {
b.Helper()
- ctx := context.Background()
+ ctx := b.Context()
body := make([]byte, payloadSize)
headers := map[string]string{
"Content-Type": "application/octet-stream",
@@ -245,7 +245,7 @@ func runProxyRequestBenchmark(b *testing.B, tunnel *AgentTunnel, payloadSize int
func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func()) {
b.Helper()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(b.Context())
envID := fmt.Sprintf("bench-grpc-%d", time.Now().UnixNano())
GetRegistry().Unregister(envID)
@@ -275,22 +275,22 @@ func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func
require.FailNowf(b, "unexpected failure", "failed to open gRPC stream: %v", err)
}
- if err := stream.Send(&tunnelpb.AgentMessage{
+ if sendErr := stream.Send(&tunnelpb.AgentMessage{
Payload: &tunnelpb.AgentMessage_Register{
Register: &tunnelpb.RegisterRequest{AgentToken: "valid-token"},
},
- }); err != nil {
+ }); sendErr != nil {
_ = conn.Close()
cancel()
tunnelServer.WaitForCleanupDone()
- require.FailNowf(b, "unexpected failure", "failed to send register message: %v", err)
+ require.FailNowf(b, "unexpected failure", "failed to send register message: %v", sendErr)
}
- if _, err := stream.Recv(); err != nil {
+ if _, recvErr := stream.Recv(); recvErr != nil {
_ = conn.Close()
cancel()
tunnelServer.WaitForCleanupDone()
- require.FailNowf(b, "unexpected failure", "failed to receive register response: %v", err)
+ require.FailNowf(b, "unexpected failure", "failed to receive register response: %v", recvErr)
}
responseBody := make([]byte, payloadSize)
@@ -298,15 +298,15 @@ func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func
go func() {
defer close(agentDone)
for {
- msg, err := stream.Recv()
- if err != nil {
+ msg, recvErr := stream.Recv()
+ if recvErr != nil {
return
}
req := msg.GetCommandRequest()
if req == nil {
continue
}
- if err := stream.Send(&tunnelpb.AgentMessage{
+ if sendErr := stream.Send(&tunnelpb.AgentMessage{
Payload: &tunnelpb.AgentMessage_CommandComplete{
CommandComplete: &tunnelpb.CommandComplete{
CommandId: req.GetCommandId(),
@@ -314,7 +314,7 @@ func setupGRPCBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel, func
Body: responseBody,
},
},
- }); err != nil {
+ }); sendErr != nil {
return
}
}
@@ -346,7 +346,7 @@ func setupWebSocketBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel,
for {
var msg TunnelMessage
- if err := wsjson.Read(r.Context(), conn, &msg); err != nil {
+ if readErr := wsjson.Read(r.Context(), conn, &msg); readErr != nil {
_ = conn.CloseNow()
return
}
@@ -361,7 +361,7 @@ func setupWebSocketBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel,
Status: http.StatusOK,
Body: responseBody,
}
- if err := wsjson.Write(r.Context(), conn, resp); err != nil {
+ if writeErr := wsjson.Write(r.Context(), conn, resp); writeErr != nil {
_ = conn.CloseNow()
return
}
@@ -369,7 +369,7 @@ func setupWebSocketBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel,
}))
wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
- conn, _, err := websocket.Dial(context.Background(), wsURL, nil)
+ conn, _, err := websocket.Dial(b.Context(), wsURL, nil)
if err != nil {
server.Close()
require.FailNowf(b, "unexpected failure", "failed to dial websocket server: %v", err)
@@ -380,8 +380,8 @@ func setupWebSocketBenchmarkTunnel(b *testing.B, payloadSize int) (*AgentTunnel,
go func() {
defer close(dispatchDone)
for {
- msg, err := tunnel.Conn.Receive()
- if err != nil {
+ msg, receiveErr := tunnel.Conn.Receive()
+ if receiveErr != nil {
return
}
if req, ok := tunnel.Pending.Load(msg.ID); ok {
diff --git a/backend/pkg/libarcane/edge/tunnel.go b/backend/pkg/libarcane/edge/tunnel.go
index 9b477a9fa..bd7ba610c 100644
--- a/backend/pkg/libarcane/edge/tunnel.go
+++ b/backend/pkg/libarcane/edge/tunnel.go
@@ -108,12 +108,12 @@ func (t *TunnelConn) Send(msg *TunnelMessage) error {
if err != nil {
return err
}
- wctx, cancel := context.WithTimeout(context.Background(), DefaultWriteTimeout)
+ wctx, cancel := context.WithTimeout(context.Background(), DefaultWriteTimeout) //nolint:forbidigo // Tunnel connection owns timed I/O independent of individual HTTP requests.
defer cancel()
- if err := t.conn.Write(wctx, websocket.MessageText, data); err != nil {
+ if writeErr := t.conn.Write(wctx, websocket.MessageText, data); writeErr != nil {
// coder/websocket closes the connection after a failed or expired write.
t.closed.Store(true)
- return err
+ return writeErr
}
return nil
}
@@ -124,7 +124,7 @@ func (t *TunnelConn) Receive() (*TunnelMessage, error) {
return nil, ErrTunnelConnectionClosed
}
- rctx, cancel := context.WithTimeout(context.Background(), tunnelReadWait)
+ rctx, cancel := context.WithTimeout(context.Background(), tunnelReadWait) //nolint:forbidigo // Tunnel connection owns timed I/O independent of individual HTTP requests.
defer cancel()
_, data, err := t.conn.Read(rctx)
if err != nil {
@@ -135,8 +135,8 @@ func (t *TunnelConn) Receive() (*TunnelMessage, error) {
}
var msg TunnelMessage
- if err := json.Unmarshal(data, &msg); err != nil {
- return nil, err
+ if unmarshalErr := json.Unmarshal(data, &msg); unmarshalErr != nil {
+ return nil, unmarshalErr
}
return &msg, nil
}
@@ -227,9 +227,9 @@ func (t *GRPCManagerTunnelConn) Send(msg *TunnelMessage) error {
return err
}
- if err := t.stream.Send(protoMsg); err != nil {
+ if sendErr := t.stream.Send(protoMsg); sendErr != nil {
t.markClosed()
- return err
+ return sendErr
}
return nil
}
@@ -321,9 +321,9 @@ func (t *GRPCAgentTunnelConn) Send(msg *TunnelMessage) error {
return err
}
- if err := t.stream.Send(protoMsg); err != nil {
+ if sendErr := t.stream.Send(protoMsg); sendErr != nil {
t.markClosed()
- return err
+ return sendErr
}
return nil
}
diff --git a/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go b/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go
index 79781f19b..60d2efeca 100644
--- a/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go
+++ b/backend/pkg/libarcane/edge/tunnel_proto_adapter_test.go
@@ -231,7 +231,7 @@ func TestTunnelMessageToManagerProto_StreamEndRequiresParity(t *testing.T) {
}
func TestGRPCAgentTunnelConn_ReceiveSkipsUnknownPayload(t *testing.T) {
- stream := &scriptedAgentStream{msgs: []*tunnelpb.ManagerMessage{
+ stream := &scriptedAgentStream{ctx: t.Context(), msgs: []*tunnelpb.ManagerMessage{
{}, // nil payload, decodes as unknown
{Payload: &tunnelpb.ManagerMessage_HeartbeatPong{HeartbeatPong: &tunnelpb.HeartbeatPong{Id: "hb-2"}}},
}}
@@ -244,6 +244,7 @@ func TestGRPCAgentTunnelConn_ReceiveSkipsUnknownPayload(t *testing.T) {
}
type scriptedAgentStream struct {
+ ctx context.Context
msgs []*tunnelpb.ManagerMessage
}
@@ -258,6 +259,6 @@ func (s *scriptedAgentStream) Recv() (*tunnelpb.ManagerMessage, error) {
return msg, nil
}
-func (s *scriptedAgentStream) Context() context.Context { return context.Background() }
+func (s *scriptedAgentStream) Context() context.Context { return s.ctx }
func (s *scriptedAgentStream) CloseSend() error { return nil }
diff --git a/backend/pkg/libarcane/edge/tunnel_test.go b/backend/pkg/libarcane/edge/tunnel_test.go
index dff4bb0a8..f986d4c7e 100644
--- a/backend/pkg/libarcane/edge/tunnel_test.go
+++ b/backend/pkg/libarcane/edge/tunnel_test.go
@@ -47,13 +47,13 @@ func TestTunnelConn(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- mt, message, err := conn.Read(r.Context())
- if err != nil {
+ mt, message, readErr := conn.Read(r.Context())
+ if readErr != nil {
break
}
// Echo back
- err = conn.Write(r.Context(), mt, message)
- if err != nil {
+ readErr = conn.Write(r.Context(), mt, message)
+ if readErr != nil {
break
}
}
@@ -168,9 +168,9 @@ func TestTunnelConn_CloseSendsCloseFrame(t *testing.T) {
require.NoError(t, tunnelConn.Close())
select {
- case err := <-peerRead:
- assert.Equal(t, websocket.StatusNormalClosure, websocket.CloseStatus(err),
- "peer should observe a normal closure, got: %v", err)
+ case operationErr := <-peerRead:
+ assert.Equal(t, websocket.StatusNormalClosure, websocket.CloseStatus(operationErr),
+ "peer should observe a normal closure, got: %v", operationErr)
case <-time.After(5 * time.Second):
require.FailNow(t, "timed out waiting for peer read to return")
}
@@ -203,6 +203,7 @@ func TestTunnelConn_ReceiveDeadlineMarksClosed(t *testing.T) {
}
type closeOrderAgentStream struct {
+ ctx context.Context
events []string
}
@@ -210,7 +211,7 @@ func (s *closeOrderAgentStream) Send(*tunnelpb.AgentMessage) error { return nil
func (s *closeOrderAgentStream) Recv() (*tunnelpb.ManagerMessage, error) { return nil, io.EOF }
-func (s *closeOrderAgentStream) Context() context.Context { return context.Background() }
+func (s *closeOrderAgentStream) Context() context.Context { return s.ctx }
func (s *closeOrderAgentStream) CloseSend() error {
s.events = append(s.events, "close_send")
@@ -218,7 +219,7 @@ func (s *closeOrderAgentStream) CloseSend() error {
}
func TestGRPCAgentTunnelConn_CloseHalfClosesBeforeCancel(t *testing.T) {
- stream := &closeOrderAgentStream{}
+ stream := &closeOrderAgentStream{ctx: t.Context()}
conn := NewGRPCAgentTunnelConn(stream, func() { stream.events = append(stream.events, "cancel") })
require.NoError(t, conn.Close())
diff --git a/backend/pkg/libarcane/edge/ws_proxy.go b/backend/pkg/libarcane/edge/ws_proxy.go
index a00ab0770..a3a48f827 100644
--- a/backend/pkg/libarcane/edge/ws_proxy.go
+++ b/backend/pkg/libarcane/edge/ws_proxy.go
@@ -65,14 +65,14 @@ func ProxyWebSocketRequest(c *echo.Context, tunnel *AgentTunnel, targetPath stri
defer tunnel.Pending.Delete(streamID)
headers := buildWebSocketHeaders(req)
- if err := DefaultCommandClient.OpenStream(streamCtx, tunnel, &CommandRequest{
+ if openStreamErr := DefaultCommandClient.OpenStream(streamCtx, tunnel, &CommandRequest{
ID: streamID,
Method: http.MethodGet,
Path: targetPath,
Query: req.URL.RawQuery,
Headers: headers,
- }); err != nil {
- slog.ErrorContext(ctx, "Failed to send WebSocket start to agent", "error", err)
+ }); openStreamErr != nil {
+ slog.ErrorContext(ctx, "Failed to send WebSocket start to agent", "error", openStreamErr)
return nil
}
@@ -115,8 +115,8 @@ func forwardClientToAgent(ctx, streamCtx context.Context, clientWS *websocket.Co
continue
}
- if err := sendStreamDataInternal(tunnel, streamID, int(msgType), data); err != nil {
- slog.DebugContext(ctx, "Failed to send WebSocket data to agent", "error", err)
+ if sendStreamDataErr := sendStreamDataInternal(tunnel, streamID, int(msgType), data); sendStreamDataErr != nil {
+ slog.DebugContext(ctx, "Failed to send WebSocket data to agent", "error", sendStreamDataErr)
return
}
}
diff --git a/backend/pkg/libarcane/edge/ws_proxy_test.go b/backend/pkg/libarcane/edge/ws_proxy_test.go
index c8a90c899..4b5e48a1a 100644
--- a/backend/pkg/libarcane/edge/ws_proxy_test.go
+++ b/backend/pkg/libarcane/edge/ws_proxy_test.go
@@ -24,8 +24,8 @@ func TestProxyWebSocketRequest(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- _, data, err := conn.Read(r.Context())
- if err != nil {
+ _, data, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
@@ -74,8 +74,8 @@ func TestProxyWebSocketRequest(t *testing.T) {
// Start receiving on tunnel
go func() {
for {
- msg, err := tunnel.Conn.Receive()
- if err != nil {
+ msg, receiveErr := tunnel.Conn.Receive()
+ if receiveErr != nil {
return
}
if req, ok := tunnel.Pending.Load(msg.ID); ok {
@@ -131,7 +131,7 @@ func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
}
defer func() { _ = conn.CloseNow() }()
for {
- if _, _, err := conn.Read(r.Context()); err != nil {
+ if _, _, readErr := conn.Read(r.Context()); readErr != nil {
return
}
}
@@ -147,7 +147,7 @@ func TestProxyWebSocketRequest_ClientClose(t *testing.T) {
go func() {
for {
- if _, err := tunnel.Conn.Receive(); err != nil {
+ if _, receiveErr := tunnel.Conn.Receive(); receiveErr != nil {
return
}
}
diff --git a/backend/pkg/libarcane/internal_resource_test.go b/backend/pkg/libarcane/internal_resource_test.go
index bd468e1bc..71dadb145 100644
--- a/backend/pkg/libarcane/internal_resource_test.go
+++ b/backend/pkg/libarcane/internal_resource_test.go
@@ -1,7 +1,6 @@
package libarcane
import (
- "context"
"errors"
"net/http"
"net/http/httptest"
@@ -67,7 +66,8 @@ func TestInspectCurrentArcaneContainer_FallsBackToLabelWhenHostnameIsSidecar(t *
case strings.HasSuffix(r.URL.Path, "/containers/json"):
_, _ = w.Write([]byte(`[{"Id":"arcane123","Names":["/arcane"],"State":"running","Labels":{"com.getarcaneapp.arcane":"true"}}]`))
case strings.HasSuffix(r.URL.Path, "/containers/arcane123/json"):
- _, _ = w.Write([]byte(`{"Id":"arcane123","Name":"/arcane","State":{"Running":true},"HostConfig":{"NetworkMode":"container:sidecar456"},"Config":{"Labels":{"com.getarcaneapp.arcane":"true"}}}`))
+ _, _ = w.Write([]byte("{\"Id\":\"arcane123\",\"Name\":\"/arcane\",\"State\":{\"Running\":true},\"HostConfig\":{\"NetworkMode\":\"container:s" +
+ "idecar456\"},\"Config\":{\"Labels\":{\"com.getarcaneapp.arcane\":\"true\"}}}"))
case strings.HasSuffix(r.URL.Path, "/json"):
_, _ = w.Write([]byte(`{"Id":"sidecar456","Name":"/ts-arcane","State":{"Running":true},"Config":{"Labels":{}}}`))
default:
@@ -75,7 +75,7 @@ func TestInspectCurrentArcaneContainer_FallsBackToLabelWhenHostnameIsSidecar(t *
}
})
- got, err := InspectCurrentArcaneContainer(context.Background(), dockerClient)
+ got, err := InspectCurrentArcaneContainer(t.Context(), dockerClient)
require.NoError(t, err)
assert.Equal(t, "arcane123", got.ID)
}
@@ -91,7 +91,8 @@ func TestInspectCurrentArcaneContainer_KeepsUnlabeledHitOverUnrelatedLabeledInst
case strings.HasSuffix(r.URL.Path, "/containers/json"):
_, _ = w.Write([]byte(`[{"Id":"other789","Names":["/arcane-other"],"State":"running","Labels":{"com.getarcaneapp.arcane":"true"}}]`))
case strings.HasSuffix(r.URL.Path, "/containers/other789/json"):
- _, _ = w.Write([]byte(`{"Id":"other789","Name":"/arcane-other","State":{"Running":true},"HostConfig":{"NetworkMode":"bridge"},"Config":{"Labels":{"com.getarcaneapp.arcane":"true"}}}`))
+ _, _ = w.Write([]byte("{\"Id\":\"other789\",\"Name\":\"/arcane-other\",\"State\":{\"Running\":true},\"HostConfig\":{\"NetworkMode\":\"bridge" +
+ "\"},\"Config\":{\"Labels\":{\"com.getarcaneapp.arcane\":\"true\"}}}"))
case strings.HasSuffix(r.URL.Path, "/json"):
_, _ = w.Write([]byte(`{"Id":"custom123","Name":"/arcane-custom","State":{"Running":true},"Config":{"Labels":{}}}`))
default:
@@ -99,7 +100,7 @@ func TestInspectCurrentArcaneContainer_KeepsUnlabeledHitOverUnrelatedLabeledInst
}
})
- got, err := InspectCurrentArcaneContainer(context.Background(), dockerClient)
+ got, err := InspectCurrentArcaneContainer(t.Context(), dockerClient)
require.NoError(t, err)
assert.Equal(t, "custom123", got.ID)
}
diff --git a/backend/pkg/libarcane/rustic/run.go b/backend/pkg/libarcane/rustic/run.go
index 353b4961d..5cce5b764 100644
--- a/backend/pkg/libarcane/rustic/run.go
+++ b/backend/pkg/libarcane/rustic/run.go
@@ -59,24 +59,24 @@ func Run(ctx context.Context, dockerClient *client.Client, password string, comm
cleanupCtx := context.WithoutCancel(ctx)
for {
attemptCtx, cancel := context.WithTimeout(cleanupCtx, timeouts.DefaultDockerAPI)
- _, err := dockerClient.ContainerRemove(attemptCtx, created.ID, volumehelper.RemoveOptions())
+ _, containerRemoveErr := dockerClient.ContainerRemove(attemptCtx, created.ID, volumehelper.RemoveOptions())
cancel()
- if err == nil || cerrdefs.IsNotFound(err) {
+ if containerRemoveErr == nil || cerrdefs.IsNotFound(containerRemoveErr) {
return
}
- slog.WarnContext(cleanupCtx, "failed to remove Rustic container, retrying", "container_id", created.ID, "error", err)
+ slog.WarnContext(cleanupCtx, "failed to remove Rustic container, retrying", "container_id", created.ID, "error", containerRemoveErr)
time.Sleep(5 * time.Second)
}
}()
- if _, err := dockerClient.ContainerStart(ctx, created.ID, client.ContainerStartOptions{}); err != nil {
- return "", fmt.Errorf("failed to start Rustic container: %w", err)
+ if _, containerStartErr := dockerClient.ContainerStart(ctx, created.ID, client.ContainerStartOptions{}); containerStartErr != nil {
+ return "", fmt.Errorf("failed to start Rustic container: %w", containerStartErr)
}
wait := dockerClient.ContainerWait(ctx, created.ID, client.ContainerWaitOptions{Condition: container.WaitConditionNotRunning})
var status container.WaitResponse
select {
- case err := <-wait.Error:
- if err != nil {
- return "", fmt.Errorf("failed to wait for Rustic container: %w", err)
+ case operationErr := <-wait.Error:
+ if operationErr != nil {
+ return "", fmt.Errorf("failed to wait for Rustic container: %w", operationErr)
}
case status = <-wait.Result:
}
@@ -87,8 +87,8 @@ func Run(ctx context.Context, dockerClient *client.Client, password string, comm
defer func() { _ = logs.Close() }()
var stdout bytes.Buffer
var stderr bytes.Buffer
- if _, err := stdcopy.StdCopy(&stdout, &stderr, logs); err != nil {
- return "", fmt.Errorf("failed to decode Rustic output: %w", err)
+ if _, stdCopyErr := stdcopy.StdCopy(&stdout, &stderr, logs); stdCopyErr != nil {
+ return "", fmt.Errorf("failed to decode Rustic output: %w", stdCopyErr)
}
if status.StatusCode != 0 {
message := cmp.Or(strings.TrimSpace(stderr.String()), strings.TrimSpace(stdout.String()))
diff --git a/backend/pkg/libarcane/startup/runtime_identity.go b/backend/pkg/libarcane/startup/runtime_identity.go
index 6e2a2ed73..8fd607e2d 100644
--- a/backend/pkg/libarcane/startup/runtime_identity.go
+++ b/backend/pkg/libarcane/startup/runtime_identity.go
@@ -83,8 +83,8 @@ func ApplyRequestedRuntimeIdentity(ctx context.Context, cfg *RuntimeIdentityConf
// Avoid re-execing forever when the requested runtime identity is already active.
if os.Geteuid() == runtimeUID && os.Getegid() == runtimeGID {
- if err := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID, inContainer); err != nil {
- return err
+ if ensureRuntimeDockerConfigErr := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID, inContainer); ensureRuntimeDockerConfigErr != nil {
+ return ensureRuntimeDockerConfigErr
}
return ensureSQLiteFilesExistInternal(cfg.DatabaseURL)
}
@@ -92,24 +92,26 @@ func ApplyRequestedRuntimeIdentity(ctx context.Context, cfg *RuntimeIdentityConf
if os.Geteuid() != 0 {
slog.WarnContext(ctx, "Runtime identity warning: process is not root, continuing as current user",
"euid", os.Geteuid(), "puid", runtimeUID, "pgid", runtimeGID)
- if err := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID, inContainer); err != nil {
- return err
+ if ensureRuntimeDockerConfigErr2 := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID, inContainer); ensureRuntimeDockerConfigErr2 != nil {
+ return ensureRuntimeDockerConfigErr2
}
return ensureSQLiteFilesExistInternal(cfg.DatabaseURL)
}
- if err := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID, inContainer); err != nil {
- return err
+ if ensureRuntimeDockerConfigErr3 := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID, inContainer); ensureRuntimeDockerConfigErr3 != nil {
+ return ensureRuntimeDockerConfigErr3
}
if inContainer {
- mountpoints, err := loadMountpointsInternal(mountInfoPath)
- if err != nil {
- return fmt.Errorf("load mountpoints: %w", err)
+ mountpoints, loadMountpointsErr := loadMountpointsInternal(mountInfoPath)
+ if loadMountpointsErr != nil {
+ return fmt.Errorf("load mountpoints: %w", loadMountpointsErr)
}
- if err := prepareWritablePathsWithRootsInternal(runtimeUID, runtimeGID, mountpoints, projectsDir, defaultDataDirectory, defaultBuildsDirectory); err != nil {
- return err
+ if prepareWritablePathsWithRootsErr := prepareWritablePathsWithRootsInternal(
+ runtimeUID, runtimeGID, mountpoints, projectsDir, defaultDataDirectory, defaultBuildsDirectory,
+ ); prepareWritablePathsWithRootsErr != nil {
+ return prepareWritablePathsWithRootsErr
}
}
@@ -203,13 +205,13 @@ func ensureRuntimeDockerConfigInternal(cfg *RuntimeIdentityConfig, setenv func(s
return nil
}
- if err := os.MkdirAll(configDir, utils.DirPerm); err != nil {
- return fmt.Errorf("create docker config directory: %w", err)
+ if mkdirAllErr := os.MkdirAll(configDir, utils.DirPerm); mkdirAllErr != nil {
+ return fmt.Errorf("create docker config directory: %w", mkdirAllErr)
}
if configDir == defaultDockerConfigDir && os.Geteuid() == 0 {
- if err := os.Chown(configDir, uid, gid); err != nil {
- return fmt.Errorf("chown docker config directory: %w", err)
+ if chownErr := os.Chown(configDir, uid, gid); chownErr != nil {
+ return fmt.Errorf("chown docker config directory: %w", chownErr)
}
}
@@ -305,38 +307,38 @@ func prepareWritablePathsWithRootsInternal(uid, gid int, mountpoints map[string]
for _, entry := range entries {
entryPath := filepath.Join(dataDirectory, entry.Name())
if _, mounted := mountpoints[entryPath]; mounted {
- if err := os.Lchown(entryPath, uid, gid); err != nil {
- return fmt.Errorf("chown mounted %s: %w", entryPath, err)
+ if lchownErr := os.Lchown(entryPath, uid, gid); lchownErr != nil {
+ return fmt.Errorf("chown mounted %s: %w", entryPath, lchownErr)
}
continue
}
if projectsDir != "" && filepath.Clean(entryPath) == projectsDir {
- if err := lchownFn(entryPath, uid, gid); err != nil {
- return fmt.Errorf("chown %s: %w", entryPath, err)
+ if lchownFnErr := lchownFn(entryPath, uid, gid); lchownFnErr != nil {
+ return fmt.Errorf("chown %s: %w", entryPath, lchownFnErr)
}
continue
}
- if err := chownRecursiveInternal(entryPath, uid, gid, mountpoints, projectsDir); err != nil {
- return fmt.Errorf("chown %s: %w", entryPath, err)
+ if chownRecursiveErr := chownRecursiveInternal(entryPath, uid, gid, mountpoints, projectsDir); chownRecursiveErr != nil {
+ return fmt.Errorf("chown %s: %w", entryPath, chownRecursiveErr)
}
}
if _, mounted := mountpoints[buildsDirectory]; mounted {
- if err := os.Lchown(buildsDirectory, uid, gid); err != nil {
- return fmt.Errorf("chown mounted builds directory: %w", err)
+ if lchownErr2 := os.Lchown(buildsDirectory, uid, gid); lchownErr2 != nil {
+ return fmt.Errorf("chown mounted builds directory: %w", lchownErr2)
}
return nil
}
- if _, err := os.Stat(buildsDirectory); err != nil {
- if os.IsNotExist(err) {
+ if _, statErr := os.Stat(buildsDirectory); statErr != nil {
+ if os.IsNotExist(statErr) {
return nil
}
- return fmt.Errorf("stat builds directory: %w", err)
+ return fmt.Errorf("stat builds directory: %w", statErr)
}
- if err := chownRecursiveInternal(buildsDirectory, uid, gid, mountpoints, projectsDir); err != nil {
- return fmt.Errorf("chown builds directory: %w", err)
+ if chownRecursiveErr2 := chownRecursiveInternal(buildsDirectory, uid, gid, mountpoints, projectsDir); chownRecursiveErr2 != nil {
+ return fmt.Errorf("chown builds directory: %w", chownRecursiveErr2)
}
return nil
@@ -356,8 +358,8 @@ func ensureSQLiteFilesExistInternal(databaseURL string) error {
// prepareWritablePathsWithRootsInternal is not called.
dir := filepath.Dir(sqlitePath)
if dir != "" && dir != "." {
- if err := os.MkdirAll(dir, utils.DirPerm); err != nil {
- return fmt.Errorf("create sqlite directory %s: %w", dir, err)
+ if mkdirAllErr := os.MkdirAll(dir, utils.DirPerm); mkdirAllErr != nil {
+ return fmt.Errorf("create sqlite directory %s: %w", dir, mkdirAllErr)
}
}
@@ -365,8 +367,8 @@ func ensureSQLiteFilesExistInternal(databaseURL string) error {
if err != nil {
return fmt.Errorf("create sqlite file %s: %w", sqlitePath, err)
}
- if err := file.Close(); err != nil {
- return fmt.Errorf("close sqlite file %s: %w", sqlitePath, err)
+ if closeErr := file.Close(); closeErr != nil {
+ return fmt.Errorf("close sqlite file %s: %w", sqlitePath, closeErr)
}
return nil
@@ -413,8 +415,8 @@ func chownRecursiveInternal(path string, uid, gid int, mountpoints map[string]st
}
}
if projectsDir != "" && filepath.Clean(currentPath) == projectsDir {
- if err := lchownFn(currentPath, uid, gid); err != nil {
- return err
+ if lchownFnErr := lchownFn(currentPath, uid, gid); lchownFnErr != nil {
+ return lchownFnErr
}
return filepath.SkipDir
}
diff --git a/backend/pkg/libarcane/startup/startup_test.go b/backend/pkg/libarcane/startup/startup_test.go
index c876d47c1..68434c1fd 100644
--- a/backend/pkg/libarcane/startup/startup_test.go
+++ b/backend/pkg/libarcane/startup/startup_test.go
@@ -44,7 +44,7 @@ func (m *mockSettingsPruner) PruneUnknownSettings(ctx context.Context) error {
}
func TestLoadAgentToken(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("loads token when agent mode and token empty", func(t *testing.T) {
cfg := &RuntimeConfig{
@@ -96,7 +96,7 @@ func TestLoadAgentToken(t *testing.T) {
}
func TestEnsureEncryptionKey(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("sets key when in agent mode", func(t *testing.T) {
cfg := &RuntimeConfig{
@@ -160,7 +160,7 @@ func TestEnsureEncryptionKey(t *testing.T) {
}
func TestInitializeDefaultSettings(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
cfg := &RuntimeConfig{}
t.Run("calls all initialization methods", func(t *testing.T) {
@@ -196,7 +196,7 @@ func TestInitializeDefaultSettings(t *testing.T) {
}
func TestCleanupUnknownSettings(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("calls prune method", func(t *testing.T) {
pruner := &mockSettingsPruner{}
@@ -218,7 +218,7 @@ func TestCleanupUnknownSettings(t *testing.T) {
}
func TestTestDockerConnection(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("executes test function", func(t *testing.T) {
called := false
@@ -242,7 +242,7 @@ func TestTestDockerConnection(t *testing.T) {
}
func TestInitializeNonAgentFeatures(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("skips in agent mode", func(t *testing.T) {
cfg := &RuntimeConfig{AgentMode: true}
diff --git a/backend/pkg/libarcane/swarm/cleanup.go b/backend/pkg/libarcane/swarm/cleanup.go
index 153023c9a..2c14da564 100644
--- a/backend/pkg/libarcane/swarm/cleanup.go
+++ b/backend/pkg/libarcane/swarm/cleanup.go
@@ -180,11 +180,11 @@ func RemoveStackResources(ctx context.Context, dockerClient *dockerclient.Client
if stackNetwork.Ingress {
continue
}
- if err := removeStaleSwarmResourceInternal(ctx, false, func(ctx context.Context) error {
- _, err := dockerClient.NetworkRemove(ctx, stackNetwork.ID, dockerclient.NetworkRemoveOptions{})
- return err
- }); err != nil {
- return fmt.Errorf("failed to remove stack network %s: %w", stackNetwork.Name, err)
+ if removeStaleSwarmResourceErr := removeStaleSwarmResourceInternal(ctx, false, func(ctx context.Context) error {
+ _, networkRemoveErr := dockerClient.NetworkRemove(ctx, stackNetwork.ID, dockerclient.NetworkRemoveOptions{})
+ return networkRemoveErr
+ }); removeStaleSwarmResourceErr != nil {
+ return fmt.Errorf("failed to remove stack network %s: %w", stackNetwork.Name, removeStaleSwarmResourceErr)
}
}
diff --git a/backend/pkg/libarcane/swarm/cleanup_test.go b/backend/pkg/libarcane/swarm/cleanup_test.go
index a1b98dc48..6dc5e0360 100644
--- a/backend/pkg/libarcane/swarm/cleanup_test.go
+++ b/backend/pkg/libarcane/swarm/cleanup_test.go
@@ -46,7 +46,7 @@ func TestCleanupStaleManagedResourcesMatchesCurrentAndLegacyLabels(t *testing.T)
}
err := cleanupStaleManagedResourcesInternal(
- context.Background(),
+ t.Context(),
"stack",
map[string]struct{}{"desired": {}},
adapter,
@@ -75,12 +75,12 @@ func TestCleanupStaleManagedResourcesFailsWhenResourceStaysInUse(t *testing.T) {
},
}
- err := cleanupStaleManagedResourcesInternal(context.Background(), "stack", map[string]struct{}{}, adapter, false, false)
+ err := cleanupStaleManagedResourcesInternal(t.Context(), "stack", map[string]struct{}{}, adapter, false, false)
require.Error(t, err)
require.Equal(t, staleSwarmResourceRemoveAttemptsInternal, removeCalls)
removeCalls = 0
- err = cleanupStaleManagedResourcesInternal(context.Background(), "stack", map[string]struct{}{}, adapter, false, true)
+ err = cleanupStaleManagedResourcesInternal(t.Context(), "stack", map[string]struct{}{}, adapter, false, true)
require.NoError(t, err)
require.Equal(t, 1, removeCalls)
}
diff --git a/backend/pkg/libarcane/swarm/convert_service.go b/backend/pkg/libarcane/swarm/convert_service.go
index 192221b19..24e9d88e4 100644
--- a/backend/pkg/libarcane/swarm/convert_service.go
+++ b/backend/pkg/libarcane/swarm/convert_service.go
@@ -123,11 +123,11 @@ func buildServiceSpecInternal(
}
}
- if err := applyDeployConfigInternal(&spec, service.Deploy, service.Scale, service.Restart); err != nil {
- return swarm.ServiceSpec{}, err
+ if applyDeployConfigErr := applyDeployConfigInternal(&spec, service.Deploy, service.Scale, service.Restart); applyDeployConfigErr != nil {
+ return swarm.ServiceSpec{}, applyDeployConfigErr
}
- if err := applyServicePortsInternal(&spec, service.Ports); err != nil {
- return swarm.ServiceSpec{}, err
+ if applyServicePortsErr := applyServicePortsInternal(&spec, service.Ports); applyServicePortsErr != nil {
+ return swarm.ServiceSpec{}, applyServicePortsErr
}
return spec, nil
@@ -195,9 +195,9 @@ func convertPrivilegesInternal(
privileges := &swarm.Privileges{CredentialSpec: convertedCredentialSpec}
hasPrivileges := convertedCredentialSpec != nil
for _, securityOption := range securityOptions {
- applied, err := applySecurityOptionInternal(privileges, securityOption)
- if err != nil {
- return nil, nil, err
+ applied, applySecurityOptionErr := applySecurityOptionInternal(privileges, securityOption)
+ if applySecurityOptionErr != nil {
+ return nil, nil, applySecurityOptionErr
}
if applied {
hasPrivileges = true
diff --git a/backend/pkg/libarcane/swarm/convert_test.go b/backend/pkg/libarcane/swarm/convert_test.go
index 226bbd695..0c7a89a76 100644
--- a/backend/pkg/libarcane/swarm/convert_test.go
+++ b/backend/pkg/libarcane/swarm/convert_test.go
@@ -1,7 +1,6 @@
package swarm
import (
- "context"
"os"
"path/filepath"
"testing"
@@ -73,7 +72,7 @@ func TestApplyDeployConfigConvertsCPUFractionToNanoCPUs(t *testing.T) {
func TestPlanConfigsUsesComposeProjectEnvironment(t *testing.T) {
t.Setenv("ARCANE_SWARM_CONFIG_SOURCE", "process-value")
- project, err := projects.LoadComposeProjectFromContent(context.Background(), projecttypes.ComposeContentOptions{
+ project, err := projects.LoadComposeProjectFromContent(t.Context(), projecttypes.ComposeContentOptions{
ProjectName: "stack",
ComposeContent: `
services:
@@ -207,7 +206,7 @@ func TestStackConversionEndToEnd(t *testing.T) {
workingDir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(workingDir, "db_pw.txt"), []byte("secret"), 0o600))
- project, err := projects.LoadComposeProjectFromContent(context.Background(), projecttypes.ComposeContentOptions{
+ project, err := projects.LoadComposeProjectFromContent(t.Context(), projecttypes.ComposeContentOptions{
ProjectName: "stack",
ComposeContent: `
services:
diff --git a/backend/pkg/libarcane/swarm/deploy.go b/backend/pkg/libarcane/swarm/deploy.go
index 2cb27a274..b9d6d32c0 100644
--- a/backend/pkg/libarcane/swarm/deploy.go
+++ b/backend/pkg/libarcane/swarm/deploy.go
@@ -80,8 +80,8 @@ func DeployStack(ctx context.Context, dockerClient *dockerclient.Client, opts St
return err
}
- if err := ensureSwarmVolumesInternal(ctx, dockerClient, project, ns, stackLabels); err != nil {
- return err
+ if ensureSwarmVolumesErr := ensureSwarmVolumesInternal(ctx, dockerClient, project, ns, stackLabels); ensureSwarmVolumesErr != nil {
+ return ensureSwarmVolumesErr
}
configPlans, err := planConfigsInternal(project, ns)
@@ -140,14 +140,14 @@ func DeployStack(ctx context.Context, dockerClient *dockerclient.Client, opts St
if _, ok := desiredServices[name]; ok {
continue
}
- if _, err := dockerClient.ServiceRemove(ctx, svc.ID, dockerclient.ServiceRemoveOptions{}); err != nil {
- return fmt.Errorf("failed to remove swarm service %s: %w", name, err)
+ if _, serviceRemoveErr := dockerClient.ServiceRemove(ctx, svc.ID, dockerclient.ServiceRemoveOptions{}); serviceRemoveErr != nil {
+ return fmt.Errorf("failed to remove swarm service %s: %w", name, serviceRemoveErr)
}
}
}
- if err := cleanupStackResourcesInternal(ctx, dockerClient, stackName, configMetaByKey, secretMetaByKey); err != nil {
- return err
+ if cleanupStackResourcesErr := cleanupStackResourcesInternal(ctx, dockerClient, stackName, configMetaByKey, secretMetaByKey); cleanupStackResourcesErr != nil {
+ return cleanupStackResourcesErr
}
return nil
@@ -178,14 +178,14 @@ func reconcileStackServicesInternal(
desiredServices[spec.Name] = struct{}{}
if existing, ok := existingServices[spec.Name]; ok {
- if err := updateSwarmServiceInternal(ctx, dockerClient, existing, spec, opts.WithRegistryAuth, opts.RegistryAuthForImage, resolveMode); err != nil {
- return nil, err
+ if updateSwarmServiceErr := updateSwarmServiceInternal(ctx, dockerClient, existing, spec, opts.WithRegistryAuth, opts.RegistryAuthForImage, resolveMode); updateSwarmServiceErr != nil {
+ return nil, updateSwarmServiceErr
}
continue
}
- if err := createSwarmServiceInternal(ctx, dockerClient, spec, opts.WithRegistryAuth, opts.RegistryAuthForImage, resolveMode); err != nil {
- return nil, err
+ if createSwarmServiceErr := createSwarmServiceInternal(ctx, dockerClient, spec, opts.WithRegistryAuth, opts.RegistryAuthForImage, resolveMode); createSwarmServiceErr != nil {
+ return nil, createSwarmServiceErr
}
}
@@ -225,8 +225,8 @@ func createSwarmServiceInternal(
QueryRegistry: queryRegistry,
}
opts.EncodedRegistryAuth = cmp.Or(encodedRegistryAuth, opts.EncodedRegistryAuth)
- if _, err := dockerClient.ServiceCreate(ctx, opts); err != nil {
- return fmt.Errorf("failed to create swarm service %s: %w", spec.Name, err)
+ if _, serviceCreateErr := dockerClient.ServiceCreate(ctx, opts); serviceCreateErr != nil {
+ return fmt.Errorf("failed to create swarm service %s: %w", spec.Name, serviceCreateErr)
}
return nil
}
@@ -263,15 +263,15 @@ func updateSwarmServiceInternal(
opts.RegistryAuthFrom = swarm.RegistryAuthFromPreviousSpec
}
- if _, err := dockerClient.ServiceUpdate(ctx, existing.ID, opts); err != nil {
- if strings.Contains(err.Error(), "service does not have a previous spec") {
+ if _, serviceUpdateErr := dockerClient.ServiceUpdate(ctx, existing.ID, opts); serviceUpdateErr != nil {
+ if strings.Contains(serviceUpdateErr.Error(), "service does not have a previous spec") {
opts.RegistryAuthFrom = ""
if _, retryErr := dockerClient.ServiceUpdate(ctx, existing.ID, opts); retryErr != nil {
return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, retryErr)
}
return nil
}
- return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, err)
+ return fmt.Errorf("failed to update swarm service %s: %w", spec.Name, serviceUpdateErr)
}
return nil
}
diff --git a/backend/pkg/libarcane/swarm/load_test.go b/backend/pkg/libarcane/swarm/load_test.go
index 965b5a008..6ef784371 100644
--- a/backend/pkg/libarcane/swarm/load_test.go
+++ b/backend/pkg/libarcane/swarm/load_test.go
@@ -1,7 +1,6 @@
package swarm
import (
- "context"
"testing"
projecttypes "github.com/getarcaneapp/arcane/types/v2/project"
@@ -14,7 +13,7 @@ func TestLoadComposeProjectMergesOverrideContent(t *testing.T) {
base := "services:\n app:\n image: nginx:alpine\n environment:\n FROM_BASE: \"1\"\n"
override := "services:\n app:\n image: busybox:latest\n environment:\n FROM_OVERRIDE: \"1\"\n"
- project, err := projects.LoadComposeProjectFromContent(context.Background(), projecttypes.ComposeContentOptions{
+ project, err := projects.LoadComposeProjectFromContent(t.Context(), projecttypes.ComposeContentOptions{
ProjectName: "stack",
ComposeContent: base,
OverrideContent: override,
@@ -28,7 +27,7 @@ func TestLoadComposeProjectMergesOverrideContent(t *testing.T) {
}
func TestLoadComposeProjectWithoutOverrideContent(t *testing.T) {
- project, err := projects.LoadComposeProjectFromContent(context.Background(), projecttypes.ComposeContentOptions{
+ project, err := projects.LoadComposeProjectFromContent(t.Context(), projecttypes.ComposeContentOptions{
ProjectName: "stack",
ComposeContent: "services:\n app:\n image: nginx:alpine\n",
})
@@ -65,7 +64,7 @@ networks:
external: true
`
- project, err := projects.LoadComposeProjectFromContent(context.Background(), projecttypes.ComposeContentOptions{
+ project, err := projects.LoadComposeProjectFromContent(t.Context(), projecttypes.ComposeContentOptions{
ProjectName: "stack",
ComposeContent: composeContent,
})
diff --git a/backend/pkg/libarcane/swarm/resources.go b/backend/pkg/libarcane/swarm/resources.go
index 288126879..1945106ab 100644
--- a/backend/pkg/libarcane/swarm/resources.go
+++ b/backend/pkg/libarcane/swarm/resources.go
@@ -163,8 +163,8 @@ func ensureSwarmNetworksInternal(ctx context.Context, dockerClient *dockerclient
IPAM: convertIPAMInternal(cfg.Ipam),
}
- if _, err := dockerClient.NetworkCreate(ctx, networkName, createOpts); err != nil {
- return nil, fmt.Errorf("failed to create network %s: %w", networkName, err)
+ if _, networkCreateErr := dockerClient.NetworkCreate(ctx, networkName, createOpts); networkCreateErr != nil {
+ return nil, fmt.Errorf("failed to create network %s: %w", networkName, networkCreateErr)
}
}
diff --git a/backend/pkg/libarcane/system/gpu.go b/backend/pkg/libarcane/system/gpu.go
index b53d497be..52593a97e 100644
--- a/backend/pkg/libarcane/system/gpu.go
+++ b/backend/pkg/libarcane/system/gpu.go
@@ -206,7 +206,7 @@ func HasAMDGPU() bool {
if !strings.HasPrefix(name, "card") || strings.Contains(name, "-") {
continue
}
- if _, err := os.Stat(fmt.Sprintf("%s/%s/device/mem_info_vram_total", AMDGPUSysfsPath, name)); err == nil {
+ if _, statErr := os.Stat(fmt.Sprintf("%s/%s/device/mem_info_vram_total", AMDGPUSysfsPath, name)); statErr == nil {
return true
}
}
@@ -250,18 +250,18 @@ func getNvidiaStatsInternal(ctx context.Context) ([]systemtypes.GPUStats, error)
if len(record) < 4 {
continue
}
- index, err := strconv.Atoi(strings.TrimSpace(record[0]))
- if err != nil {
+ index, atoiErr := strconv.Atoi(strings.TrimSpace(record[0]))
+ if atoiErr != nil {
slog.WarnContext(ctx, "Failed to parse GPU index", "value", record[0])
continue
}
- memUsed, err := strconv.ParseFloat(strings.TrimSpace(record[2]), 64)
- if err != nil {
+ memUsed, atoiErr := strconv.ParseFloat(strings.TrimSpace(record[2]), 64)
+ if atoiErr != nil {
slog.WarnContext(ctx, "Failed to parse memory used", "value", record[2])
continue
}
- memTotal, err := strconv.ParseFloat(strings.TrimSpace(record[3]), 64)
- if err != nil {
+ memTotal, atoiErr := strconv.ParseFloat(strings.TrimSpace(record[3]), 64)
+ if atoiErr != nil {
slog.WarnContext(ctx, "Failed to parse memory total", "value", record[3])
continue
}
@@ -298,13 +298,13 @@ func getAMDStatsInternal(ctx context.Context) ([]systemtypes.GPUStats, error) {
}
devicePath := fmt.Sprintf("%s/%s/device", AMDGPUSysfsPath, name)
- memTotalBytes, err := readSysfsValueInternal(devicePath + "/mem_info_vram_total")
- if err != nil {
+ memTotalBytes, readSysfsValueErr := readSysfsValueInternal(devicePath + "/mem_info_vram_total")
+ if readSysfsValueErr != nil {
continue
}
- memUsedBytes, err := readSysfsValueInternal(devicePath + "/mem_info_vram_used")
- if err != nil {
- slog.WarnContext(ctx, "Failed to read AMD GPU memory used", "card", name, "error", err)
+ memUsedBytes, readSysfsValueErr := readSysfsValueInternal(devicePath + "/mem_info_vram_used")
+ if readSysfsValueErr != nil {
+ slog.WarnContext(ctx, "Failed to read AMD GPU memory used", "card", name, "error", readSysfsValueErr)
continue
}
diff --git a/backend/pkg/libarcane/system/gpu_test.go b/backend/pkg/libarcane/system/gpu_test.go
index 3704afe33..b00e8665a 100644
--- a/backend/pkg/libarcane/system/gpu_test.go
+++ b/backend/pkg/libarcane/system/gpu_test.go
@@ -3,7 +3,6 @@
package system
import (
- "context"
"os"
"path/filepath"
"testing"
@@ -24,13 +23,13 @@ func TestGPUMonitorStatsCachedWithinTTL(t *testing.T) {
monitor := NewGPUMonitor(true, "nvidia")
- stats, err := monitor.Stats(context.Background())
+ stats, err := monitor.Stats(t.Context())
require.NoError(t, err)
require.Len(t, stats, 1)
require.Equal(t, "Fake GPU", stats[0].Name)
- require.EqualValues(t, 512*1024*1024, stats[0].MemoryUsed)
+ require.InDelta(t, float64(512*1024*1024), stats[0].MemoryUsed, 0)
- again, err := monitor.Stats(context.Background())
+ again, err := monitor.Stats(t.Context())
require.NoError(t, err)
require.Equal(t, stats, again)
diff --git a/backend/pkg/libarcane/volumehelper/container_files.go b/backend/pkg/libarcane/volumehelper/container_files.go
index 8c72c9569..d8fabe240 100644
--- a/backend/pkg/libarcane/volumehelper/container_files.go
+++ b/backend/pkg/libarcane/volumehelper/container_files.go
@@ -46,10 +46,10 @@ func DownloadFileFromContainer(
cleanup()
return nil, 0, fmt.Errorf("failed to read tar stream: %w", err)
}
- if err := validateDownloadHeaderInternal(hdr); err != nil {
+ if validateDownloadHeaderErr := validateDownloadHeaderInternal(hdr); validateDownloadHeaderErr != nil {
_ = reader.Close()
cleanup()
- return nil, 0, err
+ return nil, 0, validateDownloadHeaderErr
}
return &cleanupReadCloserInternal{
diff --git a/backend/pkg/libarcane/volumehelper/helper.go b/backend/pkg/libarcane/volumehelper/helper.go
index b074d1dc2..4aceacd35 100644
--- a/backend/pkg/libarcane/volumehelper/helper.go
+++ b/backend/pkg/libarcane/volumehelper/helper.go
@@ -106,7 +106,11 @@ func ResolveHelperImage(ctx context.Context, dockerClient *client.Client, toolsI
func ResolveArcaneRuntimeImage(ctx context.Context, dockerClient *client.Client) mo.Option[RuntimeImage] {
hostname, _ := os.Hostname()
if hostname != "" {
- if inspect, err := compat.ContainerInspectWithCompatibility(ctx, dockerClient, hostname, client.ContainerInspectOptions{}); err == nil && inspect.Container.Config != nil && strings.TrimSpace(inspect.Container.Config.Image) != "" {
+ if inspect,
+ err := compat.ContainerInspectWithCompatibility(ctx,
+ dockerClient,
+ hostname,
+ client.ContainerInspectOptions{}); err == nil && inspect.Container.Config != nil && strings.TrimSpace(inspect.Container.Config.Image) != "" {
return mo.Some(buildRuntimeImageInternal(inspect.Container.Config.Image, inspect.Container.Config.Entrypoint, inspect.Container.Config.Cmd, "hostname"))
}
}
diff --git a/backend/pkg/libarcane/volumehelper/helper_test.go b/backend/pkg/libarcane/volumehelper/helper_test.go
index f0d1289be..58bdc87fe 100644
--- a/backend/pkg/libarcane/volumehelper/helper_test.go
+++ b/backend/pkg/libarcane/volumehelper/helper_test.go
@@ -1,7 +1,6 @@
package volumehelper
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -43,7 +42,7 @@ func TestResolveHelperImage_UsesLocalToolsImage(t *testing.T) {
}))
t.Cleanup(server.Close)
- image, err := ResolveHelperImage(context.Background(), newTestDockerClientInternal(t, server), ToolsImage(""))
+ image, err := ResolveHelperImage(t.Context(), newTestDockerClientInternal(t, server), ToolsImage(""))
require.NoError(t, err)
require.Equal(t, ToolsImage(""), image)
@@ -75,7 +74,7 @@ func TestResolveHelperImage_PullsToolsImageWhenMissing(t *testing.T) {
}))
t.Cleanup(server.Close)
- image, err := ResolveHelperImage(context.Background(), newTestDockerClientInternal(t, server), ToolsImage(""))
+ image, err := ResolveHelperImage(t.Context(), newTestDockerClientInternal(t, server), ToolsImage(""))
require.NoError(t, err)
require.Equal(t, ToolsImage(""), image)
@@ -112,7 +111,7 @@ func TestResolveHelperImage_FallsBackToArcaneRuntimeWhenToolsPullFails(t *testin
}))
t.Cleanup(server.Close)
- image, err := ResolveHelperImage(context.Background(), newTestDockerClientInternal(t, server), ToolsImage(""))
+ image, err := ResolveHelperImage(t.Context(), newTestDockerClientInternal(t, server), ToolsImage(""))
require.NoError(t, err)
require.Equal(t, "arcane:local", image)
@@ -136,7 +135,7 @@ func TestResolveHelperImage_ReturnsPullErrorWhenNoFallbackExists(t *testing.T) {
}))
t.Cleanup(server.Close)
- image, err := ResolveHelperImage(context.Background(), newTestDockerClientInternal(t, server), ToolsImage(""))
+ image, err := ResolveHelperImage(t.Context(), newTestDockerClientInternal(t, server), ToolsImage(""))
require.Error(t, err)
require.Empty(t, image)
diff --git a/backend/pkg/libarcane/volumes/volume_rename.go b/backend/pkg/libarcane/volumes/volume_rename.go
index 18a94a768..f0c8341be 100644
--- a/backend/pkg/libarcane/volumes/volume_rename.go
+++ b/backend/pkg/libarcane/volumes/volume_rename.go
@@ -73,11 +73,11 @@ func PlanRename(ctx context.Context, dockerClient *client.Client, oldName, newNa
if err != nil {
return nil, fmt.Errorf("inspect source volume %s: %w", oldName, err)
}
- if err := EnsureRenameSourceDetached(ctx, dockerClient, oldName); err != nil {
- return nil, err
+ if ensureRenameSourceDetachedErr := EnsureRenameSourceDetached(ctx, dockerClient, oldName); ensureRenameSourceDetachedErr != nil {
+ return nil, ensureRenameSourceDetachedErr
}
- if err := EnsureRenameTargetAbsent(ctx, dockerClient, newName); err != nil {
- return nil, err
+ if ensureRenameTargetAbsentErr := EnsureRenameTargetAbsent(ctx, dockerClient, newName); ensureRenameTargetAbsentErr != nil {
+ return nil, ensureRenameTargetAbsentErr
}
entry := volumetypes.RenameEntry{
@@ -111,13 +111,13 @@ func (m *dockerProjectVolumeRenameMigrationInternal) Apply(ctx context.Context)
}
for _, entry := range m.entries {
- if err := createProjectRenamedVolumeInternal(ctx, dockerClient, entry); err != nil {
- return errors.Join(err, m.rollbackCreatedTargetsInternal(ctx, dockerClient))
+ if createProjectRenamedVolumeErr := createProjectRenamedVolumeInternal(ctx, dockerClient, entry); createProjectRenamedVolumeErr != nil {
+ return errors.Join(createProjectRenamedVolumeErr, m.rollbackCreatedTargetsInternal(ctx, dockerClient))
}
m.createdNew = append(m.createdNew, entry)
- if err := copyProjectVolumeDataInternal(ctx, dockerClient, copyRuntime, entry.OldName, entry.NewName); err != nil {
- return errors.Join(fmt.Errorf("copy volume data from %s to %s: %w", entry.OldName, entry.NewName, err), m.rollbackCreatedTargetsInternal(ctx, dockerClient))
+ if copyProjectVolumeDataErr := copyProjectVolumeDataInternal(ctx, dockerClient, copyRuntime, entry.OldName, entry.NewName); copyProjectVolumeDataErr != nil {
+ return errors.Join(fmt.Errorf("copy volume data from %s to %s: %w", entry.OldName, entry.NewName, copyProjectVolumeDataErr), m.rollbackCreatedTargetsInternal(ctx, dockerClient))
}
}
@@ -302,8 +302,8 @@ func removeProjectVolumeHelperContainersInternal(ctx context.Context, dockerClie
if !isProjectVolumeHelperContainerInternal(c) || !containerSummaryMountsVolumeInternal(c, volumeName) {
continue
}
- if _, err := dockerClient.ContainerRemove(ctx, c.ID, volumehelper.RemoveOptions()); err != nil && !cerrdefs.IsNotFound(err) {
- removeErr = errors.Join(removeErr, fmt.Errorf("remove helper container %s: %w", c.ID, err))
+ if _, containerRemoveErr := dockerClient.ContainerRemove(ctx, c.ID, volumehelper.RemoveOptions()); containerRemoveErr != nil && !cerrdefs.IsNotFound(containerRemoveErr) {
+ removeErr = errors.Join(removeErr, fmt.Errorf("remove helper container %s: %w", c.ID, containerRemoveErr))
}
}
return removeErr
@@ -387,7 +387,14 @@ func copyProjectVolumeDataInternal(ctx context.Context, dockerClient *client.Cli
return nil
}
-func createProjectVolumeCopyHolderContainerInternal(ctx context.Context, dockerClient *client.Client, copyRuntime projectVolumeCopyRuntimeInternal, volumeName string, readOnly bool) (string, func(), error) {
+func createProjectVolumeCopyHolderContainerInternal(ctx context.Context,
+ dockerClient *client.Client,
+ copyRuntime projectVolumeCopyRuntimeInternal,
+ volumeName string,
+ readOnly bool) (string,
+ func(),
+ error,
+) {
bind := volumeName + ":" + projectVolumeCopyMountPathInternal
if readOnly {
bind += ":ro"
@@ -414,8 +421,8 @@ func createProjectVolumeCopyHolderContainerInternal(ctx context.Context, dockerC
cleanup := func() {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
- if _, err := dockerClient.ContainerRemove(cleanupCtx, resp.ID, volumehelper.RemoveOptions()); err != nil && !cerrdefs.IsNotFound(err) {
- slog.WarnContext(cleanupCtx, "failed to remove volume copy holder", "containerID", resp.ID, "error", err)
+ if _, containerRemoveErr := dockerClient.ContainerRemove(cleanupCtx, resp.ID, volumehelper.RemoveOptions()); containerRemoveErr != nil && !cerrdefs.IsNotFound(containerRemoveErr) {
+ slog.WarnContext(cleanupCtx, "failed to remove volume copy holder", "containerID", resp.ID, "error", containerRemoveErr)
}
}
diff --git a/backend/pkg/libarcane/volumes/volume_rename_followup_test.go b/backend/pkg/libarcane/volumes/volume_rename_followup_test.go
index 269c63a59..a425d0a48 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_followup_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_followup_test.go
@@ -1,7 +1,6 @@
package volumes
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -42,7 +41,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackExplainsPreservedTar
},
}
- err := migration.Rollback(context.Background())
+ err := migration.Rollback(t.Context())
require.Error(t, err)
var preserved *volumetypes.TargetPreservedDuringRollbackError
@@ -68,7 +67,7 @@ func TestRollbackVolume_ExplainsPreservedTargetWhenSourceMissing(t *testing.T) {
}))
t.Cleanup(server.Close)
- err := RollbackVolume(context.Background(), newTestDockerClientInternal(t, server), volumetypes.JournalVolume{
+ err := RollbackVolume(t.Context(), newTestDockerClientInternal(t, server), volumetypes.JournalVolume{
OldName: "nginx_data",
NewName: "web_data",
})
diff --git a/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go b/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go
index 528447c5c..0961a62c9 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_runtime_test.go
@@ -1,7 +1,6 @@
package volumes
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -28,7 +27,7 @@ func TestGetProjectVolumeCopyRuntimeInternal_UsesToolsImageWhenAvailable(t *test
}))
t.Cleanup(server.Close)
- copyRuntime, err := getProjectVolumeCopyRuntimeInternal(context.Background(), newTestDockerClientInternal(t, server), volumehelper.ToolsImage(""))
+ copyRuntime, err := getProjectVolumeCopyRuntimeInternal(t.Context(), newTestDockerClientInternal(t, server), volumehelper.ToolsImage(""))
require.NoError(t, err)
require.Equal(t, volumehelper.ToolsImage(""), copyRuntime.Image)
@@ -58,7 +57,7 @@ func TestCreateProjectVolumeCopyHolderContainerInternal_UsesPassiveHolderCommand
t.Cleanup(server.Close)
_, cleanup, err := createProjectVolumeCopyHolderContainerInternal(
- context.Background(),
+ t.Context(),
newTestDockerClientInternal(t, server),
projectVolumeCopyRuntimeInternal{Image: "arcane:local"},
"nginx_data",
diff --git a/backend/pkg/libarcane/volumes/volume_rename_safety_test.go b/backend/pkg/libarcane/volumes/volume_rename_safety_test.go
index 46f3704b9..851cb63e3 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_safety_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_safety_test.go
@@ -1,7 +1,6 @@
package volumes
import (
- "context"
"encoding/json"
"errors"
"net/http"
@@ -43,7 +42,7 @@ func TestEnsureProjectRenameTargetVolumeAbsentInternal_ReturnsConflictWhenTarget
dockerClient := newTestDockerClientInternal(t, server)
- err := EnsureRenameTargetAbsent(context.Background(), dockerClient, "web_data")
+ err := EnsureRenameTargetAbsent(t.Context(), dockerClient, "web_data")
var conflictErr *volumetypes.ProjectVolumeRenameConflictError
require.ErrorAs(t, err, &conflictErr)
@@ -72,7 +71,7 @@ func TestEnsureProjectRenameSourceVolumeDetachedInternal_ReturnsConflictWhenCont
dockerClient := newTestDockerClientInternal(t, server)
- err := EnsureRenameSourceDetached(context.Background(), dockerClient, "nginx_data")
+ err := EnsureRenameSourceDetached(t.Context(), dockerClient, "nginx_data")
var inUseErr *volumetypes.ProjectVolumeRenameInUseError
require.ErrorAs(t, err, &inUseErr)
@@ -119,7 +118,7 @@ func TestGetProjectVolumeCopyRuntimeInternal_UsesArcaneAgentLabel(t *testing.T)
}))
t.Cleanup(server.Close)
- copyRuntime, err := getProjectVolumeCopyRuntimeInternal(context.Background(), newTestDockerClientInternal(t, server), volumehelper.ToolsImage(""))
+ copyRuntime, err := getProjectVolumeCopyRuntimeInternal(t.Context(), newTestDockerClientInternal(t, server), volumehelper.ToolsImage(""))
require.NoError(t, err)
require.Equal(t, "arcane-agent:local", copyRuntime.Image)
@@ -159,7 +158,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackPreservesTargetWhenS
},
}
- err := migration.Rollback(context.Background())
+ err := migration.Rollback(t.Context())
require.Error(t, err)
var preserved *volumetypes.TargetPreservedDuringRollbackError
@@ -217,7 +216,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackCleansSafeTargetsWhe
},
}
- err := migration.Rollback(context.Background())
+ err := migration.Rollback(t.Context())
require.Error(t, err)
var preserved *volumetypes.TargetPreservedDuringRollbackError
@@ -265,7 +264,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackPreservesTargetWhenS
},
}
- err := migration.Rollback(context.Background())
+ err := migration.Rollback(t.Context())
require.Error(t, err)
var preserved *volumetypes.TargetPreservedDuringRollbackError
@@ -315,7 +314,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackPreservesTargetWhenT
},
}
- err := migration.Rollback(context.Background())
+ err := migration.Rollback(t.Context())
require.Error(t, err)
var preserved *volumetypes.TargetPreservedDuringRollbackError
@@ -361,7 +360,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackRemovesTargetsWhenSo
},
}
- err := migration.Rollback(context.Background())
+ err := migration.Rollback(t.Context())
require.NoError(t, err)
require.True(t, targetRemoved.Load(), "rollback should remove copied targets while sources still exist")
@@ -395,7 +394,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackPreservesRemovedOldT
},
}
- err := migration.Rollback(context.Background())
+ err := migration.Rollback(t.Context())
require.Error(t, err)
var preserved *volumetypes.TargetPreservedDuringRollbackError
@@ -461,7 +460,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackAfterPartialCommitCl
createdNew: append([]volumetypes.RenameEntry(nil), entries...),
}
- err := migration.Commit(context.Background())
+ err := migration.Commit(t.Context())
var cleanupErr *volumetypes.SourceCleanupError
require.ErrorAs(t, err, &cleanupErr)
@@ -470,7 +469,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_RollbackAfterPartialCommitCl
require.Positive(t, secondSourceRemoveAttempts.Load())
require.Equal(t, []volumetypes.RenameEntry{entries[0]}, migration.removedOld)
- err = migration.Rollback(context.Background())
+ err = migration.Rollback(t.Context())
require.Error(t, err)
var preserved *volumetypes.TargetPreservedDuringRollbackError
@@ -526,7 +525,7 @@ func TestDockerProjectVolumeRenameMigrationInternal_CommitPreflightsAllTargetsBe
},
}
- err := migration.Commit(context.Background())
+ err := migration.Commit(t.Context())
var missingTarget *volumetypes.TargetMissingWithSourceError
require.ErrorAs(t, err, &missingTarget)
diff --git a/backend/pkg/libarcane/volumes/volume_rename_test.go b/backend/pkg/libarcane/volumes/volume_rename_test.go
index 7790ae63e..7c3189473 100644
--- a/backend/pkg/libarcane/volumes/volume_rename_test.go
+++ b/backend/pkg/libarcane/volumes/volume_rename_test.go
@@ -10,6 +10,7 @@ import (
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/api/types/volume"
"github.com/moby/moby/client"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
kit "go.getarcane.app/kit/pkg"
@@ -40,15 +41,19 @@ func TestPlanRenamePreservesStandaloneVolumeConfiguration(t *testing.T) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/source-data"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode(volume.Volume{
+ if !assert.NoError(t, json.NewEncoder(w).Encode(volume.Volume{
Name: "source-data",
Driver: "local",
Options: map[string]string{"type": "none", "device": "/srv/data"},
Labels: map[string]string{"owner": "arcane"},
- }))
+ })) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/containers/json"):
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]container.Summary{}))
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]container.Summary{})) {
+ return
+ }
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/volumes/renamed-data"):
http.NotFound(w, r)
default:
diff --git a/backend/pkg/libarcane/vuln/driver.go b/backend/pkg/libarcane/vuln/driver.go
index 1c1d47625..10bbf67dd 100644
--- a/backend/pkg/libarcane/vuln/driver.go
+++ b/backend/pkg/libarcane/vuln/driver.go
@@ -193,8 +193,8 @@ func CreateLogTempFile(prefix string) (*os.File, error) {
return nil, fmt.Errorf("failed to create trivy temp file (primary: %s) and user cache dir unavailable: %w", primaryErr.Error(), err)
}
fallbackDir := filepath.Join(cacheDir, "arcane", "trivy-tmp")
- if err := os.MkdirAll(fallbackDir, 0o700); err != nil {
- return nil, fmt.Errorf("failed to create trivy fallback temp dir %s (primary: %s): %w", fallbackDir, primaryErr.Error(), err)
+ if mkdirAllErr := os.MkdirAll(fallbackDir, 0o700); mkdirAllErr != nil {
+ return nil, fmt.Errorf("failed to create trivy fallback temp dir %s (primary: %s): %w", fallbackDir, primaryErr.Error(), mkdirAllErr)
}
fallbackFile, err := os.CreateTemp(fallbackDir, prefix)
if err != nil {
@@ -209,18 +209,18 @@ func CleanupLogTempFiles(ctx context.Context, files ...*os.File) {
continue
}
- path := file.Name()
+ localPath := file.Name()
if err := file.Close(); err != nil {
- slog.WarnContext(ctx, "failed to close trivy temp file", "path", path, "error", err)
+ slog.WarnContext(ctx, "failed to close trivy temp file", "path", localPath, "error", err)
}
- if path == "" {
+ if localPath == "" {
continue
}
// System temp scratch: no acfs root exists for it.
- if err := os.Remove(path); err != nil {
- slog.WarnContext(ctx, "failed to remove trivy temp file", "path", path, "error", err)
+ if err := os.Remove(localPath); err != nil {
+ slog.WarnContext(ctx, "failed to remove trivy temp file", "path", localPath, "error", err)
}
}
}
@@ -316,8 +316,8 @@ func ReadStartupLogs(ctx context.Context, dockerClient *client.Client, container
var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
- if _, err := stdcopy.StdCopy(&stdoutBuf, &stderrBuf, logs); err != nil && !dockerutils.IsExpectedStreamEndError(err) {
- slog.DebugContext(ctx, "failed to decode trivy startup logs", "containerId", containerID, "error", err)
+ if _, stdCopyErr := stdcopy.StdCopy(&stdoutBuf, &stderrBuf, logs); stdCopyErr != nil && !dockerutils.IsExpectedStreamEndError(stdCopyErr) {
+ slog.DebugContext(ctx, "failed to decode trivy startup logs", "containerId", containerID, "error", stdCopyErr)
}
stdoutLog := TruncateLogOutput(stdoutBuf.String(), errorExcerptSizeInternal)
@@ -539,12 +539,12 @@ func CleanupOutputFileInContainer(ctx context.Context, dockerClient *client.Clie
return
}
- if _, err := dockerClient.ExecStart(execCtx, execResp.ID, client.ExecStartOptions{}); err != nil {
+ if _, execStartErr := dockerClient.ExecStart(execCtx, execResp.ID, client.ExecStartOptions{}); execStartErr != nil {
slog.DebugContext(ctx,
"failed to start cleanup exec for trivy output file",
"containerId", containerID,
"outputPath", outputPath,
- "error", err,
+ "error", execStartErr,
)
return
}
@@ -622,9 +622,9 @@ func DecodeReportFromBytes(rawOutput []byte) (*vulnerability.TrivyReport, error)
lastErr := strictErr
for _, candidate := range jsonCandidates {
- report, err := decodeSingleReportInternal(candidate)
+ localReport, err := decodeSingleReportInternal(candidate)
if err == nil {
- return report, nil
+ return localReport, nil
}
lastErr = err
}
diff --git a/backend/pkg/libarcane/vuln/driver_test.go b/backend/pkg/libarcane/vuln/driver_test.go
index aabb893a4..4cc3ee7e5 100644
--- a/backend/pkg/libarcane/vuln/driver_test.go
+++ b/backend/pkg/libarcane/vuln/driver_test.go
@@ -183,7 +183,7 @@ func TestCleanupTrivyLogTempFilesInternal_RemovesFiles(t *testing.T) {
_, err = stderrFile.WriteString("stderr")
require.NoError(t, err)
- CleanupLogTempFiles(context.Background(), stdoutFile, stderrFile)
+ CleanupLogTempFiles(t.Context(), stdoutFile, stderrFile)
_, err = os.Stat(stdoutPath)
require.Error(t, err)
@@ -383,7 +383,7 @@ func TestSelectDefaultTrivyNetworkModeInternal(t *testing.T) {
func TestResolveTrivyUnixSocketSourceInternal(t *testing.T) {
t.Run("uses resolved host path", func(t *testing.T) {
source, err := ResolveUnixSocketSource(
- context.Background(),
+ t.Context(),
"/run/user/1000/podman/podman.sock",
func(context.Context, string) (string, error) {
return "/host/podman/podman.sock", nil
@@ -397,7 +397,7 @@ func TestResolveTrivyUnixSocketSourceInternal(t *testing.T) {
t.Run("fails when socket cannot be resolved in docker", func(t *testing.T) {
_, err := ResolveUnixSocketSource(
- context.Background(),
+ t.Context(),
"/run/user/1000/podman/podman.sock",
func(context.Context, string) (string, error) {
return "", nil
@@ -411,7 +411,7 @@ func TestResolveTrivyUnixSocketSourceInternal(t *testing.T) {
t.Run("falls back to original path outside docker", func(t *testing.T) {
source, err := ResolveUnixSocketSource(
- context.Background(),
+ t.Context(),
"/var/run/docker.sock",
func(context.Context, string) (string, error) {
return "", errors.New("not running in docker")
@@ -504,7 +504,7 @@ func TestAwaitContainerWaitResponseInternal_Status(t *testing.T) {
errCh := make(chan error)
statusCh <- containertypes.WaitResponse{StatusCode: 12}
- status, err := AwaitContainerWaitResponse(context.Background(), statusCh, errCh)
+ status, err := AwaitContainerWaitResponse(t.Context(), statusCh, errCh)
require.NoError(t, err)
require.Equal(t, int64(12), status)
}
@@ -514,7 +514,7 @@ func TestAwaitContainerWaitResponseInternal_Error(t *testing.T) {
errCh := make(chan error, 1)
errCh <- errors.New("boom")
- status, err := AwaitContainerWaitResponse(context.Background(), statusCh, errCh)
+ status, err := AwaitContainerWaitResponse(t.Context(), statusCh, errCh)
require.Error(t, err)
require.Contains(t, err.Error(), "boom")
require.Equal(t, int64(0), status)
@@ -527,7 +527,7 @@ func TestAwaitContainerWaitResponseInternal_ClosedErrorChannelStillReadsStatus(t
close(errCh)
statusCh <- containertypes.WaitResponse{StatusCode: 7}
- status, err := AwaitContainerWaitResponse(context.Background(), statusCh, errCh)
+ status, err := AwaitContainerWaitResponse(t.Context(), statusCh, errCh)
require.NoError(t, err)
require.Equal(t, int64(7), status)
}
@@ -535,7 +535,7 @@ func TestAwaitContainerWaitResponseInternal_ClosedErrorChannelStillReadsStatus(t
func TestAwaitContainerWaitResponseInternal_ContextDone(t *testing.T) {
statusCh := make(chan containertypes.WaitResponse)
errCh := make(chan error)
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Millisecond)
defer cancel()
status, err := AwaitContainerWaitResponse(ctx, statusCh, errCh)
@@ -550,7 +550,7 @@ func TestAwaitContainerWaitResponseInternal_NoStatus(t *testing.T) {
close(statusCh)
close(errCh)
- status, err := AwaitContainerWaitResponse(context.Background(), statusCh, errCh)
+ status, err := AwaitContainerWaitResponse(t.Context(), statusCh, errCh)
require.Error(t, err)
require.Contains(t, err.Error(), "ended without status")
require.Equal(t, int64(0), status)
diff --git a/backend/pkg/libarcane/vuln/risk_test.go b/backend/pkg/libarcane/vuln/risk_test.go
index 8f3fa3825..0e27ba8d4 100644
--- a/backend/pkg/libarcane/vuln/risk_test.go
+++ b/backend/pkg/libarcane/vuln/risk_test.go
@@ -3,6 +3,7 @@ package vuln
import (
"fmt"
"math"
+ "slices"
"testing"
"github.com/getarcaneapp/arcane/types/v2/vulnerability"
@@ -12,8 +13,22 @@ import (
func TestBuildScanInsights(t *testing.T) {
vulns := []vulnerability.Vulnerability{
{VulnerabilityID: "CVE-LOW", PkgName: "zlib", InstalledVersion: "1.0.0", Severity: vulnerability.SeverityLow, CVSS: &vulnerability.CVSSInfo{V3Score: 3}},
- {VulnerabilityID: "CVE-HIGH-1", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.2", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V3Score: 7.5}},
- {VulnerabilityID: "CVE-HIGH-2", PkgName: "openssl", InstalledVersion: "3.0.0", FixedVersion: "3.0.10", Severity: vulnerability.SeverityHigh, CVSS: &vulnerability.CVSSInfo{V2Score: 7.8}},
+ {
+ VulnerabilityID: "CVE-HIGH-1",
+ PkgName: "openssl",
+ InstalledVersion: "3.0.0",
+ FixedVersion: "3.0.2",
+ Severity: vulnerability.SeverityHigh,
+ CVSS: &vulnerability.CVSSInfo{V3Score: 7.5},
+ },
+ {
+ VulnerabilityID: "CVE-HIGH-2",
+ PkgName: "openssl",
+ InstalledVersion: "3.0.0",
+ FixedVersion: "3.0.10",
+ Severity: vulnerability.SeverityHigh,
+ CVSS: &vulnerability.CVSSInfo{V2Score: 7.8},
+ },
{VulnerabilityID: "CVE-MED", PkgName: "curl", InstalledVersion: "8.0.0", Severity: vulnerability.SeverityMedium},
}
@@ -28,7 +43,17 @@ func TestBuildScanInsights(t *testing.T) {
require.Equal(t, vulnerability.ScoreStatusComplete, insights.ScoreStatus)
require.Len(t, insights.TopPackages, 3)
- require.Equal(t, vulnerability.PackageInsight{PkgName: "openssl", Severity: vulnerability.SeverityHigh, Count: 2, InstalledVersion: "3.0.0", FixedVersion: "3.0.10"}, insights.TopPackages[0])
+ require.Equal(
+ t,
+ vulnerability.PackageInsight{
+ PkgName: "openssl",
+ Severity: vulnerability.SeverityHigh,
+ Count: 2,
+ InstalledVersion: "3.0.0",
+ FixedVersion: "3.0.10",
+ },
+ insights.TopPackages[0],
+ )
require.Equal(t, "curl", insights.TopPackages[1].PkgName)
require.Equal(t, "zlib", insights.TopPackages[2].PkgName)
}
@@ -39,7 +64,19 @@ func TestBuildScanInsights_VolumeSaturatesWithDiminishingReturns(t *testing.T) {
intel := map[string]ThreatIntel{}
for i := range n {
id := fmt.Sprintf("CVE-%d", i)
- vulns = append(vulns, vulnerability.Vulnerability{VulnerabilityID: id, PkgName: fmt.Sprintf("pkg-%d", i), FixedVersion: "1.0.1", Severity: severity, CVSS: &vulnerability.CVSSInfo{V3Score: cvss}})
+ vulns = append(
+ vulns,
+ vulnerability.Vulnerability{
+ VulnerabilityID: id,
+ PkgName: fmt.Sprintf(
+ "pkg-%d",
+ i,
+ ),
+ FixedVersion: "1.0.1",
+ Severity: severity,
+ CVSS: &vulnerability.CVSSInfo{V3Score: cvss},
+ },
+ )
intel[id] = ThreatIntel{KnownExploited: knownExploited, EPSS: new(0.0)}
}
return vulns, intel
@@ -105,7 +142,16 @@ func TestBuildScanInsights_UnknownSeverity(t *testing.T) {
require.Equal(t, vulnerability.ScoreStatusUnavailable, insights.ScoreStatus)
require.Zero(t, insights.RiskScore)
- mixed := append(unscored, vulnerability.Vulnerability{VulnerabilityID: "CVE-KEV", PkgName: "bar", FixedVersion: "1.1", Severity: vulnerability.SeverityMedium, CVSS: &vulnerability.CVSSInfo{V3Score: 6}})
+ mixed := append(
+ slices.Clone(unscored),
+ vulnerability.Vulnerability{
+ VulnerabilityID: "CVE-KEV",
+ PkgName: "bar",
+ FixedVersion: "1.1",
+ Severity: vulnerability.SeverityMedium,
+ CVSS: &vulnerability.CVSSInfo{V3Score: 6},
+ },
+ )
intel := map[string]ThreatIntel{"CVE-KEV": {KnownExploited: true}}
insights = BuildScanInsights(mixed, intel, vulnerability.ImageExposureRunning)
// The unscored finding is left out of the score.
diff --git a/backend/pkg/libarcane/vuln/trivy_test.go b/backend/pkg/libarcane/vuln/trivy_test.go
index 9e4386355..a28c4176d 100644
--- a/backend/pkg/libarcane/vuln/trivy_test.go
+++ b/backend/pkg/libarcane/vuln/trivy_test.go
@@ -227,7 +227,15 @@ func TestParseSecurityOpts(t *testing.T) {
{name: "single", value: "label=disable", want: []string{"label=disable"}},
{name: "comma separated", value: "label=disable,label=type:container_runtime_t", want: []string{"label=disable", "label=type:container_runtime_t"}},
{name: "newline separated", value: "label=disable\nlabel=type:container_runtime_t", want: []string{"label=disable", "label=type:container_runtime_t"}},
- {name: "mixed whitespace", value: " label=disable,\n\n label=type:container_runtime_t \r\n privileged=true ", want: []string{"label=disable", "label=type:container_runtime_t", "privileged=true"}},
+ {
+ name: "mixed whitespace",
+ value: " label=disable,\n\n label=type:container_runtime_t \r\n privileged=true ",
+ want: []string{
+ "label=disable",
+ "label=type:container_runtime_t",
+ "privileged=true",
+ },
+ },
}
for _, tt := range tests {
diff --git a/backend/pkg/libarcane/ws/benchmark_test.go b/backend/pkg/libarcane/ws/benchmark_test.go
index a8bce1604..029ccf1e6 100644
--- a/backend/pkg/libarcane/ws/benchmark_test.go
+++ b/backend/pkg/libarcane/ws/benchmark_test.go
@@ -20,7 +20,7 @@ import (
func benchWSServer(b *testing.B) (url string, cleanup func()) {
b.Helper()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(b.Context())
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
@@ -30,7 +30,7 @@ func benchWSServer(b *testing.B) (url string, cleanup func()) {
go func() {
// Drain reads until context cancelled
for {
- if _, _, err := conn.Read(ctx); err != nil {
+ if _, _, readErr := conn.Read(ctx); readErr != nil {
return
}
}
@@ -47,12 +47,12 @@ func benchWSServer(b *testing.B) (url string, cleanup func()) {
}
// benchHub creates a hub with N connected clients whose send channels are drained.
-// Returns the hub, a context cancel func, and a cleanup func.
-func benchHub(b *testing.B, numClients, hubBuf int) (*Hub, context.CancelFunc, func()) {
+// Returns the hub and its cleanup function.
+func benchHub(b *testing.B, numClients, hubBuf int) (*Hub, func()) {
b.Helper()
h := NewHub(hubBuf)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(b.Context())
go h.Run(ctx)
wsURL, serverCleanup := benchWSServer(b)
@@ -80,7 +80,7 @@ func benchHub(b *testing.B, numClients, hubBuf int) (*Hub, context.CancelFunc, f
time.Sleep(time.Millisecond)
}
- return h, cancel, func() {
+ return h, func() {
cancel()
for _, c := range conns {
_ = c.CloseNow()
@@ -97,7 +97,7 @@ func benchHub(b *testing.B, numClients, hubBuf int) (*Hub, context.CancelFunc, f
func BenchmarkHub_Broadcast(b *testing.B) {
for _, numClients := range []int{1, 10, 50, 100} {
b.Run(fmt.Sprintf("clients_%d", numClients), func(b *testing.B) {
- h, _, cleanup := benchHub(b, numClients, 4096)
+ h, cleanup := benchHub(b, numClients, 4096)
defer cleanup()
msg := []byte(`{"level":"info","message":"benchmark log message","timestamp":"2024-01-15T10:30:45Z"}`)
@@ -116,7 +116,7 @@ func BenchmarkHub_Broadcast(b *testing.B) {
func BenchmarkHub_BroadcastMessageSizes(b *testing.B) {
for _, size := range []int{64, 256, 1024, 4096, 16384} {
b.Run(fmt.Sprintf("bytes_%d", size), func(b *testing.B) {
- h, _, cleanup := benchHub(b, 10, 4096)
+ h, cleanup := benchHub(b, 10, 4096)
defer cleanup()
msg := make([]byte, size)
@@ -240,13 +240,13 @@ func BenchmarkLogMessageBatch_Marshal(b *testing.B) {
func BenchmarkForwardLogJSONBatched_Throughput(b *testing.B) {
for _, batchSize := range []int{1, 10, 50} {
b.Run(fmt.Sprintf("maxBatch_%d", batchSize), func(b *testing.B) {
- h, _, cleanup := benchHub(b, 1, 8192)
+ h, cleanup := benchHub(b, 1, 8192)
defer cleanup()
b.ReportAllocs()
b.ResetTimer()
- ctx := context.Background()
+ ctx := b.Context()
logs := make(chan LogMessage, b.N)
for range b.N {
logs <- LogMessage{
@@ -266,13 +266,13 @@ func BenchmarkForwardLogJSONBatched_Throughput(b *testing.B) {
// BenchmarkForwardLines_Throughput measures plain text line forwarding throughput.
func BenchmarkForwardLines_Throughput(b *testing.B) {
- h, _, cleanup := benchHub(b, 1, 8192)
+ h, cleanup := benchHub(b, 1, 8192)
defer cleanup()
b.ReportAllocs()
b.ResetTimer()
- ctx := context.Background()
+ ctx := b.Context()
lines := make(chan string, b.N)
for range b.N {
lines <- "2024-01-15T10:30:45Z this is a benchmark log line for testing throughput performance"
diff --git a/backend/pkg/libarcane/ws/bridge_test.go b/backend/pkg/libarcane/ws/bridge_test.go
index 91ea5fa22..7ed32df8c 100644
--- a/backend/pkg/libarcane/ws/bridge_test.go
+++ b/backend/pkg/libarcane/ws/bridge_test.go
@@ -12,12 +12,12 @@ import (
// registerCollector registers a client on the hub and returns its send channel.
// Must be called before broadcasting so the client is present to receive messages.
-func registerCollector(t *testing.T, h *Hub, bufSize int) *Client {
+func registerCollectorInternal(t *testing.T, h *Hub) *Client {
t.Helper()
- _, sc, cleanup := newTestWSPair(t)
+ sc, cleanup := newTestWSPairInternal(t)
t.Cleanup(cleanup)
- c := NewClient(sc, bufSize)
+ c := NewClient(sc, 256)
h.register <- c
require.Eventually(t, func() bool {
@@ -28,10 +28,10 @@ func registerCollector(t *testing.T, h *Hub, bufSize int) *Client {
}
// drainClient reads count messages from the client's send channel.
-func drainClient(t *testing.T, c *Client, count int, timeout time.Duration) [][]byte {
+func drainClientInternal(t *testing.T, c *Client, count int) [][]byte {
t.Helper()
var msgs [][]byte
- deadline := time.After(timeout)
+ deadline := time.After(2 * time.Second)
for range count {
select {
case msg := <-c.send:
@@ -49,7 +49,7 @@ func TestForwardLines(t *testing.T) {
go h.Run(ctx)
// Register collector BEFORE starting forwarder
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
lines := make(chan string, 5)
lines <- "line 1"
@@ -59,7 +59,7 @@ func TestForwardLines(t *testing.T) {
go ForwardLines(ctx, h, lines)
- msgs := drainClient(t, c, 3, 2*time.Second)
+ msgs := drainClientInternal(t, c, 3)
assert.Equal(t, "line 1", string(msgs[0]))
assert.Equal(t, "line 2", string(msgs[1]))
assert.Equal(t, "line 3", string(msgs[2]))
@@ -71,7 +71,7 @@ func TestForwardLines_ContextCancellation(t *testing.T) {
go h.Run(hubCtx)
lines := make(chan string)
- forwardCtx, forwardCancel := context.WithCancel(context.Background())
+ forwardCtx, forwardCancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() {
@@ -94,7 +94,7 @@ func TestForwardLogJSON(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
logs := make(chan LogMessage, 3)
logs <- LogMessage{Seq: 1, Level: "stdout", Message: "hello", Timestamp: "2024-01-15T10:30:45Z"}
@@ -103,7 +103,7 @@ func TestForwardLogJSON(t *testing.T) {
go ForwardLogJSON(ctx, h, logs)
- msgs := drainClient(t, c, 2, 2*time.Second)
+ msgs := drainClientInternal(t, c, 2)
var m1, m2 LogMessage
require.NoError(t, json.Unmarshal(msgs[0], &m1))
@@ -120,7 +120,7 @@ func TestForwardLogJSON_FillsEmptyTimestamp(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
logs := make(chan LogMessage, 1)
logs <- LogMessage{Seq: 1, Message: "no timestamp"}
@@ -128,7 +128,7 @@ func TestForwardLogJSON_FillsEmptyTimestamp(t *testing.T) {
go ForwardLogJSON(ctx, h, logs)
- msgs := drainClient(t, c, 1, 2*time.Second)
+ msgs := drainClientInternal(t, c, 1)
var m LogMessage
require.NoError(t, json.Unmarshal(msgs[0], &m))
@@ -143,7 +143,7 @@ func TestForwardLogJSONBatched(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
logs := make(chan LogMessage, 10)
for i := range 5 {
@@ -157,7 +157,7 @@ func TestForwardLogJSONBatched(t *testing.T) {
go ForwardLogJSONBatched(ctx, h, logs, 5, 100*time.Millisecond)
- msgs := drainClient(t, c, 1, 2*time.Second)
+ msgs := drainClientInternal(t, c, 1)
var batch []LogMessage
require.NoError(t, json.Unmarshal(msgs[0], &batch))
@@ -169,7 +169,7 @@ func TestForwardLogJSONBatched_FlushesOnInterval(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
logs := make(chan LogMessage, 10)
logs <- LogMessage{Seq: 1, Message: "a", Timestamp: "2024-01-15T10:30:45Z"}
@@ -177,7 +177,7 @@ func TestForwardLogJSONBatched_FlushesOnInterval(t *testing.T) {
go ForwardLogJSONBatched(ctx, h, logs, 10, 50*time.Millisecond)
- msgs := drainClient(t, c, 1, 2*time.Second)
+ msgs := drainClientInternal(t, c, 1)
var batch []LogMessage
require.NoError(t, json.Unmarshal(msgs[0], &batch))
@@ -189,7 +189,7 @@ func TestForwardLogJSONBatched_MultipleBatches(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
logs := make(chan LogMessage, 10)
for i := range 6 {
@@ -203,7 +203,7 @@ func TestForwardLogJSONBatched_MultipleBatches(t *testing.T) {
go ForwardLogJSONBatched(ctx, h, logs, 3, time.Second)
- msgs := drainClient(t, c, 2, 2*time.Second)
+ msgs := drainClientInternal(t, c, 2)
var batch1, batch2 []LogMessage
require.NoError(t, json.Unmarshal(msgs[0], &batch1))
@@ -217,7 +217,7 @@ func TestForwardLogJSONBatched_DelegatesToUnbatchedWhenMaxBatchOne(t *testing.T)
ctx := t.Context()
go h.Run(ctx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
logs := make(chan LogMessage, 3)
logs <- LogMessage{Seq: 1, Message: "single", Timestamp: "2024-01-15T10:30:45Z"}
@@ -226,7 +226,7 @@ func TestForwardLogJSONBatched_DelegatesToUnbatchedWhenMaxBatchOne(t *testing.T)
go ForwardLogJSONBatched(ctx, h, logs, 1, time.Second)
- msgs := drainClient(t, c, 2, 2*time.Second)
+ msgs := drainClientInternal(t, c, 2)
// Each message should be a single object, not an array
var m1 LogMessage
@@ -239,7 +239,7 @@ func TestForwardLogJSONBatched_FlushesOnChannelClose(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
logs := make(chan LogMessage, 10)
// Send 2 messages but maxBatch is 100 — should flush on channel close
@@ -249,7 +249,7 @@ func TestForwardLogJSONBatched_FlushesOnChannelClose(t *testing.T) {
go ForwardLogJSONBatched(ctx, h, logs, 100, time.Hour)
- msgs := drainClient(t, c, 1, 2*time.Second)
+ msgs := drainClientInternal(t, c, 1)
var batch []LogMessage
require.NoError(t, json.Unmarshal(msgs[0], &batch))
@@ -263,11 +263,11 @@ func TestForwardLogJSONBatched_FlushesOnContextCancel(t *testing.T) {
hubCtx := t.Context()
go h.Run(hubCtx)
- c := registerCollector(t, h, 256)
+ c := registerCollectorInternal(t, h)
// Use an unbuffered channel so we can control exactly when messages are sent
logs := make(chan LogMessage)
- forwardCtx, forwardCancel := context.WithCancel(context.Background())
+ forwardCtx, forwardCancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() {
@@ -289,7 +289,7 @@ func TestForwardLogJSONBatched_FlushesOnContextCancel(t *testing.T) {
}
// The buffered message should have been flushed
- msgs := drainClient(t, c, 1, 2*time.Second)
+ msgs := drainClientInternal(t, c, 1)
var batch []LogMessage
require.NoError(t, json.Unmarshal(msgs[0], &batch))
assert.Len(t, batch, 1)
diff --git a/backend/pkg/libarcane/ws/client_test.go b/backend/pkg/libarcane/ws/client_test.go
index a984a288a..6124ccbc1 100644
--- a/backend/pkg/libarcane/ws/client_test.go
+++ b/backend/pkg/libarcane/ws/client_test.go
@@ -16,7 +16,7 @@ import (
)
func TestNewClient(t *testing.T) {
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 64)
@@ -104,7 +104,7 @@ func TestServeClient_ContextCancellation(t *testing.T) {
hubCtx := t.Context()
go h.Run(hubCtx)
- clientCtx, clientCancel := context.WithCancel(context.Background())
+ clientCtx, clientCancel := context.WithCancel(t.Context())
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
@@ -234,8 +234,8 @@ func TestServeClient_MultipleMessages(t *testing.T) {
readCtx, readCancel := context.WithTimeout(t.Context(), 5*time.Second)
defer readCancel()
for _, expected := range messages {
- _, msg, err := clientConn.Read(readCtx)
- require.NoError(t, err)
+ _, msg, readErr := clientConn.Read(readCtx)
+ require.NoError(t, readErr)
assert.Equal(t, expected, string(msg))
}
}
@@ -256,7 +256,7 @@ func TestServeClient_StoppedHubDoesNotBlock(t *testing.T) {
cancel()
<-stopped
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
var onRemoveCalled atomic.Bool
diff --git a/backend/pkg/libarcane/ws/cpu_regression_test.go b/backend/pkg/libarcane/ws/cpu_regression_test.go
index 2e5186bce..86e69ba7b 100644
--- a/backend/pkg/libarcane/ws/cpu_regression_test.go
+++ b/backend/pkg/libarcane/ws/cpu_regression_test.go
@@ -55,8 +55,8 @@ func startStatsHubPipeline(ctx context.Context, hub *Hub) {
}
// readOneWithTimeout reads a single message with a timeout, discarding the payload.
-func readOneWithTimeout(conn *websocket.Conn, timeout time.Duration) error {
- readCtx, cancel := context.WithTimeout(context.Background(), timeout)
+func readOneWithTimeoutInternal(tb testing.TB, conn *websocket.Conn) error {
+ readCtx, cancel := context.WithTimeout(tb.Context(), 2*time.Second)
defer cancel()
_, _, err := conn.Read(readCtx)
return err
@@ -117,7 +117,7 @@ func BenchmarkCPU_PageReloadSimulation(b *testing.B) {
}
// Read one message to exercise the pipeline
- _ = readOneWithTimeout(conn, 2*time.Second)
+ _ = readOneWithTimeoutInternal(b, conn)
_ = conn.CloseNow()
// Brief settle for cleanup
@@ -203,7 +203,7 @@ func BenchmarkCPU_ContainerLogReloadSimulation(b *testing.B) {
require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
- _ = readOneWithTimeout(conn, 2*time.Second)
+ _ = readOneWithTimeoutInternal(b, conn)
_ = conn.CloseNow()
time.Sleep(50 * time.Millisecond)
if (i+1)%10 == 0 || i == b.N-1 {
@@ -259,7 +259,7 @@ func BenchmarkCPU_GoroutineScaling(b *testing.B) {
}
for _, c := range conns {
- _ = readOneWithTimeout(c, 2*time.Second)
+ _ = readOneWithTimeoutInternal(b, c)
}
// Close all
@@ -306,7 +306,7 @@ func BenchmarkCPU_SustainedStreaming(b *testing.B) {
require.FailNowf(b, "benchmark websocket dial failed", "%v", err)
}
for range 10 {
- if err := readOneWithTimeout(conn, 2*time.Second); err != nil {
+ if readOneWithTimeoutErr := readOneWithTimeoutInternal(b, conn); readOneWithTimeoutErr != nil {
break
}
}
@@ -342,7 +342,7 @@ func TestCPU_GoroutineCountReport(t *testing.T) {
for i := range 30 {
conn, _, err := websocket.Dial(t.Context(), url, nil)
require.NoError(t, err)
- _ = readOneWithTimeout(conn, 2*time.Second)
+ _ = readOneWithTimeoutInternal(t, conn)
_ = conn.CloseNow()
time.Sleep(50 * time.Millisecond)
current := runtime.NumGoroutine()
diff --git a/backend/pkg/libarcane/ws/goroutine_leak_test.go b/backend/pkg/libarcane/ws/goroutine_leak_test.go
index b5c181d7a..9dd8e8332 100644
--- a/backend/pkg/libarcane/ws/goroutine_leak_test.go
+++ b/backend/pkg/libarcane/ws/goroutine_leak_test.go
@@ -104,7 +104,7 @@ func waitForGoroutineCount(t *testing.T, target, tolerance int, timeout time.Dur
func TestLeak_HubRunExitsOnContextCancel(t *testing.T) {
baseline := goroutineCount()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
h := NewHub(64)
go h.Run(ctx)
@@ -127,7 +127,7 @@ func TestLeak_ServeClientFullLifecycle(t *testing.T) {
baseline := goroutineCount()
h := NewHub(64)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
go h.Run(ctx)
// Set up WebSocket server that calls ServeClient (mirrors ws_handler.go pattern)
@@ -175,7 +175,7 @@ func TestLeak_OnEmptyCallbackCancelsContext(t *testing.T) {
baseline := goroutineCount()
h := NewHub(64)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
h.SetOnEmpty(func() {
cancel() // This is what ws_handler.go does
@@ -273,7 +273,7 @@ func TestLeak_HubWithForwardLinesLifecycle(t *testing.T) {
if err != nil {
return
}
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
hub := NewHub(1024)
hub.SetOnEmpty(func() { cancel() })
go hub.Run(ctx) //nolint:contextcheck // intentional: context must outlive the HTTP request for WebSocket streaming
@@ -329,7 +329,7 @@ func TestLeak_HubWithForwardLogJSONBatchedLifecycle(t *testing.T) {
if err != nil {
return
}
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
hub := NewHub(1024)
hub.SetOnEmpty(func() { cancel() })
go hub.Run(ctx) //nolint:contextcheck // intentional: context must outlive the HTTP request
@@ -486,7 +486,7 @@ func TestLeak_ContainerStatsHubPattern(t *testing.T) {
if err != nil {
return
}
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
hub := NewHub(64)
hub.SetOnEmpty(func() { cancel() })
go hub.Run(ctx) //nolint:contextcheck // intentional: context must outlive the HTTP request
@@ -565,7 +565,7 @@ func TestLeak_MultipleClientsOnSameHub(t *testing.T) {
baseline := goroutineCount()
h := NewHub(64)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
h.SetOnEmpty(func() {
cancel()
diff --git a/backend/pkg/libarcane/ws/hub_test.go b/backend/pkg/libarcane/ws/hub_test.go
index a1562a955..3eca61bd1 100644
--- a/backend/pkg/libarcane/ws/hub_test.go
+++ b/backend/pkg/libarcane/ws/hub_test.go
@@ -18,7 +18,7 @@ import (
)
// newTestWSPair creates a connected client/server WebSocket pair using httptest.
-func newTestWSPair(t *testing.T) (clientConn, serverConn *websocket.Conn, cleanup func()) {
+func newTestWSPairInternal(t *testing.T) (serverConn *websocket.Conn, cleanup func()) {
t.Helper()
serverReady := make(chan *websocket.Conn, 1)
@@ -36,7 +36,7 @@ func newTestWSPair(t *testing.T) (clientConn, serverConn *websocket.Conn, cleanu
sc := <-serverReady
- return cc, sc, func() {
+ return sc, func() {
_ = cc.CloseNow()
// The hub and the forwarders own the server side and may already have
// closed it, so close errors here are expected.
@@ -62,7 +62,7 @@ func TestHub_RegisterAndClientCount(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 16)
@@ -79,7 +79,7 @@ func TestHub_UnregisterClient(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 16)
@@ -101,7 +101,7 @@ func TestHub_Broadcast(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 16)
@@ -133,7 +133,7 @@ func TestHub_BroadcastToMultipleClients(t *testing.T) {
cleanups := make([]func(), numClients)
for i := range numClients {
- _, sc, cleanup := newTestWSPair(t)
+ sc, cleanup := newTestWSPairInternal(t)
cleanups[i] = cleanup
clients[i] = NewClient(sc, 16)
h.register <- clients[i]
@@ -167,7 +167,7 @@ func TestHub_BackpressureDropsSlowClient(t *testing.T) {
go h.Run(ctx)
// Create a client with a tiny send buffer so it fills up fast
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 1)
@@ -198,7 +198,7 @@ func TestHub_OnEmptyCallback(t *testing.T) {
called.Store(true)
})
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 16)
@@ -223,9 +223,9 @@ func TestHub_OnFirstClientCallback(t *testing.T) {
callCount.Add(1)
})
- _, sc1, cleanup1 := newTestWSPair(t)
+ sc1, cleanup1 := newTestWSPairInternal(t)
defer cleanup1()
- _, sc2, cleanup2 := newTestWSPair(t)
+ sc2, cleanup2 := newTestWSPairInternal(t)
defer cleanup2()
h.register <- NewClient(sc1, 16)
@@ -250,9 +250,9 @@ func TestHub_OnEmptyCalledOnlyOnce(t *testing.T) {
})
// Register two clients
- _, sc1, cleanup1 := newTestWSPair(t)
+ sc1, cleanup1 := newTestWSPairInternal(t)
defer cleanup1()
- _, sc2, cleanup2 := newTestWSPair(t)
+ sc2, cleanup2 := newTestWSPairInternal(t)
defer cleanup2()
c1 := NewClient(sc1, 16)
@@ -282,7 +282,7 @@ func TestHub_OnEmptyCalledOnlyOnce(t *testing.T) {
func TestHub_ContextCancellation(t *testing.T) {
h := NewHub(10)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
done := make(chan struct{})
go func() {
@@ -290,7 +290,7 @@ func TestHub_ContextCancellation(t *testing.T) {
close(done)
}()
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 16)
@@ -378,7 +378,7 @@ func TestHub_ConcurrentOperations(t *testing.T) {
cleanup func()
}, goroutines)
for i := range goroutines {
- _, pairs[i].sc, pairs[i].cleanup = newTestWSPair(t)
+ pairs[i].sc, pairs[i].cleanup = newTestWSPairInternal(t)
t.Cleanup(pairs[i].cleanup)
}
@@ -410,7 +410,7 @@ func TestHub_DoubleUnregister(t *testing.T) {
ctx := t.Context()
go h.Run(ctx)
- _, serverConn, cleanup := newTestWSPair(t)
+ serverConn, cleanup := newTestWSPairInternal(t)
defer cleanup()
c := NewClient(serverConn, 16)
diff --git a/backend/pkg/libarcane/ws/proxy.go b/backend/pkg/libarcane/ws/proxy.go
index 9d1cf4b7e..4b7c4df05 100644
--- a/backend/pkg/libarcane/ws/proxy.go
+++ b/backend/pkg/libarcane/ws/proxy.go
@@ -69,12 +69,12 @@ func ProxyHTTP(w http.ResponseWriter, r *http.Request, remoteWS string, header h
go func() {
defer func() { errc <- struct{}{} }()
for {
- mt, msg, err := clientConn.Read(pumpCtx)
- if err != nil {
- relayCloseInternal(remoteConn, err)
+ mt, msg, readErr := clientConn.Read(pumpCtx)
+ if readErr != nil {
+ relayCloseInternal(remoteConn, readErr)
return
}
- if err := remoteConn.Write(pumpCtx, mt, msg); err != nil {
+ if writeErr := remoteConn.Write(pumpCtx, mt, msg); writeErr != nil {
return
}
}
@@ -84,12 +84,12 @@ func ProxyHTTP(w http.ResponseWriter, r *http.Request, remoteWS string, header h
go func() {
defer func() { errc <- struct{}{} }()
for {
- mt, msg, err := remoteConn.Read(pumpCtx)
- if err != nil {
- relayCloseInternal(clientConn, err)
+ mt, msg, readErr := remoteConn.Read(pumpCtx)
+ if readErr != nil {
+ relayCloseInternal(clientConn, readErr)
return
}
- if err := clientConn.Write(pumpCtx, mt, msg); err != nil {
+ if writeErr := clientConn.Write(pumpCtx, mt, msg); writeErr != nil {
return
}
}
diff --git a/backend/pkg/libarcane/ws/proxy_test.go b/backend/pkg/libarcane/ws/proxy_test.go
index f8ab9ab14..addc224c9 100644
--- a/backend/pkg/libarcane/ws/proxy_test.go
+++ b/backend/pkg/libarcane/ws/proxy_test.go
@@ -18,7 +18,7 @@ import (
func allowAnyOriginForTest(*http.Request) bool { return true }
func TestProxyHTTP_RequiresOriginValidator(t *testing.T) {
- err := ProxyHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil), "ws://127.0.0.1:1", nil, nil)
+ err := ProxyHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", http.NoBody), "ws://127.0.0.1:1", nil, nil)
require.Error(t, err, "proxy must refuse to upgrade without an origin validator")
}
@@ -32,12 +32,12 @@ func TestProxyHTTP_BidirectionalMessages(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- mt, msg, err := conn.Read(r.Context())
- if err != nil {
+ mt, msg, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
// Echo with prefix
- if err := conn.Write(r.Context(), mt, append([]byte("echo:"), msg...)); err != nil {
+ if writeErr := conn.Write(r.Context(), mt, append([]byte("echo:"), msg...)); writeErr != nil {
return
}
}
@@ -63,13 +63,13 @@ func TestProxyHTTP_BidirectionalMessages(t *testing.T) {
// 4. Send messages and verify they get proxied and echoed
testMessages := []string{"hello", "world", "test123"}
for _, msg := range testMessages {
- err := clientConn.Write(t.Context(), websocket.MessageText, []byte(msg))
- require.NoError(t, err)
+ writeErr := clientConn.Write(t.Context(), websocket.MessageText, []byte(msg))
+ require.NoError(t, writeErr)
readCtx, readCancel := context.WithTimeout(t.Context(), 2*time.Second)
- _, received, err := clientConn.Read(readCtx)
+ _, received, writeErr := clientConn.Read(readCtx)
readCancel()
- require.NoError(t, err)
+ require.NoError(t, writeErr)
assert.Equal(t, "echo:"+msg, string(received))
}
}
@@ -82,8 +82,8 @@ func TestProxyHTTP_RemoteClose(t *testing.T) {
return
}
// Close immediately
- if err := conn.Close(websocket.StatusNormalClosure, "bye"); err != nil {
- t.Logf("close websocket connection: %v", err)
+ if closeErr := conn.Close(websocket.StatusNormalClosure, "bye"); closeErr != nil {
+ t.Logf("close websocket connection: %v", closeErr)
}
}))
defer remoteServer.Close()
@@ -128,8 +128,8 @@ func TestProxyHTTP_InvalidRemoteURL(t *testing.T) {
}()
select {
- case err := <-proxyDone:
- require.Error(t, err, "ProxyHTTP should return error when remote is unreachable")
+ case operationErr := <-proxyDone:
+ require.Error(t, operationErr, "ProxyHTTP should return error when remote is unreachable")
case <-time.After(50 * time.Second):
require.FailNow(t, "ProxyHTTP did not return after failed dial")
}
@@ -145,11 +145,11 @@ func TestProxyHTTP_BinaryMessages(t *testing.T) {
defer func() { _ = conn.CloseNow() }()
for {
- mt, msg, err := conn.Read(r.Context())
- if err != nil {
+ mt, msg, readErr := conn.Read(r.Context())
+ if readErr != nil {
return
}
- if err := conn.Write(r.Context(), mt, msg); err != nil {
+ if writeErr := conn.Write(r.Context(), mt, msg); writeErr != nil {
return
}
}
diff --git a/backend/pkg/projects/cache.go b/backend/pkg/projects/cache.go
index 910cdd53c..3e417a201 100644
--- a/backend/pkg/projects/cache.go
+++ b/backend/pkg/projects/cache.go
@@ -117,7 +117,7 @@ func validComposeCacheEntryInternal(mtimes map[string]time.Time) bool {
if err != nil {
return false
}
- if err := file.Close(); err != nil {
+ if closeErr := file.Close(); closeErr != nil {
return false
}
}
@@ -125,7 +125,17 @@ func validComposeCacheEntryInternal(mtimes map[string]time.Time) bool {
}
// LoadCachedComposeProject resolves an executable model with isolated cached state.
-func LoadCachedComposeProject(ctx context.Context, cache projecttypes.ComposeCache[*composetypes.Project], projectID, projectPath, composePath, projectName, projectsDirectory string, autoInject bool, pathMapper *PathMapper) (*composetypes.Project, error) {
+func LoadCachedComposeProject(ctx context.Context,
+ cache projecttypes.ComposeCache[*composetypes.Project],
+ projectID,
+ projectPath,
+ composePath,
+ projectName,
+ projectsDirectory string,
+ autoInject bool,
+ pathMapper *PathMapper) (*composetypes.Project,
+ error,
+) {
fingerprint := fmt.Sprintf("%q|%q|%q|%t|%#v", composePath, projectName, projectsDirectory, autoInject, pathMapper)
if cache != nil {
if cached, ok := cache.Get(projectID, fingerprint); ok {
@@ -150,8 +160,8 @@ func LoadCachedComposeProject(ctx context.Context, cache projecttypes.ComposeCac
}
composeFiles := append(append([]string{}, model.ComposeFiles...), meta.ComposeFiles...)
dependencies.EnvFiles = append(dependencies.EnvFiles, meta.EnvFiles...)
- if err := cache.Set(projectID, fingerprint, projectPath, projectsDirectory, composePath, composeFiles, dependencies.EnvFiles, model); err != nil {
- return nil, err
+ if setErr := cache.Set(projectID, fingerprint, projectPath, projectsDirectory, composePath, composeFiles, dependencies.EnvFiles, model); setErr != nil {
+ return nil, setErr
}
return model, nil
}
diff --git a/backend/pkg/projects/cmds.go b/backend/pkg/projects/cmds.go
index 730df41d9..8c526e14d 100644
--- a/backend/pkg/projects/cmds.go
+++ b/backend/pkg/projects/cmds.go
@@ -69,7 +69,15 @@ func ComposeStop(ctx context.Context, proj *composetypes.Project, services []str
return c.svc.Stop(stopCtx, proj.Name, api.StopOptions{Services: services})
}
-func ComposeUp(ctx context.Context, proj *composetypes.Project, services []string, removeOrphans, forceRecreate, recreateVolumes bool, authConfigs map[string]registry.AuthConfig, waitTimeout time.Duration) error {
+func ComposeUp(ctx context.Context,
+ proj *composetypes.Project,
+ services []string,
+ removeOrphans,
+ forceRecreate,
+ recreateVolumes bool,
+ authConfigs map[string]registry.AuthConfig,
+ waitTimeout time.Duration,
+) error {
selected, err := SelectServices(proj, services)
if err != nil {
return err
@@ -136,7 +144,14 @@ func ComposeCreate(ctx context.Context, proj *composetypes.Project, services []s
return c.svc.Create(createCtx, selected, api.CreateOptions{Services: services, Recreate: api.RecreateForce, RecreateDependencies: api.RecreateDiverged})
}
-func composeUpOptionsInternal(proj *composetypes.Project, services []string, removeOrphans, forceRecreate bool, waitTimeout time.Duration, envOpts ComposeEnvOptions) (api.CreateOptions, api.StartOptions) {
+func composeUpOptionsInternal(proj *composetypes.Project,
+ services []string,
+ removeOrphans,
+ forceRecreate bool,
+ waitTimeout time.Duration,
+ envOpts ComposeEnvOptions) (api.CreateOptions,
+ api.StartOptions,
+) {
recreatePolicy := kit.Ternary(forceRecreate, api.RecreateForce, api.RecreateDiverged)
upOptions := api.CreateOptions{
diff --git a/backend/pkg/projects/cmds_test.go b/backend/pkg/projects/cmds_test.go
index 6836fdefd..f25f1a00e 100644
--- a/backend/pkg/projects/cmds_test.go
+++ b/backend/pkg/projects/cmds_test.go
@@ -21,7 +21,7 @@ import (
func TestDetachFromHTTPContextInternal(t *testing.T) {
t.Run("survives parent cancellation", func(t *testing.T) {
- parent, parentCancel := context.WithCancel(context.Background())
+ parent, parentCancel := context.WithCancel(t.Context())
detached, detachedCancel := detachFromHTTPContextInternal(parent, defaultComposeTimeout)
defer detachedCancel()
@@ -38,7 +38,7 @@ func TestDetachFromHTTPContextInternal(t *testing.T) {
t.Run("preserves context values", func(t *testing.T) {
type testKey struct{}
- parent := context.WithValue(context.Background(), testKey{}, "hello")
+ parent := context.WithValue(t.Context(), testKey{}, "hello")
detached, cancel := detachFromHTTPContextInternal(parent, defaultComposeTimeout)
defer cancel()
@@ -46,7 +46,7 @@ func TestDetachFromHTTPContextInternal(t *testing.T) {
})
t.Run("has its own deadline", func(t *testing.T) {
- detached, cancel := detachFromHTTPContextInternal(context.Background(), defaultComposeTimeout)
+ detached, cancel := detachFromHTTPContextInternal(t.Context(), defaultComposeTimeout)
defer cancel()
deadline, ok := detached.Deadline()
@@ -55,7 +55,7 @@ func TestDetachFromHTTPContextInternal(t *testing.T) {
})
t.Run("survives parent deadline expiry", func(t *testing.T) {
- parent, parentCancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
+ parent, parentCancel := context.WithTimeout(t.Context(), 1*time.Millisecond)
defer parentCancel()
time.Sleep(5 * time.Millisecond) // ensure parent deadline has passed
@@ -71,7 +71,7 @@ func TestDetachFromHTTPContextInternal(t *testing.T) {
})
t.Run("deadline scales with requested timeout", func(t *testing.T) {
- detached, cancel := detachFromHTTPContextInternal(context.Background(), 2*time.Hour)
+ detached, cancel := detachFromHTTPContextInternal(t.Context(), 2*time.Hour)
defer cancel()
deadline, ok := detached.Deadline()
@@ -80,7 +80,7 @@ func TestDetachFromHTTPContextInternal(t *testing.T) {
})
t.Run("app lifecycle context cancels detached work on shutdown", func(t *testing.T) {
- appCtx, cancelApp := context.WithCancel(utils.WithAppLifecycleContext(context.Background()))
+ appCtx, cancelApp := context.WithCancel(utils.WithAppLifecycleContext(t.Context()))
detached, detachedCancel := detachFromHTTPContextInternal(appCtx, defaultComposeTimeout)
defer detachedCancel()
@@ -93,10 +93,10 @@ func TestDetachFromHTTPContextInternal(t *testing.T) {
func TestComposeStopSkipsWhenNoServicesSpecified(t *testing.T) {
t.Setenv("DOCKER_HOST", "tcp://127.0.0.1:9")
- err := ComposeStop(context.Background(), &composetypes.Project{Name: "test"}, nil)
+ err := ComposeStop(t.Context(), &composetypes.Project{Name: "test"}, nil)
require.NoError(t, err)
- err = ComposeStop(context.Background(), &composetypes.Project{Name: "test"}, []string{})
+ err = ComposeStop(t.Context(), &composetypes.Project{Name: "test"}, []string{})
require.NoError(t, err)
}
@@ -152,7 +152,7 @@ func TestListGlobalComposeContainersUsesProvidedClient(t *testing.T) {
// The bogus dockerHost proves the provided client wins over the
// fallback host.
- containers, err := ListGlobalComposeContainers(context.Background(), apiClient, "tcp://unused.example.com:2375")
+ containers, err := ListGlobalComposeContainers(t.Context(), apiClient, "tcp://unused.example.com:2375")
require.NoError(t, err)
require.Len(t, containers, 1)
require.Equal(t, "abc123", containers[0].ID)
diff --git a/backend/pkg/projects/compose.go b/backend/pkg/projects/compose.go
index 4a181734a..5ccc0bed3 100644
--- a/backend/pkg/projects/compose.go
+++ b/backend/pkg/projects/compose.go
@@ -65,8 +65,8 @@ func NewClient(ctx context.Context, dockerHost string, authConfigs map[string]re
if dockerHost != "" {
opts.Hosts = []string{dockerHost}
}
- if err := cli.Initialize(opts); err != nil {
- return nil, err
+ if initializeErr := cli.Initialize(opts); initializeErr != nil {
+ return nil, initializeErr
}
if composeAuthConfigs := buildComposeAuthConfigsInternal(authConfigs); len(composeAuthConfigs) > 0 {
configFile := cli.ConfigFile()
@@ -144,7 +144,7 @@ func plainComposeClientInternal(ctx context.Context, dockerHost string) (*Client
// Built on context.Background so request-scoped values (progress
// writers, deadlines) do not leak into the long-lived client.
- c, err := NewClient(context.Background(), dockerHost, nil, nil) //nolint:contextcheck // deliberate: see comment above
+ c, err := NewClient(context.Background(), dockerHost, nil, nil) //nolint:contextcheck,forbidigo // Cached Compose client must not retain request values or cancellation.
if err != nil {
return nil, false, err
}
diff --git a/backend/pkg/projects/compose_logs_test.go b/backend/pkg/projects/compose_logs_test.go
index bbd212883..6b794217a 100644
--- a/backend/pkg/projects/compose_logs_test.go
+++ b/backend/pkg/projects/compose_logs_test.go
@@ -2,7 +2,6 @@ package projects
import (
"bytes"
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -50,10 +49,12 @@ func TestComposeLogsMarksStderrWithoutChangingComposeOptions(t *testing.T) {
w.WriteHeader(http.StatusOK)
case "/containers/json":
w.Header().Set("Content-Type", "application/json")
- require.NoError(t, json.NewEncoder(w).Encode([]map[string]any{
+ if !assert.NoError(t, json.NewEncoder(w).Encode([]map[string]any{
summary(composeLogsTestNonTTYContainerInternal, "web", "nginx"),
summary(composeLogsTestTTYContainerInternal, "ttyd", "ttyd"),
- }))
+ })) {
+ return
+ }
case "/containers/" + composeLogsTestNonTTYContainerInternal + "/json":
writeComposeInspectJSONInternal(t, w, composeLogsTestNonTTYContainerInternal, "web", false)
case "/containers/" + composeLogsTestTTYContainerInternal + "/json":
@@ -65,11 +66,15 @@ func TestComposeLogsMarksStderrWithoutChangingComposeOptions(t *testing.T) {
frameLogEntryInternal(stdcopy.Stdout, []byte(composeLogsTestTimestampInternal+"hello stdout\n")),
frameLogEntryInternal(stdcopy.Stderr, []byte(composeLogsTestTimestampInternal+"hello stderr\n")),
}, nil))
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
case "/containers/" + composeLogsTestTTYContainerInternal + "/logs":
w.Header().Set("Content-Type", "application/vnd.docker.raw-stream")
_, err := w.Write([]byte(composeLogsTestTimestampInternal + "raw tty output\n"))
- require.NoError(t, err)
+ if !assert.NoError(t, err) {
+ return
+ }
default:
http.NotFound(w, r)
}
@@ -79,7 +84,7 @@ func TestComposeLogsMarksStderrWithoutChangingComposeOptions(t *testing.T) {
t.Setenv("DOCKER_HOST", "tcp://"+strings.TrimPrefix(server.URL, "http://"))
out := &bytes.Buffer{}
- err := ComposeLogs(context.Background(), composeLogsTestProjectInternal, out, false, "all", "", true)
+ err := ComposeLogs(t.Context(), composeLogsTestProjectInternal, out, false, "all", "", true)
require.NoError(t, err)
body := out.String()
diff --git a/backend/pkg/projects/compose_test.go b/backend/pkg/projects/compose_test.go
index a9eb84c1f..50ab5e06f 100644
--- a/backend/pkg/projects/compose_test.go
+++ b/backend/pkg/projects/compose_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "context"
"reflect"
"testing"
@@ -33,7 +32,7 @@ func TestWrapDockerCLIWithInspectCompatibility(t *testing.T) {
}
func TestPlainComposeClientCachedPerDockerHost(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
first, shared, err := plainComposeClientInternal(ctx, "tcp://first.example.com:2375")
require.NoError(t, err)
diff --git a/backend/pkg/projects/coordinator.go b/backend/pkg/projects/coordinator.go
index b343e32f6..806583d07 100644
--- a/backend/pkg/projects/coordinator.go
+++ b/backend/pkg/projects/coordinator.go
@@ -44,8 +44,8 @@ func (c *composeCoordinatorInternal) Deploy(ctx context.Context, request project
}
}()
if request.PreDeploy != nil {
- if err := request.PreDeploy(ctx); err != nil {
- return nil, fmt.Errorf("pre-deploy lifecycle hook failed: %w", err)
+ if preDeployErr := request.PreDeploy(ctx); preDeployErr != nil {
+ return nil, fmt.Errorf("pre-deploy lifecycle hook failed: %w", preDeployErr)
}
}
model, err := request.Load(ctx)
@@ -66,17 +66,20 @@ func (c *composeCoordinatorInternal) Deploy(ctx context.Context, request project
pullPolicy = NormalizeDeployPullPolicy(request.DefaultPullPolicy)
}
pullPolicy = cmp.Or(pullPolicy, "missing")
- if err := c.PrepareImagesForDeploy(ctx, request.ProjectID, model, request.Progress, operations, pullPolicy); err != nil {
- return nil, fmt.Errorf("failed to prepare project images for deploy: %w", err)
+ if prepareImagesForDeployErr := c.PrepareImagesForDeploy(ctx, request.ProjectID, model, request.Progress, operations, pullPolicy); prepareImagesForDeployErr != nil {
+ return nil, fmt.Errorf("failed to prepare project images for deploy: %w", prepareImagesForDeployErr)
}
removeOrphans := ResolveRemoveOrphans(request.GitOpsManaged, request.Options)
slog.InfoContext(ctx, "starting compose up with health check support", "projectID", request.ProjectID, "projectName", model.Name, "services", len(model.Services), "removeOrphans", removeOrphans)
- if err := c.commands.Up(ctx, model, nil, removeOrphans, forceRecreate, recreateVolumes, request.AuthConfigs, request.WaitTimeout); err != nil {
- slog.ErrorContext(ctx, "compose up failed", "projectName", model.Name, "projectID", request.ProjectID, "error", err)
- if strings.Contains(err.Error(), "timeout") || strings.Contains(err.Error(), "context deadline exceeded") {
- return nil, fmt.Errorf("deployment timed out waiting for services - long-running 'service_healthy'/'service_completed_successfully' dependencies may need a higher Deploy Wait Timeout setting, and 'service_healthy' requires a healthcheck: %w", err)
+ if upErr := c.commands.Up(ctx, model, nil, removeOrphans, forceRecreate, recreateVolumes, request.AuthConfigs, request.WaitTimeout); upErr != nil {
+ slog.ErrorContext(ctx, "compose up failed", "projectName", model.Name, "projectID", request.ProjectID, "error", upErr)
+ if strings.Contains(upErr.Error(), "timeout") || strings.Contains(upErr.Error(), "context deadline exceeded") {
+ return nil,
+ fmt.Errorf("deployment timed out waiting for services - long-running 'service_healthy'/'service_completed_successfully' dependencies "+
+ "may need a higher Deploy Wait Timeout setting, and 'service_healthy' requires a healthcheck: %w",
+ upErr)
}
- return nil, fmt.Errorf("failed to deploy project: %w", err)
+ return nil, fmt.Errorf("failed to deploy project: %w", upErr)
}
slog.InfoContext(ctx, "compose up completed successfully", "projectID", request.ProjectID, "projectName", model.Name)
return model, nil
@@ -97,29 +100,29 @@ func (c *composeCoordinatorInternal) UpdateServices(ctx context.Context, request
}
return err
}
- if err := c.PullServices(ctx, selected, request.Services, request.Images, request.Progress); err != nil {
+ if pullServicesErr := c.PullServices(ctx, selected, request.Services, request.Images, request.Progress); pullServicesErr != nil {
if request.RestoreBeforeMutation != nil {
request.RestoreBeforeMutation(ctx)
}
- return fmt.Errorf("pull updated service images: %w", err)
+ return fmt.Errorf("pull updated service images: %w", pullServicesErr)
}
- if err := c.commands.Stop(ctx, selected, scope); err != nil {
- slog.WarnContext(ctx, "compose stop failed, continuing", "error", err)
+ if stopErr := c.commands.Stop(ctx, selected, scope); stopErr != nil {
+ slog.WarnContext(ctx, "compose stop failed, continuing", "error", stopErr)
}
- if err := c.commands.Up(ctx, selected, scope, false, true, false, request.AuthConfigs, request.WaitTimeout); err != nil {
+ if upErr := c.commands.Up(ctx, selected, scope, false, true, false, request.AuthConfigs, request.WaitTimeout); upErr != nil {
if request.Recover != nil {
request.Recover(ctx)
}
- return fmt.Errorf("failed to up services: %w", err)
+ return fmt.Errorf("failed to up services: %w", upErr)
}
// Stopped dependents are recreated after the up so they resolve the new
// provider containers, and are left stopped.
if len(request.StoppedDependents) > 0 {
- if err := c.commands.Create(ctx, selected, request.StoppedDependents, request.AuthConfigs); err != nil {
+ if createErr := c.commands.Create(ctx, selected, request.StoppedDependents, request.AuthConfigs); createErr != nil {
if request.Recover != nil {
request.Recover(ctx)
}
- return fmt.Errorf("failed to recreate stopped dependents: %w", err)
+ return fmt.Errorf("failed to recreate stopped dependents: %w", createErr)
}
}
return nil
@@ -259,20 +262,20 @@ func (c *composeCoordinatorInternal) PrepareImagesForDeploy(
}
for name, svc := range project.Services {
- svc, imageName, updated := PrepareDeployServiceConfig(projectID, project.Name, name, svc)
+ localSvc, imageName, updated := PrepareDeployServiceConfig(projectID, project.Name, name, svc)
if updated {
- project.Services[name] = svc
+ project.Services[name] = localSvc
}
if imageName == "" {
continue
}
- decision := DecideDeployImageAction(svc, pullPolicyOverride)
+ decision := DecideDeployImageAction(localSvc, pullPolicyOverride)
if updated {
decision = DeployImageDecision{Build: true}
}
- if err := c.ensureDeployServiceImageReadyInternal(ctx, projectID, project, name, svc, imageName, decision, progressWriter, operations); err != nil {
+ if err := c.ensureDeployServiceImageReadyInternal(ctx, projectID, project, name, localSvc, imageName, decision, progressWriter, operations); err != nil {
return err
}
@@ -287,14 +290,14 @@ func (c *composeCoordinatorInternal) PrepareImagesForDeploy(
case decision.PullIfStale:
dependentDecision = DeployImageDecision{PullIfStale: true, StaleAfter: decision.StaleAfter}
}
- dependentImages := api.GetDependentImages(svc, project.Name)
- for _, vol := range svc.Volumes {
+ dependentImages := api.GetDependentImages(localSvc, project.Name)
+ for _, vol := range localSvc.Volumes {
if vol.Type == composetypes.VolumeTypeImage && strings.TrimSpace(vol.Source) != "" {
dependentImages = append(dependentImages, strings.TrimSpace(vol.Source))
}
}
for _, img := range dependentImages {
- if err := c.ensureDeployServiceImageReadyInternal(ctx, projectID, project, name, svc, img, dependentDecision, progressWriter, operations); err != nil {
+ if err := c.ensureDeployServiceImageReadyInternal(ctx, projectID, project, name, localSvc, img, dependentDecision, progressWriter, operations); err != nil {
return err
}
}
@@ -376,14 +379,20 @@ func (c *composeCoordinatorInternal) buildServiceImageForDeployInternal(
project.Services[serviceName] = updatedSvc
}
- if err := operations.Build(ctx, buildReq, progressWriter, serviceName); err != nil {
- return err
+ if buildErr := operations.Build(ctx, buildReq, progressWriter, serviceName); buildErr != nil {
+ return buildErr
}
return nil
}
-func (c *composeCoordinatorInternal) BuildServices(ctx context.Context, projectID string, project *composetypes.Project, options projecttypes.BuildOptions, progressWriter io.Writer, operations projecttypes.ComposeImageOperations) error {
+func (c *composeCoordinatorInternal) BuildServices(ctx context.Context,
+ projectID string,
+ project *composetypes.Project,
+ options projecttypes.BuildOptions,
+ progressWriter io.Writer,
+ operations projecttypes.ComposeImageOperations,
+) error {
if operations.Build == nil {
return nil
}
@@ -411,8 +420,8 @@ func (c *composeCoordinatorInternal) BuildServices(ctx context.Context, projectI
}
buildCount++
- if err := operations.Build(ctx, buildReq, progressWriter, name); err != nil {
- return err
+ if buildErr := operations.Build(ctx, buildReq, progressWriter, name); buildErr != nil {
+ return buildErr
}
}
diff --git a/backend/pkg/projects/coordinator_test.go b/backend/pkg/projects/coordinator_test.go
index 4fa878711..4a4360908 100644
--- a/backend/pkg/projects/coordinator_test.go
+++ b/backend/pkg/projects/coordinator_test.go
@@ -118,7 +118,7 @@ func TestCoordinatorUpdateServicesScopesDependents(t *testing.T) {
"dormant": {Name: "dormant", Image: "example.com/dormant:1", Pid: "service:app"},
},
}
- err := coordinator.UpdateServices(context.Background(), projecttypes.ComposeServiceUpdate{
+ err := coordinator.UpdateServices(t.Context(), projecttypes.ComposeServiceUpdate{
Project: model,
Services: []string{"app"},
Dependents: []string{"sidecar"},
diff --git a/backend/pkg/projects/custom_labels.go b/backend/pkg/projects/custom_labels.go
index c23aa2424..8ca5499a4 100644
--- a/backend/pkg/projects/custom_labels.go
+++ b/backend/pkg/projects/custom_labels.go
@@ -157,9 +157,9 @@ func parseArcaneComposeMetadataFromFileInternal(ctx context.Context, composeFile
if !filepath.IsAbs(resolvedPath) {
resolvedPath = filepath.Join(workdir, resolvedPath)
}
- includedMeta, err := parseArcaneComposeMetadataFromFileInternal(ctx, resolvedPath, mergedEnv, visited)
- if err != nil {
- return meta, fmt.Errorf("load included Compose metadata %s: %w", resolvedPath, err)
+ includedMeta, parseArcaneComposeMetadataFromFileErr := parseArcaneComposeMetadataFromFileInternal(ctx, resolvedPath, mergedEnv, visited)
+ if parseArcaneComposeMetadataFromFileErr != nil {
+ return meta, fmt.Errorf("load included Compose metadata %s: %w", resolvedPath, parseArcaneComposeMetadataFromFileErr)
}
mergeArcaneComposeMetadata(&meta, includedMeta)
}
@@ -227,8 +227,8 @@ func parseComposeTagsInternal(value any) ([]projecttypes.TagOption, bool) {
seen := make(map[string]struct{}, len(values))
authoritative := true
for index, value := range values {
- definition, ok := kit.AsStringMap(value)
- if !ok {
+ definition, localOk := kit.AsStringMap(value)
+ if !localOk {
slog.Warn("skipping invalid x-arcane tag; expected a name/color object", "index", index)
authoritative = false
continue
@@ -412,8 +412,8 @@ func parseIncludePaths(composeFilePath string) ([]string, error) {
}
composeData := map[string]any{}
- if err := yaml.Unmarshal(content, &composeData); err != nil {
- return nil, fmt.Errorf("parse compose file: %w", err)
+ if unmarshalErr := yaml.Unmarshal(content, &composeData); unmarshalErr != nil {
+ return nil, fmt.Errorf("parse compose file: %w", unmarshalErr)
}
rawIncludes, ok := composeData["include"]
@@ -441,13 +441,13 @@ func parseIncludePaths(composeFilePath string) ([]string, error) {
case string:
paths = append(paths, v)
case map[string]any:
- if p, ok := v["path"]; ok {
+ if p, localOk := v["path"]; localOk {
switch pathValue := p.(type) {
case string:
paths = append(paths, pathValue)
case []any:
for _, entry := range pathValue {
- if s, ok := entry.(string); ok {
+ if s, localOk2 := entry.(string); localOk2 {
paths = append(paths, s)
}
}
@@ -599,14 +599,14 @@ func applyServiceLabelMetadataInternal(project *composetypes.Project) error {
}
maps.Copy(defaults, hiddenDefaults)
for name, service := range project.Services {
- overrides, err := updaterMetadataLabelsInternal(service.Extensions[arcaneBlockKey])
- if err != nil {
- return fmt.Errorf("service %s x-arcane.updater: %w", name, err)
+ overrides, updaterMetadataLabelsErr := updaterMetadataLabelsInternal(service.Extensions[arcaneBlockKey])
+ if updaterMetadataLabelsErr != nil {
+ return fmt.Errorf("service %s x-arcane.updater: %w", name, updaterMetadataLabelsErr)
}
effective := maps.Clone(defaults)
- hiddenOverrides, err := hiddenMetadataLabelInternal(service.Extensions[arcaneBlockKey])
- if err != nil {
- return fmt.Errorf("service %s x-arcane.hidden: %w", name, err)
+ hiddenOverrides, updaterMetadataLabelsErr := hiddenMetadataLabelInternal(service.Extensions[arcaneBlockKey])
+ if updaterMetadataLabelsErr != nil {
+ return fmt.Errorf("service %s x-arcane.hidden: %w", name, updaterMetadataLabelsErr)
}
maps.Copy(effective, overrides)
maps.Copy(effective, hiddenOverrides)
@@ -661,8 +661,8 @@ func updaterMetadataLabelsInternal(block any) (map[string]string, error) {
default:
return nil, fmt.Errorf("unknown updater option %q", key)
}
- text, ok := value.(string)
- if !ok {
+ text, localOk := value.(string)
+ if !localOk {
return nil, fmt.Errorf("updater %s must be a string", key)
}
text = strings.TrimSpace(text)
diff --git a/backend/pkg/projects/custom_labels_test.go b/backend/pkg/projects/custom_labels_test.go
index 70c622b22..12a277969 100644
--- a/backend/pkg/projects/custom_labels_test.go
+++ b/backend/pkg/projects/custom_labels_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "context"
"os"
"path/filepath"
"strings"
@@ -33,7 +32,7 @@ x-arcane:
composePath := filepath.Join(tempDir, "compose.yaml")
require.NoError(t, os.WriteFile(composePath, []byte(composeContent), 0o600))
- meta, err := ParseArcaneComposeMetadata(context.Background(), composePath, tempDir, false)
+ meta, err := ParseArcaneComposeMetadata(t.Context(), composePath, tempDir, false)
require.NoError(t, err)
require.Equal(t, "https://cdn.jsdelivr.net/gh/homarr-labs/webp/raspberry-pi.webp", meta.ProjectIcon.Light)
require.Equal(t, "https://cdn.jsdelivr.net/gh/homarr-labs/webp/raspberry-pi.webp", meta.ProjectIcon.Dark)
@@ -58,7 +57,7 @@ services:
composePath := filepath.Join(tempDir, "compose.yaml")
require.NoError(t, os.WriteFile(composePath, []byte(composeContent), 0o600))
- meta, err := ParseArcaneComposeMetadata(context.Background(), composePath, tempDir, false)
+ meta, err := ParseArcaneComposeMetadata(t.Context(), composePath, tempDir, false)
require.NoError(t, err)
require.Equal(t, IconSet{Light: "postgres", Dark: "postgres"}, meta.ServiceIconSets["db"])
require.NotContains(t, meta.ServiceIconSets, "umami")
@@ -84,7 +83,7 @@ services:
`
require.NoError(t, os.WriteFile(filepath.Join(tempDir, "meta.yaml"), []byte(metaContent), 0o600))
- meta, err := ParseArcaneComposeMetadata(context.Background(), composePath, tempDir, false)
+ meta, err := ParseArcaneComposeMetadata(t.Context(), composePath, tempDir, false)
require.NoError(t, err)
require.Equal(t, "https://example.com/icon-light.png", meta.ProjectIcon.Light)
require.Equal(t, "https://example.com/icon-dark.png", meta.ProjectIcon.Dark)
@@ -116,7 +115,7 @@ services:
services: {}
`), 0o600))
- meta, err := ParseArcaneComposeMetadata(context.Background(), filepath.Join(tempDir, "compose.yaml"), tempDir, false)
+ meta, err := ParseArcaneComposeMetadata(t.Context(), filepath.Join(tempDir, "compose.yaml"), tempDir, false)
require.NoError(t, err)
require.Equal(t, []projecttypes.TagOption{
{Name: "database", Color: projecttypes.TagColorPurple},
@@ -148,7 +147,7 @@ x-arcane:
icon-dark: *watchtower-icon
`), 0o600))
- meta, err := ParseArcaneComposeMetadata(context.Background(), filepath.Join(projectDir, "compose.yaml"), projectsRoot, false)
+ meta, err := ParseArcaneComposeMetadata(t.Context(), filepath.Join(projectDir, "compose.yaml"), projectsRoot, false)
require.NoError(t, err)
require.Equal(t, "https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/watchtower.svg", meta.ProjectIcon.Light)
require.Equal(t, "https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/watchtower.svg", meta.ProjectIcon.Dark)
@@ -178,7 +177,7 @@ x-arcane:
icon-dark: *watchtower-icon
`), 0o600))
- meta, err := ParseArcaneComposeMetadata(context.Background(), filepath.Join(projectDir, "compose.yaml"), projectsRoot, false)
+ meta, err := ParseArcaneComposeMetadata(t.Context(), filepath.Join(projectDir, "compose.yaml"), projectsRoot, false)
require.NoError(t, err)
require.Equal(t, "https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/watchtower.svg", meta.ProjectIcon.Light)
require.Equal(t, "https://cdn.jsdelivr.net/gh/selfhst/icons@main/svg/watchtower.svg", meta.ProjectIcon.Dark)
@@ -190,8 +189,8 @@ func TestNormalizeProjectTags(t *testing.T) {
require.Equal(t, []string{"database", "maintenance-window"}, tags)
for _, invalid := range []string{"", "bad,tag", "bad\ntag", strings.Repeat("a", ProjectTagMaxLength+1)} {
- _, err := NormalizeProjectTag(invalid)
- require.Error(t, err, invalid)
+ _, normalizeProjectTagErr := NormalizeProjectTag(invalid)
+ require.Error(t, normalizeProjectTagErr, invalid)
}
tooMany := make([]string, ProjectTagsPerSourceLimit+1)
@@ -247,7 +246,7 @@ services:
require.Equal(t, inherited[updaterlabels.LabelUpdateTagPattern], overridden[updaterlabels.LabelUpdateTagPattern])
explicit := project.Services["explicit"].Labels
require.Equal(t, "digest", explicit[updaterlabels.LabelUpdateStrategy])
- require.Equal(t, "", explicit[updaterlabels.LabelUpdateConstraint])
+ require.Empty(t, explicit[updaterlabels.LabelUpdateConstraint])
require.Equal(t, "keep", explicit["custom"])
}
source, err := os.ReadFile(path)
@@ -256,9 +255,23 @@ services:
}
func TestUpdaterMetadataValidationInternal(t *testing.T) {
- for _, config := range []string{"updater: true", "updater: {enabled: maybe}", "updater: {strategy: newest}", "updater: {constraint: 123}", "updater: {tag-pattern: []}", "updater: {unknown: true}"} {
+ for _, config := range []string{
+ "updater: true",
+ "updater: {enabled: maybe}",
+ "updater: {strategy: newest}",
+ "updater: {constraint: 123}",
+ "updater: {tag-pattern: []}",
+ "updater: {unknown: true}",
+ } {
t.Run(config, func(t *testing.T) {
- _, err := LoadComposeProjectFromContent(t.Context(), projecttypes.ComposeContentOptions{ComposeContent: "services:\n app:\n image: alpine:3.20.0\nx-arcane:\n " + config + "\n", WorkingDir: t.TempDir(), ProjectName: "metadata"})
+ _, err := LoadComposeProjectFromContent(
+ t.Context(),
+ projecttypes.ComposeContentOptions{
+ ComposeContent: "services:\n app:\n image: alpine:3.20.0\nx-arcane:\n " + config + "\n",
+ WorkingDir: t.TempDir(),
+ ProjectName: "metadata",
+ },
+ )
require.Error(t, err)
require.Contains(t, err.Error(), "updater")
})
diff --git a/backend/pkg/projects/discovery.go b/backend/pkg/projects/discovery.go
index b106c89e5..b8fed2e97 100644
--- a/backend/pkg/projects/discovery.go
+++ b/backend/pkg/projects/discovery.go
@@ -105,7 +105,16 @@ func DiscoverProjectDirectories(ctx context.Context, root string, followSymlinks
return discovered, nil
}
-func walkProjectDirectoriesInternal(ctx context.Context, root, path string, isRoot bool, currentDepth, maxDepth int, followSymlinks bool, ancestors map[string]struct{}, discovered *[]DiscoveredProjectDir) error {
+func walkProjectDirectoriesInternal(ctx context.Context,
+ root,
+ path string,
+ isRoot bool,
+ currentDepth,
+ maxDepth int,
+ followSymlinks bool,
+ ancestors map[string]struct{},
+ discovered *[]DiscoveredProjectDir,
+) error {
if !isRoot {
name := filepath.Base(path)
if IsIgnoredProjectDirName(name) {
@@ -136,15 +145,15 @@ func walkProjectDirectoriesInternal(ctx context.Context, root, path string, isRo
// The projects root directory itself is exempt — we always descend into it
// so siblings under the root are all discovered, even if the root happens
// to contain its own compose file.
- switch composePath, err := DetectComposeFile(ctx, root, path); {
- case err == nil, errors.Is(err, common.ErrProjectEnvUnreadable) && composePath != "":
- if err != nil {
+ switch composePath, detectComposeFileErr := DetectComposeFile(ctx, root, path); {
+ case detectComposeFileErr == nil, errors.Is(detectComposeFileErr, common.ErrProjectEnvUnreadable) && composePath != "":
+ if detectComposeFileErr != nil {
slog.Warn("Discovered project with an unreadable .env",
"path", path,
"envFile", filepath.Join(path, EffectiveEnvFileName),
"uid", os.Geteuid(),
"gid", os.Getegid(),
- "error", err)
+ "error", detectComposeFileErr)
}
*discovered = append(*discovered, DiscoveredProjectDir{
DirName: filepath.Base(path),
@@ -153,9 +162,9 @@ func walkProjectDirectoriesInternal(ctx context.Context, root, path string, isRo
if !isRoot {
return nil
}
- case errors.Is(err, common.ErrComposeFileNotFound):
+ case errors.Is(detectComposeFileErr, common.ErrComposeFileNotFound):
default:
- slog.Warn("Skipping undetectable project directory during discovery", "path", path, "error", err)
+ slog.Warn("Skipping undetectable project directory during discovery", "path", path, "error", detectComposeFileErr)
}
if maxDepth > 0 && currentDepth >= maxDepth {
@@ -177,8 +186,8 @@ func walkProjectDirectoriesInternal(ctx context.Context, root, path string, isRo
continue
}
- if err := walkProjectDirectoriesInternal(ctx, root, childPath, false, currentDepth+1, maxDepth, followSymlinks, ancestors, discovered); err != nil {
- return err
+ if walkProjectDirectoriesErr := walkProjectDirectoriesInternal(ctx, root, childPath, false, currentDepth+1, maxDepth, followSymlinks, ancestors, discovered); walkProjectDirectoriesErr != nil {
+ return walkProjectDirectoriesErr
}
}
diff --git a/backend/pkg/projects/discovery_test.go b/backend/pkg/projects/discovery_test.go
index fe789edf4..b0c56f979 100644
--- a/backend/pkg/projects/discovery_test.go
+++ b/backend/pkg/projects/discovery_test.go
@@ -33,10 +33,7 @@ func discoveredNamesInternal(dirs []DiscoveredProjectDir) []string {
func TestDiscoverProjectDirectories_StopsDescentAtCompose(t *testing.T) {
root := t.TempDir()
- // Layout:
- // root/networking/compose.yml
- // root/networking/adguardhome/compose.yml
- // root/networking/nginx-proxy-manager/compose.yml
+ // A Compose file in networking owns both nested project directories.
writeComposeFileInternal(t, filepath.Join(root, "networking"))
writeComposeFileInternal(t, filepath.Join(root, "networking", "adguardhome"))
writeComposeFileInternal(t, filepath.Join(root, "networking", "nginx-proxy-manager"))
diff --git a/backend/pkg/projects/env.go b/backend/pkg/projects/env.go
index 45eeab568..9c5930c31 100644
--- a/backend/pkg/projects/env.go
+++ b/backend/pkg/projects/env.go
@@ -126,8 +126,8 @@ func (l *EnvLoader) LoadEnvironment(ctx context.Context) (envMap, injectionVars
if strings.TrimSpace(l.projectsDir) != "" {
globalEnvPath := filepath.Join(l.projectsDir, GlobalEnvFileName)
- if err := l.loadAndMergeGlobalEnv(ctx, globalEnvPath, envMap, injectionVars); err != nil && !errors.Is(err, os.ErrNotExist) {
- slog.WarnContext(ctx, "Failed to load global env", "path", globalEnvPath, "error", err)
+ if loadAndMergeGlobalEnvErr := l.loadAndMergeGlobalEnv(ctx, globalEnvPath, envMap, injectionVars); loadAndMergeGlobalEnvErr != nil && !errors.Is(loadAndMergeGlobalEnvErr, os.ErrNotExist) {
+ slog.WarnContext(ctx, "Failed to load global env", "path", globalEnvPath, "error", loadAndMergeGlobalEnvErr)
}
}
@@ -139,14 +139,21 @@ func (l *EnvLoader) LoadEnvironment(ctx context.Context) (envMap, injectionVars
slog.DebugContext(ctx, "COMPOSE_DISABLE_ENV_FILE set; skipping project .env", "workdir", l.workdir)
} else {
projectEnvPath := filepath.Join(l.workdir, EffectiveEnvFileName)
- if err := l.loadAndMergeProjectEnv(ctx, projectEnvPath, envMap, injectionVars); err != nil {
+ if loadAndMergeProjectEnvErr := l.loadAndMergeProjectEnv(ctx, projectEnvPath, envMap, injectionVars); loadAndMergeProjectEnvErr != nil {
switch {
- case errors.Is(err, os.ErrNotExist):
+ case errors.Is(loadAndMergeProjectEnvErr, os.ErrNotExist):
slog.DebugContext(ctx, "Project .env file does not exist", "path", projectEnvPath)
- case errors.Is(err, os.ErrPermission):
- return envMap, injectionVars, common.Classify(common.ErrProjectEnvUnreadable, fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it: %w", projectEnvPath, os.Geteuid(), os.Getegid(), err))
+ case errors.Is(loadAndMergeProjectEnvErr, os.ErrPermission):
+ return envMap,
+ injectionVars,
+ common.Classify(common.ErrProjectEnvUnreadable,
+ fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it: %w",
+ projectEnvPath,
+ os.Geteuid(),
+ os.Getegid(),
+ loadAndMergeProjectEnvErr))
default:
- slog.WarnContext(ctx, "Failed to load project env", "path", projectEnvPath, "error", err)
+ slog.WarnContext(ctx, "Failed to load project env", "path", projectEnvPath, "error", loadAndMergeProjectEnvErr)
}
}
}
@@ -852,7 +859,13 @@ func ComposeFileEnvSelection(ctx context.Context, projectsDir, dir string) ([]st
projectEnv, err := ParseProjectEnvFile(projectEnvPath, envMap)
if err != nil {
if errors.Is(err, os.ErrPermission) {
- return nil, common.Classify(common.ErrProjectEnvUnreadable, fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it: %w", projectEnvPath, os.Geteuid(), os.Getegid(), err))
+ return nil,
+ common.Classify(common.ErrProjectEnvUnreadable,
+ fmt.Errorf("%s is not readable by the runtime user (uid %d, gid %d); fix its ownership/read permission or set PUID/PGID to a user that can read it: %w",
+ projectEnvPath,
+ os.Geteuid(),
+ os.Getegid(),
+ err))
}
return nil, err
}
diff --git a/backend/pkg/projects/env_test.go b/backend/pkg/projects/env_test.go
index 6620f7298..418aecf08 100644
--- a/backend/pkg/projects/env_test.go
+++ b/backend/pkg/projects/env_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "context"
"errors"
"os"
"path/filepath"
@@ -36,10 +35,10 @@ func TestLoadEnvironment(t *testing.T) {
t.Run("AutoInjectEnv=false", func(t *testing.T) {
loader := NewEnvLoader(projectsDir, workdir, false)
- ctx := context.Background()
+ ctx := t.Context()
- envMap, injectionVars, err := loader.LoadEnvironment(ctx)
- require.NoError(t, err)
+ envMap, injectionVars, loadEnvironmentErr := loader.LoadEnvironment(ctx)
+ require.NoError(t, loadEnvironmentErr)
// Verify envMap (should contain all vars, project overrides global)
assert.Equal(t, "global_value", envMap["GLOBAL_VAR"])
@@ -56,10 +55,10 @@ func TestLoadEnvironment(t *testing.T) {
t.Run("AutoInjectEnv=true", func(t *testing.T) {
loader := NewEnvLoader(projectsDir, workdir, true)
- ctx := context.Background()
+ ctx := t.Context()
- envMap, injectionVars, err := loader.LoadEnvironment(ctx)
- require.NoError(t, err)
+ envMap, injectionVars, loadEnvironmentErr := loader.LoadEnvironment(ctx)
+ require.NoError(t, loadEnvironmentErr)
// Verify envMap
assert.Equal(t, "global_value", envMap["GLOBAL_VAR"])
@@ -82,7 +81,7 @@ func TestLoadEnvironment_DoesNotCreateMissingGlobalEnvFile(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(workdir, ".env"), []byte("PROJECT_VAR=project_value\n"), utils.FilePerm))
loader := NewEnvLoader(projectsDir, workdir, false)
- ctx := context.Background()
+ ctx := t.Context()
envMap, injectionVars, err := loader.LoadEnvironment(ctx)
require.NoError(t, err)
@@ -381,35 +380,35 @@ func TestParseComposeEnvOptions(t *testing.T) {
_, err = ParseComposeEnvOptions(dir, EnvMap{"COMPOSE_ENV_FILES": "../outside.env"})
require.Error(t, err)
- assert.True(t, errors.Is(err, common.ErrComposeFileEnvInvalid))
+ assert.ErrorIs(t, err, common.ErrComposeFileEnvInvalid)
})
t.Run("absolute entry rejected", func(t *testing.T) {
t.Parallel()
_, err := ParseComposeEnvOptions(dir, EnvMap{"COMPOSE_FILE": filepath.Join(dir, "base.yml")})
require.Error(t, err)
- assert.True(t, errors.Is(err, common.ErrComposeFileEnvInvalid))
+ assert.ErrorIs(t, err, common.ErrComposeFileEnvInvalid)
})
t.Run("escaping entry rejected", func(t *testing.T) {
t.Parallel()
_, err := ParseComposeEnvOptions(dir, EnvMap{"COMPOSE_FILE": "../base.yml"})
require.Error(t, err)
- assert.True(t, errors.Is(err, common.ErrComposeFileEnvInvalid))
+ assert.ErrorIs(t, err, common.ErrComposeFileEnvInvalid)
})
t.Run("non-root first entry rejected", func(t *testing.T) {
t.Parallel()
_, err := ParseComposeEnvOptions(dir, EnvMap{"COMPOSE_FILE": "sub/extra.yml:base.yml"})
require.Error(t, err)
- assert.True(t, errors.Is(err, common.ErrComposeFileEnvInvalid))
+ assert.ErrorIs(t, err, common.ErrComposeFileEnvInvalid)
})
t.Run("missing entry rejected", func(t *testing.T) {
t.Parallel()
_, err := ParseComposeEnvOptions(dir, EnvMap{"COMPOSE_FILE": "base.yml:sub/missing.yml"})
require.Error(t, err)
- assert.True(t, errors.Is(err, common.ErrComposeFileEnvInvalid))
+ assert.ErrorIs(t, err, common.ErrComposeFileEnvInvalid)
})
}
diff --git a/backend/pkg/projects/env_validation.go b/backend/pkg/projects/env_validation.go
index 482a93b21..38aee2dde 100644
--- a/backend/pkg/projects/env_validation.go
+++ b/backend/pkg/projects/env_validation.go
@@ -36,15 +36,15 @@ func BuildValidationEnvironment(ctx context.Context, projectsDirectory, projectP
// handling so the validation env matches the runtime env exactly.
if !parseComposeBoolInternal(fullEnvMap, consts.ComposeDisableDefaultEnvFile) {
if effectiveEnvContent != nil {
- projectEnv, err := ParseValidationEnvContent(*effectiveEnvContent, fullEnvMap)
- if err != nil {
- return nil, fmt.Errorf("parse provided env content: %w", err)
+ projectEnv, parseValidationEnvContentErr := ParseValidationEnvContent(*effectiveEnvContent, fullEnvMap)
+ if parseValidationEnvContentErr != nil {
+ return nil, fmt.Errorf("parse provided env content: %w", parseValidationEnvContentErr)
}
maps.Copy(fullEnvMap, projectEnv)
} else {
- projectEnv, err := ParseValidationEnvFile(filepath.Join(projectPath, ".env"), fullEnvMap)
- if err != nil {
- return nil, fmt.Errorf("parse project env file: %w", err)
+ projectEnv, parseValidationEnvFileErr := ParseValidationEnvFile(filepath.Join(projectPath, ".env"), fullEnvMap)
+ if parseValidationEnvFileErr != nil {
+ return nil, fmt.Errorf("parse project env file: %w", parseValidationEnvFileErr)
}
maps.Copy(fullEnvMap, projectEnv)
}
diff --git a/backend/pkg/projects/fs_backup.go b/backend/pkg/projects/fs_backup.go
index fecddce39..be5a07a64 100644
--- a/backend/pkg/projects/fs_backup.go
+++ b/backend/pkg/projects/fs_backup.go
@@ -86,14 +86,14 @@ func BackupProjectUpdateScope(ctx context.Context, projectDir, backupDir string,
}
if scope.TopLevelFiles {
- if err := backupTopLevelFilesInternal(projRoot, backupRoot, backup); err != nil {
- return nil, err
+ if backupTopLevelFilesErr := backupTopLevelFilesInternal(projRoot, backupRoot, backup); backupTopLevelFilesErr != nil {
+ return nil, backupTopLevelFilesErr
}
}
for _, rel := range normalizeScopePathsInternal(scope.Paths) {
- if err := backupScopePathInternal(ctx, projRoot, backupRoot, projectDir, backupDir, rel, backup); err != nil {
- return nil, err
+ if backupScopePathErr := backupScopePathInternal(ctx, projRoot, backupRoot, projectDir, backupDir, rel, backup); backupScopePathErr != nil {
+ return nil, backupScopePathErr
}
}
@@ -124,12 +124,12 @@ func backupTopLevelFilesInternal(projRoot, backupRoot *os.Root, backup *ProjectU
name := entry.Name()
switch {
case entry.Type().IsRegular():
- if err := copyBackupFileInternal(projRoot, backupRoot, name, backup); err != nil {
- return err
+ if copyBackupFileErr := copyBackupFileInternal(projRoot, backupRoot, name, backup); copyBackupFileErr != nil {
+ return copyBackupFileErr
}
case name == EffectiveEnvFileName && entry.Type()&os.ModeSymlink != 0:
- if err := copyBackupEnvSymlinkInternal(projRoot, backupRoot, name, backup); err != nil {
- return err
+ if copyBackupEnvSymlinkErr := copyBackupEnvSymlinkInternal(projRoot, backupRoot, name, backup); copyBackupEnvSymlinkErr != nil {
+ return copyBackupEnvSymlinkErr
}
}
}
@@ -155,24 +155,24 @@ func backupScopePathInternal(ctx context.Context, projRoot, backupRoot *os.Root,
switch {
case info.IsDir():
destDir := filepath.Join(backupDir, filepath.FromSlash(rel))
- if err := os.MkdirAll(destDir, 0o755); err != nil {
- return fmt.Errorf("create backup directory: %w", err)
+ if mkdirAllErr := os.MkdirAll(destDir, 0o755); mkdirAllErr != nil {
+ return fmt.Errorf("create backup directory: %w", mkdirAllErr)
}
- copied, err := acfs.CopyDir(ctx, filepath.Join(projectDir, filepath.FromSlash(rel)), destDir, acfstypes.CopyOptions{TolerateUnreadable: true})
- if err != nil {
- return fmt.Errorf("backup project directory %s: %w", rel, err)
+ copied, copyDirErr := acfs.CopyDir(ctx, filepath.Join(projectDir, filepath.FromSlash(rel)), destDir, acfstypes.CopyOptions{TolerateUnreadable: true})
+ if copyDirErr != nil {
+ return fmt.Errorf("backup project directory %s: %w", rel, copyDirErr)
}
for _, sub := range copied.Skipped {
backup.Skipped = append(backup.Skipped, path.Join(rel, filepath.ToSlash(sub)))
}
backup.DirEntries = append(backup.DirEntries, rel)
case info.Mode().IsRegular():
- if err := copyBackupFileInternal(projRoot, backupRoot, rel, backup); err != nil {
- return err
+ if copyBackupFileErr := copyBackupFileInternal(projRoot, backupRoot, rel, backup); copyBackupFileErr != nil {
+ return copyBackupFileErr
}
case rel == EffectiveEnvFileName && info.Mode()&os.ModeSymlink != 0:
- if err := copyBackupEnvSymlinkInternal(projRoot, backupRoot, rel, backup); err != nil {
- return err
+ if copyBackupEnvSymlinkErr := copyBackupEnvSymlinkInternal(projRoot, backupRoot, rel, backup); copyBackupEnvSymlinkErr != nil {
+ return copyBackupEnvSymlinkErr
}
default:
// Other symlinks and special files: the apply operations reject them
@@ -209,12 +209,12 @@ func copyBackupFileInternal(projRoot, backupRoot *os.Root, rel string, backup *P
return fmt.Errorf("read project file %s: %w", rel, err)
}
if dir := path.Dir(rel); dir != "." {
- if err := backupRoot.MkdirAll(dir, 0o755); err != nil {
- return fmt.Errorf("create backup directory: %w", err)
+ if mkdirAllErr := backupRoot.MkdirAll(dir, 0o755); mkdirAllErr != nil {
+ return fmt.Errorf("create backup directory: %w", mkdirAllErr)
}
}
- if err := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, info.Mode().Perm()); err != nil {
- return fmt.Errorf("write backup file %s: %w", rel, err)
+ if writeFileErr := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, info.Mode().Perm()); writeFileErr != nil {
+ return fmt.Errorf("write backup file %s: %w", rel, writeFileErr)
}
backup.FileEntries = append(backup.FileEntries, rel)
return nil
@@ -255,8 +255,8 @@ func copyBackupEnvSymlinkInternal(projRoot, backupRoot *os.Root, rel string, bac
}
return fmt.Errorf("read project env symlink target %s: %w", rel, err)
}
- if err := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, perm); err != nil {
- return fmt.Errorf("write backup file %s: %w", rel, err)
+ if writeFileErr := atomic.WriteFile(filepath.Join(backupRoot.Name(), filepath.FromSlash(rel)), content, perm); writeFileErr != nil {
+ return fmt.Errorf("write backup file %s: %w", rel, writeFileErr)
}
backup.FileEntries = append(backup.FileEntries, rel)
@@ -298,26 +298,26 @@ func RestoreProjectUpdateBackup(ctx context.Context, projectDir string, backup *
// 1. Undo directory renames, then 2. remove debris the failed update
// created at paths that did not exist.
- if err := undoRenamedDirsAndDebrisInternal(projRoot, backup); err != nil {
- return err
+ if undoRenamedDirsAndDebrisErr := undoRenamedDirsAndDebrisInternal(projRoot, backup); undoRenamedDirsAndDebrisErr != nil {
+ return undoRenamedDirsAndDebrisErr
}
// 3. Mirror backed-up directories back in place, clearing a file the
// failed update may have put where the directory was.
for _, rel := range backup.DirEntries {
- if live, err := projRoot.Lstat(rel); err == nil && !live.IsDir() {
- if err := projRoot.Remove(rel); err != nil {
- return fmt.Errorf("remove conflicting file %s: %w", rel, err)
+ if live, lstatErr := projRoot.Lstat(rel); lstatErr == nil && !live.IsDir() {
+ if removeErr := projRoot.Remove(rel); removeErr != nil {
+ return fmt.Errorf("remove conflicting file %s: %w", rel, removeErr)
}
}
- if err := projRoot.MkdirAll(rel, 0o755); err != nil {
- return fmt.Errorf("recreate project directory %s: %w", rel, err)
+ if mkdirAllErr := projRoot.MkdirAll(rel, 0o755); mkdirAllErr != nil {
+ return fmt.Errorf("recreate project directory %s: %w", rel, mkdirAllErr)
}
preserve := skippedUnderInternal(backup.Skipped, rel)
src := filepath.Join(backup.BackupDir, filepath.FromSlash(rel))
dest := filepath.Join(projectDir, filepath.FromSlash(rel))
- if err := acfs.MirrorDir(ctx, src, dest, acfstypes.MirrorOptions{Preserve: preserve}); err != nil {
- return fmt.Errorf("restore project directory %s: %w", rel, err)
+ if mirrorDirErr := acfs.MirrorDir(ctx, src, dest, acfstypes.MirrorOptions{Preserve: preserve}); mirrorDirErr != nil {
+ return fmt.Errorf("restore project directory %s: %w", rel, mirrorDirErr)
}
}
@@ -329,8 +329,8 @@ func RestoreProjectUpdateBackup(ctx context.Context, projectDir string, backup *
// 4. Restore individual files in place.
for _, rel := range backup.FileEntries {
- if err := restoreBackupFileInternal(ctx, backupRoot, projRoot, backup, rel); err != nil {
- return err
+ if restoreBackupFileErr := restoreBackupFileInternal(ctx, backupRoot, projRoot, backup, rel); restoreBackupFileErr != nil {
+ return restoreBackupFileErr
}
}
@@ -339,8 +339,8 @@ func RestoreProjectUpdateBackup(ctx context.Context, projectDir string, backup *
// then copy every top-level backup file back. Top-level directories and
// symlinks are never touched.
if backup.TopLevelFiles {
- if err := restoreTopLevelFilesInternal(ctx, backupRoot, projRoot, backup); err != nil {
- return err
+ if restoreTopLevelFilesErr := restoreTopLevelFilesInternal(ctx, backupRoot, projRoot, backup); restoreTopLevelFilesErr != nil {
+ return restoreTopLevelFilesErr
}
}
@@ -366,8 +366,8 @@ func undoRenamedDirsAndDebrisInternal(projRoot *os.Root, backup *ProjectUpdateBa
if !slices.Contains(backup.DirEntries, src) && !slices.Contains(backup.AbsentEntries, src) {
continue
}
- if err := projRoot.RemoveAll(src); err != nil {
- return fmt.Errorf("remove recreated path %s: %w", src, err)
+ if removeAllErr := projRoot.RemoveAll(src); removeAllErr != nil {
+ return fmt.Errorf("remove recreated path %s: %w", src, removeAllErr)
}
handledAbsent[src] = true
}
@@ -415,25 +415,25 @@ func restoreBackupFileInternal(ctx context.Context, backupRoot, projRoot *os.Roo
live, liveErr := projRoot.Lstat(rel)
if liveErr == nil && live.Mode().IsRegular() {
// In place: the inode survives so container bind mounts of the file stay valid.
- if err := acfs.Write(ctx, projRoot.Name(), "/"+rel, content, acfs.WriteOptions{Mode: info.Mode().Perm(), InPlace: true}); err != nil {
- return fmt.Errorf("restore project file %s: %w", rel, err)
+ if writeErr := acfs.Write(ctx, projRoot.Name(), "/"+rel, content, acfs.WriteOptions{Mode: info.Mode().Perm(), InPlace: true}); writeErr != nil {
+ return fmt.Errorf("restore project file %s: %w", rel, writeErr)
}
return nil
}
if liveErr == nil && live.IsDir() {
- if err := projRoot.RemoveAll(rel); err != nil {
- return fmt.Errorf("remove conflicting directory %s: %w", rel, err)
+ if removeAllErr := projRoot.RemoveAll(rel); removeAllErr != nil {
+ return fmt.Errorf("remove conflicting directory %s: %w", rel, removeAllErr)
}
}
if dir := path.Dir(rel); dir != "." {
- if err := projRoot.MkdirAll(dir, 0o755); err != nil {
- return fmt.Errorf("recreate parent directory of %s: %w", rel, err)
+ if mkdirAllErr := projRoot.MkdirAll(dir, 0o755); mkdirAllErr != nil {
+ return fmt.Errorf("recreate parent directory of %s: %w", rel, mkdirAllErr)
}
}
// Atomic create: a crash mid-restore leaves either nothing or the fully
// restored file, never a torn write.
- if err := atomic.WriteFile(filepath.Join(projRoot.Name(), filepath.FromSlash(rel)), content, info.Mode().Perm()); err != nil {
- return fmt.Errorf("restore project file %s: %w", rel, err)
+ if writeFileErr := atomic.WriteFile(filepath.Join(projRoot.Name(), filepath.FromSlash(rel)), content, info.Mode().Perm()); writeFileErr != nil {
+ return fmt.Errorf("restore project file %s: %w", rel, writeFileErr)
}
return nil
}
@@ -464,8 +464,8 @@ func restoreBackupEnvSymlinkInternal(projRoot *os.Root, envBackup *projectUpdate
return fmt.Errorf("refusing to restore project env file %s: resolved symlink target changed", envBackup.relativePath)
}
- if err := atomic.WriteFile(resolvedPath, content, perm); err != nil {
- return fmt.Errorf("restore project env symlink target %s: %w", envBackup.relativePath, err)
+ if writeFileErr := atomic.WriteFile(resolvedPath, content, perm); writeFileErr != nil {
+ return fmt.Errorf("restore project env symlink target %s: %w", envBackup.relativePath, writeFileErr)
}
return nil
}
@@ -497,8 +497,8 @@ func restoreTopLevelFilesInternal(ctx context.Context, backupRoot, projRoot *os.
if !entry.Type().IsRegular() || inBackup[name] || skippedTopLevel[name] {
continue
}
- if err := projRoot.Remove(name); err != nil {
- return fmt.Errorf("prune created file %s: %w", name, err)
+ if removeErr := projRoot.Remove(name); removeErr != nil {
+ return fmt.Errorf("prune created file %s: %w", name, removeErr)
}
}
@@ -508,8 +508,8 @@ func restoreTopLevelFilesInternal(ctx context.Context, backupRoot, projRoot *os.
if !entry.Type().IsRegular() {
continue
}
- if err := restoreBackupFileInternal(ctx, backupRoot, projRoot, backup, entry.Name()); err != nil {
- return err
+ if restoreBackupFileErr := restoreBackupFileInternal(ctx, backupRoot, projRoot, backup, entry.Name()); restoreBackupFileErr != nil {
+ return restoreBackupFileErr
}
}
return nil
@@ -561,11 +561,11 @@ func RestoreProjectDirectoryBackup(ctx context.Context, projectsDirectory, proje
}
slog.DebugContext(ctx, "restoring project directory backup", "path", projectAbs, "backup", backup.BackupDir)
- if err := acfs.MkdirAll(ctx, rootAbs, projectLogical, utils.DirPerm); err != nil {
- return fmt.Errorf("failed to recreate project directory: %w", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, rootAbs, projectLogical, utils.DirPerm); mkdirAllErr != nil {
+ return fmt.Errorf("failed to recreate project directory: %w", mkdirAllErr)
}
- if err := RestoreProjectUpdateBackup(ctx, projectAbs, backup); err != nil {
- return fmt.Errorf("failed to restore project backup: %w", err)
+ if restoreProjectUpdateBackupErr := RestoreProjectUpdateBackup(ctx, projectAbs, backup); restoreProjectUpdateBackupErr != nil {
+ return fmt.Errorf("failed to restore project backup: %w", restoreProjectUpdateBackupErr)
}
return nil
}
diff --git a/backend/pkg/projects/fs_templates.go b/backend/pkg/projects/fs_templates.go
index 2af2e004d..fbf8279b0 100644
--- a/backend/pkg/projects/fs_templates.go
+++ b/backend/pkg/projects/fs_templates.go
@@ -76,8 +76,8 @@ func EnsureTemplateDir(ctx context.Context, templatesDir, base string) (dir, com
if err != nil {
return "", "", "", fmt.Errorf("template directory is outside the templates root: %w", err)
}
- if err := acfs.MkdirAll(ctx, baseDir, dirLogical, utils.DirPerm); err != nil {
- return "", "", "", fmt.Errorf("failed to create template directory: %w", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, baseDir, dirLogical, utils.DirPerm); mkdirAllErr != nil {
+ return "", "", "", fmt.Errorf("failed to create template directory: %w", mkdirAllErr)
}
composePath = filepath.Join(dir, "compose.yaml")
envPath = filepath.Join(dir, ".env.example")
@@ -156,24 +156,24 @@ func EnsureDefaultTemplates(ctx context.Context, configuredTemplatesDir string)
{"/.env.template", "env", getDefaultEnvTemplate(), retiredDefaultEnvTemplate},
}
for _, tmpl := range defaults {
- exists, err := acfs.Exists(ctx, templatesDir, tmpl.path)
- if err != nil {
- return fmt.Errorf("write default %s template: %w", tmpl.name, err)
+ exists, existsErr := acfs.Exists(ctx, templatesDir, tmpl.path)
+ if existsErr != nil {
+ return fmt.Errorf("write default %s template: %w", tmpl.name, existsErr)
}
if exists {
if tmpl.retired == "" {
continue
}
- current, err := acfs.ReadFile(ctx, templatesDir, tmpl.path)
- if err != nil {
- return fmt.Errorf("read default %s template: %w", tmpl.name, err)
+ current, readFileErr := acfs.ReadFile(ctx, templatesDir, tmpl.path)
+ if readFileErr != nil {
+ return fmt.Errorf("read default %s template: %w", tmpl.name, readFileErr)
}
if string(current) != tmpl.retired {
continue
}
}
- if err := acfs.Write(ctx, templatesDir, tmpl.path, []byte(tmpl.content), acfs.WriteOptions{Mode: utils.FilePerm}); err != nil {
- return fmt.Errorf("write default %s template: %w", tmpl.name, err)
+ if writeErr := acfs.Write(ctx, templatesDir, tmpl.path, []byte(tmpl.content), acfs.WriteOptions{Mode: utils.FilePerm}); writeErr != nil {
+ return fmt.Errorf("write default %s template: %w", tmpl.name, writeErr)
}
}
@@ -294,8 +294,8 @@ func ParseComposeServices(ctx context.Context, composeContent string) []string {
// Create a dummy .env file to prevent env file errors
envPath := filepath.Join(tmpDir, ".env")
- if err := WriteFileWithPerm(envPath, "", utils.FilePerm); err != nil {
- slog.WarnContext(ctx, "Failed to create dummy env file", "error", err)
+ if writeFileWithPermErr := WriteFileWithPerm(envPath, "", utils.FilePerm); writeFileWithPermErr != nil {
+ slog.WarnContext(ctx, "Failed to create dummy env file", "error", writeFileWithPermErr)
}
// Parse using compose-go
@@ -338,8 +338,8 @@ func ResolveTemplateIconURL(ctx context.Context, composeContent, envContent stri
defer func() { _ = os.RemoveAll(tmpDir) }()
envPath := filepath.Join(tmpDir, ".env")
- if err := WriteFileWithPerm(envPath, envContent, utils.FilePerm); err != nil {
- slog.WarnContext(ctx, "failed to create temp env file for template icon parsing", "error", err)
+ if writeFileWithPermErr := WriteFileWithPerm(envPath, envContent, utils.FilePerm); writeFileWithPermErr != nil {
+ slog.WarnContext(ctx, "failed to create temp env file for template icon parsing", "error", writeFileWithPermErr)
}
envMap := make(composetypes.Mapping)
diff --git a/backend/pkg/projects/fs_templates_test.go b/backend/pkg/projects/fs_templates_test.go
index 0b95115bf..c1f3d4308 100644
--- a/backend/pkg/projects/fs_templates_test.go
+++ b/backend/pkg/projects/fs_templates_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "context"
"os"
"path/filepath"
"testing"
@@ -112,7 +111,7 @@ services:
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- iconURL := ResolveTemplateIconURL(context.Background(), tt.compose, tt.envContent)
+ iconURL := ResolveTemplateIconURL(t.Context(), tt.compose, tt.envContent)
if tt.want == "" {
require.Nil(t, iconURL)
return
diff --git a/backend/pkg/projects/fs_util.go b/backend/pkg/projects/fs_util.go
index 787601989..9d73ffdef 100644
--- a/backend/pkg/projects/fs_util.go
+++ b/backend/pkg/projects/fs_util.go
@@ -42,8 +42,8 @@ func GetProjectsDirectory(ctx context.Context, projectsDir string) (string, erro
// os.* rather than acfs: this creates the confinement root itself, which
// has to exist before acfs can open it.
if _, err := os.Stat(projectsDirectory); os.IsNotExist(err) {
- if err := os.MkdirAll(projectsDirectory, utils.DirPerm); err != nil {
- return "", err
+ if mkdirAllErr := os.MkdirAll(projectsDirectory, utils.DirPerm); mkdirAllErr != nil {
+ return "", mkdirAllErr
}
slog.InfoContext(ctx, "Created projects directory", "path", projectsDirectory)
}
@@ -138,8 +138,8 @@ func HasComposeRootKeysInFile(path string) (bool, error) {
}
composeData := map[string]any{}
- if err := yaml.Unmarshal(content, &composeData); err != nil {
- return false, err
+ if unmarshalErr := yaml.Unmarshal(content, &composeData); unmarshalErr != nil {
+ return false, unmarshalErr
}
_, hasServices := composeData["services"]
@@ -152,8 +152,8 @@ func GetTemplatesDirectory(ctx context.Context, templatesDir string) (string, er
// os.* rather than acfs: this creates the confinement root itself, which
// has to exist before acfs can open it.
if _, err := os.Stat(resolved); os.IsNotExist(err) {
- if err := os.MkdirAll(resolved, utils.DirPerm); err != nil {
- return "", err
+ if mkdirAllErr := os.MkdirAll(resolved, utils.DirPerm); mkdirAllErr != nil {
+ return "", mkdirAllErr
}
slog.InfoContext(ctx, "Created templates directory", "path", resolved)
}
@@ -312,8 +312,8 @@ func RemoveStaleComposeFiles(ctx context.Context, projectPath, composeFileName s
}
for _, name := range stale {
- if err := acfs.Remove(ctx, projectPath, "/"+name); err != nil && !errors.Is(err, fs.ErrNotExist) {
- return err
+ if removeErr := acfs.Remove(ctx, projectPath, "/"+name); removeErr != nil && !errors.Is(removeErr, fs.ErrNotExist) {
+ return removeErr
}
}
@@ -372,8 +372,8 @@ func CreateExactDir(ctx context.Context, projectsRoot, basePath, name string, pe
return "", "", fmt.Errorf("project directory would be outside allowed projects root: %w", err)
}
- if err := acfs.Mkdir(ctx, projectsRoot, logicalPath, perm); err != nil {
- return "", "", kit.Ternary[error](errors.Is(err, os.ErrExist), ErrProjectDirExists, err)
+ if mkdirErr := acfs.Mkdir(ctx, projectsRoot, logicalPath, perm); mkdirErr != nil {
+ return "", "", kit.Ternary[error](errors.Is(mkdirErr, os.ErrExist), ErrProjectDirExists, mkdirErr)
}
return basePath, sanitized, nil
diff --git a/backend/pkg/projects/fs_util_test.go b/backend/pkg/projects/fs_util_test.go
index bab82fb62..bfe84a9bd 100644
--- a/backend/pkg/projects/fs_util_test.go
+++ b/backend/pkg/projects/fs_util_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "context"
"os"
"path/filepath"
"testing"
@@ -21,7 +20,7 @@ func TestGetProjectsDirectory_ResolvesRelativePathAgainstBackendModuleRoot(t *te
t.Chdir(repoRoot)
- resolved, err := GetProjectsDirectory(context.Background(), "data/projects")
+ resolved, err := GetProjectsDirectory(t.Context(), "data/projects")
require.NoError(t, err)
assert.Equal(t, filepath.Join(backendRoot, "data", "projects"), resolved)
}
@@ -35,7 +34,7 @@ func TestGetProjectsDirectory_ResolvesRelativePathFromBackendWorkingDirectory(t
t.Chdir(backendRoot)
- resolved, err := GetProjectsDirectory(context.Background(), "data/projects")
+ resolved, err := GetProjectsDirectory(t.Context(), "data/projects")
require.NoError(t, err)
assert.Equal(t, filepath.Join(backendRoot, "data", "projects"), resolved)
}
diff --git a/backend/pkg/projects/fs_writer.go b/backend/pkg/projects/fs_writer.go
index b57df46d8..7b7146b9f 100644
--- a/backend/pkg/projects/fs_writer.go
+++ b/backend/pkg/projects/fs_writer.go
@@ -296,9 +296,10 @@ func RollbackRenamedProjectDirectory(ctx context.Context, oldPath, newPath strin
newExists, _ := pathExistsInternal(newPath)
switch {
case oldExists && newExists:
- conflictPath, err := relocateRenameConflictDirectoryInternal(ctx, newPath)
- if err != nil {
- slog.Warn("project rename directory rollback found both paths and failed to relocate target path; keeping old path and clearing journal", "oldPath", oldPath, "newPath", newPath, "error", err)
+ conflictPath, relocateRenameConflictDirectoryErr := relocateRenameConflictDirectoryInternal(ctx, newPath)
+ if relocateRenameConflictDirectoryErr != nil {
+ slog.Warn("project rename directory rollback found both paths and failed to relocate target path; keeping old path and clearing journal",
+ "oldPath", oldPath, "newPath", newPath, "error", relocateRenameConflictDirectoryErr)
} else {
slog.Warn("project rename directory rollback found both paths; moved target path aside and kept old path", "oldPath", oldPath, "newPath", newPath, "conflictPath", conflictPath)
}
@@ -322,9 +323,9 @@ func RollbackRenamedProjectDirectory(ctx context.Context, oldPath, newPath strin
return pathsMissing, nil
}
-func relocateRenameConflictDirectoryInternal(ctx context.Context, path string) (string, error) {
- parent := filepath.Dir(path)
- base := filepath.Base(path)
+func relocateRenameConflictDirectoryInternal(ctx context.Context, localPath string) (string, error) {
+ parent := filepath.Dir(localPath)
+ base := filepath.Base(localPath)
now := time.Now().UTC().UnixNano()
for attempt := range 10 {
conflictName := fmt.Sprintf(".%s.rename-conflict-%d-%d", base, now, attempt)
@@ -338,7 +339,7 @@ func relocateRenameConflictDirectoryInternal(ctx context.Context, path string) (
}
return filepath.Join(parent, conflictName), nil
}
- return "", fmt.Errorf("relocate project rename target path: no available conflict path for %s", path)
+ return "", fmt.Errorf("relocate project rename target path: no available conflict path for %s", localPath)
}
// SyncFile represents a file to be written during directory sync
@@ -372,15 +373,15 @@ func WriteSyncedDirectory(ctx context.Context, projectsRoot, projectPath string,
return nil, fmt.Errorf("file path %s would escape project directory", file.RelativePath)
}
- if err := acfs.MkdirAll(ctx, projectPath, path.Dir(logicalPath), utils.DirPerm); err != nil {
- return nil, fmt.Errorf("failed to create directory for %s: %w", file.RelativePath, err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, projectPath, path.Dir(logicalPath), utils.DirPerm); mkdirAllErr != nil {
+ return nil, fmt.Errorf("failed to create directory for %s: %w", file.RelativePath, mkdirAllErr)
}
entry, statErr := acfs.Stat(ctx, projectPath, logicalPath, false)
switch {
case statErr == nil && entry.IsDirectory:
- if err := acfs.RemoveAll(ctx, projectPath, logicalPath); err != nil {
- return nil, fmt.Errorf("failed to replace directory at %s: %w", file.RelativePath, err)
+ if removeAllErr := acfs.RemoveAll(ctx, projectPath, logicalPath); removeAllErr != nil {
+ return nil, fmt.Errorf("failed to replace directory at %s: %w", file.RelativePath, removeAllErr)
}
case statErr != nil && !errors.Is(statErr, fs.ErrNotExist):
return nil, fmt.Errorf("failed to inspect target path for %s: %w", file.RelativePath, statErr)
@@ -389,8 +390,8 @@ func WriteSyncedDirectory(ctx context.Context, projectsRoot, projectPath string,
// Write the file. Honor the source's executable bit so scripts arrive
// runnable for lifecycle hooks and similar consumers.
perm := kit.Ternary(file.Executable, 0o755, utils.FilePerm)
- if err := acfs.Write(ctx, projectPath, logicalPath, file.Content, acfs.WriteOptions{Mode: perm, InPlace: true}); err != nil {
- return nil, fmt.Errorf("failed to write file %s: %w", file.RelativePath, err)
+ if writeErr := acfs.Write(ctx, projectPath, logicalPath, file.Content, acfs.WriteOptions{Mode: perm, InPlace: true}); writeErr != nil {
+ return nil, fmt.Errorf("failed to write file %s: %w", file.RelativePath, writeErr)
}
writtenPaths = append(writtenPaths, file.RelativePath)
@@ -429,9 +430,9 @@ func CleanupRemovedFiles(ctx context.Context, projectsRoot, projectPath string,
}
// Delete the file (best effort)
- if err := acfs.Remove(ctx, projectPath, logicalPath); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ if removeErr := acfs.Remove(ctx, projectPath, logicalPath); removeErr != nil && !errors.Is(removeErr, fs.ErrNotExist) {
// Log but continue - this is best effort
- slog.WarnContext(ctx, "Failed to remove old synced file", "file", oldFile, "error", err)
+ slog.WarnContext(ctx, "Failed to remove old synced file", "file", oldFile, "error", removeErr)
}
// Track parent directory for potential cleanup
diff --git a/backend/pkg/projects/fs_writer_test.go b/backend/pkg/projects/fs_writer_test.go
index cc8e63bf9..40653bf43 100644
--- a/backend/pkg/projects/fs_writer_test.go
+++ b/backend/pkg/projects/fs_writer_test.go
@@ -43,8 +43,8 @@ func TestWriteFilesPermissions(t *testing.T) {
if runtime.GOOS != "windows" {
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
- dirInfo, err := os.Stat(projectDir)
- require.NoError(t, err)
+ dirInfo, statErr := os.Stat(projectDir)
+ require.NoError(t, statErr)
assert.Equal(t, os.FileMode(0o700), dirInfo.Mode().Perm())
}
})
@@ -212,7 +212,7 @@ func TestWriteProjectFile_StillRejectsNonEnvSymlink(t *testing.T) {
if writer == "project" {
assert.Contains(t, err.Error(), "destination is a symlink")
} else {
- assert.ErrorIs(t, err, acfs.ErrSymlink)
+ require.ErrorIs(t, err, acfs.ErrSymlink)
}
targetContent, readErr := os.ReadFile(targetPath)
@@ -329,7 +329,7 @@ func TestWriteSyncedDirectory_HonorsExecutableBit(t *testing.T) {
require.NoError(t, err)
assert.Equal(t, os.FileMode(0), composeInfo.Mode().Perm()&0o111, "compose.yml should not be executable")
- scriptInfo, err := os.Stat(filepath.Join(project, "scripts/pre-deploy.sh"))
+ scriptInfo, err := os.Stat(filepath.Join(project, "scripts", "pre-deploy.sh"))
require.NoError(t, err)
assert.NotEqual(t, os.FileMode(0), scriptInfo.Mode().Perm()&0o111, "scripts/pre-deploy.sh should be executable")
}
@@ -346,7 +346,7 @@ func TestWriteSyncedDirectory_DowngradesExecutableBit(t *testing.T) {
{RelativePath: "scripts/hook.sh", Content: []byte("#!/bin/sh\n"), Executable: true},
})
require.NoError(t, err)
- first, err := os.Stat(filepath.Join(project, "scripts/hook.sh"))
+ first, err := os.Stat(filepath.Join(project, "scripts", "hook.sh"))
require.NoError(t, err)
require.NotEqual(t, os.FileMode(0), first.Mode().Perm()&0o111)
@@ -357,7 +357,7 @@ func TestWriteSyncedDirectory_DowngradesExecutableBit(t *testing.T) {
{RelativePath: "scripts/hook.sh", Content: []byte("#!/bin/sh\necho updated\n"), Executable: false},
})
require.NoError(t, err)
- second, err := os.Stat(filepath.Join(project, "scripts/hook.sh"))
+ second, err := os.Stat(filepath.Join(project, "scripts", "hook.sh"))
require.NoError(t, err)
assert.True(t, os.SameFile(first, second), "sync updates should preserve the inode")
assert.Equal(t, os.FileMode(0), second.Mode().Perm()&0o111, "executable bit should clear on update when repo no longer marks +x")
@@ -376,7 +376,7 @@ func TestWriteSyncedDirectory_UpgradesExecutableBitOnUpdate(t *testing.T) {
{RelativePath: "scripts/hook.sh", Content: []byte("#!/bin/sh\n"), Executable: false},
})
require.NoError(t, err)
- first, err := os.Stat(filepath.Join(project, "scripts/hook.sh"))
+ first, err := os.Stat(filepath.Join(project, "scripts", "hook.sh"))
require.NoError(t, err)
require.Equal(t, os.FileMode(0), first.Mode().Perm()&0o111)
@@ -386,7 +386,7 @@ func TestWriteSyncedDirectory_UpgradesExecutableBitOnUpdate(t *testing.T) {
{RelativePath: "scripts/hook.sh", Content: []byte("#!/bin/sh\n"), Executable: true},
})
require.NoError(t, err)
- second, err := os.Stat(filepath.Join(project, "scripts/hook.sh"))
+ second, err := os.Stat(filepath.Join(project, "scripts", "hook.sh"))
require.NoError(t, err)
assert.True(t, os.SameFile(first, second), "permission updates should preserve the inode")
assert.NotEqual(t, os.FileMode(0), second.Mode().Perm()&0o111, "executable bit should set on update when repo marks +x")
diff --git a/backend/pkg/projects/image_refs_test.go b/backend/pkg/projects/image_refs_test.go
index 822aa4611..5e1a10ce1 100644
--- a/backend/pkg/projects/image_refs_test.go
+++ b/backend/pkg/projects/image_refs_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "context"
"os"
"path/filepath"
"testing"
@@ -54,7 +53,7 @@ func TestBuildImageRefsFromComposeProject_UsesMergedComposeOverrides(t *testing.
build: ./app
`), 0o644))
- project, err := LoadComposeProject(context.Background(), composePath, "override-demo", dir, false, nil, nil, nil, false, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "override-demo", dir, false, nil, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
assert.Equal(t, []string{"overridden-app:latest"}, BuildImageRefsFromComposeProject(project))
diff --git a/backend/pkg/projects/includes.go b/backend/pkg/projects/includes.go
index 90274ba61..12025497e 100644
--- a/backend/pkg/projects/includes.go
+++ b/backend/pkg/projects/includes.go
@@ -51,8 +51,8 @@ func NewMissingIncludeStubLoader(projectPath string) *MissingIncludeStubLoader {
return &MissingIncludeStubLoader{projectPath: projectPath}
}
-func (l *MissingIncludeStubLoader) Accept(path string) bool {
- _, ok := l.resolveMissingIncludeInternal(path).Get()
+func (l *MissingIncludeStubLoader) Accept(localPath string) bool {
+ _, ok := l.resolveMissingIncludeInternal(localPath).Get()
return ok
}
@@ -65,7 +65,7 @@ func (l *MissingIncludeStubLoader) Load(ctx context.Context, filePath string) (s
if l.stubs == nil {
l.stubs = make(map[string]string)
}
- if stubPath, ok := l.stubs[validatedPath]; ok {
+ if stubPath, localOk := l.stubs[validatedPath]; localOk {
return stubPath, nil
}
@@ -87,32 +87,32 @@ func (l *MissingIncludeStubLoader) Load(ctx context.Context, filePath string) (s
if err != nil {
return "", fmt.Errorf("resolve validation include stub path: %w", err)
}
- if err := acfs.MkdirAll(ctx, l.tempDir, path.Dir(stubLogical), 0o755); err != nil {
- return "", fmt.Errorf("create validation include directory: %w", err)
+ if mkdirAllErr := acfs.MkdirAll(ctx, l.tempDir, path.Dir(stubLogical), 0o755); mkdirAllErr != nil {
+ return "", fmt.Errorf("create validation include directory: %w", mkdirAllErr)
}
- if err := acfs.Write(ctx, l.tempDir, stubLogical, []byte("services: {}\n"), acfs.WriteOptions{Mode: 0o600}); err != nil {
- return "", fmt.Errorf("write validation include stub: %w", err)
+ if writeErr := acfs.Write(ctx, l.tempDir, stubLogical, []byte("services: {}\n"), acfs.WriteOptions{Mode: 0o600}); writeErr != nil {
+ return "", fmt.Errorf("write validation include stub: %w", writeErr)
}
l.stubs[validatedPath] = stubPath
return stubPath, nil
}
-func (l *MissingIncludeStubLoader) Dir(path string) string {
- return filepath.Dir(path)
+func (l *MissingIncludeStubLoader) Dir(localPath string) string {
+ return filepath.Dir(localPath)
}
-func (l *MissingIncludeStubLoader) resolveMissingIncludeInternal(path string) mo.Option[string] {
- validatedPath, err := ValidateIncludePathForWrite(l.projectPath, path)
+func (l *MissingIncludeStubLoader) resolveMissingIncludeInternal(localPath string) mo.Option[string] {
+ validatedPath, err := ValidateIncludePathForWrite(l.projectPath, localPath)
if err != nil {
return mo.None[string]()
}
// os.Stat rather than acfs: the validated include target may live outside
// the project directory (#3556).
- if _, err := os.Stat(validatedPath); err == nil {
+ if _, statErr := os.Stat(validatedPath); statErr == nil {
return mo.None[string]()
- } else if !errors.Is(err, os.ErrNotExist) {
+ } else if !errors.Is(statErr, os.ErrNotExist) {
return mo.None[string]()
}
@@ -189,9 +189,9 @@ func parseIncludeItemInternal(item any, baseDir string, envMap EnvMap, includeCo
results := make([]IncludeFile, 0, len(includePaths))
for _, includePath := range includePaths {
- inc, err := resolveIncludeFileInternal(includePath, baseDir, envMap, includeContent)
- if err != nil {
- return nil, err
+ inc, resolveIncludeFileErr := resolveIncludeFileInternal(includePath, baseDir, envMap, includeContent)
+ if resolveIncludeFileErr != nil {
+ return nil, resolveIncludeFileErr
}
results = append(results, inc)
}
@@ -252,7 +252,7 @@ func resolveIncludeFileInternal(includePath, baseDir string, envMap EnvMap, incl
relativePath := includePath
if filepath.IsAbs(includePath) {
- if rel, err := filepath.Rel(baseDir, fullPath); err == nil {
+ if rel, relErr := filepath.Rel(baseDir, fullPath); relErr == nil {
relativePath = rel
}
}
@@ -301,7 +301,7 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)
absProjectDir = filepath.Clean(absProjectDir)
// Try to resolve symlinks for the project directory if it exists
- if evalProjectDir, err := filepath.EvalSymlinks(absProjectDir); err == nil {
+ if evalProjectDir, evalSymlinksErr := filepath.EvalSymlinks(absProjectDir); evalSymlinksErr == nil {
absProjectDir = evalProjectDir
}
diff --git a/backend/pkg/projects/load.go b/backend/pkg/projects/load.go
index 08bd7dc00..840c632e5 100644
--- a/backend/pkg/projects/load.go
+++ b/backend/pkg/projects/load.go
@@ -479,7 +479,15 @@ func LoadComposeProject(
return project, nil
}
-func finishLoadedProjectInternal(ctx context.Context, project *composetypes.Project, workingDir string, pathMapper projecttypes.VolumeSourcePathMapper, translateFileResources bool, rawSources map[string]string, prepare PrepareProjectFunc) (*composetypes.Project, error) {
+func finishLoadedProjectInternal(ctx context.Context,
+ project *composetypes.Project,
+ workingDir string,
+ pathMapper projecttypes.VolumeSourcePathMapper,
+ translateFileResources bool,
+ rawSources map[string]string,
+ prepare PrepareProjectFunc) (*composetypes.Project,
+ error,
+) {
if err := applyServiceLabelMetadataInternal(project); err != nil {
return nil, err
}
@@ -571,7 +579,12 @@ func isNilVolumeSourcePathMapperInternal(pathMapper projecttypes.VolumeSourcePat
return value.Kind() == reflect.Pointer && value.IsNil()
}
-func recoverComposeLoadPanicInternal(ctx context.Context, source string, project **composetypes.Project, err *error) {
+//nolint:gocritic // Pointer output updates the caller's named error result after recovery.
+func recoverComposeLoadPanicInternal(ctx context.Context,
+ source string,
+ project **composetypes.Project,
+ err *error,
+) {
if panicErr := utils.PanicToError(recover()); panicErr != nil {
slog.WarnContext(ctx,
"panic while loading compose project; compose file may contain invalid syntax",
@@ -685,7 +698,16 @@ func recordComposeDependenciesInternal(project *composetypes.Project, dependenci
// ValidateComposeContentForUpdate validates proposed editor content without persisting it.
// Missing includes are tolerated here; deployment uses strict executable loading.
-func ValidateComposeContentForUpdate(ctx context.Context, projectsDirectory, projectPath, projectName, composeContent string, effectiveEnvContent, overrideContent *string, overrideFileName string, lenient bool) (err error) {
+func ValidateComposeContentForUpdate(ctx context.Context,
+ projectsDirectory,
+ projectPath,
+ projectName,
+ composeContent string,
+ effectiveEnvContent,
+ overrideContent *string,
+ overrideFileName string,
+ lenient bool,
+) (err error) {
defer func() {
if panicErr := utils.PanicToError(recover()); panicErr != nil {
err = fmt.Errorf("compose file contains invalid syntax: %w", panicErr)
diff --git a/backend/pkg/projects/load_test.go b/backend/pkg/projects/load_test.go
index 034448110..73a588698 100644
--- a/backend/pkg/projects/load_test.go
+++ b/backend/pkg/projects/load_test.go
@@ -182,7 +182,7 @@ func TestLoadComposeProject_ComposeFileEnvSelectsFilesAndSkipsOverride(t *testin
require.NoError(t, os.WriteFile(filepath.Join(dir, "compose.override.yaml"), []byte("services:\n app:\n image: alpine:3\n"), 0o600))
require.NoError(t, os.WriteFile(filepath.Join(dir, ".env"), []byte("COMPOSE_FILE=base.yml:sub/extra.yml\n"), 0o600))
- project, err := LoadComposeProject(context.Background(), basePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), basePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, project)
@@ -230,7 +230,7 @@ func TestLoadComposeProject_ArcaneProcessEnvInterpolation(t *testing.T) {
basePath := filepath.Join(dir, "compose.yaml")
require.NoError(t, os.WriteFile(basePath, []byte(tc.compose), 0o600))
- project, err := LoadComposeProject(context.Background(), basePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), basePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, project)
@@ -251,7 +251,7 @@ func TestLoadComposeProject_DoesNotMergeOverrideForCustomBaseName(t *testing.T)
require.NoError(t, os.WriteFile(basePath, []byte("services:\n app:\n image: nginx:alpine\n environment:\n FROM_BASE: \"1\"\n"), 0o600))
require.NoError(t, os.WriteFile(overridePath, []byte("services:\n app:\n image: busybox:latest\n environment:\n FROM_OVERRIDE: \"1\"\n"), 0o600))
- project, err := LoadComposeProject(context.Background(), basePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), basePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, project)
@@ -282,7 +282,7 @@ func TestLoadComposeProjectFromDir_SupportsPodmanComposeNames(t *testing.T) {
require.NoError(t, os.WriteFile(expectedPath, []byte(composeContent), 0o600))
project, composePath, err := LoadComposeProjectFromDir(
- context.Background(),
+ t.Context(),
dir,
"podman-project",
filepath.Dir(dir),
@@ -307,7 +307,7 @@ func TestLoadComposeProjectFromDir_SupportsCustomComposeNames(t *testing.T) {
require.NoError(t, os.WriteFile(expectedPath, []byte("services:\n app:\n image: nginx:alpine\n"), 0o600))
project, composePath, err := LoadComposeProjectFromDir(
- context.Background(),
+ t.Context(),
dir,
"radarr",
filepath.Dir(dir),
@@ -328,7 +328,7 @@ func TestLoadComposeProjectFromDir_EmptyProjectsDirectoryDoesNotCreateParentGlob
require.NoError(t, os.MkdirAll(projectDir, 0o755))
require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte("services:\n app:\n image: nginx:alpine\n"), 0o600))
- project, composePath, err := LoadComposeProjectFromDir(context.Background(), projectDir, "nested-services", "", false, nil)
+ project, composePath, err := LoadComposeProjectFromDir(t.Context(), projectDir, "nested-services", "", false, nil)
require.NoError(t, err)
require.NotNil(t, project)
@@ -354,7 +354,7 @@ func TestLoadComposeProjectLenient_ToleratesUndefinedVariables(t *testing.T) {
- ${CONFIG_FILE}:/etc/app/app.conf
`), 0o600))
- project, err := LoadComposeProject(context.Background(), composePath, "demo", dir, false, nil, nil, nil, true, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "demo", dir, false, nil, nil, nil, true, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, project)
assert.Len(t, project.Services, 1)
@@ -380,7 +380,7 @@ func TestLoadComposeProjectLenient_ToleratesUndefinedTypedFieldVariables(t *test
memory: ${MEMORY}
`), 0o600))
- project, err := LoadComposeProject(context.Background(), composePath, "demo", dir, false, nil, nil, nil, true, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "demo", dir, false, nil, nil, nil, true, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, project)
assert.Len(t, project.Services, 1)
@@ -405,7 +405,7 @@ func TestLoadComposeProjectLenient_AppliesVariableDefaults(t *testing.T) {
- MAX_FILE_SIZE=${ARCANE_TEST_UNSET_SIZE:-104857600}
`), 0o600))
- project, err := LoadComposeProject(context.Background(), composePath, "demo", dir, false, nil, nil, nil, true, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "demo", dir, false, nil, nil, nil, true, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, project)
require.Len(t, project.Services, 1)
@@ -439,7 +439,7 @@ services:
image: busybox:latest
`), 0o600))
- project, err := LoadComposeProject(context.Background(), composePath, "demo", projectDir, false, nil, nil, nil, false, nil, []string{"root", "included"}, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "demo", projectDir, false, nil, nil, nil, false, nil, []string{"root", "included"}, nil)
require.NoError(t, err)
require.NotNil(t, project)
@@ -492,7 +492,7 @@ services:
composePath := filepath.Join(projectDir, "compose.yaml")
require.NoError(t, os.WriteFile(composePath, []byte(tt.composeBody), 0o600))
- project, err := LoadComposeProject(context.Background(), composePath, "aitools", projectDir, false, nil, nil, nil, false, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "aitools", projectDir, false, nil, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
require.NotNil(t, project)
require.Equal(t, tt.wantName, project.Name)
@@ -515,7 +515,7 @@ func TestResolveRelativeProjectPaths(t *testing.T) {
- ./config.conf:/etc/app/config.conf
`), 0o600))
- project, err := LoadComposeProject(context.Background(), composePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "demo", dir, false, nil, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
ResolveRelativeProjectPaths(project, dir)
@@ -549,7 +549,7 @@ func TestLoadComposeProject_RemapsRelativeBindEscapingProjectsMount(t *testing.T
pathMapper := NewPathMapper(projectsRoot, "/docker/112/arcane/arcane-data/projects")
require.True(t, pathMapper.IsNonMatchingMount())
- project, err := LoadComposeProject(context.Background(), composePath, "goclaw", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, nil)
+ project, err := LoadComposeProject(t.Context(), composePath, "goclaw", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
sources := make(map[string]string)
@@ -603,7 +603,7 @@ func TestLoadComposeProject_PrepareRunsBeforeHostPathTranslation(t *testing.T) {
return os.MkdirAll(filepath.Join(projectDir, "conf"), 0o755)
}
- project, err := LoadComposeProject(context.Background(), composePath, "caddy", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, prepare)
+ project, err := LoadComposeProject(t.Context(), composePath, "caddy", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, prepare)
require.NoError(t, err)
assert.Equal(t, []string{filepath.Join(projectDir, "conf")}, seen, "prepare sees only active services with local resolved sources")
@@ -611,13 +611,13 @@ func TestLoadComposeProject_PrepareRunsBeforeHostPathTranslation(t *testing.T) {
assert.DirExists(t, filepath.Join(projectDir, "conf"))
prepareErr := errors.New("boom")
- _, err = LoadComposeProject(context.Background(), composePath, "caddy", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, func(context.Context, *composetypes.Project) error {
+ _, err = LoadComposeProject(t.Context(), composePath, "caddy", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, func(context.Context, *composetypes.Project) error {
return prepareErr
})
require.ErrorIs(t, err, prepareErr)
require.NoError(t, os.RemoveAll(filepath.Join(projectDir, "conf")))
- _, err = LoadComposeProject(context.Background(), composePath, "caddy", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, nil)
+ _, err = LoadComposeProject(t.Context(), composePath, "caddy", projectsRoot, false, pathMapper, nil, nil, false, nil, nil, nil)
require.NoError(t, err)
assert.NoDirExists(t, filepath.Join(projectDir, "conf"), "nil prepare must not create bind directories")
}
diff --git a/backend/pkg/projects/logs_demux_test.go b/backend/pkg/projects/logs_demux_test.go
index 07bb66198..130a653da 100644
--- a/backend/pkg/projects/logs_demux_test.go
+++ b/backend/pkg/projects/logs_demux_test.go
@@ -98,7 +98,7 @@ func TestLogsDemuxClientContainerLogsDecisionInternal(t *testing.T) {
inner.recordContainerTTYInternal(" CTR-1 ", tt.ttyRecorded)
}
- got, err := inner.ContainerLogs(context.Background(), "ctr-1", client.ContainerLogsOptions{ShowStdout: tt.showStdout, ShowStderr: tt.showStderr})
+ got, err := inner.ContainerLogs(t.Context(), "ctr-1", client.ContainerLogsOptions{ShowStdout: tt.showStdout, ShowStderr: tt.showStderr})
require.NoError(t, err)
if !tt.wantWrapped {
diff --git a/backend/pkg/projects/path_mapper_test.go b/backend/pkg/projects/path_mapper_test.go
index b602d87c7..160bf1dcc 100644
--- a/backend/pkg/projects/path_mapper_test.go
+++ b/backend/pkg/projects/path_mapper_test.go
@@ -1,7 +1,6 @@
package projects
import (
- "context"
"path/filepath"
"testing"
@@ -11,7 +10,7 @@ import (
)
func TestNewPathMapperForConfiguredDirectory(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
t.Run("empty configuration uses default without Docker", func(t *testing.T) {
defaultDir := filepath.Join(t.TempDir(), "projects")
@@ -31,8 +30,8 @@ func TestNewPathMapperForConfiguredDirectory(t *testing.T) {
pathMapper := NewPathMapperForConfiguredDirectory(ctx, containerDir+":"+hostDir, containerDir, nil)
require.NotNil(t, pathMapper)
- source := filepath.Join(containerDir, "0/stack/compose.yaml")
- expected := filepath.Join(hostDir, "0/stack/compose.yaml")
+ source := filepath.Join(containerDir, "0", "stack", "compose.yaml")
+ expected := filepath.Join(hostDir, "0", "stack", "compose.yaml")
translated, _, err := pathMapper.ContainerToHost(source)
require.NoError(t, err)
require.Equal(t, filepath.ToSlash(expected), filepath.ToSlash(translated))
@@ -233,7 +232,7 @@ func TestRemapEscapedRelativeSources_MountTableTakesPrecedence(t *testing.T) {
}
require.NoError(t, pm.TranslateVolumeSources(project, true))
- RemapEscapedRelativeSources(context.Background(), pm, project, containerWorkingDir, rawSources, true)
+ RemapEscapedRelativeSources(t.Context(), pm, project, containerWorkingDir, rawSources, true)
volumes := project.Services["goclaw"].Volumes
assert.Equal(t, "/mnt/media", volumes[0].Source, "nested independent mount must win over the host project directory")
diff --git a/backend/pkg/projects/volume_migration.go b/backend/pkg/projects/volume_migration.go
index f7fd6321a..9885ac21a 100644
--- a/backend/pkg/projects/volume_migration.go
+++ b/backend/pkg/projects/volume_migration.go
@@ -51,9 +51,16 @@ func PlanVolumeMigration(ctx context.Context, dockerClient *client.Client, compo
return volumes.NewMigration(dockerClient, entries, oldComposeName, newComposeName, toolsImage), nil
}
-func collectProjectRenameVolumeEntriesInternal(ctx context.Context, dockerClient *client.Client, volumes map[string]composetypes.VolumeConfig, explicitVolumeNames map[string]struct{}, oldComposeName, newComposeName string) ([]volumetypes.RenameEntry, error) {
- entries := make([]volumetypes.RenameEntry, 0, len(volumes))
- for key, volumeConfig := range volumes {
+func collectProjectRenameVolumeEntriesInternal(ctx context.Context,
+ dockerClient *client.Client,
+ localVolumes map[string]composetypes.VolumeConfig,
+ explicitVolumeNames map[string]struct{},
+ oldComposeName,
+ newComposeName string) ([]volumetypes.RenameEntry,
+ error,
+) {
+ entries := make([]volumetypes.RenameEntry, 0, len(localVolumes))
+ for key, volumeConfig := range localVolumes {
entry, ok, err := inspectProjectRenameVolumeEntryInternal(ctx, dockerClient, key, volumeConfig, explicitVolumeNames, oldComposeName, newComposeName)
if err != nil {
return nil, err
@@ -65,7 +72,16 @@ func collectProjectRenameVolumeEntriesInternal(ctx context.Context, dockerClient
return entries, nil
}
-func inspectProjectRenameVolumeEntryInternal(ctx context.Context, dockerClient *client.Client, key string, volumeConfig composetypes.VolumeConfig, explicitVolumeNames map[string]struct{}, oldComposeName, newComposeName string) (volumetypes.RenameEntry, bool, error) {
+func inspectProjectRenameVolumeEntryInternal(ctx context.Context,
+ dockerClient *client.Client,
+ key string,
+ volumeConfig composetypes.VolumeConfig,
+ explicitVolumeNames map[string]struct{},
+ oldComposeName,
+ newComposeName string) (volumetypes.RenameEntry,
+ bool,
+ error,
+) {
if _, explicit := explicitVolumeNames[key]; explicit || bool(volumeConfig.External) {
return volumetypes.RenameEntry{}, false, nil
}
@@ -87,8 +103,8 @@ func inspectProjectRenameVolumeEntryInternal(ctx context.Context, dockerClient *
}
return volumetypes.RenameEntry{}, false, fmt.Errorf("inspect source volume %s: %w", oldName, err)
}
- if err := volumes.EnsureRenameSourceDetached(ctx, dockerClient, oldName); err != nil {
- return volumetypes.RenameEntry{}, false, err
+ if ensureRenameSourceDetachedErr := volumes.EnsureRenameSourceDetached(ctx, dockerClient, oldName); ensureRenameSourceDetachedErr != nil {
+ return volumetypes.RenameEntry{}, false, ensureRenameSourceDetachedErr
}
newConfig := buildProjectRenamedVolumeConfigInternal(volumeConfig, key, newName, newComposeName)
@@ -156,8 +172,8 @@ func composeVolumeKeysWithExplicitNameInFileInternal(path string) (map[string]st
}
composeData := map[string]any{}
- if err := yaml.Unmarshal(content, &composeData); err != nil {
- return nil, fmt.Errorf("parse compose file: %w", err)
+ if unmarshalErr := yaml.Unmarshal(content, &composeData); unmarshalErr != nil {
+ return nil, fmt.Errorf("parse compose file: %w", unmarshalErr)
}
rawVolumes, ok := composeData["volumes"]
@@ -165,27 +181,27 @@ func composeVolumeKeysWithExplicitNameInFileInternal(path string) (map[string]st
return map[string]struct{}{}, nil
}
- volumes, ok := rawVolumes.(map[string]any)
+ localVolumes, ok := rawVolumes.(map[string]any)
if !ok {
return nil, errors.New("parse compose file: volumes must be a mapping")
}
explicit := make(map[string]struct{})
- for key, rawVolume := range volumes {
+ for key, rawVolume := range localVolumes {
key = strings.TrimSpace(key)
if key == "" {
continue
}
- volumeConfig, ok := rawVolume.(map[string]any)
- if !ok {
+ volumeConfig, localOk := rawVolume.(map[string]any)
+ if !localOk {
continue
}
rawName, hasName := volumeConfig["name"]
if !hasName {
continue
}
- name, ok := rawName.(string)
- if ok && len(composetemplate.ExtractVariables(map[string]any{"name": name}, nil)) == 0 {
+ name, localOk := rawName.(string)
+ if localOk && len(composetemplate.ExtractVariables(map[string]any{"name": name}, nil)) == 0 {
explicit[key] = struct{}{}
}
}
@@ -193,7 +209,12 @@ func composeVolumeKeysWithExplicitNameInFileInternal(path string) (map[string]st
return explicit, nil
}
-func ApplyRenameVolumeMigration(ctx context.Context, operations projecttypes.RenameRecoveryOperations, volumeMigration volumetypes.Migration, renameJournal *projecttypes.RenameJournal, applied *bool) error {
+func ApplyRenameVolumeMigration(ctx context.Context,
+ operations projecttypes.RenameRecoveryOperations,
+ volumeMigration volumetypes.Migration,
+ renameJournal *projecttypes.RenameJournal,
+ applied *bool,
+) error {
if volumeMigration == nil {
return nil
}
@@ -204,7 +225,13 @@ func ApplyRenameVolumeMigration(ctx context.Context, operations projecttypes.Ren
return operations.WriteJournal(ctx, renameJournal, projecttypes.RenameJournalPhaseTargetsCopied)
}
-func FinalizeRenameAfterCommit(ctx context.Context, operations projecttypes.RenameRecoveryOperations, projectID string, volumeMigration volumetypes.Migration, renameJournal *projecttypes.RenameJournal, journalActive *bool) {
+func FinalizeRenameAfterCommit(ctx context.Context,
+ operations projecttypes.RenameRecoveryOperations,
+ projectID string,
+ volumeMigration volumetypes.Migration,
+ renameJournal *projecttypes.RenameJournal,
+ journalActive *bool,
+) {
if renameJournal != nil {
if err := operations.WriteJournal(ctx, renameJournal, projecttypes.RenameJournalPhaseProjectStateCommitted); err != nil {
slog.WarnContext(ctx, "failed to mark project rename journal committed", "projectID", projectID, "error", err)
@@ -214,14 +241,14 @@ func FinalizeRenameAfterCommit(ctx context.Context, operations projecttypes.Rena
if committer, ok := volumeMigration.(volumetypes.Committer); ok {
if err := committer.Commit(ctx); err != nil {
slog.WarnContext(ctx, "failed to clean up project source volumes after committed rename", "projectID", projectID, "error", err)
- if _, ok := errors.AsType[*volumetypes.SourceCleanupError](err); ok {
+ if _, localOk := errors.AsType[*volumetypes.SourceCleanupError](err); localOk {
if writeErr := operations.WriteJournal(ctx, renameJournal, projecttypes.RenameJournalPhaseSourceCleanupPending); writeErr != nil {
slog.WarnContext(ctx, "failed to mark project rename source cleanup pending", "projectID", projectID, "error", writeErr)
}
}
return
- } else if err := operations.WriteJournal(ctx, renameJournal, projecttypes.RenameJournalPhaseOldVolumesRemoved); err != nil {
- slog.WarnContext(ctx, "failed to mark old project rename volumes removed", "projectID", projectID, "error", err)
+ } else if writeJournalErr := operations.WriteJournal(ctx, renameJournal, projecttypes.RenameJournalPhaseOldVolumesRemoved); writeJournalErr != nil {
+ slog.WarnContext(ctx, "failed to mark old project rename volumes removed", "projectID", projectID, "error", writeJournalErr)
}
}
@@ -267,15 +294,29 @@ func cleanupRenameJournalSourcesInternal(ctx context.Context, operations project
return err
}
- if err := volumes.EnsureTargetsReadyForCleanup(ctx, dockerClient, journal.Volumes); err != nil {
- if missingWithSource, ok := errors.AsType[*volumetypes.TargetMissingWithSourceError](err); ok {
- slog.WarnContext(ctx, "rolling back project rename because target volume is missing and source volume remains", "projectID", journal.ProjectID, "sourceVolume", missingWithSource.SourceVolume, "targetVolume", missingWithSource.TargetVolume)
+ if ensureTargetsReadyForCleanupErr := volumes.EnsureTargetsReadyForCleanup(ctx, dockerClient, journal.Volumes); ensureTargetsReadyForCleanupErr != nil {
+ if missingWithSource, ok := errors.AsType[*volumetypes.TargetMissingWithSourceError](ensureTargetsReadyForCleanupErr); ok {
+ slog.WarnContext(ctx,
+ "rolling back project rename because target volume is missing and source volume remains",
+ "projectID",
+ journal.ProjectID,
+ "sourceVolume",
+ missingWithSource.SourceVolume,
+ "targetVolume",
+ missingWithSource.TargetVolume)
return rollbackRenameJournalInternal(ctx, operations, journal)
}
- if externallyRemoved, ok := errors.AsType[*volumetypes.VolumesExternallyRemovedError](err); ok {
- slog.WarnContext(ctx, "project rename cleanup found source and target volumes externally removed", "projectID", journal.ProjectID, "volumeCount", len(externallyRemoved.Volumes), "error", externallyRemoved)
+ if externallyRemoved, ok := errors.AsType[*volumetypes.VolumesExternallyRemovedError](ensureTargetsReadyForCleanupErr); ok {
+ slog.WarnContext(ctx,
+ "project rename cleanup found source and target volumes externally removed",
+ "projectID",
+ journal.ProjectID,
+ "volumeCount",
+ len(externallyRemoved.Volumes),
+ "error",
+ externallyRemoved)
} else {
- return err
+ return ensureTargetsReadyForCleanupErr
}
}
@@ -292,7 +333,14 @@ func rollbackRenameJournalInternal(ctx context.Context, operations projecttypes.
}
if directoryErr != nil {
- slog.WarnContext(ctx, "keeping project rename journal after restoring database state because directory rollback failed", "projectID", journal.ProjectID, "pathsMissing", pathsMissing, "error", directoryErr)
+ slog.WarnContext(ctx,
+ "keeping project rename journal after restoring database state because directory rollback failed",
+ "projectID",
+ journal.ProjectID,
+ "pathsMissing",
+ pathsMissing,
+ "error",
+ directoryErr)
}
if volumeErr != nil {
@@ -302,7 +350,14 @@ func rollbackRenameJournalInternal(ctx context.Context, operations projecttypes.
if cleanupErr := operations.WriteRollbackCleanup(ctx, journal); cleanupErr != nil {
return errors.Join(directoryErr, volumeErr, cleanupErr)
}
- slog.WarnContext(ctx, "queued project rename target volume cleanup after restoring database state despite volume rollback failure", "projectID", journal.ProjectID, "pathsMissing", pathsMissing, "error", volumeErr)
+ slog.WarnContext(ctx,
+ "queued project rename target volume cleanup after restoring database state despite volume rollback failure",
+ "projectID",
+ journal.ProjectID,
+ "pathsMissing",
+ pathsMissing,
+ "error",
+ volumeErr)
}
}
@@ -356,12 +411,12 @@ func CleanupRenameRollbackTargets(ctx context.Context, cleanup *projecttypes.Ren
return err
}
- if err := volumes.CleanupRollbackTargetVolumes(ctx, dockerClient, cleanup.Volumes); err != nil {
- if volumes.OnlyPreservedTargetErrors(err) {
- slog.WarnContext(ctx, "clearing project rename rollback cleanup after preserving target volume data", "projectID", cleanup.ProjectID, "error", err)
+ if cleanupRollbackTargetVolumesErr := volumes.CleanupRollbackTargetVolumes(ctx, dockerClient, cleanup.Volumes); cleanupRollbackTargetVolumesErr != nil {
+ if volumes.OnlyPreservedTargetErrors(cleanupRollbackTargetVolumesErr) {
+ slog.WarnContext(ctx, "clearing project rename rollback cleanup after preserving target volume data", "projectID", cleanup.ProjectID, "error", cleanupRollbackTargetVolumesErr)
return operations.ClearRollbackCleanup(ctx, cleanup.ProjectID)
}
- return err
+ return cleanupRollbackTargetVolumesErr
}
dockerutil.InvalidateVolumeUsageCache(dockerClient)
diff --git a/backend/pkg/projects/workspace.go b/backend/pkg/projects/workspace.go
index 8ea5e557e..2782e27be 100644
--- a/backend/pkg/projects/workspace.go
+++ b/backend/pkg/projects/workspace.go
@@ -83,8 +83,8 @@ func ReadProjectWorkspace(projectPath string, maxDepth int, skipDirectories, com
revisionHash: sha256.New(),
}
- if err := fs.WalkDir(root.FS(), ".", walker.visit); err != nil {
- return nil, "", false, err
+ if walkDirErr := fs.WalkDir(root.FS(), ".", walker.visit); walkDirErr != nil {
+ return nil, "", false, walkDirErr
}
slices.SortFunc(walker.files, func(a, b workspacetypes.FileEntry) int {
@@ -202,7 +202,7 @@ func (w *projectWorkspaceTreeWalkerInternal) visit(rel string, entry fs.DirEntry
workspaceEntry.Editable = true
case "symlink":
workspaceEntry.ReadOnlyReason = workspacetypes.FileReadOnlySymlink
- if target, err := os.Readlink(workspaceEntry.Path); err == nil {
+ if target, readlinkErr := os.Readlink(workspaceEntry.Path); readlinkErr == nil {
workspaceEntry.LinkTarget = target
}
case "special":
@@ -266,8 +266,8 @@ func ApplyProjectWorkspaceChanges(projectPath string, changes []project.Workspac
// Recomputed per change: an earlier change may have removed a directory
// that shadowed a protected name.
protected := ProtectedProjectPaths(projectPath, opts.ComposeFileName)
- if err := applyWorkspaceFileChangeInternal(root, protected, change, uploads, opts.MaxFileSizeBytes); err != nil {
- return err
+ if applyWorkspaceFileChangeErr := applyWorkspaceFileChangeInternal(root, protected, change, uploads, opts.MaxFileSizeBytes); applyWorkspaceFileChangeErr != nil {
+ return applyWorkspaceFileChangeErr
}
}
@@ -323,9 +323,9 @@ func applyWorkspaceFileChangeInternal(root *os.Root, protected map[string]bool,
}
return updateProjectWorkspaceFileInternal(root, protected, rel, uploads[*change.UploadIndex], baseline, change.BaselineIndex != nil, maxFileSizeBytes)
case project.FileOpRename:
- newName, err := kit.ValidateFileName(change.NewName)
- if err != nil {
- return fmt.Errorf("invalid project workspace file name: %w", err)
+ newName, validateFileNameErr := kit.ValidateFileName(change.NewName)
+ if validateFileNameErr != nil {
+ return fmt.Errorf("invalid project workspace file name: %w", validateFileNameErr)
}
return renameProjectWorkspacePathInternal(root, protected, rel, newName)
case project.FileOpMove:
@@ -423,17 +423,17 @@ func updateProjectWorkspaceFileInternal(root *os.Root, protected map[string]bool
// comparison targets the right path. The read is capped just past the
// baseline length: a longer on-disk file differs by definition.
if baselineSet {
- current, err := readProjectWorkspaceFileLimitedInternal(root, rel, int64(len(baseline))+1)
- if err != nil {
- return fmt.Errorf("read project workspace file: %w", err)
+ current, readProjectWorkspaceFileLimitedErr := readProjectWorkspaceFileLimitedInternal(root, rel, int64(len(baseline))+1)
+ if readProjectWorkspaceFileLimitedErr != nil {
+ return fmt.Errorf("read project workspace file: %w", readProjectWorkspaceFileLimitedErr)
}
if !bytes.Equal(current, baseline) {
return fmt.Errorf("file content changed since it was loaded: %w", ErrProjectWorkspaceRevisionConflict)
}
}
- if err := root.WriteFile(rel, content, utils.FilePerm); err != nil {
- return fmt.Errorf("update project workspace file: %w", err)
+ if writeFileErr := root.WriteFile(rel, content, utils.FilePerm); writeFileErr != nil {
+ return fmt.Errorf("update project workspace file: %w", writeFileErr)
}
return nil
}
@@ -467,20 +467,20 @@ func renameProjectWorkspacePathInternal(root *os.Root, protected map[string]bool
}
targetRel := path.Join(path.Dir(rel), newName)
- if err := ensureWritableProjectRelPathInternal(protected, targetRel); err != nil {
- return err
+ if ensureWritableProjectRelPathErr := ensureWritableProjectRelPathInternal(protected, targetRel); ensureWritableProjectRelPathErr != nil {
+ return ensureWritableProjectRelPathErr
}
- if err := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(targetRel)); err != nil {
- return err
+ if ensureProjectPathHasNoSymlinkErr := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(targetRel)); ensureProjectPathHasNoSymlinkErr != nil {
+ return ensureProjectPathHasNoSymlinkErr
}
- if _, err := root.Lstat(targetRel); err == nil {
+ if _, lstatErr := root.Lstat(targetRel); lstatErr == nil {
return fmt.Errorf("project workspace path already exists: %s", targetRel)
- } else if !errors.Is(err, os.ErrNotExist) {
- return fmt.Errorf("inspect project workspace path: %w", err)
+ } else if !errors.Is(lstatErr, os.ErrNotExist) {
+ return fmt.Errorf("inspect project workspace path: %w", lstatErr)
}
- if err := root.Rename(rel, targetRel); err != nil {
- return fmt.Errorf("rename project workspace path: %w", err)
+ if renameErr := root.Rename(rel, targetRel); renameErr != nil {
+ return fmt.Errorf("rename project workspace path: %w", renameErr)
}
return nil
}
@@ -505,8 +505,8 @@ func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool,
return fmt.Errorf("invalid project workspace parent path: %w", err)
}
if parentRel != "" {
- if err := ensureWritableProjectRelPathInternal(protected, parentRel); err != nil {
- return err
+ if ensureWritableProjectRelPathErr := ensureWritableProjectRelPathInternal(protected, parentRel); ensureWritableProjectRelPathErr != nil {
+ return ensureWritableProjectRelPathErr
}
}
@@ -524,8 +524,8 @@ func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool,
return errors.New("folder cannot be moved into itself or a descendant")
}
- if err := validateProjectMoveParentInternal(root, parentRel); err != nil {
- return err
+ if validateProjectMoveParentErr := validateProjectMoveParentInternal(root, parentRel); validateProjectMoveParentErr != nil {
+ return validateProjectMoveParentErr
}
targetRel := path.Base(rel)
@@ -535,20 +535,20 @@ func moveProjectWorkspacePathInternal(root *os.Root, protected map[string]bool,
if targetRel == rel {
return errors.New("project workspace path is already in the destination folder")
}
- if err := ensureWritableProjectRelPathInternal(protected, targetRel); err != nil {
- return err
+ if ensureWritableProjectRelPathErr2 := ensureWritableProjectRelPathInternal(protected, targetRel); ensureWritableProjectRelPathErr2 != nil {
+ return ensureWritableProjectRelPathErr2
}
- if err := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(targetRel)); err != nil {
- return err
+ if ensureProjectPathHasNoSymlinkErr := ensureProjectPathHasNoSymlinkInternal(root, path.Dir(targetRel)); ensureProjectPathHasNoSymlinkErr != nil {
+ return ensureProjectPathHasNoSymlinkErr
}
- if _, err := root.Lstat(targetRel); err == nil {
+ if _, lstatErr := root.Lstat(targetRel); lstatErr == nil {
return fmt.Errorf("project workspace path already exists: %s", targetRel)
- } else if !errors.Is(err, os.ErrNotExist) {
- return fmt.Errorf("inspect project workspace path: %w", err)
+ } else if !errors.Is(lstatErr, os.ErrNotExist) {
+ return fmt.Errorf("inspect project workspace path: %w", lstatErr)
}
- if err := root.Rename(rel, targetRel); err != nil {
- return fmt.Errorf("move project workspace path: %w", err)
+ if renameErr := root.Rename(rel, targetRel); renameErr != nil {
+ return fmt.Errorf("move project workspace path: %w", renameErr)
}
return nil
}
@@ -596,9 +596,9 @@ func deleteProjectWorkspacePathInternal(root *os.Root, protected map[string]bool
return fmt.Errorf("symlink paths are not supported: %w", ErrProjectWorkspaceSymlinkPath)
}
if info.IsDir() && !recursive {
- empty, err := isDirectoryEmptyInternal(root, rel)
- if err != nil {
- return err
+ empty, isDirectoryEmptyErr := isDirectoryEmptyInternal(root, rel)
+ if isDirectoryEmptyErr != nil {
+ return isDirectoryEmptyErr
}
if !empty {
return errors.New("folder is not empty")
@@ -606,13 +606,13 @@ func deleteProjectWorkspacePathInternal(root *os.Root, protected map[string]bool
}
if info.IsDir() {
- if err := root.RemoveAll(rel); err != nil {
- return fmt.Errorf("delete project workspace folder: %w", err)
+ if removeAllErr := root.RemoveAll(rel); removeAllErr != nil {
+ return fmt.Errorf("delete project workspace folder: %w", removeAllErr)
}
return nil
}
- if err := root.Remove(rel); err != nil {
- return fmt.Errorf("delete project workspace file: %w", err)
+ if removeErr := root.Remove(rel); removeErr != nil {
+ return fmt.Errorf("delete project workspace file: %w", removeErr)
}
return nil
}
diff --git a/backend/pkg/projects/workspace_test.go b/backend/pkg/projects/workspace_test.go
index d169cd4dd..d4d5f7143 100644
--- a/backend/pkg/projects/workspace_test.go
+++ b/backend/pkg/projects/workspace_test.go
@@ -4,7 +4,6 @@ import (
"fmt"
"os"
"path/filepath"
- "strings"
"testing"
"github.com/getarcaneapp/arcane/types/v2/project"
@@ -166,8 +165,8 @@ func TestApplyWorkspaceFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {
targetPath := filepath.Join(projectDir, "target.txt")
linkPath := filepath.Join(projectDir, "link.txt")
require.NoError(t, os.WriteFile(targetPath, []byte("target\n"), 0o644))
- if err := os.Symlink(targetPath, linkPath); err != nil {
- t.Skipf("symlink creation is unavailable: %v", err)
+ if symlinkErr := os.Symlink(targetPath, linkPath); symlinkErr != nil {
+ t.Skipf("symlink creation is unavailable: %v", symlinkErr)
}
content := []byte("updated\n")
@@ -180,8 +179,8 @@ func TestApplyWorkspaceFileChanges_WrapsForbiddenSentinelErrors(t *testing.T) {
outsideDir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(outsideDir, "outside.txt"), []byte("outside\n"), 0o644))
linkDirPath := filepath.Join(projectDir, "link-dir")
- if err := os.Symlink(outsideDir, linkDirPath); err != nil {
- t.Skipf("symlink creation is unavailable: %v", err)
+ if symlinkErr2 := os.Symlink(outsideDir, linkDirPath); symlinkErr2 != nil {
+ t.Skipf("symlink creation is unavailable: %v", symlinkErr2)
}
err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{
@@ -342,7 +341,7 @@ func TestApplyProjectWorkspaceChangesRejectsUnusedUploadsForEmptyManifest(t *tes
func TestValidateProjectWorkspaceFileName_RejectsPathSeparators(t *testing.T) {
t.Parallel()
- _, err := kit.ValidateFileName(strings.Join([]string{"folder", "name"}, string(filepath.Separator)))
+ _, err := kit.ValidateFileName("folder" + string(filepath.Separator) + "name")
require.Error(t, err)
}
@@ -448,7 +447,14 @@ func TestApplyProjectWorkspaceChanges_BaselineGuardsConcurrentEdit(t *testing.T)
// A baseline matching the current on-disk content saves normally.
err = ApplyProjectWorkspaceChanges(projectDir, []project.WorkspaceFileChange{
{Operation: project.FileOpUpdateFile, RelativePath: "config.txt", UploadIndex: new(0), BaselineIndex: new(1)},
- }, map[int][]byte{0: []byte("fresh draft\n"), 1: []byte("external newer edit\n")}, ProjectWorkspaceApplyOptions{ComposeFileName: "compose.yaml", ExpectedRevision: revision, MaxDepth: 3})
+ }, map[int][]byte{
+ 0: []byte("fresh draft\n"),
+ 1: []byte("external newer edit\n"),
+ }, ProjectWorkspaceApplyOptions{
+ ComposeFileName: "compose.yaml",
+ ExpectedRevision: revision,
+ MaxDepth: 3,
+ })
require.NoError(t, err)
content, err = os.ReadFile(filepath.Join(projectDir, "config.txt"))
require.NoError(t, err)
diff --git a/backend/pkg/remenv/client_test.go b/backend/pkg/remenv/client_test.go
index 15dabe4d6..ec88b1a5c 100644
--- a/backend/pkg/remenv/client_test.go
+++ b/backend/pkg/remenv/client_test.go
@@ -56,7 +56,7 @@ func TestClientDo_DirectHTTPSuccess(t *testing.T) {
defer server.Close()
client := NewClient(server.Client(), nil)
- resp, err := client.Do(context.Background(), Request{
+ resp, err := client.Do(t.Context(), Request{
Method: http.MethodPost,
URL: server.URL + "/api/registries/sync",
Path: "/api/registries/sync",
@@ -89,7 +89,7 @@ func TestClientDo_EdgeUsesTunnelTransport(t *testing.T) {
},
})
- resp, err := client.Do(context.Background(), Request{
+ resp, err := client.Do(t.Context(), Request{
EnvironmentID: "env-edge-1",
IsEdge: true,
Method: http.MethodGet,
@@ -108,7 +108,7 @@ func TestClientDo_WrapsTransportErrors(t *testing.T) {
},
})
- _, err := client.Do(context.Background(), Request{
+ _, err := client.Do(t.Context(), Request{
EnvironmentID: "env-edge-2",
IsEdge: true,
Method: http.MethodGet,
diff --git a/backend/pkg/scheduler/actor_test.go b/backend/pkg/scheduler/actor_test.go
index d0c3f3fad..d44eb45be 100644
--- a/backend/pkg/scheduler/actor_test.go
+++ b/backend/pkg/scheduler/actor_test.go
@@ -31,7 +31,12 @@ func newTestAdmissionGateInternal(t *testing.T) *runs.Admission {
return admission
}
-func newTestCoordinatorInternal(t testing.TB, ctx context.Context, location *time.Location, execute func(context.Context, schedulertypes.Run) (schedulertypes.Outcome, error)) (*runs.Coordinator, *francis.Runtime) {
+func newTestCoordinatorInternal(t testing.TB,
+ ctx context.Context,
+ location *time.Location,
+ execute func(context.Context,
+ schedulertypes.Run) (schedulertypes.Outcome, error),
+) (*runs.Coordinator, *francis.Runtime) {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
@@ -45,10 +50,10 @@ func newTestCoordinatorInternal(t testing.TB, ctx context.Context, location *tim
coordinator.SetExecutor(execute, nil)
require.NoError(t, coordinator.Register(runtime))
require.NoError(t, runtime.Start(t.Context(), ctx, nil))
- t.Cleanup(func() { require.NoError(t, runtime.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, runtime.Stop(context.WithoutCancel(t.Context()))) })
require.NoError(t, coordinator.Start(t.Context(), ctx))
coordinator.Activate()
- t.Cleanup(func() { require.NoError(t, coordinator.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, coordinator.Stop(context.WithoutCancel(t.Context()))) })
return coordinator, runtime
}
@@ -67,7 +72,7 @@ func newJobSchedulerForTestInternal(t testing.TB, ctx context.Context, location
scheduler = created.(*jobSchedulerInternal)
schedulerTestRuntimesInternal.Store(scheduler, runtime)
t.Cleanup(func() {
- require.NoError(t, scheduler.Stop(context.Background()))
+ require.NoError(t, scheduler.Stop(context.WithoutCancel(t.Context())))
schedulerTestRuntimesInternal.Delete(scheduler)
})
return scheduler
@@ -88,7 +93,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
t.Helper()
svc, err := settings.NewSettingsService(ctx, db)
if err == nil {
- t.Cleanup(func() { require.NoError(t, svc.Stop(context.Background())) })
+ t.Cleanup(func() { require.NoError(t, svc.Stop(context.WithoutCancel(t.Context()))) })
}
return svc, err
}
diff --git a/backend/pkg/scheduler/analytics_job.go b/backend/pkg/scheduler/analytics_job.go
index 8c91dd122..7dc3eb1e6 100644
--- a/backend/pkg/scheduler/analytics_job.go
+++ b/backend/pkg/scheduler/analytics_job.go
@@ -129,15 +129,15 @@ func (j *AnalyticsJob) Run(ctx context.Context) (schedulertypes.Outcome, error)
reqCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
- req, err := http.NewRequestWithContext(reqCtx, http.MethodPost, j.heartbeatURL, bytes.NewReader(body))
- if err != nil {
- return struct{}{}, fmt.Errorf("failed to create request: %w", err)
+ req, newRequestWithContextErr := http.NewRequestWithContext(reqCtx, http.MethodPost, j.heartbeatURL, bytes.NewReader(body))
+ if newRequestWithContextErr != nil {
+ return struct{}{}, fmt.Errorf("failed to create request: %w", newRequestWithContextErr)
}
req.Header.Set("Content-Type", "application/json")
- resp, err := j.httpClient.Do(req)
- if err != nil {
- return struct{}{}, fmt.Errorf("failed to send request: %w", err)
+ resp, newRequestWithContextErr := j.httpClient.Do(req)
+ if newRequestWithContextErr != nil {
+ return struct{}{}, fmt.Errorf("failed to send request: %w", newRequestWithContextErr)
}
defer func() { _ = resp.Body.Close() }()
@@ -242,8 +242,8 @@ func (j *AnalyticsJob) claimHeartbeatAttemptWindowInternal(ctx context.Context)
// Persist the attempt window before sending on purpose: the product behavior is
// best-effort at-most-once-per-24h check-ins, which avoids duplicate heartbeats
// after restarts or partially completed outbound requests.
- if err := j.kvService.Set(ctx, analyticsHeartbeatLastAttemptKey, now.Format(time.RFC3339Nano)); err != nil {
- return false, fmt.Errorf("failed to persist analytics heartbeat attempt state: %w", err)
+ if setErr := j.kvService.Set(ctx, analyticsHeartbeatLastAttemptKey, now.Format(time.RFC3339Nano)); setErr != nil {
+ return false, fmt.Errorf("failed to persist analytics heartbeat attempt state: %w", setErr)
}
return true, nil
diff --git a/backend/pkg/scheduler/analytics_job_test.go b/backend/pkg/scheduler/analytics_job_test.go
index 1f9b7d8cc..67f40874f 100644
--- a/backend/pkg/scheduler/analytics_job_test.go
+++ b/backend/pkg/scheduler/analytics_job_test.go
@@ -1,7 +1,6 @@
package scheduler
import (
- "context"
"encoding/json"
"io"
"net/http"
@@ -24,7 +23,7 @@ import (
func setupAnalyticsStateServicesInternal(t *testing.T) (*database.DB, *settings.SettingsService, *kv.KVService) {
t.Helper()
- ctx := context.Background()
+ ctx := t.Context()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))
@@ -58,7 +57,7 @@ func newHeartbeatServer(t *testing.T) (*httptest.Server, <-chan []byte, *atomic.
}
func TestAnalyticsJob_Run_ManagerPayload(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
server, bodyCh, _ := newHeartbeatServer(t)
defer server.Close()
@@ -86,7 +85,7 @@ func TestAnalyticsJob_Run_ManagerPayload(t *testing.T) {
}
func TestAnalyticsJob_Run_AgentPayload(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
server, bodyCh, _ := newHeartbeatServer(t)
defer server.Close()
@@ -112,7 +111,7 @@ func TestAnalyticsJob_Run_AgentPayload(t *testing.T) {
}
func TestAnalyticsJob_Run_SkipsWhenDisabled(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
server, bodyCh, _ := newHeartbeatServer(t)
defer server.Close()
@@ -133,7 +132,7 @@ func TestAnalyticsJob_Run_SkipsWhenDisabled(t *testing.T) {
}
func TestAnalyticsJob_Run_SkipsWhenTestEnv(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
server, bodyCh, _ := newHeartbeatServer(t)
defer server.Close()
@@ -154,7 +153,7 @@ func TestAnalyticsJob_Run_SkipsWhenTestEnv(t *testing.T) {
}
func TestAnalyticsJob_Run_SkipsWithinHeartbeatWindowAfterRestart(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
wrappedDB, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
server, _, requestCount := newHeartbeatServer(t)
defer server.Close()
@@ -174,7 +173,7 @@ func TestAnalyticsJob_Run_SkipsWithinHeartbeatWindowAfterRestart(t *testing.T) {
restartedJob := NewAnalyticsJob(reloadedSettingsService, kv.NewKVService(wrappedDB), server.Client(), cfg)
restartedJob.heartbeatURL = server.URL
restartedJob.now = func() time.Time { return firstAttemptAt.Add(19 * time.Minute) }
- if _, err := restartedJob.Run(ctx); !assert.NoError(t, err) {
+ if _, runErr := restartedJob.Run(ctx); !assert.NoError(t, runErr) {
return
}
@@ -182,7 +181,7 @@ func TestAnalyticsJob_Run_SkipsWithinHeartbeatWindowAfterRestart(t *testing.T) {
}
func TestAnalyticsJob_Run_AllowsSendAfterHeartbeatWindow(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
server, _, requestCount := newHeartbeatServer(t)
defer server.Close()
@@ -208,7 +207,7 @@ func TestAnalyticsJob_Run_AllowsSendAfterHeartbeatWindow(t *testing.T) {
}
func TestAnalyticsJob_Run_ConcurrentRunsSendOnce(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
server, _, requestCount := newHeartbeatServer(t)
defer server.Close()
@@ -241,5 +240,5 @@ func TestAnalyticsJob_Schedule_UsesFixedHourlyCheck(t *testing.T) {
_, settingsService, kvService := setupAnalyticsStateServicesInternal(t)
job := NewAnalyticsJob(settingsService, kvService, nil, &config.Config{Environment: config.AppEnvironmentProduction})
- require.Equal(t, analyticsHeartbeatCheckSchedule, job.Schedule(context.Background()))
+ require.Equal(t, analyticsHeartbeatCheckSchedule, job.Schedule(t.Context()))
}
diff --git a/backend/pkg/scheduler/auto_heal_job.go b/backend/pkg/scheduler/auto_heal_job.go
index e6d009201..3e0af26b7 100644
--- a/backend/pkg/scheduler/auto_heal_job.go
+++ b/backend/pkg/scheduler/auto_heal_job.go
@@ -157,8 +157,8 @@ func (j *AutoHealJob) Run(ctx context.Context) (schedulertypes.Outcome, error) {
if err != nil {
return schedulertypes.Outcome{}, err
}
- if err := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "heal_plan", ID: "auto-heal-plan", Status: schedulertypes.Succeeded, RecoveryData: frozen}); err != nil {
- return schedulertypes.Outcome{}, err
+ if progressErr := jobcontext.Progress(ctx, schedulertypes.TargetOutcome{ResourceType: "heal_plan", ID: "auto-heal-plan", Status: schedulertypes.Succeeded, RecoveryData: frozen}); progressErr != nil {
+ return schedulertypes.Outcome{}, progressErr
}
g, groupCtx := errgroup.WithContext(ctx)
@@ -170,10 +170,10 @@ func (j *AutoHealJob) Run(ctx context.Context) (schedulertypes.Outcome, error) {
g.Go(func() (workerErr error) {
defer utils.RecoverToError(&workerErr, "auto-heal worker")
- target, err := j.processCandidateInternal(groupCtx, dockerClient, candidate, maxRestarts, restartWindow, restartWindowMinutes)
+ target, processCandidateErr := j.processCandidateInternal(groupCtx, dockerClient, candidate, maxRestarts, restartWindow, restartWindowMinutes)
resultMu.Lock()
outcome.Targets = append(outcome.Targets, target)
- if err != nil {
+ if processCandidateErr != nil {
outcome.Status = schedulertypes.Partial
}
resultMu.Unlock()
@@ -289,16 +289,16 @@ func (j *AutoHealJob) processCandidateInternal(
}
target.RecoveryData = baseline
target.Status = schedulertypes.Running
- if err := jobcontext.Progress(ctx, target); err != nil {
+ if progressErr := jobcontext.Progress(ctx, target); progressErr != nil {
releaseSlot()
- return target, err
+ return target, progressErr
}
- if err := j.restartContainerInternal(ctx, dockerClient, containerID); err != nil {
+ if restartContainerErr := j.restartContainerInternal(ctx, dockerClient, containerID); restartContainerErr != nil {
releaseSlot()
- slog.ErrorContext(ctx, "auto-heal failed to restart container", "container", containerName, "error", err)
+ slog.ErrorContext(ctx, "auto-heal failed to restart container", "container", containerName, "error", restartContainerErr)
target.Status = schedulertypes.Failed
- target.Message = err.Error()
- return target, err
+ target.Message = restartContainerErr.Error()
+ return target, restartContainerErr
}
j.postRestartActionsInternal(ctx, containerID, containerName)
@@ -552,8 +552,8 @@ func (j *AutoHealJob) Reconcile(ctx context.Context, previous schedulertypes.Run
planned := false
for _, target := range previous.Outcome.Targets {
if target.ID == "auto-heal-plan" && len(target.RecoveryData) > 0 {
- if err := json.Unmarshal(target.RecoveryData, &plan); err != nil {
- return schedulertypes.Outcome{}, err
+ if unmarshalErr := json.Unmarshal(target.RecoveryData, &plan); unmarshalErr != nil {
+ return schedulertypes.Outcome{}, unmarshalErr
}
planned = true
break
diff --git a/backend/pkg/scheduler/auto_heal_job_test.go b/backend/pkg/scheduler/auto_heal_job_test.go
index 896efa7f4..e7396c580 100644
--- a/backend/pkg/scheduler/auto_heal_job_test.go
+++ b/backend/pkg/scheduler/auto_heal_job_test.go
@@ -137,7 +137,7 @@ func TestAutoHeal_Schedule_Default(t *testing.T) {
}
func TestAutoHeal_ShouldSchedule(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsSvc, _ := setupAnalyticsStateServicesInternal(t)
job, err := NewAutoHealJob(nil, settingsSvc, nil, nil, newTestAdmissionGateInternal(t))
require.NoError(t, err)
@@ -165,7 +165,7 @@ func TestAutoHeal_ResetRestartTracking(t *testing.T) {
}
func TestAutoHeal_Run_UsesBoundedConcurrency(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
@@ -221,7 +221,8 @@ func TestAutoHeal_Run_UsesBoundedConcurrency(t *testing.T) {
return nil
}
- job.Run(ctx)
+ _, runErr1 := job.Run(ctx)
+ require.NoError(t, runErr1)
require.Greater(t, maxConcurrent.Load(), int32(1))
require.LessOrEqual(t, maxConcurrent.Load(), int32(autoHealInspectConcurrency))
@@ -229,7 +230,7 @@ func TestAutoHeal_Run_UsesBoundedConcurrency(t *testing.T) {
}
func TestAutoHealJob_OverlappingRunIsSkippedInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsSvc, _ := setupAnalyticsStateServicesInternal(t)
require.NoError(t, settingsSvc.SetBoolSetting(ctx, "autoHealEnabled", true))
@@ -251,12 +252,18 @@ func TestAutoHealJob_OverlappingRunIsSkippedInternal(t *testing.T) {
firstDone := make(chan struct{})
go func() {
- job.Run(ctx)
+ _, runErr2 := job.Run(ctx)
+ if runErr2 != nil {
+ t.Errorf("first auto heal job run failed: %v", runErr2)
+ close(firstDone)
+ return
+ }
close(firstDone)
}()
<-started
- job.Run(ctx)
+ _, runErr3 := job.Run(ctx)
+ require.NoError(t, runErr3)
require.Equal(t, int32(1), calls.Load())
close(release)
diff --git a/backend/pkg/scheduler/auto_update_job.go b/backend/pkg/scheduler/auto_update_job.go
index 13805d4b1..e77612ba2 100644
--- a/backend/pkg/scheduler/auto_update_job.go
+++ b/backend/pkg/scheduler/auto_update_job.go
@@ -163,10 +163,24 @@ func autoUpdateRetryOptionsInternal(previous schedulertypes.Run) (updatertypes.O
if unresolvedTargets {
return options, schedulertypes.Outcome{Status: schedulertypes.Failed, Message: "Remaining targets have no confirmed completion or safe retry", Targets: previous.Outcome.Targets}, true
}
- return options, schedulertypes.Outcome{Status: schedulertypes.Failed, Message: "Target results do not confirm full-batch completion", ActivityID: previous.Outcome.ActivityID, Targets: previous.Outcome.Targets}, true
+ return options,
+ schedulertypes.Outcome{
+ Status: schedulertypes.Failed,
+ Message: "Target results do not confirm full-batch completion",
+ ActivityID: previous.Outcome.ActivityID,
+ Targets: previous.Outcome.Targets,
+ },
+ true
}
if !hasResourceTargets {
- return options, schedulertypes.Outcome{Status: schedulertypes.Failed, Message: "The previous update has no confirmed retry targets", ActivityID: previous.Outcome.ActivityID, Targets: previous.Outcome.Targets}, true
+ return options,
+ schedulertypes.Outcome{
+ Status: schedulertypes.Failed,
+ Message: "The previous update has no confirmed retry targets",
+ ActivityID: previous.Outcome.ActivityID,
+ Targets: previous.Outcome.Targets,
+ },
+ true
}
if len(options.ResourceIds) > 0 {
options.Type = "container"
diff --git a/backend/pkg/scheduler/auto_update_job_test.go b/backend/pkg/scheduler/auto_update_job_test.go
index c9125998e..7fae0cc42 100644
--- a/backend/pkg/scheduler/auto_update_job_test.go
+++ b/backend/pkg/scheduler/auto_update_job_test.go
@@ -14,7 +14,7 @@ import (
)
func TestAutoUpdateJob_ShouldSchedule_RequiresAutoUpdateAndPolling(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsSvc, _ := setupAnalyticsStateServicesInternal(t)
job, err := NewAutoUpdateJob(nil, settingsSvc, newTestAdmissionGateInternal(t))
require.NoError(t, err)
@@ -48,7 +48,7 @@ func (f *blockingApplierFakeInternal) ApplyPending(context.Context, updater.Opti
}
func TestAutoUpdateJob_OverlappingRunIsSkippedInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
_, settingsSvc, _ := setupAnalyticsStateServicesInternal(t)
require.NoError(t, settingsSvc.SetBoolSetting(ctx, "autoUpdate", true))
@@ -60,13 +60,19 @@ func TestAutoUpdateJob_OverlappingRunIsSkippedInternal(t *testing.T) {
firstDone := make(chan struct{})
go func() {
- job.Run(ctx)
+ _, runErr1 := job.Run(ctx)
+ if runErr1 != nil {
+ t.Errorf("first auto update job run failed: %v", runErr1)
+ close(firstDone)
+ return
+ }
close(firstDone)
}()
<-applier.started
// Overlapping tick returns immediately without a second ApplyPending.
- job.Run(ctx)
+ _, runErr2 := job.Run(ctx)
+ require.NoError(t, runErr2)
require.Equal(t, int32(1), applier.calls.Load())
close(applier.release)
@@ -77,7 +83,8 @@ func TestAutoUpdateJob_OverlappingRunIsSkippedInternal(t *testing.T) {
}
// The guard resets once the run finishes.
- job.Run(ctx)
+ _, runErr3 := job.Run(ctx)
+ require.NoError(t, runErr3)
require.Equal(t, int32(2), applier.calls.Load())
for _, tc := range []struct {
name string
@@ -87,11 +94,80 @@ func TestAutoUpdateJob_OverlappingRunIsSkippedInternal(t *testing.T) {
unresolved bool
}{
{name: "missing progress", unresolved: true, status: schedulertypes.Failed},
- {name: "image pull alone", unresolved: true, targets: []schedulertypes.TargetOutcome{{ID: "image", ResourceType: "image", Status: schedulertypes.Succeeded}}, status: schedulertypes.Failed},
- {name: "failed containers only", unresolved: true, targets: []schedulertypes.TargetOutcome{{ID: "done", ResourceType: "container", Status: schedulertypes.Succeeded}, {ID: "failed", ResourceType: "container", Status: schedulertypes.Failed}, {ID: "image", ResourceType: "image", Status: schedulertypes.Failed}}, retryIDs: []string{"failed"}},
- {name: "completed failed batch retry", targets: []schedulertypes.TargetOutcome{{ID: "auto-update", ResourceType: "update-batch", Status: schedulertypes.Partial}, {ID: "failed", ResourceType: "container", Status: schedulertypes.Failed}}, retryIDs: []string{"failed"}},
- {name: "scoped retry cannot confirm original batch", targets: []schedulertypes.TargetOutcome{{ID: "auto-update", ResourceType: "update-retry", Status: schedulertypes.Succeeded}, {ID: "done", ResourceType: "container", Status: schedulertypes.Succeeded}}, status: schedulertypes.Failed, unresolved: true},
- {name: "completed batch", targets: []schedulertypes.TargetOutcome{{ID: "auto-update", ResourceType: "update-batch", Status: schedulertypes.Succeeded}}, status: schedulertypes.Succeeded},
+ {
+ name: "image pull alone",
+ unresolved: true,
+ targets: []schedulertypes.TargetOutcome{{
+ ID: "image",
+ ResourceType: "image",
+ Status: schedulertypes.Succeeded,
+ }},
+ status: schedulertypes.Failed,
+ },
+ {
+ name: "failed containers only",
+ unresolved: true,
+ targets: []schedulertypes.TargetOutcome{
+ {
+ ID: "done",
+ ResourceType: "container",
+ Status: schedulertypes.Succeeded,
+ },
+ {
+ ID: "failed",
+ ResourceType: "container",
+ Status: schedulertypes.Failed,
+ },
+ {
+ ID: "image",
+ ResourceType: "image",
+ Status: schedulertypes.Failed,
+ },
+ },
+ retryIDs: []string{"failed"},
+ },
+ {
+ name: "completed failed batch retry",
+ targets: []schedulertypes.TargetOutcome{
+ {
+ ID: "auto-update",
+ ResourceType: "update-batch",
+ Status: schedulertypes.Partial,
+ },
+ {
+ ID: "failed",
+ ResourceType: "container",
+ Status: schedulertypes.Failed,
+ },
+ },
+ retryIDs: []string{"failed"},
+ },
+ {
+ name: "scoped retry cannot confirm original batch",
+ targets: []schedulertypes.TargetOutcome{
+ {
+ ID: "auto-update",
+ ResourceType: "update-retry",
+ Status: schedulertypes.Succeeded,
+ },
+ {
+ ID: "done",
+ ResourceType: "container",
+ Status: schedulertypes.Succeeded,
+ },
+ },
+ status: schedulertypes.Failed,
+ unresolved: true,
+ },
+ {
+ name: "completed batch",
+ targets: []schedulertypes.TargetOutcome{{
+ ID: "auto-update",
+ ResourceType: "update-batch",
+ Status: schedulertypes.Succeeded,
+ }},
+ status: schedulertypes.Succeeded,
+ },
} {
t.Run(tc.name, func(t *testing.T) {
previous := schedulertypes.Run{AttemptCount: 2, Outcome: schedulertypes.Outcome{Targets: tc.targets}}
@@ -115,7 +191,18 @@ func TestAutoUpdateJob_OverlappingRunIsSkippedInternal(t *testing.T) {
}
require.NoError(t, settingsSvc.SetBoolSetting(ctx, "autoUpdate", false))
- retryCtx := jobcontext.WithExecution(ctx, schedulertypes.Run{AttemptCount: 2, Outcome: schedulertypes.Outcome{Targets: []schedulertypes.TargetOutcome{{ID: "failed", ResourceType: "container", Status: schedulertypes.Failed}}}}, nil)
+ retryCtx := jobcontext.WithExecution(
+ ctx,
+ schedulertypes.Run{
+ AttemptCount: 2,
+ Outcome: schedulertypes.Outcome{Targets: []schedulertypes.TargetOutcome{{
+ ID: "failed",
+ ResourceType: "container",
+ Status: schedulertypes.Failed,
+ }}},
+ },
+ nil,
+ )
outcome, err := job.Run(retryCtx)
require.NoError(t, err)
require.Equal(t, schedulertypes.Failed, outcome.Status)
diff --git a/backend/pkg/scheduler/entityjobs/entityjobs.go b/backend/pkg/scheduler/entityjobs/entityjobs.go
index 9eb7c12fd..68366150c 100644
--- a/backend/pkg/scheduler/entityjobs/entityjobs.go
+++ b/backend/pkg/scheduler/entityjobs/entityjobs.go
@@ -41,12 +41,17 @@ func New(jobPrefix, admissionScope string) *Registry {
// SetScheduler injects the job scheduler, the admission gate and the app
// lifecycle context. The lifecycle context is what scheduled runs execute on,
// so they outlive the request or bootstrap goroutine that registered them.
-func (r *Registry) SetScheduler(ctx context.Context, scheduler schedulertypes.DynamicScheduler, admissionGate *runs.Admission) error { //nolint:contextcheck // scheduled runs must capture the app lifecycle context, not request contexts
+//
+//nolint:contextcheck // scheduled runs must capture the app lifecycle context, not request contexts
+func (r *Registry) SetScheduler(ctx context.Context,
+ scheduler schedulertypes.DynamicScheduler,
+ admissionGate *runs.Admission,
+) error {
if scheduler == nil || admissionGate == nil {
return fmt.Errorf("%s scheduler dependencies unavailable", r.admissionScope)
}
if ctx == nil {
- ctx = context.Background()
+ ctx = context.Background() //nolint:forbidigo // Fallback preserves the existing nil-context contract when no lifecycle was injected.
}
r.lifecycleCtx = ctx
r.scheduler = scheduler
@@ -70,14 +75,22 @@ func (r *Registry) Context(ctx context.Context) context.Context {
if ctx != nil {
return context.WithoutCancel(ctx)
}
- return context.Background()
+ return context.Background() //nolint:forbidigo // Fallback preserves the existing nil-context contract when no lifecycle was injected.
}
// JobName returns the scheduler job name for entityID.
func (r *Registry) JobName(entityID string) string { return r.jobPrefix + entityID }
// Register adds (or replaces) the dynamic job for entityID.
-func (r *Registry) Register(ctx context.Context, entityID string, schedule func(context.Context) string, run func(context.Context) (schedulertypes.Outcome, error), reconcile ...func(context.Context, schedulertypes.Run) (schedulertypes.Outcome, error)) {
+func (r *Registry) Register(ctx context.Context,
+ entityID string,
+ schedule func(context.Context) string,
+ run func(context.Context) (schedulertypes.Outcome,
+ error),
+ reconcile ...func(context.Context,
+ schedulertypes.Run) (schedulertypes.Outcome,
+ error),
+) {
if r.scheduler == nil {
return
}
diff --git a/backend/pkg/scheduler/filesystem_watcher_job.go b/backend/pkg/scheduler/filesystem_watcher_job.go
index aa7672c5b..e7df5399e 100644
--- a/backend/pkg/scheduler/filesystem_watcher_job.go
+++ b/backend/pkg/scheduler/filesystem_watcher_job.go
@@ -149,28 +149,28 @@ func (j *FilesystemWatcherJob) RestartProjectsWatcher(ctx context.Context) error
}
func (j *FilesystemWatcherJob) startProjectsWatcherInternal(ctx context.Context) (*fswatch.Watcher, error) {
- settings, err := j.settingsService.GetSettings(ctx)
+ localSettings, err := j.settingsService.GetSettings(ctx)
if err != nil {
return nil, err
}
- projectsDirectory, err := projects.GetProjectsDirectory(ctx, settings.ProjectsDirectory.Value)
+ projectsDirectory, err := projects.GetProjectsDirectory(ctx, localSettings.ProjectsDirectory.Value)
if err != nil {
return nil, err
}
j.logRecursiveProjectsWatchLimitWarningInternal(ctx, projectsDirectory)
- watcher, err := fswatch.NewWatcher(projectsDirectory, j.projectWatcherOptionsInternal(settings.FollowProjectSymlinks.IsTrue()))
+ watcher, err := fswatch.NewWatcher(projectsDirectory, j.projectWatcherOptionsInternal(localSettings.FollowProjectSymlinks.IsTrue()))
if err != nil {
return nil, err
}
- if err := watcher.Start(j.lifecycleCtx); err != nil { //nolint:contextcheck // watcher lifetime belongs to the application, not this replacement task.
- return watcher, err
+ if startErr := watcher.Start(j.lifecycleCtx); startErr != nil { //nolint:contextcheck // watcher lifetime belongs to the application, not this replacement task.
+ return watcher, startErr
}
slog.InfoContext(ctx, "Projects filesystem watcher started", "path", projectsDirectory)
if j.projectService != nil {
- if err := j.projectService.SyncProjectsFromFileSystem(ctx); err != nil {
- slog.ErrorContext(ctx, "Initial project sync after watcher start failed", "error", err)
+ if syncProjectsFromFileSystemErr := j.projectService.SyncProjectsFromFileSystem(ctx); syncProjectsFromFileSystemErr != nil {
+ slog.ErrorContext(ctx, "Initial project sync after watcher start failed", "error", syncProjectsFromFileSystemErr)
}
}
return watcher, nil
@@ -231,21 +231,21 @@ func (j *FilesystemWatcherJob) startTemplatesWatcherInternal(ctx context.Context
return nil, nil
}
- settings, err := j.settingsService.GetSettings(ctx)
+ localSettings, err := j.settingsService.GetSettings(ctx)
if err != nil {
return nil, err
}
- projectsDirectory, err := projects.GetProjectsDirectory(ctx, settings.ProjectsDirectory.Value)
+ projectsDirectory, err := projects.GetProjectsDirectory(ctx, localSettings.ProjectsDirectory.Value)
if err != nil {
return nil, err
}
- templatesDir, err := projects.GetTemplatesDirectory(ctx, settings.TemplatesDirectory.Value)
+ templatesDir, err := projects.GetTemplatesDirectory(ctx, localSettings.TemplatesDirectory.Value)
if err != nil {
return nil, err
}
- if err := j.templateService.SyncLocalTemplatesFromFilesystem(ctx); err != nil {
- slog.ErrorContext(ctx, "Initial template sync failed", "error", err)
+ if syncLocalTemplatesFromFilesystemErr := j.templateService.SyncLocalTemplatesFromFilesystem(ctx); syncLocalTemplatesFromFilesystemErr != nil {
+ slog.ErrorContext(ctx, "Initial template sync failed", "error", syncLocalTemplatesFromFilesystemErr)
}
if directoriesOverlapInternal(projectsDirectory, templatesDir) {
@@ -264,8 +264,8 @@ func (j *FilesystemWatcherJob) startTemplatesWatcherInternal(ctx context.Context
if err != nil {
return nil, err
}
- if err := watcher.Start(j.lifecycleCtx); err != nil { //nolint:contextcheck // watcher lifetime belongs to the application, not this replacement task.
- return watcher, err
+ if startErr := watcher.Start(j.lifecycleCtx); startErr != nil { //nolint:contextcheck // watcher lifetime belongs to the application, not this replacement task.
+ return watcher, startErr
}
slog.InfoContext(ctx, "Templates filesystem watcher started", "path", templatesDir)
diff --git a/backend/pkg/scheduler/filesystem_watcher_job_test.go b/backend/pkg/scheduler/filesystem_watcher_job_test.go
index 79d431032..cadad8e85 100644
--- a/backend/pkg/scheduler/filesystem_watcher_job_test.go
+++ b/backend/pkg/scheduler/filesystem_watcher_job_test.go
@@ -53,7 +53,7 @@ func TestFilesystemWatcherJob_ConcurrentProjectRestartsAreSerializedInternal(t *
job.mu.Unlock()
require.NotSame(t, earlyWatcher, startedWatcher)
- stopCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ stopCtx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
require.NoError(t, job.Stop(stopCtx))
}
diff --git a/backend/pkg/scheduler/git_clone_cleanup_job_test.go b/backend/pkg/scheduler/git_clone_cleanup_job_test.go
index 11f055e77..200c06e1b 100644
--- a/backend/pkg/scheduler/git_clone_cleanup_job_test.go
+++ b/backend/pkg/scheduler/git_clone_cleanup_job_test.go
@@ -1,7 +1,6 @@
package scheduler
import (
- "context"
"os"
"path/filepath"
"testing"
@@ -18,7 +17,7 @@ func TestGitCloneCleanupJob_NameAndSchedule(t *testing.T) {
job := NewGitCloneCleanupJob(nil, nil)
assert.Equal(t, GitCloneCleanupJobName, job.Name())
- assert.Equal(t, "0 30 * * * *", job.Schedule(context.Background()))
+ assert.Equal(t, "0 30 * * * *", job.Schedule(t.Context()))
}
// TestGitCloneCleanupJob_RunPurgesStaleCloneDirs pins the nil-settings guard.
@@ -33,7 +32,8 @@ func TestGitCloneCleanupJob_RunPurgesStaleCloneDirs(t *testing.T) {
staleTime := time.Now().Add(-3 * time.Hour)
require.NoError(t, os.Chtimes(stale, staleTime, staleTime))
- job.Run(context.Background())
+ _, runErr1 := job.Run(t.Context())
+ require.NoError(t, runErr1)
_, err := os.Stat(stale)
require.ErrorIs(t, err, os.ErrNotExist, "stale clone dir should be removed")
@@ -44,5 +44,8 @@ func TestGitCloneCleanupJob_RunPurgesStaleCloneDirs(t *testing.T) {
func TestGitCloneCleanupJob_RunNilRepoServiceIsNoop(t *testing.T) {
job := NewGitCloneCleanupJob(nil, nil)
- assert.NotPanics(t, func() { job.Run(context.Background()) })
+ assert.NotPanics(t, func() {
+ _, runErr2 := job.Run(t.Context())
+ require.NoError(t, runErr2)
+ })
}
diff --git a/backend/pkg/scheduler/image_update_watcher.go b/backend/pkg/scheduler/image_update_watcher.go
index ce8620a51..e72e81e42 100644
--- a/backend/pkg/scheduler/image_update_watcher.go
+++ b/backend/pkg/scheduler/image_update_watcher.go
@@ -86,7 +86,14 @@ type ImageUpdateWatcher struct {
stoppedOnce sync.Once
}
-func NewImageUpdateWatcher(cfg *config.Config, imageUpdateService *imageupdate.ImageUpdateService, settingsService *settings.SettingsService, environmentService *environment.EnvironmentService, dockerService *docker.DockerClientService, projectService *project.ProjectService) (*ImageUpdateWatcher, error) {
+func NewImageUpdateWatcher(cfg *config.Config,
+ imageUpdateService *imageupdate.ImageUpdateService,
+ settingsService *settings.SettingsService,
+ environmentService *environment.EnvironmentService,
+ dockerService *docker.DockerClientService,
+ projectService *project.ProjectService) (*ImageUpdateWatcher,
+ error,
+) {
if imageUpdateService == nil || settingsService == nil || environmentService == nil || dockerService == nil || projectService == nil {
return nil, errors.New("image update watcher dependencies unavailable")
}
@@ -94,7 +101,24 @@ func NewImageUpdateWatcher(cfg *config.Config, imageUpdateService *imageupdate.I
if cfg != nil {
location = cfg.GetLocation()
}
- return &ImageUpdateWatcher{imageUpdateService: imageUpdateService, settingsService: settingsService, environmentService: environmentService, dockerService: dockerService, projectService: projectService, location: location, debounce: imageUpdateWatcherDebounce, backfillRetry: imageUpdateWatcherBackfillRetry, metadataReady: make(chan struct{}), started: make(chan struct{}), stopped: make(chan struct{}), trigger: make(chan struct{}, 1), scheduleRefresh: make(chan struct{}, 1)}, nil
+ return &ImageUpdateWatcher{
+ imageUpdateService: imageUpdateService,
+ settingsService: settingsService,
+ environmentService: environmentService,
+ dockerService: dockerService,
+ projectService: projectService,
+ location: location,
+ debounce: imageUpdateWatcherDebounce,
+ backfillRetry: imageUpdateWatcherBackfillRetry,
+ metadataReady: make(chan struct{}),
+ started: make(chan struct{}),
+ stopped: make(chan struct{}),
+ trigger: make(chan struct{},
+ 1),
+ scheduleRefresh: make(chan struct{},
+ 1),
+ },
+ nil
}
func (w *ImageUpdateWatcher) Name() string { return "image-polling" }
@@ -130,7 +154,7 @@ func (w *ImageUpdateWatcher) runEventLoopInternal(runCtx context.Context) error
return errors.New("docker event bus unavailable")
}
eventCh, unsubscribe := eventBus.Subscribe(events.ImageEventType, bus.WithSubscriberBuffer(16))
- defer func() { unsubscribe() }()
+ defer unsubscribe()
reconnect := time.NewTicker(5 * time.Second)
defer reconnect.Stop()
timer := time.NewTimer(time.Hour)
@@ -342,9 +366,9 @@ func (w *ImageUpdateWatcher) RunNow(ctx context.Context) (err error) {
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
for {
- current, err := coordinator.Get(ctx, run.EnvironmentID, run.JobID, run.ID)
- if err != nil {
- return err
+ current, getErr := coordinator.Get(ctx, run.EnvironmentID, run.JobID, run.ID)
+ if getErr != nil {
+ return getErr
}
if current.Status.Terminal() || current.Status == schedulertypes.NeedsAttention {
if current.Status == schedulertypes.Succeeded {
diff --git a/backend/pkg/scheduler/image_update_watcher_test.go b/backend/pkg/scheduler/image_update_watcher_test.go
index 39d735a96..16e7f23d7 100644
--- a/backend/pkg/scheduler/image_update_watcher_test.go
+++ b/backend/pkg/scheduler/image_update_watcher_test.go
@@ -184,7 +184,12 @@ func (b *lockedBufferInternal) stringInternal() string {
return b.String()
}
-func newImageUpdateWatcherForTestInternal(t *testing.T, scanner imageUpdateScannerInternal, settings pollingSettingReaderInternal, eventBus *bus.DockerEventBus, backfiller projectImageRefsBackfillerInternal) *ImageUpdateWatcher {
+func newImageUpdateWatcherForTestInternal(t *testing.T,
+ scanner imageUpdateScannerInternal,
+ settings pollingSettingReaderInternal,
+ eventBus *bus.DockerEventBus,
+ backfiller projectImageRefsBackfillerInternal,
+) *ImageUpdateWatcher {
t.Helper()
if backfiller == nil {
backfiller = &projectImageRefsBackfillerFakeInternal{}
@@ -215,9 +220,9 @@ func newImageUpdateWatcherForTestInternal(t *testing.T, scanner imageUpdateScann
return watcher
}
-func startImageUpdateWatcherForTestInternal(t *testing.T, watcher *ImageUpdateWatcher) (context.CancelFunc, <-chan error) {
+func startImageUpdateWatcherForTestInternal(t *testing.T, watcher *ImageUpdateWatcher) {
t.Helper()
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
errCh := make(chan error, 1)
go func() {
errCh <- watcher.Start(ctx)
@@ -226,7 +231,6 @@ func startImageUpdateWatcherForTestInternal(t *testing.T, watcher *ImageUpdateWa
cancel()
require.NoError(t, <-errCh)
})
- return cancel, errCh
}
func TestImageUpdateWatcher_StartScansAtStartupAndCoalescesAllImageEvents(t *testing.T) {
@@ -355,12 +359,12 @@ func TestImageUpdateWatcher_RunNowReturnsInProgressErrorDuringActiveScan(t *test
startImageUpdateWatcherForTestInternal(t, watcher)
require.Equal(t, 1, <-scanner.startedCh)
- require.ErrorIs(t, watcher.RunNow(context.Background()), common.ErrImageScanInProgress)
+ require.ErrorIs(t, watcher.RunNow(t.Context()), common.ErrImageScanInProgress)
require.Equal(t, 1, scanner.countInternal())
close(releaseCh)
require.Eventually(t, func() bool {
- return watcher.RunNow(context.Background()) == nil
+ return watcher.RunNow(t.Context()) == nil
}, time.Second, time.Millisecond)
require.Equal(t, 2, scanner.countInternal())
require.Equal(t, 1, scanner.maxActiveInternal())
@@ -374,10 +378,10 @@ func TestImageUpdateWatcher_RunNowReturnsCompletedResultInternal(t *testing.T) {
require.Eventually(t, func() bool { return scanner.countInternal() == 1 }, time.Second, time.Millisecond)
require.Eventually(t, func() bool {
- return watcher.RunNow(context.Background()) == nil
+ return watcher.RunNow(t.Context()) == nil
}, time.Second, time.Millisecond)
for range 10 {
- require.NoError(t, watcher.RunNow(context.Background()))
+ require.NoError(t, watcher.RunNow(t.Context()))
}
}
@@ -391,7 +395,7 @@ func TestImageUpdateWatcher_RunNowReturnsContainedScanPanicInternal(t *testing.T
return scanner.countInternal() == 1 && watcher.triggerGeneration.Load() == watcher.acknowledgedGeneration.Load()
}, time.Second, time.Millisecond)
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
require.ErrorContains(t, watcher.RunNow(ctx), "image update scan worker panicked")
require.Equal(t, 2, scanner.countInternal())
@@ -416,7 +420,7 @@ func TestImageUpdateWatcher_TriggeredScanRetriesAfterManualScanFinishes(t *testi
manualErrCh := make(chan error, 1)
go func() {
for {
- err := watcher.RunNow(context.Background())
+ err := watcher.RunNow(t.Context())
if errors.Is(err, common.ErrImageScanInProgress) {
time.Sleep(time.Millisecond)
continue
@@ -551,7 +555,7 @@ func TestImageUpdateWatcher_CancellationStopsBackfillWithoutScanning(t *testing.
scanner := &imageUpdateScannerFakeInternal{}
settings := &pollingSettingReaderFakeInternal{enabled: true}
watcher := newImageUpdateWatcherForTestInternal(t, scanner, settings, bus.NewDockerEventBus(), backfiller)
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
errCh := make(chan error, 1)
go func() { errCh <- watcher.Start(ctx) }()
@@ -577,8 +581,8 @@ func TestImageUpdateWatcher_ScheduledPollTriggersScanWithoutEvents(t *testing.T)
require.Eventually(t, func() bool { return scanner.countInternal() == 1 }, time.Second, 5*time.Millisecond)
require.Eventually(t, func() bool {
- record, err := watcher.coordinator.ScheduleState(t.Context(), watcher.Name())
- return err == nil && record.Schedule == settings.schedule && !record.NextRun.IsZero()
+ record, scheduleStateErr := watcher.coordinator.ScheduleState(t.Context(), watcher.Name())
+ return scheduleStateErr == nil && record.Schedule == settings.schedule && !record.NextRun.IsZero()
}, time.Second, 5*time.Millisecond)
require.NoError(t, jobScheduler.StartScheduler(t.Context()))
record, err := watcher.coordinator.ScheduleState(t.Context(), watcher.Name())
@@ -587,8 +591,8 @@ func TestImageUpdateWatcher_ScheduledPollTriggersScanWithoutEvents(t *testing.T)
require.False(t, record.NextRun.IsZero())
require.Eventually(t, func() bool { return scanner.countInternal() >= 3 }, 5*time.Second, 10*time.Millisecond)
require.Eventually(t, func() bool {
- history, err := watcher.coordinator.List(t.Context(), "0", watcher.Name(), 1, 10)
- if err != nil {
+ history, listErr := watcher.coordinator.List(t.Context(), "0", watcher.Name(), 1, 10)
+ if listErr != nil {
return false
}
for _, run := range history.Runs {
@@ -638,7 +642,7 @@ func TestImageUpdateWatcher_RunNowWaitsForMetadataReadiness(t *testing.T) {
settings := &pollingSettingReaderFakeInternal{enabled: true}
watcher := newImageUpdateWatcherForTestInternal(t, scanner, settings, bus.NewDockerEventBus(), nil)
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
require.ErrorIs(t, watcher.RunNow(ctx), context.DeadlineExceeded)
require.Zero(t, scanner.countInternal())
diff --git a/backend/pkg/scheduler/job_schedule_integration_test.go b/backend/pkg/scheduler/job_schedule_integration_test.go
index e9cd88e6c..54714b9b8 100644
--- a/backend/pkg/scheduler/job_schedule_integration_test.go
+++ b/backend/pkg/scheduler/job_schedule_integration_test.go
@@ -19,12 +19,12 @@ import (
)
func TestDeprecatedImagePollingSchedulePersistsWithoutRuntimeJob(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
databasePath := filepath.Join(t.TempDir(), "arcane.db")
db, settingsService := openJobScheduleTestDatabaseInternal(t, ctx, databasePath)
appConfig := &config.Config{Timezone: "UTC"}
- lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
+ lifecycleCtx, cancelLifecycle := context.WithCancel(t.Context())
jobScheduler := newJobSchedulerForTestInternal(t, lifecycleCtx, appConfig.GetLocation())
jobService := job.NewJobService(db, settingsService, appConfig, jobScheduler.coordinator, nil, nil, nil)
@@ -60,18 +60,18 @@ func TestDeprecatedImagePollingSchedulePersistsWithoutRuntimeJob(t *testing.T) {
require.Equal(t, "pollingInterval", imagePollingStatus.SettingsKey)
cancelLifecycle()
- waitForSchedulerStopInternal(jobScheduler)
+ require.NoError(t, stopJobSchedulerForTestInternal(t.Context(), jobScheduler))
closeJobScheduleTestDatabaseInternal(t, db)
restartDB, restartSettingsService := openJobScheduleTestDatabaseInternal(t, ctx, databasePath)
- restartLifecycleCtx, cancelRestartLifecycle := context.WithCancel(context.Background())
+ restartLifecycleCtx, cancelRestartLifecycle := context.WithCancel(t.Context())
restartScheduler := newJobSchedulerForTestInternal(t, restartLifecycleCtx, appConfig.GetLocation())
restartJobService := job.NewJobService(restartDB, restartSettingsService, appConfig, restartScheduler.coordinator, nil, nil, nil)
restartJobService.SetScheduler(restartLifecycleCtx, restartScheduler)
require.NoError(t, restartScheduler.StartScheduler(t.Context()))
t.Cleanup(func() {
cancelRestartLifecycle()
- waitForSchedulerStopInternal(restartScheduler)
+ require.NoError(t, stopJobSchedulerForTestInternal(context.WithoutCancel(t.Context()), restartScheduler))
closeJobScheduleTestDatabaseInternal(t, restartDB)
})
@@ -124,10 +124,6 @@ func closeJobScheduleTestDatabaseInternal(t *testing.T, db *database.DB) {
require.NoError(t, sqlDB.Close())
}
-func waitForSchedulerStopInternal(jobScheduler *jobSchedulerInternal) {
- _ = stopJobSchedulerForTestInternal(context.Background(), jobScheduler)
-}
-
func findJobStatusInternal(t *testing.T, jobs *jobschedule.JobListResponse, jobID string) jobschedule.JobStatus {
t.Helper()
diff --git a/backend/pkg/scheduler/runs/activity.go b/backend/pkg/scheduler/runs/activity.go
index d5a69fa22..0b007c936 100644
--- a/backend/pkg/scheduler/runs/activity.go
+++ b/backend/pkg/scheduler/runs/activity.go
@@ -69,8 +69,8 @@ func (q *Coordinator) retryActivitySyncInternal(ctx context.Context) {
}
for _, entry := range page.States {
var state scheduler.CoordinatorState
- if err := entry.Data.Decode(&state); err != nil {
- slog.ErrorContext(ctx, "Decode pending job activities", "error", err)
+ if decodeErr := entry.Data.Decode(&state); decodeErr != nil {
+ slog.ErrorContext(ctx, "Decode pending job activities", "error", decodeErr)
continue
}
for runID := range state.PendingActivitySync {
diff --git a/backend/pkg/scheduler/runs/activity_test.go b/backend/pkg/scheduler/runs/activity_test.go
index c0786d895..aad9002c9 100644
--- a/backend/pkg/scheduler/runs/activity_test.go
+++ b/backend/pkg/scheduler/runs/activity_test.go
@@ -48,7 +48,7 @@ func TestActivityFailureNeverReplaysAcceptedExecution(t *testing.T) {
require.NoError(t, q.Start(t.Context(), t.Context()))
q.Activate()
t.Cleanup(func() {
- ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), time.Second)
defer cancel()
require.NoError(t, q.Stop(ctx))
})
diff --git a/backend/pkg/scheduler/runs/actors.go b/backend/pkg/scheduler/runs/actors.go
index 5aa1e1e41..4f175f23a 100644
--- a/backend/pkg/scheduler/runs/actors.go
+++ b/backend/pkg/scheduler/runs/actors.go
@@ -194,8 +194,8 @@ func (a *coordinatorActorInternal) reconcileDispatchInternal(ctx context.Context
previous.JobID = id
state.Dispatches[key] = previous
state.Revision++
- if err := a.q.service.SetState(ctx, coordinatorTypeInternal, a.id, *state, nil); err != nil {
- return false, err
+ if setStateErr := a.q.service.SetState(ctx, coordinatorTypeInternal, a.id, *state, nil); setStateErr != nil {
+ return false, setStateErr
}
}
job, err := a.q.service.GetJob(ctx, previous.JobID)
@@ -227,8 +227,8 @@ func (a *coordinatorActorInternal) dispatchRunInternal(ctx context.Context, stat
return err
}
if err == nil {
- if err := a.q.service.DeleteJob(ctx, actorType, a.id, intent.JobID); err != nil && !errors.Is(err, actor.ErrJobNotFound) {
- return err
+ if deleteJobErr := a.q.service.DeleteJob(ctx, actorType, a.id, intent.JobID); deleteJobErr != nil && !errors.Is(deleteJobErr, actor.ErrJobNotFound) {
+ return deleteJobErr
}
}
}
@@ -257,8 +257,8 @@ func (a *coordinatorActorInternal) dispatchRunInternal(ctx context.Context, stat
return err
}
if job.Status.IsTerminal() {
- if err := a.q.service.DeleteJob(ctx, actorType, a.id, id); err != nil && !errors.Is(err, actor.ErrJobNotFound) {
- return err
+ if deleteJobErr2 := a.q.service.DeleteJob(ctx, actorType, a.id, id); deleteJobErr2 != nil && !errors.Is(deleteJobErr2, actor.ErrJobNotFound) {
+ return deleteJobErr2
}
id, _, err = a.q.service.Dispatch(ctx, actorType, a.id, "execute", command, options...)
if err != nil {
@@ -336,8 +336,8 @@ func (a *coordinatorActorInternal) Alarm(ctx context.Context, name string, data
record.NextRun = schedule.Next(now.In(a.q.location))
record.Sequence++
state.Revision++
- if err := a.q.service.SetState(ctx, coordinatorTypeInternal, a.id, state, nil); err != nil {
- return err
+ if setStateErr := a.q.service.SetState(ctx, coordinatorTypeInternal, a.id, state, nil); setStateErr != nil {
+ return setStateErr
}
return a.flushInternal(ctx, &state)
}
@@ -348,8 +348,8 @@ func (q *Coordinator) repairInternal(ctx context.Context) error {
return err
}
for _, record := range records {
- if _, err := q.service.Invoke(ctx, coordinatorTypeInternal, kit.SHA256Hex(record.EnvironmentID+"\x00"+record.JobID), "repair", nil); err != nil {
- return err
+ if _, invokeErr := q.service.Invoke(ctx, coordinatorTypeInternal, kit.SHA256Hex(record.EnvironmentID+"\x00"+record.JobID), "repair", nil); invokeErr != nil {
+ return invokeErr
}
}
return nil
@@ -362,16 +362,16 @@ func (q *Coordinator) importLegacyInternal(ctx context.Context) error {
}
for _, entry := range entries {
marker := "francis-import/" + entry.Key
- _, done, err := q.store.Get(ctx, marker)
- if err != nil {
- return fmt.Errorf("import legacy job record %q: %w", entry.Key, err)
+ _, done, getErr := q.store.Get(ctx, marker)
+ if getErr != nil {
+ return fmt.Errorf("import legacy job record %q: %w", entry.Key, getErr)
}
if done {
continue
}
var record st.QueueRecord
- if err := json.Unmarshal([]byte(entry.Value), &record); err != nil {
- return fmt.Errorf("decode legacy job record %q: %w", entry.Key, err)
+ if unmarshalErr := json.Unmarshal([]byte(entry.Value), &record); unmarshalErr != nil {
+ return fmt.Errorf("decode legacy job record %q: %w", entry.Key, unmarshalErr)
}
id := kit.SHA256Hex(record.EnvironmentID + "\x00" + record.JobID)
if entry.Key != queuePrefixInternal+id {
@@ -379,12 +379,12 @@ func (q *Coordinator) importLegacyInternal(ctx context.Context) error {
}
sourceHash := kit.SHA256Hex(entry.Value)
command := st.CoordinatorImport{Record: record, SourceHash: sourceHash}
- if _, err := q.service.Invoke(ctx, coordinatorTypeInternal, id, "import", command); err != nil {
- return fmt.Errorf("import legacy job record %q: %w", entry.Key, err)
+ if _, invokeErr := q.service.Invoke(ctx, coordinatorTypeInternal, id, "import", command); invokeErr != nil {
+ return fmt.Errorf("import legacy job record %q: %w", entry.Key, invokeErr)
}
var imported st.CoordinatorState
- if err := q.service.GetState(ctx, coordinatorTypeInternal, id, &imported); err != nil {
- return fmt.Errorf("import legacy job record %q: %w", entry.Key, err)
+ if getStateErr := q.service.GetState(ctx, coordinatorTypeInternal, id, &imported); getStateErr != nil {
+ return fmt.Errorf("import legacy job record %q: %w", entry.Key, getStateErr)
}
if !imported.Imported || imported.ImportHash != sourceHash {
return fmt.Errorf("legacy import verification failed for job %q in environment %q", record.JobID, record.EnvironmentID)
@@ -392,8 +392,8 @@ func (q *Coordinator) importLegacyInternal(ctx context.Context) error {
if imported.Record.EnvironmentID != record.EnvironmentID || imported.Record.JobID != record.JobID {
return fmt.Errorf("legacy import identity mismatch for record %q", entry.Key)
}
- if err := q.store.Set(ctx, marker, "complete"); err != nil {
- return fmt.Errorf("import legacy job record %q: %w", entry.Key, err)
+ if setErr := q.store.Set(ctx, marker, "complete"); setErr != nil {
+ return fmt.Errorf("import legacy job record %q: %w", entry.Key, setErr)
}
}
return nil
diff --git a/backend/pkg/scheduler/runs/actors_test.go b/backend/pkg/scheduler/runs/actors_test.go
index 01bdc9291..ef28ef7fd 100644
--- a/backend/pkg/scheduler/runs/actors_test.go
+++ b/backend/pkg/scheduler/runs/actors_test.go
@@ -35,13 +35,37 @@ func TestLegacyImportSurvivesRestartAndDeduplicates(t *testing.T) {
sqlDB.SetMaxOpenConns(1)
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
store := kv.NewKVService(&database.DB{DB: db})
- legacy := st.QueueRecord{JobID: "legacy", EnvironmentID: "0", Runs: []st.Run{{ID: uuid.New().String(), JobID: "legacy", EnvironmentID: "0", Trigger: "manual", Status: st.Succeeded, CreatedAt: time.Now().UTC(), UpdatedAt: time.Now().UTC()}}}
+ legacy := st.QueueRecord{
+ JobID: "legacy",
+ EnvironmentID: "0",
+ Runs: []st.Run{{
+ ID: uuid.New().String(),
+ JobID: "legacy",
+ EnvironmentID: "0",
+ Trigger: "manual",
+ Status: st.Succeeded,
+ CreatedAt: time.Now().UTC(),
+ UpdatedAt: time.Now().UTC(),
+ }},
+ }
legacy.Runs[0].ActivityID = legacy.Runs[0].ID
for _, jobID := range []string{"gitops-sync:first", "gitops-sync:second"} {
record := st.QueueRecord{JobID: jobID, EnvironmentID: "0", Schedule: "@every 5m", NextRun: time.Now().UTC().Add(time.Hour)}
for i := range 1600 {
created := time.Now().UTC().Add(-time.Duration(1600-i) * 5 * time.Minute)
- record.Runs = append(record.Runs, st.Run{ID: uuid.New().String(), ActivityID: uuid.New().String(), JobID: jobID, EnvironmentID: "0", Trigger: "scheduled", Status: st.NeedsAttention, CreatedAt: created, UpdatedAt: created})
+ record.Runs = append(
+ record.Runs,
+ st.Run{
+ ID: uuid.New().String(),
+ ActivityID: uuid.New().String(),
+ JobID: jobID,
+ EnvironmentID: "0",
+ Trigger: "scheduled",
+ Status: st.NeedsAttention,
+ CreatedAt: created,
+ UpdatedAt: created,
+ },
+ )
}
data, marshalErr := json.Marshal(record)
require.NoError(t, marshalErr)
@@ -169,8 +193,8 @@ func TestDuplicateDispatchAndCanceledDelivery(t *testing.T) {
q.Activate()
t.Cleanup(func() { require.NoError(t, q.Stop(context.WithoutCancel(t.Context()))) })
require.Eventually(t, func() bool {
- info, err := q.service.GetJob(t.Context(), jobID)
- return err == nil && info.Status.IsTerminal() || cancel && errors.Is(err, actor.ErrJobNotFound)
+ info, getJobErr := q.service.GetJob(t.Context(), jobID)
+ return getJobErr == nil && info.Status.IsTerminal() || cancel && errors.Is(getJobErr, actor.ErrJobNotFound)
}, 5*time.Second, 10*time.Millisecond)
persisted, err := q.Get(t.Context(), "0", run.JobID, run.ID)
require.NoError(t, err)
@@ -343,7 +367,7 @@ func TestLostDispatchAcknowledgementRetainsOneExecution(t *testing.T) {
require.Len(t, deliveries, 1)
once.Do(func() { close(finish) })
require.Eventually(t, func() bool {
- stored, err := q.Get(t.Context(), "0", run.JobID, run.ID)
- return err == nil && stored.Status == st.Succeeded
+ stored, getErr := q.Get(t.Context(), "0", run.JobID, run.ID)
+ return getErr == nil && stored.Status == st.Succeeded
}, 5*time.Second, 10*time.Millisecond)
}
diff --git a/backend/pkg/scheduler/runs/admission.go b/backend/pkg/scheduler/runs/admission.go
index 8a9e7c6c0..d8da20767 100644
--- a/backend/pkg/scheduler/runs/admission.go
+++ b/backend/pkg/scheduler/runs/admission.go
@@ -62,9 +62,9 @@ func (a *Admission) TryAcquire(ctx context.Context, key st.AdmissionKey) (*Lease
return nil, false, err
}
var acquired bool
- if err := envelope.Decode(&acquired); err != nil {
+ if decodeErr := envelope.Decode(&acquired); decodeErr != nil {
a.releaseInternal(ctx, id, st.AdmissionCommand{Epoch: a.epoch, Token: token})
- return nil, false, err
+ return nil, false, decodeErr
}
if !acquired {
return nil, false, nil
@@ -123,8 +123,8 @@ func (a *admissionActorInternal) Invoke(ctx context.Context, method string, data
return nil, err
}
var command st.AdmissionCommand
- if err := data.Decode(&command); err != nil {
- return nil, err
+ if decodeErr := data.Decode(&command); decodeErr != nil {
+ return nil, decodeErr
}
switch method {
case "acquire":
@@ -140,8 +140,8 @@ func (a *admissionActorInternal) Invoke(ctx context.Context, method string, data
default:
return nil, errors.New("unknown resource admission command")
}
- if err := a.service.SetState(ctx, admissionTypeInternal, a.id, state, nil); err != nil {
- return nil, err
+ if setStateErr := a.service.SetState(ctx, admissionTypeInternal, a.id, state, nil); setStateErr != nil {
+ return nil, setStateErr
}
return true, nil
}
diff --git a/backend/pkg/scheduler/runs/coordinator.go b/backend/pkg/scheduler/runs/coordinator.go
index 85df6bfc0..cbce1e781 100644
--- a/backend/pkg/scheduler/runs/coordinator.go
+++ b/backend/pkg/scheduler/runs/coordinator.go
@@ -234,23 +234,23 @@ func (q *Coordinator) Start(ctx, appCtx context.Context) error {
if !changed {
continue
}
- if err := q.mutateInternal(ctx, record.EnvironmentID, record.JobID, func(current *st.QueueRecord) error {
+ if mutateErr := q.mutateInternal(ctx, record.EnvironmentID, record.JobID, func(current *st.QueueRecord) error {
for i := range current.Runs {
normalizeLegacyRunInternal(&current.Runs[i])
}
return nil
- }); err != nil {
- return fmt.Errorf("normalize startup job %q in environment %q: %w", record.JobID, record.EnvironmentID, err)
+ }); mutateErr != nil {
+ return fmt.Errorf("normalize startup job %q in environment %q: %w", record.JobID, record.EnvironmentID, mutateErr)
}
}
- if err := q.pruneInternal(ctx); err != nil {
- return fmt.Errorf("prune startup job history: %w", err)
+ if pruneErr := q.pruneInternal(ctx); pruneErr != nil {
+ return fmt.Errorf("prune startup job history: %w", pruneErr)
}
- if err := ctx.Err(); err != nil {
- return fmt.Errorf("initialize job coordinator: %w", err)
+ if errErr := ctx.Err(); errErr != nil {
+ return fmt.Errorf("initialize job coordinator: %w", errErr)
}
- if err := appCtx.Err(); err != nil {
- return fmt.Errorf("start job dispatcher: %w", err)
+ if errErr2 := appCtx.Err(); errErr2 != nil {
+ return fmt.Errorf("start job dispatcher: %w", errErr2)
}
runCtx, cancel := context.WithCancel(appCtx)
diff --git a/backend/pkg/scheduler/runs/coordinator_store.go b/backend/pkg/scheduler/runs/coordinator_store.go
index 891e1a9bf..a7e8f9c33 100644
--- a/backend/pkg/scheduler/runs/coordinator_store.go
+++ b/backend/pkg/scheduler/runs/coordinator_store.go
@@ -30,16 +30,16 @@ func (q *Coordinator) mutateInternal(ctx context.Context, environmentID, jobID s
if err != nil && !errors.Is(err, actor.ErrStateNotFound) {
return err
}
- if err := q.prepareMutationInternal(&state, environmentID, jobID, change); err != nil {
- return err
+ if prepareMutationErr := q.prepareMutationInternal(&state, environmentID, jobID, change); prepareMutationErr != nil {
+ return prepareMutationErr
}
result, err := q.service.Invoke(ctx, coordinatorTypeInternal, id, "replace", state)
if err != nil {
return err
}
var swapped bool
- if err = result.Decode(&swapped); err != nil {
- return err
+ if decodeErr := result.Decode(&swapped); decodeErr != nil {
+ return decodeErr
}
if swapped {
return nil
@@ -58,20 +58,20 @@ func (q *Coordinator) prepareMutationInternal(state *st.CoordinatorState, enviro
if state.Record.JobID == "" {
state.Record = st.QueueRecord{JobID: jobID, EnvironmentID: environmentID}
}
- if err := change(&state.Record); err != nil {
- return err
+ if changeErr := change(&state.Record); changeErr != nil {
+ return changeErr
}
preserveUnsyncedRunsInternal(state, previousRuns)
for i := range state.Record.Runs {
q.associateActivityInternal(&state.Record.Runs[i])
- if err := markChangedActivityInternal(state, &state.Record.Runs[i], previous, versions); err != nil {
- return err
+ if markChangedActivityErr := markChangedActivityInternal(state, &state.Record.Runs[i], previous, versions); markChangedActivityErr != nil {
+ return markChangedActivityErr
}
}
for id, run := range state.Record.Receipts {
q.associateActivityInternal(&run)
- if err := markChangedActivityInternal(state, &run, previous, versions); err != nil {
- return err
+ if markChangedActivityErr2 := markChangedActivityInternal(state, &run, previous, versions); markChangedActivityErr2 != nil {
+ return markChangedActivityErr2
}
state.Record.Receipts[id] = run
}
@@ -156,8 +156,8 @@ func (q *Coordinator) Records(ctx context.Context) ([]st.QueueRecord, error) {
}
for _, entry := range page.States {
var state st.CoordinatorState
- if err := entry.Data.Decode(&state); err != nil {
- return nil, fmt.Errorf("decode job coordinator %q: %w", entry.ActorID, err)
+ if decodeErr := entry.Data.Decode(&state); decodeErr != nil {
+ return nil, fmt.Errorf("decode job coordinator %q: %w", entry.ActorID, decodeErr)
}
normalizeRecordTimesInternal(&state.Record)
q.runtime.NameActor(entry.ActorID, state.Record.JobID+"@"+state.Record.EnvironmentID)
@@ -266,11 +266,11 @@ func (q *Coordinator) pruneInternal(ctx context.Context) error {
if !pruneRunsInternal(&record, now) {
continue
}
- if err := q.mutateInternal(ctx, record.EnvironmentID, record.JobID, func(current *st.QueueRecord) error {
+ if mutateErr := q.mutateInternal(ctx, record.EnvironmentID, record.JobID, func(current *st.QueueRecord) error {
pruneRunsInternal(current, now)
return nil
- }); err != nil {
- return fmt.Errorf("prune job %q in environment %q: %w", record.JobID, record.EnvironmentID, err)
+ }); mutateErr != nil {
+ return fmt.Errorf("prune job %q in environment %q: %w", record.JobID, record.EnvironmentID, mutateErr)
}
}
return nil
diff --git a/backend/pkg/scheduler/runs/resolution_test.go b/backend/pkg/scheduler/runs/resolution_test.go
index 6a3377ed3..a8d5fc078 100644
--- a/backend/pkg/scheduler/runs/resolution_test.go
+++ b/backend/pkg/scheduler/runs/resolution_test.go
@@ -150,7 +150,7 @@ func TestResolveRejectsUnsafeStates(t *testing.T) {
}
return nil
}))
- _, err = q.Resolve(context.Background(), test.environment, "auto-update", run.ID, "operator")
+ _, err = q.Resolve(t.Context(), test.environment, "auto-update", run.ID, "operator")
require.Error(t, err)
stored, err := q.Get(t.Context(), test.environment, "auto-update", run.ID)
require.NoError(t, err)
diff --git a/backend/pkg/scheduler/scheduled_prune_job.go b/backend/pkg/scheduler/scheduled_prune_job.go
index f3856b560..211cae7dd 100644
--- a/backend/pkg/scheduler/scheduled_prune_job.go
+++ b/backend/pkg/scheduler/scheduled_prune_job.go
@@ -96,8 +96,8 @@ func (j *ScheduledPruneJob) Run(ctx context.Context) (schedulertypes.Outcome, er
}
// Send notification
- if err := j.notificationService.SendPruneReportNotification(ctx, result); err != nil {
- slog.WarnContext(ctx, "failed to send prune report notification", "error", err)
+ if sendPruneReportNotificationErr := j.notificationService.SendPruneReportNotification(ctx, result); sendPruneReportNotificationErr != nil {
+ slog.WarnContext(ctx, "failed to send prune report notification", "error", sendPruneReportNotificationErr)
}
outcome := schedulertypes.Outcome{Status: schedulertypes.Succeeded}
if result.ActivityID != nil {
diff --git a/backend/pkg/scheduler/scheduled_prune_job_test.go b/backend/pkg/scheduler/scheduled_prune_job_test.go
index ebae1a896..d12d8c4f8 100644
--- a/backend/pkg/scheduler/scheduled_prune_job_test.go
+++ b/backend/pkg/scheduler/scheduled_prune_job_test.go
@@ -1,7 +1,6 @@
package scheduler
import (
- "context"
"testing"
"github.com/getarcaneapp/arcane/types/v2/system"
@@ -20,14 +19,14 @@ func setupScheduledPruneSettingsServiceInternal(t *testing.T) *settings.Settings
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))
- svc, err := newSettingsServiceForTestInternal(t, context.Background(), &database.DB{DB: db})
+ svc, err := newSettingsServiceForTestInternal(t, t.Context(), &database.DB{DB: db})
require.NoError(t, err)
return svc
}
func TestBuildScheduledPruneRequestInternal(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
settingsService := setupScheduledPruneSettingsServiceInternal(t)
require.NoError(t, settingsService.UpdateSetting(ctx, "pruneContainerMode", "olderThan"))
@@ -59,7 +58,7 @@ func TestBuildScheduledPruneRequestInternal(t *testing.T) {
}
func TestBuildScheduledPruneRequestInternal_SkipsWhenAllModesAreNone(t *testing.T) {
- ctx := context.Background()
+ ctx := t.Context()
settingsService := setupScheduledPruneSettingsServiceInternal(t)
require.NoError(t, settingsService.UpdateSetting(ctx, "pruneContainerMode", "none"))
diff --git a/backend/pkg/scheduler/scheduler.go b/backend/pkg/scheduler/scheduler.go
index 2fd0a4d32..87105f39c 100644
--- a/backend/pkg/scheduler/scheduler.go
+++ b/backend/pkg/scheduler/scheduler.go
@@ -45,7 +45,17 @@ func NewJobScheduler(ctx context.Context, coordinator *runs.Coordinator, locatio
location = time.UTC
}
lifetime, cancel := context.WithCancel(ctx)
- return &jobSchedulerInternal{context: lifetime, cancel: cancel, location: location, coordinator: coordinator, jobsByID: map[string]st.Job{}, watchers: map[string]st.BusWatcher{}, allWatchers: map[string]watcherRegistrationInternal{}, supervisors: map[string]*watcherSupervisorInternal{}}, nil
+ return &jobSchedulerInternal{
+ context: lifetime,
+ cancel: cancel,
+ location: location,
+ coordinator: coordinator,
+ jobsByID: map[string]st.Job{},
+ watchers: map[string]st.BusWatcher{},
+ allWatchers: map[string]watcherRegistrationInternal{},
+ supervisors: map[string]*watcherSupervisorInternal{},
+ },
+ nil
}
func (js *jobSchedulerInternal) RegisterJob(job st.Job) error {
@@ -135,15 +145,15 @@ func (js *jobSchedulerInternal) StartScheduler(ctx context.Context) error {
_, watching := js.watchers[record.JobID]
js.mu.RUnlock()
if record.EnvironmentID == "0" && record.Schedule != "" && !js.HasJob(record.JobID) && !watching {
- if err := js.coordinator.Checkpoint(ctx, record.JobID, "", time.Time{}); err != nil {
- return err
+ if checkpointErr := js.coordinator.Checkpoint(ctx, record.JobID, "", time.Time{}); checkpointErr != nil {
+ return checkpointErr
}
}
}
var schedulingErr error
for _, job := range js.ListRegisteredJobs() {
- if err := js.installInternal(ctx, job); err != nil {
- schedulingErr = errors.Join(schedulingErr, fmt.Errorf("%s: %w", "schedule "+job.Name(), err))
+ if installErr := js.installInternal(ctx, job); installErr != nil {
+ schedulingErr = errors.Join(schedulingErr, fmt.Errorf("%s: %w", "schedule "+job.Name(), installErr))
}
}
return schedulingErr
diff --git a/backend/pkg/scheduler/scheduler_test.go b/backend/pkg/scheduler/scheduler_test.go
index 78edd03cc..2dfd9e26e 100644
--- a/backend/pkg/scheduler/scheduler_test.go
+++ b/backend/pkg/scheduler/scheduler_test.go
@@ -95,7 +95,7 @@ func (j *conditionalTestSchedulerJob) ShouldSchedule(ctx context.Context) bool {
}
func TestJobScheduler_StartScheduler_SkipsDisabledConditionalJobs(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
job := &conditionalTestSchedulerJob{
testSchedulerJob: &testSchedulerJob{
@@ -117,7 +117,7 @@ func TestJobScheduler_StartScheduler_SkipsDisabledConditionalJobs(t *testing.T)
}
func TestJobScheduler_StartScheduler_ReportsInvalidJobSchedule(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
invalid := &testSchedulerJob{name: "invalid-startup-job", schedule: "not a cron schedule"}
valid := &testSchedulerJob{name: "valid-startup-job", schedule: "*/1 * * * * *"}
@@ -135,7 +135,7 @@ func TestJobScheduler_StartScheduler_ReportsInvalidJobSchedule(t *testing.T) {
}
func TestJobScheduler_StopWaitsForBusWatchers(t *testing.T) {
- ctx, cancel := context.WithCancel(context.Background())
+ ctx, cancel := context.WithCancel(t.Context())
js := newJobSchedulerForTestInternal(t, ctx, nil)
watcher := &testBusWatcherInternal{
name: "test-bus-watcher",
@@ -154,7 +154,7 @@ func TestJobScheduler_StopWaitsForBusWatchers(t *testing.T) {
}
stopDone := make(chan error, 1)
- go func() { stopDone <- js.Stop(context.Background()) }()
+ go func() { stopDone <- js.Stop(t.Context()) }()
cancel()
select {
@@ -171,7 +171,7 @@ func TestJobScheduler_StopWaitsForBusWatchers(t *testing.T) {
}
func TestJobScheduler_StopJoinsRunnerBeforeStoppingWatcher(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
watcher := &orderedStopBusWatcherInternal{
name: "ordered-stop-watcher",
started: make(chan struct{}),
@@ -206,14 +206,14 @@ func TestJobScheduler_RegisterBusWatcherManualRunOption(t *testing.T) {
require.NoError(t, js.RegisterBusWatcher(manualWatcher, true))
require.NoError(t, js.RegisterBusWatcher(automaticOnlyWatcher, false))
- runCtx := context.Background()
+ runCtx := t.Context()
require.NoError(t, js.RunBusWatcherNow(runCtx, manualWatcher.Name()))
require.Equal(t, runCtx, <-manualWatcher.ranNow)
require.Error(t, js.RunBusWatcherNow(runCtx, automaticOnlyWatcher.Name()))
}
func TestJobScheduler_RescheduleJob_RemovesEntryWhenDisabled(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
require.NoError(t, js.StartScheduler(t.Context()))
enabled := true
@@ -225,14 +225,14 @@ func TestJobScheduler_RescheduleJob_RemovesEntryWhenDisabled(t *testing.T) {
shouldSchedule: func(context.Context) bool { return enabled },
}
- require.NoError(t, js.RescheduleJob(context.Background(), job))
+ require.NoError(t, js.RescheduleJob(t.Context(), job))
state, ok := js.GetJobRuntimeState(job.Name())
require.True(t, ok)
require.True(t, state.Scheduled)
enabled = false
- require.NoError(t, js.RescheduleJob(context.Background(), job))
+ require.NoError(t, js.RescheduleJob(t.Context(), job))
state, ok = js.GetJobRuntimeState(job.Name())
require.True(t, ok)
require.False(t, state.Scheduled)
@@ -242,7 +242,7 @@ func TestJobScheduler_RescheduleJob_RemovesEntryWhenDisabled(t *testing.T) {
}
func TestJobScheduler_RescheduleJob_AddsEntryWhenEnabled(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
require.NoError(t, js.StartScheduler(t.Context()))
enabled := false
@@ -254,14 +254,14 @@ func TestJobScheduler_RescheduleJob_AddsEntryWhenEnabled(t *testing.T) {
shouldSchedule: func(context.Context) bool { return enabled },
}
- require.NoError(t, js.RescheduleJob(context.Background(), job))
+ require.NoError(t, js.RescheduleJob(t.Context(), job))
state, ok := js.GetJobRuntimeState(job.Name())
require.True(t, ok)
require.False(t, state.Scheduled)
enabled = true
- require.NoError(t, js.RescheduleJob(context.Background(), job))
+ require.NoError(t, js.RescheduleJob(t.Context(), job))
state, ok = js.GetJobRuntimeState(job.Name())
require.True(t, ok)
require.True(t, state.Scheduled)
@@ -269,7 +269,7 @@ func TestJobScheduler_RescheduleJob_AddsEntryWhenEnabled(t *testing.T) {
}
func TestJobScheduler_StartScheduler_SchedulesNonConditionalJobs(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
watcher := &testBusWatcherInternal{
name: "image-polling",
started: make(chan struct{}),
@@ -315,7 +315,7 @@ func TestJobScheduler_StartScheduler_SchedulesNonConditionalJobs(t *testing.T) {
}
func TestJobScheduler_RescheduleJob_UsesProvidedContext(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
var once sync.Once
runErrCh := make(chan error, 1)
@@ -341,7 +341,7 @@ func TestJobScheduler_RescheduleJob_UsesProvidedContext(t *testing.T) {
}
func TestJobScheduler_RescheduleJob_UsesLifecycleContextForShutdown(t *testing.T) {
- lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
+ lifecycleCtx, cancelLifecycle := context.WithCancel(t.Context())
js := newJobSchedulerForTestInternal(t, lifecycleCtx, nil)
startedCh := make(chan struct{}, 1)
@@ -381,11 +381,11 @@ func TestJobScheduler_RescheduleJob_UsesLifecycleContextForShutdown(t *testing.T
}
func TestJobScheduler_AddJob_UpsertReplacesEntryWithoutLeaking(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
require.NoError(t, js.StartScheduler(t.Context()))
job := &testSchedulerJob{name: "dyn-upsert", schedule: "*/5 * * * * *"}
- require.NoError(t, js.AddJob(context.Background(), job))
+ require.NoError(t, js.AddJob(t.Context(), job))
require.True(t, js.HasJob(job.Name()))
requireScheduledJobInternal(t, js, job.Name())
firstState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
@@ -394,7 +394,7 @@ func TestJobScheduler_AddJob_UpsertReplacesEntryWithoutLeaking(t *testing.T) {
// Re-adding with a changed schedule (e.g. a new sync interval) must replace the
// existing cron entry, not leak a second one that keeps firing forever.
job.schedule = "*/10 * * * * *"
- require.NoError(t, js.AddJob(context.Background(), job))
+ require.NoError(t, js.AddJob(t.Context(), job))
requireScheduledJobInternal(t, js, job.Name())
nextState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
require.NoError(t, err)
@@ -408,18 +408,18 @@ func TestJobScheduler_AddJob_UpsertReplacesEntryWithoutLeaking(t *testing.T) {
}
func TestJobScheduler_AddJob_InvalidRescheduleKeepsExistingEntry(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
require.NoError(t, js.StartScheduler(t.Context()))
job := &testSchedulerJob{name: "dyn-invalid-reschedule", schedule: "*/5 * * * * *"}
- require.NoError(t, js.AddJob(context.Background(), job))
+ require.NoError(t, js.AddJob(t.Context(), job))
require.True(t, js.HasJob(job.Name()))
requireScheduledJobInternal(t, js, job.Name())
firstState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
require.NoError(t, err)
job.schedule = "not a cron schedule"
- require.Error(t, js.AddJob(context.Background(), job))
+ require.Error(t, js.AddJob(t.Context(), job))
require.True(t, js.HasJob(job.Name()))
nextState, err := js.coordinator.ScheduleState(t.Context(), job.Name())
require.NoError(t, err)
@@ -433,19 +433,19 @@ func TestJobScheduler_AddJob_InvalidRescheduleKeepsExistingEntry(t *testing.T) {
}
func TestJobScheduler_RemoveJob_RemovesEntryAndIsNoopWhenAbsent(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
require.NoError(t, js.StartScheduler(t.Context()))
// Removing an unknown job must be a safe no-op (e.g. deleting a sync that never
// had auto-sync enabled).
- js.RemoveJob(context.Background(), "never-registered")
+ js.RemoveJob(t.Context(), "never-registered")
job := &testSchedulerJob{name: "dyn-remove", schedule: "*/5 * * * * *"}
- require.NoError(t, js.AddJob(context.Background(), job))
+ require.NoError(t, js.AddJob(t.Context(), job))
require.True(t, js.HasJob(job.Name()))
requireScheduledJobInternal(t, js, job.Name())
- js.RemoveJob(context.Background(), job.Name())
+ js.RemoveJob(t.Context(), job.Name())
require.False(t, js.HasJob(job.Name()))
record, err := js.coordinator.ScheduleState(t.Context(), job.Name())
require.NoError(t, err)
@@ -453,7 +453,7 @@ func TestJobScheduler_RemoveJob_RemovesEntryAndIsNoopWhenAbsent(t *testing.T) {
}
func TestJobScheduler_AddJob_GenericJobWithoutShouldRunIsScheduled(t *testing.T) {
- js := newJobSchedulerForTestInternal(t, context.Background(), nil)
+ js := newJobSchedulerForTestInternal(t, t.Context(), nil)
require.NoError(t, js.StartScheduler(t.Context()))
job := &schedulertypes.GenericJob{
@@ -461,13 +461,13 @@ func TestJobScheduler_AddJob_GenericJobWithoutShouldRunIsScheduled(t *testing.T)
ScheduleFn: func(context.Context) string { return "@every 1m" },
RunFn: func(context.Context) (schedulertypes.Outcome, error) { return schedulertypes.Outcome{}, nil },
}
- require.NoError(t, js.AddJob(context.Background(), job))
+ require.NoError(t, js.AddJob(t.Context(), job))
require.True(t, js.HasJob(job.Name()))
requireScheduledJobInternal(t, js, job.Name())
}
func TestJobScheduler_StopWaitsForCanceledJobToFinish(t *testing.T) {
- lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
+ lifecycleCtx, cancelLifecycle := context.WithCancel(t.Context())
jobStarted := make(chan struct{}, 1)
cancellationObserved := make(chan struct{}, 1)
releaseJob := make(chan struct{}, 1)
@@ -511,7 +511,7 @@ func TestJobScheduler_StopWaitsForCanceledJobToFinish(t *testing.T) {
}
stopDone := make(chan error, 1)
- go func() { stopDone <- stopJobSchedulerForTestInternal(context.Background(), js) }()
+ go func() { stopDone <- stopJobSchedulerForTestInternal(t.Context(), js) }()
select {
case err := <-stopDone:
diff --git a/backend/pkg/scheduler/supervision.go b/backend/pkg/scheduler/supervision.go
index 20deab93a..6c6c2cc7c 100644
--- a/backend/pkg/scheduler/supervision.go
+++ b/backend/pkg/scheduler/supervision.go
@@ -159,7 +159,7 @@ func (js *jobSchedulerInternal) WatcherHealth(id string) (schedulertypes.WorkerH
supervisor.mu.Lock()
defer supervisor.mu.Unlock()
health := supervisor.health
- if watcher, ok := supervisor.watcher.(*ImageUpdateWatcher); ok && watcher.eventDegraded.Load() && health.Status == "running" {
+ if watcher, localOk := supervisor.watcher.(*ImageUpdateWatcher); localOk && watcher.eventDegraded.Load() && health.Status == "running" {
health.Status = "degraded"
health.LastError = "Docker image event subscription unavailable; polling remains active"
}
diff --git a/backend/pkg/scheduler/volume_helper_reaper_job_test.go b/backend/pkg/scheduler/volume_helper_reaper_job_test.go
index 6e81bcc42..f76eb60c3 100644
--- a/backend/pkg/scheduler/volume_helper_reaper_job_test.go
+++ b/backend/pkg/scheduler/volume_helper_reaper_job_test.go
@@ -1,9 +1,9 @@
package scheduler
import (
- "context"
"testing"
+ "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -15,16 +15,19 @@ func TestPruningVolumeHelperJob_Name(t *testing.T) {
func TestPruningVolumeHelperJob_Schedule(t *testing.T) {
job := NewPruningVolumeHelperJob(nil, nil)
// Fixed every-5-minute schedule; the idle timeout (read in Run) is the knob.
- require.Equal(t, "0 */5 * * * *", job.Schedule(context.Background()))
+ require.Equal(t, "0 */5 * * * *", job.Schedule(t.Context()))
}
func TestPruningVolumeHelperJob_Reschedule(t *testing.T) {
job := NewPruningVolumeHelperJob(nil, nil)
- require.NoError(t, job.Reschedule(context.Background()))
+ require.NoError(t, job.Reschedule(t.Context()))
}
func TestPruningVolumeHelperJob_Run_NilVolumeServiceNoPanic(t *testing.T) {
job := NewPruningVolumeHelperJob(nil, nil)
// With no volume service the run must return without panicking (defensive guard).
- require.NotPanics(t, func() { job.Run(context.Background()) })
+ require.NotPanics(t, func() {
+ _, runErr1 := job.Run(t.Context())
+ assert.NoError(t, runErr1)
+ })
}
diff --git a/backend/pkg/utils/activity_context.go b/backend/pkg/utils/activity_context.go
index 18e50e393..8f5773d1c 100644
--- a/backend/pkg/utils/activity_context.go
+++ b/backend/pkg/utils/activity_context.go
@@ -45,7 +45,7 @@ func ValidActivityBatchID(id string) bool {
// update). Invalid IDs are ignored.
func WithActivityBatchID(ctx context.Context, batchID string) context.Context {
if ctx == nil {
- ctx = context.Background()
+ ctx = context.Background() //nolint:forbidigo // Fallback preserves the existing nil-context contract when no parent is available.
}
if !ValidActivityBatchID(batchID) {
return ctx
@@ -71,7 +71,7 @@ type activityRuntimeContext struct {
// WithAppLifecycleContext marks ctx as the application lifecycle context.
func WithAppLifecycleContext(ctx context.Context) context.Context {
if ctx == nil {
- ctx = context.Background()
+ ctx = context.Background() //nolint:forbidigo // Fallback preserves the existing nil-context contract when no parent is available.
}
return context.WithValue(ctx, appLifecycleContextKey{}, true)
}
@@ -99,7 +99,7 @@ func ActivityRuntimeContext(requestCtx, appCtx context.Context) context.Context
if requestCtx != nil {
return context.WithoutCancel(requestCtx)
}
- return context.Background()
+ return context.Background() //nolint:forbidigo // Fallback preserves the existing nil-context contract when no parent is available.
}
func (c activityRuntimeContext) Deadline() (time.Time, bool) {
diff --git a/backend/pkg/utils/activity_context_test.go b/backend/pkg/utils/activity_context_test.go
index c9e06490d..e0ad81ec2 100644
--- a/backend/pkg/utils/activity_context_test.go
+++ b/backend/pkg/utils/activity_context_test.go
@@ -11,8 +11,8 @@ import (
type activityContextTestKey string
func TestActivityRuntimeContextPrefersAppContextInternal(t *testing.T) {
- requestCtx, cancelRequest := context.WithCancel(context.Background())
- appCtx, cancelApp := context.WithCancel(context.Background())
+ requestCtx, cancelRequest := context.WithCancel(t.Context())
+ appCtx, cancelApp := context.WithCancel(t.Context())
defer cancelApp()
ctx := ActivityRuntimeContext(requestCtx, appCtx)
@@ -25,8 +25,8 @@ func TestActivityRuntimeContextPrefersAppContextInternal(t *testing.T) {
}
func TestActivityRuntimeContextPreservesRequestValuesWithAppCancellationInternal(t *testing.T) {
- requestCtx, cancelRequest := context.WithCancel(context.WithValue(context.Background(), activityContextTestKey("request-id"), "req-123"))
- appCtx, cancelApp := context.WithCancel(WithAppLifecycleContext(context.Background()))
+ requestCtx, cancelRequest := context.WithCancel(context.WithValue(t.Context(), activityContextTestKey("request-id"), "req-123"))
+ appCtx, cancelApp := context.WithCancel(WithAppLifecycleContext(t.Context()))
defer cancelApp()
ctx := ActivityRuntimeContext(requestCtx, appCtx)
@@ -44,9 +44,9 @@ func TestActivityRuntimeContextPreservesRequestValuesWithAppCancellationInternal
func TestActivityRuntimeContextUsesAppDeadlineWithRequestValuesInternal(t *testing.T) {
requestDeadline := time.Now().Add(time.Hour)
appDeadline := time.Now().Add(time.Minute)
- requestCtx, cancelRequest := context.WithDeadline(context.WithValue(context.Background(), activityContextTestKey("trace-id"), "trace-123"), requestDeadline)
+ requestCtx, cancelRequest := context.WithDeadline(context.WithValue(t.Context(), activityContextTestKey("trace-id"), "trace-123"), requestDeadline)
defer cancelRequest()
- appCtx, cancelApp := context.WithDeadline(context.Background(), appDeadline)
+ appCtx, cancelApp := context.WithDeadline(t.Context(), appDeadline)
defer cancelApp()
ctx := ActivityRuntimeContext(requestCtx, appCtx)
@@ -58,7 +58,7 @@ func TestActivityRuntimeContextUsesAppDeadlineWithRequestValuesInternal(t *testi
}
func TestActivityRuntimeContextFallsBackToDetachedRequestContextInternal(t *testing.T) {
- requestCtx, cancelRequest := context.WithCancel(context.Background())
+ requestCtx, cancelRequest := context.WithCancel(t.Context())
ctx := ActivityRuntimeContext(requestCtx, nil)
@@ -67,7 +67,7 @@ func TestActivityRuntimeContextFallsBackToDetachedRequestContextInternal(t *test
}
func TestActivityRuntimeContextPreservesMarkedAppContextInternal(t *testing.T) {
- appCtx, cancelApp := context.WithCancel(WithAppLifecycleContext(context.Background()))
+ appCtx, cancelApp := context.WithCancel(WithAppLifecycleContext(t.Context()))
ctx := ActivityRuntimeContext(appCtx, nil)
@@ -76,7 +76,7 @@ func TestActivityRuntimeContextPreservesMarkedAppContextInternal(t *testing.T) {
}
func TestWithAppLifecycleContextMarksContextInternal(t *testing.T) {
- ctx := WithAppLifecycleContext(context.Background())
+ ctx := WithAppLifecycleContext(t.Context())
require.True(t, IsAppLifecycleContext(ctx))
}
diff --git a/backend/pkg/utils/backupbrowser/browser.go b/backend/pkg/utils/backupbrowser/browser.go
index cfde96180..38c3fc64d 100644
--- a/backend/pkg/utils/backupbrowser/browser.go
+++ b/backend/pkg/utils/backupbrowser/browser.go
@@ -174,7 +174,7 @@ func explicitSelectionCandidatesInternal(requestedPaths []string, eligible []bac
if expectsDirectory && !entry.IsDirectory {
return nil, fmt.Errorf("%s is a file, not a folder", normalized)
}
- if _, exists := seen[normalized]; exists {
+ if _, localExists := seen[normalized]; localExists {
continue
}
seen[normalized] = struct{}{}
diff --git a/backend/pkg/utils/cookie/cookie_util.go b/backend/pkg/utils/cookie/cookie_util.go
index cc1f0efb7..ab0c4af04 100644
--- a/backend/pkg/utils/cookie/cookie_util.go
+++ b/backend/pkg/utils/cookie/cookie_util.go
@@ -79,8 +79,8 @@ func readTokenCookieInternal(r *http.Request, base string) (string, error) {
var value strings.Builder
value.WriteString(first)
for i := 1; ; i++ {
- chunk, ok := byName[tokenCookieChunkNameInternal(base, i)]
- if !ok {
+ chunk, localOk := byName[tokenCookieChunkNameInternal(base, i)]
+ if !localOk {
break
}
value.WriteString(chunk)
diff --git a/backend/pkg/utils/cookie/cookie_util_test.go b/backend/pkg/utils/cookie/cookie_util_test.go
index 6e647755e..1fb3af548 100644
--- a/backend/pkg/utils/cookie/cookie_util_test.go
+++ b/backend/pkg/utils/cookie/cookie_util_test.go
@@ -13,19 +13,19 @@ import (
func TestSecureCookieFromRequest(t *testing.T) {
t.Run("plain http returns false", func(t *testing.T) {
- req := httptest.NewRequest("GET", "http://example.com/", nil)
+ req := httptest.NewRequest("GET", "http://example.com/", http.NoBody)
assert.False(t, SecureCookieFromRequest(req))
})
t.Run("X-Forwarded-Proto https is not trusted directly", func(t *testing.T) {
- req := httptest.NewRequest("GET", "http://example.com/", nil)
+ req := httptest.NewRequest("GET", "http://example.com/", http.NoBody)
req.Header.Set("X-Forwarded-Proto", "https")
assert.False(t, SecureCookieFromRequest(req))
})
t.Run("secure cookie context returns true", func(t *testing.T) {
- req := httptest.NewRequest("GET", "http://example.com/", nil)
- req = req.WithContext(context.WithValue(context.Background(), SecureCookieContextKey{}, true))
+ req := httptest.NewRequest("GET", "http://example.com/", http.NoBody)
+ req = req.WithContext(context.WithValue(t.Context(), SecureCookieContextKey{}, true))
assert.True(t, SecureCookieFromRequest(req))
})
}
@@ -62,7 +62,7 @@ func TestBuildTokenCookieStringFor(t *testing.T) {
token := strings.Repeat("a", tokenCookieChunkSize) + strings.Repeat("b", tokenCookieChunkSize) + "tail"
headers := BuildTokenCookieStringFor(60, token, true)
- req := httptest.NewRequest("GET", "https://example.com/", nil)
+ req := httptest.NewRequest("GET", "https://example.com/", http.NoBody)
for _, c := range readSetCookieHeadersInternal(t, headers...) {
if c.MaxAge >= 0 {
req.AddCookie(&http.Cookie{Name: c.Name, Value: c.Value})
diff --git a/backend/pkg/utils/dbutil/dbutil_test.go b/backend/pkg/utils/dbutil/dbutil_test.go
index 13f42856c..59e66d368 100644
--- a/backend/pkg/utils/dbutil/dbutil_test.go
+++ b/backend/pkg/utils/dbutil/dbutil_test.go
@@ -1,7 +1,6 @@
package dbutil
import (
- "context"
"errors"
"testing"
@@ -29,7 +28,7 @@ func TestFirstWhereFound(t *testing.T) {
db := newTestDB(t)
require.NoError(t, db.Create(&widget{ID: "w-1", Name: "alpha"}).Error)
- got, err := FirstWhere[widget](context.Background(), db, errWidgetNotFound, "name = ?", "alpha")
+ got, err := FirstWhere[widget](t.Context(), db, errWidgetNotFound, "name = ?", "alpha")
require.NoError(t, err)
require.Equal(t, "w-1", got.ID)
}
@@ -37,14 +36,14 @@ func TestFirstWhereFound(t *testing.T) {
func TestFirstWhereNotFoundReturnsSentinel(t *testing.T) {
db := newTestDB(t)
- _, err := FirstWhere[widget](context.Background(), db, errWidgetNotFound, "name = ?", "missing")
+ _, err := FirstWhere[widget](t.Context(), db, errWidgetNotFound, "name = ?", "missing")
require.ErrorIs(t, err, errWidgetNotFound)
}
func TestFirstWhereNotFoundWithNilSentinel(t *testing.T) {
db := newTestDB(t)
- _, err := FirstWhere[widget](context.Background(), db, nil, "name = ?", "missing")
+ _, err := FirstWhere[widget](t.Context(), db, nil, "name = ?", "missing")
require.Error(t, err)
require.ErrorIs(t, err, gorm.ErrRecordNotFound)
}
@@ -52,12 +51,12 @@ func TestFirstWhereNotFoundWithNilSentinel(t *testing.T) {
func TestWithTxCommit(t *testing.T) {
db := newTestDB(t)
- err := WithTx(context.Background(), db, func(tx *gorm.DB) error {
+ err := WithTx(t.Context(), db, func(tx *gorm.DB) error {
return tx.Create(&widget{ID: "w-1", Name: "alpha"}).Error
})
require.NoError(t, err)
- got, err := FirstWhere[widget](context.Background(), db, errWidgetNotFound, "id = ?", "w-1")
+ got, err := FirstWhere[widget](t.Context(), db, errWidgetNotFound, "id = ?", "w-1")
require.NoError(t, err)
require.Equal(t, "alpha", got.Name)
}
@@ -66,7 +65,7 @@ func TestWithTxRollback(t *testing.T) {
db := newTestDB(t)
boom := errors.New("boom")
- err := WithTx(context.Background(), db, func(tx *gorm.DB) error {
+ err := WithTx(t.Context(), db, func(tx *gorm.DB) error {
if err := tx.Create(&widget{ID: "w-1", Name: "alpha"}).Error; err != nil {
return err
}
@@ -74,6 +73,6 @@ func TestWithTxRollback(t *testing.T) {
})
require.ErrorIs(t, err, boom)
- _, err = FirstWhere[widget](context.Background(), db, errWidgetNotFound, "id = ?", "w-1")
+ _, err = FirstWhere[widget](t.Context(), db, errWidgetNotFound, "id = ?", "w-1")
require.ErrorIs(t, err, errWidgetNotFound)
}
diff --git a/backend/pkg/utils/francis/runtime.go b/backend/pkg/utils/francis/runtime.go
index a49585f5b..e490e8159 100644
--- a/backend/pkg/utils/francis/runtime.go
+++ b/backend/pkg/utils/francis/runtime.go
@@ -73,8 +73,8 @@ func New(databaseURL, encryptionKey, instanceID, port string, options ...local.H
names: &runtime.actorNames,
})))
if encryptionKey != "" && instanceID != "" {
- if err := runtime.ConfigureIdentity(encryptionKey, instanceID); err != nil {
- return nil, err
+ if configureIdentityErr := runtime.ConfigureIdentity(encryptionKey, instanceID); configureIdentityErr != nil {
+ return nil, configureIdentityErr
}
}
runtime.options = append(runtime.options, options...)
@@ -148,24 +148,24 @@ func (r *Runtime) Start(ctx, appCtx context.Context, onFailure func(error)) erro
bindRetries := 0
for {
- host, errCh, err := r.runHostInternal(runCtx)
- if err != nil {
+ host, errCh, runHostErr := r.runHostInternal(runCtx)
+ if runHostErr != nil {
cancel()
- r.finishInternal(err)
- return err
+ r.finishInternal(runHostErr)
+ return runHostErr
}
select {
case <-host.Ready():
- err = waitForPeerInternal(startupCtx, r.address, errCh)
- if err != nil {
- if errors.Is(err, syscall.EADDRINUSE) && bindRetries < 3 {
+ runHostErr = waitForPeerInternal(startupCtx, r.address, errCh)
+ if runHostErr != nil {
+ if errors.Is(runHostErr, syscall.EADDRINUSE) && bindRetries < 3 {
<-errCh
bindRetries++
continue
}
cancel()
r.finishInternal(<-errCh)
- return err
+ return runHostErr
}
select {
case runErr := <-errCh:
@@ -176,17 +176,17 @@ func (r *Runtime) Start(ctx, appCtx context.Context, onFailure func(error)) erro
}
r.publishReadyInternal(runCtx, host, errCh, onFailure)
return nil
- case err = <-errCh:
- if errors.Is(err, syscall.EADDRINUSE) && bindRetries < 3 {
+ case runHostErr = <-errCh:
+ if errors.Is(runHostErr, syscall.EADDRINUSE) && bindRetries < 3 {
bindRetries++
continue
}
- if !errors.Is(err, components.ErrClusterFull) && !errors.Is(err, components.ErrHostAlreadyRegistered) {
+ if !errors.Is(runHostErr, components.ErrClusterFull) && !errors.Is(runHostErr, components.ErrHostAlreadyRegistered) {
cancel()
- r.finishInternal(err)
- return err
+ r.finishInternal(runHostErr)
+ return runHostErr
}
- slog.WarnContext(ctx, "Waiting for the previous actor host registration to expire", "error", err)
+ slog.WarnContext(ctx, "Waiting for the previous actor host registration to expire", "error", runHostErr)
case <-startupCtx.Done():
cancel()
r.finishInternal(<-errCh)
@@ -202,9 +202,9 @@ func (r *Runtime) Start(ctx, appCtx context.Context, onFailure func(error)) erro
case <-startupCtx.Done():
timer.Stop()
cancel()
- err = fmt.Errorf("another Arcane process owns this database or its registration has not expired: %w", startupCtx.Err())
- r.finishInternal(err)
- return err
+ runHostErr = fmt.Errorf("another Arcane process owns this database or its registration has not expired: %w", startupCtx.Err())
+ r.finishInternal(runHostErr)
+ return runHostErr
}
}
}
@@ -215,19 +215,19 @@ func (r *Runtime) runHostInternal(ctx context.Context) (*local.Host, chan error,
return nil, nil, err
}
for _, registration := range r.registrations {
- if err := host.RegisterActor(registration.actorType, registration.factory, registration.options...); err != nil {
+ if registerActorErr := host.RegisterActor(registration.actorType, registration.factory, registration.options...); registerActorErr != nil {
// Running a canceled host closes its provider-owned connections.
cleanupCtx, cancel := context.WithCancel(ctx)
cancel()
if cleanupErr := host.Run(cleanupCtx); cleanupErr != nil {
- return nil, nil, errors.Join(err, fmt.Errorf("clean up unregistered actor host: %w", cleanupErr))
+ return nil, nil, errors.Join(registerActorErr, fmt.Errorf("clean up unregistered actor host: %w", cleanupErr))
}
- return nil, nil, err
+ return nil, nil, registerActorErr
}
}
- errors := make(chan error, 1)
- go func() { errors <- host.Run(ctx) }()
- return host, errors, nil
+ localErrors := make(chan error, 1)
+ go func() { localErrors <- host.Run(ctx) }()
+ return host, localErrors, nil
}
func (r *Runtime) publishReadyInternal(ctx context.Context, host *local.Host, runErrors <-chan error, onFailure func(error)) {
@@ -280,8 +280,8 @@ func waitForPeerInternal(ctx context.Context, address string, runErrors chan err
connection, err := quic.DialAddr(probeCtx, address, tlsConfig, &quic.Config{})
cancel()
if connection != nil {
- if err := connection.CloseWithError(0, "readiness probe complete"); err != nil {
- return fmt.Errorf("close actor readiness probe: %w", err)
+ if closeWithErrorErr := connection.CloseWithError(0, "readiness probe complete"); closeWithErrorErr != nil {
+ return fmt.Errorf("close actor readiness probe: %w", closeWithErrorErr)
}
return nil
}
diff --git a/backend/pkg/utils/francis/testing/host.go b/backend/pkg/utils/francis/testing/host.go
index 8b70c91f4..c8d6af7a1 100644
--- a/backend/pkg/utils/francis/testing/host.go
+++ b/backend/pkg/utils/francis/testing/host.go
@@ -25,11 +25,16 @@ func New(t stdtesting.TB, databaseURLs ...string) *francis.Runtime {
t.Fatal(err)
}
port := strings.TrimPrefix(listener.LocalAddr().String(), "127.0.0.1:")
- if err := listener.Close(); err != nil {
- t.Fatal(err)
+ if closeErr := listener.Close(); closeErr != nil {
+ t.Fatal(closeErr)
}
databaseURL := "file:actor-test-unused.db"
- options := []local.HostOption{local.WithShutdownGracePeriod(time.Second), local.WithAlarmsPollInterval(110 * time.Millisecond), local.WithAlarmsFetchAheadInterval(time.Second), local.WithAlarmsLeaseDuration(2 * time.Second)}
+ options := []local.HostOption{
+ local.WithShutdownGracePeriod(time.Second),
+ local.WithAlarmsPollInterval(110 * time.Millisecond),
+ local.WithAlarmsFetchAheadInterval(time.Second),
+ local.WithAlarmsLeaseDuration(2 * time.Second),
+ }
if len(databaseURLs) > 0 {
databaseURL = databaseURLs[0]
} else {
diff --git a/backend/pkg/utils/handlerutil/feature_test.go b/backend/pkg/utils/handlerutil/feature_test.go
index da0b34d2a..5f0dee726 100644
--- a/backend/pkg/utils/handlerutil/feature_test.go
+++ b/backend/pkg/utils/handlerutil/feature_test.go
@@ -29,7 +29,12 @@ func TestFeatureDisabledError(t *testing.T) {
require.Equal(t, tt.wantContentType, err.ContentType(tt.contentType))
encoded, marshalErr := json.Marshal(err)
require.NoError(t, marshalErr)
- require.JSONEq(t, `{"status":403,"title":"Forbidden","detail":"feature vulnerabilityManagement is disabled","code":"feature_disabled","feature":"vulnerabilityManagement"}`, string(encoded))
+ require.JSONEq(
+ t,
+ "{\"status\":403,\"title\":\"Forbidden\",\"detail\":\"feature vulnerabilityManagement is disabled\",\"code\":\"fea"+
+ "ture_disabled\",\"feature\":\"vulnerabilityManagement\"}",
+ string(encoded),
+ )
})
}
}
diff --git a/backend/pkg/utils/handlerutil/remote_proxy.go b/backend/pkg/utils/handlerutil/remote_proxy.go
index 5b910e681..a3bf2b95a 100644
--- a/backend/pkg/utils/handlerutil/remote_proxy.go
+++ b/backend/pkg/utils/handlerutil/remote_proxy.go
@@ -28,8 +28,8 @@ func (p RemoteJSONProxy) JSON[T any](
}
var output T
- if err := p(ctx, environmentID, method, path, body, &output); err != nil {
- return nil, TranslateRemoteProxyError(err)
+ if pErr := p(ctx, environmentID, method, path, body, &output); pErr != nil {
+ return nil, TranslateRemoteProxyError(pErr)
}
return &output, nil
diff --git a/backend/pkg/utils/httpx/conn_context_test.go b/backend/pkg/utils/httpx/conn_context_test.go
index dcbd9b656..868348d46 100644
--- a/backend/pkg/utils/httpx/conn_context_test.go
+++ b/backend/pkg/utils/httpx/conn_context_test.go
@@ -20,7 +20,7 @@ func newConnContextForTest(t *testing.T) context.Context {
require.NoError(t, err)
t.Cleanup(func() { _ = conn.Close() })
- return WithConn(context.Background(), conn)
+ return WithConn(t.Context(), conn)
}
// HTTP/2 multiplexes the dashboard and activity streams onto one connection, so
@@ -53,7 +53,7 @@ func TestAcquireDeadPeerTimeoutHoldsUntilLastRelease(t *testing.T) {
// never passed through WithConn) must degrade quietly rather than fail the
// stream.
func TestAcquireDeadPeerTimeoutIgnoresMissingConn(t *testing.T) {
- release, err := AcquireDeadPeerTimeout(context.Background(), 45*time.Second)
+ release, err := AcquireDeadPeerTimeout(t.Context(), 45*time.Second)
require.NoError(t, err)
require.NotPanics(t, release)
}
diff --git a/backend/pkg/utils/httpx/request_test.go b/backend/pkg/utils/httpx/request_test.go
index a75e547c6..88137ef9d 100644
--- a/backend/pkg/utils/httpx/request_test.go
+++ b/backend/pkg/utils/httpx/request_test.go
@@ -1,6 +1,7 @@
package httpx
import (
+ "net/http"
"net/http/httptest"
"testing"
@@ -24,7 +25,7 @@ func TestIsWebSocketUpgradeRequest(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- r := httptest.NewRequest("GET", "/", nil)
+ r := httptest.NewRequest("GET", "/", http.NoBody)
if tt.connection != "" {
r.Header.Set("Connection", tt.connection)
}
diff --git a/backend/pkg/utils/httpx/safe_remote.go b/backend/pkg/utils/httpx/safe_remote.go
index 2053530fb..ca282c40a 100644
--- a/backend/pkg/utils/httpx/safe_remote.go
+++ b/backend/pkg/utils/httpx/safe_remote.go
@@ -58,16 +58,29 @@ func ValidateSafeRemoteURL(ctx context.Context, rawURL string, lookupIP LookupIP
scheme := strings.ToLower(parsed.Scheme)
if scheme != "http" && scheme != "https" {
- return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", fmt.Errorf("unsupported URL scheme %q", scheme))) //nolint:staticcheck // Preserve the existing error message.
+ //nolint:staticcheck // Preserve the existing error message.
+ return nil,
+ common.Classify(common.ErrUnsafeRemoteURL,
+ fmt.Errorf("Remote URL is not allowed: %w",
+ fmt.Errorf("unsupported URL scheme %q",
+ scheme)))
}
if parsed.User != nil {
- return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", errors.New("URL credentials are not allowed"))) //nolint:staticcheck // Preserve the existing error message.
+ //nolint:staticcheck // Preserve the existing error message.
+ return nil,
+ common.Classify(common.ErrUnsafeRemoteURL,
+ fmt.Errorf("Remote URL is not allowed: %w",
+ errors.New("URL credentials are not allowed")))
}
host := parsed.Hostname()
if host == "" || isBlockedHostnameInternal(host) {
- return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", errors.New("missing or blocked hostname"))) //nolint:staticcheck // Preserve the existing error message.
+ //nolint:staticcheck // Preserve the existing error message.
+ return nil,
+ common.Classify(common.ErrUnsafeRemoteURL,
+ fmt.Errorf("Remote URL is not allowed: %w",
+ errors.New("missing or blocked hostname")))
}
ips, err := resolveAllowedIPsInternal(ctx, host, lookupIP)
@@ -104,14 +117,14 @@ func NewSafeOutboundHTTPClient(base *http.Client, lookupIP LookupIPFunc) (*http.
}
transport.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
- host, port, err := net.SplitHostPort(address)
- if err != nil {
- return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", err)) //nolint:staticcheck // Preserve the existing error message.
+ host, port, splitHostPortErr := net.SplitHostPort(address)
+ if splitHostPortErr != nil {
+ return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", splitHostPortErr)) //nolint:staticcheck // Preserve the existing error message.
}
- ips, err := resolveAllowedIPsInternal(ctx, host, lookupIP)
- if err != nil {
- return nil, err
+ ips, splitHostPortErr := resolveAllowedIPsInternal(ctx, host, lookupIP)
+ if splitHostPortErr != nil {
+ return nil, splitHostPortErr
}
var lastErr error
@@ -135,8 +148,8 @@ func NewSafeOutboundHTTPClient(base *http.Client, lookupIP LookupIPFunc) (*http.
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
- if _, err := ValidateSafeRemoteURL(req.Context(), req.URL.String(), lookupIP); err != nil {
- return err
+ if _, validateSafeRemoteURLErr := ValidateSafeRemoteURL(req.Context(), req.URL.String(), lookupIP); validateSafeRemoteURLErr != nil {
+ return validateSafeRemoteURLErr
}
if base.CheckRedirect != nil {
return base.CheckRedirect(req, via)
@@ -165,7 +178,12 @@ func cloneHTTPTransportInternal(base http.RoundTripper) (*http.Transport, error)
func resolveAllowedIPsInternal(ctx context.Context, host string, lookupIP LookupIPFunc) ([]net.IP, error) {
if parsedIP := parseIPLiteralInternal(host); parsedIP != nil {
if isBlockedIPInternal(parsedIP) {
- return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", fmt.Errorf("blocked IP address %s", parsedIP))) //nolint:staticcheck // Preserve the existing error message.
+ //nolint:staticcheck // Preserve the existing error message.
+ return nil,
+ common.Classify(common.ErrUnsafeRemoteURL,
+ fmt.Errorf("Remote URL is not allowed: %w",
+ fmt.Errorf("blocked IP address %s",
+ parsedIP)))
}
return []net.IP{parsedIP}, nil
}
@@ -181,13 +199,22 @@ func resolveAllowedIPsInternal(ctx context.Context, host string, lookupIP Lookup
continue
}
if isBlockedIPInternal(ip) {
- return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", fmt.Errorf("blocked IP address %s", ip))) //nolint:staticcheck // Preserve the existing error message.
+ //nolint:staticcheck // Preserve the existing error message.
+ return nil,
+ common.Classify(common.ErrUnsafeRemoteURL,
+ fmt.Errorf("Remote URL is not allowed: %w",
+ fmt.Errorf("blocked IP address %s",
+ ip)))
}
allowed = append(allowed, ip)
}
if len(allowed) == 0 {
- return nil, common.Classify(common.ErrUnsafeRemoteURL, fmt.Errorf("Remote URL is not allowed: %w", errors.New("host did not resolve to an allowed IP"))) //nolint:staticcheck // Preserve the existing error message.
+ //nolint:staticcheck // Preserve the existing error message.
+ return nil,
+ common.Classify(common.ErrUnsafeRemoteURL,
+ fmt.Errorf("Remote URL is not allowed: %w",
+ errors.New("host did not resolve to an allowed IP")))
}
return allowed, nil
diff --git a/backend/pkg/utils/httpx/safe_remote_test.go b/backend/pkg/utils/httpx/safe_remote_test.go
index 2e3642d1a..d6446cedd 100644
--- a/backend/pkg/utils/httpx/safe_remote_test.go
+++ b/backend/pkg/utils/httpx/safe_remote_test.go
@@ -45,7 +45,7 @@ func TestValidateSafeRemoteURL(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- parsed, err := ValidateSafeRemoteURL(context.Background(), tt.rawURL, lookupIP)
+ parsed, err := ValidateSafeRemoteURL(t.Context(), tt.rawURL, lookupIP)
if tt.wantErr {
require.Error(t, err)
require.ErrorIs(t, err, common.ErrUnsafeRemoteURL)
diff --git a/backend/pkg/utils/imageref/update_lookup_test.go b/backend/pkg/utils/imageref/update_lookup_test.go
index 4088289c9..2fe281f47 100644
--- a/backend/pkg/utils/imageref/update_lookup_test.go
+++ b/backend/pkg/utils/imageref/update_lookup_test.go
@@ -8,13 +8,29 @@ import (
)
func TestIsUpdateCheckDisabled(t *testing.T) {
- for value, want := range map[string]bool{"false": true, "0": true, "no": true, " OFF ": true, "true": false, "yes": false, "": false, "maybe": false} {
+ for value, want := range map[string]bool{"false": true, "0": true, "no": true, "true": false, "yes": false, "": false, "maybe": false} {
require.Equal(t, want, IsUpdateCheckDisabled(map[string]string{UpdateCheckLabel: value}), "value %q", value)
}
+ require.True(t, IsUpdateCheckDisabled(map[string]string{UpdateCheckLabel: " OFF "}), "values are trimmed")
require.True(t, IsUpdateCheckDisabled(map[string]string{"COM.GETARCANEAPP.ARCANE.UPDATE-CHECK": "false"}), "label names match case-insensitively")
for range 50 {
- require.False(t, IsUpdateCheckDisabled(map[string]string{UpdateCheckLabel: "true", "COM.GETARCANEAPP.ARCANE.UPDATE-CHECK": "false", "Com.GetArcaneApp.Arcane.Update-Check": "false"}), "the canonical key wins over other spellings")
- require.True(t, IsUpdateCheckDisabled(map[string]string{"COM.GETARCANEAPP.ARCANE.UPDATE-CHECK": "false", "com.getarcaneapp.arcane.Update-Check": "true"}), "conflicting spellings resolve deterministically")
+ require.False(
+ t,
+ IsUpdateCheckDisabled(map[string]string{
+ UpdateCheckLabel: "true",
+ "COM.GETARCANEAPP.ARCANE.UPDATE-CHECK": "false",
+ "Com.GetArcaneApp.Arcane.Update-Check": "false",
+ }),
+ "the canonical key wins over other spellings",
+ )
+ require.True(
+ t,
+ IsUpdateCheckDisabled(map[string]string{
+ "COM.GETARCANEAPP.ARCANE.UPDATE-CHECK": "false",
+ "com.getarcaneapp.arcane.Update-Check": "true",
+ }),
+ "conflicting spellings resolve deterministically",
+ )
}
require.False(t, IsUpdateCheckDisabled(nil))
require.False(t, IsUpdateCheckDisabled(map[string]string{labels.LabelUpdater: "false"}), "the updater label only governs installation")
@@ -26,5 +42,18 @@ func TestUpdatePolicyKeyTracksMonitoringNotInstallation(t *testing.T) {
unmonitored := map[string]string{labels.LabelUpdateStrategy: "tag", labels.LabelUpdateConstraint: "3.x", UpdateCheckLabel: "false"}
require.Equal(t, UpdatePolicyKey("example:3.1.0", base), UpdatePolicyKey("example:3.1.0", installExcluded), "changing installation eligibility keeps results current")
require.NotEqual(t, UpdatePolicyKey("example:3.1.0", base), UpdatePolicyKey("example:3.1.0", unmonitored), "changing monitoring eligibility invalidates results")
- require.NotEqual(t, UpdatePolicyKey("example:3.1.0", base), UpdatePolicyKey("example:3.1.0", map[string]string{labels.LabelUpdateStrategy: "tag", labels.LabelUpdateConstraint: "4.x"}))
+ require.NotEqual(
+ t,
+ UpdatePolicyKey(
+ "example:3.1.0",
+ base,
+ ),
+ UpdatePolicyKey(
+ "example:3.1.0",
+ map[string]string{
+ labels.LabelUpdateStrategy: "tag",
+ labels.LabelUpdateConstraint: "4.x",
+ },
+ ),
+ )
}
diff --git a/backend/pkg/utils/jwtclaims/jwt.go b/backend/pkg/utils/jwtclaims/jwt.go
index b385c3189..a9eb734b9 100644
--- a/backend/pkg/utils/jwtclaims/jwt.go
+++ b/backend/pkg/utils/jwtclaims/jwt.go
@@ -51,7 +51,7 @@ func GetStringSliceClaim(m map[string]any, key string) []string {
if !ok || v == nil {
return nil
}
- if t, ok := v.(string); ok {
+ if t, localOk := v.(string); localOk {
s := strings.TrimSpace(t)
if s == "" {
return nil
diff --git a/backend/pkg/utils/logging/logrus_bridge.go b/backend/pkg/utils/logging/logrus_bridge.go
index fcb1fdc79..5da040dbb 100644
--- a/backend/pkg/utils/logging/logrus_bridge.go
+++ b/backend/pkg/utils/logging/logrus_bridge.go
@@ -73,7 +73,7 @@ func (logrusSlogHook) Fire(entry *logrus.Entry) error {
ctx := entry.Context
if ctx == nil {
- ctx = context.Background()
+ ctx = context.Background() //nolint:forbidigo // Legacy log entry has no context; logging still needs an empty root.
}
message := strings.TrimSpace(entry.Message)
slog.Log(ctx, level, message, args...)
diff --git a/backend/pkg/utils/notifications/config_credentials.go b/backend/pkg/utils/notifications/config_credentials.go
index 4f1446936..5a4a870b1 100644
--- a/backend/pkg/utils/notifications/config_credentials.go
+++ b/backend/pkg/utils/notifications/config_credentials.go
@@ -19,8 +19,8 @@ func DecodeConfig[T any](config database.JSON, providerName string) (T, error) {
if err != nil {
return out, fmt.Errorf("failed to marshal %s config: %w", providerName, err)
}
- if err := json.Unmarshal(configBytes, &out); err != nil {
- return out, fmt.Errorf("failed to unmarshal %s config: %w", providerName, err)
+ if unmarshalErr := json.Unmarshal(configBytes, &out); unmarshalErr != nil {
+ return out, fmt.Errorf("failed to unmarshal %s config: %w", providerName, unmarshalErr)
}
return out, nil
}
@@ -62,8 +62,8 @@ func PrepareSlackConfig(config database.JSON, providerName string, requireToken
if requireToken && slackConfig.Token == "" {
return SlackConfig{}, errors.New("slack token not configured")
}
- if err := DecryptStringCredential(&slackConfig.Token); err != nil {
- return SlackConfig{}, err
+ if decryptStringCredentialErr := DecryptStringCredential(&slackConfig.Token); decryptStringCredentialErr != nil {
+ return SlackConfig{}, decryptStringCredentialErr
}
return slackConfig, nil
}
@@ -83,8 +83,8 @@ func PrepareNtfyConfig(config database.JSON, providerName string, requireTopic b
if _, ok := config["firebase"]; !ok {
ntfyConfig.Firebase = true
}
- if err := DecryptStringCredential(&ntfyConfig.Password); err != nil {
- return NtfyConfig{}, err
+ if decryptStringCredentialErr := DecryptStringCredential(&ntfyConfig.Password); decryptStringCredentialErr != nil {
+ return NtfyConfig{}, decryptStringCredentialErr
}
return ntfyConfig, nil
}
@@ -95,8 +95,8 @@ func PreparePushoverConfig(config database.JSON, providerName string) (PushoverC
if err != nil {
return PushoverConfig{}, err
}
- if err := DecryptStringCredential(&pushoverConfig.Token); err != nil {
- return PushoverConfig{}, err
+ if decryptStringCredentialErr := DecryptStringCredential(&pushoverConfig.Token); decryptStringCredentialErr != nil {
+ return PushoverConfig{}, decryptStringCredentialErr
}
return pushoverConfig, nil
}
@@ -107,8 +107,8 @@ func PrepareGotifyConfig(config database.JSON, providerName string) (GotifyConfi
if err != nil {
return GotifyConfig{}, err
}
- if err := DecryptStringCredential(&gotifyConfig.Token); err != nil {
- return GotifyConfig{}, err
+ if decryptStringCredentialErr := DecryptStringCredential(&gotifyConfig.Token); decryptStringCredentialErr != nil {
+ return GotifyConfig{}, decryptStringCredentialErr
}
return gotifyConfig, nil
}
@@ -119,8 +119,8 @@ func PrepareMatrixConfig(config database.JSON) (MatrixConfig, error) {
if err != nil {
return MatrixConfig{}, err
}
- if err := DecryptStringCredential(&matrixConfig.Password); err != nil {
- return MatrixConfig{}, err
+ if decryptStringCredentialErr := DecryptStringCredential(&matrixConfig.Password); decryptStringCredentialErr != nil {
+ return MatrixConfig{}, decryptStringCredentialErr
}
return matrixConfig, nil
}
diff --git a/backend/pkg/utils/notifications/deliver.go b/backend/pkg/utils/notifications/deliver.go
index 10187ebf5..520ff029f 100644
--- a/backend/pkg/utils/notifications/deliver.go
+++ b/backend/pkg/utils/notifications/deliver.go
@@ -75,11 +75,11 @@ func deliverDiscord(ctx context.Context, config database.JSON, c Content) error
if discordConfig.WebhookID == "" || discordConfig.Token == "" {
return errors.New("discord webhook ID or token not configured")
}
- if err := DecryptStringCredential(&discordConfig.Token); err != nil {
- return err
+ if decryptStringCredentialErr := DecryptStringCredential(&discordConfig.Token); decryptStringCredentialErr != nil {
+ return decryptStringCredentialErr
}
- if err := SendDiscord(ctx, discordConfig, c.Text[MessageFormatMarkdown]); err != nil {
- return fmt.Errorf("failed to send Discord notification: %w", err)
+ if sendDiscordErr := SendDiscord(ctx, discordConfig, c.Text[MessageFormatMarkdown]); sendDiscordErr != nil {
+ return fmt.Errorf("failed to send Discord notification: %w", sendDiscordErr)
}
return nil
}
@@ -95,16 +95,16 @@ func deliverEmail(ctx context.Context, config database.JSON, c Content) error {
if len(emailConfig.ToAddresses) == 0 {
return errors.New("no recipient email addresses configured")
}
- if _, err := mail.ParseAddress(emailConfig.FromAddress); err != nil {
- return fmt.Errorf("invalid from address: %w", err)
+ if _, parseAddressErr := mail.ParseAddress(emailConfig.FromAddress); parseAddressErr != nil {
+ return fmt.Errorf("invalid from address: %w", parseAddressErr)
}
for _, addr := range emailConfig.ToAddresses {
- if _, err := mail.ParseAddress(addr); err != nil {
- return fmt.Errorf("invalid to address %s: %w", addr, err)
+ if _, parseAddressErr2 := mail.ParseAddress(addr); parseAddressErr2 != nil {
+ return fmt.Errorf("invalid to address %s: %w", addr, parseAddressErr2)
}
}
- if err := DecryptStringCredential(&emailConfig.SMTPPassword); err != nil {
- return err
+ if decryptStringCredentialErr := DecryptStringCredential(&emailConfig.SMTPPassword); decryptStringCredentialErr != nil {
+ return decryptStringCredentialErr
}
if c.RenderEmail == nil {
return errors.New("email rendering not configured for this notification")
@@ -113,8 +113,8 @@ func deliverEmail(ctx context.Context, config database.JSON, c Content) error {
if err != nil {
return err
}
- if err := SendEmail(ctx, emailConfig, subject, htmlBody); err != nil {
- return fmt.Errorf("failed to send email: %w", err)
+ if sendEmailErr := SendEmail(ctx, emailConfig, subject, htmlBody); sendEmailErr != nil {
+ return fmt.Errorf("failed to send email: %w", sendEmailErr)
}
return nil
}
@@ -130,12 +130,12 @@ func deliverTelegram(ctx context.Context, config database.JSON, c Content) error
if len(telegramConfig.ChatIDs) == 0 {
return errors.New("no telegram chat IDs configured")
}
- if err := DecryptStringCredential(&telegramConfig.BotToken); err != nil {
- return err
+ if decryptStringCredentialErr := DecryptStringCredential(&telegramConfig.BotToken); decryptStringCredentialErr != nil {
+ return decryptStringCredentialErr
}
telegramConfig.ParseMode = cmp.Or(telegramConfig.ParseMode, "HTML")
- if err := SendTelegram(ctx, telegramConfig, c.Text[MessageFormatHTML]); err != nil {
- return fmt.Errorf("failed to send Telegram notification: %w", err)
+ if sendTelegramErr := SendTelegram(ctx, telegramConfig, c.Text[MessageFormatHTML]); sendTelegramErr != nil {
+ return fmt.Errorf("failed to send Telegram notification: %w", sendTelegramErr)
}
return nil
}
@@ -156,14 +156,14 @@ func deliverSignal(ctx context.Context, config database.JSON, c Content) error {
if hasBasicAuth && hasTokenAuth {
return errors.New("signal cannot use both basic auth and token authentication simultaneously")
}
- if err := DecryptStringCredential(&signalConfig.Password); err != nil {
- return err
+ if decryptStringCredentialErr := DecryptStringCredential(&signalConfig.Password); decryptStringCredentialErr != nil {
+ return decryptStringCredentialErr
}
- if err := DecryptStringCredential(&signalConfig.Token); err != nil {
- return err
+ if decryptStringCredentialErr2 := DecryptStringCredential(&signalConfig.Token); decryptStringCredentialErr2 != nil {
+ return decryptStringCredentialErr2
}
- if err := SendSignal(ctx, signalConfig, c.Text[MessageFormatPlain]); err != nil {
- return fmt.Errorf("failed to send Signal notification: %w", err)
+ if sendSignalErr := SendSignal(ctx, signalConfig, c.Text[MessageFormatPlain]); sendSignalErr != nil {
+ return fmt.Errorf("failed to send Signal notification: %w", sendSignalErr)
}
return nil
}
@@ -173,8 +173,8 @@ func deliverSlack(ctx context.Context, config database.JSON, c Content) error {
if err != nil {
return err
}
- if err := SendSlack(ctx, slackConfig, c.Text[MessageFormatSlack]); err != nil {
- return fmt.Errorf("failed to send Slack notification: %w", err)
+ if sendSlackErr := SendSlack(ctx, slackConfig, c.Text[MessageFormatSlack]); sendSlackErr != nil {
+ return fmt.Errorf("failed to send Slack notification: %w", sendSlackErr)
}
return nil
}
@@ -184,8 +184,8 @@ func deliverNtfy(ctx context.Context, config database.JSON, c Content) error {
if err != nil {
return err
}
- if err := SendNtfy(ctx, ntfyConfig, c.Text[MessageFormatPlain]); err != nil {
- return fmt.Errorf("failed to send Ntfy notification: %w", err)
+ if sendNtfyErr := SendNtfy(ctx, ntfyConfig, c.Text[MessageFormatPlain]); sendNtfyErr != nil {
+ return fmt.Errorf("failed to send Ntfy notification: %w", sendNtfyErr)
}
return nil
}
@@ -206,8 +206,8 @@ func deliverPushover(ctx context.Context, config database.JSON, c Content) error
if pushoverConfig.Title == "" && c.DefaultTitle != "" {
pushoverConfig.Title = c.DefaultTitle
}
- if err := SendPushover(ctx, pushoverConfig, c.Text[MessageFormatPlain]); err != nil {
- return fmt.Errorf("failed to send Pushover notification: %w", err)
+ if sendPushoverErr := SendPushover(ctx, pushoverConfig, c.Text[MessageFormatPlain]); sendPushoverErr != nil {
+ return fmt.Errorf("failed to send Pushover notification: %w", sendPushoverErr)
}
return nil
}
@@ -220,8 +220,8 @@ func deliverGotify(ctx context.Context, config database.JSON, c Content) error {
if gotifyConfig.Title == "" && c.DefaultTitle != "" {
gotifyConfig.Title = c.DefaultTitle
}
- if err := SendGotify(ctx, gotifyConfig, c.Text[MessageFormatPlain]); err != nil {
- return fmt.Errorf("failed to send Gotify notification: %w", err)
+ if sendGotifyErr := SendGotify(ctx, gotifyConfig, c.Text[MessageFormatPlain]); sendGotifyErr != nil {
+ return fmt.Errorf("failed to send Gotify notification: %w", sendGotifyErr)
}
return nil
}
@@ -231,8 +231,8 @@ func deliverMatrix(ctx context.Context, config database.JSON, c Content) error {
if err != nil {
return err
}
- if err := SendMatrix(ctx, matrixConfig, c.Text[MessageFormatPlain]); err != nil {
- return fmt.Errorf("failed to send Matrix notification: %w", err)
+ if sendMatrixErr := SendMatrix(ctx, matrixConfig, c.Text[MessageFormatPlain]); sendMatrixErr != nil {
+ return fmt.Errorf("failed to send Matrix notification: %w", sendMatrixErr)
}
return nil
}
@@ -245,11 +245,11 @@ func deliverGoogleChat(ctx context.Context, config database.JSON, c Content) err
if googleChatConfig.WebhookURL == "" {
return errors.New("google chat webhook URL not configured")
}
- if err := DecryptStringCredential(&googleChatConfig.WebhookURL); err != nil {
- return err
+ if decryptStringCredentialErr := DecryptStringCredential(&googleChatConfig.WebhookURL); decryptStringCredentialErr != nil {
+ return decryptStringCredentialErr
}
- if err := SendGoogleChat(ctx, googleChatConfig, c.Text[MessageFormatPlain]); err != nil {
- return fmt.Errorf("failed to send Google Chat notification: %w", err)
+ if sendGoogleChatErr := SendGoogleChat(ctx, googleChatConfig, c.Text[MessageFormatPlain]); sendGoogleChatErr != nil {
+ return fmt.Errorf("failed to send Google Chat notification: %w", sendGoogleChatErr)
}
return nil
}
@@ -262,8 +262,8 @@ func deliverGeneric(ctx context.Context, config database.JSON, c Content) error
if genericConfig.WebhookURL == "" {
return errors.New("webhook URL not configured")
}
- if err := SendGenericWithTitle(ctx, genericConfig, c.Title, c.Text[MessageFormatPlain], c.Vars); err != nil {
- return fmt.Errorf("failed to send Generic webhook notification: %w", err)
+ if sendGenericWithTitleErr := SendGenericWithTitle(ctx, genericConfig, c.Title, c.Text[MessageFormatPlain], c.Vars); sendGenericWithTitleErr != nil {
+ return fmt.Errorf("failed to send Generic webhook notification: %w", sendGenericWithTitleErr)
}
return nil
}
diff --git a/backend/pkg/utils/notifications/deliver_test.go b/backend/pkg/utils/notifications/deliver_test.go
index 07a1b07b9..6913d59b0 100644
--- a/backend/pkg/utils/notifications/deliver_test.go
+++ b/backend/pkg/utils/notifications/deliver_test.go
@@ -1,7 +1,6 @@
package notifications
import (
- "context"
"testing"
"github.com/stretchr/testify/require"
@@ -10,7 +9,7 @@ import (
)
func TestDeliver_UnknownProviderIsNotHandled(t *testing.T) {
- handled, err := Deliver(context.Background(), "bogus", database.JSON{}, Content{})
+ handled, err := Deliver(t.Context(), "bogus", database.JSON{}, Content{})
require.False(t, handled)
require.NoError(t, err)
}
diff --git a/backend/pkg/utils/notifications/discord_sender_test.go b/backend/pkg/utils/notifications/discord_sender_test.go
index 62992038e..4836d7094 100644
--- a/backend/pkg/utils/notifications/discord_sender_test.go
+++ b/backend/pkg/utils/notifications/discord_sender_test.go
@@ -1,7 +1,7 @@
package notifications
import (
- "fmt"
+ "errors"
"testing"
"github.com/stretchr/testify/assert"
@@ -273,10 +273,10 @@ func TestSendDiscord_ValidConfiguration(t *testing.T) {
// Helper function to extract validation logic for testing
func validateDiscordConfig(config DiscordConfig) error {
if config.WebhookID == "" {
- return fmt.Errorf("discord webhook ID is empty")
+ return errors.New("discord webhook ID is empty")
}
if config.Token == "" {
- return fmt.Errorf("discord token is empty")
+ return errors.New("discord token is empty")
}
return nil
}
diff --git a/backend/pkg/utils/notifications/email_sender.go b/backend/pkg/utils/notifications/email_sender.go
index d092e35c1..7fc986969 100644
--- a/backend/pkg/utils/notifications/email_sender.go
+++ b/backend/pkg/utils/notifications/email_sender.go
@@ -131,17 +131,17 @@ func sendEmailInternal(ctx context.Context, config EmailConfig, subject, htmlBod
}
msg := mail.NewMsg()
- if err := msg.From(config.FromAddress); err != nil {
- return fmt.Errorf("invalid from address %q: %w", config.FromAddress, err)
+ if fromErr := msg.From(config.FromAddress); fromErr != nil {
+ return fmt.Errorf("invalid from address %q: %w", config.FromAddress, fromErr)
}
- if err := msg.To(config.ToAddresses...); err != nil {
- return fmt.Errorf("invalid recipient address(es): %w", err)
+ if toErr := msg.To(config.ToAddresses...); toErr != nil {
+ return fmt.Errorf("invalid recipient address(es): %w", toErr)
}
msg.Subject(subject)
msg.SetBodyString(mail.TypeTextHTML, htmlBody)
- if err := client.DialAndSendWithContext(ctx, msg); err != nil {
- return fmt.Errorf("failed to send email: %w", err)
+ if dialAndSendWithContextErr := client.DialAndSendWithContext(ctx, msg); dialAndSendWithContextErr != nil {
+ return fmt.Errorf("failed to send email: %w", dialAndSendWithContextErr)
}
return nil
diff --git a/backend/pkg/utils/notifications/email_sender_test.go b/backend/pkg/utils/notifications/email_sender_test.go
index 7bbedb4d6..005bf7bd9 100644
--- a/backend/pkg/utils/notifications/email_sender_test.go
+++ b/backend/pkg/utils/notifications/email_sender_test.go
@@ -2,7 +2,6 @@ package notifications
import (
"bufio"
- "context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
@@ -61,7 +60,7 @@ func TestSendEmailStartTLSRequiresTLSBeforeAuth(t *testing.T) {
}
err := sendEmailInternal(
- context.Background(),
+ t.Context(),
config,
"Arcane STARTTLS Test",
"<p>Test</p>",
@@ -90,7 +89,7 @@ func TestSendEmailStartTLSFailsWhenServerDoesNotSupportIt(t *testing.T) {
TLSMode: EmailTLSModeStartTLS,
}
- err := SendEmail(context.Background(), config, "Arcane STARTTLS Test", "<p>Test</p>")
+ err := SendEmail(t.Context(), config, "Arcane STARTTLS Test", "<p>Test</p>")
require.Error(t, err)
assert.Contains(t, err.Error(), "STARTTLS")
assert.NotContains(t, err.Error(), "unencrypted connection")
@@ -117,7 +116,7 @@ func TestSendEmailAuthLoginAgainstExchangeStyleServer(t *testing.T) {
}
err := sendEmailInternal(
- context.Background(),
+ t.Context(),
config,
"Arcane AUTH LOGIN Test",
"<p>Test</p>",
@@ -145,7 +144,7 @@ func TestSendEmailStalePasswordWithoutUsernameSkipsAuth(t *testing.T) {
AuthMode: EmailAuthModeAuto,
}
- err := sendEmailInternal(context.Background(), config, "Arcane No-Auth Test", "<p>Test</p>", smtpBuildOptions{})
+ err := sendEmailInternal(t.Context(), config, "Arcane No-Auth Test", "<p>Test</p>", smtpBuildOptions{})
require.NoError(t, err)
require.NoError(t, server.Wait())
@@ -199,7 +198,7 @@ func (s *smtpTestServer) Wait() error {
case err := <-s.done:
return kit.Ternary(err != nil && (isUseOfClosedNetworkConnInternal(err) || isConnectionTimeoutInternal(err)), nil, err)
case <-time.After(4 * time.Second):
- return fmt.Errorf("timed out waiting for SMTP test server")
+ return errors.New("timed out waiting for SMTP test server")
}
}
@@ -270,7 +269,7 @@ func (s *smtpTestServer) handleConnection(conn net.Conn) error {
for {
line, err := reader.ReadLine()
if err != nil {
- return kit.Ternary(err == io.EOF, nil, err)
+ return kit.Ternary(errors.Is(err, io.EOF), nil, err)
}
verb, rest, _ := strings.Cut(line, " ")
@@ -285,24 +284,24 @@ func (s *smtpTestServer) handleConnection(conn net.Conn) error {
} else {
lines = s.ehloLinesInternal()
}
- if err := writeSMTPMultiLineResponseInternal(writer, 250, lines); err != nil {
- return err
+ if writeSMTPMultiLineResponseErr := writeSMTPMultiLineResponseInternal(writer, 250, lines); writeSMTPMultiLineResponseErr != nil {
+ return writeSMTPMultiLineResponseErr
}
case "STARTTLS":
if !s.supportStartTLS {
- if err := writeSMTPResponseInternal(writer, 502, false, "STARTTLS not supported"); err != nil {
- return err
+ if writeSMTPResponseErr := writeSMTPResponseInternal(writer, 502, false, "STARTTLS not supported"); writeSMTPResponseErr != nil {
+ return writeSMTPResponseErr
}
continue
}
- if err := writeSMTPResponseInternal(writer, 220, false, "ready to start TLS"); err != nil {
- return err
+ if writeSMTPResponseErr2 := writeSMTPResponseInternal(writer, 220, false, "ready to start TLS"); writeSMTPResponseErr2 != nil {
+ return writeSMTPResponseErr2
}
tlsConn := tls.Server(conn, s.tlsConfig)
- if err := tlsConn.Handshake(); err != nil {
- return err
+ if handshakeErr := tlsConn.Handshake(); handshakeErr != nil {
+ return handshakeErr
}
conn = tlsConn
@@ -311,57 +310,70 @@ func (s *smtpTestServer) handleConnection(conn net.Conn) error {
writer = textproto.NewWriter(bufio.NewWriter(conn))
tlsActive = true
s.markStartTLSNegotiated()
- case "AUTH":
- mechanism, _, _ := strings.Cut(strings.TrimSpace(rest), " ")
- mechanism = strings.ToUpper(mechanism)
- s.recordAuthMechanismInternal(mechanism)
- if err := s.handleAuthInternal(reader, writer, mechanism); err != nil {
- return err
- }
- case "NOOP", "RSET":
- if err := writeSMTPResponseInternal(writer, 250, false, "2.0.0 OK"); err != nil {
- return err
- }
- case "MAIL":
- if err := writeSMTPResponseInternal(writer, 250, false, "2.1.0 Sender OK"); err != nil {
- return err
- }
- case "RCPT":
- if err := writeSMTPResponseInternal(writer, 250, false, "2.1.5 Recipient OK"); err != nil {
- return err
- }
- case "DATA":
- if err := writeSMTPResponseInternal(writer, 354, false, "End data with <CR><LF>.<CR><LF>"); err != nil {
- return err
- }
- for {
- dataLine, dataErr := reader.ReadLine()
- if dataErr != nil {
- return dataErr
- }
- if dataLine == "." {
- break
- }
+ default:
+ quit, commandErr := s.handleCommandInternal(reader, writer, verb, rest)
+ if commandErr != nil {
+ return commandErr
}
- if err := writeSMTPResponseInternal(writer, 250, false, "2.0.0 queued"); err != nil {
- return err
+ if quit {
+ return nil
}
- case "QUIT":
- if err := writeSMTPResponseInternal(writer, 221, false, "2.0.0 bye"); err != nil {
- return err
+ }
+ }
+}
+
+func (s *smtpTestServer) handleCommandInternal(reader *textproto.Reader, writer *textproto.Writer, verb, rest string) (bool, error) {
+ switch verb {
+ case "AUTH":
+ mechanism, _, _ := strings.Cut(strings.TrimSpace(rest), " ")
+ mechanism = strings.ToUpper(mechanism)
+ s.recordAuthMechanismInternal(mechanism)
+ if handleAuthErr := s.handleAuthInternal(reader, writer, mechanism); handleAuthErr != nil {
+ return false, handleAuthErr
+ }
+ case "NOOP", "RSET":
+ if writeSMTPResponseErr3 := writeSMTPResponseInternal(writer, 250, false, "2.0.0 OK"); writeSMTPResponseErr3 != nil {
+ return false, writeSMTPResponseErr3
+ }
+ case "MAIL":
+ if writeSMTPResponseErr4 := writeSMTPResponseInternal(writer, 250, false, "2.1.0 Sender OK"); writeSMTPResponseErr4 != nil {
+ return false, writeSMTPResponseErr4
+ }
+ case "RCPT":
+ if writeSMTPResponseErr5 := writeSMTPResponseInternal(writer, 250, false, "2.1.5 Recipient OK"); writeSMTPResponseErr5 != nil {
+ return false, writeSMTPResponseErr5
+ }
+ case "DATA":
+ if writeSMTPResponseErr6 := writeSMTPResponseInternal(writer, 354, false, "End data with <CR><LF>.<CR><LF>"); writeSMTPResponseErr6 != nil {
+ return false, writeSMTPResponseErr6
+ }
+ for {
+ dataLine, dataErr := reader.ReadLine()
+ if dataErr != nil {
+ return false, dataErr
}
- return nil
- default:
- if err := writeSMTPResponseInternal(writer, 502, false, "command not implemented"); err != nil {
- return err
+ if dataLine == "." {
+ break
}
}
+ if writeSMTPResponseErr7 := writeSMTPResponseInternal(writer, 250, false, "2.0.0 queued"); writeSMTPResponseErr7 != nil {
+ return false, writeSMTPResponseErr7
+ }
+ case "QUIT":
+ if writeSMTPResponseErr8 := writeSMTPResponseInternal(writer, 221, false, "2.0.0 bye"); writeSMTPResponseErr8 != nil {
+ return false, writeSMTPResponseErr8
+ }
+ return true, nil
+ default:
+ if writeSMTPResponseErr9 := writeSMTPResponseInternal(writer, 502, false, "command not implemented"); writeSMTPResponseErr9 != nil {
+ return false, writeSMTPResponseErr9
+ }
}
+ return false, nil
}
func (s *smtpTestServer) handleAuthInternal(reader *textproto.Reader, writer *textproto.Writer, mechanism string) error {
- switch mechanism {
- case "LOGIN":
+ if mechanism == "LOGIN" {
if err := writeSMTPResponseInternal(writer, 334, false, base64.StdEncoding.EncodeToString([]byte("Username:"))); err != nil {
return err
}
diff --git a/backend/pkg/utils/notifications/generic_sender.go b/backend/pkg/utils/notifications/generic_sender.go
index 52c957213..59175fb0f 100644
--- a/backend/pkg/utils/notifications/generic_sender.go
+++ b/backend/pkg/utils/notifications/generic_sender.go
@@ -197,8 +197,8 @@ func RenderGenericPayloadTemplate(config GenericConfig, title, message string, v
}
var rendered bytes.Buffer
- if err := tmpl.Execute(&rendered, genericTemplateDataInternal(config, title, message, vars)); err != nil {
- return "", fmt.Errorf("failed to render webhook payload template: %w", err)
+ if executeErr := tmpl.Execute(&rendered, genericTemplateDataInternal(config, title, message, vars)); executeErr != nil {
+ return "", fmt.Errorf("failed to render webhook payload template: %w", executeErr)
}
return rendered.String(), nil
}
@@ -323,8 +323,8 @@ func sendGenericTemplatedInternal(config GenericConfig, shoutrrrURL, templateID
return fmt.Errorf("failed to initialize shoutrrr Generic service: %w", err)
}
- if err := service.SetTemplateString(templateID, config.PayloadTemplate); err != nil {
- return fmt.Errorf("invalid webhook payload template: %w", err)
+ if setTemplateStringErr := service.SetTemplateString(templateID, config.PayloadTemplate); setTemplateStringErr != nil {
+ return fmt.Errorf("invalid webhook payload template: %w", setTemplateStringErr)
}
// Shoutrrr renders the registered template over the send params, remapping
@@ -337,8 +337,8 @@ func sendGenericTemplatedInternal(config GenericConfig, shoutrrrURL, templateID
params[key] = jsonEscapeString(value)
}
- if err := service.Send(jsonEscapeString(message), &params); err != nil {
- return fmt.Errorf("failed to send Generic webhook message via shoutrrr: %w", err)
+ if sendErr := service.Send(jsonEscapeString(message), &params); sendErr != nil {
+ return fmt.Errorf("failed to send Generic webhook message via shoutrrr: %w", sendErr)
}
return nil
}
diff --git a/backend/pkg/utils/notifications/messages.go b/backend/pkg/utils/notifications/messages.go
index 82e8318b2..373d56d2a 100644
--- a/backend/pkg/utils/notifications/messages.go
+++ b/backend/pkg/utils/notifications/messages.go
@@ -58,7 +58,7 @@ func formatNotificationCodeInternal(format MessageFormat, value string) string {
case MessageFormatHTML:
return fmt.Sprintf("<code>%s</code>", value)
case MessageFormatMarkdown, MessageFormatSlack:
- return fmt.Sprintf("`%s`", value)
+ return "`" + value + "`"
default:
return value
}
diff --git a/backend/pkg/utils/notifications/ntfy_sender_test.go b/backend/pkg/utils/notifications/ntfy_sender_test.go
index 46c51869c..18e0a05cc 100644
--- a/backend/pkg/utils/notifications/ntfy_sender_test.go
+++ b/backend/pkg/utils/notifications/ntfy_sender_test.go
@@ -111,7 +111,8 @@ func TestBuildNtfyURL(t *testing.T) {
},
wantErr: false,
check: func(url string) bool {
- return url == "ntfy://user:[email protected]:8080/test?cache=no&disabletlsverification=yes&firebase=no&icon=https%3A%2F%2Fexample.com%2Ficon.png&priority=max&tags=urgent&title=Arcane+Alert"
+ return url == "ntfy://user:[email protected]:8080/test?cache=no&disabletlsverification=yes&firebase=no&icon=htt"+
+ "ps%3A%2F%2Fexample.com%2Ficon.png&priority=max&tags=urgent&title=Arcane+Alert"
},
},
}
diff --git a/backend/pkg/utils/notifications/signal_sender_test.go b/backend/pkg/utils/notifications/signal_sender_test.go
index 982c30a21..489afe776 100644
--- a/backend/pkg/utils/notifications/signal_sender_test.go
+++ b/backend/pkg/utils/notifications/signal_sender_test.go
@@ -1,7 +1,7 @@
package notifications
import (
- "fmt"
+ "errors"
"testing"
"github.com/stretchr/testify/assert"
@@ -311,26 +311,26 @@ func TestSendSignal_ValidConfigurations(t *testing.T) {
// Helper function to extract validation logic for testing
func validateSignalConfig(config SignalConfig) error {
if config.Host == "" {
- return fmt.Errorf("signal host is empty")
+ return errors.New("signal host is empty")
}
if config.Port == 0 {
- return fmt.Errorf("signal port is not set")
+ return errors.New("signal port is not set")
}
if config.Source == "" {
- return fmt.Errorf("signal source phone number is empty")
+ return errors.New("signal source phone number is empty")
}
if len(config.Recipients) == 0 {
- return fmt.Errorf("no signal recipients configured")
+ return errors.New("no signal recipients configured")
}
// Validate authentication
hasBasicAuth := config.User != "" && config.Password != ""
hasTokenAuth := config.Token != ""
if !hasBasicAuth && !hasTokenAuth {
- return fmt.Errorf("signal requires either basic auth (user/password) or token authentication")
+ return errors.New("signal requires either basic auth (user/password) or token authentication")
}
if hasBasicAuth && hasTokenAuth {
- return fmt.Errorf("signal cannot use both basic auth and token authentication simultaneously")
+ return errors.New("signal cannot use both basic auth and token authentication simultaneously")
}
return nil
diff --git a/backend/pkg/utils/notifications/slack_sender_test.go b/backend/pkg/utils/notifications/slack_sender_test.go
index e073e9372..9d5ec008f 100644
--- a/backend/pkg/utils/notifications/slack_sender_test.go
+++ b/backend/pkg/utils/notifications/slack_sender_test.go
@@ -41,7 +41,8 @@ func TestBuildSlackURL(t *testing.T) {
Title: "Container Update",
ThreadTS: "1234567890.123456",
},
- wantURL: "slack://xoxb:123456789012-123456789012-abcdefghijklmnopqrstuvwx@notifications?botname=Arcane+Bot&color=%23FF0000&icon=%3Arobot%3A&thread_ts=1234567890.123456&title=Container+Update",
+ wantURL: "slack://xoxb:123456789012-123456789012-abcdefghijklmnopqrstuvwx@notifications?botname=Arcane+Bot&col" +
+ "or=%23FF0000&icon=%3Arobot%3A&thread_ts=1234567890.123456&title=Container+Update",
},
{
name: "empty token",
diff --git a/backend/pkg/utils/oidcjwk/manager.go b/backend/pkg/utils/oidcjwk/manager.go
index 62c45b911..eeeaba299 100644
--- a/backend/pkg/utils/oidcjwk/manager.go
+++ b/backend/pkg/utils/oidcjwk/manager.go
@@ -44,7 +44,7 @@ type KeySetManager struct {
func NewKeySetManager(ctx context.Context) *KeySetManager { //nolint:contextcheck // cache workers inherit the application lifecycle context, not request contexts.
if ctx == nil {
- ctx = context.Background()
+ ctx = context.Background() //nolint:forbidigo // Fallback supports construction without an application lifecycle context.
}
return &KeySetManager{
ctx: ctx,
@@ -133,8 +133,8 @@ func (m *managedCache) initializeKeySetInternal(ctx context.Context, jwksURL str
if initialized {
return
}
- cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
- defer cancel()
+ cleanupCtx, localCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer localCancel()
if m.cache.IsRegistered(cleanupCtx, jwksURL) {
_ = m.cache.Unregister(cleanupCtx, jwksURL)
}
diff --git a/backend/pkg/utils/oidcjwk/oidcjwk_test.go b/backend/pkg/utils/oidcjwk/oidcjwk_test.go
index 347a5325a..32615e963 100644
--- a/backend/pkg/utils/oidcjwk/oidcjwk_test.go
+++ b/backend/pkg/utils/oidcjwk/oidcjwk_test.go
@@ -65,15 +65,15 @@ func TestKeySetVerifySignature(t *testing.T) {
if tc.initialFailure == "http" {
w.WriteHeader(http.StatusServiceUnavailable)
} else {
- if _, err := fmt.Fprint(w, `{"keys":`); err != nil {
- t.Errorf("write malformed JWKS response: %v", err)
+ if _, fprintErr := fmt.Fprint(w, `{"keys":`); fprintErr != nil {
+ t.Errorf("write malformed JWKS response: %v", fprintErr)
}
}
return
}
w.Header().Set("Content-Type", "application/json")
- if _, err := fmt.Fprint(w, jwks); err != nil {
- t.Errorf("write JWKS response: %v", err)
+ if _, fprintErr2 := fmt.Fprint(w, jwks); fprintErr2 != nil {
+ t.Errorf("write JWKS response: %v", fprintErr2)
}
}))
defer srv.Close()
@@ -93,7 +93,7 @@ func TestKeySetVerifySignature(t *testing.T) {
manager := oidcjwk.NewKeySetManager(ctx)
jwksURL := srv.URL + "/jwks?credential=test-secret"
t.Cleanup(func() {
- shutdownCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(t.Context()), time.Second)
defer cancel()
require.NoError(t, manager.Shutdown(shutdownCtx))
})
diff --git a/backend/pkg/utils/recover.go b/backend/pkg/utils/recover.go
index 9c8eb820d..d2bdee0ed 100644
--- a/backend/pkg/utils/recover.go
+++ b/backend/pkg/utils/recover.go
@@ -21,7 +21,7 @@ import (
// to observe the panic. errPtr may be nil when the caller has no error to
// report into (e.g. a fire-and-forget goroutine); the panic is still logged.
// args are extra slog attributes appended to the log record.
-func RecoverToError(errPtr *error, label string, args ...any) {
+func RecoverToError(errPtr *error, label string, args ...any) { //nolint:gocritic // Pointer output updates the caller's named error result after recovery.
panicErr := PanicToError(recover())
if panicErr == nil {
return
diff --git a/backend/pkg/utils/s3/s3.go b/backend/pkg/utils/s3/s3.go
index 95f2cd50c..586e810ad 100644
--- a/backend/pkg/utils/s3/s3.go
+++ b/backend/pkg/utils/s3/s3.go
@@ -166,8 +166,8 @@ func (c Configuration) RusticEnvironment(rootParts ...string) []string {
// TestConnection verifies upload, download, and delete access for a destination.
func TestConnection(ctx context.Context, configuration Configuration) (err error) {
configuration = configuration.Normalized()
- if err := configuration.Validate(true); err != nil {
- return err
+ if validateErr := configuration.Validate(true); validateErr != nil {
+ return validateErr
}
client, err := newClientInternal(ctx, configuration)
if err != nil {
@@ -175,8 +175,8 @@ func TestConnection(ctx context.Context, configuration Configuration) (err error
}
payload := []byte(connectionTestPayload)
remoteKey := path.Join(configuration.Prefix, ".arcane-connection-test-"+uuid.New().String())
- if err := putObjectInternal(ctx, client, configuration.Bucket, remoteKey, payload); err != nil {
- return fmt.Errorf("failed to upload S3 connection test object: %w", err)
+ if putObjectErr := putObjectInternal(ctx, client, configuration.Bucket, remoteKey, payload); putObjectErr != nil {
+ return fmt.Errorf("failed to upload S3 connection test object: %w", putObjectErr)
}
deleted := false
@@ -196,8 +196,8 @@ func TestConnection(ctx context.Context, configuration Configuration) (err error
if !bytes.Equal(downloaded, payload) {
return errors.New("S3 connection test object contents did not match")
}
- if err := deleteObjectInternal(ctx, client, configuration.Bucket, remoteKey); err != nil {
- return fmt.Errorf("failed to delete S3 connection test object: %w", err)
+ if deleteObjectErr := deleteObjectInternal(ctx, client, configuration.Bucket, remoteKey); deleteObjectErr != nil {
+ return fmt.Errorf("failed to delete S3 connection test object: %w", deleteObjectErr)
}
deleted = true
return nil
@@ -214,28 +214,28 @@ func CheckRepository(ctx context.Context, configuration Configuration, root, sna
return backuptypes.RepositoryObservation{}, fmt.Errorf("failed to configure S3 repository check: %w", err)
}
configKey := path.Join(configuration.Prefix, root, "config")
- if err := checkBackupObjectInternal(ctx, client, configuration.Bucket, configKey); err != nil {
- if isMissingResourceInternal(err, "NoSuchBucket") {
+ if checkBackupObjectErr := checkBackupObjectInternal(ctx, client, configuration.Bucket, configKey); checkBackupObjectErr != nil {
+ if isMissingResourceInternal(checkBackupObjectErr, "NoSuchBucket") {
return backuptypes.RepositoryObservation{Reason: RepositoryReasonMissingBucket}, nil
}
- if isMissingResourceInternal(err, "NoSuchKey") {
+ if isMissingResourceInternal(checkBackupObjectErr, "NoSuchKey") {
return backuptypes.RepositoryObservation{Reason: RepositoryReasonMissingRepository}, nil
}
- return backuptypes.RepositoryObservation{}, err
+ return backuptypes.RepositoryObservation{}, checkBackupObjectErr
}
result := backuptypes.RepositoryObservation{Available: true}
if snapshotID == "" {
return result, nil
}
snapshotKey := path.Join(configuration.Prefix, root, "snapshots", snapshotID)
- if err := checkBackupObjectInternal(ctx, client, configuration.Bucket, snapshotKey); err != nil {
- if isMissingResourceInternal(err, "NoSuchKey") {
+ if checkBackupObjectErr2 := checkBackupObjectInternal(ctx, client, configuration.Bucket, snapshotKey); checkBackupObjectErr2 != nil {
+ if isMissingResourceInternal(checkBackupObjectErr2, "NoSuchKey") {
return result, nil
}
- if isMissingResourceInternal(err, "NoSuchBucket") {
+ if isMissingResourceInternal(checkBackupObjectErr2, "NoSuchBucket") {
return backuptypes.RepositoryObservation{Reason: RepositoryReasonMissingBucket}, nil
}
- return backuptypes.RepositoryObservation{}, err
+ return backuptypes.RepositoryObservation{}, checkBackupObjectErr2
}
result.SnapshotAvailable = true
return result, nil
@@ -268,9 +268,9 @@ func ListRepositoryRoots(ctx context.Context, configuration Configuration, root
Delimiter: aws.String("/"),
})
for paginator.HasMorePages() {
- page, err := paginator.NextPage(ctx)
- if err != nil {
- return nil, fmt.Errorf("failed to list S3 repository roots: %w", err)
+ page, nextPageErr := paginator.NextPage(ctx)
+ if nextPageErr != nil {
+ return nil, fmt.Errorf("failed to list S3 repository roots: %w", nextPageErr)
}
for _, commonPrefix := range page.CommonPrefixes {
if commonPrefix.Prefix == nil {
diff --git a/backend/pkg/utils/sync_gate_test.go b/backend/pkg/utils/sync_gate_test.go
index c2b43a115..c2a2f3cc4 100644
--- a/backend/pkg/utils/sync_gate_test.go
+++ b/backend/pkg/utils/sync_gate_test.go
@@ -8,11 +8,10 @@ import (
"github.com/stretchr/testify/require"
)
-func deliverInternal(gate *SyncGate, scope, key string, body []byte) bool {
- unchanged, finish, err := gate.Begin(context.Background(), scope, key, body)
- if err != nil {
- panic(err)
- }
+func deliverInternal(t *testing.T, gate *SyncGate, scope, key string, body []byte) bool {
+ t.Helper()
+ unchanged, finish, err := gate.Begin(t.Context(), scope, key, body)
+ require.NoError(t, err)
finish(!unchanged)
return unchanged
}
@@ -21,52 +20,54 @@ func TestSyncGate_TracksLastDeliveredPayloadPerScopeAndKey(t *testing.T) {
var gate SyncGate
body := []byte(`{"registries":[]}`)
- require.False(t, deliverInternal(&gate, "env", "/registries", body), "nothing delivered yet")
- require.True(t, deliverInternal(&gate, "env", "/registries", body))
- require.False(t, deliverInternal(&gate, "env", "/registries", []byte(`{"registries":[{"id":"a"}]}`)))
- require.False(t, deliverInternal(&gate, "env", "/s3", body), "keys are independent")
- require.False(t, deliverInternal(&gate, "other", "/registries", body), "scopes are independent")
+ require.False(t, deliverInternal(t, &gate, "env", "/registries", body), "nothing delivered yet")
+ require.True(t, deliverInternal(t, &gate, "env", "/registries", body))
+ require.False(t, deliverInternal(t, &gate, "env", "/registries", []byte(`{"registries":[{"id":"a"}]}`)))
+ require.False(t, deliverInternal(t, &gate, "env", "/s3", body), "keys are independent")
+ require.False(t, deliverInternal(t, &gate, "other", "/registries", body), "scopes are independent")
gate.Forget("env")
- require.False(t, deliverInternal(&gate, "env", "/registries", body), "forget drops every key in the scope")
+ require.False(t, deliverInternal(t, &gate, "env", "/registries", body), "forget drops every key in the scope")
gate.Forget("missing")
}
func TestSyncGate_FailedDeliveryIsNotRemembered(t *testing.T) {
var gate SyncGate
body := []byte(`{"registries":[]}`)
- unchanged, finish, err := gate.Begin(context.Background(), "env", "/registries", body)
+ t.Helper()
+ unchanged, finish, err := gate.Begin(t.Context(), "env", "/registries", body)
require.NoError(t, err)
require.False(t, unchanged)
finish(false)
- require.False(t, deliverInternal(&gate, "env", "/registries", body))
+ require.False(t, deliverInternal(t, &gate, "env", "/registries", body))
}
func TestSyncGate_ForgetDiscardsInFlightDelivery(t *testing.T) {
var gate SyncGate
body := []byte(`{"registries":[]}`)
- _, finish, err := gate.Begin(context.Background(), "env", "/registries", body)
+ _, finish, err := gate.Begin(t.Context(), "env", "/registries", body)
require.NoError(t, err)
gate.Forget("env")
finish(true)
- require.False(t, deliverInternal(&gate, "env", "/registries", body), "a delivery that started before Forget must not count")
- require.True(t, deliverInternal(&gate, "env", "/registries", body))
+ require.False(t, deliverInternal(t, &gate, "env", "/registries", body), "a delivery that started before Forget must not count")
+ require.True(t, deliverInternal(t, &gate, "env", "/registries", body))
}
func TestSyncGate_SerializesDeliveriesPerKey(t *testing.T) {
var gate SyncGate
older, newer := []byte(`{"v":1}`), []byte(`{"v":2}`)
- _, finishOlder, err := gate.Begin(context.Background(), "env", "/registries", older)
+ _, finishOlder, err := gate.Begin(t.Context(), "env", "/registries", older)
require.NoError(t, err)
started := make(chan struct{})
done := make(chan bool)
go func() {
close(started)
- unchanged, finish, err := gate.Begin(context.Background(), "env", "/registries", newer)
- if err != nil {
- t.Error(err)
+ t.Helper()
+ unchanged, finish, beginErr := gate.Begin(t.Context(), "env", "/registries", newer)
+ if beginErr != nil {
+ t.Error(beginErr)
done <- false
return
}
@@ -81,30 +82,30 @@ func TestSyncGate_SerializesDeliveriesPerKey(t *testing.T) {
}
finishOlder(true)
require.False(t, <-done)
- require.True(t, deliverInternal(&gate, "env", "/registries", newer), "the last delivery wins")
+ require.True(t, deliverInternal(t, &gate, "env", "/registries", newer), "the last delivery wins")
}
func TestSyncGate_BeginStopsWaitingWhenContextEnds(t *testing.T) {
var gate SyncGate
body := []byte(`{"v":1}`)
- _, finish, err := gate.Begin(context.Background(), "env", "/registries", body)
+ _, finish, err := gate.Begin(t.Context(), "env", "/registries", body)
require.NoError(t, err)
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
defer cancel()
_, _, err = gate.Begin(ctx, "env", "/registries", body)
require.ErrorIs(t, err, context.DeadlineExceeded)
finish(true)
- require.True(t, deliverInternal(&gate, "env", "/registries", body), "the key is usable after an abandoned wait")
+ require.True(t, deliverInternal(t, &gate, "env", "/registries", body), "the key is usable after an abandoned wait")
}
func TestSyncGate_ExpiryForcesPeriodicResend(t *testing.T) {
gate := SyncGate{Expiry: time.Hour}
body := []byte(`{"registries":[]}`)
- require.False(t, deliverInternal(&gate, "env", "/registries", body))
- require.True(t, deliverInternal(&gate, "env", "/registries", body))
+ require.False(t, deliverInternal(t, &gate, "env", "/registries", body))
+ require.True(t, deliverInternal(t, &gate, "env", "/registries", body))
gate.sent["env"]["/registries"] = syncGateEntryInternal{digest: gate.sent["env"]["/registries"].digest, sentAt: time.Now().Add(-2 * time.Hour)}
- require.False(t, deliverInternal(&gate, "env", "/registries", body), "an old delivery is no longer trusted")
+ require.False(t, deliverInternal(t, &gate, "env", "/registries", body), "an old delivery is no longer trusted")
}
diff --git a/backend/pkg/utils/validation/password.go b/backend/pkg/utils/validation/password.go
index 662a4e67f..700f83ace 100644
--- a/backend/pkg/utils/validation/password.go
+++ b/backend/pkg/utils/validation/password.go
@@ -104,7 +104,14 @@ func ValidateCredentialTargetChange(
slices.Sort(missingFields)
if len(missingFields) == 1 {
- return common.Classify(common.ErrValidation, &base.FieldError{Field: missingFields[0], Err: fmt.Errorf("Changing %s requires re-entering the %s", targetName, missingFields[0])}) //nolint:staticcheck // Preserve the existing error message.
+ //nolint:staticcheck // Preserve the existing error message.
+ return common.Classify(common.ErrValidation,
+ &base.FieldError{
+ Field: missingFields[0],
+ Err: fmt.Errorf("Changing %s requires re-entering the %s",
+ targetName,
+ missingFields[0]),
+ })
}
return common.NewAPIErrorWithDetails(
diff --git a/backend/pkg/workspace/workspace_test.go b/backend/pkg/workspace/workspace_test.go
index 6d8b47c14..c3cc9670e 100644
--- a/backend/pkg/workspace/workspace_test.go
+++ b/backend/pkg/workspace/workspace_test.go
@@ -52,7 +52,21 @@ func TestValidateUploadIndices(t *testing.T) {
{name: "unexpected", changes: []UploadReference{{Operation: "delete", UploadIndex: new(0)}}, uploadCount: 1, message: "not allowed"},
{name: "negative", changes: []UploadReference{{Operation: "create_file", UploadIndex: new(-1)}}, uploadCount: 1, message: "out of range"},
{name: "out of range", changes: []UploadReference{{Operation: "create_file", UploadIndex: new(1)}}, uploadCount: 1, message: "out of range"},
- {name: "duplicate", changes: []UploadReference{{Operation: "create_file", UploadIndex: new(0)}, {Operation: "update_file", UploadIndex: new(0)}}, uploadCount: 1, message: "duplicated"},
+ {
+ name: "duplicate",
+ changes: []UploadReference{
+ {
+ Operation: "create_file",
+ UploadIndex: new(0),
+ },
+ {
+ Operation: "update_file",
+ UploadIndex: new(0),
+ },
+ },
+ uploadCount: 1,
+ message: "duplicated",
+ },
{name: "unused", changes: []UploadReference{{Operation: "create_file", UploadIndex: new(0)}}, uploadCount: 2, message: "unused"},
}
for _, test := range tests {
diff --git a/cli/internal/benchmark/baseline_benchmark_test.go b/cli/internal/benchmark/baseline_benchmark_test.go
index a0f7f4bb1..fd61af893 100644
--- a/cli/internal/benchmark/baseline_benchmark_test.go
+++ b/cli/internal/benchmark/baseline_benchmark_test.go
@@ -1,7 +1,6 @@
package benchmark
import (
- "context"
"encoding/json"
"fmt"
"net/http"
@@ -48,9 +47,9 @@ func BenchmarkClientListMediumPayload(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
- resp, err := c.Get(context.Background(), "/api/environments/0/containers?limit=200")
- if err != nil {
- require.FailNowf(b, "benchmark request failed", "request: %v", err)
+ resp, getErr := c.Get(b.Context(), "/api/environments/0/containers?limit=200")
+ if getErr != nil {
+ require.FailNowf(b, "benchmark request failed", "request: %v", getErr)
}
_ = resp.Body.Close()
}
diff --git a/cli/internal/ci/ci_detect.go b/cli/internal/ci/ci_detect.go
index c63e3f30d..81562a40c 100644
--- a/cli/internal/ci/ci_detect.go
+++ b/cli/internal/ci/ci_detect.go
@@ -76,7 +76,7 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenv
parsedURL.RawQuery = q.Encode()
}
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), http.NoBody)
if err != nil {
return "", fmt.Errorf("failed to create GitHub Actions OIDC request: %w", err)
}
@@ -100,8 +100,8 @@ func mintGitHubActionsTokenInternal(ctx context.Context, audience string, getenv
var payload struct {
Value string `json:"value"`
}
- if err := json.Unmarshal(body, &payload); err != nil {
- return "", fmt.Errorf("failed to parse GitHub Actions OIDC response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &payload); unmarshalErr != nil {
+ return "", fmt.Errorf("failed to parse GitHub Actions OIDC response: %w", unmarshalErr)
}
token := strings.TrimSpace(payload.Value)
if token == "" {
diff --git a/cli/internal/ci/ci_detect_test.go b/cli/internal/ci/ci_detect_test.go
index 1b5f4d851..93e2c37c0 100644
--- a/cli/internal/ci/ci_detect_test.go
+++ b/cli/internal/ci/ci_detect_test.go
@@ -1,7 +1,6 @@
package ci
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -27,7 +26,7 @@ func TestDetectFederatedTokenFromGitHubActionsInternal(t *testing.T) {
"ACTIONS_ID_TOKEN_REQUEST_URL": server.URL + "?api-version=2",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-token",
}
- token, provider, err := DetectToken(context.Background(), "auto", "https://arcane.example.com", envGetterFromMapInternal(env), server.Client())
+ token, provider, err := DetectToken(t.Context(), "auto", "https://arcane.example.com", envGetterFromMapInternal(env), server.Client())
require.NoError(t, err)
require.Equal(t, "github.jwt", token)
@@ -39,7 +38,7 @@ func TestDetectFederatedTokenFromGitHubActionsInternal(t *testing.T) {
func TestDetectFederatedTokenFromGitLabLegacyInternal(t *testing.T) {
t.Parallel()
- token, provider, err := DetectToken(context.Background(), "auto", "https://arcane.example.com", envGetterFromMapInternal(map[string]string{
+ token, provider, err := DetectToken(t.Context(), "auto", "https://arcane.example.com", envGetterFromMapInternal(map[string]string{
"CI_JOB_JWT_V2": "gitlab.jwt",
}), http.DefaultClient)
@@ -51,7 +50,7 @@ func TestDetectFederatedTokenFromGitLabLegacyInternal(t *testing.T) {
func TestDetectFederatedTokenProviderMismatchInternal(t *testing.T) {
t.Parallel()
- _, _, err := DetectToken(context.Background(), "github", "aud", envGetterFromMapInternal(map[string]string{
+ _, _, err := DetectToken(t.Context(), "github", "aud", envGetterFromMapInternal(map[string]string{
"CI_JOB_JWT_V2": "gitlab.jwt",
}), http.DefaultClient)
diff --git a/cli/internal/client/client.go b/cli/internal/client/client.go
index bb60cac2f..baf56439e 100644
--- a/cli/internal/client/client.go
+++ b/cli/internal/client/client.go
@@ -256,9 +256,9 @@ func (c *Client) Request(ctx context.Context, method, path string, body any, hea
bodyBytes = v
case io.Reader:
// Streaming bodies cannot be replayed, so skip auto-refresh.
- req, err := http.NewRequestWithContext(ctx, method, fullURL, v)
- if err != nil {
- return nil, fmt.Errorf("failed to create request: %w", err)
+ req, newRequestWithContextErr := http.NewRequestWithContext(ctx, method, fullURL, v)
+ if newRequestWithContextErr != nil {
+ return nil, fmt.Errorf("failed to create request: %w", newRequestWithContextErr)
}
c.applyAuth(req)
req.Header.Set("Content-Type", "application/json")
@@ -269,17 +269,17 @@ func (c *Client) Request(ctx context.Context, method, path string, body any, hea
start := time.Now()
logger.GetLogger().Debug("Sending request", "method", method, "url", fullURL, "env_id", c.envID, "streaming_body", true)
- resp, err := c.httpClient.Do(req)
- if err != nil {
- logger.GetLogger().Debug("Request failed", "method", method, "url", fullURL, "env_id", c.envID, "duration", time.Since(start).String(), "error", err)
- return nil, fmt.Errorf("request failed: %w", err)
+ resp, newRequestWithContextErr := c.httpClient.Do(req)
+ if newRequestWithContextErr != nil {
+ logger.GetLogger().Debug("Request failed", "method", method, "url", fullURL, "env_id", c.envID, "duration", time.Since(start).String(), "error", newRequestWithContextErr)
+ return nil, fmt.Errorf("request failed: %w", newRequestWithContextErr)
}
logger.GetLogger().Debug("Response received", "method", method, "url", fullURL, "env_id", c.envID, "status", resp.Status, "duration", time.Since(start).String())
return resp, nil
default:
- jsonBody, err := json.Marshal(body)
- if err != nil {
- return nil, fmt.Errorf("failed to marshal request body: %w", err)
+ jsonBody, marshalErr := json.Marshal(body)
+ if marshalErr != nil {
+ return nil, fmt.Errorf("failed to marshal request body: %w", marshalErr)
}
bodyBytes = jsonBody
}
@@ -382,8 +382,8 @@ func (c *Client) doRequestInternal(ctx context.Context, method, fullURL string,
if resp.StatusCode == http.StatusUnauthorized && allowRefresh && c.jwtToken != "" && c.refreshToken != "" {
logger.GetLogger().Debug("Refreshing access token after unauthorized response", "method", method, "url", fullURL, "env_id", c.envID, "attempt", attempt)
_ = resp.Body.Close()
- if err := c.refreshAccessToken(ctx); err != nil {
- return nil, err
+ if refreshAccessTokenErr := c.refreshAccessToken(ctx); refreshAccessTokenErr != nil {
+ return nil, refreshAccessTokenErr
}
allowRefresh = false
continue
@@ -510,8 +510,8 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {
}
var result base.ApiResponse[auth.TokenRefreshResponse]
- if err := json.Unmarshal(respBody, &result); err != nil {
- return fmt.Errorf("failed to parse refresh response: %w", err)
+ if unmarshalErr := json.Unmarshal(respBody, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse refresh response: %w", unmarshalErr)
}
if !result.Success || result.Data.Token == "" {
return errors.New("token refresh failed: unexpected response from server")
@@ -533,8 +533,8 @@ func (c *Client) refreshAccessToken(ctx context.Context) error {
cfg.JWTToken = result.Data.Token
cfg.APIKey = ""
cfg.RefreshToken = newRefresh
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save refreshed token: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save refreshed token: %w", saveErr)
}
return nil
@@ -587,8 +587,8 @@ func (c *Client) DoJSON[T any](ctx context.Context, method, path string, body an
return out, fmt.Errorf("request failed with status %d: %s", resp.StatusCode, strings.TrimSpace(string(b)))
}
- if err := json.UnmarshalRead(resp.Body, &out); err != nil {
- return out, fmt.Errorf("failed to decode response: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &out); unmarshalReadErr != nil {
+ return out, fmt.Errorf("failed to decode response: %w", unmarshalReadErr)
}
return out, nil
}
@@ -673,8 +673,8 @@ func decodeResponseStrictInternal[T any](resp *http.Response) (*APIResponse[T],
}
var result APIResponse[T]
- if err := json.Unmarshal(body, &result); err != nil {
- return nil, fmt.Errorf("failed to decode response (body: %s): %w", string(body), err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return nil, fmt.Errorf("failed to decode response (body: %s): %w", string(body), unmarshalErr)
}
if !result.Success {
diff --git a/cli/internal/client/client_test.go b/cli/internal/client/client_test.go
index 62a6dc375..7494c825b 100644
--- a/cli/internal/client/client_test.go
+++ b/cli/internal/client/client_test.go
@@ -1,7 +1,6 @@
package client
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -34,7 +33,7 @@ func TestClient_UsesAPIKeyHeader(t *testing.T) {
require.NoError(t, err,
"New() error: %v", err)
- resp, err := c.Get(context.Background(), "/api/version")
+ resp, err := c.Get(t.Context(), "/api/version")
require.NoError(t, err,
"Get() error: %v", err)
@@ -67,7 +66,7 @@ func TestClient_UsesBearerTokenHeader(t *testing.T) {
require.NoError(t, err,
"New() error: %v", err)
- resp, err := c.Get(context.Background(), "/api/version")
+ resp, err := c.Get(t.Context(), "/api/version")
require.NoError(t, err,
"Get() error: %v", err)
@@ -96,7 +95,7 @@ func TestClient_NewUnauthenticated_DoesNotSendAuthHeaders(t *testing.T) {
require.NoError(t, err,
"NewUnauthenticated() error: %v", err)
- resp, err := c.Get(context.Background(), "/api/auth/login")
+ resp, err := c.Get(t.Context(), "/api/auth/login")
require.NoError(t, err,
"Get() error: %v", err)
@@ -140,7 +139,7 @@ func TestClient_Request_DoesNotDoubleMarshalBytes(t *testing.T) {
require.NoError(t, err,
"json.Marshal() error: %v", err)
- resp, err := c.Post(context.Background(), "/api/auth/login", raw)
+ resp, err := c.Post(t.Context(), "/api/auth/login", raw)
require.NoError(t, err,
"Post() error: %v", err)
diff --git a/cli/internal/client/retry_test.go b/cli/internal/client/retry_test.go
index abf22f1dd..85f2a1f19 100644
--- a/cli/internal/client/retry_test.go
+++ b/cli/internal/client/retry_test.go
@@ -1,7 +1,6 @@
package client
import (
- "context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -38,7 +37,7 @@ func TestClient_RetriesIdempotentRequests(t *testing.T) {
c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
- resp, err := c.Get(context.Background(), "/api/version")
+ resp, err := c.Get(t.Context(), "/api/version")
require.NoError(t, err,
"Get() error: %v", err)
@@ -70,7 +69,7 @@ func TestClient_DoesNotRetryNonIdempotentRequests(t *testing.T) {
c.SetRetryPolicy(3, 1*time.Millisecond, 2*time.Millisecond)
- resp, err := c.Post(context.Background(), "/api/version", map[string]any{"a": 1})
+ resp, err := c.Post(t.Context(), "/api/version", map[string]any{"a": 1})
require.NoError(t, err,
"Post() returned transport error: %v", err)
@@ -99,8 +98,8 @@ func TestClient_DoJSON_StrictStatus(t *testing.T) {
"New() error: %v", err)
{
- _, err := c.DoJSON[map[string]any](context.Background(), http.MethodGet, "/api/version", nil)
- require.Error(t, err,
+ _, requestErr := c.DoJSON[map[string]any](t.Context(), http.MethodGet, "/api/version", nil)
+ require.Error(t, requestErr,
"expected strict status error")
}
}
@@ -135,7 +134,7 @@ func TestClient_DoRaw_Success(t *testing.T) {
require.NoError(t, err,
"New() error: %v", err)
- b, err := c.DoRaw(context.Background(), http.MethodGet, "/api/version", nil)
+ b, err := c.DoRaw(t.Context(), http.MethodGet, "/api/version", nil)
require.NoError(t, err,
"DoRaw() error: %v", err)
diff --git a/cli/internal/cmdutil/resolve.go b/cli/internal/cmdutil/resolve.go
index 2d15226e5..49893e28b 100644
--- a/cli/internal/cmdutil/resolve.go
+++ b/cli/internal/cmdutil/resolve.go
@@ -114,16 +114,16 @@ func (ref ResourceRef[D, S]) Resolve(ctx context.Context, c *client.Client, iden
if ref.IDOf != nil {
identifierLower := strings.ToLower(trimmed)
if LooksLikeIDPrefix(identifierLower) {
- fallbackMatches, err := ref.fallbackByIDPrefixInternal(ctx, c, identifierLower)
- if err != nil {
- return nil, false, err
+ fallbackMatches, fallbackByIDPrefixErr := ref.fallbackByIDPrefixInternal(ctx, c, identifierLower)
+ if fallbackByIDPrefixErr != nil {
+ return nil, false, fallbackByIDPrefixErr
}
- selected, err := ref.selectCandidateInternal(fallbackMatches, trimmed, allowPrompt)
- if err != nil {
- return nil, false, err
+ fallbackCandidate, fallbackByIDPrefixErr := ref.selectCandidateInternal(fallbackMatches, trimmed, allowPrompt)
+ if fallbackByIDPrefixErr != nil {
+ return nil, false, fallbackByIDPrefixErr
}
- if selected != nil {
- return ref.Promote(*selected), false, nil
+ if fallbackCandidate != nil {
+ return ref.Promote(*fallbackCandidate), false, nil
}
}
}
@@ -145,12 +145,12 @@ func (ref ResourceRef[D, S]) fetchByIdentifierInternal(ctx context.Context, c *c
if resp.StatusCode == http.StatusOK {
var result base.ApiResponse[D]
- if err := json.Unmarshal(body, &result); err != nil {
- return nil, false, fmt.Errorf("failed to parse %s response: %w", ref.Singular, err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return nil, false, fmt.Errorf("failed to parse %s response: %w", ref.Singular, unmarshalErr)
}
if ref.Validate != nil {
- if err := ref.Validate(result.Data, identifier); err != nil {
- return nil, false, err
+ if validateErr := ref.Validate(result.Data, identifier); validateErr != nil {
+ return nil, false, validateErr
}
}
return &result.Data, true, nil
@@ -244,8 +244,8 @@ func (ref ResourceRef[D, S]) listItemsInternal(ctx context.Context, c *client.Cl
}
var result base.Paginated[S]
- if err := json.Unmarshal(body, &result); err != nil {
- return nil, fmt.Errorf("failed to parse %s response: %w", ref.Plural, err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return nil, fmt.Errorf("failed to parse %s response: %w", ref.Plural, unmarshalErr)
}
return result.Data, nil
}
diff --git a/cli/internal/cmdutil/run.go b/cli/internal/cmdutil/run.go
index 9e43e4e49..1dc3407a5 100644
--- a/cli/internal/cmdutil/run.go
+++ b/cli/internal/cmdutil/run.go
@@ -59,8 +59,8 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) erro
}
var result base.Paginated[T]
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
rows := make([][]string, len(result.Data))
@@ -68,7 +68,9 @@ func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) erro
rows[i] = spec.Row(item)
}
- output.Table(spec.Headers, rows)
+ if tableErr := output.Table(spec.Headers, rows); tableErr != nil {
+ return tableErr
+ }
output.Showing(len(result.Data), result.Pagination.TotalItems, spec.Resource)
return nil
}
diff --git a/cli/internal/cmdutil/upload.go b/cli/internal/cmdutil/upload.go
index 5623ca088..cd8f5a01c 100644
--- a/cli/internal/cmdutil/upload.go
+++ b/cli/internal/cmdutil/upload.go
@@ -65,9 +65,9 @@ func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath st
buf := make([]byte, session.ChunkSize)
for index := range session.TotalChunks {
expected := kit.Ternary(index == session.TotalChunks-1, session.Size-int64(index)*session.ChunkSize, session.ChunkSize)
- if _, err := io.ReadFull(file, buf[:expected]); err != nil {
+ if _, readFullErr := io.ReadFull(file, buf[:expected]); readFullErr != nil {
deleteSession()
- return "", fmt.Errorf("failed to read file: %w", err)
+ return "", fmt.Errorf("failed to read file: %w", readFullErr)
}
chunkPath := types.UploadSessionChunk(c.EnvID(), kind, session.ID, index)
diff --git a/cli/internal/config/config.go b/cli/internal/config/config.go
index 961b6edc9..ae6523475 100644
--- a/cli/internal/config/config.go
+++ b/cli/internal/config/config.go
@@ -163,16 +163,16 @@ func Load() (*types.Config, error) {
v.SetDefault("default_environment", "0")
v.SetDefault("federated_audience", "")
v.SetDefault("log_level", "info")
- if err := v.ReadInConfig(); err != nil {
- return nil, fmt.Errorf("failed to parse config file: %w", err)
+ if readInConfigErr := v.ReadInConfig(); readInConfigErr != nil {
+ return nil, fmt.Errorf("failed to parse config file: %w", readInConfigErr)
}
var cfg types.Config
- if err := v.Unmarshal(&cfg, func(dc *mapstructure.DecoderConfig) {
+ if unmarshalErr := v.Unmarshal(&cfg, func(dc *mapstructure.DecoderConfig) {
dc.TagName = "mapstructure"
dc.WeaklyTypedInput = true
- }); err != nil {
- return nil, fmt.Errorf("failed to unmarshal config: %w", err)
+ }); unmarshalErr != nil {
+ return nil, fmt.Errorf("failed to unmarshal config: %w", unmarshalErr)
}
normalized := normalizeConfig(&cfg)
@@ -192,8 +192,8 @@ func Save(c *types.Config) error {
// Ensure the config directory exists
dir := filepath.Dir(path)
- if err := os.MkdirAll(dir, 0o700); err != nil {
- return fmt.Errorf("failed to create config directory: %w", err)
+ if mkdirAllErr := os.MkdirAll(dir, 0o700); mkdirAllErr != nil {
+ return fmt.Errorf("failed to create config directory: %w", mkdirAllErr)
}
cfg := normalizeConfig(c)
@@ -234,11 +234,11 @@ func Save(c *types.Config) error {
v.Set(fmt.Sprintf("pagination.resources.%s.limit", resource), rc.Limit)
}
- if err := v.WriteConfigAs(path); err != nil {
- return fmt.Errorf("failed to write config file: %w", err)
+ if writeConfigAsErr := v.WriteConfigAs(path); writeConfigAsErr != nil {
+ return fmt.Errorf("failed to write config file: %w", writeConfigAsErr)
}
- if err := os.Chmod(path, 0o600); err != nil {
- return fmt.Errorf("failed to set config permissions: %w", err)
+ if chmodErr := os.Chmod(path, 0o600); chmodErr != nil {
+ return fmt.Errorf("failed to set config permissions: %w", chmodErr)
}
configCache.Set(path, cfg)
@@ -269,8 +269,8 @@ func InitDefaultFile() (bool, error) {
}
dir := filepath.Dir(path)
- if err := os.MkdirAll(dir, 0o700); err != nil {
- return false, fmt.Errorf("failed to create config directory: %w", err)
+ if mkdirAllErr := os.MkdirAll(dir, 0o700); mkdirAllErr != nil {
+ return false, fmt.Errorf("failed to create config directory: %w", mkdirAllErr)
}
v := viper.New()
@@ -288,11 +288,11 @@ func InitDefaultFile() (bool, error) {
v.Set(fmt.Sprintf("pagination.resources.%s.limit", resource), defaultPaginationInitLimit)
}
- if err := v.WriteConfigAs(path); err != nil {
- return false, fmt.Errorf("failed to write config file: %w", err)
+ if writeConfigAsErr := v.WriteConfigAs(path); writeConfigAsErr != nil {
+ return false, fmt.Errorf("failed to write config file: %w", writeConfigAsErr)
}
- if err := os.Chmod(path, 0o600); err != nil {
- return false, fmt.Errorf("failed to set config permissions: %w", err)
+ if chmodErr := os.Chmod(path, 0o600); chmodErr != nil {
+ return false, fmt.Errorf("failed to set config permissions: %w", chmodErr)
}
invalidateCache()
@@ -326,15 +326,15 @@ func BackupFile() (backupPath string, moved bool, err error) {
return "", false, fmt.Errorf("backup path is a directory: %s", backupPath)
}
rotatedPath := fmt.Sprintf("%s.%s", backupPath, time.Now().UTC().Format("20060102150405"))
- if err := os.Rename(backupPath, rotatedPath); err != nil {
- return "", false, fmt.Errorf("failed to rotate existing backup %s: %w", backupPath, err)
+ if renameErr := os.Rename(backupPath, rotatedPath); renameErr != nil {
+ return "", false, fmt.Errorf("failed to rotate existing backup %s: %w", backupPath, renameErr)
}
} else if !os.IsNotExist(backupErr) {
return "", false, fmt.Errorf("failed to stat backup path: %w", backupErr)
}
- if err := os.Rename(path, backupPath); err != nil {
- return "", false, fmt.Errorf("failed to move config to backup: %w", err)
+ if backupConfigErr := os.Rename(path, backupPath); backupConfigErr != nil {
+ return "", false, fmt.Errorf("failed to move config to backup: %w", backupConfigErr)
}
invalidateCache()
diff --git a/cli/internal/config/config_test.go b/cli/internal/config/config_test.go
index 5372eab35..52275e611 100644
--- a/cli/internal/config/config_test.go
+++ b/cli/internal/config/config_test.go
@@ -275,9 +275,9 @@ func TestBackupFileMovesConfig(t *testing.T) {
"backup path = %q, want %q", backupPath, path+".bak")
{
- _, err := os.Stat(path)
- require.True(t, os.IsNotExist(err),
- "expected original config to be removed, stat err=%v", err)
+ _, statErr := os.Stat(path)
+ require.True(t, os.IsNotExist(statErr),
+ "expected original config to be removed, stat err=%v", statErr)
}
raw, err := os.ReadFile(backupPath)
diff --git a/cli/internal/integrationtest/json_contract_test.go b/cli/internal/integrationtest/json_contract_test.go
index 11f35d1af..719c0b165 100644
--- a/cli/internal/integrationtest/json_contract_test.go
+++ b/cli/internal/integrationtest/json_contract_test.go
@@ -40,9 +40,9 @@ func TestContainersListJSONContract(t *testing.T) {
var got map[string]any
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, err,
- "json parse failed: %v\noutput=%s", err, outBuf)
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
}
for _, key := range []string{"success", "data", "pagination"} {
diff --git a/cli/internal/integrationtest/pagination_test.go b/cli/internal/integrationtest/pagination_test.go
index c391705ed..0a4abce1d 100644
--- a/cli/internal/integrationtest/pagination_test.go
+++ b/cli/internal/integrationtest/pagination_test.go
@@ -55,9 +55,9 @@ func TestContainersListSendsLimitAndStart(t *testing.T) {
var got map[string]any
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, err,
- "json parse failed: %v\noutput=%s", err, outBuf)
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
}
{
@@ -306,7 +306,7 @@ func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {
mu.Unlock()
require.FailNowf(t, "unexpected failure", "path = %q, want %q", gotPath, "/api/templates")
}
- if !(strings.Contains(gotQuery, "limit=7") && strings.Contains(gotQuery, "start=14")) {
+ if !strings.Contains(gotQuery, "limit=7") || !strings.Contains(gotQuery, "start=14") {
mu.Unlock()
require.FailNowf(t, "unexpected failure", "query = %q, want limit=7 and start=14", gotQuery)
}
@@ -314,9 +314,9 @@ func TestTemplatesListJSONIncludesPaginatedEnvelope(t *testing.T) {
var got map[string]any
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, err,
- "json parse failed: %v\noutput=%s", err, outBuf)
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
}
{
diff --git a/cli/internal/integrationtest/updates_commands_test.go b/cli/internal/integrationtest/updates_commands_test.go
index fe3fca074..4e671a102 100644
--- a/cli/internal/integrationtest/updates_commands_test.go
+++ b/cli/internal/integrationtest/updates_commands_test.go
@@ -54,9 +54,9 @@ func TestContainersListUpdatesJSONContract(t *testing.T) {
var got map[string]any
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, err,
- "json parse failed: %v\noutput=%s", err, outBuf)
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
}
for _, key := range []string{"success", "data", "pagination"} {
@@ -159,9 +159,9 @@ func TestProjectsListUpdatesJSONContract(t *testing.T) {
var got map[string]any
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
- require.NoError(t, err,
- "json parse failed: %v\noutput=%s", err, outBuf)
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &got)
+ require.NoError(t, unmarshalErr,
+ "json parse failed: %v\noutput=%s", unmarshalErr, outBuf)
}
for _, key := range []string{"success", "data", "pagination"} {
@@ -270,9 +270,9 @@ func TestImagesUpdatesCheckEncodesImageRefAndDecodesSingleResponse(t *testing.T)
var result imageupdate.Response
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &result)
- require.NoError(t, err,
- "single response JSON parse failed: %v\noutput=%s", err, outBuf)
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &result)
+ require.NoError(t, unmarshalErr,
+ "single response JSON parse failed: %v\noutput=%s", unmarshalErr, outBuf)
}
require.False(t, !result.HasUpdate || result.CurrentVersion != "1.0.0" || result.LatestVersion != "1.1.0",
@@ -346,9 +346,9 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
var batch imageupdate.BatchResponse
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &batch)
- require.NoError(t, err,
- "batch response JSON parse failed: %v\noutput=%s", err, outBuf)
+ unmarshalErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &batch)
+ require.NoError(t, unmarshalErr,
+ "batch response JSON parse failed: %v\noutput=%s", unmarshalErr, outBuf)
}
require.False(t, batch["nginx:latest"] == nil || !batch["nginx:latest"].HasUpdate,
@@ -364,9 +364,9 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
var single imageupdate.Response
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &single)
- require.NoError(t, err,
- "single response JSON parse failed: %v\noutput=%s", err, outBuf)
+ decodeSingleResponseErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &single)
+ require.NoError(t, decodeSingleResponseErr,
+ "single response JSON parse failed: %v\noutput=%s", decodeSingleResponseErr, outBuf)
}
require.False(t, single.HasUpdate || single.CurrentVersion != "1.1.0",
@@ -382,9 +382,9 @@ func TestImageUpdateCommandsDecodeExpectedResponseTypes(t *testing.T) {
var summary imageupdate.Summary
{
- err := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &summary)
- require.NoError(t, err,
- "summary response JSON parse failed: %v\noutput=%s", err, outBuf)
+ decodeSummaryResponseErr := json.Unmarshal([]byte(strings.TrimSpace(outBuf)), &summary)
+ require.NoError(t, decodeSummaryResponseErr,
+ "summary response JSON parse failed: %v\noutput=%s", decodeSummaryResponseErr, outBuf)
}
require.False(t, summary.TotalImages != 4 || summary.ImagesWithUpdates != 2 || summary.DigestUpdates != 1,
diff --git a/cli/internal/output/output.go b/cli/internal/output/output.go
index b78646b28..ced1dc3c5 100644
--- a/cli/internal/output/output.go
+++ b/cli/internal/output/output.go
@@ -236,12 +236,14 @@ func TintInsecure(value string) string {
// Table prints a formatted table with headers and rows.
// Rendering uses Lip Gloss table styles with zebra-striped rows.
-func Table(headers []string, rows [][]string) {
- fmt.Println()
+func Table(headers []string, rows [][]string) error {
+ if _, spacingErr := fmt.Println(); spacingErr != nil {
+ return fmt.Errorf("failed to print table: %w", spacingErr)
+ }
n := len(headers)
if n == 0 {
- return
+ return nil
}
rows = normalizeTableRows(rows, n)
@@ -272,7 +274,10 @@ func Table(headers []string, rows [][]string) {
t = t.Rows(rows...)
}
- lipgloss.Println(t)
+ if _, tableErr := lipgloss.Println(t); tableErr != nil {
+ return fmt.Errorf("failed to print table: %w", tableErr)
+ }
+ return nil
}
func fitTableToTerminal(headers []string, rows [][]string) ([]string, [][]string) {
diff --git a/cli/pkg/admin/apikeys/cmd.go b/cli/pkg/admin/apikeys/cmd.go
index 1559b2aea..b990d438d 100644
--- a/cli/pkg/admin/apikeys/cmd.go
+++ b/cli/pkg/admin/apikeys/cmd.go
@@ -149,9 +149,9 @@ var createCmd = &cobra.Command{
createReq.Description = &description
}
if expiresAtRaw, _ := cmd.Flags().GetString("expires-at"); expiresAtRaw != "" {
- parsed, err := time.Parse(time.RFC3339, expiresAtRaw)
- if err != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)
+ parsed, parseErr := time.Parse(time.RFC3339, expiresAtRaw)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
}
createReq.ExpiresAt = &parsed
}
@@ -257,7 +257,9 @@ var getCmd = &cobra.Command{
}
rows[i] = []string{g.Permission, scope}
}
- output.Table([]string{"PERMISSION", "SCOPE"}, rows)
+ if tableErr := output.Table([]string{"PERMISSION", "SCOPE"}, rows); tableErr != nil {
+ return tableErr
+ }
}
return nil
},
@@ -282,16 +284,16 @@ var updateCmd = &cobra.Command{
req.Description = &apikeyUpdateDescription
}
if cmd.Flags().Changed("expires-at") && apikeyUpdateExpiresAt != "" {
- parsedTime, err := time.Parse(time.RFC3339, apikeyUpdateExpiresAt)
- if err != nil {
- return fmt.Errorf("invalid expires-at format (use RFC3339): %w", err)
+ parsedTime, parseErr := time.Parse(time.RFC3339, apikeyUpdateExpiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid expires-at format (use RFC3339): %w", parseErr)
}
req.ExpiresAt = &parsedTime
}
if cmd.Flags().Changed("permission") {
- grants, err := parsePermissionGrantsInternal(apikeyUpdatePermissions)
- if err != nil {
- return err
+ grants, parsePermissionGrantsErr := parsePermissionGrantsInternal(apikeyUpdatePermissions)
+ if parsePermissionGrantsErr != nil {
+ return parsePermissionGrantsErr
}
// Allow `--permission ""` once to clear all grants. Otherwise
// the parsed slice replaces the key's permission set entirely.
diff --git a/cli/pkg/admin/events/cmd.go b/cli/pkg/admin/events/cmd.go
index 3ae67b716..570f34d41 100644
--- a/cli/pkg/admin/events/cmd.go
+++ b/cli/pkg/admin/events/cmd.go
@@ -101,8 +101,8 @@ var deleteCmd = &cobra.Command{
return err
}
- if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Event(args[0])); err != nil {
- return fmt.Errorf("failed to delete event: %w", err)
+ if _, deleteEventErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Event(args[0])); deleteEventErr != nil {
+ return fmt.Errorf("failed to delete event: %w", deleteEventErr)
}
output.Success("Event deleted successfully")
diff --git a/cli/pkg/admin/federatedcredentials/cmd.go b/cli/pkg/admin/federatedcredentials/cmd.go
index 375331dd6..287d22892 100644
--- a/cli/pkg/admin/federatedcredentials/cmd.go
+++ b/cli/pkg/admin/federatedcredentials/cmd.go
@@ -147,9 +147,9 @@ var createCmd = &cobra.Command{
req.TokenTTLSeconds = createTokenTTL
}
if createExpiresAt != "" {
- parsed, err := time.Parse(time.RFC3339, createExpiresAt)
- if err != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)
+ parsed, parseErr := time.Parse(time.RFC3339, createExpiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
}
req.ExpiresAt = &parsed
}
@@ -225,9 +225,9 @@ var updateCmd = &cobra.Command{
req.TokenTTLSeconds = &updateTokenTTL
}
if cmd.Flags().Changed("expires-at") && updateExpiresAt != "" {
- parsed, err := time.Parse(time.RFC3339, updateExpiresAt)
- if err != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)
+ parsed, parseErr := time.Parse(time.RFC3339, updateExpiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
}
req.ExpiresAt = &parsed
}
@@ -270,8 +270,8 @@ var deleteCmd = &cobra.Command{
return err
}
- if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.FederatedCredential(args[0])); err != nil {
- return fmt.Errorf("failed to delete federated credential: %w", err)
+ if _, deleteCredentialErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.FederatedCredential(args[0])); deleteCredentialErr != nil {
+ return fmt.Errorf("failed to delete federated credential: %w", deleteCredentialErr)
}
output.Success("Federated credential deleted")
diff --git a/cli/pkg/admin/notifications/cmd.go b/cli/pkg/admin/notifications/cmd.go
index 63cc81b39..ebe2eb1fc 100644
--- a/cli/pkg/admin/notifications/cmd.go
+++ b/cli/pkg/admin/notifications/cmd.go
@@ -64,7 +64,9 @@ var settingsGetCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d notification settings\n", len(result))
return nil
},
@@ -124,8 +126,8 @@ var settingsSetCmd = &cobra.Command{
if err != nil {
return fmt.Errorf("failed to read settings file: %w", err)
}
- if err := json.Unmarshal(data, &req); err != nil {
- return fmt.Errorf("failed to parse settings file: %w", err)
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse settings file: %w", unmarshalErr)
}
}
diff --git a/cli/pkg/admin/oidcmappings/cmd.go b/cli/pkg/admin/oidcmappings/cmd.go
index 80e93cd6c..ad8fdab37 100644
--- a/cli/pkg/admin/oidcmappings/cmd.go
+++ b/cli/pkg/admin/oidcmappings/cmd.go
@@ -36,7 +36,9 @@ var OidcMappingsCmd = &cobra.Command{
Use: "oidc",
Aliases: []string{"oidc-mappings", "oidc-mapping"},
Short: "Manage OIDC group → role mappings",
- Long: "Manage OIDC group → role mappings. On every OIDC login, Arcane looks up the user's groups claim and applies the matching mappings as source='oidc' role assignments. The groups claim itself is configured via the oidcGroupsClaim setting (default `groups`).",
+ Long: "Manage OIDC group → role mappings. On every OIDC login, Arcane looks up the user's groups claim and applies " +
+ "the matching mappings as source='oidc' role assignments. The groups claim itself is configured via the " +
+ "oidcGroupsClaim setting (default `groups`).",
}
var listCmd = &cobra.Command{
@@ -72,8 +74,7 @@ var listCmd = &cobra.Command{
}
rows[i] = []string{m.ID, m.ClaimValue, m.RoleID, scope}
}
- output.Table(headers, rows)
- return nil
+ return output.Table(headers, rows)
},
}
@@ -158,8 +159,8 @@ var updateCmd = &cobra.Command{
return fmt.Errorf("failed to update OIDC mapping: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to update OIDC mapping: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to update OIDC mapping: %w", ensureSuccessStatusErr)
}
output.Success("OIDC mapping updated")
return nil
@@ -192,8 +193,8 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete OIDC mapping: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete OIDC mapping: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete OIDC mapping: %w", ensureSuccessStatusErr)
}
output.Success("OIDC mapping deleted")
return nil
diff --git a/cli/pkg/admin/roles/cmd.go b/cli/pkg/admin/roles/cmd.go
index 2d8219039..3358cf8eb 100644
--- a/cli/pkg/admin/roles/cmd.go
+++ b/cli/pkg/admin/roles/cmd.go
@@ -121,7 +121,9 @@ var getCmd = &cobra.Command{
for i, p := range result.Data.Permissions {
rows[i] = []string{p}
}
- output.Table([]string{"PERMISSION"}, rows)
+ if tableErr := output.Table([]string{"PERMISSION"}, rows); tableErr != nil {
+ return tableErr
+ }
}
return nil
},
@@ -205,8 +207,8 @@ var updateCmd = &cobra.Command{
return fmt.Errorf("failed to update role: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to update role: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to update role: %w", ensureSuccessStatusErr)
}
output.Success("Role updated")
@@ -240,8 +242,8 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete role: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete role: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete role: %w", ensureSuccessStatusErr)
}
output.Success("Role deleted")
return nil
@@ -275,7 +277,9 @@ var permissionsCmd = &cobra.Command{
for i, a := range group.Actions {
rows[i] = []string{a.Permission, a.Label, a.Description}
}
- output.Table([]string{"PERMISSION", "LABEL", "DESCRIPTION"}, rows)
+ if tableErr := output.Table([]string{"PERMISSION", "LABEL", "DESCRIPTION"}, rows); tableErr != nil {
+ return tableErr
+ }
}
return nil
},
@@ -314,15 +318,17 @@ var assignmentsCmd = &cobra.Command{
}
rows[i] = []string{a.RoleID, scope, a.Source, a.CreatedAt.Format("2006-01-02 15:04")}
}
- output.Table([]string{"ROLE", "SCOPE", "SOURCE", "CREATED"}, rows)
- return nil
+ return output.Table([]string{"ROLE", "SCOPE", "SOURCE", "CREATED"}, rows)
},
}
var assignCmd = &cobra.Command{
Use: "assign <user-id>",
Short: "Replace a user's manual role assignments",
- Long: "Replace every MANUAL role assignment on the user with the set passed via --role. OIDC-sourced assignments are left untouched — manage those via OIDC role mappings.\n\nEach --role flag accepts `<roleId>[:<envId>]`. Omit the env id for a global assignment. Pass --role multiple times to assign more than one role. Pass --role \"\" (empty) once to clear every manual assignment.",
+ Long: "Replace every MANUAL role assignment on the user with the set passed via --role. OIDC-sourced assignments are " +
+ "left untouched — manage those via OIDC role mappings.\n\nEach --role flag accepts `<roleId>[:<envId>]`. Omit " +
+ "the env id for a global assignment. Pass --role multiple times to assign more than one role. Pass --role \"\" " +
+ "(empty) once to clear every manual assignment.",
Example: ` arcane admin roles assign u_123 --role role_editor:env_prod --role role_viewer
arcane admin roles assign u_123 --role role_admin
diff --git a/cli/pkg/admin/users/cmd.go b/cli/pkg/admin/users/cmd.go
index ba130806e..8b38286d8 100644
--- a/cli/pkg/admin/users/cmd.go
+++ b/cli/pkg/admin/users/cmd.go
@@ -139,9 +139,9 @@ var createCmd = &cobra.Command{
if userCreatePassword == "" {
fmt.Print("Password: ")
- bytePassword, err := term.ReadPassword(os.Stdin.Fd())
- if err != nil {
- return fmt.Errorf("failed to read password: %w", err)
+ bytePassword, readPasswordErr := term.ReadPassword(os.Stdin.Fd())
+ if readPasswordErr != nil {
+ return fmt.Errorf("failed to read password: %w", readPasswordErr)
}
userCreatePassword = string(bytePassword)
fmt.Println()
@@ -215,7 +215,9 @@ var getCmd = &cobra.Command{
}
rows[i] = []string{a.RoleID, env, a.Source}
}
- output.Table([]string{"ROLE", "SCOPE", "SOURCE"}, rows)
+ if tableErr := output.Table([]string{"ROLE", "SCOPE", "SOURCE"}, rows); tableErr != nil {
+ return tableErr
+ }
}
return nil
},
@@ -285,8 +287,8 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete user: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete user: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete user: %w", ensureSuccessStatusErr)
}
output.Success("User deleted successfully")
diff --git a/cli/pkg/auth/apikeys.go b/cli/pkg/auth/apikeys.go
index 6b830aca5..5b80481a5 100644
--- a/cli/pkg/auth/apikeys.go
+++ b/cli/pkg/auth/apikeys.go
@@ -25,7 +25,8 @@ var apiKeysCmd = &cobra.Command{
Use: "keys",
Aliases: []string{"apikeys", "key"},
Short: "Manage your own API keys",
- Long: "Manage the current user's personal API keys. Personal keys inherit the owner's role permissions. Creating and deleting them requires a session login (an API key cannot mint or remove other keys).",
+ Long: "Manage the current user's personal API keys. Personal keys inherit the owner's role permissions. Creating and " +
+ "deleting them requires a session login (an API key cannot mint or remove other keys).",
}
var apiKeysListCmd = &cobra.Command{
@@ -74,8 +75,7 @@ var apiKeysListCmd = &cobra.Command{
key.CreatedAt.Format("2006-01-02 15:04"),
}
}
- output.Table(headers, rows)
- return nil
+ return output.Table(headers, rows)
},
}
@@ -95,9 +95,9 @@ var apiKeysCreateCmd = &cobra.Command{
req.Description = &apiKeyCreateDescription
}
if apiKeyCreateExpiresAt != "" {
- parsed, err := time.Parse(time.RFC3339, apiKeyCreateExpiresAt)
- if err != nil {
- return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", err)
+ parsed, parseErr := time.Parse(time.RFC3339, apiKeyCreateExpiresAt)
+ if parseErr != nil {
+ return fmt.Errorf("invalid --expires-at format (use RFC3339): %w", parseErr)
}
req.ExpiresAt = &parsed
}
@@ -148,8 +148,8 @@ var apiKeysDeleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete API key: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete API key: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete API key: %w", ensureSuccessStatusErr)
}
output.Success("API key deleted")
diff --git a/cli/pkg/auth/cmd.go b/cli/pkg/auth/cmd.go
index 1662193b5..f2ac2b632 100644
--- a/cli/pkg/auth/cmd.go
+++ b/cli/pkg/auth/cmd.go
@@ -63,8 +63,8 @@ var loginCmd = &cobra.Command{
}
var deviceAuth auth.OidcDeviceAuthResponse
- if err := json.Unmarshal(bodyBytes, &deviceAuth); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(bodyBytes, &deviceAuth); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
output.Header("Device Login")
@@ -100,15 +100,15 @@ var loginCmd = &cobra.Command{
return cmd.Context().Err()
}
- tokenResp, err := c.Post(cmd.Context(), types.OIDCDeviceToken(), tokenReqBody)
- if err != nil {
- return fmt.Errorf("device token exchange failed: %w", err)
+ tokenResp, postErr := c.Post(cmd.Context(), types.OIDCDeviceToken(), tokenReqBody)
+ if postErr != nil {
+ return fmt.Errorf("device token exchange failed: %w", postErr)
}
- tokenBody, err := io.ReadAll(tokenResp.Body)
+ tokenBody, postErr := io.ReadAll(tokenResp.Body)
_ = tokenResp.Body.Close()
- if err != nil {
- return fmt.Errorf("failed to read token response: %w", err)
+ if postErr != nil {
+ return fmt.Errorf("failed to read token response: %w", postErr)
}
if tokenResp.StatusCode < 200 || tokenResp.StatusCode >= 300 {
@@ -125,15 +125,16 @@ var loginCmd = &cobra.Command{
case "access_denied":
return errors.New("device authorization denied")
case "mfa_required":
- return errors.New("this account has MFA enabled, which browser-based CLI login cannot complete; create a personal API key in Arcane (Account -> API keys) and run: arcane config set api-key <key>")
+ return errors.New("this account has MFA enabled, which browser-based CLI login cannot complete; create a personal API key in " +
+ "Arcane (Account -> API keys) and run: arcane config set api-key <key>")
default:
return fmt.Errorf("device token exchange failed (status %d): %s", tokenResp.StatusCode, strings.TrimSpace(string(tokenBody)))
}
}
var tokenResult auth.AuthenticationResponse
- if err := json.Unmarshal(tokenBody, &tokenResult); err != nil {
- return fmt.Errorf("failed to parse token response: %w", err)
+ if decodeTokenResponseErr := json.Unmarshal(tokenBody, &tokenResult); decodeTokenResponseErr != nil {
+ return fmt.Errorf("failed to parse token response: %w", decodeTokenResponseErr)
}
if !tokenResult.Success || tokenResult.Token == "" {
return errors.New("device token exchange failed: unexpected response from server")
@@ -149,15 +150,15 @@ var loginCmd = &cobra.Command{
})
}
- cfg, err := config.Load()
- if err != nil {
- return fmt.Errorf("failed to load config: %w", err)
+ cfg, postErr := config.Load()
+ if postErr != nil {
+ return fmt.Errorf("failed to load config: %w", postErr)
}
cfg.JWTToken = tokenResult.Token
cfg.RefreshToken = tokenResult.RefreshToken
cfg.APIKey = ""
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save token: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save token: %w", saveErr)
}
output.Success("Login successful")
@@ -190,8 +191,8 @@ var logoutCmd = &cobra.Command{
}
cfg.JWTToken = ""
cfg.RefreshToken = ""
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to clear token: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to clear token: %w", saveErr)
}
if cmdutil.JSONOutputEnabled(cmd) || jsonOutput {
@@ -303,8 +304,8 @@ var refreshCmd = &cobra.Command{
}
if refreshToken == "" {
fmt.Print("Refresh token: ")
- if _, err := fmt.Scanln(&refreshToken); err != nil {
- return fmt.Errorf("failed to read refresh token: %w", err)
+ if _, scanlnErr := fmt.Scanln(&refreshToken); scanlnErr != nil {
+ return fmt.Errorf("failed to read refresh token: %w", scanlnErr)
}
}
@@ -337,8 +338,8 @@ var refreshCmd = &cobra.Command{
if result.Data.RefreshToken != "" {
cfg.RefreshToken = result.Data.RefreshToken
}
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save token: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save token: %w", saveErr)
}
output.Success("Token refreshed successfully")
diff --git a/cli/pkg/auth/federated.go b/cli/pkg/auth/federated.go
index ccd3334da..29b751058 100644
--- a/cli/pkg/auth/federated.go
+++ b/cli/pkg/auth/federated.go
@@ -88,8 +88,8 @@ GitHub Actions example:
cfg.JWTToken = tokenResp.AccessToken
cfg.APIKey = ""
cfg.RefreshToken = ""
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save federated token: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save federated token: %w", saveErr)
}
}
@@ -201,8 +201,8 @@ func exchangeFederatedTokenInternal(cmd *cobra.Command, c *client.Client, subjec
}
var tokenResp federatedtypes.FederatedTokenResponse
- if err := json.Unmarshal(body, &tokenResp); err != nil {
- return nil, fmt.Errorf("failed to parse federated token response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &tokenResp); unmarshalErr != nil {
+ return nil, fmt.Errorf("failed to parse federated token response: %w", unmarshalErr)
}
return &tokenResp, nil
}
diff --git a/cli/pkg/backups/cmd.go b/cli/pkg/backups/cmd.go
index 4636616ae..45b93a7f9 100644
--- a/cli/pkg/backups/cmd.go
+++ b/cli/pkg/backups/cmd.go
@@ -119,9 +119,9 @@ alone stores it in S3, and --local together with --s3-destination stores it in b
s3DestinationID := ""
if createS3Destination != "" {
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, createS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
+ resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, createS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
+ if resolveErr != nil {
+ return resolveErr
}
s3DestinationID = resolved.ID
}
@@ -365,12 +365,11 @@ var policiesCmd = &cobra.Command{
return cmdutil.PrintJSON(result)
}
- printPolicies(result)
- return nil
+ return printPolicies(result)
},
}
-func printPolicies(result backup.SystemBackupPolicyCollection) {
+func printPolicies(result backup.SystemBackupPolicyCollection) error {
output.Header("System Backup Policies")
recoveryKey := kit.Ternary(result.RecoveryKeyStored, "Configured", "Not configured")
output.KeyValue("Recovery Key", recoveryKey)
@@ -393,7 +392,7 @@ func printPolicies(result backup.SystemBackupPolicyCollection) {
lastRun,
}
}
- output.Table(headers, rows)
+ return output.Table(headers, rows)
}
var policiesUpdateCmd = &cobra.Command{
@@ -430,13 +429,13 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,
return fmt.Errorf("failed to read file %s: %w", policiesUpdateFile, err)
}
}
- if err := json.Unmarshal(data, &req); err != nil {
- return fmt.Errorf("failed to parse policies file: %w", err)
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse policies file: %w", unmarshalErr)
}
} else {
- current, err := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
- if err != nil {
- return fmt.Errorf("failed to get current backup policies: %w", err)
+ current, getPoliciesErr := c.DoJSON[backup.SystemBackupPolicyCollection](cmd.Context(), http.MethodGet, types.BackupsPolicies(), nil)
+ if getPoliciesErr != nil {
+ return fmt.Errorf("failed to get current backup policies: %w", getPoliciesErr)
}
req.Policies = make([]backup.UpdateSystemBackupPolicy, len(current.Policies))
@@ -492,9 +491,9 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,
target.S3Enabled = policiesUpdateS3
}
if cmd.Flags().Changed("s3-destination") {
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, policiesUpdateS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
+ resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, policiesUpdateS3Destination, !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
+ if resolveErr != nil {
+ return resolveErr
}
target.S3DestinationID = resolved.ID
if !cmd.Flags().Changed("s3") {
@@ -513,8 +512,7 @@ Alternatively, --file replaces all policies from a raw JSON payload.`,
}
output.Success("Backup policies updated successfully")
- printPolicies(result)
- return nil
+ return printPolicies(result)
},
}
@@ -541,8 +539,8 @@ var recoveryKeyGenerateCmd = &cobra.Command{
if cmdutil.JSONOutputEnabled(cmd) {
if generateSave {
- if err := storeRecoveryKey(cmd, c, result.RecoveryKey); err != nil {
- return err
+ if storeRecoveryKeyErr := storeRecoveryKey(cmd, c, result.RecoveryKey); storeRecoveryKeyErr != nil {
+ return storeRecoveryKeyErr
}
}
return cmdutil.PrintJSON(result)
@@ -563,8 +561,8 @@ var recoveryKeyGenerateCmd = &cobra.Command{
fmt.Println("Run `arcane backups recovery set` to store it on the server later.")
return nil
}
- if err := storeRecoveryKey(cmd, c, result.RecoveryKey); err != nil {
- return err
+ if storeRotatedRecoveryKeyErr := storeRecoveryKey(cmd, c, result.RecoveryKey); storeRotatedRecoveryKeyErr != nil {
+ return storeRotatedRecoveryKeyErr
}
output.Success("Recovery key stored on the server")
return nil
diff --git a/cli/pkg/backups/s3.go b/cli/pkg/backups/s3.go
index 59b39d7e4..2bfcdcd33 100644
--- a/cli/pkg/backups/s3.go
+++ b/cli/pkg/backups/s3.go
@@ -225,9 +225,9 @@ var s3DeleteCmd = &cobra.Command{
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete S3 destination %s?", resolved.Name))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete S3 destination %s?", resolved.Name))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -276,9 +276,9 @@ passing the connection flags (--name, --bucket, --region, ...) with no argument.
if connectionFlagsSet {
return errors.New("pass either a saved destination name or ID, or the connection flags, not both")
}
- resolved, _, err := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
- if err != nil {
- return err
+ resolved, _, resolveErr := s3DestinationRef.Resolve(cmd.Context(), c, args[0], !cmdutil.JSONOutputEnabled(cmd) && prompt.IsInteractive())
+ if resolveErr != nil {
+ return resolveErr
}
testPath, testBody = types.BackupsS3DestinationTest(resolved.ID), nil
} else if s3Bucket == "" {
diff --git a/cli/pkg/config/cmd.go b/cli/pkg/config/cmd.go
index f6b895d58..6ee2495e5 100644
--- a/cli/pkg/config/cmd.go
+++ b/cli/pkg/config/cmd.go
@@ -137,11 +137,13 @@ Legacy flag syntax (flags shown below) is still supported:
updated = updated || updatedByFlags
if !updated {
- return errors.New("no configuration values provided. Use `arcane config set <key> <value>` (e.g. `arcane config set server-url http://localhost:3552`) or legacy flags (--server-url, --api-key, --jwt-token, --environment, --log-level, --default-limit, --resource-limit)")
+ return errors.New("no configuration values provided. Use `arcane config set <key> <value>` (e.g. `arcane config set server-url " +
+ "http://localhost:3552`) or legacy flags (--server-url, --api-key, --jwt-token, --environment, --log-level, " +
+ "--default-limit, --resource-limit)")
}
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save config: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save config: %w", saveErr)
}
path, _ := config.ConfigPath()
@@ -173,15 +175,15 @@ var configTestCmd = &cobra.Command{
return fmt.Errorf("failed to load config: %w", err)
}
- if err := cfg.Validate(); err != nil {
- return err
+ if validateErr := cfg.Validate(); validateErr != nil {
+ return validateErr
}
fmt.Printf("Testing connection to %s...\n", cfg.ServerURL)
// Test connection directly without importing client to avoid circular import
httpClient := &http.Client{Timeout: 10 * time.Second}
- req, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, cfg.ServerURL+"/api/version", nil)
+ req, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, cfg.ServerURL+"/api/version", http.NoBody)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
@@ -490,7 +492,8 @@ func applyConfigSetArg(cfg *types.Config, key, value string) (bool, error) {
return applyResourceLimitByKey(cfg, key, resource, value)
}
- return false, fmt.Errorf("unknown config key %q. Supported keys include server-url, api-key, jwt-token, environment, federated-audience, log-level, default-limit, resource-limit, and pagination.resources.<resource>.limit", key)
+ return false, fmt.Errorf("unknown config key %q. Supported keys include server-url, api-key, jwt-token, environment, "+
+ "federated-audience, log-level, default-limit, resource-limit, and pagination.resources.<resource>.limit", key)
}
func applyResourceLimitByKey(cfg *types.Config, key, resourceValue, limitValue string) (bool, error) {
diff --git a/cli/pkg/containers/actions.go b/cli/pkg/containers/actions.go
index c701a386f..5e02351ea 100644
--- a/cli/pkg/containers/actions.go
+++ b/cli/pkg/containers/actions.go
@@ -166,9 +166,9 @@ var containersEditCmd = &cobra.Command{
}
if editFile == "" {
- result, err := c.GetJSON[container.EditConfig](cmd.Context(), types.ContainerEditConfig(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to get container edit config: %w", err)
+ result, getEditConfigErr := c.GetJSON[container.EditConfig](cmd.Context(), types.ContainerEditConfig(c.EnvID(), resolved.ID))
+ if getEditConfigErr != nil {
+ return fmt.Errorf("failed to get container edit config: %w", getEditConfigErr)
}
return cmdutil.PrintJSON(result.Data)
@@ -179,8 +179,8 @@ var containersEditCmd = &cobra.Command{
return fmt.Errorf("failed to read file %s: %w", editFile, err)
}
var body container.Edit
- if err := json.Unmarshal(data, &body); err != nil {
- return fmt.Errorf("failed to parse edit payload: %w", err)
+ if unmarshalErr := json.Unmarshal(data, &body); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse edit payload: %w", unmarshalErr)
}
c.SetTimeout(30 * time.Minute)
diff --git a/cli/pkg/containers/cmd.go b/cli/pkg/containers/cmd.go
index d231c6b48..910d86622 100644
--- a/cli/pkg/containers/cmd.go
+++ b/cli/pkg/containers/cmd.go
@@ -188,9 +188,9 @@ var containersGetCmd = &cobra.Command{
}
if !complete {
- result, err := c.GetJSON[container.Details](cmd.Context(), types.Container(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to get container: %w", err)
+ result, getContainerErr := c.GetJSON[container.Details](cmd.Context(), types.Container(c.EnvID(), resolved.ID))
+ if getContainerErr != nil {
+ return fmt.Errorf("failed to get container: %w", getContainerErr)
}
resolved = &result.Data
}
@@ -358,9 +358,9 @@ var containersDeleteCmd = &cobra.Command{
displayName := containerDisplayName(resolved)
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete container %s?", displayName))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete container %s?", displayName))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -429,12 +429,12 @@ var containersCreateCmd = &cobra.Command{
// File mode: read base config from file
if containerCreateFile != "" {
- data, err := os.ReadFile(containerCreateFile)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", containerCreateFile, err)
+ data, readFileErr := os.ReadFile(containerCreateFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read file %s: %w", containerCreateFile, readFileErr)
}
- if err := json.Unmarshal(data, &req); err != nil {
- return fmt.Errorf("failed to parse config file: %w", err)
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse config file: %w", unmarshalErr)
}
}
diff --git a/cli/pkg/doctor/cmd.go b/cli/pkg/doctor/cmd.go
index 5156cb125..bfe252e44 100644
--- a/cli/pkg/doctor/cmd.go
+++ b/cli/pkg/doctor/cmd.go
@@ -91,9 +91,9 @@ var DoctorCmd = &cobra.Command{
rep.Healthy = false
rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "fail", Details: err.Error()})
} else {
- if err := c.TestConnection(cmd.Context()); err != nil {
+ if testConnectionErr := c.TestConnection(cmd.Context()); testConnectionErr != nil {
rep.Healthy = false
- rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "fail", Details: err.Error()})
+ rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "fail", Details: testConnectionErr.Error()})
} else {
rep.Checks = append(rep.Checks, checkResult{Name: "api_connection", Status: "ok", Details: "connected"})
}
@@ -114,7 +114,9 @@ var DoctorCmd = &cobra.Command{
for _, item := range rep.Checks {
rows = append(rows, []string{item.Name, item.Status, item.Details})
}
- output.Table([]string{"CHECK", "STATUS", "DETAILS"}, rows)
+ if tableErr := output.Table([]string{"CHECK", "STATUS", "DETAILS"}, rows); tableErr != nil {
+ return tableErr
+ }
if rep.Healthy {
output.Success("Doctor checks passed")
} else {
diff --git a/cli/pkg/environments/cmd.go b/cli/pkg/environments/cmd.go
index ff3f698df..24970ae27 100644
--- a/cli/pkg/environments/cmd.go
+++ b/cli/pkg/environments/cmd.go
@@ -118,8 +118,8 @@ var deleteCmd = &cobra.Command{
return err
}
- if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Environment(args[0])); err != nil {
- return fmt.Errorf("failed to delete environment: %w", err)
+ if _, deleteEnvironmentErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.Environment(args[0])); deleteEnvironmentErr != nil {
+ return fmt.Errorf("failed to delete environment: %w", deleteEnvironmentErr)
}
output.Success("Environment deleted successfully")
@@ -268,8 +268,8 @@ var switchCmd = &cobra.Command{
}
cfg.DefaultEnvironment = selected.ID
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save config: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save config: %w", saveErr)
}
output.Success("Default environment set to %s", selected.ID)
diff --git a/cli/pkg/generate/certs.go b/cli/pkg/generate/certs.go
index af72e624a..97c3440a2 100644
--- a/cli/pkg/generate/certs.go
+++ b/cli/pkg/generate/certs.go
@@ -179,11 +179,11 @@ func generateEdgeMTLSBundleInternal(outDir, envID, appURL string) (*edgeMTLSPath
ClientCertPath: filepath.Join(outDir, "agent.crt"),
ClientKeyPath: filepath.Join(outDir, "agent.key"),
}
- if err := writeCertificateBundleInternal(paths.CACertPath, paths.CAKeyPath, caDER, caKey); err != nil {
- return nil, err
+ if writeCertificateBundleErr := writeCertificateBundleInternal(paths.CACertPath, paths.CAKeyPath, caDER, caKey); writeCertificateBundleErr != nil {
+ return nil, writeCertificateBundleErr
}
- if err := writeCertificateBundleInternal(paths.ClientCertPath, paths.ClientKeyPath, clientDER, clientKey); err != nil {
- return nil, err
+ if writeClientBundleErr := writeCertificateBundleInternal(paths.ClientCertPath, paths.ClientKeyPath, clientDER, clientKey); writeClientBundleErr != nil {
+ return nil, writeClientBundleErr
}
return paths, nil
@@ -224,8 +224,8 @@ func generateServerTLSBundleInternal(outDir, commonName string, hosts []string,
CertPath: filepath.Join(outDir, certName),
KeyPath: filepath.Join(outDir, keyName),
}
- if err := writeCertificateBundleInternal(paths.CertPath, paths.KeyPath, certDER, privateKey); err != nil {
- return nil, err
+ if writeCertificateBundleErr := writeCertificateBundleInternal(paths.CertPath, paths.KeyPath, certDER, privateKey); writeCertificateBundleErr != nil {
+ return nil, writeCertificateBundleErr
}
return paths, nil
}
@@ -372,11 +372,11 @@ func writeCertificateBundleInternal(certPath, keyPath string, certDER []byte, pr
if err != nil {
return fmt.Errorf("failed to marshal private key: %w", err)
}
- if err := writePEMFileInternal(certPath, "CERTIFICATE", certDER, 0o644); err != nil {
- return err
+ if writePEMFileErr := writePEMFileInternal(certPath, "CERTIFICATE", certDER, 0o644); writePEMFileErr != nil {
+ return writePEMFileErr
}
- if err := writePEMFileInternal(keyPath, "PRIVATE KEY", keyDER, 0o600); err != nil {
- return err
+ if writePrivateKeyErr := writePEMFileInternal(keyPath, "PRIVATE KEY", keyDER, 0o600); writePrivateKeyErr != nil {
+ return writePrivateKeyErr
}
return nil
}
diff --git a/cli/pkg/generate/certs_test.go b/cli/pkg/generate/certs_test.go
index 5ec2f9d75..1795e7f33 100644
--- a/cli/pkg/generate/certs_test.go
+++ b/cli/pkg/generate/certs_test.go
@@ -85,8 +85,8 @@ func TestGenerateTLSCommandOverwritesCertificateAtomically(t *testing.T) {
cmd.SetArgs([]string{"tls", "--out-dir", outDir, "--common-name", "localhost", "--host", "localhost", "--cert-name", "server.crt", "--key-name", "server.key"})
_, err = captureOutput(func() error {
- _, err := cmd.ExecuteC()
- return err
+ _, executeCErr := cmd.ExecuteC()
+ return executeCErr
})
require.NoError(t, err,
diff --git a/cli/pkg/generate/secret_test.go b/cli/pkg/generate/secret_test.go
index bf644efcd..a5ba7d41a 100644
--- a/cli/pkg/generate/secret_test.go
+++ b/cli/pkg/generate/secret_test.go
@@ -71,8 +71,8 @@ func TestSecretDefaultBase64(t *testing.T) {
require.NotContains(t, out, "JWT_SECRET",
"JWT_SECRET is no longer emitted, got: %q", out)
- if b, err := base64.StdEncoding.DecodeString(encVal); err != nil {
- require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY is not valid base64: %v (value=%q)", err, encVal)
+ if b, decodeStringErr := base64.StdEncoding.DecodeString(encVal); decodeStringErr != nil {
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY is not valid base64: %v (value=%q)", decodeStringErr, encVal)
} else if len(b) != 32 {
require.Len(t, b, 32,
"ENCRYPTION_KEY decoded length != 32 bytes: %d", len(b))
@@ -123,8 +123,8 @@ func TestSecretAllFormatContainsSections(t *testing.T) {
require.NotContains(t, out, "JWT_SECRET",
"JWT_SECRET is no longer emitted, got: %q", out)
- if b, err := hex.DecodeString(strings.TrimSpace(hexEnc)); err != nil {
- require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY hex decode failed: %v", err)
+ if b, decodeStringErr := hex.DecodeString(strings.TrimSpace(hexEnc)); decodeStringErr != nil {
+ require.FailNowf(t, "unexpected failure", "ENCRYPTION_KEY hex decode failed: %v", decodeStringErr)
} else if len(b) != 32 {
require.Len(t, b, 32,
"ENCRYPTION_KEY hex decoded length != 32: %d", len(b))
diff --git a/cli/pkg/gitops/cmd.go b/cli/pkg/gitops/cmd.go
index 666b8281b..fa5934299 100644
--- a/cli/pkg/gitops/cmd.go
+++ b/cli/pkg/gitops/cmd.go
@@ -147,9 +147,9 @@ var getCmd = &cobra.Command{
}
if !complete {
- result, err := c.GetJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to get gitops sync: %w", err)
+ result, getSyncErr := c.GetJSON[gitops.GitOpsSync](cmd.Context(), types.GitOpsSync(c.EnvID(), resolved.ID))
+ if getSyncErr != nil {
+ return fmt.Errorf("failed to get gitops sync: %w", getSyncErr)
}
resolved = &result.Data
}
@@ -224,8 +224,8 @@ var updateCmd = &cobra.Command{
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to update gitops sync: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to update gitops sync: %w", ensureSuccessStatusErr)
}
output.Success("GitOps sync %s updated successfully", resolved.Name)
@@ -255,9 +255,9 @@ var deleteCmd = &cobra.Command{
if display == "" {
display = resolved.ID
}
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete gitops sync %s?", display))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete gitops sync %s?", display))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -270,8 +270,8 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete gitops sync: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete gitops sync: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete gitops sync: %w", ensureSuccessStatusErr)
}
output.Success("GitOps sync %s deleted successfully", resolved.Name)
@@ -398,8 +398,7 @@ var filesCmd = &cobra.Command{
headers := []string{"NAME", "TYPE", "PATH", "SIZE"}
rows := flattenFileTree(files, 0)
- output.Table(headers, rows)
- return nil
+ return output.Table(headers, rows)
},
}
diff --git a/cli/pkg/images/cmd.go b/cli/pkg/images/cmd.go
index 4af1d22be..c37c00d94 100644
--- a/cli/pkg/images/cmd.go
+++ b/cli/pkg/images/cmd.go
@@ -156,8 +156,8 @@ var imagesGetCmd = &cobra.Command{
Data image.DetailSummary `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
output.Header("Image Details")
@@ -228,9 +228,9 @@ var imagesRemoveCmd = &cobra.Command{
path := types.Image(c.EnvID(), resolved.ID)
if removeForce {
- u, err := url.Parse(path)
- if err != nil {
- return fmt.Errorf("failed to parse path: %w", err)
+ u, parseErr := url.Parse(path)
+ if parseErr != nil {
+ return fmt.Errorf("failed to parse path: %w", parseErr)
}
q := u.Query()
q.Set("force", "true")
@@ -269,8 +269,8 @@ var imagesRemoveCmd = &cobra.Command{
} `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
output.Success("%s", result.Data.Message)
@@ -340,11 +340,11 @@ var imagesPullCmd = &cobra.Command{
} `json:"progressDetail"`
}
- if err := json.UnmarshalDecode(decoder, &event); err != nil {
- if errors.Is(err, io.EOF) {
+ if unmarshalDecodeErr := json.UnmarshalDecode(decoder, &event); unmarshalDecodeErr != nil {
+ if errors.Is(unmarshalDecodeErr, io.EOF) {
break
}
- return fmt.Errorf("failed to decode stream: %w", err)
+ return fmt.Errorf("failed to decode stream: %w", unmarshalDecodeErr)
}
// The stream opens with an activity frame that carries no Docker
@@ -468,8 +468,8 @@ var imagesPruneCmd = &cobra.Command{
} `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
output.Success("Pruned %d images, reclaimed %s", len(result.Data.ImagesDeleted), output.Bytes(result.Data.SpaceReclaimed))
@@ -516,8 +516,8 @@ var imagesCountsCmd = &cobra.Command{
Data image.UsageCounts `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
output.Header("Image Usage Counts")
@@ -572,8 +572,8 @@ var imagesUploadCmd = &cobra.Command{
Data image.LoadResult `json:"data"`
}
- if err := json.Unmarshal(respBody, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(respBody, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
if !result.Success {
diff --git a/cli/pkg/images/extra.go b/cli/pkg/images/extra.go
index a34fd9e72..4ccd13c53 100644
--- a/cli/pkg/images/extra.go
+++ b/cli/pkg/images/extra.go
@@ -60,7 +60,9 @@ var imagesSearchCmd = &cobra.Command{
rows = append(rows, []string{item.Name, truncateCell(item.Description, 60), strconv.Itoa(item.StarCount), official})
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
output.Showing(len(result.Data), int64(len(result.Data)), "results")
return nil
@@ -110,8 +112,8 @@ var imagesHistoryCmd = &cobra.Command{
Success bool `json:"success"`
Data []image.HistoryItem `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
headers := []string{"CREATED", "CREATED BY", "SIZE", "COMMENT"}
@@ -124,9 +126,7 @@ var imagesHistoryCmd = &cobra.Command{
rows = append(rows, []string{created, truncateCell(item.CreatedBy, 60), output.Bytes(item.Size), truncateCell(item.Comment, 30)})
}
- output.Table(headers, rows)
-
- return nil
+ return output.Table(headers, rows)
},
}
@@ -179,8 +179,8 @@ var imagesTagCmd = &cobra.Command{
Success bool `json:"success"`
Data base.MessageResponse `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
output.Success("%s", result.Data.Message)
@@ -226,8 +226,8 @@ var imagesExportCmd = &cobra.Command{
return fmt.Errorf("failed to export image: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to export image: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to export image: %w", ensureSuccessStatusErr)
}
file, err := os.Create(outputFile)
@@ -328,8 +328,8 @@ var imagesAttestationsCmd = &cobra.Command{
Success bool `json:"success"`
Data image.AttestationList `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
output.Header("Image Attestations")
@@ -350,7 +350,9 @@ var imagesAttestationsCmd = &cobra.Command{
rows = append(rows, []string{att.PredicateType, att.Platform, truncateCell(att.Digest, 19), output.Bytes(att.Size)})
}
fmt.Println()
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
return nil
},
@@ -379,9 +381,9 @@ var imagesBuildCmd = &cobra.Command{
requestBody["dockerfile"] = buildDockerfile
}
if buildInlineFile != "" {
- content, err := os.ReadFile(buildInlineFile)
- if err != nil {
- return fmt.Errorf("failed to read Dockerfile: %w", err)
+ content, readFileErr := os.ReadFile(buildInlineFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read Dockerfile: %w", readFileErr)
}
requestBody["dockerfileInline"] = string(content)
}
@@ -433,8 +435,8 @@ var imagesBuildCmd = &cobra.Command{
return fmt.Errorf("failed to build image: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to build image: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to build image: %w", ensureSuccessStatusErr)
}
if cmdutil.JSONOutputEnabled(cmd) {
@@ -445,8 +447,8 @@ var imagesBuildCmd = &cobra.Command{
return nil
}
- if err := streamBuildOutput(resp.Body); err != nil {
- return err
+ if streamBuildOutputErr := streamBuildOutput(resp.Body); streamBuildOutputErr != nil {
+ return streamBuildOutputErr
}
output.Success("Image built successfully")
@@ -567,8 +569,8 @@ var imagesBuildsGetCmd = &cobra.Command{
Success bool `json:"success"`
Data image.BuildRecord `json:"data"`
}
- if err := json.Unmarshal(body, &result); err != nil {
- return fmt.Errorf("failed to parse response: %w", err)
+ if unmarshalErr := json.Unmarshal(body, &result); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse response: %w", unmarshalErr)
}
record := result.Data
diff --git a/cli/pkg/images/updates/cmd.go b/cli/pkg/images/updates/cmd.go
index 6acb82a22..4b731a15c 100644
--- a/cli/pkg/images/updates/cmd.go
+++ b/cli/pkg/images/updates/cmd.go
@@ -27,9 +27,10 @@ var UpdatesCmd = &cobra.Command{
var checkAll bool
var checkCmd = &cobra.Command{
- Use: "check [image-ref...]",
- Short: "Check image references for updates",
- Long: "Check image references for updates.\n\nWith a single reference the update status is checked directly; with multiple references a batch check is performed. With --all every image is checked.",
+ Use: "check [image-ref...]",
+ Short: "Check image references for updates",
+ Long: "Check image references for updates.\n\nWith a single reference the update status is checked directly; with " +
+ "multiple references a batch check is performed. With --all every image is checked.",
Args: cobra.ArbitraryArgs,
SilenceUsage: true,
RunE: func(cmd *cobra.Command, args []string) error {
@@ -43,9 +44,9 @@ var checkCmd = &cobra.Command{
return errors.New("--all cannot be combined with image references")
}
- result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})
- if err != nil {
- return fmt.Errorf("failed to check all updates: %w", err)
+ result, checkAllUpdatesErr := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckAll(c.EnvID()), imageupdate.CheckAllImagesRequest{})
+ if checkAllUpdatesErr != nil {
+ return fmt.Errorf("failed to check all updates: %w", checkAllUpdatesErr)
}
return printBatchResultsInternal(result.Data)
}
@@ -55,9 +56,9 @@ var checkCmd = &cobra.Command{
}
if len(args) > 1 {
- result, err := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckBatch(c.EnvID()), imageupdate.BatchImageUpdateRequest{ImageRefs: args})
- if err != nil {
- return fmt.Errorf("failed to check updates: %w", err)
+ result, checkBatchUpdatesErr := c.PostJSON[imageupdate.BatchResponse](cmd.Context(), types.ImageUpdatesCheckBatch(c.EnvID()), imageupdate.BatchImageUpdateRequest{ImageRefs: args})
+ if checkBatchUpdatesErr != nil {
+ return fmt.Errorf("failed to check updates: %w", checkBatchUpdatesErr)
}
return printBatchResultsInternal(result.Data)
}
@@ -212,7 +213,9 @@ func printBatchResultsInternal(result imageupdate.BatchResponse) error {
rows = append(rows, []string{imageRef, "No", update.CurrentVersion, "", ""})
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d images checked, %d updates available\n", len(result), updatesAvailable)
return nil
}
diff --git a/cli/pkg/jobs/cmd.go b/cli/pkg/jobs/cmd.go
index 224afa5aa..fdf08ea15 100644
--- a/cli/pkg/jobs/cmd.go
+++ b/cli/pkg/jobs/cmd.go
@@ -141,7 +141,9 @@ var listCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d jobs\n", len(result.Jobs))
return nil
},
diff --git a/cli/pkg/networks/cmd.go b/cli/pkg/networks/cmd.go
index 51b12b83d..7e0849d73 100644
--- a/cli/pkg/networks/cmd.go
+++ b/cli/pkg/networks/cmd.go
@@ -128,9 +128,9 @@ var getCmd = &cobra.Command{
}
if !complete {
- result, err := c.GetJSON[network.Inspect](cmd.Context(), types.Network(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to get network: %w", err)
+ result, inspectNetworkErr := c.GetJSON[network.Inspect](cmd.Context(), types.Network(c.EnvID(), resolved.ID))
+ if inspectNetworkErr != nil {
+ return fmt.Errorf("failed to get network: %w", inspectNetworkErr)
}
resolved = &result.Data
}
@@ -176,9 +176,9 @@ var deleteCmd = &cobra.Command{
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete network %s?", display))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete network %s?", display))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -472,8 +472,7 @@ var topologyCmd = &cobra.Command{
}
rows[i] = []string{source, target, edge.IPv4Address, edge.IPv6Address}
}
- output.Table(headers, rows)
- return nil
+ return output.Table(headers, rows)
},
}
diff --git a/cli/pkg/projects/actions.go b/cli/pkg/projects/actions.go
index 0c624f308..469b2a2cf 100644
--- a/cli/pkg/projects/actions.go
+++ b/cli/pkg/projects/actions.go
@@ -57,8 +57,7 @@ var tagsCmd = &cobra.Command{
for i, tag := range result.Data {
rows[i] = []string{tag.Name, string(tag.Color)}
}
- output.Table(headers, rows)
- return nil
+ return output.Table(headers, rows)
},
}
@@ -195,12 +194,12 @@ var buildCmd = &cobra.Command{
return fmt.Errorf("failed to build project images: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to build project images: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to build project images: %w", ensureSuccessStatusErr)
}
- if err := printOperationStreamInternal(resp.Body); err != nil {
- return fmt.Errorf("failed to build project images: %w", err)
+ if printOperationStreamErr := printOperationStreamInternal(resp.Body); printOperationStreamErr != nil {
+ return fmt.Errorf("failed to build project images: %w", printOperationStreamErr)
}
output.Success("Images built successfully for project %s", resolved.Name)
@@ -305,8 +304,8 @@ var workspaceDownloadCmd = &cobra.Command{
return fmt.Errorf("failed to download workspace file: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to download workspace file: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to download workspace file: %w", ensureSuccessStatusErr)
}
outputFile := path.Base(args[1])
diff --git a/cli/pkg/projects/cmd.go b/cli/pkg/projects/cmd.go
index 784dfb4db..ae0854f2d 100644
--- a/cli/pkg/projects/cmd.go
+++ b/cli/pkg/projects/cmd.go
@@ -177,9 +177,9 @@ var destroyCmd = &cobra.Command{
if display == "" {
display = resolved.ID
}
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to destroy project %s? This will remove all containers!", display))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to destroy project %s? This will remove all containers!", display))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -195,8 +195,8 @@ var destroyCmd = &cobra.Command{
return fmt.Errorf("failed to destroy project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to destroy project: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to destroy project: %w", ensureSuccessStatusErr)
}
output.Success("Project %s destroyed successfully", resolved.Name)
@@ -222,9 +222,9 @@ var getCmd = &cobra.Command{
}
if !complete {
- result, err := c.GetJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID))
- if err != nil {
- return fmt.Errorf("failed to get project: %w", err)
+ result, getProjectErr := c.GetJSON[project.Details](cmd.Context(), types.Project(c.EnvID(), resolved.ID))
+ if getProjectErr != nil {
+ return fmt.Errorf("failed to get project: %w", getProjectErr)
}
resolved = &result.Data
}
@@ -361,12 +361,12 @@ func runProjectStreamAction(cmd *cobra.Command, identifier string, cfg projectSt
return fmt.Errorf("%s: %w", cfg.failureMessage, err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("%s: %w", cfg.failureMessage, err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("%s: %w", cfg.failureMessage, ensureSuccessStatusErr)
}
- if err := printOperationStreamInternal(resp.Body); err != nil {
- return fmt.Errorf("%s: %w", cfg.failureMessage, err)
+ if printOperationStreamErr := printOperationStreamInternal(resp.Body); printOperationStreamErr != nil {
+ return fmt.Errorf("%s: %w", cfg.failureMessage, printOperationStreamErr)
}
output.Success(cfg.successMessage, resolved.Name)
@@ -429,9 +429,9 @@ var createCmd = &cobra.Command{
}
if createEnvFile != "" {
- envBytes, err := os.ReadFile(createEnvFile)
- if err != nil {
- return fmt.Errorf("failed to read env file: %w", err)
+ envBytes, readFileErr := os.ReadFile(createEnvFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read env file: %w", readFileErr)
}
body.EnvContent = new(string(envBytes))
}
@@ -449,14 +449,14 @@ var createCmd = &cobra.Command{
}
var requestBody bytes.Buffer
writer := multipart.NewWriter(&requestBody)
- if err := writer.WriteField("project", string(projectJSON)); err != nil {
- return fmt.Errorf("failed to write project configuration: %w", err)
+ if writeFieldErr := writer.WriteField("project", string(projectJSON)); writeFieldErr != nil {
+ return fmt.Errorf("failed to write project configuration: %w", writeFieldErr)
}
- if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {
- return fmt.Errorf("failed to write project workspace manifest: %w", err)
+ if writeManifestErr := writer.WriteField("manifest", string(manifestJSON)); writeManifestErr != nil {
+ return fmt.Errorf("failed to write project workspace manifest: %w", writeManifestErr)
}
- if err := writer.Close(); err != nil {
- return fmt.Errorf("failed to finalize project request: %w", err)
+ if closeErr := writer.Close(); closeErr != nil {
+ return fmt.Errorf("failed to finalize project request: %w", closeErr)
}
resp, err := c.RequestRaw(cmd.Context(), http.MethodPost, types.Projects(c.EnvID()), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
@@ -464,13 +464,13 @@ var createCmd = &cobra.Command{
return fmt.Errorf("failed to create project: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to create project: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to create project: %w", ensureSuccessStatusErr)
}
var result base.ApiResponse[project.CreateReponse]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
+ return decodeJSONErr
}
if jsonOutput {
@@ -510,17 +510,17 @@ var updateCmd = &cobra.Command{
}
if cmd.Flags().Changed("file") {
- composeBytes, err := os.ReadFile(updateFile)
- if err != nil {
- return fmt.Errorf("failed to read compose file: %w", err)
+ composeBytes, readFileErr := os.ReadFile(updateFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read compose file: %w", readFileErr)
}
body.ComposeContent = new(string(composeBytes))
}
if cmd.Flags().Changed("env-file") {
- envBytes, err := os.ReadFile(updateEnvFile)
- if err != nil {
- return fmt.Errorf("failed to read env file: %w", err)
+ envBytes, readEnvFileErr := os.ReadFile(updateEnvFile)
+ if readEnvFileErr != nil {
+ return fmt.Errorf("failed to read env file: %w", readEnvFileErr)
}
body.EnvContent = new(string(envBytes))
}
@@ -585,18 +585,18 @@ var updateIncludesCmd = &cobra.Command{
}
var requestBody bytes.Buffer
writer := multipart.NewWriter(&requestBody)
- if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {
- return fmt.Errorf("failed to write workspace manifest: %w", err)
+ if writeFieldErr := writer.WriteField("manifest", string(manifestJSON)); writeFieldErr != nil {
+ return fmt.Errorf("failed to write workspace manifest: %w", writeFieldErr)
}
filePart, err := writer.CreateFormFile("files", filepath.Base(includesFile))
if err != nil {
return fmt.Errorf("failed to create workspace upload: %w", err)
}
- if _, err := filePart.Write(content); err != nil {
- return fmt.Errorf("failed to write workspace upload: %w", err)
+ if _, writeErr := filePart.Write(content); writeErr != nil {
+ return fmt.Errorf("failed to write workspace upload: %w", writeErr)
}
- if err := writer.Close(); err != nil {
- return fmt.Errorf("failed to finalize workspace upload: %w", err)
+ if closeErr := writer.Close(); closeErr != nil {
+ return fmt.Errorf("failed to finalize workspace upload: %w", closeErr)
}
resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.ProjectWorkspace(c.EnvID(), resolved.ID), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
@@ -604,14 +604,14 @@ var updateIncludesCmd = &cobra.Command{
return fmt.Errorf("failed to update include file: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to update include file: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to update include file: %w", ensureSuccessStatusErr)
}
if jsonOutput {
var result base.ApiResponse[workspacetypes.Workspace]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
+ return decodeJSONErr
}
return cmdutil.PrintJSON(result.Data)
}
diff --git a/cli/pkg/registries/cmd.go b/cli/pkg/registries/cmd.go
index cdffbf52e..ae4f445f6 100644
--- a/cli/pkg/registries/cmd.go
+++ b/cli/pkg/registries/cmd.go
@@ -288,8 +288,8 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete registry: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete registry: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete registry: %w", ensureSuccessStatusErr)
}
output.Success("Registry deleted successfully")
@@ -344,8 +344,7 @@ var usageCmd = &cobra.Command{
usage.Error,
}
}
- output.Table(headers, rows)
- return nil
+ return output.Table(headers, rows)
},
}
diff --git a/cli/pkg/repos/cmd.go b/cli/pkg/repos/cmd.go
index e4a16f51c..f6c2dae07 100644
--- a/cli/pkg/repos/cmd.go
+++ b/cli/pkg/repos/cmd.go
@@ -131,9 +131,9 @@ var createCmd = &cobra.Command{
req.Username = repoCreateUsername
}
if cmd.Flags().Changed("ssh-key") {
- sshKeyData, err := os.ReadFile(repoCreateSSHKey)
- if err != nil {
- return fmt.Errorf("failed to read SSH key file: %w", err)
+ sshKeyData, readFileErr := os.ReadFile(repoCreateSSHKey)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read SSH key file: %w", readFileErr)
}
req.SSHKey = string(sshKeyData)
}
@@ -147,9 +147,9 @@ var createCmd = &cobra.Command{
req.CommitAuthorEmail = repoCreateAuthorEmail
}
if cmd.Flags().Changed("signing-key") {
- signingKeyData, err := os.ReadFile(repoCreateSigningKey)
- if err != nil {
- return fmt.Errorf("failed to read signing key file: %w", err)
+ signingKeyData, readSigningKeyErr := os.ReadFile(repoCreateSigningKey)
+ if readSigningKeyErr != nil {
+ return fmt.Errorf("failed to read signing key file: %w", readSigningKeyErr)
}
req.SigningKey = string(signingKeyData)
}
@@ -261,9 +261,9 @@ var updateCmd = &cobra.Command{
req.Username = &repoUpdateUsername
}
if cmd.Flags().Changed("ssh-key") {
- sshKeyData, err := os.ReadFile(repoUpdateSSHKey)
- if err != nil {
- return fmt.Errorf("failed to read SSH key file: %w", err)
+ sshKeyData, readFileErr := os.ReadFile(repoUpdateSSHKey)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read SSH key file: %w", readFileErr)
}
req.SSHKey = new(string(sshKeyData))
}
@@ -279,9 +279,9 @@ var updateCmd = &cobra.Command{
if cmd.Flags().Changed("signing-key") {
signingKey := ""
if repoUpdateSigningKey != "" {
- signingKeyData, err := os.ReadFile(repoUpdateSigningKey)
- if err != nil {
- return fmt.Errorf("failed to read signing key file: %w", err)
+ signingKeyData, readSigningKeyErr := os.ReadFile(repoUpdateSigningKey)
+ if readSigningKeyErr != nil {
+ return fmt.Errorf("failed to read signing key file: %w", readSigningKeyErr)
}
signingKey = string(signingKeyData)
}
@@ -334,9 +334,9 @@ var deleteCmd = &cobra.Command{
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete repository %s (%s)?", resolved.Name, resolved.ID))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete repository %s (%s)?", resolved.Name, resolved.ID))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -349,8 +349,8 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete repository: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete repository: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete repository: %w", ensureSuccessStatusErr)
}
output.Success("Repository deleted successfully")
@@ -421,7 +421,9 @@ var branchesCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d branches\n", len(result.Data.Branches))
return nil
},
@@ -480,7 +482,9 @@ var filesCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d entries\n", len(files))
return nil
},
diff --git a/cli/pkg/root.go b/cli/pkg/root.go
index 5ae6cfd6b..5a82fbff5 100644
--- a/cli/pkg/root.go
+++ b/cli/pkg/root.go
@@ -169,7 +169,7 @@ var rootCmd = &cobra.Command{
func Execute() {
if err := fang.Execute(
- context.Background(),
+ context.Background(), //nolint:forbidigo // CLI entry point establishes the process context.
rootCmd,
fang.WithColorSchemeFunc(arcaneFangColorSchemeInternal),
fang.WithVersion(config.Version),
diff --git a/cli/pkg/selfupdate/cmd.go b/cli/pkg/selfupdate/cmd.go
index 862a6b58f..fc68ed768 100644
--- a/cli/pkg/selfupdate/cmd.go
+++ b/cli/pkg/selfupdate/cmd.go
@@ -166,8 +166,8 @@ func runCLIUpdateInternal(ctx context.Context, overrideChannel string) error {
return nil
}
- if err := installCLIUpdateInternal(ctx, plan); err != nil {
- return err
+ if installCLIUpdateErr := installCLIUpdateInternal(ctx, plan); installCLIUpdateErr != nil {
+ return installCLIUpdateErr
}
output.Success("arcane-cli updated successfully")
return nil
@@ -231,8 +231,8 @@ func saveCLIUpdateChannelInternal(channel string) error {
return fmt.Errorf("failed to load config: %w", err)
}
cfg.CLIUpdateChannel = channel
- if err := config.Save(cfg); err != nil {
- return fmt.Errorf("failed to save config: %w", err)
+ if saveErr := config.Save(cfg); saveErr != nil {
+ return fmt.Errorf("failed to save config: %w", saveErr)
}
return nil
}
@@ -242,9 +242,9 @@ func resolveCLIUpdateTargetInternal() (string, error) {
return filepath.Abs(strings.TrimSpace(cliUpdateTarget))
}
if pathTarget, err := exec.LookPath("arcane-cli"); err == nil {
- absTarget, err := filepath.Abs(pathTarget)
- if err != nil {
- return "", fmt.Errorf("failed to resolve arcane-cli from PATH: %w", err)
+ absTarget, absErr := filepath.Abs(pathTarget)
+ if absErr != nil {
+ return "", fmt.Errorf("failed to resolve arcane-cli from PATH: %w", absErr)
}
return filepath.EvalSymlinks(absTarget)
}
@@ -289,7 +289,7 @@ func resolveNextCLIUpdateInternal(ctx context.Context) (*cliUpdatePlan, error) {
verboseCLIUpdateInternal("next base URL: %s", baseURL)
verboseCLIUpdateInternal("next artifact URL: %s", artifactURL)
verboseCLIUpdateInternal("next checksum URL: %s", checksumURL)
- verboseCLIUpdateInternal("next checksum candidates: %s", strings.Join([]string{artifactName, platformName}, ", "))
+ verboseCLIUpdateInternal("next checksum candidates: %s", artifactName+", "+platformName)
checksums, err := fetchTextInternal(ctx, checksumURL)
if err != nil {
@@ -374,7 +374,7 @@ func cliUpdateNeededInternal(channel, currentSHA, expectedSHA, remoteVersion str
}
func fetchLatestGitHubReleaseInternal(ctx context.Context) (string, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/repos/getarcaneapp/arcane/releases/latest", nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/repos/getarcaneapp/arcane/releases/latest", http.NoBody)
if err != nil {
return "", err
}
@@ -391,8 +391,8 @@ func fetchLatestGitHubReleaseInternal(ctx context.Context) (string, error) {
}
var latest githubLatestRelease
- if err := json.UnmarshalRead(resp.Body, &latest); err != nil {
- return "", fmt.Errorf("failed to fetch latest GitHub release: %w", err)
+ if unmarshalReadErr := json.UnmarshalRead(resp.Body, &latest); unmarshalReadErr != nil {
+ return "", fmt.Errorf("failed to fetch latest GitHub release: %w", unmarshalReadErr)
}
return strings.TrimSpace(latest.TagName), nil
}
@@ -440,11 +440,11 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {
defer func() { _ = os.RemoveAll(tmpDir) }()
downloadPath := filepath.Join(tmpDir, plan.ArtifactName)
- if err := downloadFileInternal(ctx, plan.ArtifactURL, downloadPath); err != nil {
- return err
+ if downloadFileErr := downloadFileInternal(ctx, plan.ArtifactURL, downloadPath); downloadFileErr != nil {
+ return downloadFileErr
}
- if gotSHA, err := sha256FileInternal(downloadPath); err != nil {
- return err
+ if gotSHA, sha256FileErr := sha256FileInternal(downloadPath); sha256FileErr != nil {
+ return sha256FileErr
} else if !strings.EqualFold(gotSHA, plan.ArtifactSHA) {
return fmt.Errorf("downloaded artifact SHA mismatch: got %s, expected %s", gotSHA, plan.ArtifactSHA)
}
@@ -452,14 +452,14 @@ func installCLIUpdateInternal(ctx context.Context, plan *cliUpdatePlan) error {
binaryPath := downloadPath
if strings.HasSuffix(plan.ArtifactName, ".tar.gz") {
extractedPath := filepath.Join(tmpDir, "arcane-cli")
- if err := extractCLIFromTarGzInternal(downloadPath, extractedPath); err != nil {
- return err
+ if extractCLIFromTarGzErr := extractCLIFromTarGzInternal(downloadPath, extractedPath); extractCLIFromTarGzErr != nil {
+ return extractCLIFromTarGzErr
}
binaryPath = extractedPath
}
- if err := os.Chmod(binaryPath, 0o755); err != nil {
- return fmt.Errorf("failed to make downloaded binary executable: %w", err)
+ if chmodErr := os.Chmod(binaryPath, 0o755); chmodErr != nil {
+ return fmt.Errorf("failed to make downloaded binary executable: %w", chmodErr)
}
return replaceExecutableInternal(binaryPath, plan.TargetPath)
}
@@ -481,28 +481,28 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {
}
defer func() { _ = source.Close() }()
- if _, err := io.Copy(tmpTarget, source); err != nil {
+ if _, copyErr := io.Copy(tmpTarget, source); copyErr != nil {
_ = tmpTarget.Close()
cleanup()
- return fmt.Errorf("failed to write replacement binary: %w", err)
+ return fmt.Errorf("failed to write replacement binary: %w", copyErr)
}
- if err := tmpTarget.Chmod(0o755); err != nil {
+ if chmodErr := tmpTarget.Chmod(0o755); chmodErr != nil {
_ = tmpTarget.Close()
cleanup()
- return fmt.Errorf("failed to chmod replacement binary: %w", err)
+ return fmt.Errorf("failed to chmod replacement binary: %w", chmodErr)
}
- if err := tmpTarget.Sync(); err != nil {
+ if syncErr := tmpTarget.Sync(); syncErr != nil {
_ = tmpTarget.Close()
cleanup()
- return fmt.Errorf("failed to sync replacement binary: %w", err)
+ return fmt.Errorf("failed to sync replacement binary: %w", syncErr)
}
- if err := tmpTarget.Close(); err != nil {
+ if closeErr := tmpTarget.Close(); closeErr != nil {
cleanup()
- return fmt.Errorf("failed to close replacement binary: %w", err)
+ return fmt.Errorf("failed to close replacement binary: %w", closeErr)
}
- if err := os.Rename(tmpTargetPath, targetPath); err != nil {
+ if renameErr := os.Rename(tmpTargetPath, targetPath); renameErr != nil {
cleanup()
- return fmt.Errorf("failed to replace %s: %w", targetPath, err)
+ return fmt.Errorf("failed to replace %s: %w", targetPath, renameErr)
}
dirFile, err := os.Open(targetDir)
@@ -510,8 +510,8 @@ func replaceExecutableInternal(sourcePath, targetPath string) error {
return fmt.Errorf("failed to open target directory for sync: %w", err)
}
defer func() { _ = dirFile.Close() }()
- if err := dirFile.Sync(); err != nil {
- return fmt.Errorf("failed to sync target directory: %w", err)
+ if syncDirectoryErr := dirFile.Sync(); syncDirectoryErr != nil {
+ return fmt.Errorf("failed to sync target directory: %w", syncDirectoryErr)
}
return nil
}
@@ -531,12 +531,12 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {
tarReader := tar.NewReader(gzipReader)
for {
- header, err := tarReader.Next()
- if errors.Is(err, io.EOF) {
+ header, nextErr := tarReader.Next()
+ if errors.Is(nextErr, io.EOF) {
break
}
- if err != nil {
- return fmt.Errorf("failed to read tar archive: %w", err)
+ if nextErr != nil {
+ return fmt.Errorf("failed to read tar archive: %w", nextErr)
}
if header.Typeflag != tar.TypeReg {
continue
@@ -548,16 +548,16 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {
return fmt.Errorf("arcane-cli archive entry has invalid size %d", header.Size)
}
- out, err := os.OpenFile(outputPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
- if err != nil {
- return fmt.Errorf("failed to create extracted binary: %w", err)
+ out, nextErr := os.OpenFile(outputPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
+ if nextErr != nil {
+ return fmt.Errorf("failed to create extracted binary: %w", nextErr)
}
- if _, err := io.CopyN(out, tarReader, header.Size); err != nil {
+ if _, copyNErr := io.CopyN(out, tarReader, header.Size); copyNErr != nil {
_ = out.Close()
- return fmt.Errorf("failed to extract CLI binary: %w", err)
+ return fmt.Errorf("failed to extract CLI binary: %w", copyNErr)
}
- if err := out.Close(); err != nil {
- return fmt.Errorf("failed to close extracted binary: %w", err)
+ if closeErr := out.Close(); closeErr != nil {
+ return fmt.Errorf("failed to close extracted binary: %w", closeErr)
}
return nil
}
@@ -565,7 +565,7 @@ func extractCLIFromTarGzInternal(archivePath, outputPath string) error {
}
func fetchTextInternal(ctx context.Context, url string) (string, error) {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return "", err
}
@@ -593,7 +593,7 @@ func fetchTextInternal(ctx context.Context, url string) (string, error) {
func downloadFileInternal(ctx context.Context, url, outputPath string) error {
verboseCLIUpdateInternal("downloading %s to %s", url, outputPath)
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return err
}
@@ -621,8 +621,8 @@ func downloadFileInternal(ctx context.Context, url, outputPath string) error {
_ = out.Close()
return fmt.Errorf("downloaded artifact exceeds maximum size of %d bytes", maxCLIDownloadSize)
}
- if err := out.Close(); err != nil {
- return fmt.Errorf("failed to close download file: %w", err)
+ if closeErr := out.Close(); closeErr != nil {
+ return fmt.Errorf("failed to close download file: %w", closeErr)
}
return nil
}
@@ -635,16 +635,16 @@ func verboseCLIUpdateInternal(format string, args ...any) {
fmt.Fprintf(os.Stderr, "self-update: "+format+"\n", args...)
}
-func sha256FileInternal(path string) (string, error) {
- file, err := os.Open(path)
+func sha256FileInternal(filePath string) (string, error) {
+ file, err := os.Open(filePath)
if err != nil {
- return "", fmt.Errorf("failed to open %s for SHA-256: %w", path, err)
+ return "", fmt.Errorf("failed to open %s for SHA-256: %w", filePath, err)
}
defer func() { _ = file.Close() }()
hash := sha256.New()
- if _, err := io.Copy(hash, file); err != nil {
- return "", fmt.Errorf("failed to hash %s: %w", path, err)
+ if _, copyErr := io.Copy(hash, file); copyErr != nil {
+ return "", fmt.Errorf("failed to hash %s: %w", filePath, copyErr)
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
diff --git a/cli/pkg/settings/cmd.go b/cli/pkg/settings/cmd.go
index 0db9cdc5b..7f020e282 100644
--- a/cli/pkg/settings/cmd.go
+++ b/cli/pkg/settings/cmd.go
@@ -56,8 +56,8 @@ var updateCmd = &cobra.Command{
}
var req settings.Update
- if err := json.Unmarshal(data, &req); err != nil {
- return fmt.Errorf("failed to parse settings file: %w", err)
+ if unmarshalErr := json.Unmarshal(data, &req); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse settings file: %w", unmarshalErr)
}
result, err := c.PutJSON[[]settings.SettingDto](cmd.Context(), types.Settings(c.EnvID()), req)
@@ -114,7 +114,9 @@ func runSettingsList(cmd *cobra.Command, cfg settingsListConfig) error {
rows[i] = []string{s.Key, s.Type, s.Value}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d %s\n", len(result), cfg.totalLabel)
return nil
}
diff --git a/cli/pkg/system/cmd.go b/cli/pkg/system/cmd.go
index b46b85d25..a8f039ef9 100644
--- a/cli/pkg/system/cmd.go
+++ b/cli/pkg/system/cmd.go
@@ -292,7 +292,7 @@ type environmentUpdateJob struct {
CompletedAt *time.Time `json:"completedAt,omitempty"`
}
-func printUpdateAllJobInternal(job environmentUpdateJob) {
+func printUpdateAllJobInternal(job environmentUpdateJob) error {
output.KeyValue("Status", job.Status)
if job.Username != "" {
output.KeyValue("Triggered By", job.Username)
@@ -310,7 +310,7 @@ func printUpdateAllJobInternal(job environmentUpdateJob) {
output.KeyValue("Completed At", job.CompletedAt.Format(time.RFC3339))
}
if len(job.Results) == 0 {
- return
+ return nil
}
headers := []string{"ENVIRONMENT", "STATUS", "FROM", "TO", "ERROR"}
@@ -320,8 +320,10 @@ func printUpdateAllJobInternal(job environmentUpdateJob) {
resErr := cmp.Or(res.Error, "-")
rows[i] = []string{name, res.Status, res.FromVersion, res.ToVersion, resErr}
}
- fmt.Println()
- output.Table(headers, rows)
+ if _, spacingErr := fmt.Println(); spacingErr != nil {
+ return fmt.Errorf("failed to print update status: %w", spacingErr)
+ }
+ return output.Table(headers, rows)
}
var (
@@ -336,9 +338,9 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {
}
if upgradeAllStatusFlag {
- result, err := c.GetJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAllStatus(c.EnvID()))
- if err != nil {
- return fmt.Errorf("failed to get update-all status: %w", err)
+ result, getUpgradeStatusErr := c.GetJSON[environmentUpdateJob](cmd.Context(), types.SystemUpgradeAllStatus(c.EnvID()))
+ if getUpgradeStatusErr != nil {
+ return fmt.Errorf("failed to get update-all status: %w", getUpgradeStatusErr)
}
if jsonOutput {
@@ -346,14 +348,13 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {
}
output.Header("Update-All Status")
- printUpdateAllJobInternal(result.Data)
- return nil
+ return printUpdateAllJobInternal(result.Data)
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, "Are you sure you want to update all environments?")
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, "Are you sure you want to update all environments?")
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -371,8 +372,7 @@ func runUpgradeAllInternal(cmd *cobra.Command) error {
}
output.Success("Update-all started")
- printUpdateAllJobInternal(result.Data)
- return nil
+ return printUpdateAllJobInternal(result.Data)
}
func init() {
diff --git a/cli/pkg/templates/cmd.go b/cli/pkg/templates/cmd.go
index 4553f909c..7207628c1 100644
--- a/cli/pkg/templates/cmd.go
+++ b/cli/pkg/templates/cmd.go
@@ -92,9 +92,9 @@ var listCmd = &cobra.Command{
return errors.New("--all cannot be combined with explicit pagination flags")
}
- result, err := c.GetJSON[[]template.Template](cmd.Context(), types.TemplatesAll())
- if err != nil {
- return fmt.Errorf("failed to list templates: %w", err)
+ result, listTemplatesErr := c.GetJSON[[]template.Template](cmd.Context(), types.TemplatesAll())
+ if listTemplatesErr != nil {
+ return fmt.Errorf("failed to list templates: %w", listTemplatesErr)
}
if jsonOutput {
@@ -105,7 +105,9 @@ var listCmd = &cobra.Command{
for i, tpl := range result.Data {
rows[i] = row(tpl)
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
output.Showing(len(result.Data), int64(len(result.Data)), "templates")
return nil
}
@@ -217,7 +219,9 @@ var registriesCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d registries\n", len(result.Data))
return nil
},
@@ -600,9 +604,9 @@ var createCmd = &cobra.Command{
}
if templateCreateEnvFile != "" {
- envContent, err := os.ReadFile(templateCreateEnvFile)
- if err != nil {
- return fmt.Errorf("failed to read env file %s: %w", templateCreateEnvFile, err)
+ envContent, readFileErr := os.ReadFile(templateCreateEnvFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read env file %s: %w", templateCreateEnvFile, readFileErr)
}
req.EnvContent = string(envContent)
}
@@ -663,17 +667,17 @@ var updateCmd = &cobra.Command{
}
if templateUpdateFile != "" {
- content, err := os.ReadFile(templateUpdateFile)
- if err != nil {
- return fmt.Errorf("failed to read file %s: %w", templateUpdateFile, err)
+ content, readFileErr := os.ReadFile(templateUpdateFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read file %s: %w", templateUpdateFile, readFileErr)
}
req.Content = string(content)
}
if templateUpdateEnvFile != "" {
- envContent, err := os.ReadFile(templateUpdateEnvFile)
- if err != nil {
- return fmt.Errorf("failed to read env file %s: %w", templateUpdateEnvFile, err)
+ envContent, readEnvFileErr := os.ReadFile(templateUpdateEnvFile)
+ if readEnvFileErr != nil {
+ return fmt.Errorf("failed to read env file %s: %w", templateUpdateEnvFile, readEnvFileErr)
}
req.EnvContent = string(envContent)
}
@@ -712,11 +716,11 @@ var downloadCmd = &cobra.Command{
if templateDownloadOutput != "" {
dir := filepath.Dir(templateDownloadOutput)
- if err := os.MkdirAll(dir, 0o755); err != nil {
- return fmt.Errorf("failed to create directory %s: %w", dir, err)
+ if mkdirAllErr := os.MkdirAll(dir, 0o755); mkdirAllErr != nil {
+ return fmt.Errorf("failed to create directory %s: %w", dir, mkdirAllErr)
}
- if err := os.WriteFile(templateDownloadOutput, []byte(result.Data.Content), 0o600); err != nil {
- return fmt.Errorf("failed to write file %s: %w", templateDownloadOutput, err)
+ if writeFileErr := os.WriteFile(templateDownloadOutput, []byte(result.Data.Content), 0o600); writeFileErr != nil {
+ return fmt.Errorf("failed to write file %s: %w", templateDownloadOutput, writeFileErr)
}
output.Success("Template downloaded to %s", templateDownloadOutput)
return nil
@@ -742,9 +746,9 @@ var defaultsSaveCmd = &cobra.Command{
}
if templateDefaultsEnvFile != "" {
- envContent, err := os.ReadFile(templateDefaultsEnvFile)
- if err != nil {
- return fmt.Errorf("failed to read env file %s: %w", templateDefaultsEnvFile, err)
+ envContent, readFileErr := os.ReadFile(templateDefaultsEnvFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read env file %s: %w", templateDefaultsEnvFile, readFileErr)
}
req.EnvContent = string(envContent)
}
diff --git a/cli/pkg/updater/cmd.go b/cli/pkg/updater/cmd.go
index 722cd029a..521c04171 100644
--- a/cli/pkg/updater/cmd.go
+++ b/cli/pkg/updater/cmd.go
@@ -142,7 +142,9 @@ var historyCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d history entries\n", len(result.Data))
return nil
},
diff --git a/cli/pkg/variables/cmd.go b/cli/pkg/variables/cmd.go
index 25424fd8b..4fe4856dc 100644
--- a/cli/pkg/variables/cmd.go
+++ b/cli/pkg/variables/cmd.go
@@ -52,7 +52,7 @@ func variableScope(allEnvironments bool, environmentIDs []string) string {
return strings.Join(environmentIDs, ",")
}
-func printSyncStatuses(statuses []env.EnvironmentSyncStatus) {
+func printSyncStatuses(statuses []env.EnvironmentSyncStatus) error {
headers := []string{"ENVIRONMENT ID", "NAME", "STATUS", "LAST SYNCED", "ERROR"}
rows := make([][]string, len(statuses))
for i, status := range statuses {
@@ -69,7 +69,7 @@ func printSyncStatuses(statuses []env.EnvironmentSyncStatus) {
syncError,
}
}
- output.Table(headers, rows)
+ return output.Table(headers, rows)
}
func printMutationResult(result env.GlobalVariableMutationResponse, message string) error {
@@ -123,7 +123,9 @@ var listCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
fmt.Printf("\nTotal: %d variables\n", len(result.Data))
return nil
},
@@ -255,8 +257,7 @@ var syncCmd = &cobra.Command{
return cmdutil.PrintJSON(result.Data)
}
- printSyncStatuses(result.Data)
- return nil
+ return printSyncStatuses(result.Data)
},
}
diff --git a/cli/pkg/volumes/backup.go b/cli/pkg/volumes/backup.go
index a93a3e652..98b93d2dd 100644
--- a/cli/pkg/volumes/backup.go
+++ b/cli/pkg/volumes/backup.go
@@ -70,9 +70,9 @@ var renameCmd = &cobra.Command{
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Rename volume %s to %s? The volume is copied and the source is removed.", resolved.Name, args[1]))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Rename volume %s to %s? The volume is copied and the source is removed.", resolved.Name, args[1]))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -120,8 +120,7 @@ var backupsPolicyCmd = &cobra.Command{
return cmdutil.PrintJSON(result.Data)
}
- printBackupPolicies(resolved.Name, result.Data)
- return nil
+ return printBackupPolicies(resolved.Name, result.Data)
},
}
@@ -144,12 +143,12 @@ var backupsPolicyUpdateCmd = &cobra.Command{
var payload volume.UpdateBackupPolicies
if policyFile != "" {
- raw, err := os.ReadFile(policyFile)
- if err != nil {
- return fmt.Errorf("failed to read policy file: %w", err)
+ raw, readFileErr := os.ReadFile(policyFile)
+ if readFileErr != nil {
+ return fmt.Errorf("failed to read policy file: %w", readFileErr)
}
- if err := json.Unmarshal(raw, &payload); err != nil {
- return fmt.Errorf("failed to parse policy file: %w", err)
+ if unmarshalErr := json.Unmarshal(raw, &payload); unmarshalErr != nil {
+ return fmt.Errorf("failed to parse policy file: %w", unmarshalErr)
}
} else {
payload, err = buildPolicyUpdate(cmd, c, resolved.Name)
@@ -168,8 +167,7 @@ var backupsPolicyUpdateCmd = &cobra.Command{
}
output.Success("Backup policies for volume %s saved successfully", resolved.Name)
- printBackupPolicies(resolved.Name, result.Data)
- return nil
+ return printBackupPolicies(resolved.Name, result.Data)
},
}
@@ -243,12 +241,12 @@ func buildPolicyUpdate(cmd *cobra.Command, c *client.Client, volumeName string)
return payload, nil
}
-func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollection) {
+func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollection) error {
output.Header("Backup Policies: %s", volumeName)
output.KeyValue("S3 Available", collection.S3Available)
if len(collection.Policies) == 0 {
- fmt.Println("No backup policies configured")
- return
+ _, writeErr := fmt.Println("No backup policies configured")
+ return writeErr
}
headers := []string{"ID", "ENABLED", "SCHEDULE", "RETENTION", "STOP CONTAINERS", "LOCAL", "S3", "S3 DESTINATION"}
@@ -266,7 +264,7 @@ func printBackupPolicies(volumeName string, collection volume.BackupPolicyCollec
s3Destination,
}
}
- output.Table(headers, rows)
+ return output.Table(headers, rows)
}
func yesNo(v bool) string {
@@ -336,7 +334,9 @@ func runListBackups(cmd *cobra.Command, args []string) error {
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
output.Showing(len(result.Data), result.Pagination.TotalItems, "backups")
for _, warning := range result.Warnings {
output.Warning("%s", warning)
@@ -429,9 +429,9 @@ and restored instead (no backup ID).`,
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Restore volume %s from backup %s? Current volume contents will be replaced.", resolved.Name, backupID))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Restore volume %s from backup %s? Current volume contents will be replaced.", resolved.Name, backupID))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -540,8 +540,8 @@ var backupsDeleteCmd = &cobra.Command{
return err
}
- if _, err := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.VolumeBackup(c.EnvID(), args[0])); err != nil {
- return fmt.Errorf("failed to delete backup: %w", err)
+ if _, deleteBackupErr := c.DeleteJSON[base.MessageResponse](cmd.Context(), types.VolumeBackup(c.EnvID(), args[0])); deleteBackupErr != nil {
+ return fmt.Errorf("failed to delete backup: %w", deleteBackupErr)
}
output.Success("Backup %s deleted successfully", args[0])
@@ -597,8 +597,8 @@ var backupsDownloadCmd = &cobra.Command{
return fmt.Errorf("failed to download backup: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to download backup: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to download backup: %w", ensureSuccessStatusErr)
}
outputFile := ""
@@ -609,8 +609,8 @@ var backupsDownloadCmd = &cobra.Command{
outputFile = downloadFilename(resp, args[0]+".tar.gz")
}
- if err := writeResponseToFile(resp.Body, outputFile); err != nil {
- return err
+ if writeResponseToFileErr := writeResponseToFile(resp.Body, outputFile); writeResponseToFileErr != nil {
+ return writeResponseToFileErr
}
output.Success("Backup downloaded to %s", outputFile)
@@ -634,12 +634,12 @@ func writeResponseToFile(body io.Reader, path string) error {
if err != nil {
return fmt.Errorf("failed to create file %s: %w", path, err)
}
- if _, err := io.Copy(file, body); err != nil {
+ if _, copyErr := io.Copy(file, body); copyErr != nil {
_ = file.Close()
- return fmt.Errorf("failed to write file %s: %w", path, err)
+ return fmt.Errorf("failed to write file %s: %w", path, copyErr)
}
- if err := file.Close(); err != nil {
- return fmt.Errorf("failed to write file %s: %w", path, err)
+ if closeErr := file.Close(); closeErr != nil {
+ return fmt.Errorf("failed to write file %s: %w", path, closeErr)
}
return nil
}
diff --git a/cli/pkg/volumes/cmd.go b/cli/pkg/volumes/cmd.go
index 5e4ec80bc..1bc2982c4 100644
--- a/cli/pkg/volumes/cmd.go
+++ b/cli/pkg/volumes/cmd.go
@@ -153,9 +153,9 @@ var deleteCmd = &cobra.Command{
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete volume %s?", resolved.Name))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Are you sure you want to delete volume %s?", resolved.Name))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -172,8 +172,8 @@ var deleteCmd = &cobra.Command{
return fmt.Errorf("failed to delete volume: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to delete volume: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to delete volume: %w", ensureSuccessStatusErr)
}
output.Success("Volume %s deleted successfully", resolved.Name)
@@ -260,8 +260,8 @@ func runVolumeDataCommand(cmd *cobra.Command, cfg volumeDataCommandConfig) error
if !jsonOutput {
output.Header("%s", cfg.header)
}
- if err := cmdutil.PrintJSON(result.Data); err != nil {
- return fmt.Errorf("%s: %w", cfg.marshalMessage, err)
+ if printJSONErr := cmdutil.PrintJSON(result.Data); printJSONErr != nil {
+ return fmt.Errorf("%s: %w", cfg.marshalMessage, printJSONErr)
}
return nil
}
diff --git a/cli/pkg/volumes/workspace.go b/cli/pkg/volumes/workspace.go
index 4a969d13d..ef38ac5ad 100644
--- a/cli/pkg/volumes/workspace.go
+++ b/cli/pkg/volumes/workspace.go
@@ -47,13 +47,13 @@ var workspaceCmd = &cobra.Command{
return fmt.Errorf("failed to get volume workspace: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to get volume workspace: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to get volume workspace: %w", ensureSuccessStatusErr)
}
var result base.ApiResponse[workspacetypes.Workspace]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
+ return decodeJSONErr
}
// The endpoint returns the full tree; an optional path argument
@@ -95,7 +95,9 @@ var workspaceCmd = &cobra.Command{
entry.ModTime.Format(time.RFC3339),
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
if result.Data.FileTreeTruncated {
output.Warning("File listing was truncated by the server")
}
@@ -129,13 +131,13 @@ var workspaceCatCmd = &cobra.Command{
return fmt.Errorf("failed to get workspace file: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to get workspace file: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to get workspace file: %w", ensureSuccessStatusErr)
}
var result base.ApiResponse[workspacetypes.FileContent]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ if decodeJSONErr := cmdutil.DecodeJSON(resp, &result); decodeJSONErr != nil {
+ return decodeJSONErr
}
if jsonOutput {
@@ -180,8 +182,8 @@ var workspaceDownloadCmd = &cobra.Command{
return fmt.Errorf("failed to download workspace file: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to download workspace file: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(resp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to download workspace file: %w", ensureSuccessStatusErr)
}
outputFile := ""
@@ -192,8 +194,8 @@ var workspaceDownloadCmd = &cobra.Command{
outputFile = downloadFilename(resp, path.Base(args[1]))
}
- if err := writeResponseToFile(resp.Body, outputFile); err != nil {
- return err
+ if writeResponseToFileErr := writeResponseToFile(resp.Body, outputFile); writeResponseToFileErr != nil {
+ return writeResponseToFileErr
}
output.Success("File downloaded to %s", outputFile)
@@ -229,9 +231,9 @@ var workspacePutCmd = &cobra.Command{
}
if !forceFlag {
- confirmed, err := cmdutil.Confirm(cmd, fmt.Sprintf("Write %s to %s in volume %s?", args[1], relativePath, resolved.Name))
- if err != nil {
- return err
+ confirmed, confirmErr := cmdutil.Confirm(cmd, fmt.Sprintf("Write %s to %s in volume %s?", args[1], relativePath, resolved.Name))
+ if confirmErr != nil {
+ return confirmErr
}
if !confirmed {
fmt.Println("Cancelled")
@@ -244,12 +246,12 @@ var workspacePutCmd = &cobra.Command{
return fmt.Errorf("failed to get volume workspace: %w", err)
}
defer func() { _ = workspaceResp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(workspaceResp); err != nil {
- return fmt.Errorf("failed to get volume workspace: %w", err)
+ if ensureSuccessStatusErr := cmdutil.EnsureSuccessStatus(workspaceResp); ensureSuccessStatusErr != nil {
+ return fmt.Errorf("failed to get volume workspace: %w", ensureSuccessStatusErr)
}
var current base.ApiResponse[workspacetypes.Workspace]
- if err := cmdutil.DecodeJSON(workspaceResp, &current); err != nil {
- return err
+ if decodeJSONErr := cmdutil.DecodeJSON(workspaceResp, &current); decodeJSONErr != nil {
+ return decodeJSONErr
}
operation := volume.FileOpCreateFile
@@ -276,18 +278,18 @@ var workspacePutCmd = &cobra.Command{
var requestBody bytes.Buffer
writer := multipart.NewWriter(&requestBody)
- if err := writer.WriteField("manifest", string(manifestJSON)); err != nil {
- return fmt.Errorf("failed to write workspace manifest: %w", err)
+ if writeFieldErr := writer.WriteField("manifest", string(manifestJSON)); writeFieldErr != nil {
+ return fmt.Errorf("failed to write workspace manifest: %w", writeFieldErr)
}
filePart, err := writer.CreateFormFile("files", path.Base(relativePath))
if err != nil {
return fmt.Errorf("failed to create workspace upload: %w", err)
}
- if _, err := filePart.Write(content); err != nil {
- return fmt.Errorf("failed to write workspace upload: %w", err)
+ if _, writeErr := filePart.Write(content); writeErr != nil {
+ return fmt.Errorf("failed to write workspace upload: %w", writeErr)
}
- if err := writer.Close(); err != nil {
- return fmt.Errorf("failed to finalize workspace upload: %w", err)
+ if closeErr := writer.Close(); closeErr != nil {
+ return fmt.Errorf("failed to finalize workspace upload: %w", closeErr)
}
resp, err := c.RequestRaw(cmd.Context(), http.MethodPut, types.VolumeWorkspace(c.EnvID(), resolved.Name), &requestBody, map[string]string{"Content-Type": writer.FormDataContentType()})
@@ -295,14 +297,14 @@ var workspacePutCmd = &cobra.Command{
return fmt.Errorf("failed to update volume workspace: %w", err)
}
defer func() { _ = resp.Body.Close() }()
- if err := cmdutil.EnsureSuccessStatus(resp); err != nil {
- return fmt.Errorf("failed to update volume workspace: %w", err)
+ if updateStatusErr := cmdutil.EnsureSuccessStatus(resp); updateStatusErr != nil {
+ return fmt.Errorf("failed to update volume workspace: %w", updateStatusErr)
}
if jsonOutput {
var result base.ApiResponse[workspacetypes.Workspace]
- if err := cmdutil.DecodeJSON(resp, &result); err != nil {
- return err
+ if decodeUpdateErr := cmdutil.DecodeJSON(resp, &result); decodeUpdateErr != nil {
+ return decodeUpdateErr
}
return cmdutil.PrintJSON(result.Data)
}
diff --git a/cli/pkg/vulnerabilities/cmd.go b/cli/pkg/vulnerabilities/cmd.go
index cbea46d8d..f7951294d 100644
--- a/cli/pkg/vulnerabilities/cmd.go
+++ b/cli/pkg/vulnerabilities/cmd.go
@@ -357,8 +357,8 @@ var unignoreCmd = &cobra.Command{
return err
}
- if _, err := c.DeleteJSON[struct{}](cmd.Context(), types.VulnerabilityIgnore(c.EnvID(), args[0])); err != nil {
- return fmt.Errorf("failed to remove ignore record: %w", err)
+ if _, deleteIgnoreErr := c.DeleteJSON[struct{}](cmd.Context(), types.VulnerabilityIgnore(c.EnvID(), args[0])); deleteIgnoreErr != nil {
+ return fmt.Errorf("failed to remove ignore record: %w", deleteIgnoreErr)
}
output.Success("Ignore record %s removed", args[0])
diff --git a/cli/pkg/webhooks/cmd.go b/cli/pkg/webhooks/cmd.go
index 846c9a66c..533046f92 100644
--- a/cli/pkg/webhooks/cmd.go
+++ b/cli/pkg/webhooks/cmd.go
@@ -77,7 +77,9 @@ var listCmd = &cobra.Command{
}
}
- output.Table(headers, rows)
+ if tableErr := output.Table(headers, rows); tableErr != nil {
+ return tableErr
+ }
output.Showing(len(result.Data), int64(len(result.Data)), "webhooks")
return nil
},
@@ -140,8 +142,8 @@ var updateCmd = &cobra.Command{
}
req := webhook.UpdateInput{Enabled: updateEnabled}
- if _, err := c.DoJSON[base.ApiResponse[any]](cmd.Context(), http.MethodPatch, types.Webhook(c.EnvID(), args[0]), req); err != nil {
- return fmt.Errorf("failed to update webhook: %w", err)
+ if _, updateWebhookErr := c.DoJSON[base.ApiResponse[any]](cmd.Context(), http.MethodPatch, types.Webhook(c.EnvID(), args[0]), req); updateWebhookErr != nil {
+ return fmt.Errorf("failed to update webhook: %w", updateWebhookErr)
}
if jsonOutput {
@@ -180,8 +182,8 @@ var deleteCmd = &cobra.Command{
return err
}
- if _, err := c.DeleteJSON[any](cmd.Context(), types.Webhook(c.EnvID(), args[0])); err != nil {
- return fmt.Errorf("failed to delete webhook: %w", err)
+ if _, deleteWebhookErr := c.DeleteJSON[any](cmd.Context(), types.Webhook(c.EnvID(), args[0])); deleteWebhookErr != nil {
+ return fmt.Errorf("failed to delete webhook: %w", deleteWebhookErr)
}
output.Success("Webhook %s deleted successfully", args[0])
diff --git a/types/dockerinfo/docker_info_test.go b/types/dockerinfo/docker_info_test.go
index 6606f79bc..60bdc3379 100644
--- a/types/dockerinfo/docker_info_test.go
+++ b/types/dockerinfo/docker_info_test.go
@@ -17,14 +17,12 @@ func TestInfoMarshalsEmbeddedDockerFieldsAtTopLevel(t *testing.T) {
APIVersion: "1.55",
})
- require.NoError(t, err,
- "marshal Docker info: %v", err)
+ require.NoError(t, err, "marshal Docker info: %v", err)
var payload map[string]any
{
- err := json.Unmarshal(data, &payload)
- require.NoError(t, err,
- "unmarshal Docker info payload: %v", err)
+ unmarshalErr := json.Unmarshal(data, &payload)
+ require.NoError(t, unmarshalErr, "unmarshal Docker info payload: %v", unmarshalErr)
}
for name, want := range map[string]any{
diff --git a/types/features/features_test.go b/types/features/features_test.go
index 6f12862ac..a976d0f18 100644
--- a/types/features/features_test.go
+++ b/types/features/features_test.go
@@ -14,8 +14,14 @@ func TestRegistry(t *testing.T) {
wantFound bool
want features.Definition
}{
- {name: "known feature", id: features.VulnerabilityManagement, wantFound: true, want: features.Definition{ID: features.VulnerabilityManagement, SettingKey: "featureVulnerabilityManagementEnabled", DefaultEnabled: true}},
- {name: "returned definitions are independent", id: features.VulnerabilityManagement, mutateCopy: true, wantFound: true, want: features.Definition{ID: features.VulnerabilityManagement, SettingKey: "featureVulnerabilityManagementEnabled", DefaultEnabled: true}},
+ {
+ name: "known feature", id: features.VulnerabilityManagement, wantFound: true,
+ want: features.Definition{ID: features.VulnerabilityManagement, SettingKey: "featureVulnerabilityManagementEnabled", DefaultEnabled: true},
+ },
+ {
+ name: "returned definitions are independent", id: features.VulnerabilityManagement, mutateCopy: true, wantFound: true,
+ want: features.Definition{ID: features.VulnerabilityManagement, SettingKey: "featureVulnerabilityManagementEnabled", DefaultEnabled: true},
+ },
{name: "swarm defaults off", id: features.Swarm, wantFound: true, want: features.Definition{ID: features.Swarm, SettingKey: "featureSwarmEnabled", DefaultEnabled: false}},
{name: "unknown feature", id: features.ID("unknown")},
}
diff --git a/types/project/marshal_utils.go b/types/project/marshal_utils.go
index fa3301c19..80518f17a 100644
--- a/types/project/marshal_utils.go
+++ b/types/project/marshal_utils.go
@@ -21,16 +21,16 @@ var unitBytesUnmarshalers = json.UnmarshalFromFunc(func(decoder *jsontext.Decode
case jsontext.KindNull:
return nil
case jsontext.KindString:
- parsed, err := units.RAMInBytes(strings.TrimSpace(token.String()))
- if err != nil {
- return err
+ parsed, parseMemoryErr := units.RAMInBytes(strings.TrimSpace(token.String()))
+ if parseMemoryErr != nil {
+ return parseMemoryErr
}
*value = compose.UnitBytes(parsed)
return nil
case jsontext.KindNumber:
raw := token.String()
- parsed, err := strconv.ParseInt(raw, 10, 64)
- if err != nil {
+ parsed, parseIntErr := strconv.ParseInt(raw, 10, 64)
+ if parseIntErr != nil {
floatValue, parseErr := strconv.ParseFloat(raw, 64)
if parseErr != nil {
return parseErr
diff --git a/types/role/role.go b/types/role/role.go
index 7104c4987..4d784ad68 100644
--- a/types/role/role.go
+++ b/types/role/role.go
@@ -65,7 +65,7 @@ type OidcRoleMapping struct {
ClaimValue string `json:"claimValue" doc:"OIDC claim value that triggers this mapping" example:"docker-admins"`
RoleID string `json:"roleId" doc:"Role to assign when the claim matches"`
EnvironmentID *string `json:"environmentId,omitempty" doc:"Environment ID to scope the assignment to; omit for a global assignment"`
- Source string `json:"source" enum:"manual,env" doc:"How this mapping was created. 'manual' rows are UI/API-managed and freely editable; 'env' rows are declared via OIDC_ROLE_MAPPINGS and are read-only at runtime."`
+ Source string `json:"source" enum:"manual,env" doc:"Origin: manual rows are editable via UI/API; env rows come from OIDC_ROLE_MAPPINGS and are read-only"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
}
diff --git a/types/settings/accent_color.go b/types/settings/accent_color.go
index ef2cea8cc..bd8bfc527 100644
--- a/types/settings/accent_color.go
+++ b/types/settings/accent_color.go
@@ -11,5 +11,15 @@ const DefaultAccentColor = "oklch(0.606 0.25 292.717)"
// angle brackets, or quotes are rejected to prevent CSS/SVG injection when
// the value is substituted into a style declaration.
var SafeAccentColor = regexp.MustCompile(
- `^(?:#[0-9a-fA-F]{3,8}|(?i:aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|transparent|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen)|(?:rgb|rgba|hsl|hsla|oklch|oklab)\([0-9a-zA-Z%. ,/-]{1,64}\))$`,
+ `^(?:#[0-9a-fA-F]{3,8}|(?i:aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|` +
+ `chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|` +
+ `darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|` +
+ `deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|` +
+ `honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|` +
+ `lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|` +
+ `limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|` +
+ `mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|` +
+ `paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|` +
+ `seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|transparent|turquoise|violet|` +
+ `wheat|white|whitesmoke|yellow|yellowgreen)|(?:rgb|rgba|hsl|hsla|oklch|oklab)\([0-9a-zA-Z%. ,/-]{1,64}\))$`,
)
diff --git a/types/swarm/node_test.go b/types/swarm/node_test.go
index 47c27d1e4..9b7fc35cc 100644
--- a/types/swarm/node_test.go
+++ b/types/swarm/node_test.go
@@ -47,15 +47,15 @@ func TestNodeAgentStatusAmbiguousJSON(t *testing.T) {
var actual, expected any
{
- err := json.Unmarshal(encoded, &actual)
- require.NoError(t, err,
- "unmarshal actual JSON: %v", err)
+ unmarshalErr := json.Unmarshal(encoded, &actual)
+ require.NoError(t, unmarshalErr,
+ "unmarshal actual JSON: %v", unmarshalErr)
}
{
- err := json.Unmarshal([]byte(`{"state":"ambiguous","candidates":[{"environmentId":"env-1","environmentName":"worker-1","environmentType":"edge"}]}`), &expected)
- require.NoError(t, err,
- "unmarshal expected JSON: %v", err)
+ decodeExpectedErr := json.Unmarshal([]byte(`{"state":"ambiguous","candidates":[{"environmentId":"env-1","environmentName":"worker-1","environmentType":"edge"}]}`), &expected)
+ require.NoError(t, decodeExpectedErr,
+ "unmarshal expected JSON: %v", decodeExpectedErr)
}
require.True(t, reflect.DeepEqual(actual, expected),
diff --git a/types/user/user.go b/types/user/user.go
index 4c95ce820..d4cb8a889 100644
--- a/types/user/user.go
+++ b/types/user/user.go
@@ -33,7 +33,7 @@ type Preferences struct {
// Role assignments are managed separately via PUT /users/{userId}/role-assignments.
// Fields tagged with unorm and trim are trimmed and normalized to Unicode NFC.
type CreateUser struct {
- Username string `json:"username" minLength:"1" maxLength:"255" pattern:"^[^@]+$" patternDescription:"username without an @ character" doc:"Username of the user; may not contain @" example:"johndoe"`
+ Username string `json:"username" minLength:"1" maxLength:"255" pattern:"^[^@]+$" patternDescription:"No @ character" doc:"Username; cannot contain @" example:"johndoe"`
Password string `json:"password" minLength:"8" doc:"Password of the user"`
DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user" example:"John Doe" unorm:"nfc" trim:"true"`
Email *string `json:"email,omitempty" doc:"Email address of the user" example:"[email protected]"`
@@ -44,7 +44,7 @@ type CreateUser struct {
// UpdateUser represents the request body for updating a user.
// Role assignments are managed separately via PUT /users/{userId}/role-assignments.
type UpdateUser struct {
- Username *string `json:"username,omitzero" minLength:"1" maxLength:"255" pattern:"^[^@]+$" patternDescription:"username without an @ character" doc:"Username of the user; may not contain @"`
+ Username *string `json:"username,omitzero" minLength:"1" maxLength:"255" pattern:"^[^@]+$" patternDescription:"No @ character" doc:"Username; cannot contain @"`
DisplayName *string `json:"displayName,omitzero" maxLength:"255" doc:"Display name of the user" unorm:"nfc" trim:"true"`
Email *string `json:"email,omitzero" doc:"Email address of the user"`
Locale *string `json:"locale,omitzero" doc:"Locale preference of the user"`
@@ -70,7 +70,7 @@ type User struct {
OidcSubjectId *string `json:"oidcSubjectId,omitempty" doc:"OIDC subject identifier for SSO users"`
Locale *string `json:"locale,omitempty" doc:"Locale preference of the user" example:"en-US"`
LastLogin *string `json:"lastLogin,omitempty" doc:"Date and time of the user's most recent sign-in; omitted when the user has never signed in"`
- PermissionsByEnv map[string][]string `json:"permissionsByEnv" doc:"Permissions the user effectively holds, keyed by environment ID. The 'global' key holds permissions that apply across every environment (and to org-level endpoints)."`
+ PermissionsByEnv map[string][]string `json:"permissionsByEnv" doc:"Permissions by environment ID; 'global' applies to all environments and organization endpoints"`
Preferences Preferences `json:"preferences" doc:"Personal display and UI preferences"`
ID string `json:"id" doc:"Unique identifier of the user" example:"550e8400-e29b-41d4-a716-446655440000"`
Username string `json:"username" doc:"Username of the user" example:"johndoe"`
diff --git a/types/vulnerability/vulnerability.go b/types/vulnerability/vulnerability.go
index 664b68ab7..edf489a91 100644
--- a/types/vulnerability/vulnerability.go
+++ b/types/vulnerability/vulnerability.go
@@ -283,7 +283,8 @@ type ScoreStatus string
// PatchPriority is a 0-100 risk score with its label and data status.
type PatchPriority struct {
- // RiskScore is the 0-100 patch priority. An image weighs its worst fixable findings plus their count; an environment averages images by exposure and stays in the High band while a known-exploited fix is running.
+ // RiskScore is the 0-100 patch priority. An image weighs its worst fixable findings plus their count; an environment averages images by exposure and
+ // stays in the High band while a known-exploited fix is running.
//
// Required: true
RiskScore int `json:"riskScore"`