Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: add explicit env backup switch with warning for project backup (#3937)
Kyle Mendell9ba395d5272e
diff --git a/backend/internal/gitops/backup.go b/backend/internal/gitops/backup.goindex f7c356967..08e4e405e 100644--- a/backend/internal/gitops/backup.go+++ b/backend/internal/gitops/backup.go@@ -149,7 +149,7 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, txif err := s.projectService.EnsureProjectPathUnderRoot(ctx, project, false); err != nil {return nil, err}- composeFile, composeFiles, err := s.backupComposeFilesInternal(ctx, project)+ composeFile, _, err := s.backupComposeFilesInternal(ctx, project)if err != nil {return nil, common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "projectId"))}@@ -157,12 +157,6 @@ func (s *GitOpsSyncService) prepareBackupCreateInternal(ctx context.Context, txif err != nil {return nil, common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "backupPaths"))}- if len(paths) == 0 {- paths = composeFiles- }- if !backupSelectionCoversInternal(paths, composeFile) {- return nil, common.Classify(common.ErrValidation, errors.WithDetails(errors.New("the backup selection must include the compose file "+composeFile), "field", "backupPaths"))- }config := &backupCreateConfigInternal{project: project, directory: directory, paths: paths, composeFile: composeFile, backupOnSave: true}if req.BackupOnSave != nil {config.backupOnSave = *req.BackupOnSave@@ -229,22 +223,11 @@ func (s *GitOpsSyncService) applyModeUpdatesInternal(ctx context.Context, currenupdates["backup_conflict"] = falseupdates["backup_failure_reason"] = nil}- if len(req.BackupPaths) > 0 {+ if req.BackupPaths != nil {paths, err := normalizeBackupPathsInternal(req.BackupPaths)if err != nil {return common.Classify(common.ErrValidation, errors.WithDetails(err, "field", "backupPaths"))}- composeFile := strings.TrimPrefix(strings.TrimPrefix(current.ComposePath, current.BackupDirectory), "/")- if current.ProjectID != nil {- if project, found, lookupErr := s.lookupProjectByIDInternal(ctx, *current.ProjectID); lookupErr == nil && found {- if resolved, _, resolveErr := s.backupComposeFilesInternal(ctx, project); resolveErr == nil {- composeFile = resolved- }- }- }- if !backupSelectionCoversInternal(paths, composeFile) {- return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("the backup selection must include the compose file "+composeFile), "field", "backupPaths"))- }updates["backup_paths"] = database.StringSlice(paths)}if req.BackupOnSave != nil {@@ -687,14 +670,16 @@ func (s *GitOpsSyncService) backupComposeFilesInternal(ctx context.Context, proj// buildBackupSnapshotInternal reads the selected project files, retrying when they change mid-read.func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, sync *projectpkg.GitOpsSync, project *projectpkg.Project) (*backupSnapshotInternal, error) {- paths := []string(sync.BackupPaths)- if len(paths) == 0 {- return nil, errors.WrapIf(git.ErrSelectionInvalid, "no files are selected for backup")- }- primary, _, err := s.backupComposeFilesInternal(ctx, project)+ _, composeFiles, err := s.backupComposeFilesInternal(ctx, project)if err != nil {return nil, errors.WrapIf(git.ErrSelectionInvalid, err.Error())}+ paths := slices.Clone([]string(sync.BackupPaths))+ for _, composeFile := range composeFiles {+ if !backupSelectionCoversInternal(paths, composeFile) {+ paths = append(paths, composeFile)+ }+ }maxFiles, maxTotalSize, _ := s.getEffectiveSyncLimits(ctx, sync)options := git.CollectOptions{MaxFiles: maxFiles,@@ -714,9 +699,6 @@ func (s *GitOpsSyncService) buildBackupSnapshotInternal(ctx context.Context, synfor _, file := range files {snapshot.hashes[file.Path] = hashBackupContentInternal(file.Content)}- if _, ok := snapshot.hashes[primary]; !ok {- return nil, errors.WrapIff(git.ErrSelectionInvalid, "compose file %s is not included in the backup selection", primary)- }stable := truefor _, file := range files {diff --git a/backend/internal/gitops/backup_test.go b/backend/internal/gitops/backup_test.goindex 0779a3ff3..af2f46a3c 100644--- a/backend/internal/gitops/backup_test.go+++ b/backend/internal/gitops/backup_test.go@@ -313,8 +313,8 @@ func TestGitOpsBackup_EnvFilesOnlyIncludedWhenListedExplicitly(t *testing.T) {paths []stringwantEnvFile bool}{- {name: "directory selection skips env files", paths: []string{"compose.yaml", "config"}, wantEnvFile: false},- {name: "explicit env file is included", paths: []string{"compose.yaml", "config", ".env"}, wantEnvFile: true},+ {name: "directory selection skips env files", paths: []string{"config"}, wantEnvFile: false},+ {name: "explicit env file is included", paths: []string{"config", ".env"}, wantEnvFile: true},}for _, test := range tests {t.Run(test.name, func(t *testing.T) {@@ -480,11 +480,6 @@ func TestGitOpsBackup_CreateValidation(t *testing.T) {request: gitops.CreateSyncRequest{Name: "nested", BackupDirectory: "backups/demo/nested"},wantErr: common.ErrConflict,},- {- name: "selection missing the compose file",- request: gitops.CreateSyncRequest{BackupPaths: []string{"config"}},- wantErr: common.ErrValidation,- },{name: "deployment-only directory sync",request: gitops.CreateSyncRequest{SyncDirectory: &syncDirectory},diff --git a/backend/internal/gitops/handler.go b/backend/internal/gitops/handler.goindex dc6b8be65..e474bbc7f 100644--- a/backend/internal/gitops/handler.go+++ b/backend/internal/gitops/handler.go@@ -129,10 +129,10 @@ func RegisterGitOpsSyncs(api huma.API, syncService *GitOpsSyncService) {handlerutil.RegisterSecured(api, handlerutil.Operation("performGitOpsSync", "POST", syncPath+"/sync", "Perform a GitOps sync", "Manually trigger a sync operation", "GitOps Syncs"), authz.PermGitOpsSync, h.PerformSync)handlerutil.RegisterSecured(api, handlerutil.Operation("getGitOpsSyncStatus", "GET", syncPath+"/status", "Get GitOps sync status", "Get the current status of a GitOps sync", "GitOps Syncs"), authz.PermGitOpsRead, h.GetStatus)handlerutil.RegisterSecured(api, handlerutil.Operation("browseGitOpsSyncFiles", "GET", syncPath+"/files", "Browse GitOps sync files", "Browse files in the synced repository", "GitOps Syncs"), authz.PermGitOpsRead, h.BrowseFiles)- handlerutil.RegisterSecured(api, handlerutil.Operation("previewGitOpsBackup", "GET", syncPath+"/backup/preview", "Preview a Git backup", "Show the files the next backup would commit and any conflicts", "GitOps Syncs"), authz.PermGitOpsRead, h.PreviewBackup)- handlerutil.RegisterSecured(api, handlerutil.Operation("listGitOpsBackupHistory", "GET", syncPath+"/backup/history", "List Git backup history", "List repository revisions that changed the backup", "GitOps Syncs"), authz.PermGitOpsRead, h.BackupHistory)- handlerutil.RegisterSecured(api, handlerutil.Operation("getGitOpsBackupRevision", "GET", syncPath+"/backup/history/{commit}", "Get a Git backup revision", "Get one revision with per-file diffs", "GitOps Syncs"), authz.PermGitOpsRead, h.BackupRevision)- handlerutil.RegisterSecured(api, handlerutil.Operation("resolveGitOpsBackupConflict", "POST", syncPath+"/backup/resolve", "Resolve a Git backup conflict", "Resolve a backup that needs attention", "GitOps Syncs"), authz.PermGitOpsSync, h.ResolveBackupConflict)+ handlerutil.RegisterSecured(api, handlerutil.Operation("previewGitOpsBackup", "GET", syncPath+"/backup/preview", "Preview a Git backup", "Show the files the next backup would commit and any conflicts", "GitOps Syncs"), authz.PermGitOpsBackup, h.PreviewBackup)+ handlerutil.RegisterSecured(api, handlerutil.Operation("listGitOpsBackupHistory", "GET", syncPath+"/backup/history", "List Git backup history", "List repository revisions that changed the backup", "GitOps Syncs"), authz.PermGitOpsBackup, h.BackupHistory)+ handlerutil.RegisterSecured(api, handlerutil.Operation("getGitOpsBackupRevision", "GET", syncPath+"/backup/history/{commit}", "Get a Git backup revision", "Get one revision with per-file diffs", "GitOps Syncs"), authz.PermGitOpsBackup, h.BackupRevision)+ handlerutil.RegisterSecured(api, handlerutil.Operation("resolveGitOpsBackupConflict", "POST", syncPath+"/backup/resolve", "Resolve a Git backup conflict", "Resolve a backup that needs attention", "GitOps Syncs"), authz.PermGitOpsBackup, h.ResolveBackupConflict)}// requireLifecyclePermissionInternal rejects callers lacking gitops:lifecycle@@ -154,6 +154,28 @@ func requireLifecyclePermissionInternal(ctx context.Context, environmentID strinreturn huma.Error403Forbidden("configuring a pre-deploy lifecycle hook requires the " + authz.PermGitOpsLifecycle + " permission")}+// requireBackupPermissionInternal rejects callers lacking gitops:backup for+// the target environment when the operation touches a backup-mode sync.+func requireBackupPermissionInternal(ctx context.Context, environmentID string, backup bool) error {+ if !backup {+ return nil+ }+ if ps, _ := middleware.PermissionsFromContext(ctx); ps.Allows(authz.PermGitOpsBackup, environmentID) {+ return nil+ }+ return huma.Error403Forbidden("backing a project up to Git requires the " + authz.PermGitOpsBackup + " permission")+}++// requireBackupSyncPermissionInternal loads the sync and applies requireBackupPermissionInternal when it is a backup.+func (h *GitOpsSyncHandler) requireBackupSyncPermissionInternal(ctx context.Context, environmentID, syncID string) error {+ sync, err := h.syncService.GetSyncByID(ctx, environmentID, syncID)+ if err != nil {+ apiErr := common.ToAPIError(err)+ return huma.NewError(apiErr.HTTPStatus(), "Failed to retrieve GitOps sync")+ }+ return requireBackupPermissionInternal(ctx, environmentID, sync.IsBackup())+}+// ============================================================================// Handler Methods// ============================================================================@@ -187,6 +209,9 @@ func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSif err := requireLifecyclePermissionInternal(ctx, input.EnvironmentID, input.Body.HasPreDeployConfig()); err != nil {return nil, err}+ if err := requireBackupPermissionInternal(ctx, input.EnvironmentID, input.Body.Mode == gitops.SyncModeBackup); err != nil {+ return nil, err+ }actor := handlerutil.CurrentActor(ctx)@@ -250,6 +275,9 @@ func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSif err := requireLifecyclePermissionInternal(ctx, input.EnvironmentID, input.Body.HasPreDeployConfig()); err != nil {return nil, err}+ if err := h.requireBackupSyncPermissionInternal(ctx, input.EnvironmentID, input.SyncID); err != nil {+ return nil, err+ }actor := handlerutil.CurrentActor(ctx)@@ -273,6 +301,9 @@ func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsS// DeleteSync deletes a GitOps sync by ID.func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSyncInput) (*handlerutil.Out[base.MessageResponse], error) {+ if err := h.requireBackupSyncPermissionInternal(ctx, input.EnvironmentID, input.SyncID); err != nil {+ return nil, err+ }actor := handlerutil.CurrentActor(ctx)if err := h.syncService.DeleteSync(ctx, input.EnvironmentID, input.SyncID, actor); err != nil {@@ -292,6 +323,9 @@ func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsS// PerformSync manually triggers a sync operation.func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncInput) (*handlerutil.Out[gitops.SyncResult], error) {+ if err := h.requireBackupSyncPermissionInternal(ctx, input.EnvironmentID, input.SyncID); err != nil {+ return nil, err+ }actor := handlerutil.CurrentActor(ctx)result, err := h.syncService.PerformSync(ctx, input.EnvironmentID, input.SyncID, actor)diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.goindex 460edbe61..53575b91c 100644--- a/backend/pkg/authz/catalog.go+++ b/backend/pkg/authz/catalog.go@@ -200,6 +200,7 @@ var permissionCatalog = []PermissionCatalogResource{{"delete", PermGitOpsDelete, "Delete", ""},{"sync", PermGitOpsSync, "Trigger sync", ""},{"lifecycle", PermGitOpsLifecycle, "Configure pre-deploy hooks", "Create or modify a sync's pre-deploy lifecycle hook, which runs an arbitrary container with host bind mounts and env on every sync"},+ {"backup", PermGitOpsBackup, "Back up to Git", "View a project's Git backup preview and history, and manage the backup together with the matching sync permission (create, update, sync, delete)"},}},{"webhooks", "Webhooks", PermissionScopeEnv, []PermissionCatalogAction{{"list", PermWebhooksList, "List", ""},diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.goindex 6a4ad6ee5..7f222d529 100644--- a/backend/pkg/authz/permissions.go+++ b/backend/pkg/authz/permissions.go@@ -200,6 +200,12 @@ const (// permissions (e.g. the built-in Editor role) does not by itself grant the// ability to author hooks; seeded only into the Admin built-in role.PermGitOpsLifecycle = "gitops:lifecycle"+ // PermGitOpsBackup gates the "Back up to Git" feature. Backup-only routes+ // (preview, history, resolve) require it alone; the shared sync routes+ // require it in addition to the matching gitops:* permission when the sync+ // is a backup. Backups push project files (optionally the .env) to a+ // repository, so holding the broader gitops:* permissions alone is not enough.+ PermGitOpsBackup = "gitops:backup"PermWebhooksList = "webhooks:list"PermWebhooksCreate = "webhooks:create"@@ -331,7 +337,7 @@ func BuiltInEditorPermissions() []string {PermVolumesList, PermVolumesRead, PermVolumesCreate, PermVolumesRename, PermVolumesDelete, PermVolumesPrune, PermVolumesUpload, PermVolumesBackup,PermNetworksList, PermNetworksRead, PermNetworksCreate, PermNetworksDelete, PermNetworksPrune, PermNetworksConnect, PermNetworksDisconnect,PermSwarmRead, PermSwarmSpec, PermSwarmNodes, PermSwarmServices, PermSwarmServicesLogs, PermSwarmStacks, PermSwarmConfigs, PermSwarmSecrets,- PermGitOpsList, PermGitOpsRead, PermGitOpsCreate, PermGitOpsUpdate, PermGitOpsDelete, PermGitOpsSync,+ PermGitOpsList, PermGitOpsRead, PermGitOpsCreate, PermGitOpsUpdate, PermGitOpsDelete, PermGitOpsSync, PermGitOpsBackup,PermWebhooksList, PermWebhooksCreate, PermWebhooksUpdate, PermWebhooksDelete,PermJobsManage, PermNotificationsManage, PermDashboardRead,PermSystemRead, PermSystemPrune,diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex b7938c9b5..8a3cc9dcb 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -3620,7 +3620,9 @@"included_files": "Included files","included_files_description": "The compose file is always included.","environment_file": "Environment file",- "environment_file_warning": "Environment files often contain secrets. Their contents will be stored in the repository history.",+ "environment_file_warning": "Environment files often contain secrets. Their contents will be stored in the repository history. This is usually not recommended.",+ "include_environment_file": "Include environment file",+ "include_environment_file_description": "Commit the project's .env file with the backup.","automatic_backup": "Automatic backup","automatic_backup_description": "Check for changes on a schedule.","back_up_on_save": "Back up on save",diff --git a/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelteindex db0ae82da..76b2032f3 100644--- a/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte+++ b/frontend/src/lib/components/dialogs/gitops-sync-dialog.svelte@@ -86,6 +86,7 @@// editable section and never submit its fields; the backend enforces the same// rule as defense-in-depth.let canManageLifecycle = $derived(hasPermission('gitops:lifecycle', environmentId));+ let canBackup = $derived(hasPermission('gitops:backup', environmentId));// Whether the sync being edited already has a hook configured. Used to flag// its presence to users who can't manage it and to lock the directory-sync@@ -111,6 +112,8 @@return value === 'swarm_stack' ? 'swarm_stack' : 'project';}+ const envFileName = '.env';+const formSchema = z.object({mode: z.enum(['deploy', 'backup']).default('deploy'),@@ -121,6 +124,7 @@composePath: z.string().default(''),backupDirectory: z.string().default(''),backupPaths: z.array(z.string()).default([]),+ includeEnvFile: z.boolean().default(false),backupOnSave: z.boolean().default(true),syncDirectory: z.boolean().default(false),pullImageAfterSync: z.boolean().default(false),@@ -207,6 +211,7 @@composePath: syncToEdit?.composePath ?? defaultComposePath,backupDirectory: syncToEdit?.backupDirectory ?? '',backupPaths: syncToEdit?.backupPaths ?? [],+ includeEnvFile: syncToEdit?.backupPaths?.includes(envFileName) ?? false,backupOnSave: syncToEdit?.backupOnSave ?? true,syncDirectory: syncToEdit?.syncDirectory ?? false,pullImageAfterSync: syncToEdit?.pullImageAfterSync ?? false,@@ -304,10 +309,11 @@const selectedMode = $derived<GitOpsSyncMode>(inputs.mode.value as GitOpsSyncMode);const isBackupMode = $derived(selectedMode === 'backup');- const directionOptions = [+ const allDirectionOptions = [{ value: 'deploy', label: m.pull(), description: m.deploy_from_git_description() },{ value: 'backup', label: m.push(), description: m.back_up_to_git_description() }] satisfies { value: GitOpsSyncMode; label: string; description: string }[];+ const directionOptions = $derived(allDirectionOptions.filter((option) => option.value !== 'backup' || canBackup || isEditMode));const selectedDirection = $derived(directionOptions.find((option) => option.value === selectedMode));const projectListOptions: SearchPaginationSortRequest = {@@ -360,16 +366,9 @@const workspaceFiles = $derived<WorkspaceFileEntry[]>(workspaceQuery.data?.files ?? []);const loadingWorkspace = $derived(!!selectedProjectId && (workspaceQuery.isPending || workspaceQuery.isFetching));- const composeFileNames = ['compose.yaml', 'compose.yml', 'docker-compose.yml', 'docker-compose.yaml'];-- function isComposeFileInternal(name: string): boolean {- const lowered = name.toLowerCase();- return composeFileNames.includes(lowered) || /^(docker-)?compose\..+\.ya?ml$/.test(lowered);- }-function isEnvFileInternal(name: string): boolean {const lowered = name.toLowerCase();- return lowered === '.env' || lowered.startsWith('.env.') || lowered.endsWith('.env');+ return lowered === envFileName || lowered.startsWith('.env.') || lowered.endsWith('.env');}function isEnvPathInternal(path: string): boolean {@@ -410,25 +409,9 @@return roots;});- const rootFiles = $derived(workspaceFiles.filter((entry) => !entry.isDirectory && !entry.relativePath.includes('/')));-- const entrypointPath = $derived.by(() => {- for (const candidate of composeFileNames) {- const found = rootFiles.find((entry) => entry.name.toLowerCase() === candidate);- if (found) return found.relativePath;- }- return '';- });-- const defaultBackupPaths = $derived(- rootFiles.filter((entry) => isComposeFileInternal(entry.name)).map((entry) => entry.relativePath)- );-const initialBackupPaths = $derived.by<ReadonlySet<string>>(() => {const stored = syncToEdit?.projectId === selectedProjectId ? (syncToEdit?.backupPaths ?? []) : [];- const paths = new Set(stored.length > 0 ? stored : defaultBackupPaths);- if (entrypointPath) paths.add(entrypointPath);- return paths;+ return new Set(stored.filter((path) => path !== envFileName));});const selectionOverrides = new SvelteMap<string, SvelteSet<string>>();const selectedPaths = $derived<ReadonlySet<string>>(selectionOverrides.get(selectedProjectId) ?? initialBackupPaths);@@ -456,7 +439,6 @@}function isNodeLockedInternal(node: BackupFileNode): boolean {- if (node.path === entrypointPath) return true;if (!node.isDirectory && isEnvFileInternal(node.name)) return false;return ancestorSelectedInternal(node.path);}@@ -477,8 +459,10 @@}}- const backupPaths = $derived([...selectedPaths].sort((a, b) => a.localeCompare(b)));- const hasSelectedEnvFile = $derived(backupPaths.some((path) => isEnvPathInternal(path)));+ const backupPaths = $derived(+ [...selectedPaths, ...(inputs.includeEnvFile.value ? [envFileName] : [])].sort((a, b) => a.localeCompare(b))+ );+ const hasSelectedEnvFile = $derived([...selectedPaths].some((path) => isEnvPathInternal(path)));const backupNamePlaceholder = $derived(m.project_backup_name({ name: selectedProject?.name ?? '' }));const backupSummaryDestination = $derived(`${selectedRepository?.label ?? ''} · ${selectedBranch} / ${effectiveBackupDirectory}`@@ -598,9 +582,6 @@/><Label for={`backup-path-${node.path}`} class="mb-0 flex min-w-0 flex-1 items-center gap-2 text-sm font-normal"><span class={cn('truncate', node.isDirectory && 'font-medium')}>{node.name}{node.isDirectory ? '/' : ''}</span>- {#if node.path === entrypointPath}- <span class="shrink-0 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] text-primary">{m.common_entrypoint()}</span>- {/if}{#if isEnvFile}<span class="shrink-0 rounded bg-amber-500/10 px-1.5 py-0.5 text-[10px] text-amber-600 dark:text-amber-400">{m.environment_file()}@@ -739,7 +720,9 @@disabled={isEditMode}error={inputs.projectId.error}onValueChange={(value) => {- if (value) inputs.projectId.value = value;+ if (!value) return;+ if (value !== inputs.projectId.value) inputs.includeEnvFile.value = false;+ inputs.projectId.value = value;}}/>@@ -829,6 +812,19 @@</div><Switch id="backupOnSaveSwitch" bind:checked={inputs.backupOnSave.value} disabled={!inputs.autoSync.value} /></div>++ <div class="py-3">+ <div class="flex items-center justify-between gap-4">+ <div class="min-w-0">+ <Label for="includeEnvFileSwitch" class="mb-0 text-sm font-medium">{m.include_environment_file()}</Label>+ <p class="text-xs text-muted-foreground">{m.include_environment_file_description()}</p>+ </div>+ <Switch id="includeEnvFileSwitch" bind:checked={inputs.includeEnvFile.value} />+ </div>+ {#if inputs.includeEnvFile.value}+ <p class="mt-2 text-xs text-amber-600 dark:text-amber-400">{m.environment_file_warning()}</p>+ {/if}+ </div></div>{#if showBackupSummary}diff --git a/frontend/src/lib/components/gitops/project-git-backup-summary.svelte b/frontend/src/lib/components/gitops/project-git-backup-summary.svelteindex 7b6d3b187..1b05068af 100644--- a/frontend/src/lib/components/gitops/project-git-backup-summary.svelte+++ b/frontend/src/lib/components/gitops/project-git-backup-summary.svelte@@ -47,8 +47,11 @@}));const sync = $derived(backups.data?.data?.[0] ?? null);- const canSync = $derived(hasPermission('gitops:sync', environmentId));- const canDelete = $derived(hasPermission('gitops:delete', environmentId));+ const canBackup = $derived(hasPermission('gitops:backup', environmentId));+ const canCreate = $derived(canBackup && hasPermission('gitops:create', environmentId));+ const canRun = $derived(canBackup && hasPermission('gitops:sync', environmentId));+ const canEdit = $derived(canBackup && hasPermission('gitops:update', environmentId));+ const canDisconnect = $derived(canBackup && hasPermission('gitops:delete', environmentId));const needsAttention = $derived(sync?.backupState === 'needs_attention');const showError = $derived(!!sync?.lastSyncError && (sync?.backupState === 'failed' || needsAttention));const createHref = $derived(`/environments/${environmentId}/gitops?action=create&mode=backup&projectId=${projectId}`);@@ -121,14 +124,16 @@{#if !sync}<div class="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border/50 px-4 py-3"><p class="text-sm text-muted-foreground">{m.not_backed_up_to_git()}</p>- <ArcaneButton action="base" tone="outline-primary" href={createHref} icon={UploadIcon} customLabel={m.back_up_to_git()} />+ {#if canCreate}+ <ArcaneButton action="base" tone="outline-primary" href={createHref} icon={UploadIcon} customLabel={m.back_up_to_git()} />+ {/if}</div>{:else}<DetailMetaStrip items={metaItems}><BackupStateBadge {sync} /><div class="ml-auto flex items-center gap-2">- {#if canSync}+ {#if canRun}<ArcaneButtonaction="base"tone="outline-primary"@@ -141,33 +146,37 @@/>{/if}- <RowActionsMenu>- <DropdownMenu.Item onclick={() => (historyOpen = true)}>- <ClockIcon class="size-4" />- {m.history()}- </DropdownMenu.Item>-- <DropdownMenu.Item onclick={() => goto(`/environments/${environmentId}/gitops?action=edit&syncId=${sync.id}`)}>- <SettingsIcon class="size-4" />- {m.settings()}- </DropdownMenu.Item>-- {#if needsAttention && canSync}- <DropdownMenu.Item onclick={() => (resolveOpen = true)}>- <ShieldAlertIcon class="size-4" />- {m.resolve()}+ {#if canBackup}+ <RowActionsMenu>+ <DropdownMenu.Item onclick={() => (historyOpen = true)}>+ <ClockIcon class="size-4" />+ {m.history()}</DropdownMenu.Item>- {/if}- {#if canDelete}- <DropdownMenu.Separator />-- <DropdownMenu.Item variant="destructive" disabled={disconnecting} onclick={disconnect}>- <TrashIcon class="size-4" />- {m.common_disconnect()}- </DropdownMenu.Item>- {/if}- </RowActionsMenu>+ {#if canEdit}+ <DropdownMenu.Item onclick={() => goto(`/environments/${environmentId}/gitops?action=edit&syncId=${sync.id}`)}>+ <SettingsIcon class="size-4" />+ {m.settings()}+ </DropdownMenu.Item>+ {/if}++ {#if needsAttention}+ <DropdownMenu.Item onclick={() => (resolveOpen = true)}>+ <ShieldAlertIcon class="size-4" />+ {m.resolve()}+ </DropdownMenu.Item>+ {/if}++ {#if canDisconnect}+ <DropdownMenu.Separator />++ <DropdownMenu.Item variant="destructive" disabled={disconnecting} onclick={disconnect}>+ <TrashIcon class="size-4" />+ {m.common_disconnect()}+ </DropdownMenu.Item>+ {/if}+ </RowActionsMenu>+ {/if}</div></DetailMetaStrip>diff --git a/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelteindex 482adab16..7ef1c8140 100644--- a/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte+++ b/frontend/src/routes/(app)/environments/[id]/gitops/sync-table.svelte@@ -53,8 +53,10 @@onEditSync: (sync: GitOpsSync) => void;} = $props();- const canSync = $derived(hasPermission('gitops:sync', environmentId));const canDelete = $derived(hasPermission('gitops:delete', environmentId));+ const canBackup = $derived(hasPermission('gitops:backup', environmentId));+ const canRunBackup = $derived(canBackup && hasPermission('gitops:sync', environmentId));+ const canEditBackup = $derived(canBackup && hasPermission('gitops:update', environmentId));let isLoading = $state({removing: false,@@ -448,29 +450,29 @@{#snippet RowActions({ item }: { item: GitOpsSync })}<RowActionsMenu>{#if isBackup(item)}- <DropdownMenu.Item onclick={() => handlePerformSync(item)} disabled={isLoading.syncing || !canSync}>+ <DropdownMenu.Item onclick={() => handlePerformSync(item)} disabled={isLoading.syncing || !canRunBackup}><UploadIcon class="size-4" />{m.back_up_now()}</DropdownMenu.Item>- <DropdownMenu.Item onclick={() => openBackupHistory(item)}>+ <DropdownMenu.Item onclick={() => openBackupHistory(item)} disabled={!canBackup}><ClockIcon class="size-4" />{m.history()}</DropdownMenu.Item>- {#if item.backupState === 'needs_attention' && canSync}+ {#if item.backupState === 'needs_attention' && canBackup}<DropdownMenu.Item onclick={() => openBackupResolve(item)}><AlertTriangleIcon class="size-4" />{m.resolve()}</DropdownMenu.Item>{/if}- <DropdownMenu.Item onclick={() => onEditSync(item)}>+ <DropdownMenu.Item onclick={() => onEditSync(item)} disabled={!canEditBackup}><SettingsIcon class="size-4" />{m.settings()}</DropdownMenu.Item>- {#if canDelete}+ {#if canDelete && canBackup}<RemoveMenuItemonclick={() => handleDisconnectBackup(item)}disabled={isLoading.removing}diff --git a/types/gitops/gitops.go b/types/gitops/gitops.goindex 6822d7f04..d8d5e76de 100644--- a/types/gitops/gitops.go+++ b/types/gitops/gitops.go@@ -551,8 +551,8 @@ type CreateSyncRequest struct {// Required: falseBackupDirectory string `json:"backupDirectory,omitempty"`- // BackupPaths lists project-relative files and directories to back up. Defaults- // to the project's compose files when omitted. Environment files are only+ // BackupPaths lists project-relative files and directories to back up. The+ // project's compose files are always included. Environment files are only// included when listed explicitly.//// Required: false@@ -701,7 +701,8 @@ type UpdateSyncRequest struct {// Required: falseProjectName *string `json:"projectName,omitzero"`- // BackupPaths replaces the backed-up file selection. Omitted or empty leaves it unchanged.+ // BackupPaths replaces the backed-up file selection. Omitted leaves it unchanged;+ // an empty list keeps only the compose files.//// Required: falseBackupPaths []string `json:"backupPaths,omitzero"`@@ -858,7 +859,7 @@ func (r CreateSyncRequest) HasBackupOptions() bool {// HasBackupOptions reports whether the request sets backup-only options that// a deploy sync must reject.func (r UpdateSyncRequest) HasBackupOptions() bool {- return len(r.BackupPaths) > 0 || r.BackupOnSave != nil+ return r.BackupPaths != nil || r.BackupOnSave != nil}// SyncResult represents the result of a sync operation.