Skip to content

Modern Docker Management, Designed for Everyone

fix: environment-admin resource pages request globally protected data (#4151)

Kyle Mendell91825a6865e1
diff --git a/backend/internal/container/resource_stats_test.go b/backend/internal/container/resource_stats_test.go
index 94497574d..73cf0afc3 100644
--- a/backend/internal/container/resource_stats_test.go
+++ b/backend/internal/container/resource_stats_test.go
@@ -88,6 +88,20 @@ func (f *resourceStatsServerInternal) handler() http.Handler {
list := append([]container.Summary{}, f.containers...)
f.mu.Unlock()
_ = json.NewEncoder(w).Encode(list)
+ case strings.HasPrefix(path, "/containers/") && strings.HasSuffix(path, "/json"):
+ id := strings.TrimSuffix(strings.TrimPrefix(path, "/containers/"), "/json")
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ for _, summary := range f.containers {
+ if summary.ID == id {
+ inspect := container.InspectResponse{ID: summary.ID, Name: summary.Names[0], Image: summary.ImageID, Config: &container.Config{Image: summary.Image, Labels: summary.Labels}, State: &container.State{Status: summary.State}}
+ if err := json.NewEncoder(w).Encode(inspect); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ return
+ }
+ }
+ w.WriteHeader(http.StatusNotFound)
case strings.HasPrefix(path, "/containers/") && strings.HasSuffix(path, "/stats"):
id := strings.TrimSuffix(strings.TrimPrefix(path, "/containers/"), "/stats")
cur := f.current.Add(1)
@@ -177,13 +191,30 @@ func TestResourceSortRanksMemoryByBytesNotPercent(t *testing.T) {
fixture.setStats("high-percent", 10, 800, 1000)
fixture.addContainer("high-bytes", "high-bytes", "running")
fixture.setStats("high-bytes", 10, 900, 10000)
+ fixture.addContainer("opted-out", "opted-out", "running", map[string]string{"com.getarcaneapp.arcane.updater": "false"})
+ fixture.setStats("opted-out", 10, 100, 10000)
svc := newResourceSortServiceInternal(t, fixture)
result := listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "desc", 0, 20))
- require.Equal(t, []string{"high-bytes", "high-percent"}, summaryIDsInternal(result.Items))
+ require.Equal(t, []string{"high-bytes", "high-percent", "opted-out"}, summaryIDsInternal(result.Items))
+ require.True(t, result.Items[0].AutoUpdateEnabled)
+ require.False(t, result.Items[2].AutoUpdateEnabled)
result = listResourceSortedInternal(t, svc, resourceSortParamsInternal(containertypes.SortMemoryUsage, "asc", 0, 20))
- require.Equal(t, []string{"high-percent", "high-bytes"}, summaryIDsInternal(result.Items))
+ require.Equal(t, []string{"opted-out", "high-percent", "high-bytes"}, summaryIDsInternal(result.Items))
+
+ flat, err := svc.ListContainersPaginated(t.Context(), resourceSortParamsInternal("name", "asc", 0, 20), true, true, true, "")
+ require.NoError(t, err)
+ require.Equal(t, []string{"high-bytes", "high-percent", "opted-out"}, summaryIDsInternal(flat.Items))
+ require.True(t, flat.Items[0].AutoUpdateEnabled)
+ require.False(t, flat.Items[2].AutoUpdateEnabled)
+
+ details, err := svc.GetContainerDetails(t.Context(), "opted-out")
+ require.NoError(t, err)
+ require.False(t, details.AutoUpdateEnabled, "detail status must match the list status")
+ details, err = svc.GetContainerDetails(t.Context(), "high-bytes")
+ require.NoError(t, err)
+ require.True(t, details.AutoUpdateEnabled)
}
func TestResourceSortOrdersAcrossPages(t *testing.T) {
diff --git a/backend/internal/container/service.go b/backend/internal/container/service.go
index f5cbc8c9f..3864c7fb4 100644
--- a/backend/internal/container/service.go
+++ b/backend/internal/container/service.go
@@ -1182,6 +1182,11 @@ func (s *ContainerService) GetContainerDetails(ctx context.Context, id string) (
details := containertypes.NewDetails(containerInspect)
currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
details.RedeployDisabled = labels.ShouldDisableArcaneServerRedeploy(details.Labels, details.ID, currentContainerID, currentContainerErr)
+ var excluded map[string]bool
+ if s.settingsService != nil {
+ excluded = dockerutils.ExcludedContainerNameSet(s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""))
+ }
+ details.AutoUpdateEnabled = !labels.IsUpdateDisabled(details.Labels) && !dockerutils.ContainerNameExcluded([]string{details.Name}, excluded)
s.applyContainerDetailsIconInternal(ctx, &details)
return details, nil
@@ -1421,7 +1426,7 @@ func (s *ContainerService) ListContainersPaginated(
dockerContainers = FilterExcludedContainers(dockerContainers, includeInternal, includeHidden)
updateInfoMap := s.getUpdateInfoMapInternal(ctx, dockerContainers)
currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
- items := s.BuildSummaries(dockerContainers, updateInfoMap, currentContainerID, currentContainerErr)
+ items := s.BuildSummaries(ctx, dockerContainers, updateInfoMap, currentContainerID, currentContainerErr)
config := s.buildContainerPaginationConfig()
counts := s.CalculateStatusCounts(items)
@@ -1614,8 +1619,12 @@ func (s *ContainerService) getUpdateInfoMapInternal(ctx context.Context, contain
return result
}
-func (s *ContainerService) BuildSummaries(containers []container.Summary, updateInfoMap map[string]*imagetypes.UpdateInfo, currentContainerID string, currentContainerErr error) []containertypes.Summary {
+func (s *ContainerService) BuildSummaries(ctx context.Context, containers []container.Summary, updateInfoMap map[string]*imagetypes.UpdateInfo, currentContainerID string, currentContainerErr error) []containertypes.Summary {
items := make([]containertypes.Summary, 0, len(containers))
+ var excluded map[string]bool
+ if s.settingsService != nil {
+ excluded = dockerutils.ExcludedContainerNameSet(s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""))
+ }
for _, dc := range containers {
summary := containertypes.NewSummary(dc)
key := dc.ImageID
@@ -1635,6 +1644,7 @@ func (s *ContainerService) BuildSummaries(containers []container.Summary, update
summary.UpdateInfo = info
}
summary.RedeployDisabled = labels.ShouldDisableArcaneServerRedeploy(summary.Labels, summary.ID, currentContainerID, currentContainerErr)
+ summary.AutoUpdateEnabled = !labels.IsUpdateDisabled(dc.Labels) && !dockerutils.ContainerNameExcluded(dc.Names, excluded)
summary.Hidden, _ = utils.ParseBool(dc.Labels[libarcane.HiddenResourceLabel])
items = append(items, summary)
}
diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.go
index 493752459..be127ccfb 100644
--- a/backend/internal/container/service_test.go
+++ b/backend/internal/container/service_test.go
@@ -120,11 +120,12 @@ func TestContainerSummaryIconsAppliedAfterGrouping(t *testing.T) {
projects.ArcaneIconLabel: "immich",
}},
{ID: "db", Names: []string{"/db"}, Labels: map[string]string{
- "com.docker.compose.project": "media",
+ "com.docker.compose.project": "media",
+ "com.getarcaneapp.arcane.updater": "false",
}},
}
- items := service.BuildSummaries(dockerContainers, nil, "", nil)
+ items := service.BuildSummaries(t.Context(), dockerContainers, nil, "", nil)
for _, item := range items {
require.Empty(t, item.IconLightURL, "icons must be deferred until after pagination")
}
@@ -141,6 +142,9 @@ func TestContainerSummaryIconsAppliedAfterGrouping(t *testing.T) {
require.Len(t, groups, 1)
require.NotEmpty(t, groups[0].Items[0].IconLightURL)
require.NotEmpty(t, flattened[0].IconLightURL, "flattened items must carry icons applied to the groups")
+ for _, item := range flattened {
+ require.Equal(t, item.ID != "db", item.AutoUpdateEnabled, "grouped items carry the label-derived auto-update status for %s", item.ID)
+ }
}
func groupNamesOf(groups []containertypes.SummaryGroup) []string {
@@ -595,13 +599,14 @@ func TestBuildSummariesUsesContainerTagPolicyUpdates(t *testing.T) {
{ID: "second", Image: "app:3.1.0", ImageID: "shared-image", Labels: map[string]string{strategyLabel: "auto"}},
{ID: "unchecked", Image: "app:3.1.0", ImageID: "shared-image", Labels: map[string]string{strategyLabel: "tag"}},
{ID: "digest", Image: "app:3.1.0", ImageID: "shared-image", Labels: map[string]string{strategyLabel: "digest"}},
+ {ID: "opted-out", Names: []string{"/opted-out"}, Image: "app:3.1.0", ImageID: "shared-image", Labels: map[string]string{"com.getarcaneapp.arcane.updater": "false"}},
}
updates := map[string]*imagetypes.UpdateInfo{
"shared-image": {HasUpdate: true, UpdateType: "digest"},
"container::first": {HasUpdate: true, UpdateType: "tag", LatestVersion: "3.2.0"},
"container::second": {HasUpdate: true, UpdateType: "tag", LatestVersion: "4.0.0"},
}
- items := service.BuildSummaries(containers, updates, "", nil)
+ items := service.BuildSummaries(t.Context(), containers, updates, "", nil)
require.Equal(t, "tag", items[0].UpdateStrategy)
require.Equal(t, "tag", items[1].UpdateStrategy)
require.Equal(t, "digest", items[3].UpdateStrategy)
@@ -609,4 +614,11 @@ func TestBuildSummariesUsesContainerTagPolicyUpdates(t *testing.T) {
require.Equal(t, "4.0.0", items[1].UpdateInfo.LatestVersion)
require.Nil(t, items[2].UpdateInfo)
require.Equal(t, "digest", items[3].UpdateInfo.UpdateType)
+
+ require.True(t, items[0].AutoUpdateEnabled, "containers without opt-out are eligible")
+ require.False(t, items[4].AutoUpdateEnabled, "the updater label disables auto-update")
+ encoded, err := json.Marshal(items[4])
+ require.NoError(t, err)
+ require.Contains(t, string(encoded), `"autoUpdateEnabled":false`, "false status must stay serialized")
+
}
diff --git a/backend/internal/dashboard/service.go b/backend/internal/dashboard/service.go
index aaf670da9..db2727ffb 100644
--- a/backend/internal/dashboard/service.go
+++ b/backend/internal/dashboard/service.go
@@ -192,11 +192,16 @@ func (s *DashboardService) buildSnapshotInternal(ctx context.Context, options Da
containerItems := make([]containertypes.Summary, 0, len(filteredContainers))
currentContainerID, currentContainerErr := cgroup.CurrentContainerID()
if s.containerService != nil {
- containerItems = s.containerService.BuildSummaries(filteredContainers, nil, currentContainerID, currentContainerErr)
+ containerItems = s.containerService.BuildSummaries(ctx, filteredContainers, nil, currentContainerID, currentContainerErr)
} else {
+ var excluded map[string]bool
+ if s.settingsService != nil {
+ excluded = dockerutils.ExcludedContainerNameSet(s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""))
+ }
for _, container := range filteredContainers {
summary := containertypes.NewSummary(container)
summary.RedeployDisabled = labels.ShouldDisableArcaneServerRedeploy(summary.Labels, summary.ID, currentContainerID, currentContainerErr)
+ summary.AutoUpdateEnabled = !labels.IsUpdateDisabled(container.Labels) && !dockerutils.ContainerNameExcluded(container.Names, excluded)
containerItems = append(containerItems, summary)
}
}
diff --git a/backend/internal/dashboard/service_test.go b/backend/internal/dashboard/service_test.go
index 02ce3f876..7432a539c 100644
--- a/backend/internal/dashboard/service_test.go
+++ b/backend/internal/dashboard/service_test.go
@@ -181,6 +181,7 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
projectsDir := t.TempDir()
t.Setenv("PROJECTS_DIRECTORY", projectsDir)
require.NoError(t, settingsSvc.SetStringSetting(context.Background(), "projectsDirectory", projectsDir))
+ require.NoError(t, settingsSvc.SetStringSetting(context.Background(), "autoUpdateExcludedContainers", "stopped-app"))
projectPath := createComposeProjectDirInternal(t, projectsDir, "project-with-update")
require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: repo/worker:latest\n"), 0o644))
dirName := "project-with-update"
@@ -200,6 +201,8 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {
require.Len(t, snapshot.Containers.Data, 2)
require.Equal(t, "container-stopped", snapshot.Containers.Data[0].ID)
+ require.False(t, snapshot.Containers.Data[0].AutoUpdateEnabled, "settings exclusion applies to dashboard summaries")
+ require.True(t, snapshot.Containers.Data[1].AutoUpdateEnabled)
require.Equal(t, 1, snapshot.Containers.Counts.RunningContainers)
require.Equal(t, 1, snapshot.Containers.Counts.StoppedContainers)
require.Equal(t, 2, snapshot.Containers.Counts.TotalContainers)
@@ -403,6 +406,7 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testi
}
dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)
+ require.NoError(t, settingsSvc.SetStringSetting(context.Background(), "autoUpdateExcludedContainers", "running-app"))
containerSvc := container.NewContainerService(nil, dockerSvc, nil, settingsSvc, nil)
svc := NewDashboardService(db, dockerSvc, containerSvc, nil, nil, settingsSvc, nil, nil, nil, nil)
@@ -410,6 +414,7 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testi
require.NoError(t, err)
require.Len(t, defaultSnapshot.Containers.Data, 1)
require.Contains(t, defaultSnapshot.Containers.Data[0].IconLightURL, "selfhst")
+ require.False(t, defaultSnapshot.Containers.Data[0].AutoUpdateEnabled, "container service summaries honor the settings exclusion")
// A user preferring another catalog must not be served the default-catalog
// snapshot from the cache.
diff --git a/backend/internal/image/handler.go b/backend/internal/image/handler.go
index 52fa0fd0d..37404cbd7 100644
--- a/backend/internal/image/handler.go
+++ b/backend/internal/image/handler.go
@@ -48,6 +48,11 @@ type ImageHandler struct {
// --- Huma Input/Output Wrappers ---
+// ListImagesOutput is the image list response including the upload limit.
+type ListImagesOutput struct {
+ Body image.ListResponse
+}
+
type ListImagesInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Search string `query:"search" doc:"Search query"`
@@ -311,7 +316,7 @@ func RegisterImages(api huma.API, dockerService *docker.DockerClientService, ima
}
// ListImages returns a paginated list of images.
-func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (*handlerutil.Page[image.Summary], error) {
+func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (*ListImagesOutput, error) {
params := handlerutil.PaginationParams(input.Start, input.Limit, input.Sort, input.Order, input.Search)
if input.InUse != "" {
params.Filters["inUse"] = input.InUse
@@ -333,11 +338,12 @@ func (h *ImageHandler) ListImages(ctx context.Context, input *ListImagesInput) (
images = []image.Summary{}
}
- return &handlerutil.Page[image.Summary]{
- Body: base.Paginated[image.Summary]{
- Success: true,
- Data: images,
- Pagination: handlerutil.PaginationResponse(paginationResp),
+ return &ListImagesOutput{
+ Body: image.ListResponse{
+ Success: true,
+ Data: images,
+ Pagination: handlerutil.PaginationResponse(paginationResp),
+ MaxImageUploadSize: h.settingsService.GetIntSetting(ctx, "maxImageUploadSize", 500),
},
}, nil
}
diff --git a/backend/internal/imageupdate/image_update.go b/backend/internal/imageupdate/image_update.go
index fe287244b..3dc0d72d6 100644
--- a/backend/internal/imageupdate/image_update.go
+++ b/backend/internal/imageupdate/image_update.go
@@ -10,7 +10,6 @@ import (
"fmt"
"log/slog"
"maps"
- "slices"
"strings"
"sync"
"time"
@@ -30,6 +29,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/event"
"github.com/getarcaneapp/arcane/backend/v2/internal/notification"
"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
+ dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"
activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ratelimit"
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"
@@ -739,11 +739,9 @@ func (s *ImageUpdateService) getAllImageRefsInternal(ctx context.Context, limit
return imageRefsFromSummariesInternal(imageList.Items, limit), nil
}
- excludedContainers := make(map[string]bool)
+ var excludedContainers map[string]bool
if s.settingsService != nil {
- for _, name := range utils.UniqueNonEmptyStrings(strings.Split(s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""), ",")) {
- excludedContainers[name] = true
- }
+ excludedContainers = dockerutil.ExcludedContainerNameSet(s.settingsService.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""))
}
return filterImageSummariesByContainerOptOutInternal(imageList.Items, containerList.Items, excludedContainers, limit), nil
@@ -780,9 +778,7 @@ func filterImageSummariesByContainerOptOutInternal(images []image.Summary, conta
eligibleByRef := make(map[string]bool)
for _, summary := range containers {
- eligible := !labels.IsUpdateDisabled(summary.Labels) && !slices.ContainsFunc(summary.Names, func(name string) bool {
- return excludedContainers[strings.TrimPrefix(name, "/")]
- })
+ eligible := !labels.IsUpdateDisabled(summary.Labels) && !dockerutil.ContainerNameExcluded(summary.Names, excludedContainers)
if imageID := strings.TrimSpace(summary.ImageID); imageID != "" {
eligibleByImageID[imageID] = eligibleByImageID[imageID] || eligible
diff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.go
index 47410e5b3..19eda88ed 100644
--- a/backend/internal/updater/service.go
+++ b/backend/internal/updater/service.go
@@ -1226,7 +1226,7 @@ func (s *UpdaterService) collectUsedImagesFromContainersInternal(ctx context.Con
continue
}
- if containerSummaryExcludedInternal(summary, excludedContainers) {
+ if dockerutil.ContainerNameExcluded(summary.Names, excludedContainers) {
s.loggerInternal().DebugContext(ctx, "collectUsedImagesFromContainers: skipping excluded container", "containerId", summary.ID, "names", summary.Names)
continue
}
@@ -1304,15 +1304,7 @@ func (s *UpdaterService) buildExcludedContainerSetInternal(ctx context.Context)
if s.deps.Settings == nil {
return nil
}
- names := utils.UniqueNonEmptyStrings(strings.Split(s.deps.Settings.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""), ","))
- if len(names) == 0 {
- return nil
- }
- excluded := make(map[string]bool, len(names))
- for _, name := range names {
- excluded[name] = true
- }
- return excluded
+ return dockerutil.ExcludedContainerNameSet(s.deps.Settings.GetStringSetting(ctx, "autoUpdateExcludedContainers", ""))
}
func (s *UpdaterService) collectUsedImagesFromProjectsInternal(ctx context.Context, out map[string]struct{}) error {
@@ -1384,15 +1376,3 @@ func addNormalizedImageUpdateRefInternal(ctx context.Context, out map[string]str
}
slog.Debug(logMessage, args...)
}
-
-func containerSummaryExcludedInternal(summary container.Summary, excludedContainers map[string]bool) bool {
- if len(excludedContainers) == 0 {
- return false
- }
- for _, name := range summary.Names {
- if excludedContainers[strings.TrimPrefix(name, "/")] {
- return true
- }
- }
- return false
-}
diff --git a/backend/pkg/dockerutil/container_names.go b/backend/pkg/dockerutil/container_names.go
index 0c344fb2d..55f99d555 100644
--- a/backend/pkg/dockerutil/container_names.go
+++ b/backend/pkg/dockerutil/container_names.go
@@ -2,6 +2,8 @@ package docker
import (
"strings"
+
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
)
// ContainerNameFromNames returns Docker's first container name without the
@@ -13,3 +15,31 @@ func ContainerNameFromNames(names []string) string {
return strings.TrimPrefix(names[0], "/")
}
+
+// ExcludedContainerNameSet parses a comma-separated exclusion setting into a
+// name lookup. Returns nil when the setting names no containers.
+func ExcludedContainerNameSet(raw string) map[string]bool {
+ names := utils.UniqueNonEmptyStrings(strings.Split(raw, ","))
+ if len(names) == 0 {
+ return nil
+ }
+ excluded := make(map[string]bool, len(names))
+ for _, name := range names {
+ excluded[name] = true
+ }
+ return excluded
+}
+
+// ContainerNameExcluded reports whether any of Docker's container names,
+// stripped of the leading slash, appears in the exclusion lookup.
+func ContainerNameExcluded(names []string, excluded map[string]bool) bool {
+ if len(excluded) == 0 {
+ return false
+ }
+ for _, name := range names {
+ if excluded[strings.TrimPrefix(name, "/")] {
+ return true
+ }
+ }
+ return false
+}
diff --git a/backend/pkg/dockerutil/container_names_test.go b/backend/pkg/dockerutil/container_names_test.go
index 2806ae641..7c312b490 100644
--- a/backend/pkg/dockerutil/container_names_test.go
+++ b/backend/pkg/dockerutil/container_names_test.go
@@ -45,3 +45,13 @@ func TestContainerNameFromNames(t *testing.T) {
})
}
}
+
+func TestExcludedContainerNames(t *testing.T) {
+ assert.Nil(t, ExcludedContainerNameSet(" , "))
+
+ excluded := ExcludedContainerNameSet(" app ,db,,app")
+ assert.Equal(t, map[string]bool{"app": true, "db": true}, excluded)
+ assert.True(t, ContainerNameExcluded([]string{"/other", "/db"}, excluded))
+ assert.False(t, ContainerNameExcluded([]string{"/other"}, excluded))
+ assert.False(t, ContainerNameExcluded([]string{"/app"}, nil))
+}
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index af8141546..3b24cfcd1 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -283,6 +283,7 @@
"auto_update_disabled_toast": "Auto-update disabled",
"auto_update_failed": "Failed to update auto-update setting",
"auto_update_controlled_by_label": "Controlled by Docker label",
+ "auto_update_status_unavailable": "Auto-update status is unavailable because this environment's agent does not report it. Update the agent to manage it here.",
"excluded_containers": "Excluded Containers",
"auto_heal_exclude_description": "Select containers to exclude from auto-heal monitoring.",
"auto_heal_max_restarts_label": "Max Restarts",
@@ -1830,6 +1831,8 @@
"templates_download": "Download",
"templates_use_now": "Use Now",
"templates_load_failed": "Failed to load template content",
+ "templates_load_forbidden": "The requested template cannot be loaded because you lack permission to read templates. You can still write the project yourself.",
+ "compose_optional_resource_load_failed": "{resource} could not be loaded: {message}",
"templates_download_failed": "Failed to download template",
"templates_create_template": "Create Template",
"templates_delete_template": "Delete Template",
@@ -3405,6 +3408,7 @@
"volume_backup_no_s3_destinations": "No S3 destinations are configured. Add one in Settings before creating an S3 backup.",
"volume_backup_s3_destination_required": "Select an S3 destination.",
"volume_backup_destination_unavailable": "The selected S3 destination is no longer available.",
+ "volume_backup_destination_read_only": "You lack permission to list S3 destinations, so this schedule keeps its configured destination. Local schedules can still be created.",
"volume_backup_status_succeeded": "Succeeded",
"volume_backup_trigger": "Trigger",
"volume_backup_remote_snapshot": "S3 snapshot",
diff --git a/frontend/src/lib/components/backup-policy-dialog.svelte b/frontend/src/lib/components/backup-policy-dialog.svelte
index 96b8e74df..c79915df4 100644
--- a/frontend/src/lib/components/backup-policy-dialog.svelte
+++ b/frontend/src/lib/components/backup-policy-dialog.svelte
@@ -9,6 +9,9 @@
import type { S3Destination } from '#lib/types/s3-destination.js';
import { s3DestinationService } from '#lib/services/s3-destination-service.js';
import { backupDestinationFromFlags, backupPolicyDestinationValues, backupPolicyUpdateFromPolicy } from '#lib/utils/backups.js';
+ import { extractApiErrorMessage } from '#lib/utils/api.js';
+ import { hasPermission } from '#lib/utils/auth.js';
+ import { GLOBAL_SCOPE } from '#lib/types/auth.js';
import { toast } from 'svelte-sonner';
import * as m from '#lib/paraglide/messages.js';
@@ -62,6 +65,11 @@
let deleting = $state(false);
let loadedDestinations = $state<S3Destination[]>([]);
let destinationsLoading = $state(false);
+ let destinationsLoadError = $state<string | null>(null);
+ // Destinations are a global resource. Without list access the dialog keeps a
+ // policy's configured destination read-only instead of requesting the list.
+ const canListDestinations = $derived(hasPermission('s3-destinations:list', GLOBAL_SCOPE));
+ const destinationsAccessible = $derived(destinations !== undefined || canListDestinations);
const initialPolicy = untrack(() => policies.find((item) => item.id === policyId));
let initialForm: PolicyForm;
if (initialPolicy) {
@@ -95,6 +103,8 @@
const destinationError = $derived.by(() => {
if (form.destination === 'local' || destinationsLoading) return null;
if (!form.s3DestinationId) return m.volume_backup_s3_destination_required();
+ // A destination that could not be enumerated is retained as configured.
+ if (!destinationsAccessible || destinationsLoadError) return null;
if (!destinations && !loadedDestinations.some((item) => item.id === form.s3DestinationId))
return m.volume_backup_destination_unavailable();
return null;
@@ -116,6 +126,7 @@
async function loadDestinations() {
destinationsLoading = true;
+ destinationsLoadError = null;
try {
const operationResult1 = await tryCatch(
(async () => {
@@ -123,9 +134,7 @@
})()
);
if (operationResult1.error !== null) {
- const error = operationResult1.error;
-
- toast.error(error instanceof Error ? error.message : m.s3_destinations_load_failed());
+ destinationsLoadError = extractApiErrorMessage(operationResult1.error);
}
} finally {
destinationsLoading = false;
@@ -133,7 +142,7 @@
}
onMount(() => {
- if (!destinations) void loadDestinations();
+ if (!destinations && canListDestinations) void loadDestinations();
});
function updateForm(values: Partial<BackupPolicyForm>) {
@@ -213,6 +222,8 @@
schedulePlaceholder={defaultSchedule}
{showStopContainers}
{destinationsLoading}
+ destinationReadOnly={!destinationsAccessible}
+ {destinationsLoadError}
onChange={updateForm}
/>
{#if afterFields}
diff --git a/frontend/src/lib/components/backup-policy-fields.svelte b/frontend/src/lib/components/backup-policy-fields.svelte
index c9954b76f..a619b2418 100644
--- a/frontend/src/lib/components/backup-policy-fields.svelte
+++ b/frontend/src/lib/components/backup-policy-fields.svelte
@@ -19,6 +19,8 @@
schedulePlaceholder,
showStopContainers = false,
destinationsLoading = false,
+ destinationReadOnly = false,
+ destinationsLoadError = null,
onChange
}: {
idPrefix: string;
@@ -32,11 +34,21 @@
schedulePlaceholder: string;
showStopContainers?: boolean;
destinationsLoading?: boolean;
+ /** Keeps the configured destination as-is when the user cannot list destinations. */
+ destinationReadOnly?: boolean;
+ destinationsLoadError?: string | null;
onChange: (values: Partial<BackupPolicyForm>) => void;
} = $props();
- const destinationOptions = $derived(backupDestinationOptions(destinations.length > 0, true));
- const s3Options = $derived(s3DestinationOptions(destinations));
+ const keepsConfiguredS3 = $derived(destinationReadOnly && form.destination !== 'local');
+ const destinationOptions = $derived(backupDestinationOptions(destinations.length > 0 || keepsConfiguredS3, true));
+ const s3Options = $derived.by(() => {
+ const options = s3DestinationOptions(destinations);
+ if (form.s3DestinationId && !options.some((item) => item.value === form.s3DestinationId)) {
+ options.push({ label: form.s3DestinationId, value: form.s3DestinationId, description: '' });
+ }
+ return options;
+ });
</script>
<div class="space-y-5">
@@ -85,7 +97,14 @@
label={m.backups_destination_label()}
description={m.volume_backup_destination_description()}
options={destinationOptions}
+ disabled={destinationReadOnly}
/>
+ {#if destinationReadOnly}
+ <p class="text-xs text-muted-foreground">{m.volume_backup_destination_read_only()}</p>
+ {/if}
+ {#if destinationsLoadError}
+ <p class="text-sm text-destructive">{m.s3_destinations_load_failed()}: {destinationsLoadError}</p>
+ {/if}
{#if form.destination !== 'local'}
<SelectWithLabel
id={`${idPrefix}-s3-destination`}
@@ -94,7 +113,7 @@
label={m.volume_backup_s3_destination_label()}
description={m.volume_backup_s3_destination_description()}
error={destinationError}
- disabled={destinationsLoading}
+ disabled={destinationsLoading || destinationReadOnly}
options={s3Options}
/>
{/if}
diff --git a/frontend/src/lib/components/compose-create-menu.svelte b/frontend/src/lib/components/compose-create-menu.svelte
index 4e18e65d6..68327c919 100644
--- a/frontend/src/lib/components/compose-create-menu.svelte
+++ b/frontend/src/lib/components/compose-create-menu.svelte
@@ -38,6 +38,8 @@
// Dropdown items.
itemsDisabled: boolean;
+ // Hide the template item when the user cannot list and read templates.
+ showUseTemplate?: boolean;
useTemplateLabel: string;
onUseTemplate: () => void;
convertLabel: string;
@@ -69,6 +71,7 @@
createLoadingLabel,
onCreate,
itemsDisabled,
+ showUseTemplate = true,
useTemplateLabel,
onUseTemplate,
convertLabel,
@@ -138,10 +141,12 @@
</DropdownMenu.Trigger>
<DropdownMenu.Content align="end" class={dropdownContentClass}>
<DropdownMenu.Group>
- <DropdownMenu.Item class={dropdownItemClass} disabled={itemsDisabled} onclick={onUseTemplate}>
- <TemplateIcon class="size-4" />
- {useTemplateLabel}
- </DropdownMenu.Item>
+ {#if showUseTemplate}
+ <DropdownMenu.Item class={dropdownItemClass} disabled={itemsDisabled} onclick={onUseTemplate}>
+ <TemplateIcon class="size-4" />
+ {useTemplateLabel}
+ </DropdownMenu.Item>
+ {/if}
<DropdownMenu.Item class={dropdownItemClass} onclick={onConvert}>
<TerminalIcon class="size-4" />
{convertLabel}
diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.ts
index 9c1c10779..363c6c69f 100644
--- a/frontend/src/lib/services/image-service.ts
+++ b/frontend/src/lib/services/image-service.ts
@@ -29,20 +29,22 @@ export type ImagePullResult = {
error?: string;
};
+/** Image list page plus the upload limit (MB) the environment enforces; absent on older agents. */
+export type ImagesPaginatedResponse = Paginated<ImageSummaryDto> & {
+ maxImageUploadSize?: number;
+};
+
class ImageService extends BaseAPIService {
private async resolveEnvironmentId(environmentId?: string): Promise<string> {
return environmentId ?? (await environmentStore.getCurrentEnvironmentId());
}
- async getImages(options?: SearchPaginationSortRequest): Promise<Paginated<ImageSummaryDto>> {
+ async getImages(options?: SearchPaginationSortRequest): Promise<ImagesPaginatedResponse> {
const envId = await this.resolveEnvironmentId();
return this.getImagesForEnvironment(envId, options);
}
- async getImagesForEnvironment(
- environmentId: string,
- options?: SearchPaginationSortRequest
- ): Promise<Paginated<ImageSummaryDto>> {
+ async getImagesForEnvironment(environmentId: string, options?: SearchPaginationSortRequest): Promise<ImagesPaginatedResponse> {
const params = transformPaginationParams(options);
const res = await this.api.get(`/environments/${environmentId}/images`, { params });
return res.data;
diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.ts
index bf2144cea..934fea9b0 100644
--- a/frontend/src/lib/types/docker.ts
+++ b/frontend/src/lib/types/docker.ts
@@ -182,6 +182,8 @@ export interface ContainerSummaryDto extends BaseContainer {
mounts: ContainerMounts[];
updateInfo?: ImageUpdateInfoDto;
redeployDisabled?: boolean;
+ /** Eligibility under the updater label and exclusion setting; absent on older agents. */
+ autoUpdateEnabled?: boolean;
hidden?: boolean;
resourceSample?: ContainerResourceSample | null;
}
@@ -309,6 +311,8 @@ export interface ContainerDetailsDto {
iconLightUrl?: string;
iconDarkUrl?: string;
redeployDisabled?: boolean;
+ /** Eligibility under the updater label and exclusion setting; absent on older agents. */
+ autoUpdateEnabled?: boolean;
}
export interface ContainerCommitRequest {
diff --git a/frontend/src/lib/utils/container-auto-update.ts b/frontend/src/lib/utils/container-auto-update.ts
index ee1fcb0d8..70e880771 100644
--- a/frontend/src/lib/utils/container-auto-update.ts
+++ b/frontend/src/lib/utils/container-auto-update.ts
@@ -1,12 +1,9 @@
/**
- * Auto-update exclusion helpers shared by the container detail page, the
- * environment jobs tab and the updates table. The backend stores exclusions as
- * a CSV of container *names* in `autoUpdateExcludedContainers`, and the Docker
- * label `com.getarcaneapp.arcane.updater=false` overrides that setting.
- *
- * Keyed on labels + a resolved name rather than a container DTO: the detail
- * page has `ContainerDetailsDto.name` while the tables have
- * `ContainerSummaryDto.names[]`.
+ * Auto-update exclusion helpers shared by the environment jobs tab, the
+ * container detail page and the updates table. The backend stores exclusions
+ * as a CSV of container *names* in `autoUpdateExcludedContainers`, and the
+ * Docker label `com.getarcaneapp.arcane.updater=false` overrides that setting.
+ * Container responses carry the resolved `autoUpdateEnabled` status.
*/
const AUTO_UPDATE_LABEL = 'com.getarcaneapp.arcane.updater';
@@ -33,11 +30,3 @@ export function parseExcludedContainerSet(csv?: string): Set<string> {
.filter(Boolean)
);
}
-
-/** True when the container is excluded from auto-updates, by label or by setting. */
-export function isAutoUpdateIgnored(name: string, labels: Record<string, string> | undefined, excludedCsv?: string): boolean {
- if (isAutoUpdateLabelDisabled(labels)) return true;
- const normalized = normalizeContainerName(name ?? '');
- if (!normalized) return false;
- return parseExcludedContainerSet(excludedCsv).has(normalized);
-}
diff --git a/frontend/src/lib/utils/template-load.ts b/frontend/src/lib/utils/template-load.ts
index 2130c20e5..afe6f8a13 100644
--- a/frontend/src/lib/utils/template-load.ts
+++ b/frontend/src/lib/utils/template-load.ts
@@ -2,6 +2,10 @@ import { tryCatch } from '#lib/utils/try-catch.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { templateService } from '#lib/services/template-service.js';
import { variableService } from '#lib/services/variable-service.js';
+import { extractApiErrorMessage } from '#lib/utils/api.js';
+import { userHasPermission } from '#lib/utils/auth.js';
+import type { User } from '#lib/types/auth.js';
+import type { Template, TemplateContentData } from '#lib/types/swarm.js';
import type { GlobalVariable } from '#lib/types/variable.js';
type QueryClientLike = {
@@ -10,82 +14,103 @@ type QueryClientLike = {
type ParentWithQueryClient = () => Promise<{
queryClient: unknown;
+ user?: User | null;
[key: string]: unknown;
}>;
+export type TemplateAuthoringResource = 'defaultTemplates' | 'templates' | 'globalVariables';
+
+/** An authorized optional request that failed; permission gaps never produce one. */
+export type TemplateAuthoringLoadError = { resource: TemplateAuthoringResource; message: string };
+
+export type TemplateAuthoringPermissions = {
+ canReadTemplates: boolean;
+ canListTemplates: boolean;
+ canReadVariables: boolean;
+};
+
+export type SelectedTemplateLoad = {
+ content: TemplateContentData | null;
+ /** Server error for an explicitly requested template; null when it loaded or was not requested. */
+ error: string | null;
+ /** True when the template was requested without `templates:read`, so no request was made. */
+ forbidden: boolean;
+};
+
export function globalVariablesToMap(globalVariables: GlobalVariable[] | null | undefined): Record<string, string> {
return Object.fromEntries((globalVariables ?? []).map((item) => [item.key, item.value]));
}
+const EMPTY_DEFAULT_TEMPLATES = { composeTemplate: '', envTemplate: '' };
+
+/**
+ * Loads compose-authoring resources that live behind global permissions. Each
+ * resource is fetched only when the user holds its permission; otherwise an
+ * empty value is returned without a request.
+ */
export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
- const { queryClient } = await parent();
+ const { queryClient, user } = await parent();
const client = queryClient as QueryClientLike;
+ const permissions: TemplateAuthoringPermissions = {
+ canReadTemplates: userHasPermission(user, 'templates:read'),
+ canListTemplates: userHasPermission(user, 'templates:list'),
+ canReadVariables: userHasPermission(user, 'variables:read')
+ };
+ const loadErrors: TemplateAuthoringLoadError[] = [];
- const [defaultTemplates, templates, globalVariables] = await Promise.all([
- tryCatch(
- client.query({
- queryKey: queryKeys.templates.defaults(),
- queryFn: () => templateService.getDefaultTemplates()
- })
- ).then((result) => {
- if (result.error !== null) {
- const err = result.error;
+ async function loadOptional<T>(resource: TemplateAuthoringResource, allowed: boolean, fallback: T, request: () => Promise<T>) {
+ if (!allowed) return fallback;
+ const result = await tryCatch(request());
+ if (result.error !== null) {
+ loadErrors.push({ resource, message: extractApiErrorMessage(result.error) });
+ return fallback;
+ }
+ return result.data;
+ }
- console.warn('Failed to load default templates:', err);
- return { composeTemplate: '', envTemplate: '' };
- } else {
- return result.data;
- }
- }),
- tryCatch(
+ const [defaultTemplates, templates, globalVariables] = await Promise.all([
+ loadOptional<{ composeTemplate: string; envTemplate: string }>(
+ 'defaultTemplates',
+ permissions.canReadTemplates,
+ EMPTY_DEFAULT_TEMPLATES,
+ () =>
+ client.query({
+ queryKey: queryKeys.templates.defaults(),
+ queryFn: () => templateService.getDefaultTemplates()
+ })
+ ),
+ loadOptional<Template[]>('templates', permissions.canListTemplates, [], () =>
client.query({
queryKey: queryKeys.templates.allTemplates(),
queryFn: () => templateService.getAllTemplates()
})
- ).then((result) => {
- if (result.error !== null) {
- const err = result.error;
-
- console.warn('Failed to load templates:', err);
- return [];
- } else {
- return result.data;
- }
- }),
- tryCatch(
+ ),
+ loadOptional<GlobalVariable[]>('globalVariables', permissions.canReadVariables, [], () =>
client.query({
queryKey: queryKeys.variables.list(),
queryFn: () => variableService.list()
})
- ).then((result) => {
- if (result.error !== null) {
- const err = result.error;
-
- console.warn('Failed to load global variables:', err);
- return [];
- } else {
- return result.data;
- }
- })
+ )
]);
- return { defaultTemplates, templates, globalVariables };
+ return { defaultTemplates, templates, globalVariables, permissions, loadErrors };
}
-export async function loadTemplateContent(client: QueryClientLike, templateId: string) {
- return tryCatch(
+/** Loads an explicitly requested template; without `templates:read` no request is sent. */
+export async function loadTemplateContent(
+ client: QueryClientLike,
+ templateId: string,
+ canRead: boolean
+): Promise<SelectedTemplateLoad> {
+ if (!canRead) return { content: null, error: null, forbidden: true };
+ const result = await tryCatch(
client.query({
queryKey: queryKeys.templates.content(templateId),
queryFn: () => templateService.getTemplateContent(templateId)
})
- ).then((result) => {
- if (result.error !== null) {
- const err = result.error;
-
- console.warn('Failed to load selected template:', err);
- return null;
- } else {
- return result.data;
- }
- });
+ );
+ if (result.error !== null) {
+ return { content: null, error: extractApiErrorMessage(result.error), forbidden: false };
+ }
+ return { content: result.data, error: null, forbidden: false };
}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
index 7719fab7a..7a2b89eda 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte
@@ -52,13 +52,14 @@
import { EditIcon, ImagesIcon, PauseIcon, PlayIcon, ProjectsIcon, UpdateIcon, ZapIcon } from '#lib/icons/index.js';
import { runContainerLifecycleAction, confirmAndUpdateContainer } from '#lib/utils/container-actions.js';
import { imageService } from '#lib/services/image-service.js';
- import { createQuery } from '@tanstack/svelte-query';
+ import { createQuery, useQueryClient } from '@tanstack/svelte-query';
import { queryKeys } from '#lib/query/query-keys.js';
import userStore from '#lib/stores/user-store.svelte.js';
- import { isAutoUpdateIgnored, isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
+ import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
import KillContainerDialog from '../components/kill-container-dialog.svelte';
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
let { data } = $props();
+ const queryClient = useQueryClient();
let container = $derived(data?.container as ContainerDetailsDto);
let stats = $state(null as ContainerStatsType | null);
@@ -66,13 +67,19 @@
let hasInitialStatsLoaded = $state(false);
let statsError = $state(false);
- // Auto-update: the Docker label controls the state when set (not toggleable via UI)
+ // Auto-update: the Docker label controls the state when set (not toggleable via UI).
+ // The status itself comes from the container response; older agents omit it.
const autoUpdateLabelControlled = $derived(isAutoUpdateLabelDisabled(container?.labels));
- let autoUpdateOverride = $state<boolean | null>(null);
- const autoUpdateEnabled = $derived(
- autoUpdateOverride ??
- !isAutoUpdateIgnored(container?.name ?? '', container?.labels, data?.settings?.autoUpdateExcludedContainers)
- );
+ const autoUpdateStatusAvailable = $derived(typeof container?.autoUpdateEnabled === 'boolean');
+ const autoUpdateEnabled = $derived(container?.autoUpdateEnabled === true);
+
+ async function handleAutoUpdateChanged() {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.containers.all }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.containers.detail(currentEnvId, container.id) })
+ ]);
+ await refreshAll();
+ }
const cleanContainerName = (name: string | undefined): string => {
if (!name) return m.common_not_found_title({ resource: m.containers() });
@@ -507,9 +514,8 @@
{primaryIpAddress}
{autoUpdateEnabled}
{autoUpdateLabelControlled}
- onAutoUpdateChange={(enabled) => {
- autoUpdateOverride = enabled;
- }}
+ {autoUpdateStatusAvailable}
+ onAutoUpdateChange={handleAutoUpdateChanged}
onViewPortMappings={showNetworkTab ? navigateToNetworkPortMappings : undefined}
onViewStorage={hasMounts ? () => onTabChange('storage') : undefined}
onViewNetworks={showNetworkTab ? () => onTabChange('network') : undefined}
diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.ts b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
index 8a4b37a04..cb31e5111 100644
--- a/frontend/src/routes/(app)/containers/[containerId]/+page.ts
+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.ts
@@ -2,81 +2,64 @@ import { tryCatch } from '#lib/utils/try-catch.js';
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
import { containerService } from '#lib/services/container-service.js';
-import { settingsService } from '#lib/services/settings-service.js';
import { projectService } from '#lib/services/project-service.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { queryKeys } from '#lib/query/query-keys.js';
+import { throwPageLoadError } from '#lib/utils/api.js';
export const load: PageLoad = async ({ params, parent }) => {
const { queryClient } = await parent();
const envId = await environmentStore.getCurrentEnvironmentId();
const containerId = params.containerId;
- const operationResult = await tryCatch(
- (async () => {
- const [container, settings] = await Promise.all([
- queryClient.query({
- queryKey: queryKeys.containers.detail(envId, containerId),
- queryFn: () => containerService.getContainerForEnvironment(envId, containerId)
- }),
- queryClient.query({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- })
- ]);
-
- if (!container) {
- throw error(404, 'Container not found');
- }
-
- let project = null;
- const composeProjectName = container.composeInfo?.projectName;
- if (composeProjectName) {
- const operationResult = await tryCatch(
- (async () => {
- const searchOptions = {
- search: composeProjectName,
- pagination: { page: 1, limit: 100 } // Ensure we don't miss projects beyond default page size
- };
- const projectsResult = await queryClient.query({
- queryKey: queryKeys.projects.list(envId, searchOptions),
- queryFn: () => projectService.getProjectsForEnvironment(envId, searchOptions)
- });
- const matched = projectsResult.data.find((p) => p.name === composeProjectName);
- if (matched) {
- return await queryClient.query({
- queryKey: queryKeys.projects.detail(envId, matched.id),
- queryFn: () => projectService.getProjectForEnvironment(envId, matched.id)
- });
- }
- return null;
- })()
- );
- if (operationResult.error !== null) {
- const err = operationResult.error;
+ const containerResult = await tryCatch(
+ queryClient.query({
+ queryKey: queryKeys.containers.detail(envId, containerId),
+ queryFn: () => containerService.getContainerForEnvironment(envId, containerId)
+ })
+ );
+ if (containerResult.error !== null) {
+ throwPageLoadError(containerResult.error, 'Failed to load container details');
+ }
+ const container = containerResult.data;
+ if (!container) {
+ error(404, 'Container not found');
+ }
- console.warn('Failed to load compose project:', err);
- } else {
- project = operationResult.data;
+ let project = null;
+ const composeProjectName = container.composeInfo?.projectName;
+ if (composeProjectName) {
+ const operationResult = await tryCatch(
+ (async () => {
+ const searchOptions = {
+ search: composeProjectName,
+ pagination: { page: 1, limit: 100 } // Ensure we don't miss projects beyond default page size
+ };
+ const projectsResult = await queryClient.query({
+ queryKey: queryKeys.projects.list(envId, searchOptions),
+ queryFn: () => projectService.getProjectsForEnvironment(envId, searchOptions)
+ });
+ const matched = projectsResult.data.find((p) => p.name === composeProjectName);
+ if (matched) {
+ return await queryClient.query({
+ queryKey: queryKeys.projects.detail(envId, matched.id),
+ queryFn: () => projectService.getProjectForEnvironment(envId, matched.id)
+ });
}
- }
-
- return {
- container,
- settings,
- project
- };
- })()
- );
- if (operationResult.error !== null) {
- const err: unknown = operationResult.error;
+ return null;
+ })()
+ );
+ if (operationResult.error !== null) {
+ const err = operationResult.error;
- console.error('Failed to load container:', err);
- if (typeof err === 'object' && err !== null && 'status' in err && (err as { status: number }).status === 404) {
- throw err;
+ console.warn('Failed to load compose project:', err);
+ } else {
+ project = operationResult.data;
}
- throw error(500, err instanceof Error ? err.message : 'Failed to load container details');
- } else {
- return operationResult.data;
}
+
+ return {
+ container,
+ project
+ };
};
diff --git a/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte b/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
index f93a8deed..24a8bd220 100644
--- a/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
+++ b/frontend/src/routes/(app)/containers/components/ContainerOverview.svelte
@@ -10,6 +10,7 @@
import { StartIcon, StopIcon, NetworksIcon, VolumesIcon, HealthIcon } from '#lib/icons/index.js';
import { containerService } from '#lib/services/container-service.js';
import { DetailMetaStrip, DetailSection, KeyValueCard, type DetailMetaItem } from '#lib/components/resource-detail/index.js';
+ import { extractApiErrorMessage } from '#lib/utils/api.js';
import { toast } from 'svelte-sonner';
interface Props {
@@ -17,7 +18,9 @@
primaryIpAddress: string;
autoUpdateEnabled?: boolean;
autoUpdateLabelControlled?: boolean;
- onAutoUpdateChange?: (enabled: boolean) => void;
+ /** False when the agent did not report a status; the toggle is then disabled. */
+ autoUpdateStatusAvailable?: boolean;
+ onAutoUpdateChange?: (enabled: boolean) => void | Promise<void>;
onViewPortMappings?: () => void;
onViewStorage?: () => void;
onViewNetworks?: () => void;
@@ -28,6 +31,7 @@
primaryIpAddress,
autoUpdateEnabled = true,
autoUpdateLabelControlled = false,
+ autoUpdateStatusAvailable = true,
onAutoUpdateChange,
onViewPortMappings,
onViewStorage,
@@ -39,15 +43,18 @@
async function handleAutoUpdateToggle(checked: boolean) {
autoUpdateToggling = true;
try {
- const operationResult = await tryCatch(
- (async () => {
- await containerService.setAutoUpdate(container.id, checked);
- onAutoUpdateChange?.(checked);
- toast.success(checked ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
- })()
- );
+ const operationResult = await tryCatch(containerService.setAutoUpdate(container.id, checked));
if (operationResult.error !== null) {
- toast.error(m.auto_update_failed());
+ toast.error(m.auto_update_failed(), { description: extractApiErrorMessage(operationResult.error) });
+ return;
+ }
+ toast.success(checked ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
+ // The setting is saved at this point; a failed reload must not read as a failed toggle.
+ const refreshResult = await tryCatch(Promise.resolve(onAutoUpdateChange?.(checked)));
+ if (refreshResult.error !== null) {
+ toast.error(m.common_refresh_failed({ resource: m.resource_container() }), {
+ description: extractApiErrorMessage(refreshResult.error)
+ });
}
} finally {
autoUpdateToggling = false;
@@ -160,14 +167,22 @@
<div class="flex items-center gap-3">
<Switch
checked={autoUpdateEnabled}
- disabled={autoUpdateToggling || autoUpdateLabelControlled}
+ disabled={autoUpdateToggling || autoUpdateLabelControlled || !autoUpdateStatusAvailable}
onCheckedChange={handleAutoUpdateToggle}
/>
<span class="text-sm font-medium text-foreground">
- {autoUpdateEnabled ? m.common_enabled() : m.common_disabled()}
+ {#if !autoUpdateStatusAvailable}
+ {m.common_na()}
+ {:else if autoUpdateEnabled}
+ {m.common_enabled()}
+ {:else}
+ {m.common_disabled()}
+ {/if}
</span>
</div>
- {#if autoUpdateLabelControlled}
+ {#if !autoUpdateStatusAvailable}
+ <span class="text-xs text-muted-foreground">{m.auto_update_status_unavailable()}</span>
+ {:else if autoUpdateLabelControlled}
<span class="text-xs text-muted-foreground">{m.auto_update_controlled_by_label()}</span>
{/if}
</KeyValueCard>
diff --git a/frontend/src/routes/(app)/images/+page.svelte b/frontend/src/routes/(app)/images/+page.svelte
index 2cd315b3d..160a8c381 100644
--- a/frontend/src/routes/(app)/images/+page.svelte
+++ b/frontend/src/routes/(app)/images/+page.svelte
@@ -48,9 +48,9 @@
totalImageSize: 0
};
- const maxUploadSizeMB = $derived(
- parseInt(String((data.envId === envId ? data.settings?.maxImageUploadSize : undefined) || '500'), 10)
- );
+ // The upload limit rides along with the image list; older agents omit it and
+ // the server still enforces the real limit.
+ const DEFAULT_MAX_UPLOAD_SIZE_MB = 500;
const imagesQuery = createQuery(() => {
const queryEnvId = envId;
@@ -77,6 +77,7 @@
};
});
const images = $derived(imagesQuery.data?.value ?? data.images);
+ const maxUploadSizeMB = $derived(images?.maxImageUploadSize ?? DEFAULT_MAX_UPLOAD_SIZE_MB);
const resourcesReady = $derived(imagesQuery.data?.envId === envId);
diff --git a/frontend/src/routes/(app)/images/+page.ts b/frontend/src/routes/(app)/images/+page.ts
index 66a52f20c..e62dd7eea 100644
--- a/frontend/src/routes/(app)/images/+page.ts
+++ b/frontend/src/routes/(app)/images/+page.ts
@@ -1,7 +1,6 @@
import { featureStore } from '#lib/stores/features.store.svelte.js';
import { tryCatch } from '#lib/utils/try-catch.js';
import { imageService } from '#lib/services/image-service.js';
-import { settingsService } from '#lib/services/settings-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import { resolveListPageLoadContext } from '#lib/utils/tables.js';
import { throwPageLoadError } from '#lib/utils/api.js';
@@ -18,7 +17,6 @@ export const load: PageLoad = async ({ parent }) => {
});
await featureStore.load(envId);
let images;
- let settings;
let imageUsageCounts;
const operationResult = await tryCatch(
(async () =>
@@ -27,10 +25,6 @@ export const load: PageLoad = async ({ parent }) => {
queryKey: queryKeys.images.list(envId, imageRequestOptions),
queryFn: () => imageService.getImagesForEnvironment(envId, imageRequestOptions)
}),
- queryClient.query({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
- }),
queryClient.query({
queryKey: queryKeys.images.usageCounts(envId),
queryFn: () => imageService.getImageUsageCountsForEnvironment(envId)
@@ -42,8 +36,8 @@ export const load: PageLoad = async ({ parent }) => {
throwPageLoadError(err, 'Failed to load images');
} else {
- [images, settings, imageUsageCounts] = operationResult.data;
+ [images, imageUsageCounts] = operationResult.data;
}
- return { envId, images, imageRequestOptions, settings, imageUsageCounts };
+ return { envId, images, imageRequestOptions, imageUsageCounts };
};
diff --git a/frontend/src/routes/(app)/projects/new/+page.svelte b/frontend/src/routes/(app)/projects/new/+page.svelte
index d6dab2cb1..ce5bd3789 100644
--- a/frontend/src/routes/(app)/projects/new/+page.svelte
+++ b/frontend/src/routes/(app)/projects/new/+page.svelte
@@ -25,7 +25,9 @@
import { Switch } from '#lib/components/ui/switch/index.js';
import DockerRunConverterDialog from '#lib/components/compose/docker-run-converter-dialog.svelte';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
- import { globalVariablesToMap } from '#lib/utils/template-load.js';
+ import { globalVariablesToMap, type TemplateAuthoringResource } from '#lib/utils/template-load.js';
+ import * as Alert from '#lib/components/ui/alert/index.js';
+ import { AlertIcon } from '#lib/icons/index.js';
import type { ProjectTag } from '#lib/types/swarm.js';
import ProjectTagEditor from '#lib/components/project-tag-editor.svelte';
import { createQuery } from '@tanstack/svelte-query';
@@ -120,6 +122,20 @@
});
const globalVariableMap = $derived(globalVariablesToMap(data.globalVariables));
+ const canUseTemplates = $derived(data.templatePermissions.canListTemplates && data.templatePermissions.canReadTemplates);
+ const resourceLabels: Record<TemplateAuthoringResource, () => string> = {
+ defaultTemplates: m.templates_defaults_title,
+ templates: m.templates_title,
+ globalVariables: m.variables_title
+ };
+ const templateLoadNotices = $derived.by(() => {
+ const notices: string[] = data.templateLoadErrors.map((item) =>
+ m.compose_optional_resource_load_failed({ resource: resourceLabels[item.resource](), message: item.message })
+ );
+ if (data.selectedTemplateForbidden) notices.push(m.templates_load_forbidden());
+ if (data.selectedTemplateError) notices.push(`${m.templates_load_failed()}: ${data.selectedTemplateError}`);
+ return notices;
+ });
const newProjectWorkspaceEntries = $derived(workspaceDraft.entries);
const newProjectWorkspaceLeadingRows = [
{ key: 'compose', label: 'compose.yaml', iconClass: 'text-blue-500', locked: true },
@@ -348,6 +364,7 @@
createLoadingLabel={m.common_action_creating()}
onCreate={() => handleSubmit()}
itemsDisabled={createMenuBusy}
+ showUseTemplate={canUseTemplates}
useTemplateLabel={m.common_use_template()}
onUseTemplate={() => {
// fallow-ignore-next-line code-duplication -- shared ComposeCreateMenu wiring with swarm stack create; labels/handlers are page-specific
@@ -379,6 +396,17 @@
<ProjectTagEditor bind:tags={newProjectTags} availableTags={availableProjectTags} canEdit={!ui.saving} class="mt-2" />
</div>
+ {#if templateLoadNotices.length > 0}
+ <Alert.Root variant="warning" class="py-2 [&>svg]:top-2">
+ <AlertIcon class="size-4" />
+ <Alert.Description class="text-xs">
+ {#each templateLoadNotices as notice (notice)}
+ <p>{notice}</p>
+ {/each}
+ </Alert.Description>
+ </Alert.Root>
+ {/if}
+
<div class="flex shrink-0 items-center justify-end gap-2">
<label
for="new-project-layout-mode-toggle"
diff --git a/frontend/src/routes/(app)/projects/new/+page.ts b/frontend/src/routes/(app)/projects/new/+page.ts
index b48a7f0dd..056cc42da 100644
--- a/frontend/src/routes/(app)/projects/new/+page.ts
+++ b/frontend/src/routes/(app)/projects/new/+page.ts
@@ -20,20 +20,28 @@ export const load: PageLoad = async ({ url, parent }) => {
const sourceContainerIds = url.searchParams.get('fromContainers')?.split(',').filter(Boolean) ?? [];
const sourceEnvironmentId = url.searchParams.get('fromEnv') || undefined;
- const [{ defaultTemplates, templates: allTemplates, globalVariables }, generated] = await Promise.all([
+ const [{ defaultTemplates, templates: allTemplates, globalVariables, permissions, loadErrors }, generated] = await Promise.all([
loadTemplateAuthoringData(parent),
sourceContainerIds.length ? generateFromContainers(sourceContainerIds, sourceEnvironmentId) : null
]);
const selectedTemplate = templateId
- ? await loadTemplateContent(queryClient as Parameters<typeof loadTemplateContent>[0], templateId)
+ ? await loadTemplateContent(
+ queryClient as Parameters<typeof loadTemplateContent>[0],
+ templateId,
+ permissions.canReadTemplates
+ )
: null;
return {
composeTemplates: allTemplates,
- envTemplate: generated ? '' : selectedTemplate?.envContent || defaultTemplates.envTemplate,
- defaultTemplate: generated?.composeContent || selectedTemplate?.content || defaultTemplates.composeTemplate,
- selectedTemplate: selectedTemplate?.template || null,
+ envTemplate: generated ? '' : selectedTemplate?.content?.envContent || defaultTemplates.envTemplate,
+ defaultTemplate: generated?.composeContent || selectedTemplate?.content?.content || defaultTemplates.composeTemplate,
+ selectedTemplate: selectedTemplate?.content?.template || null,
+ selectedTemplateError: selectedTemplate?.error ?? null,
+ selectedTemplateForbidden: selectedTemplate?.forbidden ?? false,
+ templatePermissions: permissions,
+ templateLoadErrors: loadErrors,
sourceContainerIds,
sourceEnvironmentId,
sourceContainerName: generated?.name ?? '',
diff --git a/frontend/src/routes/(app)/updates/+page.svelte b/frontend/src/routes/(app)/updates/+page.svelte
index 3a2011bda..609785588 100644
--- a/frontend/src/routes/(app)/updates/+page.svelte
+++ b/frontend/src/routes/(app)/updates/+page.svelte
@@ -1,5 +1,5 @@
<script lang="ts">
- import { createMutation, createQuery, keepPreviousData } from '@tanstack/svelte-query';
+ import { createMutation, createQuery, keepPreviousData, useQueryClient } from '@tanstack/svelte-query';
import { untrack } from 'svelte';
import { m } from '#lib/paraglide/messages.js';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
@@ -12,7 +12,6 @@
import { imageService } from '#lib/services/image-service.js';
import { containerService, type ContainerListRequestOptions } from '#lib/services/container-service.js';
import { projectService } from '#lib/services/project-service.js';
- import { settingsService } from '#lib/services/settings-service.js';
import { confirmAndApplyAllUpdates } from '#lib/utils/update-actions.js';
import type { ContainersPaginatedResponse } from '#lib/services/container-service.js';
import type { Paginated, SearchPaginationSortRequest } from '#lib/types/shared.js';
@@ -23,6 +22,7 @@
import { useUrlTab } from '#lib/hooks/use-url-tab.svelte.js';
let { data } = $props();
+ const queryClient = useQueryClient();
const initialContainers = untrack(() => data.containers as ContainersPaginatedResponse);
const initialProjects = untrack(() => data.projects as Paginated<Project>);
@@ -90,14 +90,15 @@
(envId === data.envId ? initialProjects : emptyProjects)
);
- const settingsQuery = createQuery(() => ({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId),
- initialData: envId === data.envId ? data.settings : undefined,
- refetchOnMount: false
- }));
-
- const excludedContainers = $derived(settingsQuery.data?.autoUpdateExcludedContainers ?? '');
+ // Ignoring a container changes its `autoUpdateEnabled` on every container
+ // response, so cached lists and details for this environment go stale.
+ async function invalidateContainerQueries() {
+ containerSnapshot = null;
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.containers.all }),
+ queryClient.invalidateQueries({ queryKey: ['container', envId] })
+ ]);
+ }
const checkUpdatesMutation = createMutation(() => ({
mutationKey: ['updates', 'check-all', envId],
@@ -223,9 +224,8 @@
{#key `${envId}-containers`}
<ContainerUpdatesTable
{containers}
- {excludedContainers}
bind:requestOptions={containerRequestOptions}
- onIgnoreChanged={() => settingsQuery.refetch()}
+ onIgnoreChanged={invalidateContainerQueries}
onRefreshData={async (options) => {
containerRequestOptions = ensureStandaloneContainerUpdatesFilter(options);
const next = await containerService.getContainersForEnvironment(envId, containerRequestOptions);
diff --git a/frontend/src/routes/(app)/updates/+page.ts b/frontend/src/routes/(app)/updates/+page.ts
index 6606c4d28..534b270cd 100644
--- a/frontend/src/routes/(app)/updates/+page.ts
+++ b/frontend/src/routes/(app)/updates/+page.ts
@@ -1,7 +1,6 @@
import { tryCatch } from '#lib/utils/try-catch.js';
import { containerService, type ContainerListRequestOptions } from '#lib/services/container-service.js';
import { projectService } from '#lib/services/project-service.js';
-import { settingsService } from '#lib/services/settings-service.js';
import { queryKeys } from '#lib/query/query-keys.js';
import type { SearchPaginationSortRequest } from '#lib/types/shared.js';
import { resolveInitialTableRequest } from '#lib/utils/tables.js';
@@ -30,7 +29,6 @@ export const load: PageLoad = async ({ parent }) => {
let containers;
let projects;
- let settings;
const operationResult = await tryCatch(
(async () =>
Promise.all([
@@ -41,11 +39,6 @@ export const load: PageLoad = async ({ parent }) => {
queryClient.query({
queryKey: queryKeys.projects.list(envId, projectRequestOptions),
queryFn: () => projectService.getProjectsForEnvironment(envId, projectRequestOptions)
- }),
- // `autoUpdateExcludedContainers` drives the ignored state on container rows.
- queryClient.query({
- queryKey: queryKeys.settings.byEnvironment(envId),
- queryFn: () => settingsService.getSettingsForEnvironmentMerged(envId)
})
]))()
);
@@ -54,14 +47,13 @@ export const load: PageLoad = async ({ parent }) => {
throwPageLoadError(err, 'Failed to load updates');
} else {
- [containers, projects, settings] = operationResult.data;
+ [containers, projects] = operationResult.data;
}
return {
envId,
containers,
projects,
- settings,
containerRequestOptions,
projectRequestOptions
};
diff --git a/frontend/src/routes/(app)/updates/container-updates-table.svelte b/frontend/src/routes/(app)/updates/container-updates-table.svelte
index 5861f24cc..e9e145c56 100644
--- a/frontend/src/routes/(app)/updates/container-updates-table.svelte
+++ b/frontend/src/routes/(app)/updates/container-updates-table.svelte
@@ -25,7 +25,8 @@
import IfPermitted from '#lib/components/if-permitted.svelte';
import { hasPermission } from '#lib/utils/auth.js';
import { confirmAndUpdateContainer } from '#lib/utils/container-actions.js';
- import { isAutoUpdateIgnored, isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
+ import { isAutoUpdateLabelDisabled } from '#lib/utils/container-auto-update.js';
+ import { extractApiErrorMessage } from '#lib/utils/api.js';
import { bulkConfirmAndRun } from '#lib/utils/bulk-actions.js';
import { throwOnContainerUpdateFailure } from '#lib/utils/update-actions.js';
import { formatImageUpdateCheckedAt, formatImageUpdateValue } from '#lib/utils/image-updates.js';
@@ -41,6 +42,9 @@
checkedAt: string;
ignored: boolean;
labelControlled: boolean;
+ /** False when the agent omitted `autoUpdateEnabled`; ignoring is then unavailable. */
+ statusAvailable: boolean;
+ ignoreTitle: string;
updateInfo?: ImageUpdateInfoDto;
container: ContainerSummaryDto;
};
@@ -48,19 +52,11 @@
interface Props {
containers: ContainersPaginatedResponse;
requestOptions: SearchPaginationSortRequest;
- /** `autoUpdateExcludedContainers` setting — a CSV of ignored container names. */
- excludedContainers?: string;
onRefreshData: (options: ContainerListRequestOptions) => Promise<ContainersPaginatedResponse>;
onIgnoreChanged?: () => Promise<unknown> | unknown;
}
- let {
- containers = $bindable(),
- requestOptions = $bindable(),
- excludedContainers,
- onRefreshData,
- onIgnoreChanged
- }: Props = $props();
+ let { containers = $bindable(), requestOptions = $bindable(), onRefreshData, onIgnoreChanged }: Props = $props();
let selectedIds = $state<string[]>([]);
let mobileFieldVisibility = $state<MobileFieldVisibility>({});
@@ -70,6 +66,14 @@
function mapContainerRow(container: ContainerSummaryDto): ContainerUpdateRow {
const name = getContainerDisplayName(container);
+ const labelControlled = isAutoUpdateLabelDisabled(container.labels);
+ const statusAvailable = typeof container.autoUpdateEnabled === 'boolean';
+ let ignoreTitle = m.updates_ignore_description();
+ if (!statusAvailable) {
+ ignoreTitle = m.auto_update_status_unavailable();
+ } else if (labelControlled) {
+ ignoreTitle = m.auto_update_controlled_by_label();
+ }
return {
id: container.id,
containerId: container.id,
@@ -78,8 +82,10 @@
currentValue: formatImageUpdateValue(container.updateInfo, 'current'),
latestValue: formatImageUpdateValue(container.updateInfo, 'latest'),
checkedAt: container.updateInfo?.checkTime ?? '',
- ignored: isAutoUpdateIgnored(name, container.labels, excludedContainers),
- labelControlled: isAutoUpdateLabelDisabled(container.labels),
+ ignored: container.autoUpdateEnabled === false,
+ labelControlled,
+ statusAvailable,
+ ignoreTitle,
updateInfo: container.updateInfo,
container
};
@@ -125,23 +131,28 @@
// Ignoring writes to the shared `autoUpdateExcludedContainers` setting, so the
// row stays listed (the list is driven by `updateInfo.hasUpdate`) and only its
- // rendering changes once the settings query reports the new value back.
+ // rendering changes once the refreshed rows report the new status back.
async function handleToggleIgnore(item: ContainerUpdateRow) {
const enable = item.ignored;
ignoringContainerIds = { ...ignoringContainerIds, [item.containerId]: true };
try {
- const operationResult = await tryCatch(
+ const operationResult = await tryCatch(containerService.setAutoUpdate(item.containerId, enable));
+ if (operationResult.error !== null) {
+ toast.error(m.auto_update_failed(), { description: extractApiErrorMessage(operationResult.error) });
+ return;
+ }
+ toast.success(enable ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
+ // The setting is saved at this point; a failed reload must not read as a failed toggle.
+ const refreshResult = await tryCatch(
(async () => {
- await containerService.setAutoUpdate(item.containerId, enable);
- toast.success(enable ? m.auto_update_enabled_toast() : m.auto_update_disabled_toast());
await onIgnoreChanged?.();
+ await refreshRows();
})()
);
- if (operationResult.error !== null) {
- const error = operationResult.error;
-
- console.error('Auto-update toggle failed:', error);
- toast.error(m.auto_update_failed());
+ if (refreshResult.error !== null) {
+ toast.error(m.common_refresh_failed({ resource: m.updates() }), {
+ description: extractApiErrorMessage(refreshResult.error)
+ });
}
} finally {
ignoringContainerIds = { ...ignoringContainerIds, [item.containerId]: false };
@@ -222,8 +233,8 @@
<DropdownMenu.Item
onclick={() => handleToggleIgnore(item)}
- disabled={item.labelControlled || !!ignoringContainerIds[item.containerId]}
- title={item.labelControlled ? m.auto_update_controlled_by_label() : m.updates_ignore_description()}
+ disabled={item.labelControlled || !item.statusAvailable || !!ignoringContainerIds[item.containerId]}
+ title={item.ignoreTitle}
>
{#if ignoringContainerIds[item.containerId]}
<Spinner class="size-4" />
diff --git a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
index 735d8b9bc..677b691e5 100644
--- a/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
+++ b/frontend/src/routes/(app)/volumes/components/volume-backup-table.svelte
@@ -44,6 +44,7 @@
import BackupFilePicker from '#lib/components/backup-file-picker.svelte';
import { environmentStore } from '#lib/stores/environment.store.svelte.js';
import { hasPermission } from '#lib/utils/auth.js';
+ import { GLOBAL_SCOPE } from '#lib/types/auth.js';
import IfPermitted from '#lib/components/if-permitted.svelte';
import { activityToastOptions, extractActivityId } from '#lib/utils/activity-toast.js';
import BackupPolicyDialog from '#lib/components/backup-policy-dialog.svelte';
@@ -81,6 +82,8 @@
const canReadActivities = $derived(hasPermission('activities:read', currentEnvId));
const canBackupVolume = $derived(hasPermission('volumes:backup', currentEnvId));
const canDeleteBackup = $derived(hasPermission('volumes:backup', currentEnvId));
+ // Destinations are a global resource; an environment-scoped backup grant does not cover them.
+ const canListS3Destinations = $derived(hasPermission('s3-destinations:list', GLOBAL_SCOPE));
let backupsPaginated = $state<VolumeBackupListResponse>({
data: [],
@@ -94,6 +97,7 @@
let backupWarnings = $state<string[]>([]);
let backupPolicies = $state<VolumeBackupPolicy[]>([]);
let s3Destinations = $state<S3Destination[]>([]);
+ let s3DestinationsError = $state<string | null>(null);
let showBackupPolicy = $state(false);
let policySession = $state(0);
let editingBackupPolicyId = $state<string | undefined>();
@@ -403,14 +407,17 @@
const name = volumeName;
const [collection, destinations] = await Promise.all([
volumeBackupService.getPolicies(name),
- canBackupVolume
- ? tryCatch(s3DestinationService.listAll()).then((result) => (result.error ? [] : result.data))
- : Promise.resolve([]),
+ canBackupVolume && canListS3Destinations ? tryCatch(s3DestinationService.listAll()) : Promise.resolve(null),
loadData(requestOptions)
]);
if (!active || environmentId !== currentEnvId || name !== volumeName) return;
backupPolicies = collection.policies;
- s3Destinations = destinations;
+ if (destinations === null) return;
+ if (destinations.error !== null) {
+ s3DestinationsError = extractApiErrorMessage(destinations.error);
+ } else {
+ s3Destinations = destinations.data;
+ }
});
const columns = [
@@ -553,27 +560,29 @@
size="sm"
icon={AddIcon}
/>
- <DropdownMenu.Root>
- <DropdownMenu.Trigger
- class={cn(arcaneButtonVariants({ tone: 'outline-primary', size: 'icon' }), 'size-8 rounded-md')}
- aria-label={m.common_open_menu()}
- disabled={creating || backupActivity.activeIds.length > 0}
- >
- <ArrowDownIcon class="size-4" />
- </DropdownMenu.Trigger>
- <DropdownMenu.Content align="end" class="w-64">
- <DropdownMenu.Label>{m.backups_destination_label()}</DropdownMenu.Label>
- <DropdownMenu.Item onclick={() => handleCreate({ destination: 'local' })}>
- {m.local()}
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => openS3DestinationDialog('s3')}>
- {m.backups_destination_s3()}
- </DropdownMenu.Item>
- <DropdownMenu.Item onclick={() => openS3DestinationDialog('local_s3')}>
- {m.backups_destination_local_s3()}
- </DropdownMenu.Item>
- </DropdownMenu.Content>
- </DropdownMenu.Root>
+ {#if canListS3Destinations}
+ <DropdownMenu.Root>
+ <DropdownMenu.Trigger
+ class={cn(arcaneButtonVariants({ tone: 'outline-primary', size: 'icon' }), 'size-8 rounded-md')}
+ aria-label={m.common_open_menu()}
+ disabled={creating || backupActivity.activeIds.length > 0}
+ >
+ <ArrowDownIcon class="size-4" />
+ </DropdownMenu.Trigger>
+ <DropdownMenu.Content align="end" class="w-64">
+ <DropdownMenu.Label>{m.backups_destination_label()}</DropdownMenu.Label>
+ <DropdownMenu.Item onclick={() => handleCreate({ destination: 'local' })}>
+ {m.local()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => openS3DestinationDialog('s3')}>
+ {m.backups_destination_s3()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Item onclick={() => openS3DestinationDialog('local_s3')}>
+ {m.backups_destination_local_s3()}
+ </DropdownMenu.Item>
+ </DropdownMenu.Content>
+ </DropdownMenu.Root>
+ {/if}
</ButtonGroup.Root>
</div>
{/if}
@@ -686,6 +695,15 @@
</Alert.Root>
{/if}
+ {#if s3DestinationsError}
+ <Alert.Root variant="destructive" class="py-2 [&>svg]:top-2">
+ <AlertIcon class="size-4" />
+ <Alert.Description class="text-xs">
+ {m.s3_destinations_load_failed()}: {s3DestinationsError}
+ </Alert.Description>
+ </Alert.Root>
+ {/if}
+
<ArcaneTable
persistKey="arcane-volume-backup-table"
items={backupsPaginated}
@@ -810,6 +828,7 @@
enabledDescription={m.volume_backup_policy_enabled_description()}
defaultSchedule="0 0 2 * * *"
showStopContainers
+ destinations={canListS3Destinations && !s3DestinationsError ? s3Destinations : undefined}
updatePolicies={async (policies) => (await volumeBackupService.updatePolicies(volumeName, policies)).policies}
messages={{
saved: m.volume_backup_policy_saved(),
diff --git a/tests/spec/rbac.spec.ts b/tests/spec/rbac.spec.ts
index 3113138ac..7c004ce49 100644
--- a/tests/spec/rbac.spec.ts
+++ b/tests/spec/rbac.spec.ts
@@ -5,8 +5,10 @@ import {
test,
type BrowserContext,
type Page,
- type Request
+ type Request,
+ type Response
} from '../fixtures/test.fixture';
+import { TEST_COMPOSE_YAML } from '../setup/project.data';
import { removeApiResource, readApiData } from '../utils/fetch.util';
import { openRowActionsMenu } from '../utils/table-actions.util';
@@ -303,7 +305,12 @@ async function editUserThroughUI(page: Page, user: TestUser) {
expect(updated.displayName).toBe('Scoped Browser User Updated');
}
-async function loginAs(page: Page, username: string, password: string, expectedPath: string) {
+async function loginAs(
+ page: Page,
+ username: string,
+ password: string,
+ expectedPath: string | RegExp
+) {
await page.goto('/login');
await page.getByLabel('Username').fill(username);
await page.getByLabel('Password').fill(password);
@@ -311,6 +318,64 @@ async function loginAs(page: Page, username: string, password: string, expectedP
await expect(page).toHaveURL(expectedPath, { timeout: 15_000 });
}
+type TestContainer = { id: string; names: string[]; labels?: Record<string, string> };
+
+/** Records forbidden API responses so pages can prove they issue no unauthorized optional requests. */
+function collectForbiddenResponses(page: Page) {
+ const forbidden: string[] = [];
+ const record = (response: Response) => {
+ if (response.status() === 403) {
+ forbidden.push(`${response.request().method()} ${new URL(response.url()).pathname}`);
+ }
+ };
+ page.on('response', record);
+ return { forbidden, stop: () => page.off('response', record) };
+}
+
+async function createEnvironmentAdminViaApi(page: Page, username: string, password: string) {
+ const user = await readApiData<TestUser>(
+ await page.request.post('/api/users', {
+ data: { username, password, displayName: 'Environment Admin Browser User' }
+ }),
+ `Create user ${username}`
+ );
+ await readApiData<unknown[]>(
+ await page.request.put(`/api/users/${user.id}/role-assignments`, {
+ data: { assignments: [{ roleId: 'role_admin', environmentId: '0' }] }
+ }),
+ `Assign the Admin role on the local environment to ${username}`
+ );
+ return user;
+}
+
+async function toggleAutoUpdateThroughUI(
+ page: Page,
+ containerId: string,
+ expectEnabledAfter: boolean
+) {
+ const card = page
+ .locator('div')
+ .filter({ hasText: /^Auto-Update/ })
+ .filter({ has: page.getByRole('switch') })
+ .last();
+ const responsePromise = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'PUT' &&
+ new URL(response.url()).pathname ===
+ `/api/environments/0/containers/${containerId}/auto-update`
+ );
+ await card.getByRole('switch').click();
+ await readApiData<{ message: string }>(await responsePromise, 'Toggle container auto-update');
+ await expect(
+ card.getByText(expectEnabledAfter ? 'Enabled' : 'Disabled', { exact: true })
+ ).toBeVisible();
+ const details = await readApiData<{ autoUpdateEnabled?: boolean }>(
+ await page.request.get(`/api/environments/0/containers/${containerId}`),
+ 'Read container details'
+ );
+ expect(details.autoUpdateEnabled).toBe(expectEnabledAfter);
+}
+
async function deleteUserThroughUI(page: Page, user: TestUser) {
await page.goto('/settings/users');
await page.getByPlaceholder('Search…').fill(user.username);
@@ -359,6 +424,8 @@ test('administers scoped identities and enforces their browser access immediatel
const remoteEnvironmentName = `E2E Scoped Remote ${suffix}`;
const username = `e2e-scoped-${suffix}`;
const noAccessUsername = `e2e-no-access-${suffix}`;
+ const environmentAdminUsername = `e2e-env-admin-${suffix}`;
+ const environmentAdminVolumeName = `e2e-env-admin-volume-${suffix}`;
const password = 'E2e-RBAC-user-123!';
let localRole: TestRole | null = null;
@@ -367,8 +434,11 @@ test('administers scoped identities and enforces their browser access immediatel
let remoteEnvironment: TestEnvironment | null = null;
let restrictedUser: TestUser | null = null;
let noAccessUser: TestUser | null = null;
+ let environmentAdminUser: TestUser | null = null;
+ let environmentAdminVolumeCreated = false;
let restrictedContext: BrowserContext | null = null;
let noAccessContext: BrowserContext | null = null;
+ let environmentAdminContext: BrowserContext | null = null;
try {
const localEnvironment = await readApiData<TestEnvironment>(
@@ -486,14 +556,6 @@ test('administers scoped identities and enforces their browser access immediatel
})
});
});
- await restrictedContext.route(`**/api/environments/${remoteID}/settings`, async (route) => {
- await route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify({ success: true, data: {} })
- });
- });
-
const restrictedPage = await restrictedContext.newPage();
restrictedPage.setDefaultTimeout(10_000);
const restrictedErrors = installPageErrorCollector(restrictedPage);
@@ -599,6 +661,172 @@ test('administers scoped identities and enforces their browser access immediatel
).toEqual([]);
}
+ // An Admin role granted only on the local environment must reach every
+ // environment-scoped page without the global settings, templates,
+ // variables, or S3 destination requests those pages used to make.
+ environmentAdminUser = await createEnvironmentAdminViaApi(
+ page,
+ environmentAdminUsername,
+ password
+ );
+ const [targetContainer] = (
+ await readApiData<TestContainer[]>(
+ await page.request.get('/api/environments/0/containers?start=0&limit=50'),
+ 'List local containers'
+ )
+ ).filter((container) => !container.labels?.['com.getarcaneapp.arcane.updater']);
+ expect(targetContainer, 'a container without an updater label is required').toBeTruthy();
+ await readApiData<unknown>(
+ await page.request.post('/api/environments/0/volumes', {
+ data: { name: environmentAdminVolumeName, driver: 'local' }
+ }),
+ `Create volume ${environmentAdminVolumeName}`
+ );
+ environmentAdminVolumeCreated = true;
+
+ environmentAdminContext = await browser.newContext({
+ baseURL,
+ storageState: { cookies: [], origins: [] }
+ });
+ const environmentAdminPage = await environmentAdminContext.newPage();
+ environmentAdminPage.setDefaultTimeout(10_000);
+ const environmentAdminErrors = installPageErrorCollector(environmentAdminPage);
+ const forbiddenResponses = collectForbiddenResponses(environmentAdminPage);
+ try {
+ await loginAs(environmentAdminPage, environmentAdminUsername, password, /^(?!.*\/login).*$/);
+
+ const environmentAdmin = await readApiData<TestUser>(
+ await environmentAdminPage.request.get('/api/auth/me'),
+ 'Get environment admin current user'
+ );
+ expect(environmentAdmin.permissionsByEnv['0']).toEqual(
+ expect.arrayContaining([
+ 'containers:autoupdate',
+ 'images:list',
+ 'projects:create',
+ 'volumes:backup'
+ ])
+ );
+ expect(environmentAdmin.permissionsByEnv.global ?? []).toEqual([]);
+
+ for (const path of [
+ '/api/environments/0/settings',
+ '/api/templates/all',
+ '/api/templates/default',
+ '/api/variables',
+ '/api/backups/s3/options',
+ `/api/environments/${remoteID}/containers`
+ ]) {
+ const rejected = await environmentAdminPage.request.get(path);
+ expect(rejected.status(), `${path} must stay forbidden`).toBe(403);
+ }
+ forbiddenResponses.forbidden.length = 0;
+
+ await environmentAdminPage.goto(`/containers/${targetContainer.id}`);
+ await expect(
+ environmentAdminPage.getByRole('tab', { name: 'Overview', exact: true })
+ ).toBeVisible();
+ await expect(environmentAdminPage.getByText('Auto-Update', { exact: true })).toBeVisible();
+ const initialDetails = await readApiData<{ autoUpdateEnabled?: boolean }>(
+ await environmentAdminPage.request.get(
+ `/api/environments/0/containers/${targetContainer.id}`
+ ),
+ 'Read initial container details'
+ );
+ expect(typeof initialDetails.autoUpdateEnabled).toBe('boolean');
+ await toggleAutoUpdateThroughUI(
+ environmentAdminPage,
+ targetContainer.id,
+ !initialDetails.autoUpdateEnabled
+ );
+ await toggleAutoUpdateThroughUI(
+ environmentAdminPage,
+ targetContainer.id,
+ initialDetails.autoUpdateEnabled === true
+ );
+
+ await environmentAdminPage.goto('/images');
+ await expect(
+ environmentAdminPage.getByRole('heading', { name: 'Images', exact: true })
+ ).toBeVisible();
+ const imageListResponse = await environmentAdminPage.request.get(
+ '/api/environments/0/images?start=0&limit=1'
+ );
+ expect(imageListResponse.ok()).toBe(true);
+ const imageListBody = await imageListResponse.json();
+ expect(Array.isArray(imageListBody.data)).toBe(true);
+ expect(typeof imageListBody.maxImageUploadSize).toBe('number');
+
+ await environmentAdminPage.goto('/updates');
+ await expect(
+ environmentAdminPage.getByRole('heading', { name: 'Updates', exact: true })
+ ).toBeVisible();
+
+ const optionalRequests: string[] = [];
+ const recordOptionalRequest = (request: Request) => {
+ const pathname = new URL(request.url()).pathname;
+ if (pathname.startsWith('/api/templates') || pathname.startsWith('/api/variables')) {
+ optionalRequests.push(`${request.method()} ${pathname}`);
+ }
+ };
+ environmentAdminPage.on('request', recordOptionalRequest);
+ await environmentAdminPage.goto('/projects/new?templateId=missing-template');
+ await expect(
+ environmentAdminPage.getByText('Docker Compose File', { exact: true })
+ ).toBeVisible();
+ await expect(
+ environmentAdminPage.getByText(
+ /cannot be loaded because you lack permission to read templates/
+ )
+ ).toBeVisible();
+ // Without default templates the editor starts empty, which hides the
+ // create button until valid compose content is entered.
+ const composeEditor = environmentAdminPage
+ .locator('.cm-editor')
+ .filter({ visible: true })
+ .first();
+ const composeContent = composeEditor.locator('.cm-content').first();
+ await expect(composeContent).toBeVisible();
+ await composeContent.click({ position: { x: 10, y: 10 } });
+ await composeContent.press('ControlOrMeta+A');
+ await environmentAdminPage.keyboard.insertText(TEST_COMPOSE_YAML);
+ await expect(
+ environmentAdminPage.getByRole('button', { name: 'Create Project', exact: true })
+ ).toBeVisible();
+ environmentAdminPage.off('request', recordOptionalRequest);
+ expect(optionalRequests).toEqual([]);
+
+ await environmentAdminPage.goto(
+ `/volumes/${encodeURIComponent(environmentAdminVolumeName)}?tab=backups`
+ );
+ await expect(
+ environmentAdminPage.getByRole('button', { name: 'Add schedule', exact: true })
+ ).toBeVisible();
+ await expect(
+ environmentAdminPage.getByRole('button', { name: 'Create Backup', exact: true })
+ ).toBeVisible();
+ await environmentAdminPage.getByRole('button', { name: 'Add schedule', exact: true }).click();
+ const policyDialog = environmentAdminPage.getByRole('dialog');
+ await expect(policyDialog).toBeVisible();
+ await expect(policyDialog.getByRole('button', { name: 'Save', exact: true })).toBeEnabled();
+ await policyDialog.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(policyDialog).toBeHidden();
+
+ expect(
+ forbiddenResponses.forbidden,
+ 'environment admin pages must not issue forbidden requests'
+ ).toEqual([]);
+ } finally {
+ forbiddenResponses.stop();
+ environmentAdminErrors.stop();
+ expect(
+ environmentAdminErrors.errors,
+ `Environment admin page errors:\n${formatPageErrors(environmentAdminErrors.errors)}`
+ ).toEqual([]);
+ }
+
+ await environmentAdminContext.close();
+ environmentAdminContext = null;
await restrictedContext.close();
restrictedContext = null;
await noAccessContext.close();
@@ -613,6 +841,7 @@ test('administers scoped identities and enforces their browser access immediatel
} finally {
await restrictedContext?.close();
await noAccessContext?.close();
+ await environmentAdminContext?.close();
if (restrictedUser) {
await removeApiResource(page, `/api/users/${restrictedUser.id}`);
@@ -620,6 +849,16 @@ test('administers scoped identities and enforces their browser access immediatel
if (noAccessUser) {
await removeApiResource(page, `/api/users/${noAccessUser.id}`);
}
+ if (environmentAdminUser) {
+ await page.request.delete(`/api/users/${environmentAdminUser.id}`).catch(() => undefined);
+ }
+ if (environmentAdminVolumeCreated) {
+ await page.request
+ .delete(
+ `/api/environments/0/volumes/${encodeURIComponent(environmentAdminVolumeName)}?force=true`
+ )
+ .catch(() => undefined);
+ }
for (const role of [clonedRole, localRole, remoteRole]) {
if (role) {
await removeApiResource(page, `/api/roles/${role.id}`);
diff --git a/tests/spec/updates.spec.ts b/tests/spec/updates.spec.ts
index b7da9fa33..f983aabd7 100644
--- a/tests/spec/updates.spec.ts
+++ b/tests/spec/updates.spec.ts
@@ -19,8 +19,8 @@ const CONTAINERS = [
ignored: false
},
{
- // Listed in `autoUpdateExcludedContainers`: automatic runs skip it, but a
- // user may still update it explicitly (#4123).
+ // Excluded from auto-update (`autoUpdateEnabled: false`): automatic runs
+ // skip it, but a user may still update it explicitly (#4123).
id: 'update-row-c',
name: 'updates-gamma',
image: 'public.ecr.aws/docker/library/nginx:1.27',
@@ -38,6 +38,7 @@ function containerWithUpdate(container: (typeof CONTAINERS)[number]) {
command: 'sleep',
created: 1_700_000_000,
labels: {},
+ autoUpdateEnabled: !container.ignored,
state: 'running',
status: 'Up 2 hours',
ports: [],
@@ -115,21 +116,6 @@ async function stubProjectWithTagUpdate(page: Page) {
});
}
-/** Marks the ignored fixture as excluded in the setting that drives the "Ignored" badge. */
-async function stubExcludedContainersSetting(page: Page) {
- const excluded = CONTAINERS.filter((container) => container.ignored)
- .map((container) => container.name)
- .join(',');
- await page.route(/\/api\/environments\/0\/settings$/, async (route) => {
- const response = await route.fetch();
- const settings = ((await response.json()) as { key: string; value: string }[]).filter(
- (setting) => setting.key !== 'autoUpdateExcludedContainers'
- );
- settings.push({ key: 'autoUpdateExcludedContainers', value: excluded });
- await route.fulfill({ response, json: settings });
- });
-}
-
/** Serves the update-pending containers so the tab always has selectable rows; returns the number of list fetches so far. */
async function stubContainersWithUpdates(page: Page) {
const fetches = { count: 0 };
@@ -265,7 +251,6 @@ test.describe('Updates Page Actions', () => {
test('applies updates to the selected container rows, including an ignored one', async ({
page
}) => {
- await stubExcludedContainersSetting(page);
const listFetches = await stubContainersWithUpdates(page);
const requested = await stubContainerUpdates(page, {});
@@ -292,7 +277,6 @@ test.describe('Updates Page Actions', () => {
});
test('does not count skipped or failed container updates as updated', async ({ page }) => {
- await stubExcludedContainersSetting(page);
await stubContainersWithUpdates(page);
const [alpha, beta] = CONTAINERS;
const requested = await stubContainerUpdates(page, {
@@ -315,7 +299,6 @@ test.describe('Updates Page Actions', () => {
});
test('row update reports a skipped reason or the server error and recovers', async ({ page }) => {
- await stubExcludedContainersSetting(page);
const listFetches = await stubContainersWithUpdates(page);
const outcomes: Record<string, ContainerUpdateOutcome> = {
[IGNORED_CONTAINER.id]: { kind: 'skipped', reason: 'immutable image reference' }
diff --git a/types/container/container.go b/types/container/container.go
index 2b1210fb4..d8597cb09 100644
--- a/types/container/container.go
+++ b/types/container/container.go
@@ -919,6 +919,13 @@ type Summary struct {
// Required: false
RedeployDisabled bool `json:"redeployDisabled,omitempty"`
+ // AutoUpdateEnabled reports whether the container is eligible for auto-update
+ // under its updater label and the excluded-containers setting. It does not
+ // reflect whether the auto-update scheduler itself is enabled.
+ //
+ // Required: true
+ AutoUpdateEnabled bool `json:"autoUpdateEnabled"`
+
// Hidden indicates whether the container is hidden from lists and dashboard counts.
//
// Required: false
@@ -1051,6 +1058,13 @@ type Details struct {
// Required: false
RedeployDisabled bool `json:"redeployDisabled,omitempty"`
+ // AutoUpdateEnabled reports whether the container is eligible for auto-update
+ // under its updater label and the excluded-containers setting. It does not
+ // reflect whether the auto-update scheduler itself is enabled.
+ //
+ // Required: true
+ AutoUpdateEnabled bool `json:"autoUpdateEnabled"`
+
// ActivityID is the background activity that tracked the action returning these details.
//
// Required: false
diff --git a/types/image/image.go b/types/image/image.go
index bf90c2820..8f86e60ad 100644
--- a/types/image/image.go
+++ b/types/image/image.go
@@ -6,11 +6,25 @@ import (
"strings"
"time"
+ "github.com/getarcaneapp/arcane/types/v2/base"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
"github.com/getarcaneapp/arcane/types/v2/vulnerability"
"github.com/moby/moby/api/types/image"
)
+// ListResponse is the paginated image list together with the upload limit the
+// environment enforces, so list consumers need no settings access.
+type ListResponse struct {
+ Success bool `json:"success" doc:"Whether the request was successful"`
+ Data []Summary `json:"data" doc:"Array of items for the current page"`
+ Pagination base.PaginationResponse `json:"pagination" doc:"Pagination metadata"`
+
+ // MaxImageUploadSize is the maximum image archive upload size in MB.
+ //
+ // Required: true
+ MaxImageUploadSize int `json:"maxImageUploadSize" doc:"Maximum image archive upload size in MB"`
+}
+
type UpdateInfo struct {
// CheckTime is the time when the update check was performed.
//