Skip to content

Modern Docker Management, Designed for Everyone

fix: resolve nil dereferences and a database pool leak

Kyle Mendellc89ac52288ea
diff --git a/backend/api/api_test.go b/backend/api/api_test.go
index 0a6cea428..5d017ade6 100644
--- a/backend/api/api_test.go
+++ b/backend/api/api_test.go
@@ -35,9 +35,6 @@ func TestCustomSchemaNamer_PrefixesArcaneTypesByPackage(t *testing.T) {
if envName != "EnvSummary" {
t.Fatalf("expected EnvSummary, got %q", envName)
}
- if imageName == envName {
- t.Fatalf("expected unique schema names, got same value %q", imageName)
- }
}
func TestCustomSchemaNamer_PointerMatchesValue(t *testing.T) {
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index ab01e2f9e..f57c4a657 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -485,11 +485,12 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con
"api_key_id": apiKeyDto.ID,
"access_token": apiKey,
}
- created, err = h.environmentService.UpdateEnvironment(ctx, created.ID, updates, &user.ID, &user.Username)
+ updated, err := h.environmentService.UpdateEnvironment(ctx, created.ID, updates, &user.ID, &user.Username)
if err != nil {
slog.ErrorContext(ctx, "Failed to link API key to environment", "environmentID", created.ID, "error", err.Error())
return nil, huma.Error500InternalServerError("Failed to link API key")
}
+ created = updated
out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)
if mapErr != nil {
diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.go
index e6e9038e4..db2e4dd2f 100644
--- a/backend/cli/upgrade/upgrade.go
+++ b/backend/cli/upgrade/upgrade.go
@@ -85,11 +85,10 @@ func runUpgrade(cmd *cobra.Command, args []string) error {
slog.Info("Found Arcane container", "name", containerName, "id", targetContainer.ID[:12])
} else {
inspectResult, inspectErr := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerName, client.ContainerInspectOptions{})
- targetContainer = inspectResult.Container
- err = inspectErr
- if err != nil {
- return errors.WrapIff(err, "failed to inspect container %s", containerName)
+ if inspectErr != nil {
+ return errors.WrapIff(inspectErr, "failed to inspect container %s", containerName)
}
+ targetContainer = inspectResult.Container
}
// Determine image to pull
diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go
index 1ed3fbf97..f5afff74b 100644
--- a/backend/internal/database/database.go
+++ b/backend/internal/database/database.go
@@ -59,11 +59,21 @@ func SetGormLogger(l logger.Interface) {
customGormLogger = l
}
-func Initialize(ctx context.Context, databaseURL string, options MigrationOptions) (*DB, error) {
+func Initialize(ctx context.Context, databaseURL string, options MigrationOptions) (database *DB, err error) {
db, err := connectDatabaseInternal(ctx, databaseURL)
if err != nil {
return nil, errors.WrapIf(err, "failed to connect to database")
}
+ // Initialization opens a connection pool before it can fail on migrations or
+ // provider detection; release it rather than leaking it into a failed startup.
+ defer func() {
+ if err == nil {
+ return
+ }
+ if closeErr := db.Close(); closeErr != nil {
+ slog.WarnContext(ctx, "Failed to close database after initialization failure", "error", closeErr)
+ }
+ }()
if err := ctx.Err(); err != nil {
return nil, err
diff --git a/backend/internal/services/federated_credential_service.go b/backend/internal/services/federated_credential_service.go
index 0378d1257..dbc2f3cf0 100644
--- a/backend/internal/services/federated_credential_service.go
+++ b/backend/internal/services/federated_credential_service.go
@@ -683,7 +683,7 @@ func applyFederatedRoleScopeUpdateInternal(existing *models.FederatedCredential,
if normalizedRoleID == "" {
return false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))
}
- roleChanged = roleChanged || normalizedRoleID != existing.RoleID
+ roleChanged = normalizedRoleID != existing.RoleID
existing.RoleID = normalizedRoleID
}
if environmentID != nil {
diff --git a/backend/internal/services/gitops_sync_service.go b/backend/internal/services/gitops_sync_service.go
index 3bb7da28f..46864d95c 100644
--- a/backend/internal/services/gitops_sync_service.go
+++ b/backend/internal/services/gitops_sync_service.go
@@ -953,6 +953,9 @@ func (s *GitOpsSyncService) PerformSync(ctx context.Context, environmentID, id s
if err != nil {
return result, err
}
+ if source == nil {
+ return result, errors.New("prepared sync source is missing")
+ }
if sync.TargetType == "swarm_stack" {
return s.performSwarmStackSyncInternal(syncCtx, sync, id, actor, result, source)
@@ -2000,12 +2003,12 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Con
}
}
- switch {
- case hasEffective:
+ if hasEffective {
if err := projects.WriteEnvFile(projectsDir, stagePath, effective); err != nil {
return errors.WrapIf(err, "seed stage .env")
}
- case hasGit || hasOverride:
+ } else {
+ // Only .env.git and/or project.env exist, so derive .env from them.
merged, mergeErr := projects.BuildEffectiveEnvContent(gitSource, override)
if mergeErr != nil {
return errors.WrapIf(mergeErr, "build effective env from pre-existing project")
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index f5901e5d2..28cd63926 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -248,6 +248,9 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef stri
if err == nil {
digestResult, snapshot, err = s.checkDigestUpdateWithSnapshotInternal(ctx, parts, composeBuildRefs)
}
+ if err == nil && digestResult == nil {
+ err = errors.New("digest update check returned no result")
+ }
if err != nil {
result := &imageupdate.Response{
Error: err.Error(),
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index 2fe677acb..7baacef1e 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -896,8 +896,13 @@ func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(
}
func (s *NotificationService) SendPruneReportNotification(ctx context.Context, result *system.PruneAllResult) error {
+ if result == nil {
+ slog.InfoContext(ctx, "skipping prune report notification because no prune result was reported")
+ return nil
+ }
+
hasChanges := pruneResultHasChangesInternal(result)
- hasErrors := result != nil && len(result.Errors) > 0
+ hasErrors := len(result.Errors) > 0
if !hasChanges && !hasErrors {
slog.InfoContext(ctx, "skipping prune report notification because no resources were pruned and no errors were reported")
return nil
@@ -923,7 +928,7 @@ func (s *NotificationService) SendPruneReportNotification(ctx context.Context, r
func (s *NotificationService) sendPruneReportNotificationForTargetInternal(ctx context.Context, target NotificationTarget, result *system.PruneAllResult) error {
hasChanges := pruneResultHasChangesInternal(result)
- hasErrors := result != nil && len(result.Errors) > 0
+ hasErrors := len(result.Errors) > 0
metadata := models.JSON{
"spaceReclaimed": result.SpaceReclaimed,
diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.go
index 8bce497b9..8ebd70eff 100644
--- a/backend/internal/services/version_service.go
+++ b/backend/internal/services/version_service.go
@@ -128,7 +128,10 @@ func (s *VersionService) fetchLatestReleaseInternal(ctx context.Context) (latest
func (s *VersionService) GetLatestVersion(ctx context.Context) (string, error) {
rel, err := s.getLatestReleaseInternal(ctx)
- return rel.TagName, err
+ if err != nil {
+ return "", err
+ }
+ return rel.TagName, nil
}
func (s *VersionService) IsNewer(latest, current string) bool {
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index de2a43b73..c2d1da51b 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -103,10 +103,10 @@ func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*volu
}
volResult, err := dockerClient.VolumeInspect(ctx, name, client.VolumeInspectOptions{})
- vol := volResult.Volume
if err != nil {
return nil, errors.WrapIf(err, "volume not found")
}
+ vol := volResult.Volume
settings := s.settingsService.GetSettingsConfig()
usageCtx, usageCancel := timeouts.WithTimeout(ctx, settings.DockerAPITimeout.AsInt(), timeouts.DefaultDockerAPI)
@@ -1128,7 +1128,6 @@ func (s *VolumeService) UploadFile(ctx context.Context, volumeName, destPath str
return err
}
if _, err := tw.Write(contentBytes); err != nil {
- _ = tw.Close()
return err
}
if err := tw.Close(); err != nil {
diff --git a/backend/internal/services/vulnerability_service.go b/backend/internal/services/vulnerability_service.go
index d0ed184f8..c193badd0 100644
--- a/backend/internal/services/vulnerability_service.go
+++ b/backend/internal/services/vulnerability_service.go
@@ -2538,11 +2538,9 @@ func copyRegistryConfigToContainerInternal(ctx context.Context, dockerClient *cl
return err
}
if err := tw.WriteHeader(&tar.Header{Name: trivyRegistryConfigTarName, Mode: 0o644, Size: int64(len(configJSON))}); err != nil {
- _ = tw.Close()
return err
}
if _, err := tw.Write(configJSON); err != nil {
- _ = tw.Close()
return err
}
if err := tw.Close(); err != nil {
@@ -2957,11 +2955,7 @@ func decodeTrivyReportFromBytesInternal(rawOutput []byte) (*vulnerability.TrivyR
lastErr = err
}
- if lastErr != nil {
- return nil, lastErr
- }
-
- return nil, errors.New("trivy output did not contain a valid report")
+ return nil, lastErr
}
func decodeSingleTrivyReportInternal(rawOutput []byte) (*vulnerability.TrivyReport, error) {
diff --git a/backend/pkg/gitutil/git.go b/backend/pkg/gitutil/git.go
index f77c29f32..d9ebf708a 100644
--- a/backend/pkg/gitutil/git.go
+++ b/backend/pkg/gitutil/git.go
@@ -254,7 +254,11 @@ func addHostKey(knownHostsPath, hostname string, key gossh.PublicKey) (err error
if err := fileLock.Lock(); err != nil {
return errors.WrapIf(err, "failed to acquire lock on known_hosts file")
}
- defer fileLock.Unlock() //nolint:errcheck
+ defer func() {
+ if unlockErr := fileLock.Unlock(); unlockErr != nil && err == nil {
+ err = errors.WrapIf(unlockErr, "failed to release lock on known_hosts file")
+ }
+ }()
// Append to the file
file, err := os.OpenFile(knownHostsPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
diff --git a/backend/pkg/libarcane/inspect_compat.go b/backend/pkg/libarcane/inspect_compat.go
index d6443ce02..7a2518142 100644
--- a/backend/pkg/libarcane/inspect_compat.go
+++ b/backend/pkg/libarcane/inspect_compat.go
@@ -234,7 +234,7 @@ func normalizeContainerInspectRawJSONInternal(raw []byte) ([]byte, bool, error)
networkSettings, ok := asMapInternal(payload["NetworkSettings"]).Get()
if ok {
- changed = normalizeAddressStringFieldInternal(networkSettings, "Gateway") || changed
+ changed = normalizeAddressStringFieldInternal(networkSettings, "Gateway")
changed = normalizeAddressStringFieldInternal(networkSettings, "IPv6Gateway") || changed
changed = normalizeAddressWithPrefixFieldInternal(networkSettings, "IPAddress", "IPPrefixLen") || changed
changed = normalizeAddressWithPrefixFieldInternal(networkSettings, "GlobalIPv6Address", "GlobalIPv6PrefixLen") || changed
diff --git a/backend/pkg/libarcane/volumes/volume_rename.go b/backend/pkg/libarcane/volumes/volume_rename.go
index a59c6ee37..ecd744eba 100644
--- a/backend/pkg/libarcane/volumes/volume_rename.go
+++ b/backend/pkg/libarcane/volumes/volume_rename.go
@@ -616,7 +616,7 @@ func RollbackVolume(ctx context.Context, dockerClient *client.Client, vol Journa
return removeProjectRenameJournalTargetVolumeInternal(ctx, dockerClient, vol.NewName, oldExists, newExists)
case !oldExists && newExists:
return NewTargetPreservedDuringRollbackError(vol, errProjectRenameRollbackSourceMissingInternal)
- case !oldExists && !newExists:
+ case !oldExists:
slog.WarnContext(ctx, "project rename source and target volumes are missing during rollback", "sourceVolume", vol.OldName, "targetVolume", vol.NewName)
}
return nil
@@ -647,7 +647,7 @@ func cleanupProjectRenameRollbackTargetVolumeInternal(ctx context.Context, docke
return removeProjectRenameJournalTargetVolumeInternal(ctx, dockerClient, vol.NewName, oldExists, newExists)
case !oldExists && newExists:
return NewTargetPreservedDuringRollbackError(vol, errProjectRenameRollbackSourceMissingInternal)
- case !oldExists && !newExists:
+ case !oldExists:
slog.WarnContext(ctx, "project rename source and target volumes are missing during rollback cleanup", "sourceVolume", vol.OldName, "targetVolume", vol.NewName)
}
return nil
diff --git a/backend/pkg/pagination/reflect.go b/backend/pkg/pagination/reflect.go
index 1b4810e26..9ef4376e9 100644
--- a/backend/pkg/pagination/reflect.go
+++ b/backend/pkg/pagination/reflect.go
@@ -43,10 +43,7 @@ func PaginateAndSortDB(params QueryParams, query *gorm.DB, result any) (Response
limit = 100
}
- page := 1
- if limit > 0 {
- page = (params.Start / limit) + 1
- }
+ page := (params.Start / limit) + 1
return paginateDB(page, limit, query, result, params.SkipCount)
}
diff --git a/backend/pkg/projects/fs_writer.go b/backend/pkg/projects/fs_writer.go
index 57da95334..d9a4bb80c 100644
--- a/backend/pkg/projects/fs_writer.go
+++ b/backend/pkg/projects/fs_writer.go
@@ -293,7 +293,7 @@ func RollbackRenamedProjectDirectory(oldPath, newPath string) (pathsMissing bool
if err := os.Rename(newPath, oldPath); err != nil {
return false, errors.WrapIf(err, "rollback project directory rename")
}
- case !oldExists && !newExists:
+ case !oldExists:
pathsMissing = true
slog.Warn("project rename directory paths are missing during rollback", "oldPath", oldPath, "newPath", newPath)
}
diff --git a/cli/internal/cmdutil/limit.go b/cli/internal/cmdutil/limit.go
index 056e46afd..ed05b21ec 100644
--- a/cli/internal/cmdutil/limit.go
+++ b/cli/internal/cmdutil/limit.go
@@ -1,6 +1,8 @@
package cmdutil
import (
+ "context"
+
"github.com/getarcaneapp/arcane/cli/v2/internal/config"
runtimectx "github.com/getarcaneapp/arcane/cli/v2/internal/runtime"
clitypes "github.com/getarcaneapp/arcane/cli/v2/internal/types"
@@ -22,7 +24,12 @@ func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fa
}
resource = clitypes.NormalizePaginatedResource(resource)
- if app, ok := runtimectx.From(cmd.Context()); ok {
+
+ var ctx context.Context
+ if cmd != nil {
+ ctx = cmd.Context()
+ }
+ if app, ok := runtimectx.From(ctx); ok {
if cfg := app.Config(); cfg != nil {
if v := cfg.LimitFor(resource); v != 0 {
return v