Skip to content

Modern Docker Management, Designed for Everyone

feat: redesign global variables with environment scoping and secrets (#3311)

Kyle Mendellcbc624b6a282
diff --git a/backend/api/api.go b/backend/api/api.go
index 53df6623b..e89e93791 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -310,7 +310,8 @@ func registerHandlersInternal(api huma.API, svc *di.Services, handlerAppCtx hand
handlers.RegisterOidc(api, svc.Auth, svc.Oidc, svc.Role, svc.User, cfg)
handlers.RegisterEnvironments(api, svc.Environment, svc.Settings, svc.ApiKey, svc.Event, cfg)
handlers.RegisterContainerRegistries(api, svc.ContainerRegistry, svc.Environment)
- handlers.RegisterTemplates(api, svc.Template, svc.Environment)
+ handlers.RegisterTemplates(api, svc.Template)
+ handlers.RegisterVariables(api, svc.Variable, svc.Environment)
handlers.RegisterImages(api, svc.Docker, svc.Image, svc.ImageUpdate, svc.Settings, svc.Build, svc.Activity, handlerAppCtx)
handlers.RegisterBuildWorkspaces(api, svc.BuildWorkspace)
handlers.RegisterImageUpdates(api, svc.ImageUpdate, svc.Image, handlerAppCtx)
diff --git a/backend/api/handlers/remenv_handlers_test.go b/backend/api/handlers/remenv_handlers_test.go
index 94db6f860..f3a2eaaec 100644
--- a/backend/api/handlers/remenv_handlers_test.go
+++ b/backend/api/handlers/remenv_handlers_test.go
@@ -179,7 +179,7 @@ func TestSettingsHandler_GetSettings_RemotePreservesAdminResponse(t *testing.T)
require.Equal(t, remoteSettings, output.Body)
}
-func TestTemplateHandler_GetGlobalVariables_RemoteSuccess(t *testing.T) {
+func TestVariableHandler_GetMaterializedVariables_RemoteSuccess(t *testing.T) {
expected := base.ApiResponse[[]env.Variable]{
Success: true,
Data: []env.Variable{{Key: "FOO", Value: "bar"}},
@@ -190,12 +190,12 @@ func TestTemplateHandler_GetGlobalVariables_RemoteSuccess(t *testing.T) {
}))
defer server.Close()
- handler := &TemplateHandler{
- templateService: &services.TemplateService{},
+ handler := &VariableHandler{
+ variableService: &services.VariableService{},
environmentService: setupRemoteHandlerEnvironmentServiceInternal(t, server),
}
- output, err := handler.GetGlobalVariables(adminTestContextInternal(), &GetGlobalVariablesInput{EnvironmentID: "env-remote"})
+ output, err := handler.GetMaterializedVariables(adminTestContextInternal(), &GetGlobalVariablesInput{EnvironmentID: "env-remote"})
require.NoError(t, err)
require.Equal(t, expected, output.Body)
}
diff --git a/backend/api/handlers/templates.go b/backend/api/handlers/templates.go
index 5b9438240..dcba3d975 100644
--- a/backend/api/handlers/templates.go
+++ b/backend/api/handlers/templates.go
@@ -3,7 +3,6 @@ package handlers
import (
"context"
json "encoding/json/v2"
- "net/http"
"net/url"
"github.com/danielgtaylor/huma/v2"
@@ -14,14 +13,12 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"
"github.com/getarcaneapp/arcane/types/v2/base"
- "github.com/getarcaneapp/arcane/types/v2/env"
"github.com/getarcaneapp/arcane/types/v2/template"
)
// TemplateHandler handles template management endpoints.
type TemplateHandler struct {
- templateService *services.TemplateService
- environmentService *services.EnvironmentService
+ templateService *services.TemplateService
}
// ============================================================================
@@ -156,30 +153,13 @@ type FetchTemplateRegistryOutput struct {
Body base.ApiResponse[template.RemoteRegistry]
}
-type GetGlobalVariablesInput struct {
- EnvironmentID string `path:"id" doc:"Environment ID"`
-}
-
-type GetGlobalVariablesOutput struct {
- Body base.ApiResponse[[]env.Variable]
-}
-
-type UpdateGlobalVariablesInput struct {
- EnvironmentID string `path:"id" doc:"Environment ID"`
- Body env.Summary
-}
-
-type UpdateGlobalVariablesOutput struct {
- Body base.ApiResponse[base.MessageResponse]
-}
-
// ============================================================================
// Registration
// ============================================================================
// RegisterTemplates registers all template management endpoints.
-func RegisterTemplates(api huma.API, templateService *services.TemplateService, environmentService *services.EnvironmentService) {
- h := &TemplateHandler{templateService: templateService, environmentService: environmentService}
+func RegisterTemplates(api huma.API, templateService *services.TemplateService) {
+ h := &TemplateHandler{templateService: templateService}
// Template registry endpoint.
huma.Register(api, huma.Operation{
@@ -376,32 +356,6 @@ func RegisterTemplates(api huma.API, templateService *services.TemplateService,
},
Middlewares: humamw.RequirePermission(api, authz.PermTemplatesDelete),
}, h.DeleteRegistry)
-
- humamw.RegisterWithPermission(api, huma.Operation{
- OperationID: "getGlobalVariables",
- Method: "GET",
- Path: "/environments/{id}/templates/variables",
- Summary: "Get global variables",
- Description: "Get global template variables for an environment",
- Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesRead, h.GetGlobalVariables)
-
- humamw.RegisterWithPermission(api, huma.Operation{
- OperationID: "updateGlobalVariables",
- Method: "PUT",
- Path: "/environments/{id}/templates/variables",
- Summary: "Update global variables",
- Description: "Update global template variables for an environment",
- Tags: []string{"Templates"},
- Security: []map[string][]string{
- {"BearerAuth": {}},
- {"ApiKeyAuth": {}},
- },
- }, authz.PermTemplatesUpdate, h.UpdateGlobalVariables)
}
// ============================================================================
@@ -889,79 +843,3 @@ func (h *TemplateHandler) FetchRegistry(ctx context.Context, input *FetchTemplat
},
}, nil
}
-
-// GetGlobalVariables returns global template variables.
-func (h *TemplateHandler) GetGlobalVariables(ctx context.Context, input *GetGlobalVariablesInput) (*GetGlobalVariablesOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- if input.EnvironmentID != "0" {
- return h.getGlobalVariablesForRemoteEnvironmentInternal(ctx, input)
- }
-
- vars, err := h.templateService.GetGlobalVariables(ctx)
- if err != nil {
- return nil, huma.Error500InternalServerError((&common.GlobalVariablesRetrievalError{Err: err}).Error())
- }
-
- return &GetGlobalVariablesOutput{
- Body: base.ApiResponse[[]env.Variable]{
- Success: true,
- Data: vars,
- },
- }, nil
-}
-
-func (h *TemplateHandler) getGlobalVariablesForRemoteEnvironmentInternal(ctx context.Context, input *GetGlobalVariablesInput) (*GetGlobalVariablesOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
-
- response, err := proxyRemoteJSONInternal[base.ApiResponse[[]env.Variable]](ctx, h.environmentService, input.EnvironmentID, http.MethodGet, "/api/environments/0/templates/variables", nil)
- if err != nil {
- return nil, err
- }
-
- return &GetGlobalVariablesOutput{Body: *response}, nil
-}
-
-// UpdateGlobalVariables updates global template variables.
-func (h *TemplateHandler) UpdateGlobalVariables(ctx context.Context, input *UpdateGlobalVariablesInput) (*UpdateGlobalVariablesOutput, error) {
- if h.templateService == nil {
- return nil, huma.Error500InternalServerError("service not available")
- }
-
- if input.EnvironmentID != "0" {
- return h.updateGlobalVariablesForRemoteEnvironmentInternal(ctx, input)
- }
-
- if err := h.templateService.UpdateGlobalVariables(ctx, input.Body.Variables); err != nil {
- if common.IsInvalidEnvKeyError(err) {
- return nil, huma.Error400BadRequest(err.Error())
- }
- return nil, huma.Error500InternalServerError((&common.GlobalVariablesUpdateError{Err: err}).Error())
- }
-
- return &UpdateGlobalVariablesOutput{
- Body: base.ApiResponse[base.MessageResponse]{
- Success: true,
- Data: base.MessageResponse{
- Message: "Global variables updated successfully",
- },
- },
- }, nil
-}
-
-func (h *TemplateHandler) updateGlobalVariablesForRemoteEnvironmentInternal(ctx context.Context, input *UpdateGlobalVariablesInput) (*UpdateGlobalVariablesOutput, error) {
- if h.environmentService == nil {
- return nil, huma.Error500InternalServerError("environment service not available")
- }
-
- response, err := proxyRemoteJSONInternal[base.ApiResponse[base.MessageResponse]](ctx, h.environmentService, input.EnvironmentID, http.MethodPut, "/api/environments/0/templates/variables", input.Body)
- if err != nil {
- return nil, err
- }
-
- return &UpdateGlobalVariablesOutput{Body: *response}, nil
-}
diff --git a/backend/api/handlers/templates_test.go b/backend/api/handlers/templates_test.go
index 6ef5fd4c0..42795f677 100644
--- a/backend/api/handlers/templates_test.go
+++ b/backend/api/handlers/templates_test.go
@@ -167,7 +167,7 @@ func newTemplateFetchTestRouter(t *testing.T, httpClient *http.Client) *echo.Ech
api := humaecho.NewWithGroup(router, apiGroup, humaConfig)
api.UseMiddleware(humamiddleware.NewAuthBridge(api, authService, nil, sudoPermResolver{}, nil, &config.Config{}))
RegisterHealth(api)
- RegisterTemplates(api, templateService, nil)
+ RegisterTemplates(api, templateService)
return router
}
diff --git a/backend/api/handlers/variables.go b/backend/api/handlers/variables.go
new file mode 100644
index 000000000..2c0153796
--- /dev/null
+++ b/backend/api/handlers/variables.go
@@ -0,0 +1,388 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/services"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
+ "github.com/getarcaneapp/arcane/types/v2/base"
+ "github.com/getarcaneapp/arcane/types/v2/env"
+)
+
+// VariableHandler handles the manager-level global variable endpoints plus the
+// per-environment /environments/{id}/templates/variables routes, which remain
+// the materialization channel the manager pushes through to agents.
+type VariableHandler struct {
+ variableService *services.VariableService
+ environmentService *services.EnvironmentService
+}
+
+// ============================================================================
+// Input/Output Types
+// ============================================================================
+
+type ListGlobalVariablesInput struct{}
+
+type ListGlobalVariablesOutput struct {
+ Body base.ApiResponse[[]env.GlobalVariable]
+}
+
+type CreateGlobalVariableInput struct {
+ Body env.CreateGlobalVariableRequest
+}
+
+type CreateGlobalVariableOutput struct {
+ Body base.ApiResponse[env.GlobalVariableMutationResponse]
+}
+
+type UpdateGlobalVariableInput struct {
+ ID string `path:"id" doc:"Variable ID"`
+ Body env.UpdateGlobalVariableRequest
+}
+
+type UpdateGlobalVariableOutput struct {
+ Body base.ApiResponse[env.GlobalVariableMutationResponse]
+}
+
+type DeleteGlobalVariableInput struct {
+ ID string `path:"id" doc:"Variable ID"`
+}
+
+type DeleteGlobalVariableOutput struct {
+ Body base.ApiResponse[env.GlobalVariableMutationResponse]
+}
+
+type SyncGlobalVariablesInput struct{}
+
+type SyncGlobalVariablesOutput struct {
+ Body base.ApiResponse[[]env.EnvironmentSyncStatus]
+}
+
+type GetGlobalVariableSyncStatusInput struct{}
+
+type GetGlobalVariableSyncStatusOutput struct {
+ Body base.ApiResponse[[]env.EnvironmentSyncStatus]
+}
+
+type GetGlobalVariablesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+}
+
+type GetGlobalVariablesOutput struct {
+ Body base.ApiResponse[[]env.Variable]
+}
+
+type UpdateGlobalVariablesInput struct {
+ EnvironmentID string `path:"id" doc:"Environment ID"`
+ Body env.Summary
+}
+
+type UpdateGlobalVariablesOutput struct {
+ Body base.ApiResponse[base.MessageResponse]
+}
+
+// ============================================================================
+// Route Registration
+// ============================================================================
+
+func RegisterVariables(api huma.API, variableService *services.VariableService, environmentService *services.EnvironmentService) {
+ h := &VariableHandler{variableService: variableService, environmentService: environmentService}
+
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "listVariables",
+ Method: "GET",
+ Path: "/variables",
+ Summary: "List global variables",
+ Description: "List all global variables with their environment scope (secret values are redacted)",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesRead, h.ListVariables)
+
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "createVariable",
+ Method: "POST",
+ Path: "/variables",
+ Summary: "Create a global variable",
+ Description: "Create a global variable scoped to all or specific environments",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesUpdate, h.CreateVariable)
+
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "updateVariable",
+ Method: "PUT",
+ Path: "/variables/{id}",
+ Summary: "Update a global variable",
+ Description: "Update a global variable's key, value, secret flag, or environment scope",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesUpdate, h.UpdateVariable)
+
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "deleteVariable",
+ Method: "DELETE",
+ Path: "/variables/{id}",
+ Summary: "Delete a global variable",
+ Description: "Delete a global variable and re-sync affected environments",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesUpdate, h.DeleteVariable)
+
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "syncVariables",
+ Method: "POST",
+ Path: "/variables/sync",
+ Summary: "Sync global variables",
+ Description: "Push the effective global variable set to every environment now",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesUpdate, h.SyncVariables)
+
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "getVariableSyncStatus",
+ Method: "GET",
+ Path: "/variables/sync-status",
+ Summary: "Get variable sync status",
+ Description: "Get the last global-variable sync result per environment",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesRead, h.GetSyncStatus)
+
+ // Per-environment materialized-file routes. Agents serve these locally; the
+ // manager pushes each environment's effective set through them.
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "getGlobalVariables",
+ Method: "GET",
+ Path: "/environments/{id}/templates/variables",
+ Summary: "Get materialized variables",
+ Description: "Get the materialized variable set for an environment. Managed via /variables on the manager.",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesRead, h.GetMaterializedVariables)
+
+ humamw.RegisterWithPermission(api, huma.Operation{
+ OperationID: "updateGlobalVariables",
+ Method: "PUT",
+ Path: "/environments/{id}/templates/variables",
+ Summary: "Update materialized variables",
+ Description: "Replace the materialized variable set for an environment. Managed via /variables on the manager.",
+ Tags: []string{"Variables"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, authz.PermTemplatesUpdate, h.UpdateMaterializedVariables)
+}
+
+// ============================================================================
+// Handler Methods
+// ============================================================================
+
+func (h *VariableHandler) ListVariables(ctx context.Context, _ *ListGlobalVariablesInput) (*ListGlobalVariablesOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ variables, err := h.variableService.ListVariables(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError(err.Error())
+ }
+
+ return &ListGlobalVariablesOutput{
+ Body: base.ApiResponse[[]env.GlobalVariable]{
+ Success: true,
+ Data: variables,
+ },
+ }, nil
+}
+
+func (h *VariableHandler) CreateVariable(ctx context.Context, input *CreateGlobalVariableInput) (*CreateGlobalVariableOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ variable, err := h.variableService.CreateVariable(ctx, input.Body)
+ if err != nil {
+ return nil, variableMutationHTTPErrorInternal(err)
+ }
+
+ return &CreateGlobalVariableOutput{
+ Body: base.ApiResponse[env.GlobalVariableMutationResponse]{
+ Success: true,
+ Data: env.GlobalVariableMutationResponse{
+ Variable: variable,
+ SyncResults: h.variableService.SyncAllBackground(ctx),
+ },
+ },
+ }, nil
+}
+
+func (h *VariableHandler) UpdateVariable(ctx context.Context, input *UpdateGlobalVariableInput) (*UpdateGlobalVariableOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ variable, err := h.variableService.UpdateVariable(ctx, input.ID, input.Body)
+ if err != nil {
+ return nil, variableMutationHTTPErrorInternal(err)
+ }
+
+ return &UpdateGlobalVariableOutput{
+ Body: base.ApiResponse[env.GlobalVariableMutationResponse]{
+ Success: true,
+ Data: env.GlobalVariableMutationResponse{
+ Variable: variable,
+ SyncResults: h.variableService.SyncAllBackground(ctx),
+ },
+ },
+ }, nil
+}
+
+func (h *VariableHandler) DeleteVariable(ctx context.Context, input *DeleteGlobalVariableInput) (*DeleteGlobalVariableOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if err := h.variableService.DeleteVariable(ctx, input.ID); err != nil {
+ return nil, variableMutationHTTPErrorInternal(err)
+ }
+
+ return &DeleteGlobalVariableOutput{
+ Body: base.ApiResponse[env.GlobalVariableMutationResponse]{
+ Success: true,
+ Data: env.GlobalVariableMutationResponse{
+ SyncResults: h.variableService.SyncAllBackground(ctx),
+ },
+ },
+ }, nil
+}
+
+func (h *VariableHandler) SyncVariables(ctx context.Context, _ *SyncGlobalVariablesInput) (*SyncGlobalVariablesOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ return &SyncGlobalVariablesOutput{
+ Body: base.ApiResponse[[]env.EnvironmentSyncStatus]{
+ Success: true,
+ Data: h.variableService.SyncAll(ctx),
+ },
+ }, nil
+}
+
+func (h *VariableHandler) GetSyncStatus(_ context.Context, _ *GetGlobalVariableSyncStatusInput) (*GetGlobalVariableSyncStatusOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ return &GetGlobalVariableSyncStatusOutput{
+ Body: base.ApiResponse[[]env.EnvironmentSyncStatus]{
+ Success: true,
+ Data: h.variableService.SyncStatuses(),
+ },
+ }, nil
+}
+
+// GetMaterializedVariables returns the environment's materialized .env.global
+// content (local file for environment "0", proxied to the agent otherwise).
+func (h *VariableHandler) GetMaterializedVariables(ctx context.Context, input *GetGlobalVariablesInput) (*GetGlobalVariablesOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.EnvironmentID != "0" {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("environment service not available")
+ }
+ response, err := proxyRemoteJSONInternal[base.ApiResponse[[]env.Variable]](ctx, h.environmentService, input.EnvironmentID, http.MethodGet, "/api/environments/0/templates/variables", nil)
+ if err != nil {
+ return nil, err
+ }
+ return &GetGlobalVariablesOutput{Body: *response}, nil
+ }
+
+ vars, err := h.variableService.ReadLocalEnvFile(ctx)
+ if err != nil {
+ return nil, huma.Error500InternalServerError((&common.GlobalVariablesRetrievalError{Err: err}).Error())
+ }
+
+ return &GetGlobalVariablesOutput{
+ Body: base.ApiResponse[[]env.Variable]{
+ Success: true,
+ Data: vars,
+ },
+ }, nil
+}
+
+// UpdateMaterializedVariables replaces the environment's materialized
+// .env.global content (local file for environment "0", proxied otherwise).
+func (h *VariableHandler) UpdateMaterializedVariables(ctx context.Context, input *UpdateGlobalVariablesInput) (*UpdateGlobalVariablesOutput, error) {
+ if h.variableService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ if input.EnvironmentID != "0" {
+ if h.environmentService == nil {
+ return nil, huma.Error500InternalServerError("environment service not available")
+ }
+ response, err := proxyRemoteJSONInternal[base.ApiResponse[base.MessageResponse]](ctx, h.environmentService, input.EnvironmentID, http.MethodPut, "/api/environments/0/templates/variables", input.Body)
+ if err != nil {
+ return nil, err
+ }
+ return &UpdateGlobalVariablesOutput{Body: *response}, nil
+ }
+
+ if err := h.variableService.WriteLocalEnvFile(ctx, input.Body.Variables); err != nil {
+ if common.IsInvalidEnvKeyError(err) {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+ return nil, huma.Error500InternalServerError((&common.GlobalVariablesUpdateError{Err: err}).Error())
+ }
+
+ return &UpdateGlobalVariablesOutput{
+ Body: base.ApiResponse[base.MessageResponse]{
+ Success: true,
+ Data: base.MessageResponse{
+ Message: "Global variables updated successfully",
+ },
+ },
+ }, nil
+}
+
+func variableMutationHTTPErrorInternal(err error) error {
+ switch {
+ case common.IsInvalidEnvKeyError(err), common.IsGlobalVariableSecretValueRequiredError(err), common.IsGlobalVariableScopeRequiredError(err):
+ return huma.Error400BadRequest(err.Error())
+ case common.IsGlobalVariableNotFoundError(err):
+ return huma.Error404NotFound(err.Error())
+ case common.IsGlobalVariableConflictError(err):
+ return huma.Error409Conflict(err.Error())
+ default:
+ return huma.Error500InternalServerError(err.Error())
+ }
+}
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index ce07794f0..9c47952d4 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -190,6 +190,15 @@ func initializeStartupState(appCtx context.Context, cfg *config.Config, appServi
if err := appServices.Environment.ReconcileEdgeStatusesOnStartup(appCtx); err != nil {
slog.WarnContext(appCtx, "Failed to reconcile edge environment statuses on startup", "error", err)
}
+
+ // Global variables are a manager resource: import any pre-existing local
+ // .env.global once, then materialize the effective set everywhere. Agents
+ // only serve the per-environment variables endpoint the manager pushes to.
+ appServices.Environment.SetVariableSyncer(appServices.Variable)
+ if err := appServices.Variable.ImportLegacyLocalEnvFile(appCtx); err != nil {
+ slog.WarnContext(appCtx, "Failed to import legacy global variables", "error", err)
+ }
+ go appServices.Variable.SyncAll(appCtx)
}
startup.TestDockerConnection(appCtx, func(ctx context.Context) error {
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index e25050a4c..1f751fa4e 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -1313,6 +1313,52 @@ func IsInvalidEnvKeyError(err error) bool {
return isErrorTypeInternal[*InvalidEnvKeyError](err)
}
+type GlobalVariableNotFoundError struct{}
+
+func (e *GlobalVariableNotFoundError) Error() string {
+ return "Global variable not found"
+}
+
+func IsGlobalVariableNotFoundError(err error) bool {
+ return isErrorTypeInternal[*GlobalVariableNotFoundError](err)
+}
+
+type GlobalVariableConflictError struct {
+ Key string
+}
+
+func (e *GlobalVariableConflictError) Error() string {
+ return fmt.Sprintf("A variable named %q already exists for an overlapping environment scope", e.Key)
+}
+
+func IsGlobalVariableConflictError(err error) bool {
+ return isErrorTypeInternal[*GlobalVariableConflictError](err)
+}
+
+// GlobalVariableScopeRequiredError is returned when a variable is scoped to
+// specific environments but no environment IDs were provided.
+type GlobalVariableScopeRequiredError struct{}
+
+func (e *GlobalVariableScopeRequiredError) Error() string {
+ return "At least one environment is required when a variable is not scoped to all environments"
+}
+
+func IsGlobalVariableScopeRequiredError(err error) bool {
+ return isErrorTypeInternal[*GlobalVariableScopeRequiredError](err)
+}
+
+// GlobalVariableSecretValueRequiredError is returned when a secret variable is
+// switched to readable without providing a replacement value.
+type GlobalVariableSecretValueRequiredError struct{}
+
+func (e *GlobalVariableSecretValueRequiredError) Error() string {
+ return "A new value is required when making a secret variable readable"
+}
+
+func IsGlobalVariableSecretValueRequiredError(err error) bool {
+ return isErrorTypeInternal[*GlobalVariableSecretValueRequiredError](err)
+}
+
type UpdaterRunError struct {
Err error
}
diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.go
index 9ff69900b..3a2d10f7f 100644
--- a/backend/internal/database/database_test.go
+++ b/backend/internal/database/database_test.go
@@ -83,6 +83,36 @@ func TestMigration065_ProjectBuildImageRefs_UpAndDown(t *testing.T) {
assert.Zero(t, columnCount)
}
+func TestMigration066_GlobalVariables_UpAndDown(t *testing.T) {
+ ctx := context.Background()
+ rawDB, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-global-variables.db")
+
+ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 65))
+ var tableCount int
+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('global_variables', 'global_variable_environments')`).Scan(&tableCount))
+ assert.Zero(t, tableCount)
+
+ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 66))
+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('global_variables', 'global_variable_environments')`).Scan(&tableCount))
+ assert.Equal(t, 2, tableCount)
+
+ _, err := rawDB.Exec(`INSERT INTO environments (id, api_url, status, enabled) VALUES ('env-1', 'http://localhost', 'online', TRUE)`)
+ require.NoError(t, err)
+ _, err = rawDB.Exec(`INSERT INTO global_variables (id, created_at, key, value, is_secret, all_environments) VALUES ('var-1', CURRENT_TIMESTAMP, 'API_URL', 'https://example.test', FALSE, FALSE)`)
+ require.NoError(t, err)
+ _, err = rawDB.Exec(`INSERT INTO global_variable_environments (global_variable_id, environment_id) VALUES ('var-1', 'env-1')`)
+ require.NoError(t, err)
+
+ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{AllowDowngrade: true}, 65))
+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('global_variables', 'global_variable_environments')`).Scan(&tableCount))
+ assert.Zero(t, tableCount)
+
+ require.NoError(t, migrateDatabaseToVersionInternal(ctx, rawDB, dbProviderSQLite, MigrationOptions{}, 66))
+ var rowCount int
+ require.NoError(t, rawDB.QueryRow(`SELECT COUNT(*) FROM global_variables`).Scan(&rowCount))
+ assert.Zero(t, rowCount)
+}
+
func TestMigrateDatabase_BlocksFutureGooseVersionWithoutFlag(t *testing.T) {
ctx := context.Background()
rawDB, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "arcane-future.db")
diff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.go
index 9a214da0f..5fdd81dca 100644
--- a/backend/internal/di/providers.go
+++ b/backend/internal/di/providers.go
@@ -63,6 +63,7 @@ type Services struct {
Vulnerability *services.VulnerabilityService
Dashboard *services.DashboardService
Role *services.RoleService
+ Variable *services.VariableService
// AuthMiddleware is the shared Echo auth middleware. It's wired here so the
// router consumes it from the container instead of building the chain inline.
AuthMiddleware *middleware.AuthMiddleware
diff --git a/backend/internal/di/wire.go b/backend/internal/di/wire.go
index b7f800d9d..b0d345b78 100644
--- a/backend/internal/di/wire.go
+++ b/backend/internal/di/wire.go
@@ -59,6 +59,7 @@ var ServiceSet = wire.NewSet(
services.NewDiagnosticsService,
services.NewGitOpsSyncService,
services.NewWebhookService,
+ services.NewVariableService,
// Services that require a wrapper (scalar config field, unexported parameter,
// or post-construction RoleService builder). See providers.go.
diff --git a/backend/internal/di/wire_gen.go b/backend/internal/di/wire_gen.go
index cca73a9cc..336f6bbcc 100644
--- a/backend/internal/di/wire_gen.go
+++ b/backend/internal/di/wire_gen.go
@@ -67,6 +67,7 @@ func InitializeServices(ctx context.Context, db *database.DB, cfg *config.Config
gitOpsSyncService := services.NewGitOpsSyncService(db, gitRepositoryService, projectService, swarmService, eventService, settingsService)
webhookService := services.NewWebhookService(db, containerService, updaterService, projectService, gitOpsSyncService, eventService, environmentService)
dashboardService := services.NewDashboardService(db, dockerClientService, containerService, projectService, imageService, settingsService, vulnerabilityService, environmentService, versionService)
+ variableService := services.NewVariableService(db, environmentService, settingsService, kvService)
authMiddleware := provideAuthMiddlewareInternal(authService, apiKeyService, environmentService, roleService, cfg)
diServices := &Services{
AppImages: applicationImagesService,
@@ -110,6 +111,7 @@ func InitializeServices(ctx context.Context, db *database.DB, cfg *config.Config
Vulnerability: vulnerabilityService,
Dashboard: dashboardService,
Role: roleService,
+ Variable: variableService,
AuthMiddleware: authMiddleware,
}
return diServices, nil
@@ -168,7 +170,7 @@ func InitializeJobs(ctx context.Context, cfg *config.Config, svcs *Services) *Jo
// no longer maintained by hand. wire.Struct assembles the aggregate Services.
var ServiceSet = wire.NewSet(
- provideResourcesFSInternal, services.NewEventService, services.NewActivityService, services.NewSettingsService, services.NewKVService, services.NewJobService, services.NewSettingsSearchService, services.NewCustomizeSearchService, services.NewApplicationImagesService, services.NewDockerClientService, services.NewRoleService, services.NewSessionService, services.NewEnvironmentService, services.NewNotificationService, services.NewVulnerabilityService, services.NewImageUpdateService, services.NewImageService, services.NewBuildService, services.NewBuildWorkspaceService, services.NewLifecycleService, provideProjectServiceInternal, services.NewContainerService, services.NewDashboardService, services.NewNetworkService, services.NewPortService, services.NewSwarmService, services.NewTemplateService, services.NewOidcService, services.NewSystemService, services.NewSystemUpgradeService, services.NewDiagnosticsService, services.NewGitOpsSyncService, services.NewWebhookService, provideVersionServiceInternal,
+ provideResourcesFSInternal, services.NewEventService, services.NewActivityService, services.NewSettingsService, services.NewKVService, services.NewJobService, services.NewSettingsSearchService, services.NewCustomizeSearchService, services.NewApplicationImagesService, services.NewDockerClientService, services.NewRoleService, services.NewSessionService, services.NewEnvironmentService, services.NewNotificationService, services.NewVulnerabilityService, services.NewImageUpdateService, services.NewImageService, services.NewBuildService, services.NewBuildWorkspaceService, services.NewLifecycleService, provideProjectServiceInternal, services.NewContainerService, services.NewDashboardService, services.NewNetworkService, services.NewPortService, services.NewSwarmService, services.NewTemplateService, services.NewOidcService, services.NewSystemService, services.NewSystemUpgradeService, services.NewDiagnosticsService, services.NewGitOpsSyncService, services.NewWebhookService, services.NewVariableService, provideVersionServiceInternal,
provideGitRepositoryServiceInternal,
provideVolumeServiceInternal,
provideAuthServiceInternal,
diff --git a/backend/internal/models/global_variable.go b/backend/internal/models/global_variable.go
new file mode 100644
index 000000000..75d67b466
--- /dev/null
+++ b/backend/internal/models/global_variable.go
@@ -0,0 +1,17 @@
+package models
+
+// GlobalVariable is a manager-level key/value variable materialized into each
+// environment's .env.global file. Value holds ciphertext when IsSecret is true.
+type GlobalVariable struct {
+ BaseModel
+
+ Key string `json:"key" gorm:"column:key" sortable:"true"`
+ Value string `json:"-" gorm:"column:value"`
+ IsSecret bool `json:"isSecret" gorm:"column:is_secret"`
+ // No gorm default tag: a default:true tag would make GORM omit false on
+ // insert and the column default would silently win.
+ AllEnvironments bool `json:"allEnvironments" gorm:"column:all_environments"`
+ Environments []Environment `json:"-" gorm:"many2many:global_variable_environments;joinForeignKey:GlobalVariableID;joinReferences:EnvironmentID"`
+}
+
+func (GlobalVariable) TableName() string { return "global_variables" }
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index c96df1cdf..aabf6f9b4 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -52,6 +52,16 @@ type EnvironmentService struct {
// runningHealthChecks guards against a per-environment health check overlapping
// with itself (replaces the old single job's atomic "running" guard).
runningHealthChecks sync.Map
+
+ // variableSyncer is injected post-construction via SetVariableSyncer
+ // (manager-only) to avoid a wire cycle with VariableService.
+ variableSyncer VariableSyncer
+}
+
+// VariableSyncer pushes the effective global-variable set to one environment.
+// Implemented by VariableService.
+type VariableSyncer interface {
+ SyncEnvironment(ctx context.Context, envID string) error
}
const (
@@ -107,6 +117,12 @@ func (s *EnvironmentService) SetScheduler(ctx context.Context, scheduler Dynamic
s.scheduler = scheduler
}
+// SetVariableSyncer injects the global-variable syncer. Called during
+// bootstrap on the manager only; agents leave it nil.
+func (s *EnvironmentService) SetVariableSyncer(syncer VariableSyncer) {
+ s.variableSyncer = syncer
+}
+
func (s *EnvironmentService) schedulerCtxInternal(ctx context.Context) context.Context {
if s.lifecycleCtx != nil {
return s.lifecycleCtx
@@ -248,6 +264,11 @@ func (s *EnvironmentService) runHealthCheckInternal(ctx context.Context, envID s
if err := s.SyncRepositoriesToEnvironment(syncCtx, envID); err != nil {
slog.WarnContext(syncCtx, "failed to sync git repositories during health check", "environment_id", envID, "error", err)
}
+ if s.variableSyncer != nil {
+ if err := s.variableSyncer.SyncEnvironment(syncCtx, envID); err != nil {
+ slog.WarnContext(syncCtx, "failed to sync global variables during health check", "environment_id", envID, "error", err)
+ }
+ }
}
func (s *EnvironmentService) ResolveEdgeEnvironmentByToken(ctx context.Context, token string) (string, error) {
diff --git a/backend/internal/services/template_service.go b/backend/internal/services/template_service.go
index 70e146ca0..e5a265337 100644
--- a/backend/internal/services/template_service.go
+++ b/backend/internal/services/template_service.go
@@ -1,7 +1,6 @@
package services
import (
- "bufio"
"context"
json "encoding/json/v2"
"errors"
@@ -12,7 +11,6 @@ import (
"net/http"
"os"
"path/filepath"
- "regexp"
"strings"
"sync"
"time"
@@ -256,11 +254,6 @@ func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params p
return result.Items, paginationResp, nil
}
-// envKeyPattern is the POSIX env-name shape used to validate global variable
-// keys before they are persisted to .env.global. Keys that do not match are
-// rejected with a common.InvalidEnvKeyError.
-var envKeyPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
-
func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*models.ComposeTemplate, error) {
if err := s.syncFilesystemTemplatesInternal(ctx); err != nil {
slog.WarnContext(ctx, "failed to sync filesystem templates", "error", err)
@@ -1096,122 +1089,6 @@ func (s *TemplateService) syncFilesystemTemplatesInternal(ctx context.Context) e
return nil
}
-func (s *TemplateService) getGlobalVariablesPath(ctx context.Context) (string, error) {
- projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))
- if err != nil {
- return "", fmt.Errorf("failed to get projects directory: %w", err)
- }
-
- return filepath.Join(projectsDirectory, ".env.global"), nil
-}
-
-func (s *TemplateService) GetGlobalVariables(ctx context.Context) ([]env.Variable, error) {
- envPath, err := s.getGlobalVariablesPath(ctx)
- if err != nil {
- return nil, err
- }
-
- if _, err := os.Stat(envPath); os.IsNotExist(err) {
- slog.DebugContext(ctx, "Global variables file does not exist yet", "path", envPath)
- return []env.Variable{}, nil
- }
-
- file, err := os.Open(envPath)
- if err != nil {
- return nil, fmt.Errorf("failed to open global variables file: %w", err)
- }
- defer func() { _ = file.Close() }()
-
- vars := []env.Variable{}
- scanner := bufio.NewScanner(file)
- lineNum := 0
-
- for scanner.Scan() {
- lineNum++
- line := strings.TrimSpace(scanner.Text())
-
- if line == "" || strings.HasPrefix(line, "#") {
- continue
- }
-
- parts := strings.SplitN(line, "=", 2)
- if len(parts) != 2 {
- slog.WarnContext(ctx, "Skipping invalid line in global variables file",
- "line", lineNum,
- "content", line)
- continue
- }
-
- key := strings.TrimSpace(parts[0])
- value := strings.TrimSpace(parts[1])
-
- if len(value) >= 2 {
- if (strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`)) ||
- (strings.HasPrefix(value, `'`) && strings.HasSuffix(value, `'`)) {
- value = value[1 : len(value)-1]
- }
- }
-
- vars = append(vars, env.Variable{
- Key: key,
- Value: value,
- })
- }
-
- if err := scanner.Err(); err != nil {
- return nil, fmt.Errorf("error reading global variables file: %w", err)
- }
-
- return vars, nil
-}
-
-func (s *TemplateService) UpdateGlobalVariables(ctx context.Context, vars []env.Variable) error {
- envPath, err := s.getGlobalVariablesPath(ctx)
- if err != nil {
- return err
- }
-
- projectsDirectory := filepath.Dir(envPath)
- if err := os.MkdirAll(projectsDirectory, common.DirPerm); err != nil {
- return fmt.Errorf("failed to create projects directory: %w", err)
- }
-
- var builder strings.Builder
- builder.WriteString("# Global Environment Variables\n")
- builder.WriteString("# These variables are available to all projects\n")
- builder.WriteString("# Last updated: ")
- builder.WriteString(time.Now().Format(time.RFC3339))
- builder.WriteString("\n\n")
-
- for _, v := range vars {
- if strings.TrimSpace(v.Key) == "" {
- continue
- }
-
- key := strings.TrimSpace(v.Key)
- if !envKeyPattern.MatchString(key) {
- return &common.InvalidEnvKeyError{Key: v.Key}
- }
- value := strings.TrimSpace(v.Value)
-
- if strings.ContainsAny(value, " \t\n\r#") {
- value = fmt.Sprintf(`"%s"`, strings.ReplaceAll(value, `"`, `\"`))
- }
-
- _, _ = fmt.Fprintf(&builder, "%s=%s\n", key, value)
- }
-
- if err := projects.WriteFileWithPerm(envPath, builder.String(), common.FilePerm); err != nil {
- return fmt.Errorf("failed to write global variables file: %w", err)
- }
-
- slog.InfoContext(ctx, "Updated global variables",
- "path", envPath,
- "count", len(vars))
-
- return nil
-}
-
// ParseComposeServices extracts service names from a compose file content using compose-go
func (s *TemplateService) ParseComposeServices(ctx context.Context, composeContent string) []string {
if composeContent == "" {
diff --git a/backend/internal/services/template_service_test.go b/backend/internal/services/template_service_test.go
index ddef6d153..cc30370da 100644
--- a/backend/internal/services/template_service_test.go
+++ b/backend/internal/services/template_service_test.go
@@ -22,7 +22,6 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
- envtypes "github.com/getarcaneapp/arcane/types/v2/env"
tmpl "github.com/getarcaneapp/arcane/types/v2/template"
)
@@ -498,25 +497,3 @@ func minimalSettingsServiceForTest(t *testing.T) *SettingsService {
require.NoError(t, err)
return svc
}
-
-func TestUpdateGlobalVariables_RejectsNewlineInjectionKey(t *testing.T) {
- projectsDir := t.TempDir()
-
- db, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})
- require.NoError(t, err)
- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))
- dbWrap := &database.DB{DB: db}
- settingsSvc, err := NewSettingsService(context.Background(), dbWrap)
- require.NoError(t, err)
- require.NoError(t, settingsSvc.UpdateSetting(context.Background(), "projectsDirectory", projectsDir))
-
- service := &TemplateService{db: dbWrap, settingsService: settingsSvc}
-
- err = service.UpdateGlobalVariables(context.Background(), []envtypes.Variable{
- {Key: "BENIGN\nINJECTED", Value: "x"},
- })
- require.True(t, common.IsInvalidEnvKeyError(err), "expected InvalidEnvKeyError, got %v", err)
-
- _, statErr := os.Stat(filepath.Join(projectsDir, ".env.global"))
- require.True(t, os.IsNotExist(statErr), ".env.global must not be written on validation failure")
-}
diff --git a/backend/internal/services/variable_service.go b/backend/internal/services/variable_service.go
new file mode 100644
index 000000000..1a1b5ffc3
--- /dev/null
+++ b/backend/internal/services/variable_service.go
@@ -0,0 +1,792 @@
+package services
+
+import (
+ "bufio"
+ "context"
+ json "encoding/json/v2"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"
+ "github.com/getarcaneapp/arcane/types/v2/env"
+ "go.getarcane.app/sys/crypto"
+ "gorm.io/gorm"
+)
+
+// envKeyPattern is the POSIX env-name shape used to validate variable keys
+// before they are persisted to .env.global. Keys that do not match are
+// rejected with a common.InvalidEnvKeyError.
+var envKeyPattern = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
+
+const (
+ globalVariablesImportedKVPrefix = "globalvars:imported:"
+ agentVariablesPath = "/api/environments/0/templates/variables"
+ variableSyncTimeout = 15 * time.Second
+)
+
+// VariableService manages manager-level global variables (DB source of truth)
+// and materializes each environment's effective set into that environment's
+// .env.global file: locally via TemplateService, remotely via the existing
+// agent variables endpoint.
+type VariableService struct {
+ db *database.DB
+ environmentService *EnvironmentService
+ settingsService *SettingsService
+ kvService *KVService
+
+ statusMu sync.RWMutex
+ syncStatus map[string]env.EnvironmentSyncStatus
+}
+
+func NewVariableService(db *database.DB, environmentService *EnvironmentService, settingsService *SettingsService, kvService *KVService) *VariableService {
+ return &VariableService{
+ db: db,
+ environmentService: environmentService,
+ settingsService: settingsService,
+ kvService: kvService,
+ syncStatus: make(map[string]env.EnvironmentSyncStatus),
+ }
+}
+
+//
+// CRUD
+//
+
+func (s *VariableService) ListVariables(ctx context.Context) ([]env.GlobalVariable, error) {
+ variables, err := s.loadVariablesInternal(ctx)
+ if err != nil {
+ return nil, &common.GlobalVariablesRetrievalError{Err: err}
+ }
+
+ result := make([]env.GlobalVariable, 0, len(variables))
+ for _, variable := range variables {
+ result = append(result, globalVariableToDTOInternal(variable))
+ }
+ return result, nil
+}
+
+func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlobalVariableRequest) (*env.GlobalVariable, error) {
+ key := strings.TrimSpace(req.Key)
+ if !envKeyPattern.MatchString(key) {
+ return nil, &common.InvalidEnvKeyError{Key: req.Key}
+ }
+
+ envIDs, err := s.normalizeScopeInternal(ctx, req.AllEnvironments, req.EnvironmentIDs)
+ if err != nil {
+ return nil, err
+ }
+ allEnvironments := len(envIDs) == 0
+
+ value := req.Value
+ if req.IsSecret {
+ if value, err = crypto.Encrypt(value); err != nil {
+ return nil, &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to encrypt secret value: %w", err)}
+ }
+ }
+
+ variable := models.GlobalVariable{
+ Key: key,
+ Value: value,
+ IsSecret: req.IsSecret,
+ AllEnvironments: allEnvironments,
+ }
+
+ err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := s.validateScopeConflictInternal(tx, key, "", allEnvironments, envIDs); err != nil {
+ return err
+ }
+ if err := tx.Omit("Environments").Create(&variable).Error; err != nil {
+ return fmt.Errorf("failed to create global variable: %w", err)
+ }
+ return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)
+ })
+ if err != nil {
+ return nil, wrapVariableMutationErrorInternal(err)
+ }
+
+ variable.Environments = environmentsFromIDsInternal(envIDs)
+ dto := globalVariableToDTOInternal(variable)
+ return &dto, nil
+}
+
+func (s *VariableService) UpdateVariable(ctx context.Context, id string, req env.UpdateGlobalVariableRequest) (*env.GlobalVariable, error) {
+ var variable models.GlobalVariable
+ if err := s.db.WithContext(ctx).Preload("Environments").First(&variable, "id = ?", id).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, &common.GlobalVariableNotFoundError{}
+ }
+ return nil, &common.GlobalVariablesRetrievalError{Err: err}
+ }
+
+ key := variable.Key
+ if req.Key != nil {
+ key = strings.TrimSpace(*req.Key)
+ if !envKeyPattern.MatchString(key) {
+ return nil, &common.InvalidEnvKeyError{Key: *req.Key}
+ }
+ }
+
+ isSecret := variable.IsSecret
+ if req.IsSecret != nil {
+ isSecret = *req.IsSecret
+ }
+
+ value, err := resolveUpdatedValueInternal(&variable, req.Value, isSecret)
+ if err != nil {
+ return nil, err
+ }
+
+ envIDs, allEnvironments, err := s.resolveUpdatedScopeInternal(ctx, &variable, req)
+ if err != nil {
+ return nil, err
+ }
+
+ variable.Key = key
+ variable.Value = value
+ variable.IsSecret = isSecret
+ variable.AllEnvironments = allEnvironments
+
+ err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := s.validateScopeConflictInternal(tx, key, variable.ID, allEnvironments, envIDs); err != nil {
+ return err
+ }
+ if err := tx.Omit("Environments").Save(&variable).Error; err != nil {
+ return fmt.Errorf("failed to update global variable: %w", err)
+ }
+ return replaceVariableScopeRowsInternal(tx, variable.ID, envIDs)
+ })
+ if err != nil {
+ return nil, wrapVariableMutationErrorInternal(err)
+ }
+
+ variable.Environments = environmentsFromIDsInternal(envIDs)
+ dto := globalVariableToDTOInternal(variable)
+ return &dto, nil
+}
+
+// resolveUpdatedValueInternal computes the stored value for an update:
+// encrypts when the result is secret and enforces that a secret cannot be
+// made readable without a replacement value (revealing the stored one).
+func resolveUpdatedValueInternal(variable *models.GlobalVariable, reqValue *string, isSecret bool) (string, error) {
+ if variable.IsSecret && !isSecret && reqValue == nil {
+ return "", &common.GlobalVariableSecretValueRequiredError{}
+ }
+
+ switch {
+ case reqValue != nil:
+ if !isSecret {
+ return *reqValue, nil
+ }
+ encrypted, err := crypto.Encrypt(*reqValue)
+ if err != nil {
+ return "", &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to encrypt secret value: %w", err)}
+ }
+ return encrypted, nil
+ case isSecret && !variable.IsSecret:
+ // Readable value becoming secret keeps its current plaintext, encrypted.
+ encrypted, err := crypto.Encrypt(variable.Value)
+ if err != nil {
+ return "", &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to encrypt secret value: %w", err)}
+ }
+ return encrypted, nil
+ default:
+ return variable.Value, nil
+ }
+}
+
+// resolveUpdatedScopeInternal merges the requested scope change (if any) with
+// the variable's current scope and normalizes it.
+func (s *VariableService) resolveUpdatedScopeInternal(ctx context.Context, variable *models.GlobalVariable, req env.UpdateGlobalVariableRequest) ([]string, bool, error) {
+ envIDs := scopedEnvironmentIDsInternal(variable.Environments)
+ if req.AllEnvironments == nil && req.EnvironmentIDs == nil {
+ return envIDs, variable.AllEnvironments, nil
+ }
+
+ requestedAll := variable.AllEnvironments
+ if req.AllEnvironments != nil {
+ requestedAll = *req.AllEnvironments
+ }
+ requestedIDs := envIDs
+ if req.EnvironmentIDs != nil {
+ requestedIDs = *req.EnvironmentIDs
+ }
+
+ normalized, err := s.normalizeScopeInternal(ctx, requestedAll, requestedIDs)
+ if err != nil {
+ return nil, false, err
+ }
+ return normalized, len(normalized) == 0, nil
+}
+
+func (s *VariableService) DeleteVariable(ctx context.Context, id string) error {
+ err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ result := tx.Delete(&models.GlobalVariable{}, "id = ?", id)
+ if result.Error != nil {
+ return fmt.Errorf("failed to delete global variable: %w", result.Error)
+ }
+ if result.RowsAffected == 0 {
+ return &common.GlobalVariableNotFoundError{}
+ }
+ return tx.Exec("DELETE FROM global_variable_environments WHERE global_variable_id = ?", id).Error
+ })
+ if err != nil {
+ return wrapVariableMutationErrorInternal(err)
+ }
+ return nil
+}
+
+//
+// Materialization
+//
+
+// resolveEffectiveVariablesInternal computes the variable set for one
+// environment: all-environment variables first, env-scoped variables override.
+// Secret values are decrypted; variables that fail to decrypt are skipped.
+func (s *VariableService) resolveEffectiveVariablesInternal(ctx context.Context, envID string) ([]env.Variable, error) {
+ variables, err := s.loadVariablesInternal(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ effective := make(map[string]string)
+ for _, scoped := range []bool{false, true} {
+ for _, variable := range variables {
+ if variable.AllEnvironments == scoped {
+ continue
+ }
+ if scoped && !slices.Contains(scopedEnvironmentIDsInternal(variable.Environments), envID) {
+ continue
+ }
+ value := variable.Value
+ if variable.IsSecret {
+ decrypted, err := crypto.Decrypt(value)
+ if err != nil {
+ slog.WarnContext(ctx, "Failed to decrypt global variable for sync; skipping",
+ "variable_id", variable.ID, "key", variable.Key, "error", err)
+ continue
+ }
+ value = decrypted
+ }
+ effective[variable.Key] = value
+ }
+ }
+
+ keys := make([]string, 0, len(effective))
+ for key := range effective {
+ keys = append(keys, key)
+ }
+ slices.Sort(keys)
+
+ result := make([]env.Variable, 0, len(effective))
+ for _, key := range keys {
+ result = append(result, env.Variable{Key: key, Value: effective[key]})
+ }
+ return result, nil
+}
+
+// SyncEnvironment materializes the effective variable set into one
+// environment's .env.global. Remote environments are imported once before the
+// first overwrite so pre-existing per-env variables are preserved.
+func (s *VariableService) SyncEnvironment(ctx context.Context, envID string) error {
+ err := s.syncEnvironmentInternal(ctx, envID)
+ s.recordSyncStatusInternal(envID, err)
+ return err
+}
+
+func (s *VariableService) syncEnvironmentInternal(ctx context.Context, envID string) error {
+ if envID != localEnvironmentID {
+ if err := s.importRemoteLegacyVarsOnceInternal(ctx, envID); err != nil {
+ return fmt.Errorf("failed to import existing variables from environment %s: %w", envID, err)
+ }
+ }
+
+ vars, err := s.resolveEffectiveVariablesInternal(ctx, envID)
+ if err != nil {
+ return err
+ }
+
+ if envID == localEnvironmentID {
+ return s.WriteLocalEnvFile(ctx, vars)
+ }
+
+ body, err := json.Marshal(env.Summary{Variables: vars})
+ if err != nil {
+ return fmt.Errorf("failed to marshal variables for sync: %w", err)
+ }
+
+ var out struct {
+ Success bool `json:"success"`
+ }
+ return s.environmentService.ProxyJSONRequest(ctx, envID, http.MethodPut, agentVariablesPath, body, &out)
+}
+
+// syncTargetsInternal returns the local environment plus every enabled
+// environment, deduplicated.
+func (s *VariableService) syncTargetsInternal(ctx context.Context) []string {
+ envIDs, err := s.environmentService.listEnabledEnvironmentIDsInternal(ctx)
+ if err != nil {
+ slog.ErrorContext(ctx, "Failed to list environments for global variable sync", "error", err)
+ envIDs = nil
+ }
+ if !slices.Contains(envIDs, localEnvironmentID) {
+ envIDs = append([]string{localEnvironmentID}, envIDs...)
+ }
+ return envIDs
+}
+
+// SyncAll pushes the effective variable set to the local environment and every
+// enabled remote environment in parallel, waiting for all of them. Failures
+// are recorded per environment and never abort the other pushes.
+func (s *VariableService) SyncAll(ctx context.Context) []env.EnvironmentSyncStatus {
+ s.syncEnvironmentsInternal(ctx, s.syncTargetsInternal(ctx))
+ return s.SyncStatuses()
+}
+
+// SyncAllBackground materializes the local environment synchronously (a fast
+// file write, no network) and pushes to remote environments in the background,
+// so mutation requests never block on slow or unreachable agents. Remotes are
+// reported as "pending" until the background push records their result.
+func (s *VariableService) SyncAllBackground(ctx context.Context) []env.EnvironmentSyncStatus {
+ if err := s.SyncEnvironment(ctx, localEnvironmentID); err != nil {
+ slog.WarnContext(ctx, "Failed to sync global variables locally", "error", err)
+ }
+
+ remoteIDs := slices.DeleteFunc(s.syncTargetsInternal(ctx), func(id string) bool { return id == localEnvironmentID })
+ for _, envID := range remoteIDs {
+ s.recordSyncPendingInternal(envID)
+ }
+
+ bgCtx := context.WithoutCancel(ctx)
+ go s.syncEnvironmentsInternal(bgCtx, remoteIDs)
+
+ return s.SyncStatuses()
+}
+
+func (s *VariableService) syncEnvironmentsInternal(ctx context.Context, envIDs []string) {
+ var wg sync.WaitGroup
+ for _, envID := range envIDs {
+ wg.Go(func() {
+ syncCtx, cancel := context.WithTimeout(ctx, variableSyncTimeout)
+ defer cancel()
+ if err := s.SyncEnvironment(syncCtx, envID); err != nil {
+ slog.WarnContext(syncCtx, "Failed to sync global variables to environment", "environment_id", envID, "error", err)
+ }
+ })
+ }
+ wg.Wait()
+}
+
+func (s *VariableService) SyncStatuses() []env.EnvironmentSyncStatus {
+ s.statusMu.RLock()
+ defer s.statusMu.RUnlock()
+
+ statuses := make([]env.EnvironmentSyncStatus, 0, len(s.syncStatus))
+ for _, status := range s.syncStatus {
+ statuses = append(statuses, status)
+ }
+ slices.SortFunc(statuses, func(a, b env.EnvironmentSyncStatus) int {
+ return strings.Compare(a.EnvironmentID, b.EnvironmentID)
+ })
+ return statuses
+}
+
+func (s *VariableService) recordSyncPendingInternal(envID string) {
+ s.statusMu.Lock()
+ status := env.EnvironmentSyncStatus{EnvironmentID: envID, Status: "pending"}
+ if previous, ok := s.syncStatus[envID]; ok {
+ status.LastSyncedAt = previous.LastSyncedAt
+ }
+ s.syncStatus[envID] = status
+ s.statusMu.Unlock()
+}
+
+func (s *VariableService) recordSyncStatusInternal(envID string, err error) {
+ status := env.EnvironmentSyncStatus{EnvironmentID: envID, Status: "synced"}
+ if err != nil {
+ status.Status = "error"
+ status.Error = err.Error()
+ } else {
+ now := time.Now()
+ status.LastSyncedAt = &now
+ }
+
+ s.statusMu.Lock()
+ if err != nil {
+ if previous, ok := s.syncStatus[envID]; ok {
+ status.LastSyncedAt = previous.LastSyncedAt
+ }
+ }
+ s.syncStatus[envID] = status
+ s.statusMu.Unlock()
+}
+
+//
+// Local .env.global file primitives (moved from TemplateService). These back
+// the local materialization and the agent-side variables endpoint.
+//
+
+func (s *VariableService) localEnvFilePathInternal(ctx context.Context) (string, error) {
+ projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))
+ if err != nil {
+ return "", fmt.Errorf("failed to get projects directory: %w", err)
+ }
+
+ return filepath.Join(projectsDirectory, projects.GlobalEnvFileName), nil
+}
+
+func (s *VariableService) ReadLocalEnvFile(ctx context.Context) ([]env.Variable, error) {
+ envPath, err := s.localEnvFilePathInternal(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ if _, err := os.Stat(envPath); os.IsNotExist(err) {
+ slog.DebugContext(ctx, "Global variables file does not exist yet", "path", envPath)
+ return []env.Variable{}, nil
+ }
+
+ file, err := os.Open(envPath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open global variables file: %w", err)
+ }
+ defer func() { _ = file.Close() }()
+
+ vars := []env.Variable{}
+ scanner := bufio.NewScanner(file)
+ lineNum := 0
+
+ for scanner.Scan() {
+ lineNum++
+ line := strings.TrimSpace(scanner.Text())
+
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+
+ parts := strings.SplitN(line, "=", 2)
+ if len(parts) != 2 {
+ slog.WarnContext(ctx, "Skipping invalid line in global variables file",
+ "line", lineNum,
+ "content", line)
+ continue
+ }
+
+ key := strings.TrimSpace(parts[0])
+ value := strings.TrimSpace(parts[1])
+
+ if len(value) >= 2 {
+ if (strings.HasPrefix(value, `"`) && strings.HasSuffix(value, `"`)) ||
+ (strings.HasPrefix(value, `'`) && strings.HasSuffix(value, `'`)) {
+ value = value[1 : len(value)-1]
+ }
+ }
+
+ vars = append(vars, env.Variable{
+ Key: key,
+ Value: value,
+ })
+ }
+
+ if err := scanner.Err(); err != nil {
+ return nil, fmt.Errorf("error reading global variables file: %w", err)
+ }
+
+ return vars, nil
+}
+
+func (s *VariableService) WriteLocalEnvFile(ctx context.Context, vars []env.Variable) error {
+ envPath, err := s.localEnvFilePathInternal(ctx)
+ if err != nil {
+ return err
+ }
+
+ projectsDirectory := filepath.Dir(envPath)
+ if err := os.MkdirAll(projectsDirectory, common.DirPerm); err != nil {
+ return fmt.Errorf("failed to create projects directory: %w", err)
+ }
+
+ var builder strings.Builder
+ builder.WriteString("# Global Environment Variables\n")
+ builder.WriteString("# These variables are available to all projects\n")
+ builder.WriteString("# Last updated: ")
+ builder.WriteString(time.Now().Format(time.RFC3339))
+ builder.WriteString("\n\n")
+
+ for _, v := range vars {
+ if strings.TrimSpace(v.Key) == "" {
+ continue
+ }
+
+ key := strings.TrimSpace(v.Key)
+ if !envKeyPattern.MatchString(key) {
+ return &common.InvalidEnvKeyError{Key: v.Key}
+ }
+ // The value is written verbatim: leading/trailing whitespace is
+ // intentional and survives inside the quoted form below.
+ value := v.Value
+
+ if strings.ContainsAny(value, " \t\n\r#") {
+ value = fmt.Sprintf(`"%s"`, strings.ReplaceAll(value, `"`, `\"`))
+ }
+
+ _, _ = fmt.Fprintf(&builder, "%s=%s\n", key, value)
+ }
+
+ if err := projects.WriteFileWithPerm(envPath, builder.String(), common.FilePerm); err != nil {
+ return fmt.Errorf("failed to write global variables file: %w", err)
+ }
+
+ slog.InfoContext(ctx, "Updated global variables",
+ "path", envPath,
+ "count", len(vars))
+
+ return nil
+}
+
+//
+// One-time import of pre-existing .env.global contents
+//
+
+// ImportLegacyLocalEnvFile imports the manager's existing .env.global entries
+// as all-environment readable variables before the first materialization
+// overwrites the file. Runs once, guarded by a KV flag.
+func (s *VariableService) ImportLegacyLocalEnvFile(ctx context.Context) error {
+ flag := globalVariablesImportedKVPrefix + localEnvironmentID
+ imported, err := s.kvService.GetBool(ctx, flag, false)
+ if err != nil {
+ return err
+ }
+ if imported {
+ return nil
+ }
+
+ vars, err := s.ReadLocalEnvFile(ctx)
+ if err != nil {
+ return err
+ }
+ if err := s.importVariablesInternal(ctx, vars, ""); err != nil {
+ return err
+ }
+
+ return s.kvService.SetBool(ctx, flag, true)
+}
+
+// importRemoteLegacyVarsOnceInternal pulls a remote environment's current
+// variables before the manager's first push and stores any key the manager
+// would not already produce for that environment as an env-scoped variable.
+// An import failure aborts the push so existing agent data is never wiped.
+func (s *VariableService) importRemoteLegacyVarsOnceInternal(ctx context.Context, envID string) error {
+ flag := globalVariablesImportedKVPrefix + envID
+ imported, err := s.kvService.GetBool(ctx, flag, false)
+ if err != nil {
+ return err
+ }
+ if imported {
+ return nil
+ }
+
+ var out struct {
+ Success bool `json:"success"`
+ Data []env.Variable `json:"data"`
+ }
+ if err := s.environmentService.ProxyJSONRequest(ctx, envID, http.MethodGet, agentVariablesPath, nil, &out); err != nil {
+ return err
+ }
+
+ if err := s.importVariablesInternal(ctx, out.Data, envID); err != nil {
+ return err
+ }
+
+ return s.kvService.SetBool(ctx, flag, true)
+}
+
+// importVariablesInternal inserts legacy entries that the DB does not cover
+// yet. An empty scopeEnvID imports as all-environments; otherwise the entry is
+// scoped to that single environment.
+func (s *VariableService) importVariablesInternal(ctx context.Context, vars []env.Variable, scopeEnvID string) error {
+ if len(vars) == 0 {
+ return nil
+ }
+
+ existing, err := s.loadVariablesInternal(ctx)
+ if err != nil {
+ return err
+ }
+ covered := make(map[string]bool, len(existing))
+ for _, variable := range existing {
+ if variable.AllEnvironments || scopeEnvID == "" ||
+ slices.Contains(scopedEnvironmentIDsInternal(variable.Environments), scopeEnvID) {
+ covered[variable.Key] = true
+ }
+ }
+
+ for _, entry := range vars {
+ key := strings.TrimSpace(entry.Key)
+ if key == "" || covered[key] || !envKeyPattern.MatchString(key) {
+ continue
+ }
+
+ variable := models.GlobalVariable{
+ Key: key,
+ Value: entry.Value,
+ AllEnvironments: scopeEnvID == "",
+ }
+ err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := tx.Omit("Environments").Create(&variable).Error; err != nil {
+ return err
+ }
+ if scopeEnvID == "" {
+ return nil
+ }
+ return replaceVariableScopeRowsInternal(tx, variable.ID, []string{scopeEnvID})
+ })
+ if err != nil {
+ return fmt.Errorf("failed to import legacy variable %q: %w", key, err)
+ }
+ covered[key] = true
+ slog.InfoContext(ctx, "Imported legacy global variable", "key", key, "environment_id", scopeEnvID)
+ }
+
+ return nil
+}
+
+//
+// Helpers
+//
+
+func (s *VariableService) loadVariablesInternal(ctx context.Context) ([]models.GlobalVariable, error) {
+ var variables []models.GlobalVariable
+ if err := s.db.WithContext(ctx).Preload("Environments").Order("key").Find(&variables).Error; err != nil {
+ return nil, fmt.Errorf("failed to load global variables: %w", err)
+ }
+ return variables, nil
+}
+
+// normalizeScopeInternal validates the requested scope and returns the
+// deduplicated environment ID list ([] means all environments).
+func (s *VariableService) normalizeScopeInternal(ctx context.Context, allEnvironments bool, envIDs []string) ([]string, error) {
+ if allEnvironments {
+ return nil, nil
+ }
+
+ unique := make([]string, 0, len(envIDs))
+ for _, id := range envIDs {
+ id = strings.TrimSpace(id)
+ if id != "" && !slices.Contains(unique, id) {
+ unique = append(unique, id)
+ }
+ }
+ // An explicitly specific scope with no environments must not silently
+ // widen to all environments.
+ if len(unique) == 0 {
+ return nil, &common.GlobalVariableScopeRequiredError{}
+ }
+
+ var count int64
+ if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil {
+ return nil, &common.GlobalVariablesUpdateError{Err: fmt.Errorf("failed to validate environment scope: %w", err)}
+ }
+ if count != int64(len(unique)) {
+ return nil, &common.GlobalVariablesUpdateError{Err: errors.New("scope references unknown environments")}
+ }
+ return unique, nil
+}
+
+// validateScopeConflictInternal enforces the duplicate-key rule: a key may
+// exist once per overlapping scope. The same key as both an all-environments
+// variable and an env-scoped variable is allowed (that is the override).
+func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key string, excludeID string, allEnvironments bool, envIDs []string) error {
+ var others []models.GlobalVariable
+ query := tx.Preload("Environments").Where("key = ?", key)
+ if excludeID != "" {
+ query = query.Where("id <> ?", excludeID)
+ }
+ if err := query.Find(&others).Error; err != nil {
+ return fmt.Errorf("failed to check for conflicting variables: %w", err)
+ }
+
+ for _, other := range others {
+ if allEnvironments != other.AllEnvironments {
+ continue
+ }
+ if allEnvironments {
+ return &common.GlobalVariableConflictError{Key: key}
+ }
+ otherIDs := scopedEnvironmentIDsInternal(other.Environments)
+ for _, id := range envIDs {
+ if slices.Contains(otherIDs, id) {
+ return &common.GlobalVariableConflictError{Key: key}
+ }
+ }
+ }
+ return nil
+}
+
+// replaceVariableScopeRowsInternal rewrites the join rows explicitly instead
+// of relying on FK cascades (the sqlite FK pragma is DSN-dependent).
+func replaceVariableScopeRowsInternal(tx *gorm.DB, variableID string, envIDs []string) error {
+ if err := tx.Exec("DELETE FROM global_variable_environments WHERE global_variable_id = ?", variableID).Error; err != nil {
+ return fmt.Errorf("failed to clear variable scope: %w", err)
+ }
+ for _, envID := range envIDs {
+ if err := tx.Exec("INSERT INTO global_variable_environments (global_variable_id, environment_id) VALUES (?, ?)", variableID, envID).Error; err != nil {
+ return fmt.Errorf("failed to set variable scope: %w", err)
+ }
+ }
+ return nil
+}
+
+func wrapVariableMutationErrorInternal(err error) error {
+ if err == nil ||
+ common.IsGlobalVariableConflictError(err) ||
+ common.IsGlobalVariableNotFoundError(err) ||
+ common.IsInvalidEnvKeyError(err) {
+ return err
+ }
+ return &common.GlobalVariablesUpdateError{Err: err}
+}
+
+func scopedEnvironmentIDsInternal(environments []models.Environment) []string {
+ ids := make([]string, 0, len(environments))
+ for _, environment := range environments {
+ ids = append(ids, environment.ID)
+ }
+ return ids
+}
+
+func environmentsFromIDsInternal(envIDs []string) []models.Environment {
+ environments := make([]models.Environment, 0, len(envIDs))
+ for _, id := range envIDs {
+ environments = append(environments, models.Environment{BaseModel: models.BaseModel{ID: id}})
+ }
+ return environments
+}
+
+func globalVariableToDTOInternal(variable models.GlobalVariable) env.GlobalVariable {
+ value := variable.Value
+ if variable.IsSecret {
+ value = ""
+ }
+ return env.GlobalVariable{
+ ID: variable.ID,
+ Key: variable.Key,
+ Value: value,
+ IsSecret: variable.IsSecret,
+ AllEnvironments: variable.AllEnvironments,
+ EnvironmentIDs: scopedEnvironmentIDsInternal(variable.Environments),
+ CreatedAt: variable.CreatedAt,
+ UpdatedAt: variable.UpdatedAt,
+ }
+}
diff --git a/backend/internal/services/variable_service_test.go b/backend/internal/services/variable_service_test.go
new file mode 100644
index 000000000..602ad5d3c
--- /dev/null
+++ b/backend/internal/services/variable_service_test.go
@@ -0,0 +1,158 @@
+package services
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/models"
+ envtypes "github.com/getarcaneapp/arcane/types/v2/env"
+ sqlite "github.com/libtnb/sqlite"
+ "github.com/stretchr/testify/require"
+ "go.getarcane.app/sys/crypto"
+ "gorm.io/gorm"
+)
+
+func setupVariableServiceTest(t *testing.T) (*VariableService, *database.DB, string) {
+ t.Helper()
+
+ dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()))
+ db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
+ require.NoError(t, err)
+ require.NoError(t, db.AutoMigrate(
+ &models.GlobalVariable{},
+ &models.Environment{},
+ &models.KVEntry{},
+ &models.SettingVariable{},
+ ))
+
+ sqlDB, err := db.DB()
+ require.NoError(t, err)
+ sqlDB.SetMaxOpenConns(1)
+ sqlDB.SetMaxIdleConns(1)
+
+ crypto.InitEncryption(&crypto.Config{
+ EncryptionKey: "test-encryption-key-for-testing-32bytes-min",
+ Environment: "test",
+ })
+
+ projectsDir := t.TempDir()
+ dbWrap := &database.DB{DB: db}
+ settingsSvc, err := NewSettingsService(context.Background(), dbWrap)
+ require.NoError(t, err)
+ require.NoError(t, settingsSvc.UpdateSetting(context.Background(), "projectsDirectory", projectsDir))
+
+ service := NewVariableService(dbWrap, nil, settingsSvc, NewKVService(dbWrap))
+ return service, dbWrap, projectsDir
+}
+
+func createVariableTestEnvironment(t *testing.T, db *database.DB, id string) {
+ t.Helper()
+ require.NoError(t, db.Create(&models.Environment{
+ BaseModel: models.BaseModel{ID: id},
+ Name: "env-" + id,
+ ApiUrl: "http://env-" + id,
+ Status: "online",
+ Enabled: true,
+ }).Error)
+}
+
+func TestCreateVariable_SecretEncryptedAtRestAndRedactedOnList(t *testing.T) {
+ service, db, _ := setupVariableServiceTest(t)
+ ctx := context.Background()
+
+ created, err := service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
+ Key: "API_TOKEN",
+ Value: "super-secret",
+ IsSecret: true,
+ AllEnvironments: true,
+ })
+ require.NoError(t, err)
+ require.Empty(t, created.Value, "mutation response must not echo the secret value")
+
+ var stored models.GlobalVariable
+ require.NoError(t, db.First(&stored, "id = ?", created.ID).Error)
+ require.NotEqual(t, "super-secret", stored.Value, "secret must not be stored as plaintext")
+ decrypted, err := crypto.Decrypt(stored.Value)
+ require.NoError(t, err)
+ require.Equal(t, "super-secret", decrypted)
+
+ listed, err := service.ListVariables(ctx)
+ require.NoError(t, err)
+ require.Len(t, listed, 1)
+ require.True(t, listed[0].IsSecret)
+ require.Empty(t, listed[0].Value)
+}
+
+func TestResolveEffectiveVariables_EnvScopedOverridesAllEnv(t *testing.T) {
+ service, db, _ := setupVariableServiceTest(t)
+ ctx := context.Background()
+ createVariableTestEnvironment(t, db, "env-a")
+ createVariableTestEnvironment(t, db, "env-b")
+
+ _, err := service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
+ Key: "REGION", Value: "default", AllEnvironments: true,
+ })
+ require.NoError(t, err)
+ _, err = service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
+ Key: "REGION", Value: "eu-west", EnvironmentIDs: []string{"env-a"},
+ })
+ require.NoError(t, err)
+
+ // A second variable with the same key and an overlapping scope is rejected.
+ _, err = service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
+ Key: "REGION", Value: "dup", EnvironmentIDs: []string{"env-a", "env-b"},
+ })
+ require.Error(t, err)
+
+ // A specific scope without environments must not widen to all environments.
+ _, err = service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
+ Key: "NO_SCOPE", Value: "x", AllEnvironments: false, EnvironmentIDs: []string{},
+ })
+ require.True(t, common.IsGlobalVariableScopeRequiredError(err), "expected GlobalVariableScopeRequiredError, got %v", err)
+
+ forA, err := service.resolveEffectiveVariablesInternal(ctx, "env-a")
+ require.NoError(t, err)
+ require.Equal(t, []envtypes.Variable{{Key: "REGION", Value: "eu-west"}}, forA)
+
+ forB, err := service.resolveEffectiveVariablesInternal(ctx, "env-b")
+ require.NoError(t, err)
+ require.Equal(t, []envtypes.Variable{{Key: "REGION", Value: "default"}}, forB)
+}
+
+func TestWriteLocalEnvFile_RejectsNewlineInjectionKey(t *testing.T) {
+ service, _, projectsDir := setupVariableServiceTest(t)
+
+ err := service.WriteLocalEnvFile(context.Background(), []envtypes.Variable{
+ {Key: "BENIGN\nINJECTED", Value: "x"},
+ })
+ require.True(t, common.IsInvalidEnvKeyError(err), "expected InvalidEnvKeyError, got %v", err)
+
+ _, statErr := os.Stat(filepath.Join(projectsDir, ".env.global"))
+ require.True(t, os.IsNotExist(statErr), ".env.global must not be written on validation failure")
+}
+
+func TestSyncEnvironment_LocalWritesEnvGlobalFile(t *testing.T) {
+ service, _, projectsDir := setupVariableServiceTest(t)
+ ctx := context.Background()
+
+ _, err := service.CreateVariable(ctx, envtypes.CreateGlobalVariableRequest{
+ Key: "DB_PASSWORD", Value: "hunter2", IsSecret: true, AllEnvironments: true,
+ })
+ require.NoError(t, err)
+
+ require.NoError(t, service.SyncEnvironment(ctx, "0"))
+
+ content, err := os.ReadFile(filepath.Join(projectsDir, ".env.global"))
+ require.NoError(t, err)
+ require.Contains(t, string(content), "DB_PASSWORD=hunter2", "materialized file must contain the decrypted secret")
+
+ statuses := service.SyncStatuses()
+ require.Len(t, statuses, 1)
+ require.Equal(t, "synced", statuses[0].Status)
+}
diff --git a/backend/resources/migrations/postgres/066_add_global_variables.sql b/backend/resources/migrations/postgres/066_add_global_variables.sql
new file mode 100644
index 000000000..dabe11d6c
--- /dev/null
+++ b/backend/resources/migrations/postgres/066_add_global_variables.sql
@@ -0,0 +1,24 @@
+-- +goose Up
+CREATE TABLE global_variables (
+ id TEXT PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL,
+ updated_at TIMESTAMPTZ,
+ key TEXT NOT NULL,
+ value TEXT NOT NULL DEFAULT '',
+ is_secret BOOLEAN NOT NULL DEFAULT FALSE,
+ all_environments BOOLEAN NOT NULL DEFAULT TRUE
+);
+
+CREATE INDEX idx_global_variables_key ON global_variables(key);
+
+CREATE TABLE global_variable_environments (
+ global_variable_id TEXT NOT NULL REFERENCES global_variables(id) ON DELETE CASCADE,
+ environment_id TEXT NOT NULL REFERENCES environments(id) ON DELETE CASCADE,
+ PRIMARY KEY (global_variable_id, environment_id)
+);
+
+CREATE INDEX idx_global_variable_environments_env ON global_variable_environments(environment_id);
+
+-- +goose Down
+DROP TABLE IF EXISTS global_variable_environments;
+DROP TABLE IF EXISTS global_variables;
diff --git a/backend/resources/migrations/sqlite/066_add_global_variables.sql b/backend/resources/migrations/sqlite/066_add_global_variables.sql
new file mode 100644
index 000000000..015b9c781
--- /dev/null
+++ b/backend/resources/migrations/sqlite/066_add_global_variables.sql
@@ -0,0 +1,24 @@
+-- +goose Up
+CREATE TABLE global_variables (
+ id TEXT PRIMARY KEY,
+ created_at DATETIME NOT NULL,
+ updated_at DATETIME,
+ key TEXT NOT NULL,
+ value TEXT NOT NULL DEFAULT '',
+ is_secret BOOLEAN NOT NULL DEFAULT FALSE,
+ all_environments BOOLEAN NOT NULL DEFAULT TRUE
+);
+
+CREATE INDEX idx_global_variables_key ON global_variables(key);
+
+CREATE TABLE global_variable_environments (
+ global_variable_id TEXT NOT NULL REFERENCES global_variables(id) ON DELETE CASCADE,
+ environment_id TEXT NOT NULL REFERENCES environments(id) ON DELETE CASCADE,
+ PRIMARY KEY (global_variable_id, environment_id)
+);
+
+CREATE INDEX idx_global_variable_environments_env ON global_variable_environments(environment_id);
+
+-- +goose Down
+DROP TABLE IF EXISTS global_variable_environments;
+DROP TABLE IF EXISTS global_variables;
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 771e5df58..3303020c6 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -1748,21 +1748,37 @@
"lifecycle_inline_runner_summary": "(image: {image}, network: {network})",
"common_syncing": "Syncing...",
"variables_title": "Variables",
- "variables_subtitle": "Manage global environment variables that are available to all projects",
- "variables_about_title": "About Global Environment Variables",
- "variables_about_description": "These variables are stored in .env.global at the root of your projects directory and are available to all Docker Compose projects.",
- "variables_count_configured": "{count} variable configured",
- "variables_count_configured_plural": "{count} variables configured",
- "variables_add_button": "Add",
- "variables_no_variables_title": "No environment variables yet",
- "variables_no_variables_description": "Click \"Add\" to create your first variable",
- "variables_no_results_title": "No variables found",
- "variables_no_results_description": "Try a different search term",
+ "variables_subtitle": "Key/value pairs synced to your environments and available to all projects",
+ "variables_no_variables_title": "No variables yet",
+ "variables_no_variables_description": "Add a variable to get started",
"key_placeholder": "KEY",
"value_placeholder": "value",
"variables_duplicate_keys_error": "Duplicate keys found. Please ensure all keys are unique.",
- "variables_save_success": "Global variables saved successfully",
- "variables_save_failed": "Failed to save. Please try again.",
+ "variable": "Variable",
+ "key": "Key",
+ "value": "Value",
+ "all_environments": "All Environments",
+ "all_environments_description": "Available to every environment, including ones added later",
+ "specific_environments": "Specific Environments",
+ "specific_environments_description": "Only synced to the environments you select",
+ "select_at_least_one_environment": "Select at least one environment",
+ "plus_count": "+{count}",
+ "secret": "Secret",
+ "secret_description": "Encrypt the value and hide it after saving",
+ "secret_value_placeholder": "Value hidden — enter a new value to replace it",
+ "secret_new_value_required": "Enter a new value to make this variable readable",
+ "create_variable": "Create Variable",
+ "edit_variable": "Edit Variable",
+ "invalid_key_format": "Keys may only contain letters, numbers, and underscores, and cannot start with a number",
+ "single": "Single",
+ "paste_env": "Paste .env",
+ "paste_env_content": "Paste .env content",
+ "paste_env_placeholder": "DATABASE_URL=postgres://user:pass@host:5432/db\n# comments and blank lines are ignored\nAPI_KEY=abc123",
+ "count_parsed": "{count} parsed",
+ "count_lines_could_not_be_parsed": "{count} line(s) could not be parsed",
+ "paste_env_empty_preview": "Paste KEY=VALUE lines above to preview them here",
+ "count_variables_created": "{count} variables created",
+ "sync_failed_environments": "Saved, but syncing to some environments failed: {envs}",
"log_stream_connection_lost": "Connection to {type} log stream lost",
"log_stream_closed_by_server": "{type} log stream was closed by server",
"log_stream_failed_connect": "Failed to connect to {type} log stream",
diff --git a/frontend/src/lib/components/sheets/environment-multi-select.svelte b/frontend/src/lib/components/sheets/environment-multi-select.svelte
new file mode 100644
index 000000000..3e3e35d75
--- /dev/null
+++ b/frontend/src/lib/components/sheets/environment-multi-select.svelte
@@ -0,0 +1,35 @@
+<script lang="ts">
+ import { Switch } from '$lib/components/ui/switch';
+ import type { Environment } from '$lib/types/environment';
+
+ let {
+ environments,
+ selected = $bindable([]),
+ disabled = false
+ }: {
+ environments: Environment[];
+ selected: string[];
+ disabled?: boolean;
+ } = $props();
+
+ function toggle(id: string, checked: boolean) {
+ if (checked) {
+ if (!selected.includes(id)) selected = [...selected, id];
+ } else {
+ selected = selected.filter((envId) => envId !== id);
+ }
+ }
+</script>
+
+<div class="max-h-48 overflow-y-auto rounded-md border border-border/50">
+ {#each environments as environment (environment.id)}
+ <label class="flex cursor-pointer items-center gap-3 px-3 py-2 hover:bg-accent/40">
+ <span class="min-w-0 flex-1 truncate text-sm">{environment.name}</span>
+ <Switch
+ checked={selected.includes(environment.id)}
+ {disabled}
+ onCheckedChange={(checked) => toggle(environment.id, checked === true)}
+ />
+ </label>
+ {/each}
+</div>
diff --git a/frontend/src/lib/components/sheets/variable-form-sheet.svelte b/frontend/src/lib/components/sheets/variable-form-sheet.svelte
new file mode 100644
index 000000000..e5087e25f
--- /dev/null
+++ b/frontend/src/lib/components/sheets/variable-form-sheet.svelte
@@ -0,0 +1,354 @@
+<script lang="ts">
+ import * as ResponsiveDialog from '$lib/components/ui/responsive-dialog/index.js';
+ import SheetFooterActions from '$lib/components/sheets/sheet-footer-actions.svelte';
+ import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';
+ import EnvironmentMultiSelect from '$lib/components/sheets/environment-multi-select.svelte';
+ import { Button } from '$lib/components/ui/button';
+ import { Input } from '$lib/components/ui/input';
+ import { Label } from '$lib/components/ui/label';
+ import { Textarea } from '$lib/components/ui/textarea';
+ import * as RadioGroup from '$lib/components/ui/radio-group/index.js';
+ import type { Environment } from '$lib/types/environment';
+ import type { GlobalVariable, GlobalVariableCreateDto, GlobalVariableUpdateDto } from '$lib/types/variable';
+ import { parseEnvText, normalizeVariableKeyInput } from '$lib/utils/env-file';
+ import { z } from 'zod/v4';
+ import { createForm, preventDefault } from '$lib/utils/settings';
+ import * as m from '$lib/paraglide/messages.js';
+
+ type VariableFormPayload =
+ | { mode: 'create'; variable: GlobalVariableCreateDto }
+ | { mode: 'edit'; id: string; variable: GlobalVariableUpdateDto }
+ | { mode: 'bulk'; variables: GlobalVariableCreateDto[] };
+
+ let {
+ open = $bindable(false),
+ variableToEdit = $bindable(null),
+ environments,
+ existingVariables = [],
+ isLoading = false,
+ onSubmit
+ }: {
+ open: boolean;
+ variableToEdit: GlobalVariable | null;
+ environments: Environment[];
+ existingVariables?: GlobalVariable[];
+ isLoading?: boolean;
+ onSubmit: (payload: VariableFormPayload) => void;
+ } = $props();
+
+ const isEditMode = $derived(!!variableToEdit);
+
+ let entryMode = $state<'single' | 'bulk'>('single');
+ let scope = $state<'all' | 'specific'>('all');
+ let selectedEnvIds = $state<string[]>([]);
+ let scopeError = $state<string | null>(null);
+ let bulkText = $state('');
+ let bulkSecret = $state(false);
+ let bulkError = $state<string | null>(null);
+
+ const keyPattern = /^[A-Z_][A-Z0-9_]*$/i;
+
+ // Mirrors the backend conflict rule: a key may exist once per overlapping
+ // scope. The same key as both an all-environments variable and an
+ // env-scoped variable is the override mechanism and is allowed.
+ function scopeConflicts(candidateKey: string): boolean {
+ const normalized = candidateKey.trim().toUpperCase();
+ const candidateAll = scope === 'all';
+ return existingVariables.some((existing) => {
+ if (variableToEdit && existing.id === variableToEdit.id) return false;
+ if (existing.key.toUpperCase() !== normalized) return false;
+ if (candidateAll !== existing.allEnvironments) return false;
+ if (candidateAll) return true;
+ return existing.environmentIds.some((id) => selectedEnvIds.includes(id));
+ });
+ }
+
+ const formSchema = $derived.by(() => {
+ const wasSecret = variableToEdit?.isSecret ?? false;
+
+ return z
+ .object({
+ key: z
+ .string()
+ .min(1, m.common_field_required({ field: m.key() }))
+ .regex(keyPattern, m.invalid_key_format())
+ .refine((key) => !scopeConflicts(key), m.variables_duplicate_keys_error()),
+ value: z.string(),
+ isSecret: z.boolean()
+ })
+ .superRefine((data, ctx) => {
+ // A stored secret is never sent back to the client, so turning the
+ // secret flag off requires the user to provide a readable value.
+ if (wasSecret && !data.isSecret && data.value.trim() === '') {
+ ctx.addIssue({ code: 'custom', path: ['value'], message: m.secret_new_value_required() });
+ }
+ });
+ });
+
+ const formData = $derived({
+ key: variableToEdit?.key ?? '',
+ value: variableToEdit ? (variableToEdit.isSecret ? '' : variableToEdit.value) : '',
+ isSecret: variableToEdit?.isSecret ?? false
+ });
+
+ let { inputs, ...form } = $derived(createForm<typeof formSchema>(formSchema, formData));
+
+ const parsed = $derived(parseEnvText(bulkText));
+
+ const bulkDuplicateKeys = $derived.by(() => {
+ // Entries in one paste share a single scope, so repeats within the batch
+ // always conflict; against existing variables the check is scope-aware.
+ const seen = new Set<string>();
+ const duplicates = new Set<string>();
+ for (const entry of parsed.entries) {
+ if (seen.has(entry.key) || scopeConflicts(entry.key)) duplicates.add(entry.key);
+ seen.add(entry.key);
+ }
+ return [...duplicates];
+ });
+
+ $effect(() => {
+ if (open) {
+ const editing = variableToEdit;
+ entryMode = 'single';
+ bulkText = '';
+ bulkSecret = false;
+ bulkError = null;
+ scopeError = null;
+ scope = editing && !editing.allEnvironments && editing.environmentIds.length > 0 ? 'specific' : 'all';
+ selectedEnvIds = editing ? [...editing.environmentIds] : [];
+ }
+ });
+
+ function validateScope(): boolean {
+ scopeError = scope === 'specific' && selectedEnvIds.length === 0 ? m.select_at_least_one_environment() : null;
+ return !scopeError;
+ }
+
+ function scopeDto(): Pick<GlobalVariableCreateDto, 'allEnvironments' | 'environmentIds'> {
+ return scope === 'all'
+ ? { allEnvironments: true, environmentIds: [] }
+ : { allEnvironments: false, environmentIds: [...selectedEnvIds] };
+ }
+
+ function handleSubmit() {
+ const scopeValid = validateScope();
+
+ if (entryMode === 'bulk' && !isEditMode) {
+ bulkError = null;
+ if (parsed.entries.length === 0) {
+ bulkError = m.paste_env_empty_preview();
+ } else if (bulkDuplicateKeys.length > 0) {
+ bulkError = m.variables_duplicate_keys_error();
+ }
+ if (bulkError || !scopeValid) return;
+
+ onSubmit({
+ mode: 'bulk',
+ variables: parsed.entries.map((entry) => ({
+ key: entry.key,
+ value: entry.value,
+ isSecret: bulkSecret,
+ ...scopeDto()
+ }))
+ });
+ return;
+ }
+
+ const data = form.validate();
+ if (!data || !scopeValid) return;
+
+ if (isEditMode && variableToEdit) {
+ const dto: GlobalVariableUpdateDto = { key: data.key, isSecret: data.isSecret, ...scopeDto() };
+ // Editing a secret with an empty value keeps the stored value.
+ if (!(variableToEdit.isSecret && data.value === '')) dto.value = data.value;
+ onSubmit({ mode: 'edit', id: variableToEdit.id, variable: dto });
+ } else {
+ onSubmit({ mode: 'create', variable: { key: data.key, value: data.value, isSecret: data.isSecret, ...scopeDto() } });
+ }
+ }
+
+ function handleOpenChange(newOpenState: boolean) {
+ open = newOpenState;
+ if (!newOpenState) {
+ variableToEdit = null;
+ }
+ }
+</script>
+
+<ResponsiveDialog.Root
+ {open}
+ onOpenChange={handleOpenChange}
+ variant="sheet"
+ title={isEditMode ? m.edit_variable() : m.create_variable()}
+ description={isEditMode ? (variableToEdit?.key ?? '') : m.common_add_description()}
+ contentClass="sm:max-w-[540px]"
+>
+ {#snippet children()}
+ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-6">
+ {#if !isEditMode}
+ <div class="inline-flex w-fit items-center gap-1 rounded-lg border border-border/50 bg-muted/30 p-1">
+ <Button
+ type="button"
+ size="sm"
+ variant={entryMode === 'single' ? 'secondary' : 'ghost'}
+ class="h-7"
+ onclick={() => (entryMode = 'single')}
+ >
+ {m.single()}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ variant={entryMode === 'bulk' ? 'secondary' : 'ghost'}
+ class="h-7"
+ onclick={() => (entryMode = 'bulk')}
+ >
+ {m.paste_env()}
+ </Button>
+ </div>
+ {/if}
+
+ {#if entryMode === 'bulk' && !isEditMode}
+ <div>
+ <Label for="variable-bulk-text">{m.paste_env_content()}</Label>
+ <Textarea
+ id="variable-bulk-text"
+ rows={10}
+ class="mt-2 font-mono text-sm"
+ placeholder={m.paste_env_placeholder()}
+ bind:value={bulkText}
+ />
+ </div>
+
+ <div class="rounded-md border border-border/50">
+ {#if parsed.entries.length === 0}
+ <p class="px-3 py-4 text-sm text-muted-foreground">{m.paste_env_empty_preview()}</p>
+ {:else}
+ <ul class="max-h-48 divide-y divide-border/50 overflow-y-auto">
+ {#each parsed.entries as entry, index (index)}
+ <li class="flex items-center gap-3 px-3 py-1.5 text-sm">
+ <span class="font-mono font-medium">{entry.key}</span>
+ <span class="min-w-0 flex-1 truncate text-right font-mono text-muted-foreground">
+ {bulkSecret ? '••••••••' : entry.value}
+ </span>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+
+ <div class="text-xs text-muted-foreground">
+ <span>{m.count_parsed({ count: parsed.entries.length })}</span>
+ {#if parsed.invalidLines.length > 0}
+ <span> &middot; {m.count_lines_could_not_be_parsed({ count: parsed.invalidLines.length })}</span>
+ {/if}
+ </div>
+
+ {#if bulkDuplicateKeys.length > 0}
+ <p class="text-sm text-destructive">
+ {m.variables_duplicate_keys_error()} ({bulkDuplicateKeys.join(', ')})
+ </p>
+ {:else if bulkError}
+ <p class="text-sm text-destructive">{bulkError}</p>
+ {/if}
+
+ <SwitchWithLabel
+ id="variable-bulk-secret"
+ label={m.secret()}
+ description={m.secret_description()}
+ bind:checked={bulkSecret}
+ />
+
+ {@render scopeSelector()}
+ {:else}
+ <div>
+ <Label for="variable-key">{m.key()}</Label>
+ <Input
+ id="variable-key"
+ type="text"
+ class="mt-2 font-mono"
+ placeholder={m.key_placeholder()}
+ bind:value={$inputs.key.value}
+ oninput={(e) => normalizeVariableKeyInput(e, (value) => ($inputs.key.value = value))}
+ />
+ {#if $inputs.key.error}
+ <p class="mt-1 text-sm text-destructive">{$inputs.key.error}</p>
+ {/if}
+ </div>
+
+ <div>
+ <Label for="variable-value">{m.value()}</Label>
+ <Textarea
+ id="variable-value"
+ rows={3}
+ class="mt-2 font-mono"
+ placeholder={variableToEdit?.isSecret ? m.secret_value_placeholder() : m.value_placeholder()}
+ bind:value={$inputs.value.value}
+ />
+ {#if $inputs.value.error}
+ <p class="mt-1 text-sm text-destructive">{$inputs.value.error}</p>
+ {/if}
+ </div>
+
+ <SwitchWithLabel
+ id="variable-secret"
+ label={m.secret()}
+ description={m.secret_description()}
+ bind:checked={$inputs.isSecret.value}
+ />
+
+ {@render scopeSelector()}
+ {/if}
+ </form>
+ {/snippet}
+
+ {#snippet footer()}
+ <SheetFooterActions
+ bind:open
+ cancelDisabled={isLoading}
+ submitAction={isEditMode ? 'save' : 'create'}
+ submitDisabled={isLoading}
+ submitLoading={isLoading}
+ onSubmit={handleSubmit}
+ submitLabel={isEditMode ? m.common_save_changes() : m.common_add_button({ resource: m.variable() })}
+ />
+ {/snippet}
+</ResponsiveDialog.Root>
+
+{#snippet scopeSelector()}
+ <div>
+ <Label class="mb-0">{m.common_scope()}</Label>
+ <RadioGroup.Root
+ class="mt-2 gap-2"
+ value={scope}
+ onValueChange={(value) => {
+ scope = value as 'all' | 'specific';
+ scopeError = null;
+ }}
+ >
+ <label class="flex cursor-pointer items-start gap-3 rounded-md border border-border/50 p-3 hover:bg-accent/40">
+ <RadioGroup.Item value="all" class="mt-0.5" />
+ <div class="grid gap-1 leading-none">
+ <span class="text-sm font-medium">{m.all_environments()}</span>
+ <span class="text-xs text-muted-foreground">{m.all_environments_description()}</span>
+ </div>
+ </label>
+ <label class="flex cursor-pointer items-start gap-3 rounded-md border border-border/50 p-3 hover:bg-accent/40">
+ <RadioGroup.Item value="specific" class="mt-0.5" />
+ <div class="grid gap-1 leading-none">
+ <span class="text-sm font-medium">{m.specific_environments()}</span>
+ <span class="text-xs text-muted-foreground">{m.specific_environments_description()}</span>
+ </div>
+ </label>
+ </RadioGroup.Root>
+ {#if scope === 'specific'}
+ <div class="mt-2">
+ <EnvironmentMultiSelect {environments} bind:selected={selectedEnvIds} />
+ </div>
+ {/if}
+ {#if scopeError}
+ <p class="mt-1 text-sm text-destructive">{scopeError}</p>
+ {/if}
+ </div>
+{/snippet}
diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.ts
index 230bfb6b9..9f44121a8 100644
--- a/frontend/src/lib/query/query-keys.ts
+++ b/frontend/src/lib/query/query-keys.ts
@@ -62,8 +62,11 @@ export const queryKeys = {
defaults: () => ['templates', 'defaults'] as const,
list: (options: SearchPaginationSortRequest) => ['templates', stableSerialize(options)] as const,
content: (templateId: string) => ['template-content', templateId] as const,
- registries: () => ['template-registries'] as const,
- globalVariables: () => ['templates', 'global-variables'] as const
+ registries: () => ['template-registries'] as const
+ },
+ variables: {
+ all: ['variables'] as const,
+ list: () => ['variables', 'list'] as const
},
notifications: {
settings: () => ['notification-settings'] as const
diff --git a/frontend/src/lib/services/template-service.ts b/frontend/src/lib/services/template-service.ts
index 21f117f15..fb4ddb898 100644
--- a/frontend/src/lib/services/template-service.ts
+++ b/frontend/src/lib/services/template-service.ts
@@ -1,9 +1,7 @@
import BaseAPIService from './api-service';
import type { TemplateRegistry, Template, RemoteRegistry, TemplateContentData } from '$lib/types/swarm';
-import type { Variable } from '$lib/types/shared';
import type { SearchPaginationSortRequest, Paginated } from '$lib/types/shared';
import { transformPaginationParams } from '$lib/utils/tables';
-import { environmentStore } from '$lib/stores/environment.store.svelte';
class TemplateService extends BaseAPIService {
async getTemplates(options?: SearchPaginationSortRequest): Promise<Paginated<Template>> {
@@ -123,17 +121,6 @@ class TemplateService extends BaseAPIService {
});
return response.data?.data;
}
-
- async getGlobalVariables(): Promise<Variable[]> {
- const envId = await environmentStore.getCurrentEnvironmentId();
- const response = await this.api.get(`/environments/${envId}/templates/variables`);
- return response.data?.data ?? [];
- }
-
- async updateGlobalVariables(variables: Variable[]): Promise<void> {
- const envId = await environmentStore.getCurrentEnvironmentId();
- await this.api.put(`/environments/${envId}/templates/variables`, { variables });
- }
}
export const templateService = new TemplateService();
diff --git a/frontend/src/lib/services/variable-service.ts b/frontend/src/lib/services/variable-service.ts
new file mode 100644
index 000000000..b0e03ed96
--- /dev/null
+++ b/frontend/src/lib/services/variable-service.ts
@@ -0,0 +1,39 @@
+import BaseAPIService from './api-service';
+import type {
+ GlobalVariable,
+ GlobalVariableCreateDto,
+ GlobalVariableUpdateDto,
+ VariableMutationResponse
+} from '$lib/types/variable';
+
+class VariableService extends BaseAPIService {
+ async list(): Promise<GlobalVariable[]> {
+ const response = await this.api.get('/variables');
+ return response.data?.data ?? [];
+ }
+
+ async create(dto: GlobalVariableCreateDto): Promise<VariableMutationResponse> {
+ const response = await this.api.post('/variables', dto);
+ return response.data?.data ?? {};
+ }
+
+ async createMany(dtos: GlobalVariableCreateDto[]): Promise<VariableMutationResponse> {
+ let last: VariableMutationResponse = {};
+ for (const dto of dtos) {
+ last = await this.create(dto);
+ }
+ return last;
+ }
+
+ async update(id: string, dto: GlobalVariableUpdateDto): Promise<VariableMutationResponse> {
+ const response = await this.api.put(`/variables/${encodeURIComponent(id)}`, dto);
+ return response.data?.data ?? {};
+ }
+
+ async delete(id: string): Promise<VariableMutationResponse> {
+ const response = await this.api.delete(`/variables/${encodeURIComponent(id)}`);
+ return response.data?.data ?? {};
+ }
+}
+
+export const variableService = new VariableService();
diff --git a/frontend/src/lib/types/shared.ts b/frontend/src/lib/types/shared.ts
index 23e127955..070503a7d 100644
--- a/frontend/src/lib/types/shared.ts
+++ b/frontend/src/lib/types/shared.ts
@@ -63,13 +63,6 @@ export interface EventSeverityCounts {
error: number;
}
-// --- Variables (key/value form helper) ---
-
-export interface Variable {
- key: string;
- value: string;
-}
-
// --- System stats ---
export interface SystemStats {
diff --git a/frontend/src/lib/types/variable.ts b/frontend/src/lib/types/variable.ts
new file mode 100644
index 000000000..e8204988b
--- /dev/null
+++ b/frontend/src/lib/types/variable.ts
@@ -0,0 +1,39 @@
+export interface GlobalVariable {
+ id: string;
+ key: string;
+ value: string; // '' when isSecret (server redacts)
+ isSecret: boolean;
+ allEnvironments: boolean;
+ environmentIds: string[];
+ createdAt: string;
+ updatedAt?: string;
+}
+
+export interface GlobalVariableCreateDto {
+ key: string;
+ value: string;
+ isSecret?: boolean;
+ allEnvironments?: boolean;
+ environmentIds?: string[];
+}
+
+export interface GlobalVariableUpdateDto {
+ key?: string;
+ value?: string; // omitted for secrets = keep stored value
+ isSecret?: boolean;
+ allEnvironments?: boolean;
+ environmentIds?: string[];
+}
+
+export interface VariableEnvSyncResult {
+ environmentId: string;
+ environmentName?: string;
+ status: 'synced' | 'pending' | 'error';
+ error?: string;
+ lastSyncedAt?: string;
+}
+
+export interface VariableMutationResponse {
+ variable?: GlobalVariable;
+ syncResults?: VariableEnvSyncResult[];
+}
diff --git a/frontend/src/lib/utils/env-file.ts b/frontend/src/lib/utils/env-file.ts
new file mode 100644
index 000000000..5c9925b94
--- /dev/null
+++ b/frontend/src/lib/utils/env-file.ts
@@ -0,0 +1,72 @@
+export interface ParsedEnvEntry {
+ key: string;
+ value: string;
+}
+
+export interface ParsedEnvResult {
+ entries: ParsedEnvEntry[];
+ invalidLines: number[]; // 1-based line numbers that could not be parsed
+}
+
+const envKeyPattern = /^[A-Za-z_][A-Za-z0-9_]*$/;
+
+/**
+ * Parses dotenv-style text: skips blanks and # comments, strips an optional
+ * `export ` prefix, splits on the first `=`, unquotes single/double-quoted
+ * values, and strips unquoted trailing comments. Later duplicate keys are kept
+ * as separate entries so callers can surface duplicates instead of silently
+ * keeping one.
+ */
+export function parseEnvText(text: string): ParsedEnvResult {
+ const entries: ParsedEnvEntry[] = [];
+ const invalidLines: number[] = [];
+
+ const lines = text.split(/\r?\n/);
+ for (let i = 0; i < lines.length; i++) {
+ let line = (lines[i] ?? '').trim();
+ if (line === '' || line.startsWith('#')) continue;
+ if (line.startsWith('export ')) line = line.slice('export '.length).trimStart();
+
+ const eqIndex = line.indexOf('=');
+ if (eqIndex <= 0) {
+ invalidLines.push(i + 1);
+ continue;
+ }
+
+ const key = line.slice(0, eqIndex).trim();
+ if (!envKeyPattern.test(key)) {
+ invalidLines.push(i + 1);
+ continue;
+ }
+
+ let value = line.slice(eqIndex + 1).trim();
+ if (value.length >= 2 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) {
+ value = value.slice(1, -1);
+ } else {
+ const commentIndex = value.indexOf(' #');
+ if (commentIndex >= 0) value = value.slice(0, commentIndex).trimEnd();
+ }
+
+ entries.push({ key: key.toUpperCase(), value });
+ }
+
+ return { entries, invalidLines };
+}
+
+/**
+ * Input handler for variable-key fields: uppercases and replaces whitespace
+ * with underscores while preserving the cursor position.
+ */
+export function normalizeVariableKeyInput(event: Event, apply: (value: string) => void): void {
+ const target = event.target as HTMLInputElement;
+ const cursorPos = target.selectionStart ?? 0;
+ const oldLength = target.value.length;
+ const newValue = target.value.toUpperCase().replace(/\s/g, '_');
+
+ apply(newValue);
+
+ requestAnimationFrame(() => {
+ const diff = newValue.length - oldLength;
+ target.setSelectionRange(cursorPos + diff, cursorPos + diff);
+ });
+}
diff --git a/frontend/src/lib/utils/template-load.ts b/frontend/src/lib/utils/template-load.ts
index b381d8ad8..58c3fe5de 100644
--- a/frontend/src/lib/utils/template-load.ts
+++ b/frontend/src/lib/utils/template-load.ts
@@ -1,6 +1,7 @@
import { queryKeys } from '$lib/query/query-keys';
import { templateService } from '$lib/services/template-service';
-import type { Variable } from '$lib/types/shared';
+import { variableService } from '$lib/services/variable-service';
+import type { GlobalVariable } from '$lib/types/variable';
type QueryClientLike = {
fetchQuery: <T>(options: { queryKey: unknown; queryFn: () => Promise<T> }) => Promise<T>;
@@ -11,7 +12,7 @@ type ParentWithQueryClient = () => Promise<{
[key: string]: unknown;
}>;
-export function globalVariablesToMap(globalVariables: Variable[] | null | undefined): Record<string, string> {
+export function globalVariablesToMap(globalVariables: GlobalVariable[] | null | undefined): Record<string, string> {
return Object.fromEntries((globalVariables ?? []).map((item) => [item.key, item.value]));
}
@@ -40,8 +41,8 @@ export async function loadTemplateAuthoringData(parent: ParentWithQueryClient) {
}),
client
.fetchQuery({
- queryKey: queryKeys.templates.globalVariables(),
- queryFn: () => templateService.getGlobalVariables()
+ queryKey: queryKeys.variables.list(),
+ queryFn: () => variableService.list()
})
.catch((err) => {
console.warn('Failed to load global variables:', err);
diff --git a/frontend/src/routes/(app)/customize/templates/[id]/+page.ts b/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
index d841bbe87..41d2aaef5 100644
--- a/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/[id]/+page.ts
@@ -1,8 +1,9 @@
import { templateService } from '$lib/services/template-service';
+import { variableService } from '$lib/services/variable-service';
import { queryKeys } from '$lib/query/query-keys';
import { error } from '@sveltejs/kit';
import type { Template, TemplateContentData } from '$lib/types/swarm';
-import type { Variable } from '$lib/types/shared';
+import type { GlobalVariable } from '$lib/types/variable';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({
@@ -11,7 +12,7 @@ export const load: PageLoad = async ({
}): Promise<{
templateData: TemplateContentData;
allTemplates: Template[];
- globalVariables: Variable[];
+ globalVariables: GlobalVariable[];
}> => {
const { queryClient } = await parent();
@@ -27,10 +28,10 @@ export const load: PageLoad = async ({
}),
queryClient
.fetchQuery({
- queryKey: queryKeys.templates.globalVariables(),
- queryFn: () => templateService.getGlobalVariables()
+ queryKey: queryKeys.variables.list(),
+ queryFn: () => variableService.list()
})
- .catch(() => [] as Variable[])
+ .catch(() => [] as GlobalVariable[])
]);
return {
diff --git a/frontend/src/routes/(app)/customize/templates/create/+page.ts b/frontend/src/routes/(app)/customize/templates/create/+page.ts
index dade51003..7829bf1b6 100644
--- a/frontend/src/routes/(app)/customize/templates/create/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/create/+page.ts
@@ -1,17 +1,17 @@
-import { templateService } from '$lib/services/template-service';
+import { variableService } from '$lib/services/variable-service';
import { queryKeys } from '$lib/query/query-keys';
-import type { Variable } from '$lib/types/shared';
+import type { GlobalVariable } from '$lib/types/variable';
import type { PageLoad } from './$types';
-export const load: PageLoad = async ({ parent }): Promise<{ globalVariables: Variable[] }> => {
+export const load: PageLoad = async ({ parent }): Promise<{ globalVariables: GlobalVariable[] }> => {
const { queryClient } = await parent();
const globalVariables = await queryClient
.fetchQuery({
- queryKey: queryKeys.templates.globalVariables(),
- queryFn: () => templateService.getGlobalVariables()
+ queryKey: queryKeys.variables.list(),
+ queryFn: () => variableService.list()
})
- .catch(() => [] as Variable[]);
+ .catch(() => [] as GlobalVariable[]);
return { globalVariables };
};
diff --git a/frontend/src/routes/(app)/customize/templates/default/+page.ts b/frontend/src/routes/(app)/customize/templates/default/+page.ts
index c2de4338c..63b684152 100644
--- a/frontend/src/routes/(app)/customize/templates/default/+page.ts
+++ b/frontend/src/routes/(app)/customize/templates/default/+page.ts
@@ -1,11 +1,11 @@
import type { Template } from '$lib/types/swarm';
-import type { Variable } from '$lib/types/shared';
+import type { GlobalVariable } from '$lib/types/variable';
import { loadTemplateAuthoringData } from '$lib/utils/template-load';
import type { PageLoad } from './$types';
export const load: PageLoad = async ({
parent
-}): Promise<{ composeTemplate: string; envTemplate: string; templates: Template[]; globalVariables: Variable[] }> => {
+}): Promise<{ composeTemplate: string; envTemplate: string; templates: Template[]; globalVariables: GlobalVariable[] }> => {
const { defaultTemplates, templates, globalVariables } = await loadTemplateAuthoringData(parent);
return {
diff --git a/frontend/src/routes/(app)/customize/variables/+page.svelte b/frontend/src/routes/(app)/customize/variables/+page.svelte
index 1dde7149f..0c95adc77 100644
--- a/frontend/src/routes/(app)/customize/variables/+page.svelte
+++ b/frontend/src/routes/(app)/customize/variables/+page.svelte
@@ -1,130 +1,127 @@
<script lang="ts">
- import * as Card from '$lib/components/ui/card';
- import { ArcaneButton } from '$lib/components/arcane-button/index.js';
- import { Input } from '$lib/components/ui/input';
- import * as InputGroup from '$lib/components/ui/input-group/index.js';
import { toast } from 'svelte-sonner';
- import { CopyButton } from '$lib/components/ui/copy-button';
- import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
- import { templateService } from '$lib/services/template-service.js';
- import type { Variable } from '$lib/types/shared';
import { untrack } from 'svelte';
+ import { ResourcePageLayout, type ActionButton } from '$lib/layouts/index.js';
+ import { openConfirmDialog } from '$lib/components/confirm-dialog';
+ import VariableFormSheet from '$lib/components/sheets/variable-form-sheet.svelte';
+ import VariableTable from './variable-table.svelte';
+ import { variableService } from '$lib/services/variable-service';
+ import type {
+ GlobalVariable,
+ GlobalVariableCreateDto,
+ GlobalVariableUpdateDto,
+ VariableEnvSyncResult
+ } from '$lib/types/variable';
import { m } from '$lib/paraglide/messages';
- import { SearchIcon, CloseIcon, AlertIcon, VariableIcon } from '$lib/icons';
import { hasPermission } from '$lib/utils/auth';
- let { data } = $props();
- let envVars = $state<Variable[]>(untrack(() => [...data.variables]));
- let originalVars = $state<Variable[]>(untrack(() => [...data.variables]));
- let searchQuery = $state('');
- let isLoading = $state(false);
-
- const filteredVars = $derived.by(() => {
- if (!searchQuery.trim()) return envVars;
-
- const query = searchQuery.toLowerCase();
- return envVars.filter((v) => v.key.toLowerCase().includes(query) || v.value.toLowerCase().includes(query));
- });
-
- const hasChanges = $derived.by(() => {
- if (envVars.length !== originalVars.length) return true;
-
- const originalMap = new Map(originalVars.map((v) => [v.key, v.value]));
-
- for (const v of envVars) {
- if (!v.key.trim()) continue;
+ type VariableFormPayload =
+ | { mode: 'create'; variable: GlobalVariableCreateDto }
+ | { mode: 'edit'; id: string; variable: GlobalVariableUpdateDto }
+ | { mode: 'bulk'; variables: GlobalVariableCreateDto[] };
- const originalValue = originalMap.get(v.key);
- if (originalValue !== v.value) return true;
- if (originalValue === undefined) return true;
- }
+ let { data } = $props();
- const currentMap = new Map(envVars.filter((v) => v.key.trim()).map((v) => [v.key, v.value]));
- for (const key of originalMap.keys()) {
- if (!currentMap.has(key)) return true;
+ let variables = $state(untrack(() => data.variables));
+ let isSheetOpen = $state(false);
+ let variableToEdit = $state<GlobalVariable | null>(null);
+ let isSubmitting = $state(false);
+
+ const canManageVariables = $derived(hasPermission('templates:update'));
+
+ function reportSyncResults(results?: VariableEnvSyncResult[]) {
+ const failed = results?.filter((result) => result.status === 'error') ?? [];
+ if (failed.length > 0) {
+ toast.warning(
+ m.sync_failed_environments({
+ envs: failed.map((result) => result.environmentName || result.environmentId).join(', ')
+ })
+ );
}
-
- return false;
- });
-
- function addEnvVar() {
- envVars = [...envVars, { key: '', value: '' }];
}
- function removeEnvVar(index: number) {
- envVars = envVars.filter((_, i) => i !== index);
+ function openCreateSheet() {
+ variableToEdit = null;
+ isSheetOpen = true;
}
- async function onSubmit() {
- isLoading = true;
+ function openEditSheet(variable: GlobalVariable) {
+ variableToEdit = variable;
+ isSheetOpen = true;
+ }
+ async function handleSheetSubmit(payload: VariableFormPayload) {
+ isSubmitting = true;
try {
- const validVars = envVars
- .filter((v) => v.key.trim() !== '')
- .map((v) => ({
- key: v.key.trim(),
- value: v.value.trim()
- }));
-
- const keys = validVars.map((v) => v.key);
- const uniqueKeys = new Set(keys);
- if (keys.length !== uniqueKeys.size) {
- toast.error(m.variables_duplicate_keys_error());
- return;
+ let response;
+ if (payload.mode === 'edit') {
+ response = await variableService.update(payload.id, payload.variable);
+ } else if (payload.mode === 'bulk') {
+ response = await variableService.createMany(payload.variables);
+ } else {
+ response = await variableService.create(payload.variable);
}
- await templateService.updateGlobalVariables(validVars);
+ variables = await variableService.list();
- originalVars = [...validVars];
- envVars = [...validVars];
+ if (payload.mode === 'bulk') {
+ toast.success(m.count_variables_created({ count: payload.variables.length }));
+ } else if (payload.mode === 'edit') {
+ toast.success(m.common_update_success({ resource: m.variable() }));
+ } else {
+ toast.success(m.common_create_success({ resource: m.variable() }));
+ }
+ reportSyncResults(response?.syncResults);
- toast.success(m.variables_save_success());
+ isSheetOpen = false;
+ variableToEdit = null;
} catch (error) {
- console.error('Failed to save global environment variables:', error);
- toast.error(m.variables_save_failed());
+ console.error('Error saving variable:', error);
+ toast.error(
+ payload.mode === 'edit'
+ ? m.common_update_failed({ resource: m.variable() })
+ : m.common_create_failed({ resource: m.variable() })
+ );
+ // A bulk create can partially succeed before the failing entry, so
+ // refresh even on error to keep the table and duplicate-key
+ // validation in sync with what was actually persisted.
+ variables = await variableService.list().catch(() => variables);
} finally {
- isLoading = false;
+ isSubmitting = false;
}
}
- function resetForm() {
- envVars = [...originalVars];
- searchQuery = '';
- }
-
- function handleKeyDown(event: KeyboardEvent) {
- if (event.key === 'Enter') {
- event.preventDefault();
- addEnvVar();
- }
+ function handleDelete(variable: GlobalVariable) {
+ openConfirmDialog({
+ title: m.common_delete_title({ resource: m.variable() }),
+ message: m.common_delete_confirm({ resource: variable.key }),
+ confirm: {
+ label: m.common_delete(),
+ destructive: true,
+ action: async () => {
+ try {
+ const response = await variableService.delete(variable.id);
+ variables = await variableService.list();
+ toast.success(m.common_delete_success({ resource: m.variable() }));
+ reportSyncResults(response?.syncResults);
+ } catch (error) {
+ console.error('Error deleting variable:', error);
+ toast.error(m.common_delete_failed({ resource: m.variable() }));
+ variables = await variableService.list().catch(() => variables);
+ }
+ }
+ }
+ });
}
- $effect(() => {
- if (envVars.length === 0) {
- addEnvVar();
- }
- });
-
- const canUpdateVariables = $derived(hasPermission('templates:update'));
-
const actionButtons = $derived<ActionButton[]>(
- canUpdateVariables
+ canManageVariables
? [
{
- id: 'reset',
- action: 'restart',
- label: m.common_reset(),
- onclick: resetForm,
- disabled: !hasChanges || isLoading
- },
- {
- id: 'save',
- action: 'save',
- label: m.common_save(),
- loadingLabel: m.common_saving(),
- loading: isLoading,
- disabled: isLoading || !hasChanges,
- onclick: onSubmit
+ id: 'create',
+ action: 'create',
+ label: m.common_add_button({ resource: m.variable() }),
+ onclick: openCreateSheet
}
]
: []
@@ -133,139 +130,17 @@
<ResourcePageLayout title={m.variables_title()} subtitle={m.variables_subtitle()} {actionButtons}>
{#snippet mainContent()}
- <fieldset class="relative">
- <div class="space-y-4 sm:space-y-6">
- <Card.Root class="overflow-hidden border-primary/20 bg-primary/5 pt-0">
- <Card.Content class="px-3 py-4 sm:px-6">
- <div class="flex items-start gap-3">
- <div class="mt-0.5 shrink-0 text-primary">
- <AlertIcon class="size-5" />
- </div>
- <div class="space-y-1 text-sm">
- <p class="font-medium text-foreground">{m.variables_about_title()}</p>
- <p class="text-muted-foreground">
- {m.variables_about_description()}
- </p>
- </div>
- </div>
- </Card.Content>
- </Card.Root>
-
- <Card.Root class="overflow-hidden pt-0">
- <Card.Header class="sticky top-0 z-[var(--arcane-z-sticky)] border-b bg-muted/20 !py-3">
- <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div class="flex items-center gap-3">
- <div class="flex size-8 items-center justify-center rounded-lg bg-primary/10 text-primary ring-1 ring-primary/20">
- <VariableIcon class="size-4" />
- </div>
- <div>
- <Card.Title class="text-base">{m.common_environment_variables()}</Card.Title>
- <Card.Description class="text-xs">
- {#if envVars.filter((v) => v.key.trim()).length === 1}
- {m.variables_count_configured({ count: 1 })}
- {:else}
- {m.variables_count_configured_plural({ count: envVars.filter((v) => v.key.trim()).length })}
- {/if}
- </Card.Description>
- </div>
- </div>
-
- <div class="flex items-center gap-2">
- <div class="relative w-full sm:w-52">
- <SearchIcon class="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
- <Input type="text" placeholder={m.common_search()} bind:value={searchQuery} class="h-9 pl-10" />
- </div>
- {#if canUpdateVariables}
- <ArcaneButton
- action="create"
- size="sm"
- onclick={addEnvVar}
- disabled={isLoading}
- customLabel={m.variables_add_button()}
- class="shrink-0"
- />
- {/if}
- </div>
- </div>
- </Card.Header>
-
- <Card.Content class="px-3 py-4 sm:px-6">
- {#if filteredVars.length === 0 && searchQuery.trim()}
- <div class="flex flex-col items-center justify-center py-12 text-center text-muted-foreground">
- <SearchIcon class="mb-3 size-12 opacity-20" />
- <p class="text-sm font-medium">{m.variables_no_results_title()}</p>
- <p class="text-xs">{m.variables_no_results_description()}</p>
- </div>
- {:else if filteredVars.length === 0}
- <div class="flex flex-col items-center justify-center py-12 text-center text-muted-foreground">
- <VariableIcon class="mb-3 size-12 opacity-20" />
- <p class="text-sm font-medium">{m.variables_no_variables_title()}</p>
- <p class="text-xs">{m.variables_no_variables_description()}</p>
- </div>
- {:else}
- <div class="space-y-2">
- {#each filteredVars as envVar, index (index)}
- {@const actualIndex = envVars.indexOf(envVar)}
- <div class="flex flex-col gap-2 sm:flex-row sm:items-center">
- <div class="flex flex-1 items-center gap-2">
- <InputGroup.Root class="flex-1 sm:max-w-[200px]">
- <InputGroup.Input
- type="text"
- placeholder={m.key_placeholder()}
- bind:value={envVar.key}
- disabled={isLoading}
- class="font-mono text-sm"
- onkeydown={(e) => handleKeyDown(e)}
- oninput={(e) => {
- const target = e.target as HTMLInputElement;
- const cursorPos = target.selectionStart || 0;
- const oldValue = envVar.key;
- const newValue = target.value.toUpperCase().replace(/\s/g, '_');
-
- envVar.key = newValue;
+ <VariableTable bind:variables environments={data.environments} onEdit={openEditSheet} onDelete={handleDelete} />
+ {/snippet}
- requestAnimationFrame(() => {
- const diff = newValue.length - oldValue.length;
- target.setSelectionRange(cursorPos + diff, cursorPos + diff);
- });
- }}
- />
- </InputGroup.Root>
- <span class="font-mono text-sm text-muted-foreground">=</span>
- <InputGroup.Root class="flex-[2]">
- <InputGroup.Input
- type="text"
- placeholder={m.value_placeholder()}
- bind:value={envVar.value}
- disabled={isLoading}
- class="font-mono text-sm"
- onkeydown={(e) => handleKeyDown(e)}
- />
- <InputGroup.Addon align="inline-end">
- <CopyButton text={envVar.value} variant="ghost" tabindex={-1} />
- {#if canUpdateVariables}
- <InputGroup.Button
- variant="ghost"
- aria-label={m.common_remove()}
- size="icon-xs"
- onclick={() => removeEnvVar(actualIndex)}
- disabled={isLoading}
- class="text-destructive hover:text-destructive"
- title={m.common_remove()}
- >
- <CloseIcon />
- </InputGroup.Button>
- {/if}
- </InputGroup.Addon>
- </InputGroup.Root>
- </div>
- </div>
- {/each}
- </div>
- {/if}
- </Card.Content>
- </Card.Root>
- </div>
- </fieldset>
+ {#snippet additionalContent()}
+ <VariableFormSheet
+ bind:open={isSheetOpen}
+ bind:variableToEdit
+ environments={data.environments}
+ existingVariables={variables}
+ isLoading={isSubmitting}
+ onSubmit={handleSheetSubmit}
+ />
{/snippet}
</ResourcePageLayout>
diff --git a/frontend/src/routes/(app)/customize/variables/+page.ts b/frontend/src/routes/(app)/customize/variables/+page.ts
index e8527d5a7..b15e18690 100644
--- a/frontend/src/routes/(app)/customize/variables/+page.ts
+++ b/frontend/src/routes/(app)/customize/variables/+page.ts
@@ -1,16 +1,27 @@
-import type { PageLoad } from './$types';
-import { templateService } from '$lib/services/template-service';
+import { variableService } from '$lib/services/variable-service';
+import { environmentManagementService } from '$lib/services/env-mgmt-service';
import { queryKeys } from '$lib/query/query-keys';
+import type { SearchPaginationSortRequest } from '$lib/types/shared';
+import type { PageLoad } from './$types';
+
+const environmentListOptions: SearchPaginationSortRequest = {
+ pagination: { page: 1, limit: 1000 },
+ sort: { column: 'name', direction: 'asc' }
+};
export const load: PageLoad = async ({ parent }) => {
const { queryClient } = await parent();
- const variables = await queryClient.fetchQuery({
- queryKey: queryKeys.templates.globalVariables(),
- queryFn: () => templateService.getGlobalVariables()
- });
+ const [variables, environmentsPage] = await Promise.all([
+ queryClient.fetchQuery({
+ queryKey: queryKeys.variables.list(),
+ queryFn: () => variableService.list()
+ }),
+ queryClient.fetchQuery({
+ queryKey: queryKeys.environments.list(environmentListOptions),
+ queryFn: () => environmentManagementService.getEnvironments(environmentListOptions)
+ })
+ ]);
- return {
- variables
- };
+ return { variables, environments: environmentsPage.data };
};
diff --git a/frontend/src/routes/(app)/customize/variables/variable-table.svelte b/frontend/src/routes/(app)/customize/variables/variable-table.svelte
new file mode 100644
index 000000000..a0e5a9fd7
--- /dev/null
+++ b/frontend/src/routes/(app)/customize/variables/variable-table.svelte
@@ -0,0 +1,214 @@
+<script lang="ts">
+ import ArcaneTable from '$lib/components/arcane-table/arcane-table.svelte';
+ import { UniversalMobileCard } from '$lib/components/arcane-table';
+ import type { ColumnSpec, MobileFieldVisibility } from '$lib/components/arcane-table';
+ import * as DropdownMenu from '$lib/components/ui/dropdown-menu/index.js';
+ import RowActionsMenu from '$lib/components/arcane-table/row-actions-menu.svelte';
+ import CreatedAtCell from '$lib/components/arcane-table/cells/created-at-cell.svelte';
+ import { Badge } from '$lib/components/ui/badge';
+ import { CopyButton } from '$lib/components/ui/copy-button';
+ import IfPermitted from '$lib/components/if-permitted.svelte';
+ import type { GlobalVariable } from '$lib/types/variable';
+ import type { Environment } from '$lib/types/environment';
+ import type { Paginated, SearchPaginationSortRequest } from '$lib/types/shared';
+ import { VariableIcon, LockIcon, EditIcon, TrashIcon, ClockIcon, GlobeIcon } from '$lib/icons';
+ import { m } from '$lib/paraglide/messages';
+ import { formatDateTime } from '$lib/utils/formatting';
+
+ let {
+ variables = $bindable(),
+ environments,
+ onEdit,
+ onDelete
+ }: {
+ variables: GlobalVariable[];
+ environments: Environment[];
+ onEdit: (variable: GlobalVariable) => void;
+ onDelete: (variable: GlobalVariable) => void;
+ } = $props();
+
+ let requestOptions = $state<SearchPaginationSortRequest>({ pagination: { page: 1, limit: 20 } });
+ let mobileFieldVisibility = $state<MobileFieldVisibility>({});
+
+ const envNameById = $derived(new Map(environments.map((environment) => [environment.id, environment.name])));
+
+ function updatedTimestamp(variable: GlobalVariable): string {
+ return variable.updatedAt ?? variable.createdAt;
+ }
+
+ function scopeNames(variable: GlobalVariable): string[] {
+ return variable.environmentIds.map((id) => envNameById.get(id) ?? id);
+ }
+
+ function scopeLabel(variable: GlobalVariable): string {
+ if (variable.allEnvironments || variable.environmentIds.length === 0) return m.all_environments();
+ return scopeNames(variable).join(', ');
+ }
+
+ const filteredVariables = $derived.by(() => {
+ const query = (requestOptions.search ?? '').trim().toLowerCase();
+ let list = query
+ ? variables.filter(
+ (variable) =>
+ variable.key.toLowerCase().includes(query) || (!variable.isSecret && variable.value.toLowerCase().includes(query))
+ )
+ : [...variables];
+
+ const sort = requestOptions.sort;
+ if (sort?.column === 'key') {
+ list.sort((a, b) => a.key.localeCompare(b.key));
+ if (sort.direction === 'desc') list.reverse();
+ } else if (sort?.column === 'updatedAt') {
+ list.sort((a, b) => new Date(updatedTimestamp(a)).getTime() - new Date(updatedTimestamp(b)).getTime());
+ if (sort.direction === 'desc') list.reverse();
+ }
+ return list;
+ });
+
+ function buildVariableTableData(items: GlobalVariable[]): Paginated<GlobalVariable> {
+ return {
+ data: items,
+ pagination: {
+ totalPages: 1,
+ totalItems: items.length,
+ currentPage: 1,
+ itemsPerPage: Math.max(items.length, 1)
+ }
+ };
+ }
+
+ const tableData = $derived(buildVariableTableData(filteredVariables));
+
+ const columns = [
+ { accessorKey: 'key', title: m.key(), sortable: true, cell: KeyCell },
+ { accessorKey: 'value', title: m.value(), cell: ValueCell },
+ { id: 'scope', accessorFn: (row) => row.id, title: m.common_scope(), cell: ScopeCell },
+ { accessorKey: 'updatedAt', title: m.common_updated(), sortable: true, cell: UpdatedCell }
+ ] satisfies ColumnSpec<GlobalVariable>[];
+
+ const mobileFields = [
+ { id: 'value', label: m.value(), defaultVisible: true },
+ { id: 'scope', label: m.common_scope(), defaultVisible: true },
+ { id: 'updatedAt', label: m.common_updated(), defaultVisible: true }
+ ];
+</script>
+
+{#if variables.length === 0}
+ <div class="flex flex-col items-center justify-center py-12 text-sm text-muted-foreground">
+ <VariableIcon class="mb-3 size-10 opacity-40" />
+ <p class="font-medium">{m.variables_no_variables_title()}</p>
+ <p class="mt-1">{m.variables_no_variables_description()}</p>
+ </div>
+{:else}
+ <ArcaneTable
+ persistKey="arcane-variables-table"
+ items={tableData}
+ bind:requestOptions
+ bind:mobileFieldVisibility
+ selectionDisabled={true}
+ withoutPagination
+ onRefresh={async () => tableData}
+ {columns}
+ {mobileFields}
+ rowActions={RowActions}
+ mobileCard={VariableMobileCardSnippet}
+ />
+{/if}
+
+{#snippet KeyCell({ item }: { item: GlobalVariable })}
+ <div class="flex items-center gap-2">
+ <span class="font-mono text-sm font-medium">{item.key}</span>
+ {#if item.isSecret}
+ <Badge variant="amber" size="sm">
+ <LockIcon class="size-3" />
+ {m.secret()}
+ </Badge>
+ {/if}
+ </div>
+{/snippet}
+
+{#snippet ValueCell({ item }: { item: GlobalVariable })}
+ {#if item.isSecret}
+ <span class="font-mono text-muted-foreground select-none">••••••••</span>
+ {:else}
+ <div class="flex items-center gap-2">
+ <span class="max-w-[280px] truncate font-mono text-sm">{item.value}</span>
+ <CopyButton text={item.value} class="size-6" />
+ </div>
+ {/if}
+{/snippet}
+
+{#snippet ScopeCell({ item }: { item: GlobalVariable })}
+ {#if item.allEnvironments || item.environmentIds.length === 0}
+ <Badge variant="outline" size="sm">{m.all_environments()}</Badge>
+ {:else}
+ {@const names = scopeNames(item)}
+ <div class="flex flex-wrap items-center gap-1">
+ {#each names.slice(0, 2) as name, index (index)}
+ <Badge variant="outline" size="sm" class="max-w-40 truncate">{name}</Badge>
+ {/each}
+ {#if names.length > 2}
+ <Badge variant="gray" size="sm">{m.plus_count({ count: names.length - 2 })}</Badge>
+ {/if}
+ </div>
+ {/if}
+{/snippet}
+
+{#snippet UpdatedCell({ item }: { item: GlobalVariable })}
+ <CreatedAtCell value={updatedTimestamp(item)} />
+{/snippet}
+
+{#snippet VariableMobileCardSnippet({
+ item,
+ mobileFieldVisibility
+}: {
+ item: GlobalVariable;
+ mobileFieldVisibility: MobileFieldVisibility;
+})}
+ <UniversalMobileCard
+ {item}
+ icon={{ component: VariableIcon, variant: 'blue' }}
+ title={(item: GlobalVariable) => item.key}
+ badges={item.isSecret ? [{ variant: 'amber' as const, text: m.secret() }] : []}
+ fields={[
+ {
+ label: m.value(),
+ getValue: (item: GlobalVariable) => (item.isSecret ? '••••••••' : item.value),
+ icon: LockIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility['value'] ?? true
+ },
+ {
+ label: m.common_scope(),
+ getValue: (item: GlobalVariable) => scopeLabel(item),
+ icon: GlobeIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility['scope'] ?? true
+ },
+ {
+ label: m.common_updated(),
+ getValue: (item: GlobalVariable) => formatDateTime(updatedTimestamp(item)) || updatedTimestamp(item),
+ icon: ClockIcon,
+ iconVariant: 'gray' as const,
+ show: mobileFieldVisibility['updatedAt'] ?? true
+ }
+ ]}
+ rowActions={RowActions}
+ />
+{/snippet}
+
+{#snippet RowActions({ item }: { item: GlobalVariable })}
+ <RowActionsMenu>
+ <IfPermitted perm="templates:update">
+ <DropdownMenu.Item onclick={() => onEdit(item)}>
+ <EditIcon class="size-4" />
+ {m.common_edit()}
+ </DropdownMenu.Item>
+ <DropdownMenu.Separator />
+ <DropdownMenu.Item variant="destructive" onclick={() => onDelete(item)}>
+ <TrashIcon class="size-4" />
+ {m.common_delete()}
+ </DropdownMenu.Item>
+ </IfPermitted>
+ </RowActionsMenu>
+{/snippet}
diff --git a/frontend/src/routes/(app)/projects/[projectId]/+page.ts b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
index 3d911b82a..2e1ddd2c9 100644
--- a/frontend/src/routes/(app)/projects/[projectId]/+page.ts
+++ b/frontend/src/routes/(app)/projects/[projectId]/+page.ts
@@ -1,5 +1,5 @@
import { projectService } from '$lib/services/project-service';
-import { templateService } from '$lib/services/template-service';
+import { variableService } from '$lib/services/variable-service';
import { environmentStore } from '$lib/stores/environment.store.svelte';
import { queryKeys } from '$lib/query/query-keys';
import { throwPageLoadError } from '$lib/utils/api';
@@ -9,8 +9,8 @@ import type { PageLoad } from './$types';
async function loadGlobalVariables(queryClient: QueryClient) {
return queryClient
.fetchQuery({
- queryKey: queryKeys.templates.globalVariables(),
- queryFn: () => templateService.getGlobalVariables()
+ queryKey: queryKeys.variables.list(),
+ queryFn: () => variableService.list()
})
.catch((err) => {
console.warn('Failed to load global variables:', err);
diff --git a/frontend/src/routes/(app)/swarm/stacks/new/+page.ts b/frontend/src/routes/(app)/swarm/stacks/new/+page.ts
index 9b786a74d..d2230978f 100644
--- a/frontend/src/routes/(app)/swarm/stacks/new/+page.ts
+++ b/frontend/src/routes/(app)/swarm/stacks/new/+page.ts
@@ -1,5 +1,6 @@
import { error } from '@sveltejs/kit';
import { templateService } from '$lib/services/template-service';
+import { variableService } from '$lib/services/variable-service';
import { swarmService } from '$lib/services/swarm-service';
import type { PageLoad } from './$types';
@@ -35,7 +36,7 @@ export const load: PageLoad = async ({ url }) => {
})
: Promise.resolve(null),
sourceStackPromise,
- templateService.getGlobalVariables().catch((err) => {
+ variableService.list().catch((err) => {
console.warn('Failed to load global variables:', err);
return [];
})
diff --git a/tests/spec/dashboard-system-stats.spec.ts b/tests/spec/dashboard-system-stats.spec.ts
index 8f24da0cf..1444306fc 100644
--- a/tests/spec/dashboard-system-stats.spec.ts
+++ b/tests/spec/dashboard-system-stats.spec.ts
@@ -155,7 +155,6 @@ test.describe('Dashboard system stats websocket', () => {
await page.goto(defaultDashboardPath);
await page.waitForLoadState('load');
- await expect(page.getByRole('heading', { name: 'Overview' })).toBeVisible();
await expect(page.getByRole('heading', { name: 'Environment Board' })).toBeVisible();
await expect(page.getByText('12.3%', { exact: true })).toBeVisible();
await expect(page.getByText('50.0%', { exact: true })).toBeVisible();
@@ -164,7 +163,6 @@ test.describe('Dashboard system stats websocket', () => {
await expect(page.getByText('512 MB / 1 GB', { exact: true })).toBeVisible();
await expect(page.getByText('256 MB / 1 GB', { exact: true })).toBeVisible();
await expect(page.locator('main').getByText('Local Docker', { exact: true })).toBeVisible();
- await expect(page.getByText('HTTP', { exact: true }).first()).toBeVisible();
});
test('loads dashboard content without eagerly loading docker info', async ({ page }) => {
diff --git a/types/env/env.go b/types/env/env.go
index 241ccd814..73502d1f2 100644
--- a/types/env/env.go
+++ b/types/env/env.go
@@ -1,5 +1,7 @@
package env
+import "time"
+
type Variable struct {
Key string `json:"key"`
Value string `json:"value"`
@@ -8,3 +10,47 @@ type Variable struct {
type Summary struct {
Variables []Variable `json:"variables"`
}
+
+// GlobalVariable is the manager-level variable resource. Value is empty on
+// reads when IsSecret is true.
+type GlobalVariable struct {
+ ID string `json:"id"`
+ Key string `json:"key"`
+ Value string `json:"value"`
+ IsSecret bool `json:"isSecret"`
+ AllEnvironments bool `json:"allEnvironments"`
+ EnvironmentIDs []string `json:"environmentIds"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt *time.Time `json:"updatedAt,omitempty"`
+}
+
+type CreateGlobalVariableRequest struct {
+ Key string `json:"key"`
+ Value string `json:"value"`
+ IsSecret bool `json:"isSecret,omitempty"`
+ AllEnvironments bool `json:"allEnvironments,omitempty"`
+ EnvironmentIDs []string `json:"environmentIds,omitempty"`
+}
+
+// UpdateGlobalVariableRequest updates a variable; nil fields keep the current
+// value. A nil Value on a secret variable keeps the stored ciphertext.
+type UpdateGlobalVariableRequest struct {
+ Key *string `json:"key,omitempty"`
+ Value *string `json:"value,omitempty"`
+ IsSecret *bool `json:"isSecret,omitempty"`
+ AllEnvironments *bool `json:"allEnvironments,omitempty"`
+ EnvironmentIDs *[]string `json:"environmentIds,omitempty"`
+}
+
+type EnvironmentSyncStatus struct {
+ EnvironmentID string `json:"environmentId"`
+ EnvironmentName string `json:"environmentName,omitempty"`
+ Status string `json:"status"` // "synced" | "pending" | "error"
+ Error string `json:"error,omitempty"`
+ LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"`
+}
+
+type GlobalVariableMutationResponse struct {
+ Variable *GlobalVariable `json:"variable,omitempty"`
+ SyncResults []EnvironmentSyncStatus `json:"syncResults,omitempty"`
+}