Skip to content

Modern Docker Management, Designed for Everyone

fix: normalize identity and display text with Kit struct tags (#3856)

Kyle Mendellb51613f2c6d3
diff --git a/backend/api/api.go b/backend/api/api.go
index 88005123b..a89d5bffc 100644
--- a/backend/api/api.go
+++ b/backend/api/api.go
@@ -35,7 +35,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/internal/project"
"github.com/getarcaneapp/arcane/backend/v2/internal/registry"
"github.com/getarcaneapp/arcane/backend/v2/internal/role"
- s3domain "github.com/getarcaneapp/arcane/backend/v2/internal/s3"
+ "github.com/getarcaneapp/arcane/backend/v2/internal/s3"
"github.com/getarcaneapp/arcane/backend/v2/internal/search"
"github.com/getarcaneapp/arcane/backend/v2/internal/settings"
"github.com/getarcaneapp/arcane/backend/v2/internal/swarm"
@@ -231,7 +231,7 @@ type HandlerDeps struct {
Build *build.BuildService
BuildWorkspace *build.BuildWorkspaceService
Volume *volume.Module
- S3Destination *s3domain.Module
+ S3Destination *s3.Module
SystemBackup *systembackup.Module
Network *network.NetworkService
Port *port.PortService
@@ -319,6 +319,7 @@ func SetupAPI(e *echo.Echo, apiGroup *echo.Group, appCtx handlerutil.ActivityApp
// Add authentication middleware
api.UseMiddleware(auth.NewHumaMiddleware(api, deps.Auth.Service(), deps.ApiKey.Service(), deps.Role.Service(), deps.Environment.Service(), cfg))
api.UseMiddleware(middleware.NewActivityBatchID())
+ registerNormalizationInternal(api)
// Register all Huma handlers
registerHandlersInternal(api, deps, appCtx, cfg)
@@ -398,6 +399,7 @@ func SetupAPIForSpec() huma.API {
api := humaecho.NewWithGroup(e, apiGroup, humaConfig)
// Register handlers with zero-value dependencies for schema discovery only.
+ registerNormalizationInternal(api)
registerHandlersInternal(api, HandlerDeps{}, handlerutil.NewActivityAppContext(context.Background()), nil)
return api
diff --git a/backend/api/json_serializer.go b/backend/api/json_serializer.go
index bce84eba0..4ad52e4dc 100644
--- a/backend/api/json_serializer.go
+++ b/backend/api/json_serializer.go
@@ -10,6 +10,7 @@ import (
"emperror.dev/errors"
"github.com/labstack/echo/v5"
+ "go.getarcane.app/kit/normalization"
)
type jsonV2Serializer struct{}
@@ -28,6 +29,9 @@ func (jsonV2Serializer) Serialize(c *echo.Context, value any, indent string) err
func (jsonV2Serializer) Deserialize(c *echo.Context, value any) error {
err := json.UnmarshalRead(c.Request().Body, value, jsonV2APIOptions)
if err == nil {
+ if err := normalization.Normalize(value); err != nil {
+ return echo.NewHTTPError(http.StatusUnprocessableEntity, err.Error()).Wrap(err)
+ }
return nil
}
diff --git a/backend/api/normalization.go b/backend/api/normalization.go
new file mode 100644
index 000000000..d77c10a62
--- /dev/null
+++ b/backend/api/normalization.go
@@ -0,0 +1,155 @@
+package api
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "mime"
+ "net"
+ "net/http"
+ "reflect"
+ "strings"
+ "time"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"
+ "go.getarcane.app/kit/normalization"
+)
+
+// Install before routes so Huma validates normalized input.
+func registerNormalizationInternal(api huma.API) {
+ api.OpenAPI().OnAddOperation = append(api.OpenAPI().OnAddOperation, func(_ *huma.OpenAPI, op *huma.Operation) {
+ typ := normalizationBodyTypeInternal(api, op)
+ if typ == nil {
+ return
+ }
+ if _, err := normalization.HasRules(typ); err != nil {
+ panic(fmt.Errorf("operation %s normalization: %w", op.OperationID, err))
+ }
+ })
+ api.UseMiddleware(func(ctx huma.Context, next func(huma.Context)) {
+ op := ctx.Operation()
+ typ := normalizationBodyTypeInternal(api, op)
+ if typ == nil {
+ next(ctx)
+ return
+ }
+ hasRules, err := normalization.HasRules(typ)
+ if err != nil {
+ writeNormalizationErrorInternal(api, ctx, http.StatusInternalServerError, "invalid request normalization configuration")
+ return
+ }
+ if !hasRules || !isNormalizationJSONInternal(ctx.Header("Content-Type")) {
+ next(ctx)
+ return
+ }
+
+ body, err := readNormalizationBodyInternal(ctx)
+ if err != nil {
+ status := http.StatusInternalServerError
+ if statusErr, ok := errors.AsType[huma.StatusError](err); ok {
+ status = statusErr.GetStatus()
+ }
+ writeNormalizationErrorInternal(api, ctx, status, err.Error())
+ return
+ }
+ if normalized, normalizeErr := normalization.NormalizeJSON(body, typ); normalizeErr == nil {
+ body = normalized
+ }
+ // Let Huma report malformed JSON and incompatible values as usual.
+ request := humaecho.Unwrap(ctx).Request()
+ request.Body = io.NopCloser(bytes.NewReader(body))
+ request.ContentLength = int64(len(body))
+ next(ctx)
+ })
+}
+
+func normalizationBodyTypeInternal(api huma.API, op *huma.Operation) reflect.Type {
+ if op.RequestBody == nil {
+ return nil
+ }
+ media := op.RequestBody.Content["application/json"]
+ if media == nil || media.Schema == nil {
+ return nil
+ }
+ return normalizationSchemaTypeInternal(api.OpenAPI().Components.Schemas, media.Schema)
+}
+
+func normalizationSchemaTypeInternal(registry huma.Registry, schema *huma.Schema) reflect.Type {
+ if schema.Ref != "" {
+ return registry.TypeFromRef(schema.Ref)
+ }
+ if schema.Type == "array" && schema.Items != nil {
+ if item := normalizationSchemaTypeInternal(registry, schema.Items); item != nil {
+ return reflect.SliceOf(item)
+ }
+ }
+ return nil
+}
+
+func isNormalizationJSONInternal(contentType string) bool {
+ if contentType == "" {
+ return true
+ }
+ mediaType, _, err := mime.ParseMediaType(contentType)
+ return err == nil && (mediaType == "application/json" || strings.HasPrefix(mediaType, "application/") && strings.HasSuffix(mediaType, "+json"))
+}
+
+func writeNormalizationErrorInternal(api huma.API, ctx huma.Context, status int, message string) {
+ if err := huma.WriteErr(api, ctx, status, message); err != nil {
+ slog.WarnContext(ctx.Context(), "failed to write normalization response", "error", err)
+ }
+}
+
+// Read the original request with the same limits Huma applies.
+// It closes the original reader and reports errors with Huma HTTP status codes.
+func readNormalizationBodyInternal(ctx huma.Context) ([]byte, error) {
+ op := ctx.Operation()
+ if op.BodyReadTimeout != 0 {
+ controller := http.NewResponseController(humaecho.Unwrap(ctx).Response())
+ deadline := time.Time{}
+ if op.BodyReadTimeout > 0 {
+ deadline = time.Now().Add(op.BodyReadTimeout)
+ }
+ if err := controller.SetReadDeadline(deadline); err != nil {
+ // Some response writers do not expose connection deadlines.
+ if !errors.Is(err, http.ErrNotSupported) {
+ return nil, huma.Error500InternalServerError("cannot configure request body read deadline", err)
+ }
+ } else if op.BodyReadTimeout > 0 {
+ defer func() {
+ if err := controller.SetReadDeadline(time.Time{}); err != nil {
+ slog.WarnContext(ctx.Context(), "failed to clear request body read deadline", "error", err)
+ }
+ }()
+ }
+ }
+ reader := ctx.BodyReader()
+ if reader == nil {
+ return nil, nil
+ }
+ if closer, ok := reader.(io.Closer); ok {
+ defer func() {
+ if err := closer.Close(); err != nil {
+ slog.WarnContext(ctx.Context(), "failed to close request body", "error", err)
+ }
+ }()
+ }
+ if op.MaxBodyBytes > 0 {
+ reader = io.LimitReader(reader, op.MaxBodyBytes)
+ }
+ body, err := io.ReadAll(reader)
+ // Huma rejects bodies at exactly MaxBodyBytes as well as larger ones.
+ if op.MaxBodyBytes > 0 && int64(len(body)) == op.MaxBodyBytes {
+ return nil, huma.Error413RequestEntityTooLarge(fmt.Sprintf("request body is too large limit=%d bytes", op.MaxBodyBytes))
+ }
+ if err != nil {
+ if netErr, ok := errors.AsType[net.Error](err); ok && netErr.Timeout() {
+ return nil, huma.Error408RequestTimeout("request body read timeout")
+ }
+ return nil, huma.Error500InternalServerError("cannot read request body", err)
+ }
+ return body, nil
+}
diff --git a/backend/api/normalization_test.go b/backend/api/normalization_test.go
new file mode 100644
index 000000000..df2d159c6
--- /dev/null
+++ b/backend/api/normalization_test.go
@@ -0,0 +1,261 @@
+package api
+
+import (
+ "bytes"
+ "context"
+ "encoding/json/v2"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/danielgtaylor/huma/v2/adapters/humaecho"
+ authtypes "github.com/getarcaneapp/arcane/types/v2/auth"
+ usertypes "github.com/getarcaneapp/arcane/types/v2/user"
+ "github.com/labstack/echo/v5"
+ "github.com/stretchr/testify/require"
+)
+
+type normalizationTestBody struct {
+ Name string `json:"name" minLength:"1" maxLength:"1" unorm:"nfc" trim:"true"`
+ Optional *string `json:"optional,omitempty" unorm:"nfc" trim:"true"`
+ Password string `json:"password,omitempty"`
+ Number uint64 `json:"number,omitempty"`
+}
+
+func TestNormalizationBeforeHumaValidation(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ status int
+ }{
+ {"normalized length", `{"name":" e\u0301 ","password":" e\u0301 ","number":9007199254740993}`, http.StatusOK},
+ {"required whitespace", `{"name":" \t "}`, http.StatusUnprocessableEntity},
+ {"too long", `{"name":" ab "}`, http.StatusUnprocessableEntity},
+ {"wrong type", `{"name":12}`, http.StatusUnprocessableEntity},
+ {"malformed", `{"name":`, http.StatusBadRequest},
+ {"missing required", `{}`, http.StatusUnprocessableEntity},
+ {"empty required body", ``, http.StatusBadRequest},
+ {"nil optional", `{"name":"x","optional":null}`, http.StatusOK},
+ {"empty optional", `{"name":"x","optional":" "}`, http.StatusOK},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ router := echo.New()
+ cfg := huma.DefaultConfig("test", "1")
+ cfg.Formats = map[string]huma.Format{"application/json": jsonV2Format, "json": jsonV2Format}
+ api := humaecho.New(router, cfg)
+ registerNormalizationInternal(api)
+ called := false
+ var received normalizationTestBody
+ huma.Register(api, huma.Operation{OperationID: "normalize", Method: http.MethodPost, Path: "/normalize"}, func(_ context.Context, input *struct{ Body normalizationTestBody }) (*struct{ Body normalizationTestBody }, error) {
+ called = true
+ received = input.Body
+ return &struct{ Body normalizationTestBody }{Body: input.Body}, nil
+ })
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "/normalize", strings.NewReader(tc.body))
+ request.Header.Set("Content-Type", "application/json")
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, tc.status, recorder.Code, recorder.Body.String())
+ require.Equal(t, tc.status == http.StatusOK, called)
+ if tc.status == http.StatusOK {
+ var result normalizationTestBody
+ require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &result))
+ switch tc.name {
+ case "normalized length":
+ require.Equal(t, "é", result.Name)
+ require.Equal(t, " e\u0301 ", result.Password)
+ require.Equal(t, uint64(9007199254740993), result.Number)
+ require.Nil(t, result.Optional)
+ case "nil optional":
+ require.Nil(t, result.Optional)
+ case "empty optional":
+ require.NotNil(t, received.Optional)
+ require.Empty(t, *received.Optional)
+ }
+ }
+ })
+ }
+ t.Run("identity fields pass through unchanged", func(t *testing.T) {
+ router := echo.New()
+ api := humaecho.New(router, huma.DefaultConfig("test", "1"))
+ registerNormalizationInternal(api)
+ var received usertypes.CreateUser
+ huma.Register(api, huma.Operation{OperationID: "create", Method: http.MethodPost, Path: "/create"}, func(_ context.Context, input *struct{ Body usertypes.CreateUser }) (*struct{}, error) {
+ received = input.Body
+ return &struct{}{}, nil
+ })
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "/create", strings.NewReader(`{"username":" Jose\u0301 ","email":" Jose\[email protected] ","displayName":" Jose\u0301 ","password":" password "}`))
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, http.StatusNoContent, recorder.Code, recorder.Body.String())
+ require.Equal(t, " Jose\u0301 ", received.Username)
+ require.Equal(t, " Jose\[email protected] ", *received.Email)
+ require.Equal(t, "José", *received.DisplayName)
+ require.Equal(t, " password ", received.Password)
+
+ var login authtypes.Login
+ huma.Register(api, huma.Operation{OperationID: "login", Method: http.MethodPost, Path: "/login"}, func(_ context.Context, input *struct{ Body authtypes.Login }) (*struct{}, error) {
+ login = input.Body
+ return &struct{}{}, nil
+ })
+ recorder = httptest.NewRecorder()
+ request = httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":" Jose\u0301 ","password":" password "}`))
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, http.StatusNoContent, recorder.Code, recorder.Body.String())
+ require.Equal(t, " Jose\u0301 ", login.Username)
+ require.Equal(t, " password ", login.Password)
+ })
+}
+
+func TestNormalizationBodyLimits(t *testing.T) {
+ router := echo.New()
+ api := humaecho.New(router, huma.DefaultConfig("test", "1"))
+ registerNormalizationInternal(api)
+ huma.Register(api, huma.Operation{OperationID: "limit", Method: http.MethodPost, Path: "/limit", MaxBodyBytes: 32}, func(_ context.Context, _ *struct{ Body normalizationTestBody }) (*struct{}, error) {
+ t.Fatal("oversized body must not reach application code")
+ return nil, nil
+ })
+ for _, size := range []int{32, 33, 128} {
+ recorder := httptest.NewRecorder()
+ body := `{"name":"x"}` + strings.Repeat(" ", size-len(`{"name":"x"}`))
+ router.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, "/limit", strings.NewReader(body)))
+ require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code)
+ }
+}
+
+type normalizationTimeoutReader struct {
+ body *strings.Reader
+ closeErr error
+ closed bool
+}
+
+func (r *normalizationTimeoutReader) Read(data []byte) (int, error) {
+ if r.body != nil {
+ return r.body.Read(data)
+ }
+ return 0, normalizationTimeoutError{}
+}
+
+func (r *normalizationTimeoutReader) Close() error {
+ r.closed = true
+ return r.closeErr
+}
+
+type normalizationResponseRecorder struct {
+ *httptest.ResponseRecorder
+
+ setupErr error
+ resetErr error
+ calls int
+}
+
+func (r *normalizationResponseRecorder) SetReadDeadline(deadline time.Time) error {
+ r.calls++
+ if r.calls == 1 {
+ return r.setupErr
+ }
+ if deadline.IsZero() {
+ return r.resetErr
+ }
+ return nil
+}
+
+type normalizationTimeoutError struct{}
+
+func (normalizationTimeoutError) Error() string { return "read timed out" }
+func (normalizationTimeoutError) Timeout() bool { return true }
+func (normalizationTimeoutError) Temporary() bool { return true }
+
+func TestNormalizationReadTimeout(t *testing.T) {
+ var logs bytes.Buffer
+ previousLogger := slog.Default()
+ slog.SetDefault(slog.New(slog.NewTextHandler(&logs, nil)))
+ t.Cleanup(func() { slog.SetDefault(previousLogger) })
+ for _, tc := range []struct {
+ name string
+ timeout time.Duration
+ readTimeout bool
+ setupErr, resetErr, closeErr error
+ status int
+ logMessage string
+ }{
+ {name: "read timeout", timeout: time.Second, readTimeout: true, status: http.StatusRequestTimeout},
+ {name: "unsupported deadline", timeout: time.Second, setupErr: fmt.Errorf("writer: %w", http.ErrNotSupported), status: http.StatusNoContent},
+ {name: "setting deadline fails", timeout: time.Second, setupErr: errors.New("deadline failed"), status: http.StatusInternalServerError},
+ {name: "disabling deadline fails", timeout: -1, setupErr: errors.New("deadline failed"), status: http.StatusInternalServerError},
+ {name: "reset fails", timeout: time.Second, resetErr: errors.New("reset failed"), status: http.StatusNoContent, logMessage: "failed to clear request body read deadline"},
+ {name: "close fails", timeout: time.Second, closeErr: errors.New("close failed"), status: http.StatusNoContent, logMessage: "failed to close request body"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ logs.Reset()
+ router := echo.New()
+ api := humaecho.New(router, huma.DefaultConfig("test", "1"))
+ registerNormalizationInternal(api)
+ called := false
+ huma.Register(api, huma.Operation{OperationID: "timeout", Method: http.MethodPost, Path: "/timeout", BodyReadTimeout: tc.timeout}, func(_ context.Context, _ *struct{ Body normalizationTestBody }) (*struct{}, error) {
+ called = true
+ return &struct{}{}, nil
+ })
+ recorder := &normalizationResponseRecorder{ResponseRecorder: httptest.NewRecorder(), setupErr: tc.setupErr, resetErr: tc.resetErr}
+ body := &normalizationTimeoutReader{closeErr: tc.closeErr}
+ if !tc.readTimeout {
+ body.body = strings.NewReader(`{"name":"x"}`)
+ }
+ request := httptest.NewRequest(http.MethodPost, "/timeout", nil)
+ request.Body = body
+ router.ServeHTTP(recorder, request)
+ require.Equal(t, tc.status, recorder.Code, recorder.Body.String())
+ require.Equal(t, tc.status == http.StatusNoContent, called)
+ if tc.status != http.StatusInternalServerError {
+ require.True(t, body.closed)
+ }
+ if tc.logMessage != "" {
+ require.Contains(t, logs.String(), tc.logMessage)
+ } else {
+ require.Empty(t, logs.String())
+ }
+ })
+ }
+}
+
+func TestNormalizationRejectsInvalidTagsAtRegistration(t *testing.T) {
+ router := echo.New()
+ api := humaecho.New(router, huma.DefaultConfig("test", "1"))
+ registerNormalizationInternal(api)
+ require.Panics(t, func() {
+ huma.Register(api, huma.Operation{OperationID: "invalid", Method: http.MethodPost, Path: "/invalid"}, func(_ context.Context, _ *struct {
+ Body struct {
+ Name string `json:"name" unorm:"invalid"`
+ }
+ }) (*struct{}, error) {
+ return nil, nil
+ })
+ })
+}
+
+func TestEchoSerializerNormalization(t *testing.T) {
+ router := echo.New()
+ request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":" e\u0301 ","password":" secret "}`))
+ ctx := router.NewContext(request, httptest.NewRecorder())
+ var result normalizationTestBody
+ require.NoError(t, (jsonV2Serializer{}).Deserialize(ctx, &result))
+ require.Equal(t, "é", result.Name)
+ require.Equal(t, " secret ", result.Password)
+}
+
+func TestEchoSerializerRejectsNormalizedEmptyName(t *testing.T) {
+ router := echo.New()
+ request := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":" "}`))
+ ctx := router.NewContext(request, httptest.NewRecorder())
+ var result normalizationTestBody
+ err := (jsonV2Serializer{}).Deserialize(ctx, &result)
+ var httpError *echo.HTTPError
+ require.ErrorAs(t, err, &httpError)
+ require.Equal(t, http.StatusUnprocessableEntity, httpError.Code)
+}
diff --git a/backend/go.mod b/backend/go.mod
index 62dae353c..d60537356 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -68,7 +68,7 @@ require (
go.getarcane.app/acfs v0.6.0
go.getarcane.app/builds v0.4.1
go.getarcane.app/docker/convert v0.3.1
- go.getarcane.app/kit v0.1.1
+ go.getarcane.app/kit v0.2.0
go.getarcane.app/streams v0.4.3
go.getarcane.app/sys/cgroup v0.2.3
go.getarcane.app/sys/crypto v0.2.1
@@ -88,6 +88,7 @@ require (
google.golang.org/protobuf v1.36.12
gorm.io/driver/postgres v1.6.2
gorm.io/gorm v1.31.2
+ modernc.org/sqlite v1.57.0
)
require (
@@ -308,6 +309,5 @@ require (
modernc.org/libc v1.75.6 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.12.1 // indirect
- modernc.org/sqlite v1.57.0 // indirect
tags.cncf.io/container-device-interface v1.1.0 // indirect
)
diff --git a/backend/go.sum b/backend/go.sum
index be7f050ed..c180e1f93 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -740,6 +740,8 @@ go.getarcane.app/docker/convert v0.3.1 h1:VcC2gtTFtGBrHTSBd0RodA0u+aerRAYVJIah7p
go.getarcane.app/docker/convert v0.3.1/go.mod h1:9ResEOrcsXh6ksRE5MMYnAFJ2STeJzj6zz1wCOP0mTs=
go.getarcane.app/kit v0.1.1 h1:EN3s6J2FvpJOULwm7wESr8CC0FC9eMgCnW9nQGEqcY0=
go.getarcane.app/kit v0.1.1/go.mod h1:oiH4hLowxfQYFtmldyk/y79XYBHYfzgd86MrSQS9UEg=
+go.getarcane.app/kit v0.2.0 h1:3PPHo5nHuns1vjqmCMFPFdnmbH/qQOserONCba/gBi4=
+go.getarcane.app/kit v0.2.0/go.mod h1:TGqQCbAJs3ldzkFncXZ93wTVSDhAMQlqyNdVO2CNjIk=
go.getarcane.app/streams v0.4.3 h1:Rzg6xCWzYmD4IN+GiKYmAc8HqCgVIq/sQ4DC3OxiZ1o=
go.getarcane.app/streams v0.4.3/go.mod h1:SC/7A3pR8RanF5DqdX99A40qEw13TbmmbEtJK3yPuy4=
go.getarcane.app/sys/cgroup v0.2.3 h1:+eGLUC+3Ct+BNcPBQwC/g/psDOzjWN2vUr6KhKyNWgI=
diff --git a/backend/internal/apikey/service.go b/backend/internal/apikey/service.go
index 20a2adeb2..937168a47 100644
--- a/backend/internal/apikey/service.go
+++ b/backend/internal/apikey/service.go
@@ -12,6 +12,8 @@ import (
"sync/atomic"
"time"
+ "go.getarcane.app/kit/normalization"
+
"emperror.dev/errors"
"github.com/samber/hot"
@@ -332,6 +334,9 @@ func (s *ApiKeyService) invalidateValidatedKeysInternal(ids ...string) {
}
func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerPerms *authz.PermissionSet, req apikey.CreateApiKey) (*apikey.ApiKeyCreatedDto, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return nil, err
+ }
if err := validateGrantsAgainstPermissionSetInternal(callerPerms, req.Permissions); err != nil {
return nil, err
}
@@ -425,6 +430,9 @@ func toApiKeyPermissionRowsInternal(apiKeyID string, grants []apikey.PermissionG
// no permission grants of their own; the auth middleware resolves them to the
// owner's role permissions, so there is nothing to validate or escalate here.
func (s *ApiKeyService) CreatePersonalApiKey(ctx context.Context, userID string, req apikey.CreateUserApiKey) (*apikey.ApiKeyCreatedDto, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return nil, err
+ }
rawKey, err := s.generateApiKey()
if err != nil {
return nil, err
@@ -856,6 +864,9 @@ func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([
}
func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.PermissionSet, id string, req apikey.UpdateApiKey) (*apikey.ApiKey, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return nil, err
+ }
var ak ApiKey
if err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
diff --git a/backend/internal/apikey/service_test.go b/backend/internal/apikey/service_test.go
index 905fdea6d..619143f9f 100644
--- a/backend/internal/apikey/service_test.go
+++ b/backend/internal/apikey/service_test.go
@@ -366,8 +366,11 @@ func TestCreatePersonalApiKeyHasNoGrantsAndCannotGainAny(t *testing.T) {
service, db, userService := setupAPIKeyService(t)
user := createTestAPIKeyUser(t, ctx, userService, "user-personal")
- created, err := service.CreatePersonalApiKey(ctx, user.ID, apikey.CreateUserApiKey{Name: "personal"})
+ _, err := service.CreatePersonalApiKey(ctx, user.ID, apikey.CreateUserApiKey{Name: " \t "})
+ require.EqualError(t, err, "name: must contain at least 1 characters after normalization")
+ created, err := service.CreatePersonalApiKey(ctx, user.ID, apikey.CreateUserApiKey{Name: " cafe\u0301 personal "})
require.NoError(t, err)
+ require.Equal(t, "café personal", created.Name)
require.Equal(t, ApiKeyKindPersonal, created.Kind)
require.Empty(t, created.Permissions)
require.Equal(t, ApiKeyKindPersonal, fetchAPIKey(t, db, created.ID).Kind)
diff --git a/backend/internal/apns/service.go b/backend/internal/apns/service.go
index a2d03508f..48233ec0c 100644
--- a/backend/internal/apns/service.go
+++ b/backend/internal/apns/service.go
@@ -19,6 +19,8 @@ import (
"time"
"uuid"
+ "go.getarcane.app/kit/normalization"
+
"emperror.dev/errors"
"go.getarcane.app/sys/crypto"
"gorm.io/gorm"
@@ -293,6 +295,9 @@ func (s *ApnsService) Status(ctx context.Context, userID string) (apnstypes.Stat
}
func (s *ApnsService) RegisterDevice(ctx context.Context, userID string, req apnstypes.RegisterDeviceRequest) (apnstypes.Device, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return apnstypes.Device{}, err
+ }
if !s.Enabled(ctx) {
return apnstypes.Device{}, common.ErrApnsDisabled
}
@@ -314,7 +319,7 @@ func (s *ApnsService) RegisterDevice(ctx context.Context, userID string, req apn
case err == nil && existing.UserID != userID:
return apnstypes.Device{}, common.ErrApnsDeviceConflict
case err == nil:
- existing.Label = strings.TrimSpace(req.Label)
+ existing.Label = req.Label
existing.Events = events
existing.EnvironmentIDs = environmentIDs
existing.LastSeenAt = &now
@@ -325,7 +330,7 @@ func (s *ApnsService) RegisterDevice(ctx context.Context, userID string, req apn
case !errors.Is(err, gorm.ErrRecordNotFound):
return apnstypes.Device{}, errors.WrapIf(err, "failed to load push device")
}
- device := Device{UserID: userID, RecipientID: req.RecipientID, Label: strings.TrimSpace(req.Label), Events: events, EnvironmentIDs: environmentIDs, LastSeenAt: &now}
+ device := Device{UserID: userID, RecipientID: req.RecipientID, Label: req.Label, Events: events, EnvironmentIDs: environmentIDs, LastSeenAt: &now}
if err := s.db.WithContext(ctx).Create(&device).Error; err != nil {
return apnstypes.Device{}, errors.WrapIf(err, "failed to register push device")
}
@@ -344,12 +349,15 @@ func (s *ApnsService) deviceInternal(ctx context.Context, userID, id string) (*D
}
func (s *ApnsService) UpdateDevice(ctx context.Context, userID, id string, req apnstypes.UpdateDeviceRequest) (apnstypes.Device, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return apnstypes.Device{}, err
+ }
device, err := s.deviceInternal(ctx, userID, id)
if err != nil {
return apnstypes.Device{}, err
}
if req.Label != nil {
- device.Label = strings.TrimSpace(*req.Label)
+ device.Label = *req.Label
}
if req.Events != nil {
device.Events = *req.Events
diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.go
index c0dfa3c98..39692940d 100644
--- a/backend/internal/auth/service.go
+++ b/backend/internal/auth/service.go
@@ -32,6 +32,7 @@ import (
"github.com/lestrrat-go/jwx/v4/jwa"
"github.com/lestrrat-go/jwx/v4/jwt"
"github.com/samber/hot"
+ "go.getarcane.app/kit/normalization"
)
const (
@@ -382,6 +383,9 @@ func (s *AuthService) LogLogout(ctx context.Context, user *common.User) {
}
func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {
+ if err := normalization.Normalize(&userInfo); err != nil {
+ return nil, false, err
+ }
user, err := s.userService.GetUserByOidcSubjectId(ctx, userInfo.Subject)
if err != nil && !errors.Is(err, common.ErrUserNotFound) {
return nil, false, err
@@ -528,6 +532,9 @@ func (s *AuthService) resolveOidcUsernameInternal(ctx context.Context, userInfo
username = userInfo.PreferredUsername
}
+ // CreateUser trims usernames; check availability using the same value.
+ username = strings.TrimSpace(username)
+
if _, lookupErr := s.userService.GetUserByUsername(ctx, username); errors.Is(lookupErr, common.ErrUserNotFound) {
return username, nil
} else if lookupErr != nil {
diff --git a/backend/internal/auth/service_test.go b/backend/internal/auth/service_test.go
index 7cda86675..0483dbe03 100644
--- a/backend/internal/auth/service_test.go
+++ b/backend/internal/auth/service_test.go
@@ -806,26 +806,45 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_NoExistingUser_Creat
authSvc.userService = userSvc
authSvc.settingsService = settingsSvc
+ existing, err := userSvc.CreateUser(ctx, &common.User{
+ ID: "existing-canonical-identity", Username: "José", Email: new("né[email protected]"),
+ })
+ require.NoError(t, err)
+
userInfo := auth.OidcUserInfo{
- Subject: "sub-123",
- Email: "[email protected]",
- EmailVerified: false, // provider omitted/false
+ Subject: "sub-123",
+ Email: " ne\[email protected] ",
+ PreferredUsername: " Jose\u0301 ",
+ Name: " Jose\u0301 ",
+ EmailVerified: false, // provider omitted/false
}
created, isNew, err := authSvc.findOrCreateOidcUser(ctx, userInfo, &auth.OidcTokenResponse{AccessToken: "at"})
require.NoError(t, err)
require.True(t, isNew)
+ require.NotEqual(t, existing.ID, created.ID)
require.NotNil(t, created)
require.NotNil(t, created.OidcSubjectId)
require.Equal(t, userInfo.Subject, *created.OidcSubjectId)
require.NotNil(t, created.Email)
require.Equal(t, userInfo.Email, *created.Email)
+ require.Equal(t, "Jose\u0301", created.Username)
+ require.Equal(t, "José", *created.DisplayName)
require.NotEmpty(t, created.Username)
// Ensure the user actually persisted
fetched, err := userSvc.GetUserByOidcSubjectId(ctx, userInfo.Subject)
require.NoError(t, err)
require.Equal(t, created.ID, fetched.ID)
+ otherInfo := userInfo
+ otherInfo.Subject = "another-subject"
+ otherInfo.Email = "[email protected]"
+ other, isNew, err := authSvc.findOrCreateOidcUser(ctx, otherInfo, &auth.OidcTokenResponse{AccessToken: "other-token"})
+ require.NoError(t, err)
+ require.True(t, isNew)
+ require.NotEqual(t, created.ID, other.ID)
+ require.NotEqual(t, created.Username, other.Username)
+
}
func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_WithExistingUser_ReturnsError(t *testing.T) {
@@ -929,6 +948,8 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {
require.NoError(t, err)
for _, u := range []*common.User{
{ID: "u-email-login", Username: "bob", Email: new("[email protected]"), PasswordHash: hash},
+ {ID: "u-unicode", Username: "José", Email: new("josé@example.com"), PasswordHash: hash},
+ {ID: "u-decomposed", Username: "Jose\u0301", Email: new("jose\[email protected]"), PasswordHash: hash},
{ID: "u-dup-1", Username: "dup1", Email: new("[email protected]"), PasswordHash: hash},
{ID: "u-dup-2", Username: "dup2", Email: new("[email protected]"), PasswordHash: dupHash},
{ID: "u-carol", Username: "[email protected]", Email: new("[email protected]"), PasswordHash: hash},
@@ -939,6 +960,10 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {
require.NoError(t, err)
}
+ require.NoError(t, db.Create(&common.User{
+ ID: "u-legacy-spaces", Username: " Jose\u0301 ", Email: new(" [email protected] "), PasswordHash: hash,
+ }).Error)
+
tests := []struct {
name string
login string
@@ -946,6 +971,15 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {
wantID string
wantErr error
}{
+ {name: "composed username", login: "José", password: "hunter22!", wantID: "u-unicode"},
+ {name: "decomposed username stays distinct", login: "Jose\u0301", password: "hunter22!", wantID: "u-decomposed"},
+ {name: "composed email", login: "josé@example.com", password: "hunter22!", wantID: "u-unicode"},
+ {name: "decomposed email stays distinct", login: "jose\[email protected]", password: "hunter22!", wantID: "u-decomposed"},
+ {name: "legacy username whitespace", login: " Jose\u0301 ", password: "hunter22!", wantID: "u-legacy-spaces"},
+ {name: "legacy email whitespace", login: " [email protected] ", password: "hunter22!", wantID: "u-legacy-spaces"},
+ {name: "username whitespace is not a new alias", login: " José ", password: "hunter22!", wantErr: ErrInvalidCredentials},
+ {name: "email whitespace is not a new alias", login: " josé@example.com ", password: "hunter22!", wantErr: ErrInvalidCredentials},
+ {name: "password not trimmed", login: "José", password: " hunter22! ", wantErr: ErrInvalidCredentials},
{name: "email resolves user", login: "[email protected]", password: "hunter22!", wantID: "u-email-login"},
{name: "unknown email", login: "[email protected]", password: "hunter22!", wantErr: ErrInvalidCredentials},
{name: "duplicate email rejected", login: "[email protected]", password: "dup-two-pass!", wantErr: ErrInvalidCredentials},
diff --git a/backend/internal/common/user.go b/backend/internal/common/user.go
index 91b06e614..dcd031da9 100644
--- a/backend/internal/common/user.go
+++ b/backend/internal/common/user.go
@@ -14,7 +14,7 @@ type User struct {
Username string `json:"username" sortable:"true"`
PasswordHash string `json:"-" gorm:"column:password_hash"`
- DisplayName *string `json:"displayName,omitempty" gorm:"column:display_name" sortable:"true"`
+ DisplayName *string `json:"displayName,omitempty" gorm:"column:display_name" sortable:"true" unorm:"nfc" trim:"true"`
Email *string `json:"email,omitempty" sortable:"true"`
OidcSubjectId *string `json:"oidcSubjectId,omitempty" gorm:"column:oidc_subject_id"`
LastLogin *time.Time `json:"lastLogin,omitempty" gorm:"column:last_login" sortable:"true"`
diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go
index 56030816a..54821ceba 100644
--- a/backend/internal/database/database.go
+++ b/backend/internal/database/database.go
@@ -14,6 +14,8 @@ import (
"strings"
"time"
+ sqliteutil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/sqlite"
+
"emperror.dev/errors"
"github.com/libtnb/sqlite"
@@ -121,6 +123,9 @@ func connectDatabaseInternal(ctx context.Context, databaseURL string) (*DB, erro
switch {
case strings.HasPrefix(databaseURL, "file:"):
+ if err := sqliteutil.RegisterFunctions(); err != nil {
+ return nil, errors.WrapIf(err, "failed to register SQLite functions")
+ }
connString, err := ParseSQLiteConnectionString(databaseURL)
if err != nil {
return nil, errors.WrapIf(err, "failed to parse SQLite connection string")
diff --git a/backend/internal/database/database_test.go b/backend/internal/database/database_test.go
index 811adfbe7..a67d63518 100644
--- a/backend/internal/database/database_test.go
+++ b/backend/internal/database/database_test.go
@@ -3,11 +3,17 @@ package database
import (
"context"
stdsql "database/sql"
+ "fmt"
"io/fs"
+ "net/url"
+ "os"
"path/filepath"
"strconv"
"strings"
"testing"
+ "time"
+
+ sqliteutil "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/sqlite"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -394,6 +400,7 @@ func downgradeTargetVersionInternal(t *testing.T) int64 {
func newSQLiteSQLDBInternal(t *testing.T, dirPath, fileName string) (*stdsql.DB, string) {
t.Helper()
+ require.NoError(t, sqliteutil.RegisterFunctions())
dsn := "file:" + filepath.Join(dirPath, fileName)
db, err := stdsql.Open("sqlite", dsn)
@@ -731,3 +738,123 @@ func sectionHasSQLInternal(section string) bool {
}
return false
}
+
+func TestIdentityNormalizationMigration(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ first, second string
+ emailFirst, emailSecond string
+ }{
+ {name: "identity whitespace preserved", first: " Jose\u0301 ", second: "Other", emailFirst: " é@example.com ", emailSecond: "e\[email protected]"},
+ {name: "canonically equivalent usernames preserved", first: "Jose\u0301", second: "José"},
+ {name: "whitespace username preserved", first: "\t ", second: "Other"},
+ {name: "existing duplicate emails preserved", first: "one", second: "two", emailFirst: "[email protected]", emailSecond: "[email protected]"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := context.Background()
+ db, _ := newSQLiteSQLDBInternal(t, t.TempDir(), "identities.db")
+ require.NoError(t, migrateDatabaseToVersionInternal(ctx, db, dbProviderSQLite, MigrationOptions{}, 80))
+ const displayName = "\t\n\v\f\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000Jose\u0301\u3000"
+ _, err := db.Exec("INSERT INTO users (id, username, email, display_name, password_hash) VALUES (?, ?, ?, ?, 'unchanged'), (?, ?, ?, ?, 'unchanged')", "first", tc.first, tc.emailFirst, displayName, "second", tc.second, tc.emailSecond, nil)
+ require.NoError(t, err)
+ require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderSQLite, MigrationOptions{}))
+ require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderSQLite, MigrationOptions{}))
+ for _, expected := range []struct {
+ id, username, email string
+ displayName stdsql.NullString
+ }{
+ {"first", tc.first, tc.emailFirst, stdsql.NullString{String: "José", Valid: true}},
+ {"second", tc.second, tc.emailSecond, stdsql.NullString{}},
+ } {
+ var id, username, email, password string
+ var displayName stdsql.NullString
+ require.NoError(t, db.QueryRow("SELECT id, username, email, display_name, password_hash FROM users WHERE id = ?", expected.id).Scan(&id, &username, &email, &displayName, &password))
+ require.Equal(t, expected.id, id)
+ require.Equal(t, expected.username, username)
+ require.Equal(t, expected.email, email)
+ require.Equal(t, expected.displayName, displayName)
+ require.Equal(t, "unchanged", password)
+ }
+ var version int64
+ require.NoError(t, db.QueryRow("SELECT MAX(version_id) FROM goose_db_version WHERE is_applied = 1").Scan(&version))
+ require.Equal(t, int64(81), version)
+ })
+ }
+}
+
+func TestIdentityNormalizationGooseUpgrade(t *testing.T) {
+ ctx := context.Background()
+ db, dsn := newSQLiteSQLDBInternal(t, t.TempDir(), "upgrade.db")
+ require.NoError(t, migrateDatabaseToVersionInternal(ctx, db, dbProviderSQLite, MigrationOptions{}, 80))
+ _, err := db.Exec("INSERT INTO users (id, username, display_name, password_hash) VALUES (?, ?, ?, ?), (?, ?, ?, ?)", "first", " Jose\u0301 ", " Jose\u0301 ", "unchanged", "second", "José", nil, "unchanged")
+ require.NoError(t, err)
+ initialized, err := Initialize(ctx, dsn, MigrationOptions{})
+ require.NoError(t, err)
+ initializedSQL, err := initialized.DB.DB()
+ require.NoError(t, err)
+ require.NoError(t, initializedSQL.Close())
+ require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderSQLite, MigrationOptions{}))
+ var id, username, password string
+ var email, displayName stdsql.NullString
+ require.NoError(t, db.QueryRow("SELECT id, username, email, display_name, password_hash FROM users WHERE id = 'first'").Scan(&id, &username, &email, &displayName, &password))
+ require.Equal(t, "first", id)
+ require.Equal(t, " Jose\u0301 ", username)
+ require.False(t, email.Valid)
+ require.Equal(t, stdsql.NullString{String: "José", Valid: true}, displayName)
+ require.Equal(t, "unchanged", password)
+ var version int64
+ require.NoError(t, db.QueryRow("SELECT MAX(version_id) FROM goose_db_version WHERE is_applied = 1").Scan(&version))
+ require.Equal(t, int64(81), version)
+}
+
+func TestIdentityNormalizationPostgresUpgrade(t *testing.T) {
+ dsn := os.Getenv("ARCANE_TEST_POSTGRES_DSN")
+ if dsn == "" {
+ t.Skip("ARCANE_TEST_POSTGRES_DSN is not set")
+ }
+ ctx := context.Background()
+ admin, err := stdsql.Open("pgx", dsn)
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, admin.Close()) })
+ schema := fmt.Sprintf("normalization_test_%d", time.Now().UnixNano())
+ _, err = admin.ExecContext(ctx, "CREATE SCHEMA "+schema)
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _, err := admin.ExecContext(ctx, "DROP SCHEMA "+schema+" CASCADE")
+ require.NoError(t, err)
+ })
+ parsed, err := url.Parse(dsn)
+ require.NoError(t, err)
+ require.Contains(t, []string{"postgres", "postgresql"}, parsed.Scheme)
+ query := parsed.Query()
+ query.Set("search_path", schema)
+ parsed.RawQuery = query.Encode()
+ db, err := stdsql.Open("pgx", parsed.String())
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, db.Close()) })
+ require.NoError(t, migrateDatabaseToVersionInternal(ctx, db, dbProviderPostgres, MigrationOptions{}, 80))
+ const whitespace = "\t\n\v\f\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000"
+ _, err = db.ExecContext(ctx, "INSERT INTO users (id, username, email, display_name, password_hash) VALUES ($1, $2, $3, $4, $5), ($6, $7, $8, $9, $10)", "first", " Jose\u0301 ", " [email protected] ", whitespace+"Jose\u0301"+whitespace, "unchanged", "second", "José", nil, nil, "unchanged")
+ require.NoError(t, err)
+ require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderPostgres, MigrationOptions{}))
+ require.NoError(t, migrateDatabaseInternal(ctx, db, dbProviderPostgres, MigrationOptions{}))
+ for _, expected := range []struct {
+ id, username string
+ email, displayName stdsql.NullString
+ }{
+ {"first", " Jose\u0301 ", stdsql.NullString{String: " [email protected] ", Valid: true}, stdsql.NullString{String: "José", Valid: true}},
+ {"second", "José", stdsql.NullString{}, stdsql.NullString{}},
+ } {
+ var id, username, password string
+ var email, displayName stdsql.NullString
+ require.NoError(t, db.QueryRowContext(ctx, "SELECT id, username, email, display_name, password_hash FROM users WHERE id = $1", expected.id).Scan(&id, &username, &email, &displayName, &password))
+ require.Equal(t, expected.id, id)
+ require.Equal(t, expected.username, username)
+ require.Equal(t, expected.email, email)
+ require.Equal(t, expected.displayName, displayName)
+ require.Equal(t, "unchanged", password)
+ }
+ var version int64
+ require.NoError(t, db.QueryRowContext(ctx, "SELECT MAX(version_id) FROM goose_db_version WHERE is_applied").Scan(&version))
+ require.Equal(t, int64(81), version)
+}
diff --git a/backend/internal/environment/environment.go b/backend/internal/environment/environment.go
index 0030f8075..e7dd5bcdd 100644
--- a/backend/internal/environment/environment.go
+++ b/backend/internal/environment/environment.go
@@ -2,6 +2,7 @@ package environment
import (
"github.com/getarcaneapp/arcane/backend/v2/internal/registry"
+ "go.getarcane.app/kit/normalization"
"context"
"fmt"
@@ -212,6 +213,9 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl
}
func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *Environment, userID, username *string) (*Environment, error) {
+ if err := normalization.Normalize(environment); err != nil {
+ return nil, err
+ }
environment.ID = uuid.New().String()
// Only set status to offline if not already set (e.g., API key flow sets it to pending)
@@ -250,6 +254,9 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)
}
func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]any, userID, username *string) (*Environment, error) {
+ if name, ok := updates["name"].(string); ok {
+ updates["name"] = normalization.Text(name, true, true)
+ }
current, err := s.GetEnvironmentByID(ctx, id)
if err != nil {
return nil, err
diff --git a/backend/internal/environment/model.go b/backend/internal/environment/model.go
index d6e34216d..46ea11808 100644
--- a/backend/internal/environment/model.go
+++ b/backend/internal/environment/model.go
@@ -9,7 +9,7 @@ import (
type Environment struct {
database.BaseModel
- Name string `json:"name" sortable:"true"`
+ Name string `json:"name" sortable:"true" unorm:"nfc" trim:"true"`
ApiUrl string `json:"apiUrl" gorm:"column:api_url" sortable:"true"`
Status string `json:"status" sortable:"true"`
Enabled bool `json:"enabled" sortable:"true"`
diff --git a/backend/internal/federated/credential.go b/backend/internal/federated/credential.go
index ec63de4cc..2500531f5 100644
--- a/backend/internal/federated/credential.go
+++ b/backend/internal/federated/credential.go
@@ -5,6 +5,8 @@ import (
"net/url"
"strings"
+ "go.getarcane.app/kit/normalization"
+
"emperror.dev/errors"
"github.com/samber/mo"
@@ -15,7 +17,9 @@ import (
)
func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederatedCredential) (federatedtypes.CreateFederatedCredential, error) {
- req.Name = strings.TrimSpace(req.Name)
+ if err := normalization.Normalize(&req); err != nil {
+ return req, common.Classify(common.ErrFederatedCredentialInvalid, err)
+ }
req.IssuerURL = strings.TrimRight(strings.TrimSpace(req.IssuerURL), "/")
req.SubjectClaim = strings.TrimSpace(req.SubjectClaim)
req.SubjectMatch = strings.TrimSpace(req.SubjectMatch)
@@ -27,7 +31,7 @@ func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederat
if req.SubjectClaim == "" {
req.SubjectClaim = defaultFederatedSubjectClaim
}
- if req.Name == "" || req.SubjectMatch == "" || req.RoleID == "" || len(req.Audiences) == 0 {
+ if req.SubjectMatch == "" || req.RoleID == "" || len(req.Audiences) == 0 {
return req, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))
}
if err := validateIssuerURLInternal(req.IssuerURL); err != nil {
@@ -40,13 +44,10 @@ func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederat
}
func applyFederatedCredentialUpdateInternal(existing FederatedCredential, req federatedtypes.UpdateFederatedCredential) (FederatedCredential, bool, error) {
- if req.Name != nil {
- name := strings.TrimSpace(*req.Name)
- if name == "" {
- return existing, false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))
- }
- existing.Name = name
+ if err := normalization.Normalize(&req); err != nil {
+ return existing, false, common.Classify(common.ErrFederatedCredentialInvalid, err)
}
+ utils.ApplyChanged(&existing.Name, mo.PointerToOption(req.Name))
if req.Description != nil {
existing.Description = req.Description
}
diff --git a/backend/internal/gitrepo/handler.go b/backend/internal/gitrepo/handler.go
index dfc05ac5b..7134ab5a3 100644
--- a/backend/internal/gitrepo/handler.go
+++ b/backend/internal/gitrepo/handler.go
@@ -31,7 +31,7 @@ type ListGitRepositoriesInput struct {
}
type CreateGitRepositoryInput struct {
- Body CreateGitRepositoryRequest
+ Body gitops.CreateRepositoryRequest
}
type GetGitRepositoryInput struct {
@@ -40,7 +40,7 @@ type GetGitRepositoryInput struct {
type UpdateGitRepositoryInput struct {
ID string `path:"id" doc:"Repository ID"`
- Body UpdateGitRepositoryRequest
+ Body gitops.UpdateRepositoryRequest
}
type DeleteGitRepositoryInput struct {
diff --git a/backend/internal/gitrepo/model.go b/backend/internal/gitrepo/model.go
index 3884f3579..b3a465b7f 100644
--- a/backend/internal/gitrepo/model.go
+++ b/backend/internal/gitrepo/model.go
@@ -19,27 +19,3 @@ type GitRepository struct {
func (GitRepository) TableName() string {
return "git_repositories"
}
-
-type CreateGitRepositoryRequest struct {
- Name string `json:"name" binding:"required"`
- URL string `json:"url" binding:"required"`
- AuthType string `json:"authType" binding:"required,oneof=none http ssh"`
- Username string `json:"username,omitempty"`
- Token string `json:"token,omitempty"`
- SSHKey string `json:"sshKey,omitempty"`
- SSHHostKeyVerification string `json:"sshHostKeyVerification,omitempty" binding:"omitempty,oneof=strict accept_new skip"`
- Description *string `json:"description,omitempty"`
- Enabled *bool `json:"enabled,omitempty"`
-}
-
-type UpdateGitRepositoryRequest struct {
- Name *string `json:"name,omitempty"`
- URL *string `json:"url,omitempty"`
- AuthType *string `json:"authType,omitempty" binding:"omitempty,oneof=none http ssh"`
- Username *string `json:"username,omitempty"`
- Token *string `json:"token,omitempty"`
- SSHKey *string `json:"sshKey,omitempty"`
- SSHHostKeyVerification *string `json:"sshHostKeyVerification,omitempty" binding:"omitempty,oneof=strict accept_new skip"`
- Description *string `json:"description,omitempty"`
- Enabled *bool `json:"enabled,omitempty"`
-}
diff --git a/backend/internal/gitrepo/service.go b/backend/internal/gitrepo/service.go
index 466e63771..3d6ab91fb 100644
--- a/backend/internal/gitrepo/service.go
+++ b/backend/internal/gitrepo/service.go
@@ -2,6 +2,7 @@ package gitrepo
import (
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "go.getarcane.app/kit/normalization"
"context"
"fmt"
@@ -114,7 +115,10 @@ func (s *GitRepositoryService) FindEnabledRepositoryByURL(ctx context.Context, r
return nil, nil
}
-func (s *GitRepositoryService) CreateRepository(ctx context.Context, req CreateGitRepositoryRequest, actor common.User) (*GitRepository, error) {
+func (s *GitRepositoryService) CreateRepository(ctx context.Context, req gitops.CreateRepositoryRequest, actor common.User) (*GitRepository, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return nil, err
+ }
repository := GitRepository{
Name: req.Name,
URL: req.URL,
@@ -171,7 +175,10 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req CreateG
return &repository, nil
}
-func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string, req UpdateGitRepositoryRequest, actor common.User) (*GitRepository, error) {
+func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string, req gitops.UpdateRepositoryRequest, actor common.User) (*GitRepository, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return nil, err
+ }
repository, err := s.GetRepositoryByID(ctx, id)
if err != nil {
return nil, err
@@ -448,6 +455,9 @@ func (s *GitRepositoryService) BrowseFiles(ctx context.Context, id, branch, path
// SyncRepositories syncs repositories from a manager to this agent instance.
// It creates, updates, or deletes repositories to match the provided list.
func (s *GitRepositoryService) SyncRepositories(ctx context.Context, syncItems []gitops.RepositorySync) error {
+ if err := normalization.Normalize(&syncItems); err != nil {
+ return err
+ }
existingMap, err := s.getExistingRepositoriesMap(ctx)
if err != nil {
return err
diff --git a/backend/internal/gitrepo/service_test.go b/backend/internal/gitrepo/service_test.go
index 43b8c928a..8ea943e60 100644
--- a/backend/internal/gitrepo/service_test.go
+++ b/backend/internal/gitrepo/service_test.go
@@ -3,6 +3,7 @@ package gitrepo
import (
"context"
"fmt"
+ "github.com/getarcaneapp/arcane/types/v2/gitops"
"strings"
"testing"
"time"
@@ -76,7 +77,7 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *da
return settings.NewSettingsService(ctx, db, executor, effects)
}
-func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepositoryService, req CreateGitRepositoryRequest) *GitRepository {
+func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepositoryService, req gitops.CreateRepositoryRequest) *GitRepository {
t.Helper()
repo, err := svc.CreateRepository(context.Background(), req, common.User{
@@ -89,7 +90,7 @@ func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepository
func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWouldBeReused(t *testing.T) {
svc, _ := setupGitRepositoryServiceTestInternal(t)
- repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{
+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
AuthType: "http",
@@ -97,7 +98,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWo
Token: "ghp_old_token",
})
- _, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{
+ _, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://attacker.tld/repo.git"),
}, common.User{})
require.Error(t, err)
@@ -114,14 +115,14 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWo
func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyWouldBeReused(t *testing.T) {
svc, _ := setupGitRepositoryServiceTestInternal(t)
- repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{
+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "infra-repo",
URL: "[email protected]:acme/private.git",
AuthType: "ssh",
SSHKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nkey-material\n-----END OPENSSH PRIVATE KEY-----",
})
- _, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{
+ _, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("[email protected]:acme/private.git"),
}, common.User{})
require.Error(t, err)
@@ -138,7 +139,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyW
func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAndSSHKeyWouldBeReused(t *testing.T) {
svc, _ := setupGitRepositoryServiceTestInternal(t)
- repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{
+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "hybrid-repo",
URL: "https://github.com/acme/private.git",
AuthType: "http",
@@ -147,7 +148,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAn
SSHKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nkey-material\n-----END OPENSSH PRIVATE KEY-----",
})
- _, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{
+ _, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://attacker.tld/repo.git"),
}, common.User{})
require.Error(t, err)
@@ -161,7 +162,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAn
func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResupplied(t *testing.T) {
svc, _ := setupGitRepositoryServiceTestInternal(t)
- repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{
+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
AuthType: "http",
@@ -169,7 +170,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResuppl
Token: "ghp_old_token",
})
- updated, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{
+ updated, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://github.com/acme/private-rotated.git"),
Token: new("ghp_new_token"),
}, common.User{})
@@ -183,7 +184,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResuppl
func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsCleared(t *testing.T) {
svc, _ := setupGitRepositoryServiceTestInternal(t)
- repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{
+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
AuthType: "http",
@@ -191,7 +192,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsCleared
Token: "ghp_old_token",
})
- updated, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{
+ updated, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://github.com/acme/public.git"),
Token: new(""),
}, common.User{})
@@ -203,7 +204,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsCleared
func TestGitRepositoryService_UpdateRepository_AllowsSameURLWithoutCredentialResupply(t *testing.T) {
svc, _ := setupGitRepositoryServiceTestInternal(t)
- repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{
+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, gitops.CreateRepositoryRequest{
Name: "prod-repo",
URL: "https://github.com/acme/private.git",
AuthType: "http",
@@ -211,7 +212,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsSameURLWithoutCredentialRes
Token: "ghp_old_token",
})
- updated, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{
+ updated, err := svc.UpdateRepository(context.Background(), repo.ID, gitops.UpdateRepositoryRequest{
URL: new("https://github.com/acme/private.git"),
Username: new("deploy-bot"),
}, common.User{})
diff --git a/backend/internal/registry/handler.go b/backend/internal/registry/handler.go
index d3d948885..3f7a2c5df 100644
--- a/backend/internal/registry/handler.go
+++ b/backend/internal/registry/handler.go
@@ -38,7 +38,7 @@ type ListContainerRegistriesInput struct {
}
type CreateContainerRegistryInput struct {
- Body CreateContainerRegistryRequest
+ Body containerregistry.CreateContainerRegistryRequest
}
type GetContainerRegistryInput struct {
@@ -47,7 +47,7 @@ type GetContainerRegistryInput struct {
type UpdateContainerRegistryInput struct {
ID string `path:"id" doc:"Registry ID"`
- Body UpdateContainerRegistryRequest
+ Body containerregistry.UpdateContainerRegistryRequest
}
type DeleteContainerRegistryInput struct {
diff --git a/backend/internal/registry/model.go b/backend/internal/registry/model.go
index 1c1fa2a09..da99f5cae 100644
--- a/backend/internal/registry/model.go
+++ b/backend/internal/registry/model.go
@@ -29,31 +29,3 @@ type ContainerRegistry struct {
func (ContainerRegistry) TableName() string {
return "container_registries"
}
-
-type CreateContainerRegistryRequest struct {
- URL string `json:"url" binding:"required"`
- Username string `json:"username"`
- Token string `json:"token"`
- Description *string `json:"description"`
- Insecure *bool `json:"insecure"`
- Enabled *bool `json:"enabled"`
- RegistryType string `json:"registryType"`
- RepositoryNames []string `json:"repositoryNames"`
- AWSAccessKeyID string `json:"awsAccessKeyId"`
- AWSSecretAccessKey string `json:"awsSecretAccessKey"`
- AWSRegion string `json:"awsRegion"`
-}
-
-type UpdateContainerRegistryRequest struct {
- URL *string `json:"url"`
- Username *string `json:"username"`
- Token *string `json:"token"`
- Description *string `json:"description"`
- Insecure *bool `json:"insecure"`
- Enabled *bool `json:"enabled"`
- RegistryType *string `json:"registryType"`
- RepositoryNames *[]string `json:"repositoryNames"`
- AWSAccessKeyID *string `json:"awsAccessKeyId"`
- AWSSecretAccessKey *string `json:"awsSecretAccessKey"`
- AWSRegion *string `json:"awsRegion"`
-}
diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.go
index 2048cd051..5312b5858 100644
--- a/backend/internal/registry/service.go
+++ b/backend/internal/registry/service.go
@@ -9,6 +9,8 @@ import (
"strings"
"time"
+ "go.getarcane.app/kit/normalization"
+
"github.com/cenkalti/backoff/v5"
ref "github.com/distribution/reference"
"github.com/samber/hot"
@@ -172,7 +174,10 @@ func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id strin
return &registryRecord, nil
}
-func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req CreateContainerRegistryRequest) (*ContainerRegistry, error) {
+func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req containerregistry.CreateContainerRegistryRequest) (*ContainerRegistry, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return nil, err
+ }
registryType, err := NormalizeRegistryType(req.RegistryType)
if err != nil {
return nil, err
@@ -232,7 +237,10 @@ func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req Creat
return registryRecord, nil
}
-func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string, req UpdateContainerRegistryRequest) (*ContainerRegistry, error) {
+func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string, req containerregistry.UpdateContainerRegistryRequest) (*ContainerRegistry, error) {
+ if err := normalization.Normalize(&req); err != nil {
+ return nil, err
+ }
registryRecord, err := s.GetRegistryByID(ctx, id)
if err != nil {
return nil, err
@@ -314,7 +322,7 @@ func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *Con
return nil
}
-func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *ContainerRegistry, req UpdateContainerRegistryRequest) error {
+func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *ContainerRegistry, req containerregistry.UpdateContainerRegistryRequest) error {
utils.ApplyChanged(&registry.AWSAccessKeyID, mo.PointerToOption(req.AWSAccessKeyID))
utils.ApplyChanged(&registry.AWSRegion, mo.PointerToOption(req.AWSRegion))
@@ -344,7 +352,7 @@ func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *Con
return nil
}
-func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registry *ContainerRegistry, req UpdateContainerRegistryRequest) error {
+func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registry *ContainerRegistry, req containerregistry.UpdateContainerRegistryRequest) error {
utils.ApplyChanged(&registry.Username, mo.PointerToOption(req.Username))
if req.Token != nil && *req.Token != "" {
@@ -1069,6 +1077,9 @@ func (s *ContainerRegistryService) getMatchingRegistryCredentialsInternal(ctx co
// SyncRegistries syncs registries from a manager to this agent instance
// It creates, updates, or deletes registries to match the provided list
func (s *ContainerRegistryService) SyncRegistries(ctx context.Context, syncItems []containerregistry.Sync) error {
+ if err := normalization.Normalize(&syncItems); err != nil {
+ return err
+ }
existingMap, err := s.getExistingRegistriesMapInternal(ctx)
if err != nil {
return err
diff --git a/backend/internal/registry/service_test.go b/backend/internal/registry/service_test.go
index b83b3518f..ecf1d0a69 100644
--- a/backend/internal/registry/service_test.go
+++ b/backend/internal/registry/service_test.go
@@ -371,7 +371,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsUnsupportedRegistryType(
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "registry.example.com",
RegistryType: "ECR-ish",
})
@@ -385,7 +385,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyUsernameForGeneric(
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "",
Token: "my-token",
@@ -400,7 +400,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyTokenForGeneric(t *
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "",
@@ -415,7 +415,7 @@ func TestContainerRegistryService_CreateRegistry_AcceptsValidGenericCredentials(
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -429,14 +429,14 @@ func TestContainerRegistryService_UpdateRegistry_RejectsBlankingUsername(t *test
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- _, err = svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
Username: new(""),
})
require.Error(t, err)
@@ -449,7 +449,7 @@ func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProvid
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -457,7 +457,7 @@ func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProvid
require.NoError(t, err)
originalToken := reg.Token
- updated, err := svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
Username: new("updated-user"),
})
require.NoError(t, err)
@@ -479,7 +479,7 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTo
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -487,7 +487,7 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTo
require.NoError(t, err)
originalToken := registry.Token
- _, err = svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("https://attacker.example.com"),
Token: tt.token,
})
@@ -508,7 +508,7 @@ func TestContainerRegistryService_UpdateRegistry_AllowsPathChangeOnSameHostWitho
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com/one",
Username: "my-user",
Token: "my-token",
@@ -516,7 +516,7 @@ func TestContainerRegistryService_UpdateRegistry_AllowsPathChangeOnSameHostWitho
require.NoError(t, err)
originalToken := registry.Token
- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("REGISTRY.EXAMPLE.COM/two"),
})
require.NoError(t, err)
@@ -528,14 +528,14 @@ func TestContainerRegistryService_UpdateRegistry_AllowsTargetChangeWhenTokenIsRe
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("https://registry.example.net"),
Token: new("new-token"),
})
@@ -551,7 +551,7 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStored
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "123456789012.dkr.ecr.us-east-1.amazonaws.com",
RegistryType: RegistryTypeECR,
AWSAccessKeyID: "old-access-key",
@@ -561,7 +561,7 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStored
require.NoError(t, err)
originalSecret := registry.AWSSecretAccessKey
- _, err = svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),
})
require.Error(t, err)
@@ -576,7 +576,7 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStored
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, UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),
AWSAccessKeyID: new("new-access-key"),
AWSSecretAccessKey: new("new-secret-key"),
@@ -593,14 +593,14 @@ func TestContainerRegistryService_UpdateRegistry_RejectsChangingRegistryType(t *
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- _, err = svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{
+ _, err = svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
RegistryType: new("ecr"),
})
require.Error(t, err)
@@ -613,14 +613,14 @@ func TestContainerRegistryService_UpdateRegistry_AllowsSameRegistryType(t *testi
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ reg, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
})
require.NoError(t, err)
- updated, err := svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(context.Background(), reg.ID, containerregistry.UpdateContainerRegistryRequest{
RegistryType: new("generic"),
Username: new("updated-user"),
})
@@ -1256,7 +1256,7 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthori
func createRegistryWithRepositoryNames(t *testing.T, svc *ContainerRegistryService, repositoryNames ...string) *ContainerRegistry {
t.Helper()
- registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ registry, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
Username: "my-user",
Token: "my-token",
@@ -1291,7 +1291,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsInvalidRepositoryName(t
db := setupContainerRegistryTestDBInternal(t)
svc := NewContainerRegistryService(db, nil, nil)
- _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{
+ _, err := svc.CreateRegistry(context.Background(), containerregistry.CreateContainerRegistryRequest{
URL: "https://registry.example.com",
RepositoryNames: []string{"team:latest"},
})
@@ -1306,14 +1306,14 @@ func TestContainerRegistryService_UpdateRegistry_RepositoryNamesPointerSemantics
registry := createRegistryWithRepositoryNames(t, svc, "team", "team/platform")
// A nil pointer leaves the existing names untouched.
- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{
+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
Username: new("updated-user"),
})
require.NoError(t, err)
assert.Equal(t, database.StringSlice{"team", "team/platform"}, updated.RepositoryNames)
// An empty slice clears them.
- updated, err = svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{
+ updated, err = svc.UpdateRegistry(context.Background(), registry.ID, containerregistry.UpdateContainerRegistryRequest{
RepositoryNames: &[]string{},
})
require.NoError(t, err)
diff --git a/backend/internal/role/service.go b/backend/internal/role/service.go
index 6ad2eacdd..6cd54f888 100644
--- a/backend/internal/role/service.go
+++ b/backend/internal/role/service.go
@@ -7,6 +7,8 @@ import (
"strings"
"time"
+ "go.getarcane.app/kit/normalization"
+
"emperror.dev/errors"
"gorm.io/gorm"
@@ -202,21 +204,22 @@ func (s *RoleService) GetRole(ctx context.Context, id string) (*Role, error) {
}
func (s *RoleService) CreateRole(ctx context.Context, name string, description *string, permissions []string) (*Role, error) {
- if strings.TrimSpace(name) == "" {
- return nil, errors.New("role name is required")
+ input := roletypes.CreateRole{Name: name, Description: description, Permissions: permissions}
+ if err := normalization.Normalize(&input); err != nil {
+ return nil, err
}
if err := validatePermissionsInternal(permissions); err != nil {
return nil, err
}
role := &Role{
- Name: name,
- Description: description,
+ Name: input.Name,
+ Description: input.Description,
Permissions: database.StringSlice(permissions),
BuiltIn: false,
}
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
var conflict int64
- if err := tx.Model(&Role{}).Where("name = ?", name).Count(&conflict).Error; err != nil {
+ if err := tx.Model(&Role{}).Where("name = ?", input.Name).Count(&conflict).Error; err != nil {
return errors.WrapIf(err, "failed to check role name uniqueness")
}
if conflict > 0 {
@@ -259,6 +262,10 @@ func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error)
}
func (s *RoleService) UpdateRole(ctx context.Context, id, name string, description *string, permissions []string) (*Role, error) {
+ input := roletypes.UpdateRole{Name: name, Description: description, Permissions: permissions}
+ if err := normalization.Normalize(&input); err != nil {
+ return nil, err
+ }
if err := validatePermissionsInternal(permissions); err != nil {
return nil, err
}
@@ -274,9 +281,9 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti
if existing.BuiltIn {
return common.Classify(common.ErrRoleBuiltIn, errors.New("Built-in role cannot be modified"))
}
- if name != existing.Name {
+ if input.Name != existing.Name {
var conflict int64
- if err := tx.Model(&Role{}).Where("name = ? AND id <> ?", name, id).Count(&conflict).Error; err != nil {
+ if err := tx.Model(&Role{}).Where("name = ? AND id <> ?", input.Name, id).Count(&conflict).Error; err != nil {
return errors.WrapIf(err, "failed to check role name uniqueness")
}
if conflict > 0 {
@@ -286,8 +293,8 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti
if _, err := lockAssignedUserRowsInternal(tx, id); err != nil {
return err
}
- existing.Name = name
- existing.Description = description
+ existing.Name = input.Name
+ existing.Description = input.Description
existing.Permissions = permissions
if err := tx.Save(&existing).Error; err != nil {
return errors.WrapIf(err, "failed to update role")
diff --git a/backend/internal/s3/service.go b/backend/internal/s3/service.go
index 67a6f9749..edc80f0dd 100644
--- a/backend/internal/s3/service.go
+++ b/backend/internal/s3/service.go
@@ -5,6 +5,8 @@ import (
"fmt"
"strings"
+ "go.getarcane.app/kit/normalization"
+
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/backend/v2/internal/database"
@@ -126,6 +128,9 @@ func applyS3ConfigurationInternal(destination *S3Destination, configuration s3co
}
func (s *S3DestinationService) CreateS3Destination(ctx context.Context, input backuptypes.CreateS3Destination) (*backuptypes.S3Destination, error) {
+ if err := normalization.Normalize(&input); err != nil {
+ return nil, err
+ }
configuration := destinationConfigurationInternal("", input)
if err := configuration.Validate(true); err != nil {
return nil, err
@@ -160,6 +165,9 @@ func storedConfigurationInternal(destination *S3Destination) s3config.Configurat
}
func (s *S3DestinationService) UpdateS3Destination(ctx context.Context, id string, input backuptypes.UpdateS3Destination) (*backuptypes.S3Destination, error) {
+ if err := normalization.Normalize(&input); err != nil {
+ return nil, err
+ }
configuration := destinationConfigurationInternal("", input)
if err := configuration.Validate(false); err != nil {
return nil, err
@@ -241,6 +249,9 @@ func (s *S3DestinationService) S3DestinationExists(ctx context.Context, id strin
// SyncS3Destinations replaces an agent's destination cache with the manager-owned destinations.
func (s *S3DestinationService) SyncS3Destinations(ctx context.Context, destinations []backuptypes.S3DestinationSync) error {
+ if err := normalization.Normalize(&destinations); err != nil {
+ return err
+ }
var existing []S3Destination
if err := s.db.WithContext(ctx).Find(&existing).Error; err != nil {
return fmt.Errorf("failed to load existing S3 destinations: %w", err)
@@ -324,6 +335,9 @@ func (s *S3DestinationService) TestS3Destination(ctx context.Context, id string,
return err
}
if input != nil {
+ if err := normalization.Normalize(input); err != nil {
+ return err
+ }
updated := destinationConfigurationInternal("", *input)
updated.ID = configuration.ID
if updated.SecretAccessKey == "" {
@@ -340,5 +354,8 @@ func (s *S3DestinationService) TestS3Destination(ctx context.Context, id string,
}
func (s *S3DestinationService) TestS3DestinationConfiguration(ctx context.Context, input backuptypes.CreateS3Destination) error {
+ if err := normalization.Normalize(&input); err != nil {
+ return err
+ }
return s3config.TestConnection(ctx, destinationConfigurationInternal("", input))
}
diff --git a/backend/internal/s3/service_test.go b/backend/internal/s3/service_test.go
index bc1dd8813..64caa72ae 100644
--- a/backend/internal/s3/service_test.go
+++ b/backend/internal/s3/service_test.go
@@ -45,7 +45,7 @@ func TestS3DestinationService_CRUD(t *testing.T) {
ctx := context.Background()
created, err := service.CreateS3Destination(ctx, backuptypes.CreateS3Destination{
- Name: "Offsite",
+ Name: " Cafe\u0301 offsite ",
Endpoint: "https://s3.example.com",
Bucket: "arcane-backups",
Region: "eu-central-1",
@@ -57,6 +57,7 @@ func TestS3DestinationService_CRUD(t *testing.T) {
})
require.NoError(t, err)
require.NotEmpty(t, created.ID)
+ require.Equal(t, "Café offsite", created.Name)
require.True(t, created.SecretConfigured)
require.Equal(t, "production", created.Prefix)
@@ -73,7 +74,7 @@ func TestS3DestinationService_CRUD(t *testing.T) {
require.Len(t, listed, 1)
updated, err := service.UpdateS3Destination(ctx, created.ID, backuptypes.UpdateS3Destination{
- Name: "Primary offsite",
+ Name: " Primary cafe\u0301 offsite ",
Endpoint: created.Endpoint,
Bucket: created.Bucket,
Region: created.Region,
@@ -83,7 +84,7 @@ func TestS3DestinationService_CRUD(t *testing.T) {
ForcePathStyle: created.ForcePathStyle,
})
require.NoError(t, err)
- require.Equal(t, "Primary offsite", updated.Name)
+ require.Equal(t, "Primary café offsite", updated.Name)
var updatedStored S3Destination
require.NoError(t, gormDB.First(&updatedStored, "id = ?", created.ID).Error)
diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.go
index 0be7720df..ae07bbe58 100644
--- a/backend/internal/settings/service.go
+++ b/backend/internal/settings/service.go
@@ -18,6 +18,8 @@ import (
"time"
"uuid"
+ "go.getarcane.app/kit/normalization"
+
"emperror.dev/errors"
"github.com/samber/mo"
@@ -524,6 +526,9 @@ func (s *SettingsService) UpdateSettingValues(ctx context.Context, updates []lib
}
func (s *SettingsService) updateSettingValueNoRefreshInternal(ctx context.Context, key, value string) error {
+ if key == "oidcProviderName" {
+ value = normalization.Text(value, true, true)
+ }
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
settingVar := &SettingVariable{
Key: key,
@@ -536,6 +541,9 @@ func (s *SettingsService) updateSettingValueNoRefreshInternal(ctx context.Contex
// UpdateSettings publishes the refreshed snapshot before returning. Each
// subscriber's effects remain ordered and may finish after this method returns.
func (s *SettingsService) UpdateSettings(ctx context.Context, updates settingstypes.Update) ([]SettingVariable, error) {
+ if err := normalization.Normalize(&updates); err != nil {
+ return nil, err
+ }
result, err := s.writes.Execute(ctx, "update settings", func(writeCtx context.Context) (settingsUpdateResultInternal, error) {
return s.updateSettingsInternal(writeCtx, updates)
}, func(result settingsUpdateResultInternal, err error) {
@@ -707,6 +715,9 @@ func extractUpdateValue(field reflect.StructField, fieldValue reflect.Value) (st
func (s *SettingsService) persistSettings(ctx context.Context, values []SettingVariable) error {
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for _, setting := range values {
+ if setting.Key == "oidcProviderName" {
+ setting.Value = normalization.Text(setting.Value, true, true)
+ }
if err := tx.Save(&setting).Error; err != nil {
return errors.WrapIff(err, "failed to update setting %s", setting.Key)
}
diff --git a/backend/internal/settings/service_test.go b/backend/internal/settings/service_test.go
index e5e272dec..6ddc6e29f 100644
--- a/backend/internal/settings/service_test.go
+++ b/backend/internal/settings/service_test.go
@@ -240,7 +240,13 @@ func TestSettingsServiceUpdateSettingsAllowsOIDCIssuerChangeWithReplacementSecre
require.NoError(t, svc.UpdateSetting(ctx, "oidcIssuerUrl", "https://issuer.example.com"))
require.NoError(t, svc.UpdateSetting(ctx, "oidcClientSecret", "old-client-secret"))
+ require.NoError(t, svc.UpdateSetting(ctx, "oidcProviderName", " Cafe\u0301 SSO "))
+ before, loadErr := svc.GetSettings(ctx)
+ require.NoError(t, loadErr)
+ require.Equal(t, "Café SSO", before.OidcProviderName.Value)
+
_, err = svc.UpdateSettings(ctx, settingstypes.Update{
+ OidcProviderName: new(" Cafe\u0301 Login "),
OidcIssuerUrl: new("https://replacement.example.com"),
OidcClientSecret: new("new-client-secret"),
})
@@ -250,6 +256,7 @@ func TestSettingsServiceUpdateSettingsAllowsOIDCIssuerChangeWithReplacementSecre
require.NoError(t, loadErr)
require.Equal(t, "https://replacement.example.com", current.OidcIssuerUrl.Value)
require.Equal(t, "new-client-secret", current.OidcClientSecret.Value)
+ require.Equal(t, "Café Login", current.OidcProviderName.Value)
}
func TestSettingsServiceUpdateSettingsRejectsTrivyServerChangeWithStoredTokenInternal(t *testing.T) {
diff --git a/backend/internal/template/model.go b/backend/internal/template/model.go
index b22c8742b..a210b6bb1 100644
--- a/backend/internal/template/model.go
+++ b/backend/internal/template/model.go
@@ -5,17 +5,17 @@ import "github.com/getarcaneapp/arcane/backend/v2/internal/database"
type TemplateRegistry struct {
database.BaseModel
- Name string `json:"name"`
+ Name string `json:"name" unorm:"nfc" trim:"true"`
URL string `json:"url"`
Enabled bool `json:"enabled"`
- Description string `json:"description"`
+ Description string `json:"description" unorm:"nfc" trim:"true"`
}
type ComposeTemplate struct {
database.BaseModel
- Name string `json:"name"`
- Description string `json:"description"`
+ Name string `json:"name" unorm:"nfc" trim:"true" minLength:"1"`
+ Description string `json:"description" unorm:"nfc" trim:"true"`
Content string `json:"content" gorm:"type:text"`
EnvContent *string `json:"envContent,omitempty" gorm:"type:text"`
IsCustom bool `json:"isCustom"`
diff --git a/backend/internal/template/service.go b/backend/internal/template/service.go
index 810acab08..917dca657 100644
--- a/backend/internal/template/service.go
+++ b/backend/internal/template/service.go
@@ -15,6 +15,8 @@ import (
"time"
"uuid"
+ "go.getarcane.app/kit/normalization"
+
"emperror.dev/errors"
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
@@ -296,6 +298,9 @@ func (s *TemplateService) remoteCacheSizeInternal() int {
}
func (s *TemplateService) CreateTemplate(ctx context.Context, template *ComposeTemplate) error {
+ if err := normalization.Normalize(template); err != nil {
+ return err
+ }
if template.ID == "" {
template.ID = uuid.New().String()
}
@@ -311,6 +316,9 @@ func (s *TemplateService) CreateTemplate(ctx context.Context, template *ComposeT
}
func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updates *ComposeTemplate) error {
+ if err := normalization.Normalize(updates); err != nil {
+ return err
+ }
return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var existing ComposeTemplate
if err := tx.Where("id = ?", id).First(&existing).Error; err != nil {
@@ -461,6 +469,9 @@ func (s *TemplateService) GetRegistryFetchErrors() map[string]string {
}
func (s *TemplateService) CreateRegistry(ctx context.Context, registry *TemplateRegistry) error {
+ if err := normalization.Normalize(registry); err != nil {
+ return err
+ }
// Hydrate metadata if needed
if registry.Name == "" || registry.Description == "" {
if registry.URL == "" {
@@ -478,6 +489,9 @@ func (s *TemplateService) CreateRegistry(ctx context.Context, registry *Template
}
}
+ if err := normalization.Normalize(registry); err != nil {
+ return err
+ }
if registry.ID == "" {
registry.ID = uuid.New().String()
}
@@ -497,6 +511,9 @@ func (s *TemplateService) CreateRegistry(ctx context.Context, registry *Template
}
func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updates *TemplateRegistry) error {
+ if err := normalization.Normalize(updates); err != nil {
+ return err
+ }
err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var existing TemplateRegistry
if err := tx.Where("id = ?", id).First(&existing).Error; err != nil {
@@ -510,6 +527,9 @@ func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updates
return err
}
+ if err := normalization.Normalize(updates); err != nil {
+ return err
+ }
if err := tx.Model(&TemplateRegistry{}).Where("id = ?", id).
Select("Name", "URL", "Description", "Enabled").
Updates(updates).Error; err != nil {
diff --git a/backend/internal/user/service.go b/backend/internal/user/service.go
index 2a7155898..ca133630c 100644
--- a/backend/internal/user/service.go
+++ b/backend/internal/user/service.go
@@ -23,6 +23,7 @@ import (
"github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"
"github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"
"github.com/getarcaneapp/arcane/types/v2/user"
+ "go.getarcane.app/kit/normalization"
)
type Argon2Params struct {
@@ -140,6 +141,9 @@ func (s *UserService) ValidatePassword(encodedHash, password string) error {
}
func (s *UserService) CreateUser(ctx context.Context, user *common.User) (*common.User, error) {
+ if err := normalization.Normalize(user); err != nil {
+ return nil, err
+ }
username, err := normalizeUsernameInternal(user.Username)
if err != nil {
return nil, err
@@ -274,6 +278,9 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gorm
// performing the change; authenticated global-admin callers must also be
// present in ctx. Pass nil for internal service-to-service calls.
func (s *UserService) UpdateUser(ctx context.Context, user *common.User, actorPerms *authz.PermissionSet) (*common.User, error) {
+ if err := normalization.Normalize(user); err != nil {
+ return nil, err
+ }
err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {
if err := s.checkTargetPrivilegeInternal(ctx, tx, actorPerms, user.ID); err != nil {
return err
@@ -402,6 +409,9 @@ func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userID
updateFn(&u)
}
+ if err := normalization.Normalize(&u); err != nil {
+ return err
+ }
if err := tx.Save(&u).Error; err != nil {
// Bubble up uniqueness violations with a clearer message
if strings.Contains(strings.ToLower(err.Error()), "unique") || strings.Contains(strings.ToLower(err.Error()), "duplicate key") {
diff --git a/backend/internal/user/service_test.go b/backend/internal/user/service_test.go
index d81c29bd9..4159d7237 100644
--- a/backend/internal/user/service_test.go
+++ b/backend/internal/user/service_test.go
@@ -425,3 +425,33 @@ func TestCreateDefaultAdminRecoversArcaneUserWhenNoGlobalAdminExists(t *testing.
require.Equal(t, authz.BuiltInRoleAdmin, assignments[0].RoleID)
require.Nil(t, assignments[0].EnvironmentID)
}
+
+func TestUserDisplayNameNormalization(t *testing.T) {
+ svc := NewUserService(setupAuthServiceTestDBInternal(t))
+ ctx := context.Background()
+ created, err := svc.CreateUser(ctx, &common.User{ID: "normalized", Username: " Jose\u0301 ", Email: new(" Jose\[email protected] "), DisplayName: new(" Jose\u0301 ")})
+ require.NoError(t, err)
+ require.Equal(t, "Jose\u0301", created.Username)
+ require.Equal(t, " Jose\[email protected] ", *created.Email)
+ require.Equal(t, "José", *created.DisplayName)
+ created.DisplayName = new(" Andre\u0301 ")
+ profile, err := svc.UpdateUser(ctx, created, nil)
+ require.NoError(t, err)
+ require.Equal(t, "André", *profile.DisplayName)
+ require.Equal(t, "Jose\u0301", profile.Username)
+ require.Equal(t, " Jose\[email protected] ", *profile.Email)
+ created.Username = " Andre\u0301 "
+ created.DisplayName = nil
+ updated, err := svc.UpdateUser(ctx, created, nil)
+ require.NoError(t, err)
+ require.Equal(t, " Andre\u0301 ", updated.Username)
+ require.Nil(t, updated.DisplayName)
+ reloaded, err := svc.GetUserByID(ctx, updated.ID)
+ require.NoError(t, err)
+ require.Equal(t, " Andre\u0301 ", reloaded.Username)
+ require.Equal(t, " Jose\[email protected] ", *reloaded.Email)
+ _, err = svc.GetUserByUsername(ctx, " Andre\u0301 ")
+ require.NoError(t, err)
+ _, err = svc.CreateUser(ctx, &common.User{ID: "empty", Username: " \t "})
+ require.ErrorIs(t, err, ErrUsernameRequired)
+}
diff --git a/backend/internal/webhook/webhook.go b/backend/internal/webhook/webhook.go
index 7926ef1a5..57b1be9fe 100644
--- a/backend/internal/webhook/webhook.go
+++ b/backend/internal/webhook/webhook.go
@@ -2,6 +2,7 @@ package webhook
import (
"github.com/getarcaneapp/arcane/backend/v2/internal/common"
+ "go.getarcane.app/kit/normalization"
"context"
"crypto/rand"
@@ -220,6 +221,10 @@ func resolvedWebhookActionTypeInternal(targetType, actionType string) string {
// CreateWebhook creates a new webhook targeting a stack, the environment-wide updater, or a gitops sync.
// It returns the webhook record with the raw token populated (only available at creation time).
func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, actionType, targetID, environmentID string, actor common.User) (*Webhook, string, error) {
+ input := webhooktypes.CreateInput{Name: name, TargetType: targetType, ActionType: actionType, TargetID: targetID}
+ if err := normalization.Normalize(&input); err != nil {
+ return nil, "", err
+ }
resolvedActionType, err := resolveWebhookActionTypeInternal(targetType, actionType)
if err != nil {
return nil, "", err
@@ -249,7 +254,7 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, ac
}
wh := &Webhook{
- Name: name,
+ Name: input.Name,
TokenHash: hash,
TokenPrefix: prefix,
TargetType: targetType,
diff --git a/backend/internal/webhook/webhook_test.go b/backend/internal/webhook/webhook_test.go
index 2c59fd2cf..433218665 100644
--- a/backend/internal/webhook/webhook_test.go
+++ b/backend/internal/webhook/webhook_test.go
@@ -257,12 +257,13 @@ func TestCreateWebhook_PrefixMatchesToken(t *testing.T) {
db := setupWebhookServiceTestDB(t)
svc := newTestWebhookService(db)
- wh, rawToken, err := svc.CreateWebhook(ctx, "prefix-check", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})
+ wh, rawToken, err := svc.CreateWebhook(ctx, " cafe\u0301 hook ", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})
require.NoError(t, err)
hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)
expectedPrefix := webhookTokenPrefix + hexPart[:webhookTokenPrefixLen]
assert.Equal(t, expectedPrefix, wh.TokenPrefix)
+ assert.Equal(t, "café hook", wh.Name)
stored := fetchWebhook(t, db, wh.ID)
assert.Equal(t, expectedPrefix, stored.TokenPrefix)
diff --git a/backend/pkg/utils/sqlite/sqlite.go b/backend/pkg/utils/sqlite/sqlite.go
new file mode 100644
index 000000000..2498e1d24
--- /dev/null
+++ b/backend/pkg/utils/sqlite/sqlite.go
@@ -0,0 +1,53 @@
+package sqlite
+
+import (
+ "database/sql/driver"
+ "errors"
+ "fmt"
+ "strings"
+ "sync"
+
+ "golang.org/x/text/unicode/norm"
+ "modernc.org/sqlite"
+)
+
+var (
+ registerOnce sync.Once
+ errRegister error
+)
+
+// RegisterFunctions makes normalize(text, form) available to new SQLite connections.
+func RegisterFunctions() error {
+ registerOnce.Do(func() {
+ errRegister = sqlite.RegisterDeterministicScalarFunction("normalize", 2,
+ func(_ *sqlite.FunctionContext, args []driver.Value) (driver.Value, error) {
+ if args[0] == nil {
+ return nil, nil
+ }
+ value, ok := args[0].(string)
+ if !ok {
+ return nil, errors.New("normalize requires text as its first argument")
+ }
+ name, ok := args[1].(string)
+ if !ok {
+ return nil, errors.New("normalize requires a form as its second argument")
+ }
+ var form norm.Form
+ switch strings.ToLower(name) {
+ case "nfc":
+ form = norm.NFC
+ case "nfd":
+ form = norm.NFD
+ case "nfkc":
+ form = norm.NFKC
+ case "nfkd":
+ form = norm.NFKD
+ default:
+ return nil, fmt.Errorf("unsupported normalization form: %s", name)
+ }
+ return form.String(value), nil
+ },
+ )
+ })
+ return errRegister
+}
diff --git a/backend/resources/migrations/postgres/081_normalize_user_identity.sql b/backend/resources/migrations/postgres/081_normalize_user_identity.sql
new file mode 100644
index 000000000..d4faaa974
--- /dev/null
+++ b/backend/resources/migrations/postgres/081_normalize_user_identity.sql
@@ -0,0 +1,21 @@
+-- +goose Up
+-- +goose StatementBegin
+DO $$
+BEGIN
+ IF current_setting('server_encoding') = 'UTF8' THEN
+ -- Match Go's Unicode whitespace trimming before NFC normalization.
+ WITH whitespace AS (
+ SELECT U&'\0009\000A\000B\000C\000D\0020\0085\00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\2028\2029\202F\205F\3000' AS chars
+ )
+ UPDATE users
+ SET display_name = normalize(btrim(display_name, whitespace.chars), NFC)
+ FROM whitespace;
+ ELSE
+ RAISE NOTICE 'Skipping normalization: server_encoding is %', current_setting('server_encoding');
+ END IF;
+END;
+$$ LANGUAGE plpgsql;
+-- +goose StatementEnd
+
+-- +goose Down
+-- Original text cannot be reconstructed; restore it from a pre-upgrade backup.
diff --git a/backend/resources/migrations/sqlite/081_normalize_user_identity.sql b/backend/resources/migrations/sqlite/081_normalize_user_identity.sql
new file mode 100644
index 000000000..e709eedb5
--- /dev/null
+++ b/backend/resources/migrations/sqlite/081_normalize_user_identity.sql
@@ -0,0 +1,13 @@
+-- +goose Up
+-- Trim the same Unicode whitespace as Go, then normalize existing display names.
+WITH whitespace(chars) AS (
+ VALUES (char(9, 10, 11, 12, 13, 32, 133, 160, 5760,
+ 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202,
+ 8232, 8233, 8239, 8287, 12288))
+)
+UPDATE users
+SET display_name = normalize(trim(display_name, whitespace.chars), 'nfc')
+FROM whitespace;
+
+-- +goose Down
+-- Original text cannot be reconstructed; restore it from a pre-upgrade backup.
diff --git a/go.work.sum b/go.work.sum
index 4e5ed3d1c..1f49f0c54 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -2640,6 +2640,7 @@ go.getarcane.app/acfs v0.2.0/go.mod h1:sU3t21KctTsQM3OW10+RNB0Z6lR+YfaSr5Nxubq3c
go.getarcane.app/acfs v0.4.1/go.mod h1:sU3t21KctTsQM3OW10+RNB0Z6lR+YfaSr5Nxubq3cpI=
go.getarcane.app/acfs v0.4.2/go.mod h1:58JU/5d9TIawZrRvtND1jBmcDy6DrUP0FLhXklmrRjY=
go.getarcane.app/acfs v0.5.0/go.mod h1:Z+0Gs4LGNjvGMLq+TKv/oGKh29FRbAH6mcVPwY5KhFI=
+go.getarcane.app/acfs v0.5.1 h1:Rkrzpz8Qh9SVzP2VwpHtLA0clEjBpTA+xmrVuoZ+mMM=
go.getarcane.app/acfs v0.5.1/go.mod h1:Z+0Gs4LGNjvGMLq+TKv/oGKh29FRbAH6mcVPwY5KhFI=
go.getarcane.app/builds v0.3.1 h1:jymgkbcJ98o+XM9P0Ympn7m3WowWhG3vbiVwxIhhwns=
go.getarcane.app/builds v0.3.1/go.mod h1:MJXC3VNSspckX6NBu+l7kBaCckuNsXIw4B8WAuxXo94=
diff --git a/types/apikey/apikey.go b/types/apikey/apikey.go
index 58bdf1100..d1ff89d6e 100644
--- a/types/apikey/apikey.go
+++ b/types/apikey/apikey.go
@@ -10,9 +10,10 @@ type PermissionGrant struct {
}
// CreateApiKey represents the request body for creating an API key.
+// Fields tagged with unorm and trim are trimmed and normalized to Unicode NFC.
type CreateApiKey struct {
- Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key"`
- Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key"`
+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key" unorm:"nfc" trim:"true"`
+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key" unorm:"nfc" trim:"true"`
ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Optional expiration date for the API key"`
Permissions []PermissionGrant `json:"permissions" minItems:"1" doc:"Permissions granted to this key. Cannot exceed the creator's own permissions."`
}
@@ -21,8 +22,8 @@ type CreateApiKey struct {
// Personal keys carry no grants of their own; they inherit the owner's role
// permissions at authentication time.
type CreateUserApiKey struct {
- Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key"`
- Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key"`
+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Name of the API key" example:"My API Key" unorm:"nfc" trim:"true"`
+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description of the API key" unorm:"nfc" trim:"true"`
ExpiresAt *time.Time `json:"expiresAt,omitempty" doc:"Optional expiration date for the API key"`
}
@@ -52,8 +53,8 @@ type ApiKeyCreatedDto struct {
// UpdateApiKey represents the request body for updating an API key.
type UpdateApiKey struct {
- Name *string `json:"name,omitzero" maxLength:"255" doc:"New name for the API key"`
- Description *string `json:"description,omitzero" maxLength:"1000" doc:"New description for the API key"`
+ Name *string `json:"name,omitzero" maxLength:"255" doc:"New name for the API key" unorm:"nfc" trim:"true"`
+ Description *string `json:"description,omitzero" maxLength:"1000" doc:"New description for the API key" unorm:"nfc" trim:"true"`
ExpiresAt *time.Time `json:"expiresAt,omitzero" doc:"New expiration date for the API key"`
Permissions []PermissionGrant `json:"permissions,omitempty" doc:"Replace the key's permission grants. Omit to leave unchanged. Cannot exceed the updater's own permissions."`
}
diff --git a/types/apns/apns.go b/types/apns/apns.go
index f18f5991d..6682a7ca0 100644
--- a/types/apns/apns.go
+++ b/types/apns/apns.go
@@ -26,13 +26,13 @@ type PairingToken struct {
type RegisterDeviceRequest struct {
RecipientID string `json:"recipientId" minLength:"1" maxLength:"128"`
- Label string `json:"label" maxLength:"100"`
+ Label string `json:"label" maxLength:"100" unorm:"nfc" trim:"true"`
Events map[string]bool `json:"events,omitzero"`
EnvironmentIDs []string `json:"environmentIds,omitzero"`
}
type UpdateDeviceRequest struct {
- Label *string `json:"label,omitzero" maxLength:"100"`
+ Label *string `json:"label,omitzero" maxLength:"100" unorm:"nfc" trim:"true"`
Events *map[string]bool `json:"events,omitzero"`
EnvironmentIDs *[]string `json:"environmentIds,omitzero"`
}
diff --git a/types/auth/oidc.go b/types/auth/oidc.go
index 2a031b557..ef21e3143 100644
--- a/types/auth/oidc.go
+++ b/types/auth/oidc.go
@@ -16,7 +16,7 @@ type OidcUserInfo struct {
// Name is the full name of the user.
//
// Required: false
- Name string `json:"name,omitempty"`
+ Name string `json:"name,omitempty" unorm:"nfc" trim:"true"`
// Email is the email address of the user.
//
@@ -31,12 +31,12 @@ type OidcUserInfo struct {
// GivenName is the user's given name (first name).
//
// Required: false
- GivenName string `json:"given_name,omitempty"`
+ GivenName string `json:"given_name,omitempty" unorm:"nfc" trim:"true"`
// FamilyName is the user's family name (last name).
//
// Required: false
- FamilyName string `json:"family_name,omitempty"`
+ FamilyName string `json:"family_name,omitempty" unorm:"nfc" trim:"true"`
// Roles is a list of roles assigned to the user.
//
diff --git a/types/backup/s3.go b/types/backup/s3.go
index e4f5dc5fa..143925335 100644
--- a/types/backup/s3.go
+++ b/types/backup/s3.go
@@ -17,8 +17,9 @@ type S3Destination struct {
UpdatedAt *time.Time `json:"updatedAt,omitempty"`
}
+// CreateS3Destination trims and NFC-normalizes tagged display fields.
type CreateS3Destination struct {
- Name string `json:"name"`
+ Name string `json:"name" unorm:"nfc" trim:"true" minLength:"1"`
Endpoint string `json:"endpoint,omitempty"`
Bucket string `json:"bucket"`
Region string `json:"region"`
diff --git a/types/containerregistry/container_registry.go b/types/containerregistry/container_registry.go
index cea4ef10f..568969e62 100644
--- a/types/containerregistry/container_registry.go
+++ b/types/containerregistry/container_registry.go
@@ -174,7 +174,7 @@ type Sync struct {
// Description of the container registry.
//
// Required: false
- Description *string `json:"description,omitzero"`
+ Description *string `json:"description,omitzero" unorm:"nfc" trim:"true"`
// Insecure indicates if the registry uses an insecure connection (HTTP).
//
@@ -262,3 +262,32 @@ type SyncRequest struct {
// Required: true
Registries []Sync `json:"registries" binding:"required"`
}
+
+// CreateContainerRegistryRequest configures a registry with a normalized description.
+type CreateContainerRegistryRequest struct {
+ URL string `json:"url" binding:"required"`
+ Username string `json:"username"`
+ Token string `json:"token"`
+ Description *string `json:"description" unorm:"nfc" trim:"true"`
+ Insecure *bool `json:"insecure"`
+ Enabled *bool `json:"enabled"`
+ RegistryType string `json:"registryType"`
+ RepositoryNames []string `json:"repositoryNames"`
+ AWSAccessKeyID string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey string `json:"awsSecretAccessKey"`
+ AWSRegion string `json:"awsRegion"`
+}
+
+type UpdateContainerRegistryRequest struct {
+ URL *string `json:"url"`
+ Username *string `json:"username"`
+ Token *string `json:"token"`
+ Description *string `json:"description" unorm:"nfc" trim:"true"`
+ Insecure *bool `json:"insecure"`
+ Enabled *bool `json:"enabled"`
+ RegistryType *string `json:"registryType"`
+ RepositoryNames *[]string `json:"repositoryNames"`
+ AWSAccessKeyID *string `json:"awsAccessKeyId"`
+ AWSSecretAccessKey *string `json:"awsSecretAccessKey"`
+ AWSRegion *string `json:"awsRegion"`
+}
diff --git a/types/environment/environment.go b/types/environment/environment.go
index 37ad1376e..c963f63aa 100644
--- a/types/environment/environment.go
+++ b/types/environment/environment.go
@@ -2,6 +2,7 @@ package environment
import "time"
+// Create trims and NFC-normalizes tagged display fields.
type Create struct {
// ApiUrl is the URL of the environment API.
//
@@ -11,7 +12,7 @@ type Create struct {
// Name of the environment.
//
// Required: false
- Name *string `json:"name,omitempty"`
+ Name *string `json:"name,omitempty" unorm:"nfc" trim:"true"`
// Enabled indicates if the environment is enabled.
//
@@ -43,7 +44,7 @@ type Update struct {
// Name of the environment.
//
// Required: false
- Name *string `json:"name,omitzero"`
+ Name *string `json:"name,omitzero" unorm:"nfc" trim:"true"`
// Enabled indicates if the environment is enabled.
//
diff --git a/types/federated/federated.go b/types/federated/federated.go
index 53c6553b7..9d2c0e9c4 100644
--- a/types/federated/federated.go
+++ b/types/federated/federated.go
@@ -42,8 +42,8 @@ type FederatedCredential struct {
// CreateFederatedCredential is the request body for creating a federated
// workload identity credential.
type CreateFederatedCredential struct {
- Name string `json:"name" minLength:"1" maxLength:"255" doc:"Display name"`
- Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description"`
+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Display name" unorm:"nfc" trim:"true"`
+ Description *string `json:"description,omitempty" maxLength:"1000" doc:"Optional description" unorm:"nfc" trim:"true"`
Enabled bool `json:"enabled" doc:"Whether exchanges are allowed"`
IssuerURL string `json:"issuerUrl" minLength:"1" format:"uri" doc:"Trusted external OIDC issuer URL"`
Audiences []string `json:"audiences" minItems:"1" doc:"Allowed external token audiences"`
@@ -59,8 +59,8 @@ type CreateFederatedCredential struct {
// UpdateFederatedCredential is the request body for updating a federated
// workload identity credential.
type UpdateFederatedCredential struct {
- Name *string `json:"name,omitzero" maxLength:"255" doc:"Display name"`
- Description *string `json:"description,omitzero" maxLength:"1000" doc:"Optional description"`
+ Name *string `json:"name,omitzero" minLength:"1" maxLength:"255" doc:"Display name" unorm:"nfc" trim:"true"`
+ Description *string `json:"description,omitzero" maxLength:"1000" doc:"Optional description" unorm:"nfc" trim:"true"`
Enabled *bool `json:"enabled,omitzero" doc:"Whether exchanges are allowed"`
IssuerURL *string `json:"issuerUrl,omitzero" format:"uri" doc:"Trusted external OIDC issuer URL"`
Audiences []string `json:"audiences,omitempty" minItems:"1" doc:"Allowed external token audiences"`
diff --git a/types/gitops/gitops.go b/types/gitops/gitops.go
index 47ec43f8c..564b26d80 100644
--- a/types/gitops/gitops.go
+++ b/types/gitops/gitops.go
@@ -274,7 +274,7 @@ type CreateRepositoryRequest struct {
// Name of the git repository.
//
// Required: true
- Name string `json:"name" binding:"required"`
+ Name string `json:"name" binding:"required" unorm:"nfc" trim:"true"`
// URL of the git repository.
//
@@ -284,7 +284,7 @@ type CreateRepositoryRequest struct {
// AuthType specifies the authentication method (none, http, ssh).
//
// Required: true
- AuthType string `json:"authType" binding:"required"`
+ AuthType string `json:"authType" binding:"required,oneof=none http ssh"`
// Username for HTTP authentication.
//
@@ -306,12 +306,12 @@ type CreateRepositoryRequest struct {
// Default: accept_new
//
// Required: false
- SSHHostKeyVerification string `json:"sshHostKeyVerification,omitempty"`
+ SSHHostKeyVerification string `json:"sshHostKeyVerification,omitempty" binding:"omitempty,oneof=strict accept_new skip"`
// Description of the git repository.
//
// Required: false
- Description *string `json:"description,omitempty"`
+ Description *string `json:"description,omitempty" unorm:"nfc" trim:"true"`
// Enabled indicates if the repository is enabled.
//
@@ -324,7 +324,7 @@ type UpdateRepositoryRequest struct {
// Name of the git repository.
//
// Required: false
- Name *string `json:"name,omitzero"`
+ Name *string `json:"name,omitzero" unorm:"nfc" trim:"true"`
// URL of the git repository.
//
@@ -334,7 +334,7 @@ type UpdateRepositoryRequest struct {
// AuthType specifies the authentication method (none, http, ssh).
//
// Required: false
- AuthType *string `json:"authType,omitzero"`
+ AuthType *string `json:"authType,omitzero" binding:"omitempty,oneof=none http ssh"`
// Username for HTTP authentication.
//
@@ -355,12 +355,12 @@ type UpdateRepositoryRequest struct {
// Options: strict (require known_hosts), accept_new (auto-add new hosts), skip (disable verification).
//
// Required: false
- SSHHostKeyVerification *string `json:"sshHostKeyVerification,omitzero"`
+ SSHHostKeyVerification *string `json:"sshHostKeyVerification,omitzero" binding:"omitempty,oneof=strict accept_new skip"`
// Description of the git repository.
//
// Required: false
- Description *string `json:"description,omitzero"`
+ Description *string `json:"description,omitzero" unorm:"nfc" trim:"true"`
// Enabled indicates if the repository is enabled.
//
@@ -757,7 +757,7 @@ type RepositorySync struct {
// Name of the git repository.
//
// Required: true
- Name string `json:"name" binding:"required"`
+ Name string `json:"name" binding:"required" unorm:"nfc" trim:"true"`
// URL of the git repository.
//
@@ -792,7 +792,7 @@ type RepositorySync struct {
// Description of the git repository.
//
// Required: false
- Description *string `json:"description,omitempty"`
+ Description *string `json:"description,omitempty" unorm:"nfc" trim:"true"`
// Enabled indicates if the repository is enabled.
//
diff --git a/types/role/role.go b/types/role/role.go
index 3aea68f0f..7104c4987 100644
--- a/types/role/role.go
+++ b/types/role/role.go
@@ -18,17 +18,18 @@ type Role struct {
}
// CreateRole is the request body for creating a custom role.
+// Fields tagged with unorm and trim are trimmed and normalized to Unicode NFC.
type CreateRole struct {
- Name string `json:"name" minLength:"1" maxLength:"100" doc:"Display name of the role" example:"Deploy Bot"`
- Description *string `json:"description,omitempty" maxLength:"500" doc:"Optional human description"`
+ Name string `json:"name" minLength:"1" maxLength:"100" doc:"Display name of the role" example:"Deploy Bot" unorm:"nfc" trim:"true"`
+ Description *string `json:"description,omitempty" maxLength:"500" doc:"Optional human description" unorm:"nfc" trim:"true"`
Permissions []string `json:"permissions" minItems:"1" doc:"Permission strings granted by this role"`
}
// UpdateRole is the request body for editing a custom role. Built-in roles
// cannot be updated and will return 403.
type UpdateRole struct {
- Name string `json:"name" minLength:"1" maxLength:"100" doc:"Display name of the role"`
- Description *string `json:"description,omitzero" maxLength:"500" doc:"Optional human description"`
+ Name string `json:"name" minLength:"1" maxLength:"100" doc:"Display name of the role" unorm:"nfc" trim:"true"`
+ Description *string `json:"description,omitzero" maxLength:"500" doc:"Optional human description" unorm:"nfc" trim:"true"`
Permissions []string `json:"permissions" minItems:"1" doc:"Permission strings granted by this role"`
}
diff --git a/types/settings/settings.go b/types/settings/settings.go
index dffe04aa5..48a203fe5 100644
--- a/types/settings/settings.go
+++ b/types/settings/settings.go
@@ -421,7 +421,7 @@ type Update struct {
// OidcProviderName is the custom display name for the OIDC provider.
//
// Required: false
- OidcProviderName *string `json:"oidcProviderName,omitzero"`
+ OidcProviderName *string `json:"oidcProviderName,omitzero" unorm:"nfc" trim:"true"`
// OidcProviderLogoUrl is the custom logo URL for the OIDC provider.
//
diff --git a/types/template/template.go b/types/template/template.go
index c0910185c..ca1f542ac 100644
--- a/types/template/template.go
+++ b/types/template/template.go
@@ -190,16 +190,17 @@ type Template struct {
}
// CreateRequest represents the request to create a template.
+// Fields tagged with unorm and trim are trimmed and normalized to Unicode NFC.
type CreateRequest struct {
// Name of the template.
//
// Required: true
- Name string `json:"name"`
+ Name string `json:"name" unorm:"nfc" trim:"true" minLength:"1"`
// Description of the template.
//
// Required: false
- Description string `json:"description"`
+ Description string `json:"description" unorm:"nfc" trim:"true"`
// Content is the Docker Compose file content.
//
@@ -217,12 +218,12 @@ type UpdateRequest struct {
// Name of the template.
//
// Required: true
- Name string `json:"name"`
+ Name string `json:"name" unorm:"nfc" trim:"true" minLength:"1"`
// Description of the template.
//
// Required: false
- Description string `json:"description"`
+ Description string `json:"description" unorm:"nfc" trim:"true"`
// Content is the Docker Compose file content.
//
@@ -276,7 +277,7 @@ type CreateRegistryRequest struct {
// Name of the registry.
//
// Required: true
- Name string `json:"name"`
+ Name string `json:"name" unorm:"nfc" trim:"true"`
// URL of the registry.
//
@@ -286,7 +287,7 @@ type CreateRegistryRequest struct {
// Description of the registry.
//
// Required: false
- Description string `json:"description"`
+ Description string `json:"description" unorm:"nfc" trim:"true"`
// Enabled indicates if the registry is enabled.
//
@@ -299,7 +300,7 @@ type UpdateRegistryRequest struct {
// Name of the registry.
//
// Required: true
- Name string `json:"name"`
+ Name string `json:"name" unorm:"nfc" trim:"true"`
// URL of the registry.
//
@@ -309,7 +310,7 @@ type UpdateRegistryRequest struct {
// Description of the registry.
//
// Required: false
- Description string `json:"description"`
+ Description string `json:"description" unorm:"nfc" trim:"true"`
// Enabled indicates if the registry is enabled.
//
diff --git a/types/user/user.go b/types/user/user.go
index 01b503a21..874c776dd 100644
--- a/types/user/user.go
+++ b/types/user/user.go
@@ -30,10 +30,11 @@ type Preferences struct {
// CreateUser represents the request body for creating a new user.
// Role assignments are managed separately via PUT /users/{userId}/role-assignments.
+// Fields tagged with unorm and trim are trimmed and normalized to Unicode NFC.
type CreateUser struct {
Username string `json:"username" minLength:"1" maxLength:"255" pattern:"^[^@]+$" patternDescription:"username without an @ character" doc:"Username of the user; may not contain @" example:"johndoe"`
Password string `json:"password" minLength:"8" doc:"Password of the user"`
- DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user" example:"John Doe"`
+ DisplayName *string `json:"displayName,omitempty" maxLength:"255" doc:"Display name of the user" example:"John Doe" unorm:"nfc" trim:"true"`
Email *string `json:"email,omitempty" doc:"Email address of the user" example:"[email protected]"`
Locale *string `json:"locale,omitempty" doc:"Locale preference of the user" example:"en-US"`
TimeFormat *TimeFormat `json:"timeFormat,omitempty" enum:"auto,12h,24h" doc:"Preferred time display format" example:"auto"`
@@ -43,7 +44,7 @@ type CreateUser struct {
// Role assignments are managed separately via PUT /users/{userId}/role-assignments.
type UpdateUser struct {
Username *string `json:"username,omitzero" minLength:"1" maxLength:"255" pattern:"^[^@]+$" patternDescription:"username without an @ character" doc:"Username of the user; may not contain @"`
- DisplayName *string `json:"displayName,omitzero" maxLength:"255" doc:"Display name of the user"`
+ DisplayName *string `json:"displayName,omitzero" maxLength:"255" doc:"Display name of the user" unorm:"nfc" trim:"true"`
Email *string `json:"email,omitzero" doc:"Email address of the user"`
Locale *string `json:"locale,omitzero" doc:"Locale preference of the user"`
TimeFormat *TimeFormat `json:"timeFormat,omitzero" enum:"auto,12h,24h" doc:"Preferred time display format"`
diff --git a/types/webhook/webhook.go b/types/webhook/webhook.go
index bd926c478..708a4c5ae 100644
--- a/types/webhook/webhook.go
+++ b/types/webhook/webhook.go
@@ -4,7 +4,7 @@ import "time"
// CreateInput is the request body for creating a webhook.
type CreateInput struct {
- Name string `json:"name" minLength:"1" maxLength:"255" doc:"Human-readable name for this webhook"`
+ Name string `json:"name" minLength:"1" maxLength:"255" doc:"Human-readable name for this webhook" unorm:"nfc" trim:"true"`
TargetType string `json:"targetType" doc:"Resource type this webhook targets: 'container', 'project', 'updater', or 'gitops'" enum:"container,project,updater,gitops"`
ActionType string `json:"actionType" doc:"Action to run for the selected target type. Supported values depend on targetType." enum:"update,start,stop,restart,redeploy,up,down,run,sync"`
TargetID string `json:"targetId" doc:"Container ID, project ID, or GitOps sync ID to target. Leave empty for 'updater' webhooks."`