Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: cleanup more backend services and restructure dtos
Kyle Mendella66ea025f2a1
diff --git a/backend/internal/dto/container_dto.go b/backend/internal/dto/container_dto.goindex a02a95125..e1c78de36 100644--- a/backend/internal/dto/container_dto.go+++ b/backend/internal/dto/container_dto.go@@ -17,3 +17,11 @@ type CreateContainerDto struct {Memory int64 `json:"memory,omitempty"` // Memory limit in bytesCPUs float64 `json:"cpus,omitempty"` // CPU limit}++type ContainerActionResult struct {+ Started []string `json:"started,omitempty"`+ Stopped []string `json:"stopped,omitempty"`+ Failed []string `json:"failed,omitempty"`+ Success bool `json:"success"`+ Errors []string `json:"errors,omitempty"`+}diff --git a/backend/internal/dto/oidc.go b/backend/internal/dto/oidc.gonew file mode 100644index 000000000..14ca725a9--- /dev/null+++ b/backend/internal/dto/oidc.go@@ -0,0 +1,38 @@+package dto++type OidcUserInfo struct {+ Subject string `json:"sub"`+ Name string `json:"name,omitempty"`+ Email string `json:"email,omitempty"`+ GivenName string `json:"given_name,omitempty"`+ FamilyName string `json:"family_name,omitempty"`+}++type OidcDiscoveryDocument struct {+ Issuer string `json:"issuer"`+ AuthorizationEndpoint string `json:"authorization_endpoint"`+ TokenEndpoint string `json:"token_endpoint"`+ UserinfoEndpoint string `json:"userinfo_endpoint"`+ JwksURI string `json:"jwks_uri"`+ ScopesSupported []string `json:"scopes_supported"`+ ResponseTypesSupported []string `json:"response_types_supported"`+ CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`+}++type OidcTokenResponse struct {+ AccessToken string `json:"access_token"`+ TokenType string `json:"token_type"`+ RefreshToken string `json:"refresh_token,omitempty"`+ ExpiresIn int `json:"expires_in,omitempty"`+ IDToken string `json:"id_token,omitempty"`+}++// Used by GET /auth/oidc/status+type OidcStatusInfo struct {+ EnvForced bool `json:"envForced"`+ EnvConfigured bool `json:"envConfigured"`+ DbEnabled bool `json:"dbEnabled"`+ DbConfigured bool `json:"dbConfigured"`+ EffectivelyEnabled bool `json:"effectivelyEnabled"`+ EffectivelyConfigured bool `json:"effectivelyConfigured"`+}diff --git a/backend/internal/dto/prune_dto.go b/backend/internal/dto/prune_dto.goindex b2da5f0a5..ace59b5fc 100644--- a/backend/internal/dto/prune_dto.go+++ b/backend/internal/dto/prune_dto.go@@ -7,3 +7,13 @@ type PruneSystemDto struct {Networks bool `json:"networks"`Dangling bool `json:"dangling"`}++type PruneAllResult struct {+ ContainersPruned []string `json:"containersPruned,omitempty"`+ ImagesDeleted []string `json:"imagesDeleted,omitempty"`+ VolumesDeleted []string `json:"volumesDeleted,omitempty"`+ NetworksDeleted []string `json:"networksDeleted,omitempty"`+ SpaceReclaimed uint64 `json:"spaceReclaimed"`+ Success bool `json:"success"`+ Errors []string `json:"errors,omitempty"`+}diff --git a/backend/internal/dto/template.go b/backend/internal/dto/template.gonew file mode 100644index 000000000..b9492a89a--- /dev/null+++ b/backend/internal/dto/template.go@@ -0,0 +1,21 @@+package dto++type RemoteTemplate struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Description string `json:"description"`+ Version string `json:"version"`+ Author string `json:"author"`+ Tags []string `json:"tags"`+ ComposeURL string `json:"composeUrl"`+ EnvURL string `json:"envUrl"`+ DocsURL string `json:"docsUrl"`+ IconURL string `json:"iconUrl"`+ UpdatedAt string `json:"updatedAt"`+}++type RemoteRegistry struct {+ Name string `json:"name"`+ Description string `json:"description"`+ Templates []RemoteTemplate `json:"templates"`+}diff --git a/backend/internal/models/template.go b/backend/internal/models/template.goindex 894e89182..45d76c3f2 100644--- a/backend/internal/models/template.go+++ b/backend/internal/models/template.go@@ -40,27 +40,6 @@ type ComposeTemplateMetadata struct {UpdatedAt *string `json:"updatedAt,omitempty" gorm:"column:meta_updated_at"`}-type RemoteTemplate struct {- ID string `json:"id"`- Name string `json:"name"`- Description string `json:"description"`- Version string `json:"version"`- ComposeURL string `json:"compose_url"`- EnvURL string `json:"env_url,omitempty"`- UpdatedAt string `json:"updated_at"`- Author string `json:"author,omitempty"`- Tags []string `json:"tags,omitempty"`- IconURL string `json:"icon_url,omitempty"`- DocsURL string `json:"documentation_url,omitempty"`-}--type RemoteRegistry struct {- Name string `json:"name"`- Description string `json:"description"`- Version string `json:"version"`- Templates []RemoteTemplate `json:"templates"`-}-func (TemplateRegistry) TableName() string {return "template_registries"}diff --git a/backend/internal/services/auth_service.go b/backend/internal/services/auth_service.goindex c16d48edb..dba5e5dc8 100644--- a/backend/internal/services/auth_service.go+++ b/backend/internal/services/auth_service.go@@ -13,6 +13,7 @@ import ("github.com/gin-gonic/gin""github.com/golang-jwt/jwt/v5""github.com/ofkm/arcane-backend/internal/config"+ "github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/models""github.com/ofkm/arcane-backend/internal/utils")@@ -35,15 +36,6 @@ type TokenPair struct {ExpiresAt time.Time `json:"expiresAt"`}-// OidcUserInfo contains user information from OIDC provider-type OidcUserInfo struct {- Subject string `json:"sub"`- Name string `json:"name,omitempty"`- Email string `json:"email,omitempty"`- GivenName string `json:"given_name,omitempty"`- FamilyName string `json:"family_name,omitempty"`-}-// AuthSettings represents the auth configuration structuretype AuthSettings struct {LocalAuthEnabled bool `json:"localAuthEnabled"`@@ -122,8 +114,8 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, errorreturn authSettings, nil}-func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*OidcStatusInfo, error) {- status := &OidcStatusInfo{}+func (s *AuthService) GetOidcConfigurationStatus(ctx context.Context) (*dto.OidcStatusInfo, error) {+ status := &dto.OidcStatusInfo{}status.EnvForced = s.config.OidcEnabled@@ -164,14 +156,6 @@ func (s *AuthService) GetSessionTimeout(ctx context.Context) (int, error) {return timeoutSeconds / 60, nil}-func (s *AuthService) UpdateSessionTimeout(ctx context.Context, minutes int) error {- if minutes <= 0 {- return errors.New("session timeout must be positive")- }-- return s.settingsService.UpdateSetting(ctx, "authSessionTimeout", fmt.Sprintf("%d", minutes*60))-}-func (s *AuthService) IsLocalAuthEnabled(ctx context.Context) (bool, error) {settings, err := s.settingsService.GetSettings(ctx)if err != nil {@@ -201,23 +185,6 @@ func (s *AuthService) GetOidcConfig(ctx context.Context) (*models.OidcConfig, erreturn authSettings.Oidc, nil}-func (s *AuthService) SetLocalAuthEnabled(ctx context.Context, enabled bool) error {- return s.settingsService.UpdateSetting(ctx, "authLocalEnabled", fmt.Sprintf("%t", enabled))-}--func (s *AuthService) SetOidcEnabled(ctx context.Context, enabled bool) error {- return s.settingsService.UpdateSetting(ctx, "authOidcEnabled", fmt.Sprintf("%t", enabled))-}--func (s *AuthService) UpdateOidcConfig(ctx context.Context, oidcConfig *models.OidcConfig) error {- oidcConfigBytes, err := json.Marshal(oidcConfig)- if err != nil {- return fmt.Errorf("failed to marshal OIDC config: %w", err)- }-- return s.settingsService.UpdateSetting(ctx, "authOidcConfig", string(oidcConfigBytes))-}-func (s *AuthService) Login(ctx context.Context, username, password string) (*models.User, *TokenPair, error) {localEnabled, err := s.IsLocalAuthEnabled(ctx)if err != nil {@@ -277,7 +244,7 @@ func (s *AuthService) Login(ctx context.Context, username, password string) (*moreturn user, tokenPair, nil}-func (s *AuthService) OidcLogin(ctx context.Context, userInfo OidcUserInfo) (*models.User, *TokenPair, error) {+func (s *AuthService) OidcLogin(ctx context.Context, userInfo dto.OidcUserInfo) (*models.User, *TokenPair, error) {oidcEnabled, err := s.IsOidcEnabled(ctx)if err != nil {return nil, nil, errdiff --git a/backend/internal/services/auto_update_service.go b/backend/internal/services/auto_update_service.goindex 45dcae240..259dd075e 100644--- a/backend/internal/services/auto_update_service.go+++ b/backend/internal/services/auto_update_service.go@@ -1312,43 +1312,3 @@ func (s *AutoUpdateService) checkStackImagesForUpdates(ctx context.Context, stacreturn hasUpdates, imageUpdates, nil}--func (s *AutoUpdateService) GetRecentErrors(ctx context.Context, since time.Time) ([]models.AutoUpdateRecord, error) {- var records []models.AutoUpdateRecord-- err := s.db.WithContext(ctx).- Where("start_time >= ? AND error IS NOT NULL", since).- Order("start_time DESC").- Find(&records).Error-- if err != nil {- return nil, fmt.Errorf("failed to get recent auto-update errors: %w", err)- }-- return records, nil-}--func (s *AutoUpdateService) GetErrorSummary(ctx context.Context, since time.Time) (map[string]int, error) {- var results []struct {- ErrorType string `json:"error_type"`- Count int `json:"count"`- }-- err := s.db.WithContext(ctx).- Model(&models.AutoUpdateRecord{}).- Select("JSON_EXTRACT(details, '$.errorType') as error_type, COUNT(*) as count").- Where("start_time >= ? AND error IS NOT NULL", since).- Group("JSON_EXTRACT(details, '$.errorType')").- Scan(&results).Error-- if err != nil {- return nil, fmt.Errorf("failed to get error summary: %w", err)- }-- summary := make(map[string]int)- for _, result := range results {- summary[result.ErrorType] = result.Count- }-- return summary, nil-}diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.goindex 81359f328..c83981de0 100644--- a/backend/internal/services/container_registry_service.go+++ b/backend/internal/services/container_registry_service.go@@ -57,14 +57,6 @@ func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id strinreturn ®istry, nil}-func (s *ContainerRegistryService) GetRegistryByURL(ctx context.Context, url string) (*models.ContainerRegistry, error) {- var registry models.ContainerRegistry- if err := s.db.WithContext(ctx).Where("url = ? AND enabled = ?", url, true).First(®istry).Error; err != nil {- return nil, fmt.Errorf("failed to get container registry by URL: %w", err)- }- return ®istry, nil-}-func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req models.CreateContainerRegistryRequest) (*models.ContainerRegistry, error) {// Encrypt the token before storingencryptedToken, err := utils.Encrypt(req.Token)diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.goindex ce779569c..884d9485a 100644--- a/backend/internal/services/container_service.go+++ b/backend/internal/services/container_service.go@@ -8,7 +8,6 @@ import ("fmt""io""strings"- "time""github.com/docker/docker/api/types/container""github.com/docker/docker/api/types/image"@@ -175,37 +174,6 @@ func (s *ContainerService) GetContainerByID(ctx context.Context, id string) (*coreturn &container, nil}-func (s *ContainerService) UpdateContainer(ctx context.Context, container *models.Container) (*models.Container, error) {- now := time.Now()- container.UpdatedAt = &now-- if err := s.db.WithContext(ctx).Save(container).Error; err != nil {- return nil, fmt.Errorf("failed to update container: %w", err)- }- return container, nil-}--func (s *ContainerService) GetContainersByStack(ctx context.Context, stackID string) ([]*models.Container, error) {- var containers []*models.Container- if err := s.db.WithContext(ctx).Where("stack_id = ?", stackID).Find(&containers).Error; err != nil {- return nil, fmt.Errorf("failed to get containers by stack: %w", err)- }- return containers, nil-}--func (s *ContainerService) UpdateContainerStatus(ctx context.Context, id, status, state string) error {- updates := map[string]interface{}{- "status": status,- "state": state,- "updated_at": time.Now(),- }-- if err := s.db.WithContext(ctx).Model(&models.Container{}).Where("container_id = ? OR id = ?", id, id).Updates(updates).Error; err != nil {- return fmt.Errorf("failed to update container status: %w", err)- }- return nil-}-func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force bool, removeVolumes bool, user models.User) error {dockerClient, err := s.dockerService.CreateConnection(ctx)if err != nil {@@ -349,7 +317,6 @@ func (s *ContainerService) StreamLogs(ctx context.Context, containerID string, l}defer dockerClient.Close()- // Configure log optionsoptions := container.LogsOptions{ShowStdout: true,ShowStderr: true,@@ -359,23 +326,19 @@ func (s *ContainerService) StreamLogs(ctx context.Context, containerID string, lTimestamps: timestamps,}- // Get log streamlogs, err := dockerClient.ContainerLogs(ctx, containerID, options)if err != nil {return fmt.Errorf("failed to get container logs: %w", err)}defer logs.Close()- // If following logs, we need to handle the multiplexed streamif follow {return s.streamMultiplexedLogs(ctx, logs, logsChan)}- // For non-following logs, read all at once and send line by linereturn s.readAllLogs(logs, logsChan)}-// streamMultiplexedLogs handles the multiplexed Docker log stream for following logsfunc (s *ContainerService) streamMultiplexedLogs(ctx context.Context, logs io.ReadCloser, logsChan chan<- string) error {// Use stdcopy to demultiplex Docker's stream format// Docker multiplexes stdout and stderr in a special format@@ -451,9 +414,7 @@ func (s *ContainerService) readLogsFromReader(ctx context.Context, reader io.Reareturn scanner.Err()}-// readAllLogs reads all logs at once for non-following requestsfunc (s *ContainerService) readAllLogs(logs io.ReadCloser, logsChan chan<- string) error {- // For non-following logs, read all and demultiplexstdoutBuf := &strings.Builder{}stderrBuf := &strings.Builder{}diff --git a/backend/internal/services/oidc_service.go b/backend/internal/services/oidc_service.goindex 85bc91d07..bdeb965f9 100644--- a/backend/internal/services/oidc_service.go+++ b/backend/internal/services/oidc_service.go@@ -16,29 +16,20 @@ import ("time""github.com/ofkm/arcane-backend/internal/config"+ "github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/models")-type OidcDiscoveryDocument struct {- Issuer string `json:"issuer"`- AuthorizationEndpoint string `json:"authorization_endpoint"`- TokenEndpoint string `json:"token_endpoint"`- UserinfoEndpoint string `json:"userinfo_endpoint"`- JwksURI string `json:"jwks_uri"`- ScopesSupported []string `json:"scopes_supported"`- ResponseTypesSupported []string `json:"response_types_supported"`- CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported"`-}-type OidcService struct {authService *AuthServiceconfig *config.ConfighttpClient *http.Client- discoveryCache map[string]*OidcDiscoveryDocument+ discoveryCache map[string]*dto.OidcDiscoveryDocumentcacheMutex sync.RWMutexcacheExpiry map[string]time.Time}+// internal-only state persisted in cookietype OidcState struct {State string `json:"state"`CodeVerifier string `json:"code_verifier"`@@ -46,27 +37,17 @@ type OidcState struct {CreatedAt time.Time `json:"created_at"`}-type TokenResponse struct {- AccessToken string `json:"access_token"`- TokenType string `json:"token_type"`- RefreshToken string `json:"refresh_token,omitempty"`- ExpiresIn int `json:"expires_in,omitempty"`- IDToken string `json:"id_token,omitempty"`-}-func NewOidcService(authService *AuthService, cfg *config.Config) *OidcService {return &OidcService{- authService: authService,- config: cfg,- httpClient: &http.Client{- Timeout: 30 * time.Second,- },- discoveryCache: make(map[string]*OidcDiscoveryDocument),+ authService: authService,+ config: cfg,+ httpClient: &http.Client{Timeout: 30 * time.Second},+ discoveryCache: make(map[string]*dto.OidcDiscoveryDocument),cacheExpiry: make(map[string]time.Time),}}-func (s *OidcService) discoverOidcEndpoints(ctx context.Context, issuerURL string) (*OidcDiscoveryDocument, error) {+func (s *OidcService) discoverOidcEndpoints(ctx context.Context, issuerURL string) (*dto.OidcDiscoveryDocument, error) {s.cacheMutex.RLock()if cached, exists := s.discoveryCache[issuerURL]; exists {if expiry, hasExpiry := s.cacheExpiry[issuerURL]; hasExpiry && time.Now().Before(expiry) {@@ -110,7 +91,7 @@ func (s *OidcService) discoverOidcEndpoints(ctx context.Context, issuerURL strincontentType, string(bodyBytes[:min(500, len(bodyBytes))]))}- var discovery OidcDiscoveryDocument+ var discovery dto.OidcDiscoveryDocumentif err := json.Unmarshal(bodyBytes, &discovery); err != nil {return nil, fmt.Errorf("failed to decode discovery document from %s: %w. Response body: %s",wellKnownURL, err, string(bodyBytes[:min(500, len(bodyBytes))]))@@ -215,7 +196,7 @@ func (s *OidcService) GenerateAuthURL(ctx context.Context, redirectTo string) (sreturn authURL.String(), encodedState, nil}-func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedState string) (*OidcUserInfo, error) {+func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedState string) (*dto.OidcUserInfo, error) {// Decode stored state to get the original state value and code verifierstateData, err := s.decodeState(storedState)if err != nil {@@ -253,7 +234,7 @@ func (s *OidcService) HandleCallback(ctx context.Context, code, state, storedStareturn userInfo, nil}-func (s *OidcService) exchangeCodeForTokens(ctx context.Context, config *models.OidcConfig, code, codeVerifier string) (*TokenResponse, error) {+func (s *OidcService) exchangeCodeForTokens(ctx context.Context, config *models.OidcConfig, code, codeVerifier string) (*dto.OidcTokenResponse, error) {redirectURI := s.config.GetOidcRedirectURI()data := url.Values{}@@ -283,7 +264,7 @@ func (s *OidcService) exchangeCodeForTokens(ctx context.Context, config *models.return nil, fmt.Errorf("token endpoint returned %d: %s", resp.StatusCode, string(bodyBytes))}- var tokenResponse TokenResponse+ var tokenResponse dto.OidcTokenResponseif err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil {return nil, err}@@ -291,7 +272,7 @@ func (s *OidcService) exchangeCodeForTokens(ctx context.Context, config *models.return &tokenResponse, nil}-func (s *OidcService) getUserInfo(ctx context.Context, config *models.OidcConfig, accessToken string) (*OidcUserInfo, error) {+func (s *OidcService) getUserInfo(ctx context.Context, config *models.OidcConfig, accessToken string) (*dto.OidcUserInfo, error) {req, err := http.NewRequestWithContext(ctx, http.MethodGet, config.UserinfoEndpoint, nil)if err != nil {return nil, err@@ -311,7 +292,7 @@ func (s *OidcService) getUserInfo(ctx context.Context, config *models.OidcConfigreturn nil, fmt.Errorf("userinfo endpoint returned %d: %s", resp.StatusCode, string(bodyBytes))}- var userInfo OidcUserInfo+ var userInfo dto.OidcUserInfoif err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {return nil, err}diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.goindex 65b24773d..f0784a2e6 100644--- a/backend/internal/services/system_service.go+++ b/backend/internal/services/system_service.go@@ -42,30 +42,12 @@ func NewSystemService(}}-type PruneAllResult struct {- ContainersPruned []string `json:"containersPruned,omitempty"`- ImagesDeleted []string `json:"imagesDeleted,omitempty"`- VolumesDeleted []string `json:"volumesDeleted,omitempty"`- NetworksDeleted []string `json:"networksDeleted,omitempty"`- SpaceReclaimed uint64 `json:"spaceReclaimed"`- Success bool `json:"success"`- Errors []string `json:"errors,omitempty"`-}--type ContainerActionResult struct {- Started []string `json:"started,omitempty"`- Stopped []string `json:"stopped,omitempty"`- Failed []string `json:"failed,omitempty"`- Success bool `json:"success"`- Errors []string `json:"errors,omitempty"`-}-var systemUser = models.User{Username: "System",ID: "0",}-func (s *SystemService) PruneAll(ctx context.Context, req dto.PruneSystemDto) (*PruneAllResult, error) {+func (s *SystemService) PruneAll(ctx context.Context, req dto.PruneSystemDto) (*dto.PruneAllResult, error) {slog.InfoContext(ctx, "Starting selective prune operation",slog.Bool("containers", req.Containers),slog.Bool("images", req.Images),@@ -73,7 +55,7 @@ func (s *SystemService) PruneAll(ctx context.Context, req dto.PruneSystemDto) (*slog.Bool("networks", req.Networks),slog.Bool("dangling", req.Dangling))- result := &PruneAllResult{+ result := &dto.PruneAllResult{Success: true,}@@ -151,8 +133,8 @@ func (s *SystemService) getDanglingModeFromSettings(ctx context.Context) (bool,}}-func (s *SystemService) StartAllContainers(ctx context.Context) (*ContainerActionResult, error) {- result := &ContainerActionResult{+func (s *SystemService) StartAllContainers(ctx context.Context) (*dto.ContainerActionResult, error) {+ result := &dto.ContainerActionResult{Success: true,}@@ -178,8 +160,8 @@ func (s *SystemService) StartAllContainers(ctx context.Context) (*ContainerActioreturn result, nil}-func (s *SystemService) StartAllStoppedContainers(ctx context.Context) (*ContainerActionResult, error) {- result := &ContainerActionResult{+func (s *SystemService) StartAllStoppedContainers(ctx context.Context) (*dto.ContainerActionResult, error) {+ result := &dto.ContainerActionResult{Success: true,}@@ -205,8 +187,8 @@ func (s *SystemService) StartAllStoppedContainers(ctx context.Context) (*Containreturn result, nil}-func (s *SystemService) StopAllContainers(ctx context.Context) (*ContainerActionResult, error) {- result := &ContainerActionResult{+func (s *SystemService) StopAllContainers(ctx context.Context) (*dto.ContainerActionResult, error) {+ result := &dto.ContainerActionResult{Success: true,}@@ -230,7 +212,7 @@ func (s *SystemService) StopAllContainers(ctx context.Context) (*ContainerActionreturn result, nil}-func (s *SystemService) pruneContainers(ctx context.Context, result *PruneAllResult) error {+func (s *SystemService) pruneContainers(ctx context.Context, result *dto.PruneAllResult) error {dockerClient, err := s.dockerService.CreateConnection(ctx)if err != nil {return fmt.Errorf("failed to connect to Docker: %w", err)@@ -249,7 +231,7 @@ func (s *SystemService) pruneContainers(ctx context.Context, result *PruneAllResreturn nil}-func (s *SystemService) pruneImages(ctx context.Context, danglingOnly bool, result *PruneAllResult) error {+func (s *SystemService) pruneImages(ctx context.Context, danglingOnly bool, result *dto.PruneAllResult) error {slog.DebugContext(ctx, "Starting image pruning", slog.Bool("dangling_only", danglingOnly))dockerClient, err := s.dockerService.CreateConnection(ctx)@@ -299,10 +281,10 @@ func (s *SystemService) pruneImages(ctx context.Context, danglingOnly bool, resureturn nil}-func (s *SystemService) pruneBuildCache(ctx context.Context, result *PruneAllResult, pruneAllCache bool) error {+func (s *SystemService) pruneBuildCache(ctx context.Context, result *dto.PruneAllResult, pruneAllCache bool) error {dockerClient, err := s.dockerService.CreateConnection(ctx)if err != nil {- result.Errors = append(result.Errors, fmt.Sprintf("Build cache pruning failed (connection): %v", err))+ result.Errors = append(result.Errors, fmt.Errorf("build cache pruning failed (connection): %w", err).Error())slog.ErrorContext(ctx, "Error connecting to Docker for build cache prune", slog.String("error", err.Error()))return fmt.Errorf("failed to connect to Docker for build cache prune: %w", err)}@@ -312,23 +294,24 @@ func (s *SystemService) pruneBuildCache(ctx context.Context, result *PruneAllResAll: pruneAllCache,}- slog.DebugContext(ctx, "Starting build cache pruning", slog.Bool("prune_all", pruneAllCache))+ slog.DebugContext(ctx, "starting build cache pruning", slog.Bool("prune_all", pruneAllCache))report, err := dockerClient.BuildCachePrune(ctx, options)if err != nil {- result.Errors = append(result.Errors, fmt.Sprintf("Build cache pruning failed: %v", err))+ result.Errors = append(result.Errors, fmt.Errorf("build cache pruning failed: %w", err).Error())slog.ErrorContext(ctx, "Error pruning build cache", slog.String("error", err.Error()))return fmt.Errorf("failed to prune build cache: %w", err)}- slog.InfoContext(ctx, "Build cache pruning completed",+ slog.InfoContext(ctx, "build cache pruning completed",slog.Int("cache_entries_deleted", len(report.CachesDeleted)),- slog.Uint64("bytes_reclaimed", report.SpaceReclaimed))+ slog.Uint64("bytes_reclaimed", report.SpaceReclaimed),+ )result.SpaceReclaimed += report.SpaceReclaimedreturn nil}-func (s *SystemService) pruneVolumes(ctx context.Context, result *PruneAllResult) error {+func (s *SystemService) pruneVolumes(ctx context.Context, result *dto.PruneAllResult) error {report, err := s.volumeService.PruneVolumes(ctx)if err != nil {return err@@ -339,7 +322,7 @@ func (s *SystemService) pruneVolumes(ctx context.Context, result *PruneAllResultreturn nil}-func (s *SystemService) pruneNetworks(ctx context.Context, result *PruneAllResult) error {+func (s *SystemService) pruneNetworks(ctx context.Context, result *dto.PruneAllResult) error {report, err := s.networkService.PruneNetworks(ctx)if err != nil {return err@@ -349,10 +332,10 @@ func (s *SystemService) pruneNetworks(ctx context.Context, result *PruneAllResulreturn nil}-func (s *SystemService) PruneSystem(ctx context.Context, all bool) (*PruneAllResult, error) {+func (s *SystemService) PruneSystem(ctx context.Context, all bool) (*dto.PruneAllResult, error) {slog.InfoContext(ctx, "Starting system-wide prune operation", slog.Bool("all", all))- result := &PruneAllResult{+ result := &dto.PruneAllResult{Success: true,}diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.goindex 083631347..d5caab58b 100644--- a/backend/internal/services/template_service.go+++ b/backend/internal/services/template_service.go@@ -11,10 +11,11 @@ import ("path/filepath""regexp""strings"- "sync" // Import sync package+ "sync""time""github.com/ofkm/arcane-backend/internal/database"+ "github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/models""gorm.io/gorm")@@ -25,12 +26,17 @@ type TemplateService struct {remoteTemplatesCache []models.ComposeTemplatelastRemoteFetch time.TimeremoteFetchMutex sync.Mutex++ httpClient *http.Client}const remoteCacheDuration = 5 * time.Minute // Cache durationfunc NewTemplateService(db *database.DB) *TemplateService {- return &TemplateService{db: db}+ return &TemplateService{+ db: db,+ httpClient: &http.Client{Timeout: 30 * time.Second},+ }}// Helper to load remote templates into cache@@ -278,28 +284,36 @@ func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]models.Comreturn templates, nil}-func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, url string) ([]models.RemoteTemplate, error) {- client := &http.Client{Timeout: 30 * time.Second}+// doGET performs a GET and returns the whole body. Centralizes timeout/client use.+func (s *TemplateService) doGET(ctx context.Context, url string) ([]byte, error) {req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)if err != nil {- return nil, fmt.Errorf("failed to create request: %w", err)+ return nil, fmt.Errorf("failed to create request for %s: %w", url, err)}- resp, err := client.Do(req)+ resp, err := s.httpClient.Do(req)if err != nil {- return nil, fmt.Errorf("failed to fetch registry: %w", err)+ return nil, fmt.Errorf("failed to fetch %s: %w", url, err)}defer resp.Body.Close()if resp.StatusCode != http.StatusOK {- return nil, fmt.Errorf("registry returned status %d", resp.StatusCode)+ return nil, fmt.Errorf("HTTP status %d for URL %s", resp.StatusCode, url)}body, err := io.ReadAll(resp.Body)if err != nil {- return nil, fmt.Errorf("failed to read registry response: %w", err)+ return nil, fmt.Errorf("failed to read response body from %s: %w", url, err)+ }+ return body, nil+}++func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, url string) ([]dto.RemoteTemplate, error) {+ body, err := s.doGET(ctx, url)+ if err != nil {+ return nil, err}- var registry models.RemoteRegistry+ var registry dto.RemoteRegistryif err := json.Unmarshal(body, ®istry); err != nil {return nil, fmt.Errorf("failed to parse registry JSON: %w", err)}@@ -307,7 +321,7 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, url stringreturn registry.Templates, nil}-func (s *TemplateService) convertRemoteToLocal(remote models.RemoteTemplate, registry *models.TemplateRegistry) models.ComposeTemplate {+func (s *TemplateService) convertRemoteToLocal(remote dto.RemoteTemplate, registry *models.TemplateRegistry) models.ComposeTemplate {tagsJSON := ""if len(remote.Tags) > 0 {if data, err := json.Marshal(remote.Tags); err == nil {@@ -400,26 +414,10 @@ func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *mo}func (s *TemplateService) fetchURL(ctx context.Context, url string) (string, error) {- client := &http.Client{Timeout: 30 * time.Second}- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)- if err != nil {- return "", fmt.Errorf("failed to create request for %s: %w", url, err)- }- resp, err := client.Do(req)+ body, err := s.doGET(ctx, url)if err != nil {- return "", fmt.Errorf("failed to fetch URL %s: %w", url, err)+ return "", err}- defer resp.Body.Close()-- if resp.StatusCode != http.StatusOK {- return "", fmt.Errorf("HTTP status %d for URL %s", resp.StatusCode, url)- }-- body, err := io.ReadAll(resp.Body)- if err != nil {- return "", fmt.Errorf("failed to read response body from %s: %w", url, err)- }-return string(body), nil}diff --git a/backend/internal/services/user_service.go b/backend/internal/services/user_service.goindex 23c24c75e..5c6145652 100644--- a/backend/internal/services/user_service.go+++ b/backend/internal/services/user_service.go@@ -14,6 +14,8 @@ import ("golang.org/x/crypto/bcrypt""gorm.io/gorm"+ "crypto/subtle"+"github.com/google/uuid""github.com/ofkm/arcane-backend/internal/database""github.com/ofkm/arcane-backend/internal/dto"@@ -121,16 +123,11 @@ func (s *UserService) validateArgon2Password(encodedHash, password string) errorcomparisonHash := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(hashLen))- if len(comparisonHash) != len(decodedHash) {+ // constant-time compare+ if subtle.ConstantTimeCompare(comparisonHash, decodedHash) != 1 {return fmt.Errorf("invalid password")}- for i := range comparisonHash {- if comparisonHash[i] != decodedHash[i] {- return fmt.Errorf("invalid password")- }- }-return nil}@@ -185,10 +182,6 @@ func (s *UserService) GetUserByID(ctx context.Context, id string) (*models.User,return &user, nil}-func (s *UserService) GetUserById(ctx context.Context, id string) (*models.User, error) {- return s.GetUserByID(ctx, id)-}-func (s *UserService) GetUserByOidcSubjectId(ctx context.Context, subjectId string) (*models.User, error) {var user models.Userif err := s.db.WithContext(ctx).Where("oidc_subject_id = ?", subjectId).First(&user).Error; err != nil {@@ -280,32 +273,19 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, req utils.SortedPavar result []dto.UserResponseDtofor _, user := range users {- userResponse := dto.UserResponseDto{- ID: user.ID,- Username: user.Username,- DisplayName: user.DisplayName,- Email: user.Email,- Roles: user.Roles,- OidcSubjectId: user.OidcSubjectId,- CreatedAt: user.CreatedAt.Format("2006-01-02T15:04:05.999999Z"),- UpdatedAt: user.UpdatedAt.Format("2006-01-02T15:04:05.999999Z"),- }- result = append(result, userResponse)+ result = append(result, toUserResponseDto(user))}// Apply search filter if providedif req.Search != "" {- var filteredResult []dto.UserResponseDto+ var filtered []dto.UserResponseDtosearchLower := strings.ToLower(req.Search)-- for _, userResponse := range result {- if strings.Contains(strings.ToLower(userResponse.Username), searchLower) ||- (userResponse.Email != nil && strings.Contains(strings.ToLower(*userResponse.Email), searchLower)) ||- (userResponse.DisplayName != nil && strings.Contains(strings.ToLower(*userResponse.DisplayName), searchLower)) {- filteredResult = append(filteredResult, userResponse)+ for _, u := range result {+ if matchesSearch(u, searchLower) {+ filtered = append(filtered, u)}}- result = filteredResult+ result = filtered}totalItems := len(result)@@ -337,3 +317,22 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, req utils.SortedPareturn result, pagination, nil}++func toUserResponseDto(user models.User) dto.UserResponseDto {+ return dto.UserResponseDto{+ ID: user.ID,+ Username: user.Username,+ DisplayName: user.DisplayName,+ Email: user.Email,+ Roles: user.Roles,+ OidcSubjectId: user.OidcSubjectId,+ CreatedAt: user.CreatedAt.Format("2006-01-02T15:04:05.999999Z"),+ UpdatedAt: user.UpdatedAt.Format("2006-01-02T15:04:05.999999Z"),+ }+}++func matchesSearch(u dto.UserResponseDto, searchLower string) bool {+ return strings.Contains(strings.ToLower(u.Username), searchLower) ||+ (u.Email != nil && strings.Contains(strings.ToLower(*u.Email), searchLower)) ||+ (u.DisplayName != nil && strings.Contains(strings.ToLower(*u.DisplayName), searchLower))+}diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.goindex 4fcb4b67b..f3869a297 100644--- a/backend/internal/services/volume_service.go+++ b/backend/internal/services/volume_service.go@@ -9,6 +9,7 @@ import ("github.com/docker/docker/api/types/container""github.com/docker/docker/api/types/filters""github.com/docker/docker/api/types/volume"+ "github.com/docker/docker/client""github.com/ofkm/arcane-backend/internal/database""github.com/ofkm/arcane-backend/internal/models""github.com/ofkm/arcane-backend/internal/utils"@@ -28,6 +29,64 @@ func NewVolumeService(db *database.DB, dockerService *DockerClientService, event}}+func (s *VolumeService) buildVolumeUsageMap(ctx context.Context, dockerClient *client.Client) (map[string]bool, error) {+ containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})+ if err != nil {+ return nil, fmt.Errorf("failed to list containers: %w", err)+ }++ usage := make(map[string]bool)+ for _, c := range containers {+ info, err := dockerClient.ContainerInspect(ctx, c.ID)+ if err != nil {+ continue+ }+ for _, m := range info.Mounts {+ if m.Type == "volume" && m.Name != "" {+ usage[m.Name] = true+ }+ }+ }+ return usage, nil+}++func (s *VolumeService) containersUsingVolume(ctx context.Context, dockerClient *client.Client, name string) (bool, []string, error) {+ containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})+ if err != nil {+ return false, nil, fmt.Errorf("failed to list containers: %w", err)+ }++ inUse := false+ var using []string+ for _, c := range containers {+ info, err := dockerClient.ContainerInspect(ctx, c.ID)+ if err != nil {+ continue+ }+ for _, m := range info.Mounts {+ if m.Type == "volume" && m.Name == name {+ inUse = true+ using = append(using, c.ID)+ break+ }+ }+ }+ return inUse, using, nil+}++func toVolumeMap(v volume.Volume, inUse bool) map[string]interface{} {+ return map[string]interface{}{+ "Name": v.Name,+ "Driver": v.Driver,+ "Mountpoint": v.Mountpoint,+ "Scope": v.Scope,+ "Options": v.Options,+ "Labels": v.Labels,+ "CreatedAt": v.CreatedAt,+ "InUse": inUse,+ }+}+func (s *VolumeService) ListVolumes(ctx context.Context) ([]volume.Volume, error) {dockerClient, err := s.dockerService.CreateConnection(ctx)if err != nil {@@ -142,7 +201,7 @@ func (s *VolumeService) PruneVolumes(ctx context.Context) (*volume.PruneReport,return nil, fmt.Errorf("failed to prune volumes: %w", err)}- // Log volume prune event using system user since this is typically a system operation+ // Log volume prune event (system user)metadata := models.JSON{"action": "prune","volumesDeleted": len(report.VolumesDeleted),@@ -182,29 +241,10 @@ func (s *VolumeService) GetVolumeUsage(ctx context.Context, name string) (bool,return false, nil, fmt.Errorf("volume not found: %w", err)}- containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})+ inUse, usingContainers, err := s.containersUsingVolume(ctx, dockerClient, name)if err != nil {- return false, nil, fmt.Errorf("failed to list containers: %w", err)+ return false, nil, err}-- inUse := false- var usingContainers []string-- for _, container := range containers {- containerInfo, err := dockerClient.ContainerInspect(ctx, container.ID)- if err != nil {- continue- }-- for _, mount := range containerInfo.Mounts {- if mount.Type == "volume" && mount.Name == name {- inUse = true- usingContainers = append(usingContainers, container.ID)- break- }- }- }-return inUse, usingContainers, nil}@@ -221,58 +261,27 @@ func (s *VolumeService) ListVolumesPaginated(ctx context.Context, req utils.Sort}defer dockerClient.Close()- containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})+ volumeUsageMap, err := s.buildVolumeUsageMap(ctx, dockerClient)if err != nil {- return nil, utils.PaginationResponse{}, fmt.Errorf("failed to list containers: %w", err)- }-- volumeUsageMap := make(map[string]bool)- for _, container := range containers {- containerInfo, err := dockerClient.ContainerInspect(ctx, container.ID)- if err != nil {- continue- }-- for _, mount := range containerInfo.Mounts {- if mount.Type == "volume" {- volumeUsageMap[mount.Name] = true- }- }+ return nil, utils.PaginationResponse{}, err}var result []map[string]interface{}- for _, volume := range volumes {- inUse := volumeUsageMap[volume.Name]-- volumeData := map[string]interface{}{- "Name": volume.Name,- "Driver": volume.Driver,- "Mountpoint": volume.Mountpoint,- "Scope": volume.Scope,- "Options": volume.Options,- "Labels": volume.Labels,- "CreatedAt": volume.CreatedAt,- "InUse": inUse,- }-- result = append(result, volumeData)+ for _, v := range volumes {+ result = append(result, toVolumeMap(v, volumeUsageMap[v.Name]))}if req.Search != "" {- filtered := make([]map[string]interface{}, 0)+ filtered := make([]map[string]interface{}, 0, len(result))searchLower := strings.ToLower(req.Search)- for _, volume := range result {- if name, ok := volume["Name"].(string); ok {- if strings.Contains(strings.ToLower(name), searchLower) {- filtered = append(filtered, volume)- continue- }+ for _, vol := range result {+ if name, ok := vol["Name"].(string); ok && strings.Contains(strings.ToLower(name), searchLower) {+ filtered = append(filtered, vol)+ continue}- if driver, ok := volume["Driver"].(string); ok {- if strings.Contains(strings.ToLower(driver), searchLower) {- filtered = append(filtered, volume)- continue- }+ if driver, ok := vol["Driver"].(string); ok && strings.Contains(strings.ToLower(driver), searchLower) {+ filtered = append(filtered, vol)+ continue}}result = filtered@@ -323,41 +332,14 @@ func (s *VolumeService) ListVolumesWithUsage(ctx context.Context) ([]map[string]}defer dockerClient.Close()- containers, err := dockerClient.ContainerList(ctx, container.ListOptions{All: true})+ volumeUsageMap, err := s.buildVolumeUsageMap(ctx, dockerClient)if err != nil {- return nil, fmt.Errorf("failed to list containers: %w", err)- }-- volumeUsageMap := make(map[string]bool)- for _, container := range containers {- containerInfo, err := dockerClient.ContainerInspect(ctx, container.ID)- if err != nil {- continue- }-- for _, mount := range containerInfo.Mounts {- if mount.Type == "volume" {- volumeUsageMap[mount.Name] = true- }- }+ return nil, err}var result []map[string]interface{}- for _, volume := range volumes {- inUse := volumeUsageMap[volume.Name]-- volumeData := map[string]interface{}{- "Name": volume.Name,- "Driver": volume.Driver,- "Mountpoint": volume.Mountpoint,- "Scope": volume.Scope,- "Options": volume.Options,- "Labels": volume.Labels,- "CreatedAt": volume.CreatedAt,- "InUse": inUse,- }-- result = append(result, volumeData)+ for _, v := range volumes {+ result = append(result, toVolumeMap(v, volumeUsageMap[v.Name]))}return result, nil