Skip to content

Modern Docker Management, Designed for Everyone

fix: harden credential targets and browse paths (#3403)

Kyle Mendell058f3adc2355
diff --git a/backend/api/handlers/environments.go b/backend/api/handlers/environments.go
index 6da9d9c17..58e4cb528 100644
--- a/backend/api/handlers/environments.go
+++ b/backend/api/handlers/environments.go
@@ -477,13 +477,13 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con
return nil, huma.Error500InternalServerError("Failed to create environment API key")
}
- // Store the API key in AccessToken field (encrypted) for manager-to-agent auth
- encryptedKey := apiKeyDto.Key // Store the full key
+ // Store the full API key in AccessToken for manager-to-agent auth.
+ apiKey := apiKeyDto.Key
- // Link API key to environment and store encrypted key for manager use
+ // Link the API key to the environment for manager use.
updates := map[string]any{
"api_key_id": apiKeyDto.ID,
- "access_token": encryptedKey,
+ "access_token": apiKey,
}
created, err = h.environmentService.UpdateEnvironment(ctx, created.ID, updates, &user.ID, &user.Username)
if err != nil {
@@ -580,7 +580,11 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
}
updated, updateErr := h.environmentService.UpdateEnvironment(ctx, input.ID, updates, userID, username)
if updateErr != nil {
- return nil, huma.Error500InternalServerError("Failed to update environment")
+ apiErr := models.ToAPIError(updateErr)
+ if apiErr.HTTPStatus() == http.StatusInternalServerError {
+ return nil, huma.Error500InternalServerError("Failed to update environment")
+ }
+ return nil, huma.NewError(apiErr.HTTPStatus(), apiErr.Message)
}
h.triggerPostUpdateTasksInternal(ctx, input.ID, updated, &input.Body)
@@ -612,8 +616,8 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat
}
// Use service method to update environment and create event
- encryptedKey := apiKeyDto.Key
- err = h.environmentService.RegenerateEnvironmentApiKey(ctx, input.ID, apiKeyDto.ID, encryptedKey, user.ID, user.Username, updated.Name)
+ apiKey := apiKeyDto.Key
+ err = h.environmentService.RegenerateEnvironmentApiKey(ctx, input.ID, apiKeyDto.ID, apiKey, user.ID, user.Username, updated.Name)
if err != nil {
slog.ErrorContext(ctx, "Failed to regenerate API key", "environmentID", input.ID, "error", err.Error())
return nil, huma.Error500InternalServerError("Failed to regenerate API key")
@@ -683,11 +687,22 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConn
if input.Body != nil {
apiUrl = input.Body.ApiUrl
}
+ if apiUrl != nil {
+ permissions, ok := humamw.PermissionsFromContext(ctx)
+ if !ok || !permissions.Allows(authz.PermEnvironmentsUpdate, "") {
+ return nil, huma.Error403Forbidden("permission denied: " + authz.PermEnvironmentsUpdate)
+ }
+ }
status, err := h.environmentService.TestConnection(ctx, input.ID, apiUrl)
resp := environment.Test{Status: status}
if err != nil {
- resp.Message = new(err.Error())
+ if apiUrl == nil {
+ resp.Message = new(err.Error())
+ } else {
+ apiErr := models.ToAPIError(err)
+ err = huma.NewError(apiErr.HTTPStatus(), apiErr.Message)
+ }
return &TestConnectionOutput{
Body: base.ApiResponse[environment.Test]{
Success: false,
diff --git a/backend/api/handlers/environments_test.go b/backend/api/handlers/environments_test.go
index 1873e5081..b6270d1df 100644
--- a/backend/api/handlers/environments_test.go
+++ b/backend/api/handlers/environments_test.go
@@ -1,12 +1,15 @@
package handlers
import (
+ "context"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
+ "github.com/danielgtaylor/huma/v2"
+ humamw "github.com/getarcaneapp/arcane/backend/v2/api/middleware"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/internal/services"
"github.com/getarcaneapp/arcane/backend/v2/pkg/authz"
@@ -16,6 +19,56 @@ import (
"github.com/stretchr/testify/require"
)
+func TestEnvironmentHandlerTestConnectionRequiresUpdatePermissionForCustomURLInternal(t *testing.T) {
+ permissions := authz.NewPermissionSet()
+ permissions.AddGlobal(authz.PermEnvironmentsRead)
+ ctx := context.WithValue(context.Background(), humamw.ContextKeyUserPermissions, permissions)
+
+ output, err := (&EnvironmentHandler{}).TestConnection(ctx, &TestConnectionInput{
+ ID: "0",
+ Body: &envtypes.TestConnectionRequest{
+ ApiUrl: new("http://10.0.0.2:3553"),
+ },
+ })
+
+ require.Nil(t, output)
+ require.ErrorContains(t, err, "permission denied: "+authz.PermEnvironmentsUpdate)
+}
+
+func TestEnvironmentHandlerTestConnectionReturnsOpaqueBadRequestForCustomURLInternal(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusTeapot)
+ }))
+ t.Cleanup(server.Close)
+
+ db := setupActivityHandlerTestDBInternal(t)
+ env := &models.Environment{Name: "Test", ApiUrl: "http://stored.example", Enabled: true}
+ env.ID = "env-1"
+ require.NoError(t, db.Create(env).Error)
+
+ permissions := authz.NewPermissionSet()
+ permissions.AddGlobal(authz.PermEnvironmentsUpdate)
+ ctx := context.WithValue(context.Background(), humamw.ContextKeyUserPermissions, permissions)
+ handler := &EnvironmentHandler{
+ environmentService: services.NewEnvironmentService(db, server.Client(), nil, nil, nil, nil),
+ }
+
+ output, err := handler.TestConnection(ctx, &TestConnectionInput{
+ ID: "env-1",
+ Body: &envtypes.TestConnectionRequest{
+ ApiUrl: new(server.URL),
+ },
+ })
+
+ require.NotNil(t, output)
+ require.False(t, output.Body.Success)
+ require.Nil(t, output.Body.Data.Message)
+ var statusErr huma.StatusError
+ require.ErrorAs(t, err, &statusErr)
+ require.Equal(t, http.StatusBadRequest, statusErr.GetStatus())
+ require.Equal(t, "Environment connection test failed", statusErr.Error())
+}
+
func TestEnvironmentSecretDeploymentRoutesRequirePairPermission(t *testing.T) {
testCases := []struct {
name string
diff --git a/backend/api/handlers/notifications.go b/backend/api/handlers/notifications.go
index 9033e17e1..0f5ba5187 100644
--- a/backend/api/handlers/notifications.go
+++ b/backend/api/handlers/notifications.go
@@ -228,7 +228,11 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Con
models.JSON(input.Body.Config),
)
if err != nil {
- return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to update notification settings").Error())
+ apiErr := models.ToAPIError(err)
+ if apiErr.HTTPStatus() == http.StatusInternalServerError {
+ return nil, huma.Error500InternalServerError("Failed to update notification settings")
+ }
+ return nil, huma.NewError(apiErr.HTTPStatus(), apiErr.Message)
}
response := notification.Response{
diff --git a/backend/api/handlers/settings.go b/backend/api/handlers/settings.go
index 2f9765b5c..5d630f30f 100644
--- a/backend/api/handlers/settings.go
+++ b/backend/api/handlers/settings.go
@@ -384,7 +384,11 @@ func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context,
updatedSettings, err := h.settingsService.UpdateSettings(ctx, input)
if err != nil {
- return nil, huma.Error500InternalServerError("Failed to update settings")
+ apiErr := models.ToAPIError(err)
+ if apiErr.HTTPStatus() == http.StatusInternalServerError {
+ return nil, huma.Error500InternalServerError("Failed to update settings")
+ }
+ return nil, huma.NewError(apiErr.HTTPStatus(), apiErr.Message)
}
settingDtos := make([]settings.SettingDto, 0, len(updatedSettings))
diff --git a/backend/api/middleware/role_test.go b/backend/api/middleware/role_test.go
index 2fb0d7dae..e9089729e 100644
--- a/backend/api/middleware/role_test.go
+++ b/backend/api/middleware/role_test.go
@@ -116,6 +116,35 @@ func TestRequirePermission_EnvScopedDoesNotLeakAcrossEnvs(t *testing.T) {
require.Equal(t, http.StatusForbidden, rec.Code)
}
+func TestRequirePermissionEnvironmentGrantCannotManageGlobalNotificationsInternal(t *testing.T) {
+ router := echo.New()
+ api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
+
+ api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
+ ps := authz.NewPermissionSet()
+ ps.AddEnv("env-1", authz.PermNotificationsManage)
+ next(huma.WithContext(ctx, context.WithValue(ctx.Context(), ContextKeyUserPermissions, ps)))
+ })
+
+ huma.Register(api, huma.Operation{
+ OperationID: "guarded-global-notifications",
+ Method: http.MethodPost,
+ Path: "/environments/{id}/notifications/settings",
+ Middlewares: RequirePermission(api, authz.PermNotificationsManage),
+ }, func(_ context.Context, _ *struct {
+ ID string `path:"id"`
+ }) (*struct{}, error) {
+ t.Fatal("handler must not run for an environment-scoped grant on global notification settings")
+ return nil, nil
+ })
+
+ req := httptest.NewRequest(http.MethodPost, "/api/environments/env-1/notifications/settings", nil)
+ rec := httptest.NewRecorder()
+ router.ServeHTTP(rec, req)
+
+ require.Equal(t, http.StatusForbidden, rec.Code)
+}
+
func TestRequirePermission_SudoCallerAllowed(t *testing.T) {
router := echo.New()
api := humaecho.NewWithGroup(router, router.Group("/api"), huma.DefaultConfig("test", "1.0.0"))
diff --git a/backend/internal/common/errors.go b/backend/internal/common/errors.go
index fefde84f6..4059bb6f6 100644
--- a/backend/internal/common/errors.go
+++ b/backend/internal/common/errors.go
@@ -90,6 +90,7 @@ var (
ErrProjectComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("Project compose file not found"))
ErrComposeFileNotFound = Classify(ErrNotFound, errors.Sentinel("no compose file found"))
ErrEnvironmentInvalidProxyTarget = Classify(ErrBadRequest, errors.Sentinel("Invalid proxy target URL"))
+ ErrEnvironmentConnectionTestFailed = Classify(ErrBadRequest, errors.Sentinel("Environment connection test failed"))
ErrUnsafeRemoteURL = Classify(ErrBadRequest, errors.Sentinel("Remote URL is not allowed"))
ErrImageScanInProgress = Classify(ErrConflict, errors.Sentinel("an image update check is already in progress"))
ErrRedeployAfterSyncFailed = errors.Sentinel("redeploy failed")
diff --git a/backend/internal/services/build_workspace_service_test.go b/backend/internal/services/build_workspace_service_test.go
new file mode 100644
index 000000000..7426c5589
--- /dev/null
+++ b/backend/internal/services/build_workspace_service_test.go
@@ -0,0 +1,26 @@
+package services
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestBuildWorkspaceServiceDeleteFileRejectsCurrentDirectoryInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ settingsService, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+
+ root := t.TempDir()
+ require.NoError(t, settingsService.UpdateSetting(ctx, "buildsDirectory", root))
+ sentinel := filepath.Join(root, "keep.txt")
+ require.NoError(t, os.WriteFile(sentinel, []byte("keep"), 0o600))
+
+ err = NewBuildWorkspaceService(settingsService).DeleteFile(ctx, ".")
+ require.ErrorContains(t, err, "cannot delete root directory")
+ require.FileExists(t, sentinel)
+}
diff --git a/backend/internal/services/container_registry_service.go b/backend/internal/services/container_registry_service.go
index 6807c4dce..ed01ca1b8 100644
--- a/backend/internal/services/container_registry_service.go
+++ b/backend/internal/services/container_registry_service.go
@@ -213,18 +213,28 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string
return nil, err
}
- if registry.RegistryType != registryTypeECR {
- if err := validation.ValidateCredentialTargetChange(
- "registry URL",
- registry.URL,
- req.URL,
- normalizeRegistryServerAddressInternal,
- map[string]bool{"token": registry.Token != ""},
- map[string]bool{"token": req.Token != nil && *req.Token != ""},
- ); err != nil {
- return nil, err
+ storedCredentials := map[string]bool{"token": registry.Token != ""}
+ updatedCredentials := map[string]bool{"token": req.Token != nil && *req.Token != ""}
+ if registry.RegistryType == registryTypeECR {
+ storedCredentials = map[string]bool{
+ "awsAccessKeyId": registry.AWSAccessKeyID != "",
+ "awsSecretAccessKey": registry.AWSSecretAccessKey != "",
+ }
+ updatedCredentials = map[string]bool{
+ "awsAccessKeyId": req.AWSAccessKeyID != nil && *req.AWSAccessKeyID != "",
+ "awsSecretAccessKey": req.AWSSecretAccessKey != nil && *req.AWSSecretAccessKey != "",
}
}
+ if err := validation.ValidateCredentialTargetChange(
+ "registry URL",
+ registry.URL,
+ req.URL,
+ normalizeRegistryServerAddressInternal,
+ storedCredentials,
+ updatedCredentials,
+ ); err != nil {
+ return nil, err
+ }
// Update common fields
utils.ApplyChanged(&registry.URL, mo.PointerToOption(req.URL))
diff --git a/backend/internal/services/container_registry_service_test.go b/backend/internal/services/container_registry_service_test.go
index 18f828055..8d90f6f69 100644
--- a/backend/internal/services/container_registry_service_test.go
+++ b/backend/internal/services/container_registry_service_test.go
@@ -513,6 +513,48 @@ func TestContainerRegistryService_UpdateRegistry_AllowsTargetChangeWhenTokenIsRe
assert.Equal(t, "new-token", decryptedToken)
}
+func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStoredCredentialsInternal(t *testing.T) {
+ _, db := setupImageServiceAuthTest(t)
+ svc := NewContainerRegistryService(db, nil, nil)
+
+ registry, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{
+ URL: "123456789012.dkr.ecr.us-east-1.amazonaws.com",
+ RegistryType: registryTypeECR,
+ AWSAccessKeyID: "old-access-key",
+ AWSSecretAccessKey: "old-secret-key",
+ AWSRegion: "us-east-1",
+ })
+ require.NoError(t, err)
+ originalSecret := registry.AWSSecretAccessKey
+
+ _, err = svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{
+ URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),
+ })
+ require.Error(t, err)
+
+ var apiErr *models.APIError
+ require.ErrorAs(t, err, &apiErr)
+ require.Equal(t, models.APIErrorCodeValidationError, apiErr.Code)
+ require.ElementsMatch(t, []string{"awsAccessKeyId", "awsSecretAccessKey"}, apiErr.Details.(map[string]any)["fields"])
+
+ stored, loadErr := svc.GetRegistryByID(context.Background(), registry.ID)
+ require.NoError(t, loadErr)
+ require.Equal(t, "123456789012.dkr.ecr.us-east-1.amazonaws.com", stored.URL)
+ require.Equal(t, originalSecret, stored.AWSSecretAccessKey)
+
+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{
+ URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),
+ AWSAccessKeyID: new("new-access-key"),
+ AWSSecretAccessKey: new("new-secret-key"),
+ })
+ require.NoError(t, err)
+ require.Equal(t, "999999999999.dkr.ecr.us-east-1.amazonaws.com", updated.URL)
+
+ decryptedSecret, decryptErr := crypto.Decrypt(updated.AWSSecretAccessKey)
+ require.NoError(t, decryptErr)
+ require.Equal(t, "new-secret-key", decryptedSecret)
+}
+
func TestContainerRegistryService_UpdateRegistry_RejectsChangingRegistryType(t *testing.T) {
_, db := setupImageServiceAuthTest(t)
svc := NewContainerRegistryService(db, nil, nil)
diff --git a/backend/internal/services/environment_service.go b/backend/internal/services/environment_service.go
index a2bd85421..b04f7364e 100644
--- a/backend/internal/services/environment_service.go
+++ b/backend/internal/services/environment_service.go
@@ -15,6 +15,7 @@ import (
"emperror.dev/errors"
+ "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/libarcane/edge"
@@ -24,6 +25,7 @@ import (
pkgutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"
"github.com/getarcaneapp/arcane/types/v2/containerregistry"
"github.com/getarcaneapp/arcane/types/v2/environment"
"github.com/getarcaneapp/arcane/types/v2/gitops"
@@ -1111,6 +1113,35 @@ func (s *EnvironmentService) SyncRegistriesToRemoteEnvironments(ctx context.Cont
}
func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]any, userID, username *string) (*models.Environment, error) {
+ current, err := s.GetEnvironmentByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+
+ var nextAPIURL *string
+ if rawAPIURL, ok := updates["api_url"]; ok {
+ if apiURL, isString := rawAPIURL.(string); isString {
+ nextAPIURL = new(apiURL)
+ }
+ }
+ _, accessTokenUpdated := updates["access_token"]
+ if err := validation.ValidateCredentialTargetChange(
+ "environment API URL",
+ current.ApiUrl,
+ nextAPIURL,
+ func(value string) string {
+ normalized, normalizeErr := normalizeEnvironmentBaseURLInternal(value)
+ if normalizeErr != nil {
+ return strings.TrimSpace(value)
+ }
+ return normalized
+ },
+ map[string]bool{"accessToken": current.AccessToken != nil && *current.AccessToken != ""},
+ map[string]bool{"accessToken": accessTokenUpdated},
+ ); err != nil {
+ return nil, err
+ }
+
updates["updated_at"] = new(time.Now())
if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {
@@ -1209,6 +1240,13 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, cust
if err != nil {
return "error", err
}
+ connectionFailure := func(status string, failure error) (string, error) {
+ if customApiUrl == nil {
+ return status, failure
+ }
+ slog.WarnContext(ctx, "Environment custom URL connection test failed", "environment_id", id, "error", failure)
+ return "error", common.ErrEnvironmentConnectionTestFailed
+ }
// Special handling for local Docker environment (ID "0")
if id == "0" && customApiUrl == nil {
@@ -1221,7 +1259,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, cust
}
apiUrl := environment.ApiUrl
- if customApiUrl != nil && *customApiUrl != "" {
+ if customApiUrl != nil {
apiUrl = *customApiUrl
}
@@ -1230,7 +1268,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, cust
if customApiUrl == nil {
_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
}
- return "offline", errors.WrapIf(err, "invalid environment API URL")
+ return connectionFailure("offline", errors.WrapIf(err, "invalid environment API URL"))
}
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
@@ -1240,14 +1278,14 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, cust
if customApiUrl == nil {
_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
}
- return "offline", errors.WrapIf(err, "failed to create request")
+ return connectionFailure("offline", errors.WrapIf(err, "failed to create request"))
}
resp, err := s.httpClient.Do(req)
if err != nil {
if customApiUrl == nil {
_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))
}
- return "offline", errors.WrapIf(err, "connection failed")
+ return connectionFailure("offline", errors.WrapIf(err, "connection failed"))
}
defer func() { _ = resp.Body.Close() }()
@@ -1261,7 +1299,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, cust
if customApiUrl == nil {
_ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))
}
- return "error", errors.Errorf("unexpected status code: %d", resp.StatusCode)
+ return connectionFailure("error", errors.Errorf("unexpected status code: %d", resp.StatusCode))
}
// testEdgeConnection tests connection to an edge agent via its tunnel
@@ -1431,16 +1469,16 @@ func (s *EnvironmentService) createEnvironmentEvent(ctx context.Context, envID,
})
}
-func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, envID string, newApiKeyID string, encryptedKey string, userID, username string, envName string) error {
+func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, envID string, newApiKeyID string, apiKey string, userID, username string, envName string) error {
// Trim once at the boundary so the value persisted, the value cached,
// and the value returned by callers (which already TrimSpace before
// returning) all stay byte-identical. Any divergence here would surface
// as a 401 "invalid agent token" because lookup is direct equality.
- encryptedKey = strings.TrimSpace(encryptedKey)
+ apiKey = strings.TrimSpace(apiKey)
updates := map[string]any{
"api_key_id": newApiKeyID,
- "access_token": encryptedKey,
+ "access_token": apiKey,
"status": string(models.EnvironmentStatusPending),
"last_seen": nil, // Clear last seen time
}
@@ -1449,11 +1487,11 @@ func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, en
return errors.WrapIf(err, "failed to update environment with new API key")
}
- s.syncEnvironmentTokenCacheInternal(envID, encryptedKey)
+ s.syncEnvironmentTokenCacheInternal(envID, apiKey)
now := time.Now()
s.updateRemoteEnvironmentSnapshotInternal(envID, func(environment *models.Environment) {
environment.ApiKeyID = &newApiKeyID
- environment.AccessToken = &encryptedKey
+ environment.AccessToken = &apiKey
environment.Status = string(models.EnvironmentStatusPending)
environment.LastSeen = nil
environment.UpdatedAt = &now
diff --git a/backend/internal/services/environment_service_test.go b/backend/internal/services/environment_service_test.go
index 8cd740aa0..1b492755d 100644
--- a/backend/internal/services/environment_service_test.go
+++ b/backend/internal/services/environment_service_test.go
@@ -17,6 +17,7 @@ import (
"github.com/stretchr/testify/require"
"gorm.io/gorm"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
@@ -559,6 +560,42 @@ func TestEnvironmentService_UpdateEnvironment_ClearingAccessTokenInvalidatesCach
require.Contains(t, err.Error(), "invalid agent token")
}
+func TestEnvironmentServiceUpdateEnvironmentRejectsTargetChangeWithStoredTokenInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupEnvironmentServiceTestDB(t)
+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
+
+ oldToken := "stored-agent-token"
+ createTestEnvironment(t, db, "env-target", "http://agent.example:3553", &oldToken)
+ updates := map[string]any{"api_url": "http://attacker.example:3553"}
+
+ _, err := svc.UpdateEnvironment(ctx, "env-target", updates, nil, nil)
+ require.ErrorIs(t, err, common.ErrValidation)
+ require.NotContains(t, updates, "updated_at")
+
+ var stored models.Environment
+ require.NoError(t, db.WithContext(ctx).First(&stored, "id = ?", "env-target").Error)
+ require.Equal(t, "http://agent.example:3553", stored.ApiUrl)
+ require.Equal(t, oldToken, *stored.AccessToken)
+}
+
+func TestEnvironmentServiceUpdateEnvironmentAllowsTargetChangeWithReplacementTokenInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupEnvironmentServiceTestDB(t)
+ svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)
+
+ oldToken := "stored-agent-token"
+ createTestEnvironment(t, db, "env-target", "http://agent.example:3553", &oldToken)
+
+ updated, err := svc.UpdateEnvironment(ctx, "env-target", map[string]any{
+ "api_url": "http://replacement.example:3553",
+ "access_token": "replacement-agent-token",
+ }, nil, nil)
+ require.NoError(t, err)
+ require.Equal(t, "http://replacement.example:3553", updated.ApiUrl)
+ require.Equal(t, "replacement-agent-token", *updated.AccessToken)
+}
+
func TestEnvironmentService_getCachedEnvironmentIDForTokenInternal_ExpiresAndCleansReverseIndex(t *testing.T) {
svc := NewEnvironmentService(nil, nil, nil, nil, nil, nil)
svc.tokenCacheMu.Lock()
@@ -1129,8 +1166,41 @@ func TestEnvironmentService_TestConnection_RejectsInvalidCustomURL(t *testing.T)
createTestEnvironment(t, db, "env-1", "http://example.com", nil)
status, err := svc.TestConnection(ctx, "env-1", new("ftp://example.com"))
require.Error(t, err)
- require.Equal(t, "offline", status)
- require.Contains(t, err.Error(), "invalid environment API URL")
+ require.Equal(t, "error", status)
+ require.EqualError(t, err, "Environment connection test failed")
+}
+
+func TestEnvironmentServiceTestConnectionHidesCustomURLFailureInternal(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusTeapot)
+ }))
+ t.Cleanup(server.Close)
+
+ ctx := context.Background()
+ db := setupEnvironmentServiceTestDB(t)
+ svc := NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)
+ createTestEnvironment(t, db, "env-1", "http://stored.example", nil)
+
+ status, err := svc.TestConnection(ctx, "env-1", new(server.URL))
+ require.Equal(t, "error", status)
+ require.EqualError(t, err, "Environment connection test failed")
+ require.NotContains(t, err.Error(), "418")
+}
+
+func TestEnvironmentServiceTestConnectionAllowsStoredPrivateURLInternal(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(server.Close)
+
+ ctx := context.Background()
+ db := setupEnvironmentServiceTestDB(t)
+ svc := NewEnvironmentService(db, server.Client(), nil, nil, nil, nil)
+ createTestEnvironment(t, db, "env-private", server.URL, nil)
+
+ status, err := svc.TestConnection(ctx, "env-private", nil)
+ require.NoError(t, err)
+ require.Equal(t, "online", status)
}
func TestEnvironmentService_ExecuteRemoteRequest_RejectsInvalidEnvironmentURL(t *testing.T) {
diff --git a/backend/internal/services/notification_service.go b/backend/internal/services/notification_service.go
index bff469eb7..69f4a99ab 100644
--- a/backend/internal/services/notification_service.go
+++ b/backend/internal/services/notification_service.go
@@ -21,6 +21,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"
"github.com/getarcaneapp/arcane/backend/v2/resources"
"github.com/getarcaneapp/arcane/types/v2/imageupdate"
notificationdto "github.com/getarcaneapp/arcane/types/v2/notification"
@@ -40,6 +41,14 @@ var notificationCredentialFieldsByProviderInternal = map[models.NotificationProv
models.NotificationProviderMatrix: {"password"},
}
+var notificationTargetFieldByProviderInternal = map[models.NotificationProvider]string{
+ models.NotificationProviderEmail: "smtpHost",
+ models.NotificationProviderSignal: "host",
+ models.NotificationProviderNtfy: "host",
+ models.NotificationProviderGotify: "host",
+ models.NotificationProviderMatrix: "host",
+}
+
const ErrUnauthorizedNotificationDispatch = errors.Sentinel("unauthorized notification dispatch")
const ErrUnsupportedDispatchKind = errors.Sentinel("unsupported notification dispatch kind")
@@ -316,6 +325,36 @@ func encryptNotificationConfigCredentialsInternal(provider models.NotificationPr
if provider == models.NotificationProviderEmail {
preserveConfig = emailCredentialPreservationConfigInternal(config, existingConfig)
}
+ if targetField := notificationTargetFieldByProviderInternal[provider]; targetField != "" {
+ currentTarget, _ := existingConfig[targetField].(string)
+ nextTarget, _ := encryptedConfig[targetField].(string)
+ if strings.TrimSpace(nextTarget) == "" && strings.TrimSpace(currentTarget) != "" {
+ nextTarget = currentTarget
+ encryptedConfig[targetField] = currentTarget
+ }
+
+ storedCredentials := make(map[string]bool, len(notificationCredentialFieldsByProviderInternal[provider]))
+ updatedCredentials := make(map[string]bool, len(notificationCredentialFieldsByProviderInternal[provider]))
+ for _, field := range notificationCredentialFieldsByProviderInternal[provider] {
+ preservedValue, _ := preserveConfig[field].(string)
+ updatedValue, _ := encryptedConfig[field].(string)
+ storedCredentials[field] = preservedValue != ""
+ updatedCredentials[field] = updatedValue != ""
+ }
+
+ if err := validation.ValidateCredentialTargetChange(
+ targetField,
+ currentTarget,
+ new(nextTarget),
+ func(value string) string {
+ return strings.ToLower(strings.TrimSuffix(strings.TrimSpace(value), "."))
+ },
+ storedCredentials,
+ updatedCredentials,
+ ); err != nil {
+ return nil, err
+ }
+ }
for _, field := range notificationCredentialFieldsByProviderInternal[provider] {
value, _ := encryptedConfig[field].(string)
if value == "" {
diff --git a/backend/internal/services/notification_service_test.go b/backend/internal/services/notification_service_test.go
index a05869b73..75c43f562 100644
--- a/backend/internal/services/notification_service_test.go
+++ b/backend/internal/services/notification_service_test.go
@@ -18,6 +18,7 @@ import (
"github.com/stretchr/testify/require"
"gorm.io/gorm"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
@@ -577,6 +578,41 @@ func TestNotificationService_CreateOrUpdateSettingsPreservesStoredCredentialWhen
require.Equal(t, "initial-gotify-token", decrypted)
}
+func TestNotificationService_CreateOrUpdateSettingsRejectsTargetChangeWithStoredCredentialInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupNotificationTestDB(t)
+ svc := NewNotificationService(db, &config.Config{}, nil, nil)
+
+ created, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{
+ "host": "gotify.example",
+ "port": 443,
+ "token": "initial-gotify-token",
+ })
+ require.NoError(t, err)
+ originalToken := created.Config["token"]
+
+ _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{
+ "host": "attacker.example",
+ "port": 443,
+ "token": "",
+ })
+ require.ErrorIs(t, err, common.ErrValidation)
+
+ var stored models.NotificationSettings
+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderGotify).First(&stored).Error)
+ require.Equal(t, "gotify.example", stored.Config["host"])
+ require.Equal(t, originalToken, stored.Config["token"])
+
+ updated, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{
+ "host": "gotify.example",
+ "port": 8443,
+ "token": "",
+ })
+ require.NoError(t, err)
+ require.Equal(t, 8443, updated.Config["port"])
+ require.Equal(t, originalToken, updated.Config["token"])
+}
+
func TestNotificationService_CreateOrUpdateSettingsClearsEmailPasswordWhenAuthModeNoneInternal(t *testing.T) {
ctx := context.Background()
db := setupNotificationTestDB(t)
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 564c6baf1..ad07e6f9b 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -27,6 +27,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"
"github.com/getarcaneapp/arcane/backend/v2/pkg/projects"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils"
+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"
"github.com/getarcaneapp/arcane/types/v2/settings"
)
@@ -406,17 +407,49 @@ func (s *SettingsService) updateSettingValueNoRefreshInternal(ctx context.Contex
func (s *SettingsService) UpdateSettings(ctx context.Context, updates settings.Update) ([]models.SettingVariable, error) {
defaultCfg := s.getDefaultSettings()
cfg := s.GetSettingsConfig().Clone()
+ trivyServerTokenUpdated := updates.TrivyServerToken != nil && *updates.TrivyServerToken != "" && !s.isEnvOverrideActiveInternal("trivyServerToken")
+ normalizeTargetURL := func(value string) string {
+ normalized, err := normalizeEnvironmentBaseURLInternal(value)
+ if err != nil {
+ return strings.TrimSpace(value)
+ }
+ return normalized
+ }
- valuesToUpdate, changedPolling, changedAutoUpdate, changedScheduledPrune, changedVulnerabilityScan, changedAutoHeal, changedTimeouts, err := s.prepareUpdateValues(updates, cfg, defaultCfg)
- if err != nil {
+ if err := validation.ValidateCredentialTargetChange(
+ "OIDC issuer URL",
+ cfg.OidcIssuerUrl.Value,
+ updates.OidcIssuerUrl,
+ normalizeTargetURL,
+ map[string]bool{"oidcClientSecret": cfg.OidcClientSecret.Value != ""},
+ map[string]bool{"oidcClientSecret": updates.OidcClientSecret != nil && *updates.OidcClientSecret != ""},
+ ); err != nil {
return nil, err
}
- if err := s.persistSettings(ctx, valuesToUpdate); err != nil {
+ if err := validation.ValidateCredentialTargetChange(
+ "Trivy server URL",
+ cfg.TrivyServerUrl.Value,
+ updates.TrivyServerUrl,
+ normalizeTargetURL,
+ map[string]bool{"trivyServerToken": cfg.TrivyServerToken.Value != ""},
+ map[string]bool{"trivyServerToken": trivyServerTokenUpdated},
+ ); err != nil {
return nil, err
}
- if err := s.handleOidcConfigUpdate(ctx, updates); err != nil {
+ valuesToUpdate, changedPolling, changedAutoUpdate, changedScheduledPrune, changedVulnerabilityScan, changedAutoHeal, changedTimeouts, err := s.prepareUpdateValues(updates, cfg, defaultCfg)
+ if err != nil {
+ return nil, err
+ }
+ if updates.OidcClientSecret != nil && *updates.OidcClientSecret != "" {
+ valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: "oidcClientSecret", Value: *updates.OidcClientSecret})
+ }
+ if trivyServerTokenUpdated {
+ valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: "trivyServerToken", Value: *updates.TrivyServerToken})
+ }
+
+ if err := s.persistSettings(ctx, valuesToUpdate); err != nil {
return nil, err
}
@@ -574,31 +607,6 @@ func (s *SettingsService) persistSettings(ctx context.Context, values []models.S
})
}
-func (s *SettingsService) handleOidcConfigUpdate(ctx context.Context, updates settings.Update) error {
- // Handle new individual field for client secret (sensitive field)
- if updates.OidcClientSecret != nil {
- secret := *updates.OidcClientSecret
-
- // If empty secret provided, preserve existing secret
- if secret == "" {
- current, err := s.GetSettings(ctx)
- if err != nil {
- return errors.WrapIf(err, "failed to load current settings for secret")
- }
- if current.OidcClientSecret.Value != "" {
- // Keep existing secret, don't update
- return nil
- }
- }
-
- if err := s.updateSettingValueNoRefreshInternal(ctx, "oidcClientSecret", secret); err != nil {
- return errors.WrapIf(err, "failed to update oidcClientSecret")
- }
- }
-
- return nil
-}
-
func (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {
defaultSettings := s.getDefaultSettings()
defaultSettingVars := defaultSettings.ToSettingVariableSlice(models.SettingVisibilityAll, false)
diff --git a/backend/internal/services/settings_service_test.go b/backend/internal/services/settings_service_test.go
index 8e6e04065..c6f747b7c 100644
--- a/backend/internal/services/settings_service_test.go
+++ b/backend/internal/services/settings_service_test.go
@@ -9,6 +9,7 @@ import (
"github.com/stretchr/testify/require"
"gorm.io/gorm"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"
"github.com/getarcaneapp/arcane/backend/v2/internal/config"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
"github.com/getarcaneapp/arcane/backend/v2/internal/models"
@@ -151,6 +152,121 @@ func TestSettingsService_AvatarMaxUploadSizeDefaultAndUpdate(t *testing.T) {
require.Equal(t, "8", current.AvatarMaxUploadSizeMb.Value)
}
+func TestSettingsServiceUpdateSettingsRejectsOIDCIssuerChangeWithStoredSecretInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, svc.UpdateSetting(ctx, "oidcIssuerUrl", "https://issuer.example.com"))
+ require.NoError(t, svc.UpdateSetting(ctx, "oidcClientSecret", "old-client-secret"))
+
+ _, err = svc.UpdateSettings(ctx, settings.Update{
+ OidcIssuerUrl: new("https://attacker.example.com"),
+ OidcClientSecret: new(""),
+ })
+ require.ErrorIs(t, err, common.ErrValidation)
+
+ current, loadErr := svc.GetSettings(ctx)
+ require.NoError(t, loadErr)
+ require.Equal(t, "https://issuer.example.com", current.OidcIssuerUrl.Value)
+ require.Equal(t, "old-client-secret", current.OidcClientSecret.Value)
+}
+
+func TestSettingsServiceUpdateSettingsAllowsOIDCIssuerChangeWithReplacementSecretInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, svc.UpdateSetting(ctx, "oidcIssuerUrl", "https://issuer.example.com"))
+ require.NoError(t, svc.UpdateSetting(ctx, "oidcClientSecret", "old-client-secret"))
+
+ _, err = svc.UpdateSettings(ctx, settings.Update{
+ OidcIssuerUrl: new("https://replacement.example.com"),
+ OidcClientSecret: new("new-client-secret"),
+ })
+ require.NoError(t, err)
+
+ current, loadErr := svc.GetSettings(ctx)
+ require.NoError(t, loadErr)
+ require.Equal(t, "https://replacement.example.com", current.OidcIssuerUrl.Value)
+ require.Equal(t, "new-client-secret", current.OidcClientSecret.Value)
+}
+
+func TestSettingsServiceUpdateSettingsRejectsTrivyServerChangeWithStoredTokenInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, svc.UpdateSetting(ctx, "trivyServerUrl", "https://trivy.example.com"))
+ require.NoError(t, svc.UpdateSetting(ctx, "trivyServerToken", "old-trivy-token"))
+
+ _, err = svc.UpdateSettings(ctx, settings.Update{
+ TrivyServerUrl: new("https://attacker.example.com"),
+ })
+ require.ErrorIs(t, err, common.ErrValidation)
+
+ current, loadErr := svc.GetSettings(ctx)
+ require.NoError(t, loadErr)
+ require.Equal(t, "https://trivy.example.com", current.TrivyServerUrl.Value)
+ require.Equal(t, "old-trivy-token", current.TrivyServerToken.Value)
+}
+
+func TestSettingsServiceUpdateSettingsAllowsTrivyServerChangeWithReplacementTokenInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, svc.UpdateSetting(ctx, "trivyServerUrl", "https://trivy.example.com"))
+ require.NoError(t, svc.UpdateSetting(ctx, "trivyServerToken", "old-trivy-token"))
+
+ _, err = svc.UpdateSettings(ctx, settings.Update{
+ TrivyServerUrl: new("https://replacement.example.com"),
+ TrivyServerToken: new("new-trivy-token"),
+ })
+ require.NoError(t, err)
+
+ current, loadErr := svc.GetSettings(ctx)
+ require.NoError(t, loadErr)
+ require.Equal(t, "https://replacement.example.com", current.TrivyServerUrl.Value)
+ require.Equal(t, "new-trivy-token", current.TrivyServerToken.Value)
+}
+
+func TestSettingsServiceUpdateSettingsAllowsClearingTrivyServerWithStoredTokenInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, svc.UpdateSetting(ctx, "trivyServerUrl", "https://trivy.example.com"))
+ require.NoError(t, svc.UpdateSetting(ctx, "trivyServerToken", "old-trivy-token"))
+
+ _, err = svc.UpdateSettings(ctx, settings.Update{
+ TrivyServerUrl: new(""),
+ })
+ require.NoError(t, err)
+
+ current, loadErr := svc.GetSettings(ctx)
+ require.NoError(t, loadErr)
+ require.Empty(t, current.TrivyServerUrl.Value)
+ require.Equal(t, "old-trivy-token", current.TrivyServerToken.Value)
+}
+
+func TestSettingsServiceUpdateSettingsAllowsTrivyServerChangeWithoutStoredTokenInternal(t *testing.T) {
+ ctx := context.Background()
+ db := setupSettingsTestDB(t)
+ svc, err := NewSettingsService(ctx, db)
+ require.NoError(t, err)
+ require.NoError(t, svc.UpdateSetting(ctx, "trivyServerUrl", "https://trivy.example.com"))
+
+ _, err = svc.UpdateSettings(ctx, settings.Update{
+ TrivyServerUrl: new("https://replacement.example.com"),
+ })
+ require.NoError(t, err)
+
+ current, loadErr := svc.GetSettings(ctx)
+ require.NoError(t, loadErr)
+ require.Equal(t, "https://replacement.example.com", current.TrivyServerUrl.Value)
+}
+
func TestSettingsService_PruneUnknownSettings_RemovesStaleKeys(t *testing.T) {
ctx := context.Background()
db := setupSettingsTestDB(t)
diff --git a/backend/internal/services/volume_service.go b/backend/internal/services/volume_service.go
index 700e40236..de2a43b73 100644
--- a/backend/internal/services/volume_service.go
+++ b/backend/internal/services/volume_service.go
@@ -319,8 +319,13 @@ func (s *VolumeService) ListDirectory(ctx context.Context, volumeName, dirPath s
defer cleanup()
targetPath := path.Join("/volume", sanitizedPath)
- quotedPath := strconv.Quote(targetPath)
- cmd := []string{"sh", "-c", fmt.Sprintf("find %s -mindepth 1 -maxdepth 1 | while IFS= read -r f; do out=$(stat -c \"%%s %%Y %%f %%A\" -- \"$f\" 2>/dev/null) || continue; printf \"%%s\\0%%s\\0\" \"$f\" \"$out\"; done", quotedPath)}
+ cmd := []string{
+ "sh",
+ "-c",
+ `find "$1" -mindepth 1 -maxdepth 1 | while IFS= read -r f; do out=$(stat -c "%s %Y %f %A" -- "$f" 2>/dev/null) || continue; printf "%s\0%s\0" "$f" "$out"; done`,
+ "sh",
+ targetPath,
+ }
stdout, _, err := s.execInContainerInternal(ctx, containerID, cmd)
if err != nil {
return nil, errors.WrapIf(err, "failed to list directory")
diff --git a/backend/pkg/authz/access_policy.go b/backend/pkg/authz/access_policy.go
index a39a83e1d..4e8299e94 100644
--- a/backend/pkg/authz/access_policy.go
+++ b/backend/pkg/authz/access_policy.go
@@ -97,7 +97,7 @@ var accessSurfacesInternal = []AccessSurface{
settingsCategorySurfaceInternal("authentication", "/settings/authentication", "Authentication", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),
settingsCategorySurfaceInternal("build", "/settings/builds", "Builds", AccessScopeModeGlobalOnly, []string{PermSettingsRead}),
settingsCategorySurfaceInternal("jobschedule", "", "Automations", AccessScopeModeSelectedEnvPlusGlobal, []string{PermJobsManage}),
- settingsCategorySurfaceInternal("notifications", "/settings/notifications", "Notifications", AccessScopeModeSelectedEnvPlusGlobal, []string{PermNotificationsManage}),
+ settingsCategorySurfaceInternal("notifications", "/settings/notifications", "Notifications", AccessScopeModeGlobalOnly, []string{PermNotificationsManage}),
settingsCategorySurfaceInternal("roles", "/settings/roles", "Roles", AccessScopeModeGlobalOnly, []string{PermRolesList, PermRolesRead}),
routeSurfaceInternal("route.settings.roles.new", "/settings/roles/new", "Create role", AccessScopeModeGlobalOnly, []string{PermRolesList, PermRolesRead}, 0),
routeSurfaceInternal("route.settings.roles.detail", "/settings/roles/{id}", "Role", AccessScopeModeGlobalOnly, []string{PermRolesList, PermRolesRead}, 0),
diff --git a/backend/pkg/authz/access_policy_test.go b/backend/pkg/authz/access_policy_test.go
index 2383913f1..2e7bc4abf 100644
--- a/backend/pkg/authz/access_policy_test.go
+++ b/backend/pkg/authz/access_policy_test.go
@@ -31,6 +31,10 @@ func TestAccessSurfaceRegistryDefinesSettingsCustomizeAndLandingSemantics(t *tes
require.Empty(t, jobSchedule.URL)
require.ElementsMatch(t, []string{authz.PermJobsManage}, jobSchedule.Permissions)
+ notifications := requireAccessSurfaceInternal(t, "settings.category.notifications")
+ require.Equal(t, authz.AccessScopeModeGlobalOnly, notifications.ScopeMode)
+ require.ElementsMatch(t, []string{authz.PermNotificationsManage}, notifications.Permissions)
+
templates := requireAccessSurfaceInternal(t, "customize.category.templates")
require.Equal(t, authz.AccessSurfaceKindCustomizeCategory, templates.Kind)
require.Equal(t, authz.AccessScopeModeGlobalOnly, templates.ScopeMode)
@@ -89,6 +93,12 @@ func TestCanAccessSurfaceEvaluatesScopeModesAndLandingChildren(t *testing.T) {
require.True(t, authz.CanAccessSurface(jobsPS, "landing.settings", "env-a"))
require.False(t, authz.CanAccessSurface(jobsPS, "settings.category.jobschedule", "env-b"))
+ notificationPS := authz.NewPermissionSet()
+ notificationPS.AddEnv("env-a", authz.PermNotificationsManage)
+ require.False(t, authz.CanAccessSurface(notificationPS, "settings.category.notifications", "env-a"))
+ notificationPS.AddGlobal(authz.PermNotificationsManage)
+ require.True(t, authz.CanAccessSurface(notificationPS, "settings.category.notifications", "env-a"))
+
customizePS := authz.NewPermissionSet()
customizePS.AddGlobal(authz.PermCustomizeManage)
require.True(t, authz.CanAccessSurface(customizePS, "customize.category.registries", "env-a"))
diff --git a/backend/pkg/authz/catalog.go b/backend/pkg/authz/catalog.go
index 0b2faf0dd..8766bba28 100644
--- a/backend/pkg/authz/catalog.go
+++ b/backend/pkg/authz/catalog.go
@@ -191,7 +191,7 @@ var permissionCatalog = []PermissionCatalogResource{
{"jobs", "Background Jobs", PermissionScopeEnv, []PermissionCatalogAction{
{"manage", PermJobsManage, "Manage", ""},
}},
- {"notifications", "Notifications", PermissionScopeEnv, []PermissionCatalogAction{
+ {"notifications", "Notifications", PermissionScopeGlobal, []PermissionCatalogAction{
{"manage", PermNotificationsManage, "Manage", ""},
}},
{"dashboard", "Dashboard", PermissionScopeEnv, []PermissionCatalogAction{
diff --git a/backend/pkg/authz/permission_set_test.go b/backend/pkg/authz/permission_set_test.go
index 903b226fe..ec21860f5 100644
--- a/backend/pkg/authz/permission_set_test.go
+++ b/backend/pkg/authz/permission_set_test.go
@@ -317,3 +317,23 @@ func TestPermissionCatalogDerivesKnownPermissionsAndScopes(t *testing.T) {
}
}
}
+
+func TestNotificationsManageRequiresGlobalScope(t *testing.T) {
+ if !IsOrgLevel(PermNotificationsManage) {
+ t.Fatal("notifications:manage must be org-level for manager-global notification settings")
+ }
+ if IsEnvScoped(PermNotificationsManage) {
+ t.Fatal("notifications:manage must not be environment-scoped")
+ }
+
+ ps := NewPermissionSet()
+ ps.AddEnv("env-1", PermNotificationsManage)
+ if ps.Allows(PermNotificationsManage, "") {
+ t.Fatal("an environment-scoped notification grant must not authorize the global resource")
+ }
+
+ ps.AddGlobal(PermNotificationsManage)
+ if !ps.Allows(PermNotificationsManage, "") {
+ t.Fatal("a global notification grant must authorize the global resource")
+ }
+}
diff --git a/backend/pkg/authz/permissions.go b/backend/pkg/authz/permissions.go
index 598437da3..a7e66566d 100644
--- a/backend/pkg/authz/permissions.go
+++ b/backend/pkg/authz/permissions.go
@@ -83,9 +83,10 @@ const (
PermGitReposTest = "git-repositories:test"
PermGitReposSync = "git-repositories:sync"
- PermEventsRead = "events:read"
- PermEventsDelete = "events:delete"
- PermCustomizeManage = "customize:manage"
+ PermEventsRead = "events:read"
+ PermEventsDelete = "events:delete"
+ PermCustomizeManage = "customize:manage"
+ PermNotificationsManage = "notifications:manage"
// PermDiagnosticsRead gates the admin-only runtime diagnostics surface
// (runtime/memory/GC stats, WebSocket metrics, pprof profiles, and the live
@@ -178,9 +179,8 @@ const (
PermWebhooksUpdate = "webhooks:update"
PermWebhooksDelete = "webhooks:delete"
- PermJobsManage = "jobs:manage"
- PermNotificationsManage = "notifications:manage"
- PermDashboardRead = "dashboard:read"
+ PermJobsManage = "jobs:manage"
+ PermDashboardRead = "dashboard:read"
PermSystemRead = "system:read"
PermSystemPrune = "system:prune"
diff --git a/backend/pkg/utils/path_util.go b/backend/pkg/utils/path_util.go
index 8385f7511..f61999f84 100644
--- a/backend/pkg/utils/path_util.go
+++ b/backend/pkg/utils/path_util.go
@@ -15,8 +15,11 @@ func SanitizeBrowsePath(input string) (string, error) {
}
cleaned := path.Clean(trimmed)
+ if cleaned == ".." || strings.HasPrefix(cleaned, "../") {
+ return "", errors.New("invalid path: path traversal not allowed")
+ }
if !path.IsAbs(cleaned) {
- cleaned = "/" + cleaned
+ cleaned = path.Clean("/" + cleaned)
}
if strings.Contains(cleaned, "/../") || strings.HasSuffix(cleaned, "/..") || cleaned == "/.." {
return "", errors.New("invalid path: path traversal not allowed")
diff --git a/backend/pkg/utils/path_util_test.go b/backend/pkg/utils/path_util_test.go
new file mode 100644
index 000000000..07d868365
--- /dev/null
+++ b/backend/pkg/utils/path_util_test.go
@@ -0,0 +1,37 @@
+package utils
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestSanitizeBrowsePath(t *testing.T) {
+ tests := []struct {
+ name string
+ input string
+ want string
+ wantErr bool
+ }{
+ {name: "current directory is root", input: ".", want: "/"},
+ {name: "parent traversal is rejected", input: "..", wantErr: true},
+ {name: "root stays root", input: "/", want: "/"},
+ {name: "empty is root", input: "", want: "/"},
+ {name: "relative path is rooted", input: "a/b", want: "/a/b"},
+ {name: "absolute path is cleaned", input: "/a/../b", want: "/b"},
+ {name: "escaping relative traversal is rejected", input: "a/../../../etc", wantErr: true},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := SanitizeBrowsePath(tt.input)
+ if tt.wantErr {
+ require.Error(t, err)
+ return
+ }
+
+ require.NoError(t, err)
+ require.Equal(t, tt.want, got)
+ })
+ }
+}
diff --git a/backend/pkg/utils/validation/credential_target.go b/backend/pkg/utils/validation/credential_target.go
index 43e4c8a7a..b59c057f5 100644
--- a/backend/pkg/utils/validation/credential_target.go
+++ b/backend/pkg/utils/validation/credential_target.go
@@ -3,6 +3,7 @@ package validation
import (
"fmt"
"slices"
+ "strings"
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
@@ -22,6 +23,9 @@ func ValidateCredentialTargetChange(
if nextTarget == nil {
return nil
}
+ if strings.TrimSpace(*nextTarget) == "" {
+ return nil
+ }
if normalize == nil {
normalize = func(value string) string { return value }
diff --git a/backend/pkg/utils/validation/credential_target_test.go b/backend/pkg/utils/validation/credential_target_test.go
index e20b05e16..c86f8d4a8 100644
--- a/backend/pkg/utils/validation/credential_target_test.go
+++ b/backend/pkg/utils/validation/credential_target_test.go
@@ -37,6 +37,12 @@ func TestValidateCredentialTargetChange(t *testing.T) {
nextTarget: new("registry.example.com"),
storedCredentials: map[string]bool{"token": true},
},
+ {
+ name: "cleared target",
+ currentTarget: "registry.example.com",
+ nextTarget: new(" "),
+ storedCredentials: map[string]bool{"token": true},
+ },
{
name: "normalized target alias",
currentTarget: "https://registry.example.com",