Skip to content

Modern Docker Management, Designed for Everyone

refactor: consolidate and cleanup backend utils (#1419)

Kyle Mendell8759100aa57c
diff --git a/backend/cli/upgrade/upgrade.go b/backend/cli/upgrade/upgrade.go
index b8d693871..f91dedc4b 100644
--- a/backend/cli/upgrade/upgrade.go
+++ b/backend/cli/upgrade/upgrade.go
@@ -13,8 +13,8 @@ import (
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
"github.com/getarcaneapp/arcane/backend/internal/utils/arcaneupdater"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/docker"
"github.com/spf13/cobra"
)
@@ -122,7 +122,7 @@ func findArcaneContainer(ctx context.Context, dockerClient *client.Client) (cont
return container.InspectResponse{}, err
}
- selfID, _ := utils.GetCurrentContainerID()
+ selfID, _ := docker.GetCurrentContainerID()
slog.Info("Searching for Arcane container", "selfID", selfID, "totalContainers", len(containers))
now := time.Now()
diff --git a/backend/internal/api/ws_handler.go b/backend/internal/api/ws_handler.go
index 38ac4c819..26c0ca3a8 100644
--- a/backend/internal/api/ws_handler.go
+++ b/backend/internal/api/ws_handler.go
@@ -20,7 +20,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/docker"
httputil "github.com/getarcaneapp/arcane/backend/internal/utils/http"
ws "github.com/getarcaneapp/arcane/backend/internal/utils/ws"
"github.com/gin-gonic/gin"
@@ -164,10 +164,16 @@ func (h *WebSocketHandler) ProjectLogs(c *gin.Context) {
}
follow := c.DefaultQuery("follow", "true") == "true"
- tail := c.DefaultQuery("tail", "100")
- since := c.Query("since")
+ tail, _ := httputil.GetQueryParam(c, "tail", false)
+ if tail == "" {
+ tail = "100"
+ }
+ since, _ := httputil.GetQueryParam(c, "since", false)
timestamps := c.DefaultQuery("timestamps", "false") == "true"
- format := c.DefaultQuery("format", "text")
+ format, _ := httputil.GetQueryParam(c, "format", false)
+ if format == "" {
+ format = "text"
+ }
batched := c.DefaultQuery("batched", "false") == "true"
conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
@@ -267,10 +273,16 @@ func (h *WebSocketHandler) ContainerLogs(c *gin.Context) {
}
follow := c.DefaultQuery("follow", "true") == "true"
- tail := c.DefaultQuery("tail", "100")
- since := c.Query("since")
+ tail, _ := httputil.GetQueryParam(c, "tail", false)
+ if tail == "" {
+ tail = "100"
+ }
+ since, _ := httputil.GetQueryParam(c, "since", false)
timestamps := c.DefaultQuery("timestamps", "false") == "true"
- format := c.DefaultQuery("format", "text")
+ format, _ := httputil.GetQueryParam(c, "format", false)
+ if format == "" {
+ format = "text"
+ }
batched := c.DefaultQuery("batched", "false") == "true"
conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
@@ -567,7 +579,7 @@ func (h *WebSocketHandler) getMemoryInfo() (uint64, uint64) {
// applyCgroupLimits applies cgroup limits when running in a container.
func (h *WebSocketHandler) applyCgroupLimits(cpuCount int, memUsed, memTotal uint64) (int, uint64, uint64) {
- cgroupLimits, err := utils.DetectCgroupLimits()
+ cgroupLimits, err := docker.DetectCgroupLimits()
if err != nil {
return cpuCount, memUsed, memTotal
}
@@ -659,7 +671,12 @@ func (h *WebSocketHandler) SystemStats(c *gin.Context) {
}
defer conn.Close()
- ticker := time.NewTicker(2 * time.Second)
+ interval, _ := httputil.GetIntQueryParam(c, "interval", false)
+ if interval <= 0 {
+ interval = 2
+ }
+
+ ticker := time.NewTicker(time.Duration(interval) * time.Second)
defer ticker.Stop()
cpuUpdateTicker := time.NewTicker(1 * time.Second)
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 158d9bb5a..d2c4356d2 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -17,6 +17,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
httputils "github.com/getarcaneapp/arcane/backend/internal/utils/http"
)
@@ -53,7 +54,7 @@ func Bootstrap(ctx context.Context) error {
utils.LoadAgentToken(appCtx, cfg, appServices.Settings.GetStringSetting)
utils.EnsureEncryptionKey(appCtx, cfg, appServices.Settings.EnsureEncryptionKey)
- utils.InitEncryption(cfg)
+ crypto.InitEncryption(cfg)
utils.InitializeDefaultSettings(appCtx, cfg, appServices.Settings)
if err := appServices.Settings.NormalizeProjectsDirectory(appCtx, cfg.ProjectsDirectory); err != nil {
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index 240297a7d..090444e6b 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -674,14 +674,6 @@ func (e *ProjectIDRequiredError) Error() string {
return "Project ID is required"
}
-type ProjectDeploymentError struct {
- Err error
-}
-
-func (e *ProjectDeploymentError) Error() string {
- return fmt.Sprintf("Failed to deploy project: %v", e.Err)
-}
-
type ProjectDownError struct {
Err error
}
diff --git a/backend/internal/huma/handlers/container_registries.go b/backend/internal/huma/handlers/container_registries.go
index 276a29395..18657d92a 100644
--- a/backend/internal/huma/handlers/container_registries.go
+++ b/backend/internal/huma/handlers/container_registries.go
@@ -8,7 +8,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
"github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
"github.com/getarcaneapp/arcane/backend/internal/utils/registry"
"github.com/getarcaneapp/arcane/types/base"
@@ -348,7 +348,7 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test
return nil, huma.NewError(apiErr.HTTPStatus(), (&common.RegistryRetrievalError{Err: err}).Error())
}
- decryptedToken, err := utils.Decrypt(reg.Token)
+ decryptedToken, err := crypto.Decrypt(reg.Token)
if err != nil {
return nil, huma.Error500InternalServerError((&common.TokenDecryptionError{Err: err}).Error())
}
diff --git a/backend/internal/huma/handlers/environments.go b/backend/internal/huma/handlers/environments.go
index 84561f7f9..ff1b695fe 100644
--- a/backend/internal/huma/handlers/environments.go
+++ b/backend/internal/huma/handlers/environments.go
@@ -15,9 +15,9 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
"github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
"github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/stringutils"
"github.com/getarcaneapp/arcane/types/base"
"github.com/getarcaneapp/arcane/types/environment"
"github.com/getarcaneapp/arcane/types/version"
@@ -724,7 +724,7 @@ func (h *EnvironmentHandler) PairAgent(ctx context.Context, input *PairAgentInpu
shouldRotate := input.Body != nil && input.Body.Rotate != nil && *input.Body.Rotate
if h.cfg.AgentToken == "" || shouldRotate {
- h.cfg.AgentToken = utils.GenerateRandomString(48)
+ h.cfg.AgentToken = stringutils.GenerateRandomString(48)
}
if err := h.settingsService.SetStringSetting(ctx, "agentToken", h.cfg.AgentToken); err != nil {
diff --git a/backend/internal/huma/handlers/system.go b/backend/internal/huma/handlers/system.go
index 9d444eb99..88d737d35 100644
--- a/backend/internal/huma/handlers/system.go
+++ b/backend/internal/huma/handlers/system.go
@@ -12,7 +12,7 @@ import (
humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/docker"
"github.com/getarcaneapp/arcane/types/base"
containertypes "github.com/getarcaneapp/arcane/types/container"
"github.com/getarcaneapp/arcane/types/dockerinfo"
@@ -284,7 +284,7 @@ func (h *SystemHandler) GetDockerInfo(ctx context.Context, input *GetDockerInfoI
memTotal := info.MemTotal
// Check for cgroup limits (LXC, Docker, etc.)
- if cgroupLimits, err := utils.DetectCgroupLimits(); err == nil {
+ if cgroupLimits, err := docker.DetectCgroupLimits(); err == nil {
if limit := cgroupLimits.MemoryLimit; limit > 0 {
limitInt := int64(limit)
if memTotal == 0 || limitInt < memTotal {
diff --git a/backend/internal/huma/middleware/auth.go b/backend/internal/huma/middleware/auth.go
index d4218e676..fe7dde6bf 100644
--- a/backend/internal/huma/middleware/auth.go
+++ b/backend/internal/huma/middleware/auth.go
@@ -238,17 +238,6 @@ func setUserInContext(ctx context.Context, user *models.User) context.Context {
return ctx
}
-// RequireAdmin is a Huma middleware that ensures the current user is an admin.
-func RequireAdmin(api huma.API) func(ctx huma.Context, next func(huma.Context)) {
- return func(ctx huma.Context, next func(huma.Context)) {
- if !IsAdminFromContext(ctx.Context()) {
- _ = huma.WriteErr(api, ctx, http.StatusForbidden, "Forbidden: admin access required")
- return
- }
- next(ctx)
- }
-}
-
func userHasRole(user *models.User, role string) bool {
for _, r := range user.Roles {
if r == role {
diff --git a/backend/internal/job/filesystem_watcher_job.go b/backend/internal/job/filesystem_watcher_job.go
index d2186411e..283cecbd0 100644
--- a/backend/internal/job/filesystem_watcher_job.go
+++ b/backend/internal/job/filesystem_watcher_job.go
@@ -6,7 +6,6 @@ import (
"time"
"github.com/getarcaneapp/arcane/backend/internal/services"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
"github.com/getarcaneapp/arcane/backend/internal/utils/fs"
)
@@ -14,8 +13,8 @@ type FilesystemWatcherJob struct {
projectService *services.ProjectService
templateService *services.TemplateService
settingsService *services.SettingsService
- projectsWatcher *utils.FilesystemWatcher
- templatesWatcher *utils.FilesystemWatcher
+ projectsWatcher *fs.Watcher
+ templatesWatcher *fs.Watcher
}
func NewFilesystemWatcherJob(
@@ -54,7 +53,7 @@ func (j *FilesystemWatcherJob) Start(ctx context.Context) error {
return err
}
- sw, err := utils.NewFilesystemWatcher(projectsDirectory, utils.WatcherOptions{
+ sw, err := fs.NewWatcher(projectsDirectory, fs.WatcherOptions{
Debounce: 3 * time.Second, // Wait 3 seconds after last change before syncing
OnChange: j.handleFilesystemChange,
MaxDepth: 1,
@@ -71,7 +70,7 @@ func (j *FilesystemWatcherJob) Start(ctx context.Context) error {
}
if j.templateService != nil {
- tw, err := utils.NewFilesystemWatcher(templatesDir, utils.WatcherOptions{
+ tw, err := fs.NewWatcher(templatesDir, fs.WatcherOptions{
Debounce: 3 * time.Second,
OnChange: j.handleTemplatesChange,
MaxDepth: 1,
@@ -175,7 +174,7 @@ func (j *FilesystemWatcherJob) RestartProjectsWatcher(ctx context.Context) error
}
// Create a new watcher with the updated path
- sw, err := utils.NewFilesystemWatcher(projectsDirectory, utils.WatcherOptions{
+ sw, err := fs.NewWatcher(projectsDirectory, fs.WatcherOptions{
Debounce: 3 * time.Second,
OnChange: j.handleFilesystemChange,
MaxDepth: 1,
diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.go
index c97963ea9..924706cfa 100644
--- a/backend/internal/services/auth_service.go
+++ b/backend/internal/services/auth_service.go
@@ -11,6 +11,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
"github.com/getarcaneapp/arcane/types/auth"
"github.com/golang-jwt/jwt/v5"
"github.com/google/uuid"
@@ -63,7 +64,7 @@ func NewAuthService(userService *UserService, settingsService *SettingsService,
userService: userService,
settingsService: settingsService,
eventService: eventService,
- jwtSecret: utils.CheckOrGenerateJwtSecret(jwtSecret),
+ jwtSecret: crypto.CheckOrGenerateJwtSecret(jwtSecret),
refreshExpiry: 7 * 24 * time.Hour,
config: cfg,
}
@@ -446,13 +447,13 @@ func (s *AuthService) isAdminFromOidc(ctx context.Context, userInfo auth.OidcUse
return false
}
- if v, ok := utils.GetByPath(userInfo.Extra, claimKey); ok && utils.EvalMatch(v, values) {
+ if v, ok := crypto.GetByPath(userInfo.Extra, claimKey); ok && crypto.EvalMatch(v, values) {
return true
}
if tokenResp != nil && tokenResp.IDToken != "" {
- if claims := utils.ParseJWTClaims(tokenResp.IDToken); claims != nil {
- if v, ok := utils.GetByPath(claims, claimKey); ok && utils.EvalMatch(v, values) {
+ if claims := crypto.ParseJWTClaims(tokenResp.IDToken); claims != nil {
+ if v, ok := crypto.GetByPath(claims, claimKey); ok && crypto.EvalMatch(v, values) {
return true
}
}
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index ed0ee5646..a03a5e385 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -15,6 +15,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/utils"
"github.com/getarcaneapp/arcane/backend/internal/utils/cache"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
"github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
"github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
"github.com/getarcaneapp/arcane/backend/internal/utils/registry"
@@ -99,7 +100,7 @@ func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id strin
func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req models.CreateContainerRegistryRequest) (*models.ContainerRegistry, error) {
// Encrypt the token before storing
- encryptedToken, err := utils.Encrypt(req.Token)
+ encryptedToken, err := crypto.Encrypt(req.Token)
if err != nil {
return nil, fmt.Errorf("failed to encrypt token: %w", err)
}
@@ -134,7 +135,7 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
if req.Token != nil && *req.Token != "" {
// Encrypt the new token
- encryptedToken, err := utils.Encrypt(*req.Token)
+ encryptedToken, err := crypto.Encrypt(*req.Token)
if err != nil {
return nil, fmt.Errorf("failed to encrypt token: %w", err)
}
@@ -168,7 +169,7 @@ func (s *ContainerRegistryService) GetDecryptedToken(ctx context.Context, id str
return "", err
}
- decryptedToken, err := utils.Decrypt(registry.Token)
+ decryptedToken, err := crypto.Decrypt(registry.Token)
if err != nil {
return "", fmt.Errorf("failed to decrypt token: %w", err)
}
@@ -285,7 +286,7 @@ func (s *ContainerRegistryService) findCredentialsForRegistry(ctx context.Contex
regURL = strings.TrimPrefix(regURL, "http://")
if strings.Contains(normalizedURL, regURL) || strings.Contains(regURL, normalizedURL) {
- token, err := utils.Decrypt(reg.Token)
+ token, err := crypto.Decrypt(reg.Token)
if err != nil {
slog.WarnContext(ctx, "Failed to decrypt registry token", "registry", reg.URL, "error", err)
continue
@@ -445,7 +446,7 @@ func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item contain
needsUpdate = utils.UpdateIfChanged(&existing.Username, item.Username) || needsUpdate
// Always update token as it comes decrypted from manager
- encryptedToken, err := utils.Encrypt(item.Token)
+ encryptedToken, err := crypto.Encrypt(item.Token)
if err == nil {
needsUpdate = utils.UpdateIfChanged(&existing.Token, encryptedToken) || needsUpdate
}
@@ -458,7 +459,7 @@ func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item contain
}
func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.Context, item containerregistry.Sync) error {
- encryptedToken, err := utils.Encrypt(item.Token)
+ encryptedToken, err := crypto.Encrypt(item.Token)
if err != nil {
return fmt.Errorf("failed to encrypt token for new registry %s: %w", item.ID, err)
}
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index d53369f21..c7e03a665 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -14,7 +14,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
"github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
"github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
"github.com/getarcaneapp/arcane/types/containerregistry"
@@ -396,7 +396,7 @@ func (s *EnvironmentService) GetEnabledRegistryCredentials(ctx context.Context)
continue
}
- decryptedToken, err := utils.Decrypt(reg.Token)
+ decryptedToken, err := crypto.Decrypt(reg.Token)
if err != nil {
slog.WarnContext(ctx, "Failed to decrypt registry token", "registryURL", reg.URL, "error", err.Error())
continue
@@ -484,7 +484,7 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en
// Prepare sync items with decrypted tokens
syncItems := make([]containerregistry.Sync, 0, len(registries))
for _, reg := range registries {
- decryptedToken, err := utils.Decrypt(reg.Token)
+ decryptedToken, err := crypto.Decrypt(reg.Token)
if err != nil {
slog.WarnContext(ctx, "Failed to decrypt registry token for sync", "registryID", reg.ID, "registryURL", reg.URL, "error", err.Error())
continue
@@ -610,7 +610,7 @@ func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context,
// Decrypt token if present
if repo.Token != "" {
- decryptedToken, err := utils.Decrypt(repo.Token)
+ decryptedToken, err := crypto.Decrypt(repo.Token)
if err != nil {
slog.WarnContext(ctx, "Failed to decrypt repository token for sync", "repositoryID", repo.ID, "repositoryName", repo.Name, "error", err.Error())
continue
@@ -620,7 +620,7 @@ func (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context,
// Decrypt SSH key if present
if repo.SSHKey != "" {
- decryptedSSHKey, err := utils.Decrypt(repo.SSHKey)
+ decryptedSSHKey, err := crypto.Decrypt(repo.SSHKey)
if err != nil {
slog.WarnContext(ctx, "Failed to decrypt repository SSH key for sync", "repositoryID", repo.ID, "repositoryName", repo.Name, "error", err.Error())
continue
diff --git a/backend/internal/services/git_repository_service.go b/backend/internal/services/git_repository_service.go
index 257e8e62e..2e5d7a59f 100644
--- a/backend/internal/services/git_repository_service.go
+++ b/backend/internal/services/git_repository_service.go
@@ -9,6 +9,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
"github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
"github.com/getarcaneapp/arcane/backend/internal/utils/git"
"github.com/getarcaneapp/arcane/backend/internal/utils/mapper"
"github.com/getarcaneapp/arcane/backend/internal/utils/pagination"
@@ -96,7 +97,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.
// Encrypt sensitive fields
if req.Token != "" {
- encrypted, err := utils.Encrypt(req.Token)
+ encrypted, err := crypto.Encrypt(req.Token)
if err != nil {
return nil, fmt.Errorf("failed to encrypt token: %w", err)
}
@@ -104,7 +105,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.
}
if req.SSHKey != "" {
- encrypted, err := utils.Encrypt(req.SSHKey)
+ encrypted, err := crypto.Encrypt(req.SSHKey)
if err != nil {
return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)
}
@@ -161,7 +162,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
if *req.Token == "" {
updates["token"] = ""
} else {
- encrypted, err := utils.Encrypt(*req.Token)
+ encrypted, err := crypto.Encrypt(*req.Token)
if err != nil {
return nil, fmt.Errorf("failed to encrypt token: %w", err)
}
@@ -173,7 +174,7 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,
if *req.SSHKey == "" {
updates["ssh_key"] = ""
} else {
- encrypted, err := utils.Encrypt(*req.SSHKey)
+ encrypted, err := crypto.Encrypt(*req.SSHKey)
if err != nil {
return nil, fmt.Errorf("failed to encrypt SSH key: %w", err)
}
@@ -250,7 +251,7 @@ func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, br
}
if repository.Token != "" {
- token, err := utils.Decrypt(repository.Token)
+ token, err := crypto.Decrypt(repository.Token)
if err != nil {
return fmt.Errorf("failed to decrypt token: %w", err)
}
@@ -258,7 +259,7 @@ func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, br
}
if repository.SSHKey != "" {
- sshKey, err := utils.Decrypt(repository.SSHKey)
+ sshKey, err := crypto.Decrypt(repository.SSHKey)
if err != nil {
return fmt.Errorf("failed to decrypt SSH key: %w", err)
}
@@ -307,7 +308,7 @@ func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *mo
}
if repository.Token != "" {
- token, err := utils.Decrypt(repository.Token)
+ token, err := crypto.Decrypt(repository.Token)
if err != nil {
return authConfig, fmt.Errorf("failed to decrypt token: %w", err)
}
@@ -315,7 +316,7 @@ func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *mo
}
if repository.SSHKey != "" {
- sshKey, err := utils.Decrypt(repository.SSHKey)
+ sshKey, err := crypto.Decrypt(repository.SSHKey)
if err != nil {
return authConfig, fmt.Errorf("failed to decrypt SSH key: %w", err)
}
@@ -454,7 +455,7 @@ func (s *GitRepositoryService) checkRepositoryNeedsUpdate(item gitops.Repository
// Handle Token update
if item.Token != "" {
- encryptedToken, err := utils.Encrypt(item.Token)
+ encryptedToken, err := crypto.Encrypt(item.Token)
if err == nil {
needsUpdate = utils.UpdateIfChanged(&existing.Token, encryptedToken) || needsUpdate
}
@@ -465,7 +466,7 @@ func (s *GitRepositoryService) checkRepositoryNeedsUpdate(item gitops.Repository
// Handle SSH Key update
if item.SSHKey != "" {
- encryptedSSHKey, err := utils.Encrypt(item.SSHKey)
+ encryptedSSHKey, err := crypto.Encrypt(item.SSHKey)
if err == nil {
needsUpdate = utils.UpdateIfChanged(&existing.SSHKey, encryptedSSHKey) || needsUpdate
}
@@ -482,14 +483,14 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item git
var err error
if item.Token != "" {
- encryptedToken, err = utils.Encrypt(item.Token)
+ encryptedToken, err = crypto.Encrypt(item.Token)
if err != nil {
return fmt.Errorf("failed to encrypt token for repository %s: %w", item.ID, err)
}
}
if item.SSHKey != "" {
- encryptedSSHKey, err = utils.Encrypt(item.SSHKey)
+ encryptedSSHKey, err = crypto.Encrypt(item.SSHKey)
if err != nil {
return fmt.Errorf("failed to encrypt SSH key for repository %s: %w", item.ID, err)
}
diff --git a/backend/internal/services/image_update_service.go b/backend/internal/services/image_update_service.go
index 77d77fa81..888c0bf51 100644
--- a/backend/internal/services/image_update_service.go
+++ b/backend/internal/services/image_update_service.go
@@ -11,7 +11,7 @@ import (
"github.com/docker/docker/api/types/image"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
registry "github.com/getarcaneapp/arcane/backend/internal/utils/registry"
"github.com/getarcaneapp/arcane/types/containerregistry"
"github.com/getarcaneapp/arcane/types/imageupdate"
@@ -145,7 +145,7 @@ func (s *ImageUpdateService) getRegistryToken(ctx context.Context, regHost, repo
if reg.Username == "" || reg.Token == "" {
continue
}
- decrypted, decErr := utils.Decrypt(reg.Token)
+ decrypted, decErr := crypto.Decrypt(reg.Token)
if decErr != nil {
lastErr = decErr
continue
@@ -730,7 +730,7 @@ func (s *ImageUpdateService) buildCredentialMap(ctx context.Context, externalCre
if _, exists := credMap[host]; !exists {
credMap[host] = batchCred{username: c.Username, token: c.Token}
}
- encToken, encErr := utils.Encrypt(c.Token)
+ encToken, encErr := crypto.Encrypt(c.Token)
if encErr != nil {
slog.WarnContext(ctx, "Failed to encrypt external registry token", "registryURL", c.URL, "error", encErr.Error())
continue
@@ -761,7 +761,7 @@ func (s *ImageUpdateService) buildCredentialMap(ctx context.Context, externalCre
if host == "" {
continue
}
- dec, decErr := utils.Decrypt(r.Token)
+ dec, decErr := crypto.Decrypt(r.Token)
if decErr != nil {
slog.DebugContext(ctx, "Decrypt registry token failed", "registryURL", r.URL, "error", decErr.Error())
continue
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index 389e8d712..671fbde9d 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -17,7 +17,7 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
"github.com/getarcaneapp/arcane/backend/internal/utils/notifications"
"github.com/getarcaneapp/arcane/backend/resources"
"github.com/getarcaneapp/arcane/types/imageupdate"
@@ -247,7 +247,7 @@ func (s *NotificationService) sendDiscordNotification(ctx context.Context, image
// Decrypt webhook URL if encrypted
webhookURL := discordConfig.WebhookURL
- if decrypted, err := utils.Decrypt(webhookURL); err == nil {
+ if decrypted, err := crypto.Decrypt(webhookURL); err == nil {
webhookURL = decrypted
}
@@ -368,7 +368,7 @@ func (s *NotificationService) sendEmailNotification(ctx context.Context, imageRe
}
if emailConfig.SMTPPassword != "" {
- if decrypted, err := utils.Decrypt(emailConfig.SMTPPassword); err == nil {
+ if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
emailConfig.SMTPPassword = decrypted
}
}
@@ -460,7 +460,7 @@ func (s *NotificationService) sendDiscordContainerUpdateNotification(ctx context
}
webhookURL := discordConfig.WebhookURL
- if decrypted, err := utils.Decrypt(webhookURL); err == nil {
+ if decrypted, err := crypto.Decrypt(webhookURL); err == nil {
webhookURL = decrypted
}
@@ -576,7 +576,7 @@ func (s *NotificationService) sendEmailContainerUpdateNotification(ctx context.C
}
if emailConfig.SMTPPassword != "" {
- if decrypted, err := utils.Decrypt(emailConfig.SMTPPassword); err == nil {
+ if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
emailConfig.SMTPPassword = decrypted
}
}
@@ -737,7 +737,7 @@ func (s *NotificationService) sendTestEmail(ctx context.Context, config models.J
}
if emailConfig.SMTPPassword != "" {
- if decrypted, err := utils.Decrypt(emailConfig.SMTPPassword); err == nil {
+ if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
emailConfig.SMTPPassword = decrypted
}
}
@@ -909,7 +909,7 @@ func (s *NotificationService) sendBatchDiscordNotification(ctx context.Context,
// Decrypt webhook URL if encrypted
webhookURL := discordConfig.WebhookURL
- if decrypted, err := utils.Decrypt(webhookURL); err == nil {
+ if decrypted, err := crypto.Decrypt(webhookURL); err == nil {
webhookURL = decrypted
}
@@ -1009,7 +1009,7 @@ func (s *NotificationService) sendBatchEmailNotification(ctx context.Context, up
}
if emailConfig.SMTPPassword != "" {
- if decrypted, err := utils.Decrypt(emailConfig.SMTPPassword); err == nil {
+ if decrypted, err := crypto.Decrypt(emailConfig.SMTPPassword); err == nil {
emailConfig.SMTPPassword = decrypted
}
}
diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.go
index b2713c337..d4e0c14ff 100644
--- a/backend/internal/services/oidc_service.go
+++ b/backend/internal/services/oidc_service.go
@@ -21,7 +21,8 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/stringutils"
"github.com/getarcaneapp/arcane/types/auth"
)
@@ -162,9 +163,9 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string, or
return "", "", fmt.Errorf("failed to discover provider: %w", err)
}
- state := utils.GenerateRandomString(32)
- nonce := utils.GenerateRandomString(32)
- codeVerifier := utils.GenerateRandomString(128)
+ state := stringutils.GenerateRandomString(32)
+ nonce := stringutils.GenerateRandomString(32)
+ codeVerifier := stringutils.GenerateRandomString(128)
oauth2Config := s.getOauth2Config(config, provider, origin)
@@ -420,7 +421,7 @@ func (s *OidcService) buildUserInfo(ctx context.Context, provider *oidc.Provider
return nil, nil, fmt.Errorf("failed to fetch user claims: %w", err)
}
- subject := utils.GetStringClaim(claims, "sub")
+ subject := crypto.GetStringClaim(claims, "sub")
if subject == "" {
slog.Error("HandleCallback: missing required 'sub' claim")
return nil, nil, errors.New("missing required 'sub' claim in user info")
@@ -428,15 +429,15 @@ func (s *OidcService) buildUserInfo(ctx context.Context, provider *oidc.Provider
userInfoDto := auth.OidcUserInfo{
Subject: subject,
- Name: utils.GetStringClaim(claims, "name"),
- Email: utils.GetStringClaim(claims, "email"),
- EmailVerified: utils.GetBoolClaim(claims, "email_verified"),
- PreferredUsername: utils.GetStringClaim(claims, "preferred_username"),
- GivenName: utils.GetStringClaim(claims, "given_name"),
- FamilyName: utils.GetStringClaim(claims, "family_name"),
- Admin: utils.GetBoolClaim(claims, "admin"),
- Roles: utils.GetStringSliceClaim(claims, "roles"),
- Groups: utils.GetStringSliceClaim(claims, "groups"),
+ Name: crypto.GetStringClaim(claims, "name"),
+ Email: crypto.GetStringClaim(claims, "email"),
+ EmailVerified: crypto.GetBoolClaim(claims, "email_verified"),
+ PreferredUsername: crypto.GetStringClaim(claims, "preferred_username"),
+ GivenName: crypto.GetStringClaim(claims, "given_name"),
+ FamilyName: crypto.GetStringClaim(claims, "family_name"),
+ Admin: crypto.GetBoolClaim(claims, "admin"),
+ Roles: crypto.GetStringSliceClaim(claims, "roles"),
+ Groups: crypto.GetStringSliceClaim(claims, "groups"),
Extra: claims,
}
diff --git a/backend/internal/services/project_service.go b/backend/internal/services/project_service.go
index 6d8383ee9..e0f4058e1 100644
--- a/backend/internal/services/project_service.go
+++ b/backend/internal/services/project_service.go
@@ -91,7 +91,12 @@ func (s *ProjectService) getPathMapper(ctx context.Context) (*pathmapper.PathMap
hostDirResolved = filepath.Clean(hostDirResolved)
}
- return pathmapper.NewPathMapper(containerDirResolved, hostDirResolved), nil
+ pm := pathmapper.NewPathMapper(containerDirResolved, hostDirResolved)
+ if !pm.IsNonMatchingMount() {
+ return nil, nil
+ }
+
+ return pm, nil
}
// Helpers
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 701222182..dca274b3e 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -23,8 +23,8 @@ import (
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/database"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
"github.com/getarcaneapp/arcane/backend/internal/utils/pathmapper"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/stringutils"
"github.com/getarcaneapp/arcane/types/settings"
)
@@ -188,7 +188,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *dat
continue
}
- envVarName := utils.CamelCaseToScreamingSnakeCase(key)
+ envVarName := stringutils.CamelCaseToScreamingSnakeCase(key)
// debug: log each env name checked and whether a value exists
if val, ok := os.LookupEnv(envVarName); ok {
@@ -197,7 +197,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *dat
mask = fmt.Sprintf("%d chars", len(val))
}
slog.DebugContext(ctx, "loadDatabaseConfigFromEnv: env override found", "key", key, "env", envVarName, "valueMasked", mask)
- rv.Field(i).FieldByName("Value").SetString(utils.TrimQuotes(val))
+ rv.Field(i).FieldByName("Value").SetString(stringutils.TrimQuotes(val))
continue
} else if val, ok := settingsMap[key]; ok {
// Fallback to database if environment variable is not set
@@ -249,10 +249,10 @@ func (s *SettingsService) applyEnvOverrides(ctx context.Context, dest *models.Se
}
// Check if environment variable is set
- envVarName := utils.CamelCaseToScreamingSnakeCase(key)
+ envVarName := stringutils.CamelCaseToScreamingSnakeCase(key)
if val, ok := os.LookupEnv(envVarName); ok && val != "" {
slog.DebugContext(ctx, "applyEnvOverrides: applying env override", "key", key, "env", envVarName)
- rv.Field(i).FieldByName("Value").SetString(utils.TrimQuotes(val))
+ rv.Field(i).FieldByName("Value").SetString(stringutils.TrimQuotes(val))
}
}
}
@@ -620,12 +620,12 @@ func (s *SettingsService) processEnvField(ctx context.Context, tx *gorm.DB, fiel
return nil
}
- envVarName := utils.CamelCaseToScreamingSnakeCase(key)
+ envVarName := stringutils.CamelCaseToScreamingSnakeCase(key)
envVal, ok := os.LookupEnv(envVarName)
if !ok {
return nil
}
- envVal = utils.TrimQuotes(envVal)
+ envVal = stringutils.TrimQuotes(envVal)
return s.upsertEnvSetting(ctx, tx, key, envVal)
}
diff --git a/backend/internal/services/system_upgrade_service.go b/backend/internal/services/system_upgrade_service.go
index fbf5dd853..75b0fd3f5 100644
--- a/backend/internal/services/system_upgrade_service.go
+++ b/backend/internal/services/system_upgrade_service.go
@@ -16,7 +16,6 @@ import (
imagetypes "github.com/docker/docker/api/types/image"
mounttypes "github.com/docker/docker/api/types/mount"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
dockerutils "github.com/getarcaneapp/arcane/backend/internal/utils/docker"
)
@@ -186,7 +185,7 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user mo
// getCurrentContainerID detects if we're running in Docker and returns container ID
func (s *SystemUpgradeService) getCurrentContainerID() (string, error) {
- id, err := utils.GetCurrentContainerID()
+ id, err := dockerutils.GetCurrentContainerID()
if err != nil {
return "", ErrNotRunningInDocker
}
diff --git a/backend/internal/services/version_service.go b/backend/internal/services/version_service.go
index 0761b5cea..81e7f01e1 100644
--- a/backend/internal/services/version_service.go
+++ b/backend/internal/services/version_service.go
@@ -14,9 +14,9 @@ import (
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/getarcaneapp/arcane/backend/internal/config"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
"github.com/getarcaneapp/arcane/backend/internal/utils/arcaneupdater"
"github.com/getarcaneapp/arcane/backend/internal/utils/cache"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/docker"
"github.com/getarcaneapp/arcane/types/version"
ref "go.podman.io/image/v5/docker/reference"
"golang.org/x/mod/semver"
@@ -374,7 +374,7 @@ func (s *VersionService) normalizeImageRef(configImage string) string {
// getCurrentContainerID detects if we're running in Docker via cgroup, mountinfo, or hostname
func (s *VersionService) getCurrentContainerID() (string, error) {
- return utils.GetCurrentContainerID()
+ return docker.GetCurrentContainerID()
}
// extractTagFromImageRef extracts the tag from an image reference using distribution/reference
diff --git a/backend/internal/utils/encryption.go b/backend/internal/utils/crypto/encryption.go
similarity index 96%
rename from backend/internal/utils/encryption.go
rename to backend/internal/utils/crypto/encryption.go
index af83fa7cc..d85e28e15 100644
--- a/backend/internal/utils/encryption.go
+++ b/backend/internal/utils/crypto/encryption.go
@@ -1,4 +1,4 @@
-package utils
+package crypto
import (
"crypto/aes"
@@ -19,6 +19,7 @@ import (
var encryptionKey []byte
+// InitEncryption initializes the global encryption key based on configuration
func InitEncryption(cfg *config.Config) {
if keyStr := strings.TrimSpace(cfg.EncryptionKey); keyStr != "" {
key, err := parseExplicitKey(keyStr)
@@ -155,6 +156,7 @@ func deriveDevKey() []byte {
return sum[:]
}
+// Encrypt encrypts a plaintext string using AES-GCM
func Encrypt(plaintext string) (string, error) {
if encryptionKey == nil {
return "", fmt.Errorf("encryption not initialized - call InitEncryption first")
@@ -183,6 +185,7 @@ func Encrypt(plaintext string) (string, error) {
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
+// Decrypt decrypts a base64 encoded ciphertext string using AES-GCM
func Decrypt(ciphertext string) (string, error) {
if encryptionKey == nil {
return "", fmt.Errorf("encryption not initialized - call InitEncryption first")
diff --git a/backend/internal/utils/encryption_test.go b/backend/internal/utils/crypto/encryption_test.go
similarity index 98%
rename from backend/internal/utils/encryption_test.go
rename to backend/internal/utils/crypto/encryption_test.go
index 69414ed95..020c3ac1c 100644
--- a/backend/internal/utils/encryption_test.go
+++ b/backend/internal/utils/crypto/encryption_test.go
@@ -1,4 +1,4 @@
-package utils
+package crypto
import (
"encoding/base64"
@@ -233,7 +233,7 @@ func TestEncryptDecrypt(t *testing.T) {
})
t.Run("encrypt and decrypt unicode text", func(t *testing.T) {
- plaintext := "Unicode test: hello world with emoji" // Removed non-Latin characters per gosmopolitan
+ plaintext := "Unicode test: hello world with emoji"
encrypted, err := Encrypt(plaintext)
require.NoError(t, err)
diff --git a/backend/internal/utils/jwt_util.go b/backend/internal/utils/crypto/jwt.go
similarity index 86%
rename from backend/internal/utils/jwt_util.go
rename to backend/internal/utils/crypto/jwt.go
index 7fd274df9..f140ef494 100644
--- a/backend/internal/utils/jwt_util.go
+++ b/backend/internal/utils/crypto/jwt.go
@@ -1,4 +1,4 @@
-package utils
+package crypto
import (
"crypto/rand"
@@ -8,6 +8,7 @@ import (
"strings"
)
+// GetStringClaim extracts a string claim from a map
func GetStringClaim(m map[string]any, key string) string {
if v, ok := m[key]; ok {
switch t := v.(type) {
@@ -20,6 +21,7 @@ func GetStringClaim(m map[string]any, key string) string {
return ""
}
+// GetBoolClaim extracts a boolean claim from a map
func GetBoolClaim(m map[string]any, key string) bool {
if v, ok := m[key]; ok {
switch t := v.(type) {
@@ -39,6 +41,7 @@ func GetBoolClaim(m map[string]any, key string) bool {
return false
}
+// GetStringSliceClaim extracts a string slice claim from a map
func GetStringSliceClaim(m map[string]any, key string) []string {
v, ok := m[key]
if !ok || v == nil {
@@ -80,6 +83,7 @@ func GetStringSliceClaim(m map[string]any, key string) []string {
return nil
}
+// CheckOrGenerateJwtSecret verifies a secret exists or generates a random one
func CheckOrGenerateJwtSecret(jwtSecret string) []byte {
var secretBytes []byte
if jwtSecret != "" {
@@ -91,9 +95,10 @@ func CheckOrGenerateJwtSecret(jwtSecret string) []byte {
panic(fmt.Errorf("failed to generate random JWT secret: %w", err))
}
}
- return nil
+ return secretBytes
}
+// ParseJWTClaims decodes and unmarshals the payload part of a JWT
func ParseJWTClaims(idToken string) map[string]any {
parts := strings.Split(idToken, ".")
if len(parts) < 2 {
@@ -110,6 +115,7 @@ func ParseJWTClaims(idToken string) map[string]any {
return claims
}
+// GetByPath extracts a value from a nested map using a dot-separated path
func GetByPath(m map[string]any, path string) (any, bool) {
if m == nil {
return nil, false
@@ -130,6 +136,7 @@ func GetByPath(m map[string]any, path string) (any, bool) {
return cur, true
}
+// EvalMatch checks if a claim matches any of the desired values
func EvalMatch(v any, want []string) bool {
if len(want) == 0 {
if b, ok := v.(bool); ok {
diff --git a/backend/internal/utils/cgroup_utils.go b/backend/internal/utils/docker/cgroup_utils.go
similarity index 99%
rename from backend/internal/utils/cgroup_utils.go
rename to backend/internal/utils/docker/cgroup_utils.go
index 1073559b2..f2b546316 100644
--- a/backend/internal/utils/cgroup_utils.go
+++ b/backend/internal/utils/docker/cgroup_utils.go
@@ -1,4 +1,4 @@
-package utils
+package docker
import (
"bufio"
diff --git a/backend/internal/utils/filesystem_watcher.go b/backend/internal/utils/fs/watcher.go
similarity index 83%
rename from backend/internal/utils/filesystem_watcher.go
rename to backend/internal/utils/fs/watcher.go
index b0da3565f..49d6f1fa1 100644
--- a/backend/internal/utils/filesystem_watcher.go
+++ b/backend/internal/utils/fs/watcher.go
@@ -1,4 +1,4 @@
-package utils
+package fs
import (
"context"
@@ -11,7 +11,7 @@ import (
"github.com/fsnotify/fsnotify"
)
-type FilesystemWatcher struct {
+type Watcher struct {
watcher *fsnotify.Watcher
watchedPath string
maxDepth int
@@ -27,7 +27,7 @@ type WatcherOptions struct {
MaxDepth int
}
-func NewFilesystemWatcher(watchPath string, opts WatcherOptions) (*FilesystemWatcher, error) {
+func NewWatcher(watchPath string, opts WatcherOptions) (*Watcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
@@ -41,7 +41,7 @@ func NewFilesystemWatcher(watchPath string, opts WatcherOptions) (*FilesystemWat
opts.MaxDepth = 0
}
- return &FilesystemWatcher{
+ return &Watcher{
watcher: watcher,
watchedPath: filepath.Clean(watchPath),
maxDepth: opts.MaxDepth,
@@ -52,7 +52,7 @@ func NewFilesystemWatcher(watchPath string, opts WatcherOptions) (*FilesystemWat
}, nil
}
-func (fw *FilesystemWatcher) Start(ctx context.Context) error {
+func (fw *Watcher) Start(ctx context.Context) error {
if err := fw.watcher.Add(fw.watchedPath); err != nil {
return err
}
@@ -69,13 +69,13 @@ func (fw *FilesystemWatcher) Start(ctx context.Context) error {
return nil
}
-func (fw *FilesystemWatcher) Stop() error {
+func (fw *Watcher) Stop() error {
close(fw.stopCh)
<-fw.stoppedCh // Wait for watchLoop to finish
return fw.watcher.Close()
}
-func (fw *FilesystemWatcher) watchLoop(ctx context.Context) {
+func (fw *Watcher) watchLoop(ctx context.Context) {
defer close(fw.stoppedCh)
debounceTimer := time.NewTimer(0)
@@ -105,7 +105,7 @@ func (fw *FilesystemWatcher) watchLoop(ctx context.Context) {
}
}
-func (fw *FilesystemWatcher) handleEvent(ctx context.Context, event fsnotify.Event, debounceTimer *time.Timer) {
+func (fw *Watcher) handleEvent(ctx context.Context, event fsnotify.Event, debounceTimer *time.Timer) {
if event.Has(fsnotify.Create) {
if info, err := os.Stat(event.Name); err == nil && info.IsDir() {
if fw.shouldWatchDir(event.Name) {
@@ -144,7 +144,7 @@ func (fw *FilesystemWatcher) handleEvent(ctx context.Context, event fsnotify.Eve
}
}
-func (fw *FilesystemWatcher) handleDebounce(ctx context.Context, timer *time.Timer) {
+func (fw *Watcher) handleDebounce(ctx context.Context, timer *time.Timer) {
select {
case <-ctx.Done():
return
@@ -157,12 +157,12 @@ func (fw *FilesystemWatcher) handleDebounce(ctx context.Context, timer *time.Tim
}
}
-func (fw *FilesystemWatcher) shouldHandleEvent(event fsnotify.Event) bool {
+func (fw *Watcher) shouldHandleEvent(event fsnotify.Event) bool {
name := filepath.Base(event.Name)
// Watch for new directories, compose files, .env being manipulated.
if event.Has(fsnotify.Write) || event.Has(fsnotify.Create) || event.Has(fsnotify.Rename) || event.Has(fsnotify.Remove) {
- if info, err := os.Stat(event.Name); err == nil && info.IsDir() || isProjectFile(name) {
+ if info, err := os.Stat(event.Name); err == nil && info.IsDir() || IsProjectFile(name) {
return true
}
}
@@ -170,7 +170,7 @@ func (fw *FilesystemWatcher) shouldHandleEvent(event fsnotify.Event) bool {
return false
}
-func (fw *FilesystemWatcher) addExistingDirectories(root string) error {
+func (fw *Watcher) addExistingDirectories(root string) error {
return filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
slog.Warn("Error walking directory",
@@ -202,7 +202,8 @@ func (fw *FilesystemWatcher) addExistingDirectories(root string) error {
})
}
-func isProjectFile(filename string) bool {
+// IsProjectFile checks if a filename is a common Docker Compose or environment file
+func IsProjectFile(filename string) bool {
composeFiles := []string{
"compose.yaml",
"compose.yml",
@@ -219,7 +220,7 @@ func isProjectFile(filename string) bool {
return false
}
-func (fw *FilesystemWatcher) dirDepth(path string) int {
+func (fw *Watcher) dirDepth(path string) int {
cleanRoot := fw.watchedPath
cleanPath := filepath.Clean(path)
if cleanPath == cleanRoot {
@@ -238,7 +239,7 @@ func (fw *FilesystemWatcher) dirDepth(path string) int {
return strings.Count(rel, "/") + 1
}
-func (fw *FilesystemWatcher) shouldWatchDir(path string) bool {
+func (fw *Watcher) shouldWatchDir(path string) bool {
if fw.maxDepth <= 0 {
return true
}
diff --git a/backend/internal/utils/pagination/reflect.go b/backend/internal/utils/pagination/reflect.go
index cbd6e76ce..570c41440 100644
--- a/backend/internal/utils/pagination/reflect.go
+++ b/backend/internal/utils/pagination/reflect.go
@@ -4,7 +4,7 @@ import (
"reflect"
"strconv"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/stringutils"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
@@ -17,14 +17,14 @@ func PaginateAndSortDB(params QueryParams, query *gorm.DB, result interface{}) (
sortDirection = "asc"
}
- capitalizedSortColumn := utils.CapitalizeFirstLetter(sortColumn)
+ capitalizedSortColumn := stringutils.CapitalizeFirstLetter(sortColumn)
sortField, sortFieldFound := reflect.TypeOf(result).Elem().Elem().FieldByName(capitalizedSortColumn)
isSortable, _ := strconv.ParseBool(sortField.Tag.Get("sortable"))
sortDirection = normalizeSortDirection(sortDirection)
if sortFieldFound && isSortable {
- columnName := utils.CamelCaseToSnakeCase(sortColumn)
+ columnName := stringutils.CamelCaseToSnakeCase(sortColumn)
query = query.Clauses(clause.OrderBy{
Columns: []clause.OrderByColumn{
{Column: clause.Column{Name: columnName}, Desc: sortDirection == "desc"},
diff --git a/backend/internal/utils/pathmapper/path_mapper.go b/backend/internal/utils/pathmapper/path_mapper.go
index 0855a59a9..f510ea133 100644
--- a/backend/internal/utils/pathmapper/path_mapper.go
+++ b/backend/internal/utils/pathmapper/path_mapper.go
@@ -33,7 +33,7 @@ func NewPathMapper(containerDir, hostDir string) *PathMapper {
// ContainerToHost translates a container path to host path
func (pm *PathMapper) ContainerToHost(containerPath string) (string, error) {
- if !pm.isNonMatching {
+ if !pm.IsNonMatchingMount() {
return containerPath, nil // No translation needed
}
@@ -64,7 +64,7 @@ func (pm *PathMapper) ContainerToHost(containerPath string) (string, error) {
// TranslateVolumeSources translates all bind mount sources in a compose project
func (pm *PathMapper) TranslateVolumeSources(project *composetypes.Project) error {
- if !pm.isNonMatching {
+ if !pm.IsNonMatchingMount() {
return nil // No translation needed
}
diff --git a/backend/internal/utils/projects/cmds.go b/backend/internal/utils/projects/cmds.go
index 951cb2aa3..dab4e9f30 100644
--- a/backend/internal/utils/projects/cmds.go
+++ b/backend/internal/utils/projects/cmds.go
@@ -137,7 +137,8 @@ func emitDeployContainerUpdate(w io.Writer, lastSig map[string]string, cs api.Co
}
phase := deployPhaseFromSummary(cs)
- sig := strings.Join([]string{phase, cs.State, cs.Health, strings.TrimSpace(cs.Status)}, "|")
+ status := strings.TrimSpace(cs.Status)
+ sig := strings.Join([]string{phase, cs.State, cs.Health, status}, "|")
if lastSig[name] == sig {
return
}
@@ -150,8 +151,8 @@ func emitDeployContainerUpdate(w io.Writer, lastSig map[string]string, cs api.Co
"state": cs.State,
"health": cs.Health,
}
- if strings.TrimSpace(cs.Status) != "" {
- payload["status"] = strings.TrimSpace(cs.Status)
+ if status != "" {
+ payload["status"] = status
}
writeJSONLine(w, payload)
}
@@ -163,7 +164,7 @@ func deployPhaseFromSummary(cs api.ContainerSummary) string {
switch {
case state == "running" && health == "healthy":
return "service_healthy"
- case health == "starting" || health == "unhealthy":
+ case health == "starting", health == "unhealthy":
return "service_waiting_healthy"
case state != "running" && state != "":
return "service_state"
diff --git a/backend/internal/utils/projects/compose.go b/backend/internal/utils/projects/compose.go
index 27b0a0c78..af1ecff06 100644
--- a/backend/internal/utils/projects/compose.go
+++ b/backend/internal/utils/projects/compose.go
@@ -52,24 +52,17 @@ func (w writerConsumer) Start(container string) {}
func (w writerConsumer) Stop(container string) {}
func (w writerConsumer) Status(container, msg string) {}
func (w writerConsumer) Log(container, msg string) {
- if w.out == nil {
- return
- }
- // Include container/service name in the format expected by NormalizeProjectLine
- output := msg
- if container != "" {
- output = container + " | " + msg
- }
- if !strings.HasSuffix(output, "\n") {
- output += "\n"
- }
- _, _ = io.WriteString(w.out, output)
+ w.write(container, msg)
}
+
func (w writerConsumer) Err(container, msg string) {
+ w.write(container, msg)
+}
+
+func (w writerConsumer) write(container, msg string) {
if w.out == nil {
return
}
- // Include container/service name in the format expected by NormalizeProjectLine
output := msg
if container != "" {
output = container + " | " + msg
diff --git a/backend/internal/utils/projects/env.go b/backend/internal/utils/projects/env.go
index 1e0b1e9a4..af09ab716 100644
--- a/backend/internal/utils/projects/env.go
+++ b/backend/internal/utils/projects/env.go
@@ -2,6 +2,7 @@ package projects
import (
"context"
+ "errors"
"fmt"
"log/slog"
"os"
@@ -75,14 +76,14 @@ func (l *EnvLoader) loadProcessEnv() EnvMap {
}
func (l *EnvLoader) ensureGlobalEnvFile(ctx context.Context, path string) error {
- if _, err := os.Stat(path); os.IsNotExist(err) {
+ if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
header := fmt.Sprintf(globalEnvHeader, time.Now().Format(time.RFC3339))
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, common.DirPerm); err != nil {
return fmt.Errorf("create dir: %w", err)
}
- if werr := os.WriteFile(path, []byte(header), common.FilePerm); werr != nil {
- return fmt.Errorf("write file: %w", werr)
+ if err := os.WriteFile(path, []byte(header), common.FilePerm); err != nil {
+ return fmt.Errorf("write file: %w", err)
}
slog.InfoContext(ctx, "Created global env file", "path", path)
} else if err != nil {
@@ -96,7 +97,7 @@ func (l *EnvLoader) loadAndMergeGlobalEnv(ctx context.Context, path string, envM
info, err := os.Stat(path)
if err != nil {
- if os.IsNotExist(err) {
+ if errors.Is(err, os.ErrNotExist) {
slog.DebugContext(ctx, "Global env file does not exist", "path", path)
} else {
slog.DebugContext(ctx, "Global env file not accessible", "path", path, "error", err)
@@ -108,15 +109,11 @@ func (l *EnvLoader) loadAndMergeGlobalEnv(ctx context.Context, path string, envM
return fmt.Errorf("path is a directory: %s", path)
}
- slog.DebugContext(ctx, "Found global env file", "path", path)
-
globalEnv, err := parseEnvFileWithContext(path, envMap)
if err != nil {
return fmt.Errorf("parse env file: %w", err)
}
- slog.DebugContext(ctx, "Read global env file", "count", len(globalEnv))
-
for k, v := range globalEnv {
if _, exists := envMap[k]; !exists {
envMap[k] = v
@@ -133,7 +130,7 @@ func (l *EnvLoader) loadAndMergeProjectEnv(ctx context.Context, path string, env
info, err := os.Stat(path)
if err != nil {
- if os.IsNotExist(err) {
+ if errors.Is(err, os.ErrNotExist) {
slog.DebugContext(ctx, "Project .env file does not exist", "path", path)
} else {
slog.DebugContext(ctx, "Project .env file not accessible", "path", path, "error", err)
@@ -145,21 +142,16 @@ func (l *EnvLoader) loadAndMergeProjectEnv(ctx context.Context, path string, env
return fmt.Errorf("path is a directory: %s", path)
}
- slog.DebugContext(ctx, "Found project .env file", "path", path)
-
projectEnv, err := parseEnvFileWithContext(path, envMap)
if err != nil {
return fmt.Errorf("parse env file: %w", err)
}
- slog.DebugContext(ctx, "Read project .env file", "count", len(projectEnv))
-
for k, v := range projectEnv {
envMap[k] = v
if l.autoInjectEnv {
injectionVars[k] = v
}
- slog.DebugContext(ctx, "Loaded env var from project .env", "key", k, "value", v)
}
slog.DebugContext(ctx, "Merged project .env into environment map", "total_env_count", len(envMap))
diff --git a/backend/internal/utils/projects/includes.go b/backend/internal/utils/projects/includes.go
index 4294fc9de..b5846126e 100644
--- a/backend/internal/utils/projects/includes.go
+++ b/backend/internal/utils/projects/includes.go
@@ -1,6 +1,7 @@
package projects
import (
+ "errors"
"fmt"
"os"
"path/filepath"
@@ -77,19 +78,16 @@ func parseIncludeItem(item interface{}, baseDir string) (IncludeFile, error) {
return IncludeFile{}, fmt.Errorf("empty include path")
}
- var fullPath string
- if filepath.IsAbs(includePath) {
- fullPath = includePath
- } else {
+ fullPath := includePath
+ if !filepath.IsAbs(includePath) {
fullPath = filepath.Join(baseDir, includePath)
}
-
fullPath = filepath.Clean(fullPath)
var content string
fileContent, err := os.ReadFile(fullPath)
if err != nil {
- if os.IsNotExist(err) {
+ if errors.Is(err, os.ErrNotExist) {
// File doesn't exist yet - return empty content so it can be created
content = "# This file will be created when you save changes\nservices:\n"
} else {
@@ -134,10 +132,8 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)
}
// Resolve include path to absolute path
- var fullPath string
- if filepath.IsAbs(includePath) {
- fullPath = includePath
- } else {
+ fullPath := includePath
+ if !filepath.IsAbs(includePath) {
fullPath = filepath.Join(absProjectDir, includePath)
}
@@ -148,23 +144,19 @@ func ValidateIncludePathForWrite(projectDir, includePath string) (string, error)
absFullPath = filepath.Clean(absFullPath)
// Resolve symlinks in the include path to prevent symlink-based path traversal attacks
- // For parent directories, we evaluate what exists up to the file itself
evalPath := absFullPath
if evalFullPath, err := filepath.EvalSymlinks(absFullPath); err == nil {
evalPath = evalFullPath
- } else if !os.IsNotExist(err) {
- // If error is not "file doesn't exist", it's a real error
+ } else if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("failed to resolve include path: %w", err)
} else {
// File doesn't exist yet - evaluate parent directory symlinks
dir := filepath.Dir(absFullPath)
if evalDir, err := filepath.EvalSymlinks(dir); err == nil {
evalPath = filepath.Join(evalDir, filepath.Base(absFullPath))
- } else if !os.IsNotExist(err) {
+ } else if !errors.Is(err, os.ErrNotExist) {
return "", fmt.Errorf("failed to resolve parent directory: %w", err)
}
- // If parent also doesn't exist, use the original path
- // The validation will still catch if it's outside the project
}
// Prevent targeting the project directory itself
@@ -191,46 +183,13 @@ func WriteIncludeFile(projectDir, includePath, content string) error {
return err
}
- // Resolve project directory symlinks for comparison
- absProjectDir, err := filepath.Abs(projectDir)
- if err != nil {
- return fmt.Errorf("invalid project directory: %w", err)
- }
- absProjectDir = filepath.Clean(absProjectDir)
- absProjectDir, err = filepath.EvalSymlinks(absProjectDir)
- if err != nil {
- return fmt.Errorf("failed to resolve project directory symlinks: %w", err)
- }
- absProjectDir = filepath.Clean(absProjectDir)
-
- // Use the validated path for all operations
dir := filepath.Dir(validatedPath)
-
- // Only validate that the directory path is not empty or current directory
if dir == "" || dir == "." {
return fmt.Errorf("invalid include path: cannot create directory '%s'", dir)
}
- // Additional check: ensure 'dir' (after resolving symlinks) is inside the project directory
- absDir, err := filepath.Abs(dir)
- if err != nil {
- return fmt.Errorf("invalid include directory: %w", err)
- }
- absDir = filepath.Clean(absDir)
- realDir := absDir
- if evaluatedDir, evalErr := filepath.EvalSymlinks(absDir); evalErr == nil {
- realDir = filepath.Clean(evaluatedDir)
- } else if !os.IsNotExist(evalErr) {
- return fmt.Errorf("failed to resolve include directory symlinks: %w", evalErr)
- }
- projectPrefix := absProjectDir + string(filepath.Separator)
- isWithinProject := strings.HasPrefix(realDir+string(filepath.Separator), projectPrefix) || realDir == absProjectDir
- if !isWithinProject {
- return fmt.Errorf("write access denied: include directory is outside project directory")
- }
-
// Only create directory if it doesn't exist
- if _, err := os.Stat(dir); os.IsNotExist(err) {
+ if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
if err := os.MkdirAll(dir, common.DirPerm); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
diff --git a/backend/internal/utils/projects/load.go b/backend/internal/utils/projects/load.go
index f6d105221..48612f8e5 100644
--- a/backend/internal/utils/projects/load.go
+++ b/backend/internal/utils/projects/load.go
@@ -61,14 +61,9 @@ func LoadComposeProject(ctx context.Context, composeFile, projectName, projectsD
slog.WarnContext(ctx, "Failed to set PWD environment variable", "workdir", workdir, "error", absErr)
}
- // Debug: Log all environment variables being passed to compose
- slog.DebugContext(ctx, "Environment variables for compose interpolation", "count", len(fullEnvMap))
- for k, v := range fullEnvMap {
- slog.DebugContext(ctx, "Env var", "key", k, "value", v)
- }
-
// Pass full environment to compose-go for interpolation, compose-go will use this for ${VAR} expansion in the compose file
cfg := composetypes.ConfigDetails{
+ Version: api.ComposeVersion,
WorkingDir: workdir,
ConfigFiles: []composetypes.ConfigFile{
{Filename: composeFile},
@@ -101,8 +96,21 @@ func LoadComposeProject(ctx context.Context, composeFile, projectName, projectsD
return project, nil
}
+func applyCustomLabelsInternal(projectName string, serviceName string, workingDirectory string, composeFile string) composetypes.Labels {
+ return composetypes.Labels{
+ api.ProjectLabel: projectName,
+ api.ServiceLabel: serviceName,
+ api.VersionLabel: api.ComposeVersion,
+ api.OneoffLabel: "False",
+ api.WorkingDirLabel: workingDirectory,
+ api.ConfigFilesLabel: composeFile,
+ }
+}
+
func injectServiceConfiguration(project *composetypes.Project, injectionVars EnvMap, workdir, composeFile string) {
for i, s := range project.Services {
+ s.CustomLabels = applyCustomLabelsInternal(project.Name, s.Name, workdir, composeFile)
+
// Initialize environment if nil
if s.Environment == nil {
s.Environment = make(composetypes.MappingWithEquals)
@@ -115,17 +123,6 @@ func injectServiceConfiguration(project *composetypes.Project, injectionVars Env
}
}
- if s.CustomLabels == nil {
- s.CustomLabels = composetypes.Labels{}
- }
-
- s.CustomLabels[api.ProjectLabel] = project.Name
- s.CustomLabels[api.ServiceLabel] = s.Name
- s.CustomLabels[api.VersionLabel] = api.ComposeVersion
- s.CustomLabels[api.OneoffLabel] = "False"
- s.CustomLabels[api.WorkingDirLabel] = workdir
- s.CustomLabels[api.ConfigFilesLabel] = composeFile
-
project.Services[i] = s
}
}
@@ -153,19 +150,20 @@ func resolveRelativeProjectPaths(project *composetypes.Project, workdir string)
return
}
- for si := range project.Services {
- service := project.Services[si]
- for vi := range service.Volumes {
- volume := service.Volumes[vi]
- if volume.Type != composetypes.VolumeTypeBind {
- continue
- }
- if resolved, ok := resolvePathRelative(workdir, volume.Source); ok {
- volume.Source = resolved
- service.Volumes[vi] = volume
+ for name, service := range project.Services {
+ modified := false
+ for i := range service.Volumes {
+ v := &service.Volumes[i]
+ if v.Type == composetypes.VolumeTypeBind {
+ if resolved, ok := resolvePathRelative(workdir, v.Source); ok {
+ v.Source = resolved
+ modified = true
+ }
}
}
- project.Services[si] = service
+ if modified {
+ project.Services[name] = service
+ }
}
for name, secret := range project.Secrets {
@@ -184,15 +182,8 @@ func resolveRelativeProjectPaths(project *composetypes.Project, workdir string)
}
func resolvePathRelative(workdir, candidate string) (string, bool) {
- if candidate == "" {
- return candidate, false
- }
- if filepath.IsAbs(candidate) {
+ if candidate == "" || filepath.IsAbs(candidate) || workdir == "" {
return filepath.Clean(candidate), false
}
- if workdir == "" {
- return candidate, false
- }
- resolved := filepath.Join(workdir, candidate)
- return filepath.Clean(resolved), true
+ return filepath.Clean(filepath.Join(workdir, candidate)), true
}
diff --git a/backend/internal/utils/registry/auth.go b/backend/internal/utils/registry/auth.go
index ae30321f3..2a03a8afb 100644
--- a/backend/internal/utils/registry/auth.go
+++ b/backend/internal/utils/registry/auth.go
@@ -13,7 +13,7 @@ import (
ref "go.podman.io/image/v5/docker/reference"
"github.com/getarcaneapp/arcane/backend/internal/models"
- "github.com/getarcaneapp/arcane/backend/internal/utils"
+ "github.com/getarcaneapp/arcane/backend/internal/utils/crypto"
)
type Credentials struct {
@@ -201,7 +201,7 @@ func AcquireTokenViaChallenge(
if normalizeHost(cr.URL) != hostNorm {
continue
}
- dec, err := utils.Decrypt(cr.Token)
+ dec, err := crypto.Decrypt(cr.Token)
if err != nil {
continue
}
@@ -322,7 +322,7 @@ func GetAuthHeaderForImage(ctx context.Context, imageRef string, enabledRegs []m
if normalizeHost(cr.URL) != h {
continue
}
- dec, err := utils.Decrypt(cr.Token)
+ dec, err := crypto.Decrypt(cr.Token)
if err != nil {
continue
}
diff --git a/backend/internal/utils/string_util.go b/backend/internal/utils/stringutils/stringutils.go
similarity index 73%
rename from backend/internal/utils/string_util.go
rename to backend/internal/utils/stringutils/stringutils.go
index 937a57cc5..ca384d248 100644
--- a/backend/internal/utils/string_util.go
+++ b/backend/internal/utils/stringutils/stringutils.go
@@ -1,9 +1,8 @@
-package utils
+package stringutils
import (
"crypto/rand"
"encoding/base64"
- "regexp"
"strings"
)
@@ -25,14 +24,8 @@ func CamelCaseToSnakeCase(str string) string {
return strings.ToLower(result.String())
}
-var camelCaseToScreamingSnakeCaseRe = regexp.MustCompile(`([a-z0-9])([A-Z])`)
-
func CamelCaseToScreamingSnakeCase(s string) string {
- // Insert underscores before uppercase letters (except the first one)
- stringValue := camelCaseToScreamingSnakeCaseRe.ReplaceAllString(s, `${1}_${2}`)
-
- // Convert to uppercase
- return strings.ToUpper(stringValue)
+ return strings.ToUpper(CamelCaseToSnakeCase(s))
}
func GenerateRandomString(length int) string {
diff --git a/backend/internal/utils/stringutils/stringutils_test.go b/backend/internal/utils/stringutils/stringutils_test.go
new file mode 100644
index 000000000..ec7fad347
--- /dev/null
+++ b/backend/internal/utils/stringutils/stringutils_test.go
@@ -0,0 +1,105 @@
+package stringutils
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestCapitalizeFirstLetter(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string
+ }{
+ {"empty string", "", ""},
+ {"single lowercase", "a", "A"},
+ {"single uppercase", "A", "A"},
+ {"word starting with lowercase", "hello", "Hello"},
+ {"word starting with uppercase", "Hello", "Hello"},
+ {"sentence", "hello world", "Hello world"},
+ {"starts with number", "123hello", "123hello"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.expected, CapitalizeFirstLetter(tt.input))
+ })
+ }
+}
+
+func TestCamelCaseToSnakeCase(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string
+ }{
+ {"empty string", "", ""},
+ {"simple", "camelCase", "camel_case"},
+ {"multiple words", "thisIsALongerString", "this_is_a_longer_string"},
+ {"already snake", "already_snake", "already_snake"},
+ {"single word", "word", "word"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.expected, CamelCaseToSnakeCase(tt.input))
+ })
+ }
+}
+
+func TestCamelCaseToScreamingSnakeCase(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string
+ }{
+ {"empty string", "", ""},
+ {"simple", "camelCase", "CAMEL_CASE"},
+ {"multiple words", "thisIsALongerString", "THIS_IS_A_LONGER_STRING"},
+ {"with number", "version2", "VERSION2"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.expected, CamelCaseToScreamingSnakeCase(tt.input))
+ })
+ }
+}
+
+func TestGenerateRandomString(t *testing.T) {
+ t.Run("length check", func(t *testing.T) {
+ length := 32
+ s := GenerateRandomString(length)
+ assert.Len(t, s, length)
+ })
+
+ t.Run("randomness check", func(t *testing.T) {
+ s1 := GenerateRandomString(16)
+ s2 := GenerateRandomString(16)
+ assert.NotEqual(t, s1, s2, "Consecutive calls should produce different strings")
+ })
+}
+
+func TestTrimQuotes(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ expected string
+ }{
+ {"empty string", "", ""},
+ {"no quotes", "hello", "hello"},
+ {"double quotes", "\"hello\"", "hello"},
+ {"single quotes", "'hello'", "hello"},
+ {"only starting double quote", "\"hello", "\"hello"},
+ {"only ending single quote", "hello'", "hello'"},
+ {"mismatched quotes", "'hello\"", "'hello\""},
+ {"long string with quotes", "\"this is a test\"", "this is a test"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.expected, TrimQuotes(tt.input))
+ })
+ }
+}