Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: move models into standalone domain packages (#3636)
Kyle Mendell2bfc5889d3b6
diff --git a/backend/cli/admin/reset_mfa_test.go b/backend/cli/admin/reset_mfa_test.goindex cc004390f..1adf7c3a7 100644--- a/backend/cli/admin/reset_mfa_test.go+++ b/backend/cli/admin/reset_mfa_test.go@@ -1,6 +1,8 @@package adminimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"bytes""context""testing"@@ -15,7 +17,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/types/v2/auth")@@ -24,12 +25,12 @@ func newResetMFATestDBInternal(t *testing.T) *database.DB {gormDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, gormDB.AutoMigrate(- &models.User{},- &models.UserSession{},- &models.Passkey{},- &models.PasskeyCeremony{},- &models.AuthTransaction{},- &models.PasskeyRecoveryCode{},+ &common.User{},+ &session.UserSession{},+ &passkey.Passkey{},+ &passkey.PasskeyCeremony{},+ &passkey.AuthTransaction{},+ &passkey.PasskeyRecoveryCode{},))db := &database.DB{DB: gormDB}@@ -56,14 +57,14 @@ func TestConfirmMFAResetInternal(t *testing.T) {func TestResetMFACommandServiceStatePreservesPasskey(t *testing.T) {db := newResetMFATestDBInternal(t)ctx := context.Background()- user := &models.User{- BaseModel: models.BaseModel{ID: "mfa-reset-user"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "mfa-reset-user"},Username: "alice",PasskeyMFAEnabled: true,}require.NoError(t, db.Create(user).Error)- passkeyRecord := &models.Passkey{- BaseModel: models.BaseModel{ID: "mfa-reset-passkey"},+ passkeyRecord := &passkey.Passkey{+ BaseModel: database.BaseModel{ID: "mfa-reset-passkey"},UserID: user.ID,RPID: "arcane.example.test",CredentialID: []byte("credential"),@@ -76,22 +77,22 @@ func TestResetMFACommandServiceStatePreservesPasskey(t *testing.T) {require.NoError(t, err)secondSession, _, err := sessionService.CreateSession(ctx, user.ID, time.Now().Add(time.Hour), auth.SessionMeta{})require.NoError(t, err)- require.NoError(t, db.Create(&models.PasskeyRecoveryCode{- BaseModel: models.BaseModel{ID: "mfa-reset-code"},+ require.NoError(t, db.Create(&passkey.PasskeyRecoveryCode{+ BaseModel: database.BaseModel{ID: "mfa-reset-code"},UserID: user.ID,CodeHash: "stored-hash",}).Error)- transaction := &models.AuthTransaction{- BaseModel: models.BaseModel{ID: "mfa-reset-transaction"},+ transaction := &passkey.AuthTransaction{+ BaseModel: database.BaseModel{ID: "mfa-reset-transaction"},Kind: "mfa",UserID: user.ID,- Source: models.UserSessionSourceLocal,+ Source: session.UserSessionSourceLocal,Status: "pending",ExpiresAt: time.Now().Add(time.Minute),}require.NoError(t, db.Create(transaction).Error)- require.NoError(t, db.Create(&models.PasskeyCeremony{- BaseModel: models.BaseModel{ID: "mfa-reset-ceremony"},+ require.NoError(t, db.Create(&passkey.PasskeyCeremony{+ BaseModel: database.BaseModel{ID: "mfa-reset-ceremony"},Purpose: "mfa",UserID: new(user.ID),AuthTransactionID: new(transaction.ID),@@ -103,18 +104,18 @@ func TestResetMFACommandServiceStatePreservesPasskey(t *testing.T) {service := passkey.NewPasskeyService(db, &config.Config{AppUrl: "https://arcane.example.test"})require.NoError(t, service.ResetMFAForUser(ctx, user.ID))- var updatedUser models.User+ var updatedUser common.Userrequire.NoError(t, db.Where("id = ?", user.ID).First(&updatedUser).Error)require.False(t, updatedUser.PasskeyMFAEnabled)var count int64- require.NoError(t, db.Model(&models.PasskeyRecoveryCode{}).Where("user_id = ?", user.ID).Count(&count).Error)+ require.NoError(t, db.Model(&passkey.PasskeyRecoveryCode{}).Where("user_id = ?", user.ID).Count(&count).Error)require.Zero(t, count)- require.NoError(t, db.Model(&models.PasskeyCeremony{}).Where("user_id = ?", user.ID).Count(&count).Error)+ require.NoError(t, db.Model(&passkey.PasskeyCeremony{}).Where("user_id = ?", user.ID).Count(&count).Error)require.Zero(t, count)- require.NoError(t, db.Model(&models.AuthTransaction{}).Where("user_id = ?", user.ID).Count(&count).Error)+ require.NoError(t, db.Model(&passkey.AuthTransaction{}).Where("user_id = ?", user.ID).Count(&count).Error)require.Zero(t, count)- var preserved models.Passkey+ var preserved passkey.Passkeyrequire.NoError(t, db.Where("id = ?", passkeyRecord.ID).First(&preserved).Error)require.Equal(t, passkeyRecord.ID, preserved.ID)first, err := sessionService.GetSessionByID(ctx, firstSession.ID)diff --git a/backend/cli/admin/reset_password.go b/backend/cli/admin/reset_password.goindex 264d960f8..0ea6d99ed 100644--- a/backend/cli/admin/reset_password.go+++ b/backend/cli/admin/reset_password.go@@ -1,6 +1,8 @@package adminimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""fmt""io"@@ -15,7 +17,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"@@ -138,7 +139,7 @@ func validatePasswordPairInternal(password, confirmation, policy string) error {}func passwordPolicyFromDBInternal(ctx context.Context, db *database.DB) string {- var setting models.SettingVariable+ var setting settings.SettingVariableerr := db.WithContext(ctx).First(&setting, "key = ?", "authPasswordPolicy").Errorif err != nil || strings.TrimSpace(setting.Value) == "" {return validation.PasswordPolicyStrongdiff --git a/backend/cli/admin/reset_password_test.go b/backend/cli/admin/reset_password_test.goindex 5548bbd77..72dbd910c 100644--- a/backend/cli/admin/reset_password_test.go+++ b/backend/cli/admin/reset_password_test.go@@ -1,6 +1,8 @@package adminimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""testing""time"@@ -11,7 +13,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/user"@@ -26,10 +27,10 @@ func newResetPasswordTestDBInternal(t *testing.T) *database.DB {gormDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, gormDB.AutoMigrate(- &models.User{},- &models.UserSession{},- &models.Role{},- &models.UserRoleAssignment{},+ &common.User{},+ &session.UserSession{},+ &role.Role{},+ &role.UserRoleAssignment{},))db := &database.DB{DB: gormDB}@@ -39,7 +40,7 @@ func newResetPasswordTestDBInternal(t *testing.T) *database.DB {return db}-func createGlobalAdminInternal(t *testing.T, db *database.DB) (*models.User, *role.RoleService, *user.UserService) {+func createGlobalAdminInternal(t *testing.T, db *database.DB) (*common.User, *role.RoleService, *user.UserService) {t.Helper()ctx := context.Background()roleService := role.NewRoleService(db)@@ -47,14 +48,14 @@ func createGlobalAdminInternal(t *testing.T, db *database.DB) (*models.User, *rouserService := user.NewUserService(db).WithRoleService(roleService)passwordHash, err := userService.HashPassword("old-password")require.NoError(t, err)- adminUser, err := userService.CreateUser(ctx, &models.User{- BaseModel: models.BaseModel{ID: "admin-1"},+ adminUser, err := userService.CreateUser(ctx, &common.User{+ BaseModel: database.BaseModel{ID: "admin-1"},Username: "arcane",PasswordHash: passwordHash,RequiresPasswordChange: true,})require.NoError(t, err)- require.NoError(t, roleService.SetUserAssignments(ctx, adminUser.ID, []models.UserRoleAssignment{+ require.NoError(t, roleService.SetUserAssignments(ctx, adminUser.ID, []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleAdmin},}))@@ -122,8 +123,8 @@ func TestResetPasswordInternalRejectsNonAdmin(t *testing.T) {_, _, userService := createGlobalAdminInternal(t, db)passwordHash, err := userService.HashPassword("old-password")require.NoError(t, err)- nonAdmin, err := userService.CreateUser(ctx, &models.User{- BaseModel: models.BaseModel{ID: "user-1"},+ nonAdmin, err := userService.CreateUser(ctx, &common.User{+ BaseModel: database.BaseModel{ID: "user-1"},Username: "operator",PasswordHash: passwordHash,RequiresPasswordChange: true,diff --git a/backend/internal/activity/handler.go b/backend/internal/activity/handler.goindex 7cf449e3f..6ac54664e 100644--- a/backend/internal/activity/handler.go+++ b/backend/internal/activity/handler.go@@ -1,6 +1,8 @@package activityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""hash/fnv"@@ -15,7 +17,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"@@ -37,9 +38,9 @@ type ActivityHandler struct {type EnvironmentDependencies struct {ProxyJSONRequest handlerutil.RemoteJSONProxy- ListRemoteEnvironments func(context.Context) ([]models.Environment, error)- GetActiveRemoteEnvironment func(string) mo.Option[models.Environment]- ProxyJSONRequestForEnvironment func(context.Context, models.Environment, string, string, []byte, any) error+ ListRemoteEnvironments func(context.Context) ([]environment.Environment, error)+ GetActiveRemoteEnvironment func(string) mo.Option[environment.Environment]+ ProxyJSONRequestForEnvironment func(context.Context, environment.Environment, string, string, []byte, any) errorResolveEnvironmentName func(context.Context, string) string}@@ -269,7 +270,7 @@ func (h *ActivityHandler) proxyCancelActivityInternal(ctx context.Context, input// audit message, preferring the authenticated user and falling back to a name// forwarded from a proxying controller.func (h *ActivityHandler) cancelRequestedByInternal(ctx context.Context, forwarded string) string {- if user, ok := models.CurrentUserFromContext(ctx); ok && user != nil {+ if user, ok := common.CurrentUserFromContext(ctx); ok && user != nil {if user.DisplayName != nil && strings.TrimSpace(*user.DisplayName) != "" {return strings.TrimSpace(*user.DisplayName)}@@ -339,7 +340,7 @@ func (h *ActivityHandler) RunLocalStreamProducer(ctx context.Context, limit int,// or removed while the stream is open are picked up without a reconnect.func (h *ActivityHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz.PermissionSet, limit int, events chan<- activitytypes.StreamEvent) {agg.ReconcilePollersByKey(ctx,- func(ctx context.Context) ([]models.Environment, error) {+ func(ctx context.Context) ([]environment.Environment, error) {environments, err := h.environment.ListRemoteEnvironments(ctx)if err != nil {return nil, err@@ -352,13 +353,13 @@ func (h *ActivityHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz.}return allowed, nil},- func(environment models.Environment) string {+ func(environment environment.Environment) string {return environment.ID},activityStreamEnvironmentVersionInternal,activityStreamEnvReconcileInterval,"activity stream",- func(pollCtx context.Context, environment models.Environment) {+ func(pollCtx context.Context, environment environment.Environment) {// One shared poller per environment (and snapshot limit) serves// every connected client; this subscriber only forwards its// events onto this client's stream.@@ -373,7 +374,7 @@ func (h *ActivityHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz.})}-func activityStreamEnvironmentVersionInternal(environment models.Environment) string {+func activityStreamEnvironmentVersionInternal(environment environment.Environment) string {if environment.UpdatedAt == nil {return environment.ID}@@ -408,7 +409,7 @@ func activitySnapshotFingerprintInternal(items []activitytypes.Activity) stringreturn strconv.FormatUint(hash.Sum64(), 16)}-func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Context, environment models.Environment, limit int, publish func(activitytypes.StreamEvent)) {+func (h *ActivityHandler) runRemoteActivityStreamPollerInternal(ctx context.Context, environment environment.Environment, limit int, publish func(activitytypes.StreamEvent)) {environmentID := environment.IDlastError := ""lastFingerprint := ""@@ -489,7 +490,7 @@ func (h *ActivityHandler) proxyListActivitiesInternal(ctx context.Context, inputreturn &ListActivitiesOutput{Body: *out}, nil}-func (h *ActivityHandler) proxyListActivitiesForEnvironmentInternal(ctx context.Context, environment models.Environment, input *ListActivitiesInput) (*ListActivitiesOutput, error) {+func (h *ActivityHandler) proxyListActivitiesForEnvironmentInternal(ctx context.Context, environment environment.Environment, input *ListActivitiesInput) (*ListActivitiesOutput, error) {path := "/api/environments/0/activities?" + activityListQueryInternal(input).Encode()var out base.Paginated[activitytypes.Activity]if err := h.environment.ProxyJSONRequestForEnvironment(ctx, environment, http.MethodGet, path, nil, &out); err != nil {@@ -542,14 +543,14 @@ func (h *ActivityHandler) applyActivityStreamEventSourceLabelInternal(ctx contex}}-func applyActivitySourceLabelsForEnvironmentInternal(environmentModel models.Environment, activities []activitytypes.Activity) {+func applyActivitySourceLabelsForEnvironmentInternal(environmentModel environment.Environment, activities []activitytypes.Activity) {sourceID, sourceName := activitySourceFromEnvironmentInternal(environmentModel)for i := range activities {applyActivitySourceInternal(&activities[i], sourceID, sourceName)}}-func activitySourceFromEnvironmentInternal(environmentModel models.Environment) (string, string) {+func activitySourceFromEnvironmentInternal(environmentModel environment.Environment) (string, string) {environmentID := environmentModel.IDif environmentID == "" {environmentID = environment.LocalEnvironmentIDdiff --git a/backend/internal/activity/model.go b/backend/internal/activity/model.gonew file mode 100644index 000000000..1737ce4ab--- /dev/null+++ b/backend/internal/activity/model.go@@ -0,0 +1,50 @@+package activity++import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"++ "time"++ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+)++type Activity struct {+ database.BaseModel++ EnvironmentID string `json:"environmentId" gorm:"column:environment_id;not null;index" sortable:"true"`+ BatchID *string `json:"batchId,omitempty" gorm:"column:batch_id;index"`+ Type activitytypes.Type `json:"type" gorm:"column:type;not null;index" sortable:"true"`+ Status activitytypes.Status `json:"status" gorm:"column:status;not null;index" sortable:"true"`+ ResourceType *string `json:"resourceType,omitempty" gorm:"column:resource_type;index" sortable:"true"`+ ResourceID *string `json:"resourceId,omitempty" gorm:"column:resource_id;index"`+ ResourceName *string `json:"resourceName,omitempty" gorm:"column:resource_name" sortable:"true"`+ Progress *int `json:"progress,omitempty" gorm:"column:progress"`+ Step string `json:"step,omitempty" gorm:"column:step"`+ LatestMessage string `json:"latestMessage,omitempty" gorm:"column:latest_message"`+ StartedByUserID *string `json:"startedByUserId,omitempty" gorm:"column:started_by_user_id;index"`+ StartedByUsername *string `json:"startedByUsername,omitempty" gorm:"column:started_by_username"`+ StartedByDisplayName *string `json:"startedByDisplayName,omitempty" gorm:"column:started_by_display_name"`+ StartedAt time.Time `json:"startedAt" gorm:"column:started_at;not null" sortable:"true"`+ EndedAt *time.Time `json:"endedAt,omitempty" gorm:"column:ended_at" sortable:"true"`+ DurationMs *int64 `json:"durationMs,omitempty" gorm:"column:duration_ms" sortable:"true"`+ Error *string `json:"error,omitempty" gorm:"column:error"`+ Metadata database.JSON `json:"metadata,omitempty" gorm:"type:text"`+}++func (Activity) TableName() string {+ return "activities"+}++type ActivityMessage struct {+ database.BaseModel++ ActivityID string `json:"activityId" gorm:"column:activity_id;not null;index"`+ Level activitytypes.MessageLevel `json:"level" gorm:"column:level;not null"`+ Message string `json:"message" gorm:"column:message;not null"`+ Payload database.JSON `json:"payload,omitempty" gorm:"type:text"`+ Activity *Activity `json:"-" gorm:"foreignKey:ActivityID;constraint:OnDelete:CASCADE"`+}++func (ActivityMessage) TableName() string {+ return "activity_messages"+}diff --git a/backend/internal/activity/service.go b/backend/internal/activity/service.goindex c249f6ba2..5ac77fdc4 100644--- a/backend/internal/activity/service.go+++ b/backend/internal/activity/service.go@@ -14,7 +14,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"@@ -319,17 +318,17 @@ func (s *ActivityService) StartActivity(ctx context.Context, req StartActivityRe// Queue-opted activities take a concurrency slot up front when one is// free; otherwise they are created as queued and AwaitActivitySlot blocks// until a slot opens.- status := models.ActivityStatusRunning+ status := activitytypes.StatusRunningvar slotRelease func()if req.Queue {if release, ok := s.limiter.tryAcquireInternal(ctx, environmentID).Get(); ok {slotRelease = release} else {- status = models.ActivityStatusQueued+ status = activitytypes.StatusQueued}}- model := &models.Activity{+ model := &Activity{EnvironmentID: environmentID,BatchID: copyPtrInternal(batchID),Type: req.Type,@@ -345,12 +344,12 @@ func (s *ActivityService) StartActivity(ctx context.Context, req StartActivityReLatestMessage: strings.TrimSpace(req.LatestMessage),StartedAt: now,Metadata: cloneJSONInternal(req.Metadata),- BaseModel: models.BaseModel{+ BaseModel: database.BaseModel{CreatedAt: now,},}if model.Type == "" {- model.Type = models.ActivityTypeAutoUpdate+ model.Type = activitytypes.TypeAutoUpdate}if err := s.db.WithContext(ctx).Create(model).Error; err != nil {@@ -423,7 +422,7 @@ func (s *ActivityService) AwaitActivitySlot(ctx context.Context, activityID, env}s.registerSlotReleaseInternal(activityID, release)- if _, updateErr := s.UpdateActivity(ctx, activityID, UpdateActivityRequest{Status: models.ActivityStatusRunning}); updateErr != nil {+ if _, updateErr := s.UpdateActivity(ctx, activityID, UpdateActivityRequest{Status: activitytypes.StatusRunning}); updateErr != nil {slog.Warn("failed to mark queued activity running", "activityId", activityID, "error", updateErr)}return nil@@ -483,9 +482,9 @@ func (s *ActivityService) UpdateActivity(ctx context.Context, activityID string,lock.Lock()defer lock.Unlock()- var model models.Activity+ var model Activityif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- result := tx.Model(&models.Activity{}).Where("id = ?", activityID).Updates(updates)+ result := tx.Model(&Activity{}).Where("id = ?", activityID).Updates(updates)if result.Error != nil {return errors.WrapIf(result.Error, "failed to update activity")}@@ -562,9 +561,9 @@ func (s *ActivityService) AppendMessages(ctx context.Context, activityID string,// buildAppendBatchInternal turns the request batch into insertable message rows// plus the coalesced Activity column updates (latest message/progress/step from// the last request carrying each).-func buildAppendBatchInternal(activityID string, reqs []AppendActivityMessageRequest) ([]*models.ActivityMessage, map[string]any) {+func buildAppendBatchInternal(activityID string, reqs []AppendActivityMessageRequest) ([]*ActivityMessage, map[string]any) {now := time.Now()- messages := make([]*models.ActivityMessage, 0, len(reqs))+ messages := make([]*ActivityMessage, 0, len(reqs))latestMessage := ""var latestProgress *intlatestStep := ""@@ -579,15 +578,15 @@ func buildAppendBatchInternal(activityID string, reqs []AppendActivityMessageReqlevel := req.Levelif level == "" {- level = models.ActivityMessageLevelInfo+ level = activitytypes.MessageLevelInfo}- messages = append(messages, &models.ActivityMessage{+ messages = append(messages, &ActivityMessage{ActivityID: activityID,Level: level,Message: messageText,Payload: cloneJSONInternal(req.Payload),- BaseModel: models.BaseModel{+ BaseModel: database.BaseModel{// Spread inside the shared timestamp so the created_at sort// used for retrieval keeps the original line order.CreatedAt: now.Add(time.Duration(len(messages)) * time.Microsecond),@@ -624,8 +623,8 @@ func buildAppendBatchInternal(activityID string, reqs []AppendActivityMessageReq// SQLite write lock, and a batch lost to transient SQLITE_BUSY silently drops// up to 32 output lines — the Writer drain has no error path to replay them —// so retry like CompleteActivity does.-func (s *ActivityService) appendBatchWithRetryInternal(ctx context.Context, activityID string, messages []*models.ActivityMessage, updates map[string]any) (*models.Activity, error) {- var current models.Activity+func (s *ActivityService) appendBatchWithRetryInternal(ctx context.Context, activityID string, messages []*ActivityMessage, updates map[string]any) (*Activity, error) {+ var current Activityconst appendWriteAttempts = 3var writeErr errorfor attempt := 1; attempt <= appendWriteAttempts; attempt++ {@@ -641,7 +640,7 @@ func (s *ActivityService) appendBatchWithRetryInternal(ctx context.Context, actireturn errors.WrapIf(err, "failed to append activity message")}- result := tx.Model(&models.Activity{}).Where("id = ?", activityID).Updates(updates)+ result := tx.Model(&Activity{}).Where("id = ?", activityID).Updates(updates)if result.Error != nil {return errors.WrapIf(result.Error, "failed to update activity latest message")}@@ -665,15 +664,15 @@ func (s *ActivityService) appendBatchWithRetryInternal(ctx context.Context, actireturn nil, writeErr}-func (s *ActivityService) CompleteActivity(ctx context.Context, activityID string, status models.ActivityStatus, finalMessage string, errMessage *string, finalStep ...string) (*activitytypes.Activity, error) {+func (s *ActivityService) CompleteActivity(ctx context.Context, activityID string, status activitytypes.Status, finalMessage string, errMessage *string, finalStep ...string) (*activitytypes.Activity, error) {if err := s.checkInitInternal(); err != nil {return nil, err}if status == "" {- status = models.ActivityStatusSuccess+ status = activitytypes.StatusSuccess}- if status != models.ActivityStatusSuccess && status != models.ActivityStatusFailed && status != models.ActivityStatusCancelled {- status = models.ActivityStatusSuccess+ if status != activitytypes.StatusSuccess && status != activitytypes.StatusFailed && status != activitytypes.StatusCancelled {+ status = activitytypes.StatusSuccess}activityID = strings.TrimSpace(activityID)@@ -691,7 +690,7 @@ func (s *ActivityService) CompleteActivity(ctx context.Context, activityID strinctx = context.WithoutCancel(ctx)now := time.Now()- var model models.Activity+ var model Activity// A lost terminal write leaves the activity stuck in running forever, so// retry transient DB contention (SQLITE_BUSY under bulk activity writes)// instead of surfacing it once and giving up.@@ -704,7 +703,7 @@ func (s *ActivityService) CompleteActivity(ctx context.Context, activityID strin}updates := completeActivityUpdatesInternal(model.StartedAt, status, finalMessage, errMessage, finalStep, now)- if err := tx.Model(&models.Activity{}).Where("id = ?", activityID).Updates(updates).Error; err != nil {+ if err := tx.Model(&Activity{}).Where("id = ?", activityID).Updates(updates).Error; err != nil {return errors.WrapIf(err, "failed to complete activity")}if err := tx.First(&model, "id = ?", activityID).Error; err != nil {@@ -726,13 +725,13 @@ func (s *ActivityService) CompleteActivity(ctx context.Context, activityID strin}if strings.TrimSpace(finalMessage) != "" {- level := models.ActivityMessageLevelSuccess+ level := activitytypes.MessageLevelSuccessswitch status {- case models.ActivityStatusFailed:- level = models.ActivityMessageLevelError- case models.ActivityStatusCancelled:- level = models.ActivityMessageLevelWarning- case models.ActivityStatusQueued, models.ActivityStatusRunning, models.ActivityStatusSuccess:+ case activitytypes.StatusFailed:+ level = activitytypes.MessageLevelError+ case activitytypes.StatusCancelled:+ level = activitytypes.MessageLevelWarning+ case activitytypes.StatusQueued, activitytypes.StatusRunning, activitytypes.StatusSuccess:}activityCtx := utils.ActivityRuntimeContext(ctx, nil)if _, err := s.AppendMessage(activityCtx, activityID, AppendActivityMessageRequest{@@ -756,12 +755,12 @@ func (s *ActivityService) CompleteActivity(ctx context.Context, activityID strin// guarantees the terminal event carries every field already streamed. The// passed model is published as-is if the re-read fails, and is updated in// place otherwise so callers return the published state.-func (s *ActivityService) publishTerminalSnapshotInternal(ctx context.Context, model *models.Activity) activitytypes.Activity {+func (s *ActivityService) publishTerminalSnapshotInternal(ctx context.Context, model *Activity) activitytypes.Activity {lock := s.publishLockInternal(model.ID)lock.Lock()defer lock.Unlock()- var fresh models.Activity+ var fresh Activityif err := s.db.WithContext(ctx).First(&fresh, "id = ?", model.ID).Error; err != nil {slog.DebugContext(ctx, "failed to reload activity for terminal publish", "activityId", model.ID, "error", err)} else {@@ -790,14 +789,14 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, actenvironmentID = "0"}- var model models.Activity+ var model Activityif err := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", activityID, environmentID).First(&model).Error; err != nil {return nil, err}switch model.Status {- case models.ActivityStatusSuccess, models.ActivityStatusFailed, models.ActivityStatusCancelled:+ case activitytypes.StatusSuccess, activitytypes.StatusFailed, activitytypes.StatusCancelled:return nil, ErrActivityNotCancelable- case models.ActivityStatusQueued, models.ActivityStatusRunning:+ case activitytypes.StatusQueued, activitytypes.StatusRunning:// Active states — cancellation can proceed.}@@ -807,7 +806,7 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, act}writeCtx := utils.ActivityRuntimeContext(ctx, nil)if _, err := s.AppendMessage(writeCtx, activityID, AppendActivityMessageRequest{- Level: models.ActivityMessageLevelWarning,+ Level: activitytypes.MessageLevelWarning,Message: "Cancellation requested by " + requestedBy,}); err != nil {slog.DebugContext(ctx, "failed to append cancellation message", "activityId", activityID, "error", err)@@ -825,14 +824,14 @@ func (s *ActivityService) CancelActivity(ctx context.Context, environmentID, act// runner): finalize directly, but only if it is still active to avoid// clobbering a concurrently-completing activity.now := time.Now()- var finalized models.Activity+ var finalized Activityif err := s.db.WithContext(writeCtx).Transaction(func(tx *gorm.DB) error {if err := tx.First(&finalized, "id = ? AND environment_id = ?", activityID, environmentID).Error; err != nil {return err}- updates := completeActivityUpdatesInternal(finalized.StartedAt, models.ActivityStatusCancelled, cancelledMessageInternal, nil, nil, now)- result := tx.Model(&models.Activity{}).- Where("id = ? AND status IN ?", activityID, []models.ActivityStatus{models.ActivityStatusQueued, models.ActivityStatusRunning}).+ updates := completeActivityUpdatesInternal(finalized.StartedAt, activitytypes.StatusCancelled, cancelledMessageInternal, nil, nil, now)+ result := tx.Model(&Activity{}).+ Where("id = ? AND status IN ?", activityID, []activitytypes.Status{activitytypes.StatusQueued, activitytypes.StatusRunning}).Updates(updates)if result.Error != nil {return errors.WrapIf(result.Error, "failed to cancel activity")@@ -863,9 +862,9 @@ func (s *ActivityService) FailStaleImageUpdateChecks(ctx context.Context) (int64}cutoff := time.Now().Add(-staleImageUpdateCheckAge)- var staleChecks []models.Activity+ var staleChecks []Activityif err := s.db.WithContext(ctx).- Where("type = ? AND status = ? AND started_at < ?", models.ActivityTypeImageUpdateCheck, models.ActivityStatusRunning, cutoff).+ Where("type = ? AND status = ? AND started_at < ?", activitytypes.TypeImageUpdateCheck, activitytypes.StatusRunning, cutoff).Find(&staleChecks).Error; err != nil {return 0, errors.WrapIf(err, "find stale image update checks")}@@ -875,7 +874,7 @@ func (s *ActivityService) FailStaleImageUpdateChecks(ctx context.Context) (int64var failed int64var failErrs []errorfor i := range staleChecks {- if _, err := s.CompleteActivity(ctx, staleChecks[i].ID, models.ActivityStatusFailed, message, &errMessage, "Image update check failed"); err != nil {+ if _, err := s.CompleteActivity(ctx, staleChecks[i].ID, activitytypes.StatusFailed, message, &errMessage, "Image update check failed"); err != nil {failErrs = append(failErrs, errors.WrapIff(err, "fail stale image update check %s", staleChecks[i].ID))continue}@@ -912,8 +911,8 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, e}cutoff := time.Now().Add(-abandonedActivityGrace)- activeStatuses := []models.ActivityStatus{models.ActivityStatusQueued, models.ActivityStatusRunning}- var candidates []models.Activity+ activeStatuses := []activitytypes.Status{activitytypes.StatusQueued, activitytypes.StatusRunning}+ var candidates []Activityif err := s.db.WithContext(ctx).Where("status IN ? AND started_at < ?", activeStatuses, cutoff).Find(&candidates).Error; err != nil {@@ -931,11 +930,11 @@ func (s *ActivityService) FailAbandonedActivities(ctx context.Context) (int64, e}now := time.Now()- var finalized models.Activity+ var finalized ActivitylostRace := falseif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- updates := completeActivityUpdatesInternal(candidates[i].StartedAt, models.ActivityStatusFailed, message, &errMessage, nil, now)- result := tx.Model(&models.Activity{}).+ updates := completeActivityUpdatesInternal(candidates[i].StartedAt, activitytypes.StatusFailed, message, &errMessage, nil, now)+ result := tx.Model(&Activity{}).Where("id = ? AND status IN ?", activityID, activeStatuses).Updates(updates)if result.Error != nil {@@ -973,9 +972,9 @@ func (s *ActivityService) ResolveOrphanedQueuedActivities(ctx context.Context) (return 0, nil}- var queued []models.Activity+ var queued []Activityif err := s.db.WithContext(ctx).- Where("status = ?", models.ActivityStatusQueued).+ Where("status = ?", activitytypes.StatusQueued).Find(&queued).Error; err != nil {return 0, errors.WrapIf(err, "find orphaned queued activities")}@@ -985,7 +984,7 @@ func (s *ActivityService) ResolveOrphanedQueuedActivities(ctx context.Context) (var failed int64var failErrs []errorfor i := range queued {- if _, err := s.CompleteActivity(ctx, queued[i].ID, models.ActivityStatusFailed, message, &errMessage); err != nil {+ if _, err := s.CompleteActivity(ctx, queued[i].ID, activitytypes.StatusFailed, message, &errMessage); err != nil {failErrs = append(failErrs, errors.WrapIff(err, "fail orphaned queued activity %s", queued[i].ID))continue}@@ -997,7 +996,7 @@ func (s *ActivityService) ResolveOrphanedQueuedActivities(ctx context.Context) (// PatchActivityMetadata merges patch into the activity's existing metadata,// unlike UpdateActivity which replaces the metadata wholesale.-func (s *ActivityService) PatchActivityMetadata(ctx context.Context, activityID string, patch models.JSON) error {+func (s *ActivityService) PatchActivityMetadata(ctx context.Context, activityID string, patch database.JSON) error {if err := s.checkInitInternal(); err != nil {return err}@@ -1010,16 +1009,16 @@ func (s *ActivityService) PatchActivityMetadata(ctx context.Context, activityID}return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var activity models.Activity+ var activity Activityif err := tx.First(&activity, "id = ?", activityID).Error; err != nil {return errors.WrapIf(err, "failed to load activity")}merged := cloneJSONInternal(activity.Metadata)if merged == nil {- merged = models.JSON{}+ merged = database.JSON{}}maps.Copy(merged, patch)- if err := tx.Model(&models.Activity{}).Where("id = ?", activityID).+ if err := tx.Model(&Activity{}).Where("id = ?", activityID).Updates(map[string]any{"metadata": merged, "updated_at": time.Now()}).Error; err != nil {return errors.WrapIf(err, "failed to patch activity metadata")}@@ -1036,9 +1035,9 @@ func (s *ActivityService) ResolveStaleAutoUpdateActivities(ctx context.Context)return 0, nil}- var stale []models.Activity+ var stale []Activityif err := s.db.WithContext(ctx).- Where("type = ? AND status = ?", models.ActivityTypeAutoUpdate, models.ActivityStatusRunning).+ Where("type = ? AND status = ?", activitytypes.TypeAutoUpdate, activitytypes.StatusRunning).Find(&stale).Error; err != nil {return 0, errors.WrapIf(err, "find stale auto-update activities")}@@ -1046,11 +1045,11 @@ func (s *ActivityService) ResolveStaleAutoUpdateActivities(ctx context.Context)var resolved int64var resolveErrs []errorfor i := range stale {- status := models.ActivityStatusFailed+ status := activitytypes.StatusFailedmessage := "Auto-update interrupted by Arcane restart"var errMessage *stringif selfUpdate, _ := stale[i].Metadata["selfUpdateTriggered"].(bool); selfUpdate {- status = models.ActivityStatusSuccess+ status = activitytypes.StatusSuccessmessage = "Auto-update completed — Arcane restarted with the updated image"} else {errMessage = new(message)@@ -1065,7 +1064,7 @@ func (s *ActivityService) ResolveStaleAutoUpdateActivities(ctx context.Context)return resolved, stderrors.Join(resolveErrs...)}-func completeActivityUpdatesInternal(startedAt time.Time, status models.ActivityStatus, finalMessage string, errMessage *string, finalStep []string, now time.Time) map[string]any {+func completeActivityUpdatesInternal(startedAt time.Time, status activitytypes.Status, finalMessage string, errMessage *string, finalStep []string, now time.Time) map[string]any {updates := map[string]any{"status": status,"ended_at": now,@@ -1083,7 +1082,7 @@ func completeActivityUpdatesInternal(startedAt time.Time, status models.Activityif errMessage != nil && strings.TrimSpace(*errMessage) != "" {updates["error"] = strings.TrimSpace(*errMessage)}- if status == models.ActivityStatusSuccess {+ if status == activitytypes.StatusSuccess {updates["progress"] = 100}return updates@@ -1099,8 +1098,8 @@ func (s *ActivityService) ListActivitiesPaginated(ctx context.Context, environmeenvironmentID = "0"}- var activities []models.Activity- q := s.db.WithContext(ctx).Model(&models.Activity{}).Where("environment_id = ?", environmentID)+ var activities []Activity+ q := s.db.WithContext(ctx).Model(&Activity{}).Where("environment_id = ?", environmentID)if term := strings.TrimSpace(params.Search); term != "" {escaped := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(term)@@ -1144,14 +1143,14 @@ func (s *ActivityService) GetActivityDetail(ctx context.Context, environmentID,limit = defaultActivityMessages}- var model models.Activity+ var model Activityif err := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", activityID, environmentID).First(&model).Error; err != nil {return nil, errors.WrapIf(err, "failed to load activity")}- var messages []models.ActivityMessage+ var messages []ActivityMessageif err := s.db.WithContext(ctx).Where("activity_id = ?", activityID).Order("created_at DESC").@@ -1383,7 +1382,7 @@ func (s *ActivityService) publishInternal(environmentID string, event activityty}}-func activityToDTOInternal(model *models.Activity) activitytypes.Activity {+func activityToDTOInternal(model *Activity) activitytypes.Activity {if model == nil {return activitytypes.Activity{}}@@ -1392,8 +1391,8 @@ func activityToDTOInternal(model *models.Activity) activitytypes.Activity {EnvironmentID: model.EnvironmentID,SourceEnvironmentID: model.EnvironmentID,BatchID: copyPtrInternal(model.BatchID),- Type: activitytypes.Type(model.Type),- Status: activitytypes.Status(model.Status),+ Type: model.Type,+ Status: model.Status,ResourceType: copyPtrInternal(model.ResourceType),ResourceID: copyPtrInternal(model.ResourceID),ResourceName: copyPtrInternal(model.ResourceName),@@ -1411,14 +1410,14 @@ func activityToDTOInternal(model *models.Activity) activitytypes.Activity {}}-func activityMessageToDTOInternal(model *models.ActivityMessage) activitytypes.Message {+func activityMessageToDTOInternal(model *ActivityMessage) activitytypes.Message {if model == nil {return activitytypes.Message{}}return activitytypes.Message{ID: model.ID,ActivityID: model.ActivityID,- Level: activitytypes.MessageLevel(model.Level),+ Level: model.Level,Message: model.Message,Payload: jsonToMapInternal(model.Payload),CreatedAt: model.CreatedAt,@@ -1439,16 +1438,16 @@ func clampProgressPtrInternal(value *int) *int {return new(min(max(*value, 0), 100))}-func cloneJSONInternal(input models.JSON) models.JSON {+func cloneJSONInternal(input database.JSON) database.JSON {if len(input) == 0 {return nil}- out := make(models.JSON, len(input))+ out := make(database.JSON, len(input))maps.Copy(out, input)return out}-func jsonToMapInternal(input models.JSON) map[string]any {+func jsonToMapInternal(input database.JSON) map[string]any {if len(input) == 0 {return nil}@@ -1457,17 +1456,17 @@ func jsonToMapInternal(input models.JSON) map[string]any {return out}-func terminalActivityStatusesInternal() []models.ActivityStatus {- return []models.ActivityStatus{- models.ActivityStatusSuccess,- models.ActivityStatusFailed,- models.ActivityStatusCancelled,+func terminalActivityStatusesInternal() []activitytypes.Status {+ return []activitytypes.Status{+ activitytypes.StatusSuccess,+ activitytypes.StatusFailed,+ activitytypes.StatusCancelled,}}func findTerminalActivityIDsInternal(q *gorm.DB) ([]string, error) {var activityIDs []string- if err := q.Model(&models.Activity{}).+ if err := q.Model(&Activity{}).Where("status IN ?", terminalActivityStatusesInternal()).Pluck("id", &activityIDs).Error; err != nil {return nil, err@@ -1507,10 +1506,10 @@ func deleteActivitiesByIDInternal(tx *gorm.DB, activityIDs []string) (int64, errend := min(i+deleteActivitiesBatchSize, len(activityIDs))batch := activityIDs[i:end]- if err := tx.Where("activity_id IN ?", batch).Delete(&models.ActivityMessage{}).Error; err != nil {+ if err := tx.Where("activity_id IN ?", batch).Delete(&ActivityMessage{}).Error; err != nil {return totalDeleted, errors.WrapIf(err, "failed to delete activity messages")}- result := tx.Where("id IN ?", batch).Delete(&models.Activity{})+ result := tx.Where("id IN ?", batch).Delete(&Activity{})if result.Error != nil {return totalDeleted, errors.WrapIf(result.Error, "failed to delete activities")}@@ -1520,7 +1519,7 @@ func deleteActivitiesByIDInternal(tx *gorm.DB, activityIDs []string) (int64, errreturn totalDeleted, nil}-func activityStartedByDTOInternal(model *models.Activity) *activitytypes.StartedBy {+func activityStartedByDTOInternal(model *Activity) *activitytypes.StartedBy {if model.StartedByUsername == nil || strings.TrimSpace(*model.StartedByUsername) == "" {return &activitytypes.StartedBy{Username: "System"}}diff --git a/backend/internal/activity/service_test.go b/backend/internal/activity/service_test.goindex 1ba8cf964..6d44d33c9 100644--- a/backend/internal/activity/service_test.go+++ b/backend/internal/activity/service_test.go@@ -1,6 +1,8 @@package activityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""testing""time"@@ -12,7 +14,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -25,7 +26,7 @@ func setupActivityServiceTestDBInternal(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Activity{}, &models.ActivityMessage{}))+ require.NoError(t, db.AutoMigrate(&Activity{}, &ActivityMessage{}))return &database.DB{DB: db}}@@ -35,14 +36,14 @@ func TestActivityServiceLifecycleInternal(t *testing.T) {service := NewActivityService(db, nil)progress := 5- startedBy := &models.User{- BaseModel: models.BaseModel{ID: "user-1"},+ startedBy := &common.User{+ BaseModel: database.BaseModel{ID: "user-1"},Username: "arcane",DisplayName: new("Arcane Admin"),}created, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImagePull,+ Type: activitytypes.TypeImagePull,ResourceType: new("image"),ResourceID: new("img-123"),ResourceName: new("nginx:latest"),@@ -63,7 +64,7 @@ func TestActivityServiceLifecycleInternal(t *testing.T) {progress = 42message, err := service.AppendMessage(ctx, created.ID, AppendActivityMessageRequest{- Level: models.ActivityMessageLevelInfo,+ Level: activitytypes.MessageLevelInfo,Message: "Downloading layers",Progress: &progress,Step: "download",@@ -72,7 +73,7 @@ func TestActivityServiceLifecycleInternal(t *testing.T) {require.NotNil(t, message)require.Equal(t, created.ID, message.ActivityID)- completed, err := service.CompleteActivity(ctx, created.ID, models.ActivityStatusSuccess, "Pull complete", nil)+ completed, err := service.CompleteActivity(ctx, created.ID, activitytypes.StatusSuccess, "Pull complete", nil)require.NoError(t, err)require.Equal(t, "success", string(completed.Status))require.NotNil(t, completed.EndedAt)@@ -105,7 +106,7 @@ func TestActivityServiceStreamFanoutInternal(t *testing.T) {created, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeProjectDeploy,+ Type: activitytypes.TypeProjectDeploy,LatestMessage: "Deploy queued",})require.NoError(t, err)@@ -116,7 +117,7 @@ func TestActivityServiceStreamFanoutInternal(t *testing.T) {require.NotNil(t, first.Activity)_, err = service.AppendMessage(ctx, created.ID, AppendActivityMessageRequest{- Level: models.ActivityMessageLevelInfo,+ Level: activitytypes.MessageLevelInfo,Message: "Deploying services",Step: "deploy",})@@ -136,7 +137,7 @@ func TestActivityServiceRetentionCleanupInternal(t *testing.T) {created, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeSystemPrune,+ Type: activitytypes.TypeSystemPrune,LatestMessage: "Prune started",})require.NoError(t, err)@@ -144,22 +145,22 @@ func TestActivityServiceRetentionCleanupInternal(t *testing.T) {Message: "Removing unused resources",})require.NoError(t, err)- _, err = service.CompleteActivity(ctx, created.ID, models.ActivityStatusSuccess, "Prune complete", nil)+ _, err = service.CompleteActivity(ctx, created.ID, activitytypes.StatusSuccess, "Prune complete", nil)require.NoError(t, err)oldEndedAt := time.Now().Add(-((time.Duration(defaultActivityRetentionDays) * 24 * time.Hour) + time.Hour))- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", created.ID).Update("ended_at", oldEndedAt).Error)+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", created.ID).Update("ended_at", oldEndedAt).Error)deleted, err := service.PruneHistory(ctx, defaultActivityRetentionDays, 0)require.NoError(t, err)require.EqualValues(t, 1, deleted)var activityCount int64- require.NoError(t, db.Model(&models.Activity{}).Count(&activityCount).Error)+ require.NoError(t, db.Model(&Activity{}).Count(&activityCount).Error)require.Zero(t, activityCount)var messageCount int64- require.NoError(t, db.Model(&models.ActivityMessage{}).Count(&messageCount).Error)+ require.NoError(t, db.Model(&ActivityMessage{}).Count(&messageCount).Error)require.Zero(t, messageCount)}@@ -170,22 +171,22 @@ func TestActivityServicePruneHistoryZeroRetentionDisablesAgeCleanupInternal(t *tcreated, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeSystemPrune,+ Type: activitytypes.TypeSystemPrune,LatestMessage: "Prune started",})require.NoError(t, err)- _, err = service.CompleteActivity(ctx, created.ID, models.ActivityStatusSuccess, "Prune complete", nil)+ _, err = service.CompleteActivity(ctx, created.ID, activitytypes.StatusSuccess, "Prune complete", nil)require.NoError(t, err)oldEndedAt := time.Now().Add(-((time.Duration(defaultActivityRetentionDays) * 24 * time.Hour) + time.Hour))- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", created.ID).Update("ended_at", oldEndedAt).Error)+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", created.ID).Update("ended_at", oldEndedAt).Error)deleted, err := service.PruneHistory(ctx, 0, 0)require.NoError(t, err)require.Zero(t, deleted)var activityCount int64- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", created.ID).Count(&activityCount).Error)+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", created.ID).Count(&activityCount).Error)require.EqualValues(t, 1, activityCount)}@@ -211,26 +212,26 @@ func TestActivityServiceDeleteHistoryPreservesActiveActivitiesInternal(t *testindb := setupActivityServiceTestDBInternal(t)service := NewActivityService(db, nil)- completed, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeResourceAction})+ completed, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeResourceAction})require.NoError(t, err)_, err = service.AppendMessage(ctx, completed.ID, AppendActivityMessageRequest{Message: "done"})require.NoError(t, err)- _, err = service.CompleteActivity(ctx, completed.ID, models.ActivityStatusSuccess, "complete", nil)+ _, err = service.CompleteActivity(ctx, completed.ID, activitytypes.StatusSuccess, "complete", nil)require.NoError(t, err)- running, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeResourceAction})+ running, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeResourceAction})require.NoError(t, err)- remoteCompleted, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "remote-1", Type: models.ActivityTypeResourceAction})+ remoteCompleted, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "remote-1", Type: activitytypes.TypeResourceAction})require.NoError(t, err)- _, err = service.CompleteActivity(ctx, remoteCompleted.ID, models.ActivityStatusFailed, "failed", nil)+ _, err = service.CompleteActivity(ctx, remoteCompleted.ID, activitytypes.StatusFailed, "failed", nil)require.NoError(t, err)deleted, err := service.DeleteHistory(ctx, "0")require.NoError(t, err)require.EqualValues(t, 1, deleted)- var remaining []models.Activity+ var remaining []Activityrequire.NoError(t, db.Order("id").Find(&remaining).Error)require.Len(t, remaining, 2)require.ElementsMatch(t, []string{running.ID, remoteCompleted.ID}, []string{remaining[0].ID, remaining[1].ID})@@ -241,29 +242,29 @@ func TestActivityServicePruneHistoryByAgeAndCountInternal(t *testing.T) {db := setupActivityServiceTestDBInternal(t)service := NewActivityService(db, nil)- oldActivity, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeResourceAction})+ oldActivity, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeResourceAction})require.NoError(t, err)- _, err = service.CompleteActivity(ctx, oldActivity.ID, models.ActivityStatusSuccess, "old", nil)+ _, err = service.CompleteActivity(ctx, oldActivity.ID, activitytypes.StatusSuccess, "old", nil)require.NoError(t, err)oldTime := time.Now().Add(-48 * time.Hour)- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", oldActivity.ID).Updates(map[string]any{+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", oldActivity.ID).Updates(map[string]any{"ended_at": oldTime,"updated_at": oldTime,}).Error)for i := range 3 {- item, startErr := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "remote-1", Type: models.ActivityTypeResourceAction})+ item, startErr := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "remote-1", Type: activitytypes.TypeResourceAction})require.NoError(t, startErr)- _, completeErr := service.CompleteActivity(ctx, item.ID, models.ActivityStatusSuccess, "done", nil)+ _, completeErr := service.CompleteActivity(ctx, item.ID, activitytypes.StatusSuccess, "done", nil)require.NoError(t, completeErr)stamp := time.Now().Add(time.Duration(i) * time.Minute)- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", item.ID).Updates(map[string]any{+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", item.ID).Updates(map[string]any{"ended_at": stamp,"updated_at": stamp,}).Error)}- running, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "remote-1", Type: models.ActivityTypeResourceAction})+ running, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "remote-1", Type: activitytypes.TypeResourceAction})require.NoError(t, err)deleted, err := service.PruneHistory(ctx, 1, 2)@@ -271,17 +272,17 @@ func TestActivityServicePruneHistoryByAgeAndCountInternal(t *testing.T) {require.EqualValues(t, 2, deleted)var terminalRemoteCount int64- require.NoError(t, db.Model(&models.Activity{}).+ require.NoError(t, db.Model(&Activity{}).Where("environment_id = ? AND status IN ?", "remote-1", terminalActivityStatusesInternal()).Count(&terminalRemoteCount).Error)require.EqualValues(t, 2, terminalRemoteCount)var runningCount int64- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", running.ID).Count(&runningCount).Error)+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", running.ID).Count(&runningCount).Error)require.EqualValues(t, 1, runningCount)var oldCount int64- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", oldActivity.ID).Count(&oldCount).Error)+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", oldActivity.ID).Count(&oldCount).Error)require.Zero(t, oldCount)}@@ -328,16 +329,16 @@ func TestActivityServiceListOrderStableUnderProgressUpdatesInternal(t *testing.Tdb := setupActivityServiceTestDBInternal(t)service := NewActivityService(db, nil)- older, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull})+ older, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull})require.NoError(t, err)- newer, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull})+ newer, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull})require.NoError(t, err)- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", older.ID).+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", older.ID).Update("created_at", time.Now().Add(-time.Minute)).Error)- terminal, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull})+ terminal, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull})require.NoError(t, err)- _, err = service.CompleteActivity(ctx, terminal.ID, models.ActivityStatusSuccess, "done", nil)+ _, err = service.CompleteActivity(ctx, terminal.ID, activitytypes.StatusSuccess, "done", nil)require.NoError(t, err)listIDs := func() []string {@@ -367,7 +368,7 @@ func setupQueuedActivityServiceInternal(t *testing.T) (*ActivityService, contextdb, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Activity{}, &models.ActivityMessage{}, &models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&Activity{}, &ActivityMessage{}, &settings.SettingVariable{}))wrapped := &database.DB{DB: db}// Every extra pooled connection to a :memory: SQLite database is a fresh@@ -404,11 +405,11 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *dafunc TestActivityServiceQueuedActivityFlipsToRunningWhenSlotFreesInternal(t *testing.T) {service, ctx := setupQueuedActivityServiceInternal(t)- first, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})+ first, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true})require.NoError(t, err)require.Equal(t, "running", string(first.Status))- second, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})+ second, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true})require.NoError(t, err)require.Equal(t, "queued", string(second.Status))@@ -421,7 +422,7 @@ func TestActivityServiceQueuedActivityFlipsToRunningWhenSlotFreesInternal(t *tescase <-time.After(100 * time.Millisecond):}- _, err = service.CompleteActivity(ctx, first.ID, models.ActivityStatusSuccess, "done", nil)+ _, err = service.CompleteActivity(ctx, first.ID, activitytypes.StatusSuccess, "done", nil)require.NoError(t, err)select {@@ -431,18 +432,18 @@ func TestActivityServiceQueuedActivityFlipsToRunningWhenSlotFreesInternal(t *tesrequire.FailNow(t, "await did not acquire the freed slot")}- var model models.Activity+ var model Activityrequire.NoError(t, service.db.First(&model, "id = ?", second.ID).Error)- require.Equal(t, models.ActivityStatusRunning, model.Status)+ require.Equal(t, activitytypes.StatusRunning, model.Status)}func TestActivityServiceLimitIncreaseKeepsCountingActiveSlotsInternal(t *testing.T) {service, ctx := setupQueuedActivityServiceInternal(t)- running, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})+ running, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true})require.NoError(t, err)require.Equal(t, "running", string(running.Status))- waiting, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})+ waiting, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true})require.NoError(t, err)require.Equal(t, "queued", string(waiting.Status))@@ -460,7 +461,7 @@ func TestActivityServiceLimitIncreaseKeepsCountingActiveSlotsInternal(t *testingrequire.FailNow(t, "waiter was not admitted after the limit increase")}- third, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})+ third, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true})require.NoError(t, err)require.Equal(t, "queued", string(third.Status))}@@ -468,9 +469,9 @@ func TestActivityServiceLimitIncreaseKeepsCountingActiveSlotsInternal(t *testingfunc TestActivityServiceCancelWhileQueuedUnblocksAwaitInternal(t *testing.T) {service, ctx := setupQueuedActivityServiceInternal(t)- _, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})+ _, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true})require.NoError(t, err)- queued, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: models.ActivityTypeImagePull, Queue: true})+ queued, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0", Type: activitytypes.TypeImagePull, Queue: true})require.NoError(t, err)require.Equal(t, "queued", string(queued.Status))@@ -490,7 +491,7 @@ func TestActivityServiceCancelWhileQueuedUnblocksAwaitInternal(t *testing.T) {func TestActivityServiceCompleteActivityRejectsUninitializedServiceInternal(t *testing.T) {service := NewActivityService(nil, nil)- _, err := service.CompleteActivity(context.Background(), "any-id", models.ActivityStatusSuccess, "done", nil)+ _, err := service.CompleteActivity(context.Background(), "any-id", activitytypes.StatusSuccess, "done", nil)require.Error(t, err)}@@ -504,7 +505,7 @@ func TestActivityServiceTrackAndRequestCancelInternal(t *testing.T) {created, err := service.StartActivity(runtimeCtx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImagePull,+ Type: activitytypes.TypeImagePull,LatestMessage: "running",})require.NoError(t, err)@@ -520,7 +521,7 @@ func TestActivityServiceTrackAndRequestCancelInternal(t *testing.T) {// Completion must land even though the work context is cancelled (this is the// path CompleteHandlerActivity takes after re-wrapping the work context).- completed, err := service.CompleteActivity(utils.ActivityRuntimeContext(workCtx, nil), created.ID, models.ActivityStatusCancelled, "Cancelled by user", nil)+ completed, err := service.CompleteActivity(utils.ActivityRuntimeContext(workCtx, nil), created.ID, activitytypes.StatusCancelled, "Cancelled by user", nil)require.NoError(t, err)require.Equal(t, "cancelled", string(completed.Status))require.NotNil(t, completed.EndedAt)@@ -537,7 +538,7 @@ func TestActivityServiceCancelActivityInternal(t *testing.T) {// An untracked running activity (e.g. after a restart) is finalized directly.created, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeSystemPrune,+ Type: activitytypes.TypeSystemPrune,LatestMessage: "running",})require.NoError(t, err)@@ -563,34 +564,34 @@ func TestActivityServiceFailStaleImageUpdateChecksInternal(t *testing.T) {staleCheck, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImageUpdateCheck,+ Type: activitytypes.TypeImageUpdateCheck,LatestMessage: "checking",})require.NoError(t, err)freshCheck, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImageUpdateCheck,+ Type: activitytypes.TypeImageUpdateCheck,LatestMessage: "checking",})require.NoError(t, err)staleOtherType, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImagePull,+ Type: activitytypes.TypeImagePull,LatestMessage: "pulling",})require.NoError(t, err)completedCheck, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImageUpdateCheck,+ Type: activitytypes.TypeImageUpdateCheck,LatestMessage: "checking",})require.NoError(t, err)- _, err = service.CompleteActivity(ctx, completedCheck.ID, models.ActivityStatusSuccess, "complete", nil)+ _, err = service.CompleteActivity(ctx, completedCheck.ID, activitytypes.StatusSuccess, "complete", nil)require.NoError(t, err)oldStartedAt := time.Now().Add(-7 * time.Hour)for _, id := range []string{staleCheck.ID, staleOtherType.ID, completedCheck.ID} {- require.NoError(t, db.Model(&models.Activity{}).Where("id = ?", id).Updates(map[string]any{+ require.NoError(t, db.Model(&Activity{}).Where("id = ?", id).Updates(map[string]any{"started_at": oldStartedAt,"updated_at": oldStartedAt,}).Error)@@ -600,28 +601,28 @@ func TestActivityServiceFailStaleImageUpdateChecksInternal(t *testing.T) {require.NoError(t, err)require.EqualValues(t, 1, failed)- var stale models.Activity+ var stale Activityrequire.NoError(t, db.First(&stale, "id = ?", staleCheck.ID).Error)- require.Equal(t, models.ActivityStatusFailed, stale.Status)+ require.Equal(t, activitytypes.StatusFailed, stale.Status)require.NotNil(t, stale.EndedAt)require.NotNil(t, stale.DurationMs)require.Contains(t, stale.LatestMessage, "stale")require.NotNil(t, stale.Error)require.Contains(t, *stale.Error, "stale")- var fresh models.Activity+ var fresh Activityrequire.NoError(t, db.First(&fresh, "id = ?", freshCheck.ID).Error)- require.Equal(t, models.ActivityStatusRunning, fresh.Status)+ require.Equal(t, activitytypes.StatusRunning, fresh.Status)require.Nil(t, fresh.EndedAt)- var other models.Activity+ var other Activityrequire.NoError(t, db.First(&other, "id = ?", staleOtherType.ID).Error)- require.Equal(t, models.ActivityStatusRunning, other.Status)+ require.Equal(t, activitytypes.StatusRunning, other.Status)require.Nil(t, other.EndedAt)- var completed models.Activity+ var completed Activityrequire.NoError(t, db.First(&completed, "id = ?", completedCheck.ID).Error)- require.Equal(t, models.ActivityStatusSuccess, completed.Status)+ require.Equal(t, activitytypes.StatusSuccess, completed.Status)}func TestActivityServiceFailAbandonedActivitiesInternal(t *testing.T) {@@ -631,25 +632,25 @@ func TestActivityServiceFailAbandonedActivitiesInternal(t *testing.T) {abandoned, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImageUpdateCheck,+ Type: activitytypes.TypeImageUpdateCheck,LatestMessage: "checking",})require.NoError(t, err)tracked, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeAutoUpdate,+ Type: activitytypes.TypeAutoUpdate,LatestMessage: "updating",})require.NoError(t, err)fresh, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImageUpdateCheck,+ Type: activitytypes.TypeImageUpdateCheck,LatestMessage: "checking",})require.NoError(t, err)backdated := time.Now().Add(-10 * time.Minute)- require.NoError(t, db.Model(&models.Activity{}).+ require.NoError(t, db.Model(&Activity{}).Where("id IN ?", []string{abandoned.ID, tracked.ID}).Update("started_at", backdated).Error)_ = service.Track(ctx, tracked.ID)@@ -658,19 +659,19 @@ func TestActivityServiceFailAbandonedActivitiesInternal(t *testing.T) {require.NoError(t, err)require.EqualValues(t, 1, swept)- var abandonedRow models.Activity+ var abandonedRow Activityrequire.NoError(t, db.First(&abandonedRow, "id = ?", abandoned.ID).Error)- require.Equal(t, models.ActivityStatusFailed, abandonedRow.Status)+ require.Equal(t, activitytypes.StatusFailed, abandonedRow.Status)require.NotNil(t, abandonedRow.EndedAt)require.Contains(t, abandonedRow.LatestMessage, "worker is no longer running")- var trackedRow models.Activity+ var trackedRow Activityrequire.NoError(t, db.First(&trackedRow, "id = ?", tracked.ID).Error)- require.Equal(t, models.ActivityStatusRunning, trackedRow.Status)+ require.Equal(t, activitytypes.StatusRunning, trackedRow.Status)- var freshRow models.Activity+ var freshRow Activityrequire.NoError(t, db.First(&freshRow, "id = ?", fresh.ID).Error)- require.Equal(t, models.ActivityStatusRunning, freshRow.Status)+ require.Equal(t, activitytypes.StatusRunning, freshRow.Status)}func TestActivityServiceResolveStaleAutoUpdateActivitiesInternal(t *testing.T) {@@ -680,22 +681,22 @@ func TestActivityServiceResolveStaleAutoUpdateActivitiesInternal(t *testing.T) {selfUpdateRun, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeAutoUpdate,+ Type: activitytypes.TypeAutoUpdate,LatestMessage: "updating",- Metadata: models.JSON{"dryRun": false},+ Metadata: database.JSON{"dryRun": false},})require.NoError(t, err)- require.NoError(t, service.PatchActivityMetadata(ctx, selfUpdateRun.ID, models.JSON{"selfUpdateTriggered": true}))+ require.NoError(t, service.PatchActivityMetadata(ctx, selfUpdateRun.ID, database.JSON{"selfUpdateTriggered": true}))interruptedRun, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeAutoUpdate,+ Type: activitytypes.TypeAutoUpdate,LatestMessage: "updating",})require.NoError(t, err)otherType, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImagePull,+ Type: activitytypes.TypeImagePull,LatestMessage: "pulling",})require.NoError(t, err)@@ -704,21 +705,21 @@ func TestActivityServiceResolveStaleAutoUpdateActivitiesInternal(t *testing.T) {require.NoError(t, err)require.EqualValues(t, 2, resolved)- var selfUpdated models.Activity+ var selfUpdated Activityrequire.NoError(t, db.First(&selfUpdated, "id = ?", selfUpdateRun.ID).Error)- require.Equal(t, models.ActivityStatusSuccess, selfUpdated.Status)+ require.Equal(t, activitytypes.StatusSuccess, selfUpdated.Status)require.NotNil(t, selfUpdated.EndedAt)require.Contains(t, selfUpdated.LatestMessage, "restarted with the updated image")require.Equal(t, false, selfUpdated.Metadata["dryRun"])- var interrupted models.Activity+ var interrupted Activityrequire.NoError(t, db.First(&interrupted, "id = ?", interruptedRun.ID).Error)- require.Equal(t, models.ActivityStatusFailed, interrupted.Status)+ require.Equal(t, activitytypes.StatusFailed, interrupted.Status)require.Contains(t, interrupted.LatestMessage, "interrupted")- var other models.Activity+ var other Activityrequire.NoError(t, db.First(&other, "id = ?", otherType.ID).Error)- require.Equal(t, models.ActivityStatusRunning, other.Status)+ require.Equal(t, activitytypes.StatusRunning, other.Status)}func receiveActivityEventInternal(t *testing.T, events <-chan activitytypes.StreamEvent) activitytypes.StreamEvent {@@ -743,7 +744,7 @@ func TestActivityServiceAppendMessagesBatchInternal(t *testing.T) {created, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImagePull,+ Type: activitytypes.TypeImagePull,Step: "queued",LatestMessage: "Pull queued",})@@ -792,7 +793,7 @@ func TestActivityServiceDropsStaleSnapshotAfterTerminalPublishInternal(t *testincreated, err := service.StartActivity(ctx, StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImagePull,+ Type: activitytypes.TypeImagePull,LatestMessage: "Pull queued",})require.NoError(t, err)@@ -801,7 +802,7 @@ func TestActivityServiceDropsStaleSnapshotAfterTerminalPublishInternal(t *testinevents, _, unsubscribe := service.Subscribe("0")defer unsubscribe()- completed, err := service.CompleteActivity(ctx, created.ID, models.ActivityStatusSuccess, "", nil)+ completed, err := service.CompleteActivity(ctx, created.ID, activitytypes.StatusSuccess, "", nil)require.NoError(t, err)require.Equal(t, activitytypes.StatusSuccess, completed.Status)diff --git a/backend/internal/apikey/model.go b/backend/internal/apikey/model.gonew file mode 100644index 000000000..7e03a3053--- /dev/null+++ b/backend/internal/apikey/model.go@@ -0,0 +1,36 @@+package apikey++import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/role"++ "time"+)++const (+ // ApiKeyKindScoped keys carry their own permission grant rows.+ ApiKeyKindScoped = "scoped"+ // ApiKeyKindPersonal keys have no grants; they inherit the owner's role+ // permissions at authentication time.+ ApiKeyKindPersonal = "personal"+)++type ApiKey struct {+ database.BaseModel++ Name string `json:"name" gorm:"column:name;not null" sortable:"true"`+ Description *string `json:"description,omitempty" gorm:"column:description"`+ KeyHash string `json:"-" gorm:"column:key_hash;not null"`+ KeyPrefix string `json:"keyPrefix" gorm:"column:key_prefix;not null"`+ ManagedBy *string `json:"-" gorm:"column:managed_by"`+ Kind string `json:"kind" gorm:"column:kind;not null;default:scoped"`+ UserID *string `json:"userId,omitempty" gorm:"column:user_id"`+ EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`+ LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`+ PermissionGrants []role.ApiKeyPermission `json:"-" gorm:"foreignKey:ApiKeyID;references:ID;constraint:OnDelete:CASCADE"`+}++func (ApiKey) TableName() string {+ return "api_keys"+}diff --git a/backend/internal/apikey/service.go b/backend/internal/apikey/service.goindex 645f6f5db..20a2adeb2 100644--- a/backend/internal/apikey/service.go+++ b/backend/internal/apikey/service.go@@ -18,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -60,7 +59,7 @@ type ApiKeyService struct {// written after a full hash validation, so a hit safely skips the Argon2id// derivation. Expiry is re-checked on every hit and entries are invalidated// on key update/delete.- validatedKeyCache *hot.HotCache[string, models.ApiKey]+ validatedKeyCache *hot.HotCache[string, ApiKey]// cacheKeyPepper is a random per-process HMAC key for deriving cache keys.// Generated keys carry 256 bits of entropy, but the static admin key is// operator-provided and may be weak; the pepper keeps its in-memory digest@@ -90,7 +89,7 @@ func NewApiKeyService(db *database.DB, userService *user.UserService) *ApiKeySerdb: db,userService: userService,argon2Params: user.DefaultArgon2Params(),- validatedKeyCache: hot.NewHotCache[string, models.ApiKey](hot.LRU, 4096).+ validatedKeyCache: hot.NewHotCache[string, ApiKey](hot.LRU, 4096).WithTTL(15 * time.Second).WithJanitor().Build(),@@ -108,6 +107,107 @@ func (s *ApiKeyService) WithRoleService(roleService *role.RoleService) *ApiKeySereturn s}+// BackfillApiKeyPermissions ensures every ownerless (bootstrap) API key has+// its expected permission grants. Called once per boot.+//+// Per-key, not all-or-nothing: a single bootstrap key with zero grants is+// repaired even if other keys are already populated. This recovers env-+// bootstrap keys that pre-date the per-key permission feature, or that were+// created on a deployment where the original SetApiKeyPermissions call failed+// (e.g., the api_key_permissions table didn't exist yet).+//+// User-owned keys are deliberately skipped. A user-owned key with zero grants+// is an intentional "no access" state; rehydrating from the owner's effective+// permissions on every boot would clobber that. User keys are seeded at+// creation time by CreateApiKey instead.+func (s *ApiKeyService) BackfillApiKeyPermissions(ctx context.Context) error {+ // Bootstrap-class keys we'll repair if they have zero grants:+ // - user_id IS NULL → env-bootstrap keys.+ // - managed_by IS NOT NULL → admin-static (ADMIN_STATIC_API_KEY) keys,+ // which DO have a user_id but are infrastructure-managed and must+ // always carry full perms.+ // Regular user-created keys are deliberately excluded — empty grants on+ // those are an intentional "no access" state we must not overwrite.+ var keys []ApiKey+ if err := s.db.WithContext(ctx).Where("user_id IS NULL OR managed_by IS NOT NULL").Find(&keys).Error; err != nil {+ return errors.WrapIf(err, "failed to list bootstrap api keys for backfill")+ }+ if len(keys) == 0 {+ return nil+ }++ return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {+ for _, key := range keys {+ var existing int64+ if err := tx.Model(&role.ApiKeyPermission{}).Where("api_key_id = ?", key.ID).Count(&existing).Error; err != nil {+ return errors.WrapIff(err, "failed to count permissions for api key %s", key.ID)+ }+ if existing > 0 {+ continue+ }+ perms, err := s.backfillPermsForKeyInternal(ctx, tx, key)+ if err != nil {+ return err+ }+ for _, p := range perms {+ if err := tx.Create(&role.ApiKeyPermission{+ ApiKeyID: key.ID,+ Permission: p,+ EnvironmentID: key.EnvironmentID,+ }).Error; err != nil {+ return errors.WrapIf(err, "failed to seed api key permission")+ }+ }+ slog.InfoContext(ctx, "Backfilled missing permissions for bootstrap api key", "api_key_id", key.ID, "perm_count", len(perms), "env_id", key.EnvironmentID)+ }+ return nil+ })+}++func (s *ApiKeyService) backfillPermsForKeyInternal(ctx context.Context, tx *gorm.DB, key ApiKey) ([]string, error) {+ // Static admin bootstrap keys (no owner, no env scope) get full access.+ if key.UserID == nil && key.EnvironmentID == nil {+ return authz.AllPermissions(), nil+ }+ // Environment bootstrap keys (key bound to a specific env, no owner) get+ // full access scoped to that environment via the auth bridge — replicate+ // that by granting all permissions scoped to that environment. Org-level+ // permissions land in PerEnv[envID] and are unreachable via org-level+ // checks (which always pass envID=""), so over-granting is harmless here.+ if key.UserID == nil && key.EnvironmentID != nil {+ return authz.AllPermissions(), nil+ }+ // Otherwise inherit the owner's current effective permissions.+ var owner common.User+ if err := tx.WithContext(ctx).Where("id = ?", *key.UserID).First(&owner).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return nil, nil+ }+ return nil, errors.WrapIf(err, "failed to load api key owner")+ }+ ps, err := s.roleService.ResolveUserPermissionsInDB(ctx, tx, owner.ID)+ if err != nil {+ return nil, err+ }+ // Flatten ps into a deduplicated list of permissions for this key's scope.+ seen := make(map[string]struct{}, len(ps.Global))+ for p := range ps.Global {+ seen[p] = struct{}{}+ }+ if key.EnvironmentID != nil {+ if env, ok := ps.PerEnv[*key.EnvironmentID]; ok {+ for p := range env {+ seen[p] = struct{}{}+ }+ }+ }+ out := make([]string, 0, len(seen))+ for p := range seen {+ out = append(out, p)+ }+ return out, nil+}+func (s *ApiKeyService) generateApiKey() (string, error) {bytes := make([]byte, apiKeyLength)if _, err := rand.Read(bytes); err != nil {@@ -142,7 +242,7 @@ func (s *ApiKeyService) markApiKeyUsedInternal(ctx context.Context, keyID stringnow := time.Now()cutoff := now.Add(-apiKeyLastUsedWriteWindow)if err := s.db.WithContext(ctx).- Model(&models.ApiKey{}).+ Model(&ApiKey{}).Where("id = ? AND (last_used_at IS NULL OR last_used_at < ?)", keyID, cutoff).Update("last_used_at", now).Error; err != nil {return errors.WrapIf(err, "failed to update API key last-used timestamp")@@ -215,7 +315,7 @@ func (s *ApiKeyService) invalidateValidatedKeysInternal(ids ...string) {s.cacheFillMu.Lock()s.cacheGen.Add(1)var cacheKeys []string- s.validatedKeyCache.Range(func(key string, entry models.ApiKey) bool {+ s.validatedKeyCache.Range(func(key string, entry ApiKey) bool {if _, ok := idSet[entry.ID]; ok {cacheKeys = append(cacheKeys, key)}@@ -243,7 +343,7 @@ func (s *ApiKeyService) CreateApiKey(ctx context.Context, userID string, callerPreturn nil, err}- created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil, models.ApiKeyKindScoped)+ created, err := s.createAPIKeyWithRawKey(ctx, &userID, rawKey, req, nil, nil, ApiKeyKindScoped)if err != nil {return nil, err}@@ -309,10 +409,10 @@ func validateGrantsAgainstPermissionSetInternal(callerPerms *authz.PermissionSetreturn nil}-func toApiKeyPermissionRowsInternal(apiKeyID string, grants []apikey.PermissionGrant) []models.ApiKeyPermission {- out := make([]models.ApiKeyPermission, len(grants))+func toApiKeyPermissionRowsInternal(apiKeyID string, grants []apikey.PermissionGrant) []role.ApiKeyPermission {+ out := make([]role.ApiKeyPermission, len(grants))for i, g := range grants {- out[i] = models.ApiKeyPermission{+ out[i] = role.ApiKeyPermission{ApiKeyID: apiKeyID,Permission: g.Permission,EnvironmentID: g.EnvironmentID,@@ -334,7 +434,7 @@ func (s *ApiKeyService) CreatePersonalApiKey(ctx context.Context, userID string,Name: req.Name,Description: req.Description,ExpiresAt: req.ExpiresAt,- }, nil, nil, models.ApiKeyKindPersonal)+ }, nil, nil, ApiKeyKindPersonal)if err != nil {return nil, err}@@ -362,7 +462,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(return nil, errors.WrapIf(err, "failed to hash API key")}- ak := &models.ApiKey{+ ak := &ApiKey{Name: req.Name,Description: req.Description,KeyHash: keyHash,@@ -386,7 +486,7 @@ func (s *ApiKeyService) createAPIKeyWithRawKey(}, nil}-func isStaticAPIKeyInternal(ak models.ApiKey) bool {+func isStaticAPIKeyInternal(ak ApiKey) bool {return ak.ManagedBy != nil && *ak.ManagedBy == managedByAdminBootstrap}@@ -399,7 +499,7 @@ func isStaticAPIKeyInternal(ak models.ApiKey) bool {// still applies when the environment row itself is removed.func (s *ApiKeyService) isEnvironmentReferencedApiKeyInternal(ctx context.Context, keyID string) (bool, error) {var count int64- if err := s.db.WithContext(ctx).Model(&models.Environment{}).+ if err := s.db.WithContext(ctx).Table("environments").Where("api_key_id = ?", keyID).Count(&count).Error; err != nil {return false, errors.WrapIf(err, "failed to check environment references for API key")}@@ -411,7 +511,7 @@ func (s *ApiKeyService) isEnvironmentReferencedApiKeyInternal(ctx context.Contex// single query instead of one per row.func (s *ApiKeyService) environmentReferencedApiKeyIDsInternal(ctx context.Context) (map[string]struct{}, error) {var ids []string- if err := s.db.WithContext(ctx).Model(&models.Environment{}).+ if err := s.db.WithContext(ctx).Table("environments").Where("api_key_id IS NOT NULL").Pluck("api_key_id", &ids).Error; err != nil {return nil, errors.WrapIf(err, "failed to list environment-referenced API key ids")}@@ -422,7 +522,7 @@ func (s *ApiKeyService) environmentReferencedApiKeyIDsInternal(ctx context.Contereturn set, nil}-func toAPIKeyDTOInternal(ak *models.ApiKey, isBootstrap bool) apikey.ApiKey {+func toAPIKeyDTOInternal(ak *ApiKey, isBootstrap bool) apikey.ApiKey {return apikey.ApiKey{ID: ak.ID,Name: ak.Name,@@ -441,7 +541,7 @@ func toAPIKeyDTOInternal(ak *models.ApiKey, isBootstrap bool) apikey.ApiKey {// toAPIKeyDTOWithPermissionsInternal is like toAPIKeyDTOInternal but// additionally attaches the key's persisted permission grants.-func toAPIKeyDTOWithPermissionsInternal(ak *models.ApiKey, isBootstrap bool) apikey.ApiKey {+func toAPIKeyDTOWithPermissionsInternal(ak *ApiKey, isBootstrap bool) apikey.ApiKey {dto := toAPIKeyDTOInternal(ak, isBootstrap)dto.Permissions = make([]apikey.PermissionGrant, len(ak.PermissionGrants))for i, grant := range ak.PermissionGrants {@@ -457,10 +557,10 @@ func (s *ApiKeyService) CreateDefaultAdminAPIKey(ctx context.Context, userID, rareturn s.createAPIKeyWithRawKey(ctx, &userID, rawKey, apikey.CreateApiKey{Name: defaultAdminAPIKeyName,Description: defaultAdminAPIKeyDescription,- }, new(managedByAdminBootstrap), nil, models.ApiKeyKindScoped)+ }, new(managedByAdminBootstrap), nil, ApiKeyKindScoped)}-func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*models.User, error) {+func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*common.User, error) {adminUser, err := s.userService.GetUserByUsername(ctx, defaultAdminUsername)if err != nil {if errors.Is(err, common.ErrUserNotFound) {@@ -486,8 +586,8 @@ func (s *ApiKeyService) getDefaultAdminUser(ctx context.Context) (*models.User,return adminUser, nil}-func (s *ApiKeyService) listManagedAPIKeys(tx *gorm.DB, userID string) ([]models.ApiKey, error) {- var managedKeys []models.ApiKey+func (s *ApiKeyService) listManagedAPIKeys(tx *gorm.DB, userID string) ([]ApiKey, error) {+ var managedKeys []ApiKeyif err := tx.Where("user_id = ? AND managed_by = ?", userID, managedByAdminBootstrap).Order("created_at asc, id asc").Find(&managedKeys).Error; err != nil {@@ -501,13 +601,13 @@ func (s *ApiKeyService) deleteManagedAPIKeysByIDs(tx *gorm.DB, ids []string) errif len(ids) == 0 {return nil}- if err := tx.Delete(&models.ApiKey{}, "id IN ?", ids).Error; err != nil {+ if err := tx.Delete(&ApiKey{}, "id IN ?", ids).Error; err != nil {return errors.WrapIf(err, "failed to delete managed API keys")}return nil}-func (s *ApiKeyService) findMatchingManagedAPIKey(rawKey string, managedKeys []models.ApiKey) int {+func (s *ApiKeyService) findMatchingManagedAPIKey(rawKey string, managedKeys []ApiKey) int {for i, managedKey := range managedKeys {if err := s.validateApiKeyHash(managedKey.KeyHash, rawKey); err == nil {return i@@ -516,7 +616,7 @@ func (s *ApiKeyService) findMatchingManagedAPIKey(rawKey string, managedKeys []mreturn -1}-func managedAPIKeyDeleteIDsInternal(managedKeys []models.ApiKey, keepIndex int) []string {+func managedAPIKeyDeleteIDsInternal(managedKeys []ApiKey, keepIndex int) []string {deleteIDs := make([]string, 0, len(managedKeys))for i, managedKey := range managedKeys {if i == keepIndex {@@ -528,7 +628,7 @@ func managedAPIKeyDeleteIDsInternal(managedKeys []models.ApiKey, keepIndex int)}func (s *ApiKeyService) updateMatchingManagedAPIKey(tx *gorm.DB, apiKeyID string) error {- if err := tx.Model(&models.ApiKey{}).+ if err := tx.Model(&ApiKey{}).Where("id = ?", apiKeyID).Updates(map[string]any{"name": defaultAdminAPIKeyName,@@ -551,7 +651,7 @@ func (s *ApiKeyService) createManagedDefaultAdminAPIKey(tx *gorm.DB, userID, rawreturn errors.WrapIf(err, "failed to hash API key")}- ak := &models.ApiKey{+ ak := &ApiKey{Name: defaultAdminAPIKeyName,Description: defaultAdminAPIKeyDescription,KeyHash: keyHash,@@ -637,7 +737,7 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environmentcreated, err := s.createAPIKeyWithRawKey(ctx, nil, rawKey, apikey.CreateApiKey{Name: name,Description: new("Auto-generated key for environment pairing"),- }, nil, &environmentID, models.ApiKeyKindScoped)+ }, nil, &environmentID, ApiKeyKindScoped)if err != nil {return nil, err}@@ -648,9 +748,9 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environment// downstream RequirePermission check fails with 403.if s.roleService != nil {all := authz.AllPermissions()- grants := make([]models.ApiKeyPermission, len(all))+ grants := make([]role.ApiKeyPermission, len(all))for i, p := range all {- grants[i] = models.ApiKeyPermission{+ grants[i] = role.ApiKeyPermission{ApiKeyID: created.ID,Permission: p,EnvironmentID: &environmentID,@@ -667,7 +767,7 @@ func (s *ApiKeyService) CreateEnvironmentApiKey(ctx context.Context, environment}func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKey, error) {- var ak models.ApiKey+ var ak ApiKeyquery := s.db.WithContext(ctx)if s.roleService != nil {query = query.Preload("PermissionGrants")@@ -686,8 +786,8 @@ func (s *ApiKeyService) GetApiKey(ctx context.Context, id string) (*apikey.ApiKe}func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.QueryParams) ([]apikey.ApiKey, pagination.Response, error) {- var apiKeys []models.ApiKey- query := s.db.WithContext(ctx).Model(&models.ApiKey{})+ var apiKeys []ApiKey+ query := s.db.WithContext(ctx).Model(&ApiKey{})if s.roleService != nil {query = query.Preload("PermissionGrants")}@@ -728,7 +828,7 @@ func (s *ApiKeyService) ListApiKeys(ctx context.Context, params pagination.Query// created before user_id became nullable) — self-service must never touch a// live pairing credential.func (s *ApiKeyService) ListApiKeysByUser(ctx context.Context, userID string) ([]apikey.ApiKey, error) {- var apiKeys []models.ApiKey+ var apiKeys []ApiKeyquery := s.db.WithContext(ctx)if s.roleService != nil {query = query.Preload("PermissionGrants")@@ -756,7 +856,7 @@ 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) {- var ak models.ApiKey+ var ak ApiKeyif err := s.db.WithContext(ctx).Where("id = ?", id).First(&ak).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrApiKeyNotFound@@ -773,7 +873,7 @@ func (s *ApiKeyService) UpdateApiKey(ctx context.Context, callerPerms *authz.Per}if req.Permissions != nil {- if ak.Kind == models.ApiKeyKindPersonal {+ if ak.Kind == ApiKeyKindPersonal {return nil, ErrApiKeyPersonalNoGrants}// Grants are capped twice: by the calling credential's effective@@ -853,7 +953,7 @@ func (s *ApiKeyService) loadKeyGrantsInternal(ctx context.Context, apiKeyID striif s.roleService == nil {return empty}- var rows []models.ApiKeyPermission+ var rows []role.ApiKeyPermissionif err := s.db.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Find(&rows).Error; err != nil {slog.WarnContext(ctx, "failed to load api key permission grants", "api_key_id", apiKeyID, "error", err)return empty@@ -866,7 +966,7 @@ func (s *ApiKeyService) loadKeyGrantsInternal(ctx context.Context, apiKeyID stri}func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {- var apiKey models.ApiKey+ var apiKey ApiKeyif err := s.db.WithContext(ctx).Where("id = ?", id).First(&apiKey).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return ErrApiKeyNotFound@@ -882,7 +982,7 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {return ErrApiKeyProtected}- result := s.db.WithContext(ctx).Delete(&models.ApiKey{}, "id = ?", id)+ result := s.db.WithContext(ctx).Delete(&ApiKey{}, "id = ?", id)if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete API key")}@@ -893,14 +993,14 @@ func (s *ApiKeyService) DeleteApiKey(ctx context.Context, id string) error {return nil}-func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*models.User, error) {+func (s *ApiKeyService) ValidateApiKey(ctx context.Context, rawKey string) (*common.User, error) {user, _, err := s.ValidateApiKeyWithID(ctx, rawKey)return user, err}// ValidateApiKeyWithID is like ValidateApiKey but additionally returns the// API key record so callers can resolve permissions according to its kind.-func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, *models.ApiKey, error) {+func (s *ApiKeyService) ValidateApiKeyWithID(ctx context.Context, rawKey string) (*common.User, *ApiKey, error) {apiKey, err := s.validateRawAPIKeyInternal(ctx, rawKey)if err != nil {return nil, nil, err@@ -929,7 +1029,7 @@ func (s *ApiKeyService) GetEnvironmentByApiKey(ctx context.Context, rawKey strin// validateRawAPIKeyInternal resolves a raw key to its validated record. A cache// hit skips the per-candidate Argon2id derivation; expiry is always re-checked// so a key expiring mid-TTL is rejected immediately.-func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey string) (*models.ApiKey, error) {+func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey string) (*ApiKey, error) {rawKey = strings.TrimSpace(rawKey)keyPrefix, err := parseAPIKeyPrefixInternal(rawKey)if err != nil {@@ -949,7 +1049,7 @@ func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey st// Snapshot before the read: if a revocation lands between this read and the// publish below, the generation will have moved and the publish is dropped.gen := s.cacheGen.Load()- var apiKeys []models.ApiKey+ var apiKeys []ApiKeyif err := s.db.WithContext(ctx).Where("key_prefix = ?", keyPrefix).Find(&apiKeys).Error; err != nil {return nil, errors.WrapIf(err, "failed to find API keys")}@@ -975,7 +1075,7 @@ func (s *ApiKeyService) validateRawAPIKeyInternal(ctx context.Context, rawKey st// read. The current request still proceeds — it validated against a row that// existed at read time, indistinguishable from a request racing the revocation// itself — but the result must not outlive the revocation in the cache.-func (s *ApiKeyService) storeValidatedKeyInternal(gen uint64, cacheKey string, apiKey models.ApiKey) {+func (s *ApiKeyService) storeValidatedKeyInternal(gen uint64, cacheKey string, apiKey ApiKey) {s.cacheFillMu.Lock()defer s.cacheFillMu.Unlock()if s.cacheGen.Load() == gen {diff --git a/backend/internal/apikey/service_test.go b/backend/internal/apikey/service_test.goindex 26f3b3239..58e2bb232 100644--- a/backend/internal/apikey/service_test.go+++ b/backend/internal/apikey/service_test.go@@ -1,6 +1,12 @@package apikeyimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""runtime"@@ -14,7 +20,6 @@ import ("gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -29,15 +34,15 @@ func setupAPIKeyServiceTestDB(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.SettingVariable{},- &models.User{},- &models.UserSession{},- &models.Environment{},- &models.Role{},- &models.UserRoleAssignment{},- &models.ApiKey{},- &models.ApiKeyPermission{},- &models.OidcRoleMapping{},+ &settings.SettingVariable{},+ &common.User{},+ &session.UserSession{},+ &testEnvironmentRow{},+ &role.Role{},+ &role.UserRoleAssignment{},+ &ApiKey{},+ &role.ApiKeyPermission{},+ &role.OidcRoleMapping{},))sqlDB, err := db.DB()@@ -56,15 +61,15 @@ func setupAPIKeyService(t *testing.T) (*ApiKeyService, *database.DB, *user.UserSreturn NewApiKeyService(db, userService), db, userService}-func createTestAPIKeyUser(t *testing.T, ctx context.Context, userService *user.UserService, id string, usernames ...string) *models.User {+func createTestAPIKeyUser(t *testing.T, ctx context.Context, userService *user.UserService, id string, usernames ...string) *common.User {t.Helper()username := fmt.Sprintf("user-%s", id)if len(usernames) > 0 {username = usernames[0]}- user := &models.User{- BaseModel: models.BaseModel{ID: id},+ user := &common.User{+ BaseModel: database.BaseModel{ID: id},Username: username,}@@ -73,19 +78,19 @@ func createTestAPIKeyUser(t *testing.T, ctx context.Context, userService *user.Ureturn created}-func fetchAPIKey(t *testing.T, db *database.DB, keyID string) models.ApiKey {+func fetchAPIKey(t *testing.T, db *database.DB, keyID string) ApiKey {t.Helper()- var apiKey models.ApiKey+ var apiKey ApiKeyerr := db.WithContext(context.Background()).Where("id = ?", keyID).First(&apiKey).Errorrequire.NoError(t, err)return apiKey}-func listAPIKeysForUser(t *testing.T, db *database.DB, userID string) []models.ApiKey {+func listAPIKeysForUser(t *testing.T, db *database.DB, userID string) []ApiKey {t.Helper()- var apiKeys []models.ApiKey+ var apiKeys []ApiKeyerr := db.WithContext(context.Background()).Where("user_id = ?", userID).Order("created_at asc").Find(&apiKeys).Errorrequire.NoError(t, err)return apiKeys@@ -103,11 +108,11 @@ func invalidateAPIKey(rawKey string) string {return rawKey[:len(rawKey)-1] + "0"}-func createDefaultAdminUser(t *testing.T, ctx context.Context, userService *user.UserService) *models.User {+func createDefaultAdminUser(t *testing.T, ctx context.Context, userService *user.UserService) *common.User {t.Helper()- user := &models.User{- BaseModel: models.BaseModel{ID: "default-admin-user"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "default-admin-user"},Username: defaultAdminUsername,}@@ -126,20 +131,20 @@ func TestListApiKeysPermissionQueryCountIsConstant(t *testing.T) {service := NewApiKeyService(db, user.NewUserService(db)).WithRoleService(role.NewRoleService(db))userID := "query-count-user"- apiKeys := make([]models.ApiKey, keyCount)- permissions := make([]models.ApiKeyPermission, keyCount)+ apiKeys := make([]ApiKey, keyCount)+ permissions := make([]role.ApiKeyPermission, keyCount)for i := range keyCount {keyID := fmt.Sprintf("key-%d", i)- apiKeys[i] = models.ApiKey{- BaseModel: models.BaseModel{ID: keyID},+ apiKeys[i] = ApiKey{+ BaseModel: database.BaseModel{ID: keyID},Name: keyID,KeyHash: "hash",KeyPrefix: fmt.Sprintf("arc_%04d", i),- Kind: models.ApiKeyKindScoped,+ Kind: ApiKeyKindScoped,UserID: &userID,}- permissions[i] = models.ApiKeyPermission{- BaseModel: models.BaseModel{ID: fmt.Sprintf("permission-%d", i)},+ permissions[i] = role.ApiKeyPermission{+ BaseModel: database.BaseModel{ID: fmt.Sprintf("permission-%d", i)},ApiKeyID: keyID,Permission: authz.PermContainersList,}@@ -270,7 +275,7 @@ func TestUpdateApiKeyRollsBackMetadataWhenPermissionUpdateFails(t *testing.T) {userSvc := user.NewUserService(db).WithRoleService(roleSvc)service := NewApiKeyService(db, userSvc).WithRoleService(roleSvc)admin := createTestAPIKeyUser(t, ctx, userSvc, "admin-update-rollback", "admin-update-rollback")- require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},}))@@ -312,7 +317,7 @@ func TestCreateApiKeyRejectsGrantsBeyondCallerPermissions(t *testing.T) {Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},})require.NoError(t, err)- require.Equal(t, models.ApiKeyKindScoped, created.Kind)+ require.Equal(t, ApiKeyKindScoped, created.Kind)}func TestApiKeyGrantsAreCappedByOwnerRoles(t *testing.T) {@@ -343,12 +348,12 @@ func TestApiKeyGrantsAreCappedByOwnerRoles(t *testing.T) {// Ownerless rows (not env-bootstrap; no production path creates these)// have no owner ceiling to validate against — grant edits are refused.- require.NoError(t, db.WithContext(ctx).Create(&models.ApiKey{+ require.NoError(t, db.WithContext(ctx).Create(&ApiKey{Name: "orphaned",KeyHash: "hash",KeyPrefix: "arc_orph",}).Error)- var orphan models.ApiKey+ var orphan ApiKeyrequire.NoError(t, db.WithContext(ctx).Where("key_prefix = ?", "arc_orph").First(&orphan).Error)_, err = service.UpdateApiKey(ctx, authz.SudoPermissionSet(), orphan.ID, apikey.UpdateApiKey{Permissions: []apikey.PermissionGrant{{Permission: authz.PermContainersList}},@@ -363,9 +368,9 @@ func TestCreatePersonalApiKeyHasNoGrantsAndCannotGainAny(t *testing.T) {created, err := service.CreatePersonalApiKey(ctx, user.ID, apikey.CreateUserApiKey{Name: "personal"})require.NoError(t, err)- require.Equal(t, models.ApiKeyKindPersonal, created.Kind)+ require.Equal(t, ApiKeyKindPersonal, created.Kind)require.Empty(t, created.Permissions)- require.Equal(t, models.ApiKeyKindPersonal, fetchAPIKey(t, db, created.ID).Kind)+ require.Equal(t, ApiKeyKindPersonal, fetchAPIKey(t, db, created.ID).Kind)// Attaching grants to a personal key is rejected even for sudo callers._, err = service.UpdateApiKey(ctx, authz.SudoPermissionSet(), created.ID, apikey.UpdateApiKey{@@ -517,7 +522,7 @@ func TestReconcileDefaultAdminAPIKeySkipsWhenDefaultAdminMissing(t *testing.T) {require.NoError(t, err)var count int64- err = db.WithContext(ctx).Model(&models.ApiKey{}).Count(&count).Error+ err = db.WithContext(ctx).Model(&ApiKey{}).Count(&count).Errorrequire.NoError(t, err)require.Zero(t, count)}@@ -562,7 +567,7 @@ func TestValidateAPIKeyCacheSkipsHashValidationAndInvalidatesOnRevoke(t *testing// Corrupt the stored hash: a second validation can only succeed by hitting// the validated-key cache and skipping the Argon2id check.- require.NoError(t, db.Model(&models.ApiKey{}).Where("id = ?", created.ID).Update("key_hash", "corrupted").Error)+ require.NoError(t, db.Model(&ApiKey{}).Where("id = ?", created.ID).Update("key_hash", "corrupted").Error)validatedUser, err := service.ValidateApiKey(ctx, created.Key)require.NoError(t, err)@@ -608,7 +613,7 @@ func TestValidateAPIKeyDebouncesLastUsedWrites(t *testing.T) {// Clear the column directly; a validation inside the debounce window must// not issue another write.- require.NoError(t, db.Model(&models.ApiKey{}).Where("id = ?", created.ID).Update("last_used_at", nil).Error)+ require.NoError(t, db.Model(&ApiKey{}).Where("id = ?", created.ID).Update("last_used_at", nil).Error)_, err = service.ValidateApiKey(ctx, created.Key)require.NoError(t, err)@@ -750,8 +755,8 @@ func TestApiKeyProtectedWhileEnvironmentReferenced(t *testing.T) {created, err := service.CreateEnvironmentApiKey(ctx, "env-referenced")require.NoError(t, err)- env := &models.Environment{- BaseModel: models.BaseModel{ID: "env-referenced"},+ env := &testEnvironmentRow{+ BaseModel: database.BaseModel{ID: "env-referenced"},Name: "referenced",ApiUrl: "http://localhost:2375",ApiKeyID: &created.ID,@@ -766,17 +771,17 @@ func TestApiKeyProtectedWhileEnvironmentReferenced(t *testing.T) {// Legacy pre-046 bootstrap rows carry an owner; the reference alone must// still protect them.legacyUserID := "legacy-owner"- legacy := &models.ApiKey{- BaseModel: models.BaseModel{ID: "legacy-key"},+ legacy := &ApiKey{+ BaseModel: database.BaseModel{ID: "legacy-key"},Name: "Environment Bootstrap Key - legacy",KeyHash: "hash",KeyPrefix: "arc_lgcy",- Kind: models.ApiKeyKindScoped,+ Kind: ApiKeyKindScoped,UserID: &legacyUserID,EnvironmentID: new("env-referenced"),}require.NoError(t, db.WithContext(ctx).Create(legacy).Error)- require.NoError(t, db.WithContext(ctx).Model(&models.Environment{}).+ require.NoError(t, db.WithContext(ctx).Model(&testEnvironmentRow{}).Where("id = ?", env.ID).Update("api_key_id", legacy.ID).Error)require.ErrorIs(t, service.DeleteApiKey(ctx, legacy.ID), ErrApiKeyProtected)@@ -816,7 +821,7 @@ func TestGetEnvironmentByAPIKeyExpiredDoesNotUpdateLastUsedAt(t *testing.T) {require.NoError(t, err)expiredAt := time.Now().Add(-time.Minute)- err = db.WithContext(ctx).Model(&models.ApiKey{}).Where("id = ?", created.ID).Update("expires_at", expiredAt).Error+ err = db.WithContext(ctx).Model(&ApiKey{}).Where("id = ?", created.ID).Update("expires_at", expiredAt).Errorrequire.NoError(t, err)_, err = service.GetEnvironmentByApiKey(ctx, created.Key)@@ -836,7 +841,7 @@ func TestCreateEnvironmentApiKeySeedsAllPermissionsScopedToEnv(t *testing.T) {userSvc := user.NewUserService(db).WithRoleService(roleSvc)service := NewApiKeyService(db, userSvc).WithRoleService(roleSvc)admin := createTestAPIKeyUser(t, ctx, userSvc, "admin-env-bootstrap", "admin-env-bootstrap")- require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},}))@@ -864,21 +869,39 @@ func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {roleSvc := role.NewRoleService(db)require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))+ userSvc := user.NewUserService(db).WithRoleService(roleSvc)+ service := NewApiKeyService(db, userSvc).WithRoleService(roleSvc)// Simulate a pre-existing env-bootstrap key with NO permission grants// (e.g., created on a deployment where the per-key seed step failed).envID := "env-broken-bootstrap"- require.NoError(t, db.WithContext(ctx).Create(&models.ApiKey{+ require.NoError(t, db.WithContext(ctx).Create(&ApiKey{Name: "Environment Bootstrap Key - broken",KeyHash: "hash",KeyPrefix: "arc_brkn",EnvironmentID: &envID,}).Error)- require.NoError(t, roleSvc.BackfillApiKeyPermissions(ctx))+ // A user-owned key with a single deliberate grant must NOT be rehydrated+ // from the owner's effective permissions by the backfill.+ owner := createTestAPIKeyUser(t, ctx, userSvc, "backfill-scoped-owner")+ scopedKey := ApiKey{+ Name: "Custom scoped key",+ KeyHash: "scoped-hash",+ KeyPrefix: "arc_scpd",+ Kind: ApiKeyKindScoped,+ UserID: &owner.ID,+ }+ require.NoError(t, db.WithContext(ctx).Create(&scopedKey).Error)+ require.NoError(t, db.WithContext(ctx).Create(&role.ApiKeyPermission{+ ApiKeyID: scopedKey.ID,+ Permission: authz.PermTemplatesRead,+ }).Error)++ require.NoError(t, service.BackfillApiKeyPermissions(ctx))// The backfill should have populated the env-scoped perms retroactively.- var keys []models.ApiKey+ var keys []ApiKeyrequire.NoError(t, db.WithContext(ctx).Where("environment_id = ?", envID).Find(&keys).Error)require.Len(t, keys, 1)ps, err := roleSvc.ResolveApiKeyPermissions(ctx, keys[0].ID)@@ -886,6 +909,55 @@ func TestBackfillApiKeyPermissionsRepairsExistingBootstrapKey(t *testing.T) {envPerms, ok := ps.PerEnv[envID]require.True(t, ok)require.Len(t, envPerms, len(authz.AllPermissions()))++ var scopedPerms []role.ApiKeyPermission+ require.NoError(t, db.WithContext(ctx).Where("api_key_id = ?", scopedKey.ID).Find(&scopedPerms).Error)+ require.Len(t, scopedPerms, 1)+ require.Equal(t, authz.PermTemplatesRead, scopedPerms[0].Permission)+}++func TestBackfillPermsForKeyDeduplicatesGlobalAndEnvironmentPermissions(t *testing.T) {+ ctx := context.Background()+ db := setupAPIKeyServiceTestDB(t)++ roleSvc := role.NewRoleService(db)+ require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))+ userSvc := user.NewUserService(db).WithRoleService(roleSvc)+ service := NewApiKeyService(db, userSvc).WithRoleService(roleSvc)++ admin := createTestAPIKeyUser(t, ctx, userSvc, "admin", "admin")+ require.NoError(t, roleSvc.SetUserAssignments(ctx, admin.ID, []role.UserRoleAssignment{+ {RoleID: authz.BuiltInRoleAdmin},+ }))+ owner := createTestAPIKeyUser(t, ctx, userSvc, "api-key-owner")+ envID := "env-1"+ now := time.Now()+ require.NoError(t, db.WithContext(ctx).Create(&testEnvironmentRow{+ BaseModel: database.BaseModel{ID: envID, CreatedAt: now, UpdatedAt: &now},+ Name: "env-" + envID,+ ApiUrl: "http://localhost:3552",+ Status: "online",+ Enabled: true,+ }).Error)++ require.NoError(t, roleSvc.SetUserAssignments(ctx, owner.ID, []role.UserRoleAssignment{+ {RoleID: authz.BuiltInRoleViewer, EnvironmentID: nil},+ {RoleID: authz.BuiltInRoleEditor, EnvironmentID: &envID},+ }))++ perms, err := service.backfillPermsForKeyInternal(ctx, db.WithContext(ctx), ApiKey{+ UserID: &owner.ID,+ EnvironmentID: &envID,+ })+ require.NoError(t, err)+ require.Contains(t, perms, authz.PermContainersList)+ count := 0+ for _, p := range perms {+ if p == authz.PermContainersList {+ count+++ }+ }+ require.Equal(t, 1, count)}func TestGetEnvironmentByAPIKeyRecentLastUsedAtDoesNotRewriteImmediately(t *testing.T) {@@ -896,7 +968,7 @@ func TestGetEnvironmentByAPIKeyRecentLastUsedAtDoesNotRewriteImmediately(t *testrequire.NoError(t, err)recent := time.Now().Add(-time.Minute)- err = db.WithContext(ctx).Model(&models.ApiKey{}).Where("id = ?", created.ID).Update("last_used_at", recent).Error+ err = db.WithContext(ctx).Model(&ApiKey{}).Where("id = ?", created.ID).Update("last_used_at", recent).Errorrequire.NoError(t, err)before := fetchAPIKey(t, db, created.ID)@@ -911,3 +983,17 @@ func TestGetEnvironmentByAPIKeyRecentLastUsedAtDoesNotRewriteImmediately(t *testrequire.NotNil(t, after.LastUsedAt)require.Equal(t, before.LastUsedAt.UTC().Unix(), after.LastUsedAt.UTC().Unix())}++// testEnvironmentRow is a minimal stand-in for environment.Environment: the+// environment package imports apikey, so this in-package test cannot import it.+type testEnvironmentRow struct {+ database.BaseModel+ Name string+ ApiUrl string `gorm:"column:api_url"`+ Status string+ Enabled bool+ AccessToken *string `gorm:"column:access_token"`+ ApiKeyID *string `gorm:"column:api_key_id"`+}++func (testEnvironmentRow) TableName() string { return "environments" }diff --git a/backend/internal/auth/handler.go b/backend/internal/auth/handler.goindex 507cc00c1..679367ab6 100644--- a/backend/internal/auth/handler.go+++ b/backend/internal/auth/handler.go@@ -1,6 +1,8 @@package authimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"+"bytes""context""fmt"@@ -20,7 +22,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"@@ -248,7 +249,7 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpu}if userModel.PasskeyMFAEnabled {- challenge, err := h.beginMFAAuthentication(ctx, userModel.ID, meta, models.UserSessionSourceLocal)+ challenge, err := h.beginMFAAuthentication(ctx, userModel.ID, meta, session.UserSessionSourceLocal)if err != nil {return nil, huma.Error500InternalServerError("Authentication failed")}@@ -264,7 +265,7 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpu}, nil}- tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, models.UserSessionSourceLocal, "")+ tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, session.UserSessionSourceLocal, "")if err != nil {return nil, huma.Error500InternalServerError("Authentication failed")}@@ -302,7 +303,7 @@ func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutpuslog.ErrorContext(ctx, "Failed to revoke session on logout; clearing cookie anyway", "sessionID", sessionID, "error", err)}}- if userModel, exists := models.CurrentUserFromContext(ctx); exists {+ if userModel, exists := common.CurrentUserFromContext(ctx); exists {h.authService.LogLogout(ctx, userModel)}}diff --git a/backend/internal/auth/huma_middleware.go b/backend/internal/auth/huma_middleware.goindex ce55e3f90..e03d65a55 100644--- a/backend/internal/auth/huma_middleware.go+++ b/backend/internal/auth/huma_middleware.go@@ -1,6 +1,10 @@package authimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""errors""log/slog"@@ -14,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie")@@ -68,7 +71,7 @@ func parseSecurityRequirementsInternal(api huma.API, ctx operationProvider) secu// authenticated user on success, or the underlying error from VerifyToken so// the caller can distinguish a missing/invalid token from a token-version// mismatch (which requires clearing the stale cookie).-func tryBearerAuthInternal(ctx huma.Context, authService *AuthService) (*models.User, string, error) {+func tryBearerAuthInternal(ctx huma.Context, authService *AuthService) (*common.User, string, error) {token := extractBearerTokenInternal(ctx)if token == "" {return nil, "", nil@@ -83,7 +86,7 @@ func tryBearerAuthInternal(ctx huma.Context, authService *AuthService) (*models.// tryApiKeyAuthInternal checks if API key authentication should be allowed// through. Returns the resolved user plus the API key record so the caller// can resolve permissions according to the key's kind.-func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *apikey.ApiKeyService) (*models.User, *models.ApiKey, bool) {+func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *apikey.ApiKeyService) (*common.User, *apikey.ApiKey, bool) {apiKey := ctx.Header(utils.HeaderApiKey)if apiKey == "" {return nil, nil, false@@ -97,7 +100,7 @@ func tryApiKeyAuthInternal(ctx huma.Context, apiKeyService *apikey.ApiKeyServicereturn user, key, true}-func tryEnvironmentAccessTokenAuthInternal(ctx huma.Context, resolver EnvironmentAccessTokenResolver, token string) (*models.User, *models.Environment, bool) {+func tryEnvironmentAccessTokenAuthInternal(ctx huma.Context, resolver EnvironmentAccessTokenResolver, token string) (*common.User, *environment.Environment, bool) {if resolver == nil || strings.TrimSpace(token) == "" {return nil, nil, false}@@ -112,7 +115,7 @@ func tryEnvironmentAccessTokenAuthInternal(ctx huma.Context, resolver Environmen// tryAgentAuthInternal checks if the request is from an authenticated agent.// Returns a sudo agent user if the agent token is valid.-func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*models.User, bool) {+func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*common.User, bool) {if cfg == nil || !cfg.AgentMode {return nil, false}@@ -141,9 +144,9 @@ func tryAgentAuthInternal(ctx huma.Context, cfg *config.Config) (*models.User, b// createAgentSudoUserInternal creates a sudo user for agent authentication.// The sudo PermissionSet attached to the context by the agent token path// bypasses every check; the user's Roles field is intentionally empty.-func createAgentSudoUserInternal() *models.User {- return &models.User{- BaseModel: models.BaseModel{ID: "agent"},+func createAgentSudoUserInternal() *common.User {+ return &common.User{+ BaseModel: database.BaseModel{ID: "agent"},Email: new("[email protected]"),Username: "agent",}@@ -157,7 +160,7 @@ func createAgentSudoUserInternal() *models.User {// Only called on synthetic-user auth paths (agent token, environment access// token), where the header is set by the manager after it strips any// client-supplied value. Real-user auth paths never read it.-func applyProxiedIconCatalogInternal(ctx huma.Context, user *models.User) {+func applyProxiedIconCatalogInternal(ctx huma.Context, user *common.User) {if user == nil {return}@@ -168,9 +171,9 @@ func applyProxiedIconCatalogInternal(ctx huma.Context, user *models.User) {user.Preferences.IconCatalog = &catalog}-func createEnvironmentUserInternal(env *models.Environment) *models.User {- return &models.User{- BaseModel: models.BaseModel{ID: "environment:" + env.ID},+func createEnvironmentUserInternal(env *environment.Environment) *common.User {+ return &common.User{+ BaseModel: database.BaseModel{ID: "environment:" + env.ID},Username: env.Name,}}@@ -262,7 +265,7 @@ func handleApiKeyAuthInternal(api huma.API, ctx huma.Context, authService *AuthS// Personal keys inherit the owner's role permissions (same resolution// as session auth); scoped keys are limited to their own grants.var ps *authz.PermissionSet- if key.Kind == models.ApiKeyKindPersonal {+ if key.Kind == apikey.ApiKeyKindPersonal {ps = resolveUserPermissionsInternal(ctx.Context(), permResolver, user)} else {ps = resolveApiKeyPermissionsInternal(ctx.Context(), permResolver, key.ID)@@ -318,7 +321,7 @@ func handleBearerAuthInternal(api huma.API, ctx huma.Context, authService *AuthS// PermissionSet. If RoleService is unavailable or the lookup fails (boot-time// edge cases, broken DB) it returns nil and logs a warning — handlers then// see deny-all, which is the safe default.-func resolveUserPermissionsInternal(ctx context.Context, permResolver PermissionResolver, user *models.User) *authz.PermissionSet {+func resolveUserPermissionsInternal(ctx context.Context, permResolver PermissionResolver, user *common.User) *authz.PermissionSet {if permResolver == nil || user == nil {return nil}@@ -377,12 +380,12 @@ func extractTokenFromCookieHeaderInternal(cookieHeader string) string {// setUserInContextInternal adds the authenticated user and the resolved// PermissionSet to the context. Callers must supply a non-nil PermissionSet;// pass authz.NewPermissionSet() to express deny-all.-func setUserInContextInternal(ctx context.Context, user *models.User, ps *authz.PermissionSet) context.Context {+func setUserInContextInternal(ctx context.Context, user *common.User, ps *authz.PermissionSet) context.Context {if ps == nil {ps = authz.NewPermissionSet()}ctx = context.WithValue(ctx, middleware.ContextKeyUserID, user.ID)- ctx = context.WithValue(ctx, models.CurrentUserContextKey{}, user)+ ctx = context.WithValue(ctx, common.CurrentUserContextKey{}, user)ctx = context.WithValue(ctx, middleware.ContextKeyUserPermissions, ps)return ctx}diff --git a/backend/internal/auth/huma_middleware_test.go b/backend/internal/auth/huma_middleware_test.goindex 88bf8a6a6..032315142 100644--- a/backend/internal/auth/huma_middleware_test.go+++ b/backend/internal/auth/huma_middleware_test.go@@ -1,6 +1,12 @@package authimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""net/http""net/http/httptest"@@ -12,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -34,7 +39,7 @@ type secureOutput struct {}type testEnvironmentAccessResolver struct {- env *models.Environment+ env *environment.Environment}func TestNewHumaMiddleware_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T) {@@ -53,8 +58,8 @@ func TestNewHumaMiddleware_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T)api := humaecho.NewWithGroup(router, apiGroup, humaConfig)api.UseMiddleware(NewHumaMiddleware(api, &AuthService{}, nil, nil, testEnvironmentAccessResolver{- env: &models.Environment{- BaseModel: models.BaseModel{ID: "env-self"},+ env: &environment.Environment{+ BaseModel: database.BaseModel{ID: "env-self"},Name: "Self Target",AccessToken: &token,},@@ -66,7 +71,7 @@ func TestNewHumaMiddleware_AcceptsEnvironmentAccessTokenViaAPIKey(t *testing.T)Path: "/secure",Security: []map[string][]string{{"ApiKeyAuth": {}}},}, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {- user, ok := models.CurrentUserFromContext(ctx)+ user, ok := common.CurrentUserFromContext(ctx)require.True(t, ok)require.Equal(t, "environment:env-self", user.ID)require.Equal(t, "Self Target", user.Username)@@ -117,8 +122,8 @@ func TestNewHumaMiddleware_UsesBearerWhenLoopbackProxySendsEnvironmentAccessTokeapi := humaecho.NewWithGroup(router, apiGroup, humaConfig)api.UseMiddleware(NewHumaMiddleware(api, authSvc, nil, staticPermissionResolverInternal{ps: ps}, testEnvironmentAccessResolver{- env: &models.Environment{- BaseModel: models.BaseModel{ID: "remote-env"},+ env: &environment.Environment{+ BaseModel: database.BaseModel{ID: "remote-env"},Name: "Remote Env",AccessToken: &envToken,},@@ -137,7 +142,7 @@ func TestNewHumaMiddleware_UsesBearerWhenLoopbackProxySendsEnvironmentAccessTokeID string `path:"id"`CID string `path:"cid"`}) (*secureOutput, error) {- user, ok := models.CurrentUserFromContext(ctx)+ user, ok := common.CurrentUserFromContext(ctx)require.True(t, ok)require.Equal(t, "u-loopback", user.ID)@@ -264,8 +269,8 @@ func TestNewHumaMiddleware_OpportunisticAuthOnPublicRoute(t *testing.T) {cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, cfg, nil)- _, err := userSvc.CreateUser(context.Background(), &models.User{- BaseModel: models.BaseModel{ID: "u-logout"},+ _, err := userSvc.CreateUser(context.Background(), &common.User{+ BaseModel: database.BaseModel{ID: "u-logout"},Username: "logouttest",})require.NoError(t, err)@@ -352,8 +357,8 @@ func TestNewHumaMiddleware_VersionMismatchIsRecoverable(t *testing.T) {cfg := &config.Config{JWTRefreshExpiry: 24 * time.Hour}authSvc := NewAuthService(userSvc, nil, nil, sessionSvc, nil, jwtSecret, cfg, nil)- _, err := userSvc.CreateUser(context.Background(), &models.User{- BaseModel: models.BaseModel{ID: "u-ver"},+ _, err := userSvc.CreateUser(context.Background(), &common.User{+ BaseModel: database.BaseModel{ID: "u-ver"},Username: "vertest",})require.NoError(t, err)@@ -443,7 +448,7 @@ func TestNewHumaMiddleware_AgentAuthAppliesForwardedIconCatalog(t *testing.T) {Path: "/secure-agent-icon-catalog",Security: []map[string][]string{{"ApiKeyAuth": {}}},}, func(ctx context.Context, _ *secureInput) (*secureOutput, error) {- user, ok := models.CurrentUserFromContext(ctx)+ user, ok := common.CurrentUserFromContext(ctx)require.True(t, ok)require.NotNil(t, user.Preferences.IconCatalog)require.Equal(t, "dashboard-icons", *user.Preferences.IconCatalog)@@ -463,7 +468,7 @@ func TestNewHumaMiddleware_AgentAuthAppliesForwardedIconCatalog(t *testing.T) {require.Equal(t, http.StatusOK, rec.Code)}-func (r testEnvironmentAccessResolver) ResolveEnvironmentByAccessToken(_ context.Context, token string) (*models.Environment, error) {+func (r testEnvironmentAccessResolver) ResolveEnvironmentByAccessToken(_ context.Context, token string) (*environment.Environment, error) {if r.env != nil && r.env.AccessToken != nil && *r.env.AccessToken == token {return r.env, nil}@@ -474,15 +479,15 @@ func setupAuthMiddlewareTestDBInternal(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}, &models.User{}, &models.UserSession{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}, &common.User{}, &session.UserSession{}))return &database.DB{DB: db}}func mintHumaMiddlewareTestTokenInternal(t *testing.T, userSvc *user.UserService, sessionSvc *session.SessionService, jwtSecret string, userID string) string {t.Helper()- _, err := userSvc.CreateUser(context.Background(), &models.User{- BaseModel: models.BaseModel{ID: userID},+ _, err := userSvc.CreateUser(context.Background(), &common.User{+ BaseModel: database.BaseModel{ID: userID},Username: userID,})require.NoError(t, err)@@ -505,7 +510,7 @@ func mintHumaMiddlewareTestTokenInternal(t *testing.T, userSvc *user.UserServicereturn token}-func (r staticPermissionResolverInternal) ResolvePermissions(_ context.Context, _ *models.User) (*authz.PermissionSet, error) {+func (r staticPermissionResolverInternal) ResolvePermissions(_ context.Context, _ *common.User) (*authz.PermissionSet, error) {return r.ps, nil}diff --git a/backend/internal/auth/middleware.go b/backend/internal/auth/middleware.goindex 3e7a2e06b..3c72a112e 100644--- a/backend/internal/auth/middleware.go+++ b/backend/internal/auth/middleware.go@@ -1,6 +1,12 @@package authimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"github.com/samber/mo""context"@@ -14,7 +20,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"@@ -27,17 +32,17 @@ type AuthOptions struct {}type ApiKeyValidator interface {- ValidateApiKeyWithID(ctx context.Context, rawKey string) (*models.User, *models.ApiKey, error)+ ValidateApiKeyWithID(ctx context.Context, rawKey string) (*common.User, *apikey.ApiKey, error)}type EnvironmentAccessTokenResolver interface {- ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*models.Environment, error)+ ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*environment.Environment, error)}// PermissionResolver resolves a caller's effective permission set. Implemented// by role.RoleService; kept as an interface so tests can stub it.type PermissionResolver interface {- ResolvePermissions(ctx context.Context, user *models.User) (*authz.PermissionSet, error)+ ResolvePermissions(ctx context.Context, user *common.User) (*authz.PermissionSet, error)ResolveApiKeyPermissions(ctx context.Context, apiKeyID string) (*authz.PermissionSet, error)}@@ -130,7 +135,7 @@ func (m *AuthMiddleware) agentAuth(ctx context.Context, c *echo.Context, next ec"has_agent_token_hdr", req.Header.Get(utils.HeaderAgentToken) != "","agent_token_config_set", m.cfg.AgentToken != "",)- return c.JSON(http.StatusForbidden, models.APIError{+ return c.JSON(http.StatusForbidden, common.APIError{Code: "FORBIDDEN",Message: "Invalid or missing agent token",})@@ -164,8 +169,8 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c *echo.Context, nextif m.options.SuccessOptional {return next(c)}- return c.JSON(http.StatusUnauthorized, models.APIError{- Code: models.APIErrorCodeUnauthorized,+ return c.JSON(http.StatusUnauthorized, common.APIError{+ Code: common.APIErrorCodeUnauthorized,Message: "Authentication required",})}@@ -176,16 +181,16 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c *echo.Context, next// (the refresh path tolerates the version change and rotates the token), so do// NOT clear the cookies. Return a recoverable 401 the frontend refreshes from.if errors.Is(err, common.ErrTokenVersionMismatch) {- return c.JSON(http.StatusUnauthorized, models.APIError{- Code: models.APIErrorCodeUnauthorized,+ return c.JSON(http.StatusUnauthorized, common.APIError{+ Code: common.APIErrorCodeUnauthorized,Message: "Application has been updated. Refreshing session.",})}if errors.Is(err, common.ErrSessionRevoked) || errors.Is(err, common.ErrTokenValidation) {cookie.ClearTokenCookie(c.Response(), req)- return c.JSON(http.StatusUnauthorized, models.APIError{- Code: models.APIErrorCodeUnauthorized,+ return c.JSON(http.StatusUnauthorized, common.APIError{+ Code: common.APIErrorCodeUnauthorized,Message: "Session expired. Please log in again.",})}@@ -193,15 +198,15 @@ func (m *AuthMiddleware) managerAuth(ctx context.Context, c *echo.Context, nextif m.options.SuccessOptional {return next(c)}- return c.JSON(http.StatusUnauthorized, models.APIError{- Code: models.APIErrorCodeUnauthorized,+ return c.JSON(http.StatusUnauthorized, common.APIError{+ Code: common.APIErrorCodeUnauthorized,Message: "Invalid or expired token",})}ps := m.resolvePermissionsOrDeny(ctx, user)if m.options.AdminRequired && !ps.IsGlobalAdmin() {- return c.JSON(http.StatusForbidden, models.APIError{+ return c.JSON(http.StatusForbidden, common.APIError{Code: "FORBIDDEN",Message: "You don't have permission to access this resource",})@@ -223,13 +228,13 @@ func (m *AuthMiddleware) apiKeyHeaderAuth(ctx context.Context, c *echo.Context,// Personal keys inherit the owner's role permissions (same// resolution as session auth); scoped keys use their own grants.var ps *authz.PermissionSet- if key.Kind == models.ApiKeyKindPersonal {+ if key.Kind == apikey.ApiKeyKindPersonal {ps = m.resolvePermissionsOrDeny(ctx, user)} else {ps = m.resolveApiKeyPermissionsOrDeny(ctx, key.ID)}if m.options.AdminRequired && !ps.IsGlobalAdmin() {- return c.JSON(http.StatusForbidden, models.APIError{+ return c.JSON(http.StatusForbidden, common.APIError{Code: "FORBIDDEN",Message: "You don't have permission to access this resource",})@@ -245,8 +250,8 @@ func (m *AuthMiddleware) apiKeyHeaderAuth(ctx context.Context, c *echo.Context,environmentScopedInternal(c, env)return next(c)}- return c.JSON(http.StatusUnauthorized, models.APIError{- Code: models.APIErrorCodeUnauthorized,+ return c.JSON(http.StatusUnauthorized, common.APIError{+ Code: common.APIErrorCodeUnauthorized,Message: "Invalid or expired API key",})}@@ -254,7 +259,7 @@ func (m *AuthMiddleware) apiKeyHeaderAuth(ctx context.Context, c *echo.Context,// resolvePermissionsOrDeny returns the user's permission set, or an empty// (deny-all) set if the resolver is unavailable or fails. Resolver failures// are logged.-func (m *AuthMiddleware) resolvePermissionsOrDeny(ctx context.Context, user *models.User) *authz.PermissionSet {+func (m *AuthMiddleware) resolvePermissionsOrDeny(ctx context.Context, user *common.User) *authz.PermissionSet {if m.roleResolver == nil || user == nil {return authz.NewPermissionSet()}@@ -281,14 +286,14 @@ func (m *AuthMiddleware) resolveApiKeyPermissionsOrDeny(ctx context.Context, apireturn ps}-func (m *AuthMiddleware) resolveEnvironmentAccessToken(ctx context.Context, token string) mo.Option[*models.Environment] {+func (m *AuthMiddleware) resolveEnvironmentAccessToken(ctx context.Context, token string) mo.Option[*environment.Environment] {if m.envTokenResolver == nil {- return mo.None[*models.Environment]()+ return mo.None[*environment.Environment]()}env, err := m.envTokenResolver.ResolveEnvironmentByAccessToken(ctx, token)if err != nil || env == nil {- return mo.None[*models.Environment]()+ return mo.None[*environment.Environment]()}return mo.Some(env)@@ -299,8 +304,8 @@ func isPreflightInternal(c *echo.Context) bool {}func agentSudoInternal(c *echo.Context) {- agentUser := &models.User{- BaseModel: models.BaseModel{ID: "agent"},+ agentUser := &common.User{+ BaseModel: database.BaseModel{ID: "agent"},Email: new("[email protected]"),Username: "agent",}@@ -310,9 +315,9 @@ func agentSudoInternal(c *echo.Context) {c.Set(string(middleware.ContextKeyAuthMethod), "agent_token")}-func environmentScopedInternal(c *echo.Context, env *models.Environment) {- envUser := &models.User{- BaseModel: models.BaseModel{ID: "environment:" + env.ID},+func environmentScopedInternal(c *echo.Context, env *environment.Environment) {+ envUser := &common.User{+ BaseModel: database.BaseModel{ID: "environment:" + env.ID},Username: env.Name,}c.Set(string(middleware.ContextKeyUserID), envUser.ID)diff --git a/backend/internal/auth/middleware_test.go b/backend/internal/auth/middleware_test.goindex c62fe4e9c..af2665b88 100644--- a/backend/internal/auth/middleware_test.go+++ b/backend/internal/auth/middleware_test.go@@ -1,23 +1,30 @@package authimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"++ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""net/http""net/http/httptest""testing""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/labstack/echo/v5""github.com/stretchr/testify/require")type testEnvironmentTokenResolver struct {- env *models.Environment+ env *environment.Environment}-func (r testEnvironmentTokenResolver) ResolveEnvironmentByAccessToken(_ context.Context, token string) (*models.Environment, error) {+func (r testEnvironmentTokenResolver) ResolveEnvironmentByAccessToken(_ context.Context, token string) (*environment.Environment, error) {if r.env != nil && r.env.AccessToken != nil && *r.env.AccessToken == token {return r.env, nil}@@ -27,11 +34,11 @@ func (r testEnvironmentTokenResolver) ResolveEnvironmentByAccessToken(_ context.var ErrInvalidEnvironmentAccessTokenForTest = context.Canceledtype testApiKeyValidator struct {- user *models.User- key *models.ApiKey+ user *common.User+ key *apikey.ApiKey}-func (v testApiKeyValidator) ValidateApiKeyWithID(_ context.Context, rawKey string) (*models.User, *models.ApiKey, error) {+func (v testApiKeyValidator) ValidateApiKeyWithID(_ context.Context, rawKey string) (*common.User, *apikey.ApiKey, error) {if rawKey == "valid-key" {return v.user, v.key, nil}@@ -42,7 +49,7 @@ func (v testApiKeyValidator) ValidateApiKeyWithID(_ context.Context, rawKey stri// resolution path the middleware took: user roles vs per-key grants.type testPermissionResolver struct{}-func (testPermissionResolver) ResolvePermissions(_ context.Context, _ *models.User) (*authz.PermissionSet, error) {+func (testPermissionResolver) ResolvePermissions(_ context.Context, _ *common.User) (*authz.PermissionSet, error) {ps := authz.NewPermissionSet()ps.AddGlobal("containers:list")return ps, nil@@ -56,7 +63,7 @@ func (testPermissionResolver) ResolveApiKeyPermissions(_ context.Context, _ strifunc TestAuthMiddleware_ManagerAuthResolvesPermissionsByKeyKind(t *testing.T) {userID := "key-owner"- user := &models.User{BaseModel: models.BaseModel{ID: userID}, Username: "owner"}+ user := &common.User{BaseModel: database.BaseModel{ID: userID}, Username: "owner"}cases := []struct {name string@@ -64,8 +71,8 @@ func TestAuthMiddleware_ManagerAuthResolvesPermissionsByKeyKind(t *testing.T) {wantAllowed stringwantDenied string}{- {name: "personal key inherits owner role permissions", kind: models.ApiKeyKindPersonal, wantAllowed: "containers:list", wantDenied: "images:list"},- {name: "scoped key limited to its own grants", kind: models.ApiKeyKindScoped, wantAllowed: "images:list", wantDenied: "containers:list"},+ {name: "personal key inherits owner role permissions", kind: apikey.ApiKeyKindPersonal, wantAllowed: "containers:list", wantDenied: "images:list"},+ {name: "scoped key limited to its own grants", kind: apikey.ApiKeyKindScoped, wantAllowed: "images:list", wantDenied: "containers:list"},}for _, tc := range cases {@@ -75,7 +82,7 @@ func TestAuthMiddleware_ManagerAuthResolvesPermissionsByKeyKind(t *testing.T) {NewAuthMiddleware(nil, &config.Config{}).WithApiKeyValidator(testApiKeyValidator{user: user,- key: &models.ApiKey{BaseModel: models.BaseModel{ID: "key-1"}, Kind: tc.kind, UserID: &userID},+ key: &apikey.ApiKey{BaseModel: database.BaseModel{ID: "key-1"}, Kind: tc.kind, UserID: &userID},}).WithPermissionResolver(testPermissionResolver{}).Add(),@@ -104,8 +111,8 @@ func TestAuthMiddleware_ManagerAuthAcceptsEnvironmentAccessTokenViaAPIKey(t *tesrouter.Use(NewAuthMiddleware(nil, &config.Config{}).WithEnvironmentAccessTokenResolver(testEnvironmentTokenResolver{- env: &models.Environment{- BaseModel: models.BaseModel{ID: "env-self"},+ env: &environment.Environment{+ BaseModel: database.BaseModel{ID: "env-self"},Name: "Self Target",AccessToken: &token,},@@ -116,7 +123,7 @@ func TestAuthMiddleware_ManagerAuthAcceptsEnvironmentAccessTokenViaAPIKey(t *tescurrentUser := c.Get("currentUser")require.NotNil(t, currentUser)- user, ok := currentUser.(*models.User)+ user, ok := currentUser.(*common.User)require.True(t, ok)require.Equal(t, "environment:env-self", user.ID)require.Equal(t, "Self Target", user.Username)diff --git a/backend/internal/auth/service.go b/backend/internal/auth/service.goindex f108d4b98..f7a0b3016 100644--- a/backend/internal/auth/service.go+++ b/backend/internal/auth/service.go@@ -1,6 +1,8 @@package authimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""crypto/sha256""encoding/hex"@@ -16,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -43,10 +44,10 @@ type TokenPair struct {}type AuthSettings struct {- LocalAuthEnabled bool `json:"localAuthEnabled"`- OidcEnabled bool `json:"oidcEnabled"`- SessionTimeout int `json:"sessionTimeout"`- Oidc *models.OidcConfig `json:"oidc,omitempty"`+ LocalAuthEnabled bool `json:"localAuthEnabled"`+ OidcEnabled bool `json:"oidcEnabled"`+ SessionTimeout int `json:"sessionTimeout"`+ Oidc *settings.OidcConfig `json:"oidc,omitempty"`}type userClaims struct {@@ -71,7 +72,7 @@ type refreshClaims struct {}type verifiedTokenEntry struct {- User models.User+ User common.UserSessionID string}@@ -116,7 +117,7 @@ func NewAuthService(userService *user.UserService, settingsService *settings.Set}func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, error) {- settings, err := s.settingsService.GetSettings(ctx)+ appSettings, err := s.settingsService.GetSettings(ctx)if err != nil {return nil, errors.WrapIf(err, "failed to get settings")}@@ -124,24 +125,24 @@ func (s *AuthService) getAuthSettings(ctx context.Context) (*AuthSettings, errortimeoutMinutes, _ := s.GetSessionTimeout(ctx)authSettings := &AuthSettings{- LocalAuthEnabled: settings.AuthLocalEnabled.IsTrue(),- OidcEnabled: settings.OidcEnabled.IsTrue(),+ LocalAuthEnabled: appSettings.AuthLocalEnabled.IsTrue(),+ OidcEnabled: appSettings.OidcEnabled.IsTrue(),SessionTimeout: timeoutMinutes,}if authSettings.OidcEnabled {- oidcConfig := &models.OidcConfig{- ClientID: settings.OidcClientId.Value,- ClientSecret: settings.OidcClientSecret.Value,- IssuerURL: settings.OidcIssuerUrl.Value,- AuthorizationEndpoint: settings.OidcAuthorizationEndpoint.Value,- TokenEndpoint: settings.OidcTokenEndpoint.Value,- UserinfoEndpoint: settings.OidcUserinfoEndpoint.Value,- JwksURI: settings.OidcJwksEndpoint.Value,- DeviceAuthorizationEndpoint: settings.OidcDeviceAuthorizationEndpoint.Value,- Scopes: settings.OidcScopes.Value,- GroupsClaim: settings.OidcGroupsClaim.Value,- SkipTlsVerify: settings.OidcSkipTlsVerify.IsTrue(),+ oidcConfig := &settings.OidcConfig{+ ClientID: appSettings.OidcClientId.Value,+ ClientSecret: appSettings.OidcClientSecret.Value,+ IssuerURL: appSettings.OidcIssuerUrl.Value,+ AuthorizationEndpoint: appSettings.OidcAuthorizationEndpoint.Value,+ TokenEndpoint: appSettings.OidcTokenEndpoint.Value,+ UserinfoEndpoint: appSettings.OidcUserinfoEndpoint.Value,+ JwksURI: appSettings.OidcJwksEndpoint.Value,+ DeviceAuthorizationEndpoint: appSettings.OidcDeviceAuthorizationEndpoint.Value,+ Scopes: appSettings.OidcScopes.Value,+ GroupsClaim: appSettings.OidcGroupsClaim.Value,+ SkipTlsVerify: appSettings.OidcSkipTlsVerify.IsTrue(),}if oidcConfig.ClientID != "" || oidcConfig.IssuerURL != "" {@@ -226,7 +227,7 @@ func (s *AuthService) IsOidcEnabled(ctx context.Context) (bool, error) {return settings.OidcEnabled.IsTrue(), nil}-func (s *AuthService) GetOidcConfig(ctx context.Context) (*models.OidcConfig, error) {+func (s *AuthService) GetOidcConfig(ctx context.Context) (*settings.OidcConfig, error) {authSettings, err := s.getAuthSettings(ctx)if err != nil {return nil, err@@ -242,7 +243,7 @@ func (s *AuthService) GetOidcConfig(ctx context.Context) (*models.OidcConfig, er// AuthenticateLocalPrimary validates the local primary factor without// creating a session. Callers must complete passkey MFA, when enabled, before// issuing a bearer or refresh token.-func (s *AuthService) AuthenticateLocalPrimary(ctx context.Context, username, password string) (*models.User, error) {+func (s *AuthService) AuthenticateLocalPrimary(ctx context.Context, username, password string) (*common.User, error) {localEnabled, err := s.IsLocalAuthEnabled(ctx)if err != nil {return nil, err@@ -296,7 +297,7 @@ func (s *AuthService) AuthenticateLocalPrimary(ctx context.Context, username, pa// PrepareOidcLogin reconciles the provider identity without creating a// session. The caller must complete passkey MFA, when enabled, before issuing// tokens.-func (s *AuthService) PrepareOidcLogin(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*models.User, bool, error) {+func (s *AuthService) PrepareOidcLogin(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {if userInfo.Subject == "" {return nil, false, errors.New("missing OIDC subject identifier")}@@ -305,15 +306,15 @@ func (s *AuthService) PrepareOidcLogin(ctx context.Context, userInfo auth.OidcUs// CompleteLogin creates the authenticated session after all required factors// have succeeded. Source is server-selected and is persisted with the session.-func (s *AuthService) CompleteLogin(ctx context.Context, user *models.User, meta auth.SessionMeta, source, mfaMethod string, eventMetadata ...models.JSON) (*TokenPair, error) {+func (s *AuthService) CompleteLogin(ctx context.Context, user *common.User, meta auth.SessionMeta, source, mfaMethod string, eventMetadata ...database.JSON) (*TokenPair, error) {if user == nil {return nil, common.ErrUserNotFound}if strings.TrimSpace(source) == "" {- source = models.UserSessionSourceLocal+ source = session.UserSessionSourceLocal}mfaMethod = strings.TrimSpace(mfaMethod)- if user.PasskeyMFAEnabled && source != models.UserSessionSourcePasskey && mfaMethod != models.PasskeyMFAMethod && mfaMethod != models.RecoveryCodeMFAMethod {+ if user.PasskeyMFAEnabled && source != session.UserSessionSourcePasskey && mfaMethod != session.PasskeyMFAMethod && mfaMethod != session.RecoveryCodeMFAMethod {return nil, ErrMFARequired}meta.Source = source@@ -328,7 +329,7 @@ func (s *AuthService) CompleteLogin(ctx context.Context, user *models.User, metareturn nil, err}- metadata := models.JSON{"action": "login", "method": source}+ metadata := database.JSON{"action": "login", "method": source}if len(eventMetadata) > 0 {maps.Copy(metadata, eventMetadata[0])}@@ -339,14 +340,14 @@ func (s *AuthService) CompleteLogin(ctx context.Context, user *models.User, metalogUserID := user.IDlogUsername := user.Usernames.runInBackground(ctx, "log_user_login", func(ctx context.Context) error {- return s.eventService.LogUserEvent(ctx, models.EventTypeUserLogin, logUserID, logUsername, metadata)+ return s.eventService.LogUserEvent(ctx, event.EventTypeUserLogin, logUserID, logUsername, metadata)})}return tokenPair, nil}-func (s *AuthService) Login(ctx context.Context, username, password string, meta auth.SessionMeta) (*models.User, *TokenPair, error) {+func (s *AuthService) Login(ctx context.Context, username, password string, meta auth.SessionMeta) (*common.User, *TokenPair, error) {user, err := s.AuthenticateLocalPrimary(ctx, username, password)if err != nil {return nil, nil, err@@ -354,14 +355,14 @@ func (s *AuthService) Login(ctx context.Context, username, password string, metaif user.PasskeyMFAEnabled {return nil, nil, ErrMFARequired}- tokenPair, err := s.CompleteLogin(ctx, user, meta, models.UserSessionSourceLocal, "")+ tokenPair, err := s.CompleteLogin(ctx, user, meta, session.UserSessionSourceLocal, "")if err != nil {return nil, nil, err}return user, tokenPair, nil}-func (s *AuthService) OidcLogin(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse, meta auth.SessionMeta) (*models.User, *TokenPair, error) {+func (s *AuthService) OidcLogin(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse, meta auth.SessionMeta) (*common.User, *TokenPair, error) {user, isNewUser, err := s.PrepareOidcLogin(ctx, userInfo, tokenResp)if err != nil {return nil, nil, err@@ -369,7 +370,7 @@ func (s *AuthService) OidcLogin(ctx context.Context, userInfo auth.OidcUserInfo,if user.PasskeyMFAEnabled {return nil, nil, ErrMFARequired}- tokenPair, err := s.CompleteLogin(ctx, user, meta, models.UserSessionSourceOidc, "", models.JSON{+ tokenPair, err := s.CompleteLogin(ctx, user, meta, session.UserSessionSourceOidc, "", database.JSON{"newUser": isNewUser,"subject": userInfo.Subject,})@@ -379,23 +380,23 @@ func (s *AuthService) OidcLogin(ctx context.Context, userInfo auth.OidcUserInfo,return user, tokenPair, nil}-func (s *AuthService) LogLogout(ctx context.Context, user *models.User) {+func (s *AuthService) LogLogout(ctx context.Context, user *common.User) {if s.eventService == nil || user == nil {return}- metadata := models.JSON{+ metadata := database.JSON{"action": "logout",}userID := user.IDusername := user.Usernames.runInBackground(ctx, "log_user_logout", func(ctx context.Context) error {- return s.eventService.LogUserEvent(ctx, models.EventTypeUserLogout, userID, username, metadata)+ return s.eventService.LogUserEvent(ctx, event.EventTypeUserLogout, userID, username, metadata)})}-func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*models.User, bool, error) {+func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {user, err := s.userService.GetUserByOidcSubjectId(ctx, userInfo.Subject)if err != nil && !errors.Is(err, common.ErrUserNotFound) {return nil, false, err@@ -420,14 +421,14 @@ func (s *AuthService) findOrCreateOidcUser(ctx context.Context, userInfo auth.Oireturn created, true, nil}-func (s *AuthService) updateExistingOidcUser(ctx context.Context, user *models.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*models.User, bool, error) {+func (s *AuthService) updateExistingOidcUser(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {if err := s.updateOidcUser(ctx, user, userInfo, tokenResp); err != nil {return nil, false, err}return user, false, nil}-func (s *AuthService) tryMergeOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*models.User, bool, error) {+func (s *AuthService) tryMergeOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, bool, error) {if userInfo.Email == "" || !s.isOidcMergeEnabled(ctx) {return nil, false, nil}@@ -475,7 +476,7 @@ func (s *AuthService) validateMergeEmailVerification(userInfo auth.OidcUserInfo)return nil}-func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*models.User, error) {+func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) (*common.User, error) {var username stringif userInfo.PreferredUsername == "" {username = generateUsernameFromEmail(userInfo.Email, userInfo.Subject)@@ -493,8 +494,8 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUserdisplayName = new(username)}- user := &models.User{- BaseModel: models.BaseModel{ID: uuid.NewString()},+ user := &common.User{+ BaseModel: database.BaseModel{ID: uuid.NewString()},Username: username,DisplayName: displayName,Email: new(userInfo.Email),@@ -513,7 +514,7 @@ func (s *AuthService) createOidcUser(ctx context.Context, userInfo auth.OidcUserreturn user, nil}-func (s *AuthService) updateOidcUser(ctx context.Context, user *models.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {+func (s *AuthService) updateOidcUser(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {if userInfo.Name != "" && user.DisplayName == nil {user.DisplayName = new(userInfo.Name)}@@ -533,9 +534,9 @@ func (s *AuthService) updateOidcUser(ctx context.Context, user *models.User, usereturn nil}-func (s *AuthService) mergeOidcWithExistingUser(ctx context.Context, user *models.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {+func (s *AuthService) mergeOidcWithExistingUser(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {// Perform the merge atomically to avoid races when multiple OIDC subjects share the same email- merged, err := s.userService.AttachOidcSubjectTransactional(ctx, user.ID, userInfo.Subject, func(u *models.User) {+ merged, err := s.userService.AttachOidcSubjectTransactional(ctx, user.ID, userInfo.Subject, func(u *common.User) {if userInfo.Name != "" && u.DisplayName == nil {u.DisplayName = new(userInfo.Name)}@@ -556,7 +557,7 @@ func (s *AuthService) mergeOidcWithExistingUser(ctx context.Context, user *model// syncOidcRoleAssignments rebuilds the user's `source='oidc'` role assignments// based on the OIDC group claim and the configured OidcRoleMapping rows.// Manual assignments are untouched.-func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *models.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {+func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *common.User, userInfo auth.OidcUserInfo, tokenResp *auth.OidcTokenResponse) error {if s.roleService == nil || user == nil {return nil}@@ -572,7 +573,7 @@ func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *models.groupSet[g] = struct{}{}}- var desired []models.UserRoleAssignment+ var desired []role.UserRoleAssignmentseen := make(map[string]struct{}) // dedup by roleID|envIDfor _, m := range mappings {if _, ok := groupSet[m.ClaimValue]; !ok {@@ -586,7 +587,7 @@ func (s *AuthService) syncOidcRoleAssignments(ctx context.Context, user *models.continue}seen[key] = struct{}{}- desired = append(desired, models.UserRoleAssignment{+ desired = append(desired, role.UserRoleAssignment{RoleID: m.RoleID,EnvironmentID: m.EnvironmentID,})@@ -660,7 +661,7 @@ func stringValuesFromClaim(v any) []string {}}-func (s *AuthService) persistOidcTokens(user *models.User, tokenResp *auth.OidcTokenResponse) {+func (s *AuthService) persistOidcTokens(user *common.User, tokenResp *auth.OidcTokenResponse) {if tokenResp == nil {return}@@ -741,7 +742,7 @@ func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string, metreturn s.buildTokenPairInternal(ctx, user, rotatedSession, refreshJTI)}-func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*models.User, string, error) {+func (s *AuthService) VerifyToken(ctx context.Context, accessToken string) (*common.User, string, error) {token, err := jwt.ParseWithClaims(accessToken, &userClaims{},func(t *jwt.Token) (any, error) {if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {@@ -927,7 +928,7 @@ func (s *AuthService) LogoutAllOtherSessions(ctx context.Context, userID, currenreturn s.sessionService.RevokeAllUserSessionsExcept(ctx, userID, currentSessionID)}-func (s *AuthService) createSessionAndTokensInternal(ctx context.Context, user *models.User, meta auth.SessionMeta) (*TokenPair, error) {+func (s *AuthService) createSessionAndTokensInternal(ctx context.Context, user *common.User, meta auth.SessionMeta) (*TokenPair, error) {if s.sessionService == nil {return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))}@@ -939,7 +940,7 @@ func (s *AuthService) createSessionAndTokensInternal(ctx context.Context, user *return s.buildTokenPairInternal(ctx, user, session, refreshJTI)}-func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *models.User, session *models.UserSession, refreshJTI string) (*TokenPair, error) {+func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *common.User, session *session.UserSession, refreshJTI string) (*TokenPair, error) {sessionTimeout, _ := s.GetSessionTimeout(ctx)accessTokenExpiry := time.Now().Add(time.Duration(sessionTimeout) * time.Minute)@@ -996,7 +997,7 @@ func (s *AuthService) buildTokenPairInternal(ctx context.Context, user *models.U}, nil}-func (s *AuthService) IssueFederatedToken(ctx context.Context, user *models.User, credentialID string, ttlSeconds int) (*TokenPair, error) {+func (s *AuthService) IssueFederatedToken(ctx context.Context, user *common.User, credentialID string, ttlSeconds int) (*TokenPair, error) {if s.sessionService == nil {return nil, common.Classify(common.ErrUnavailable, errors.New("Session service is not configured"))}@@ -1008,7 +1009,7 @@ func (s *AuthService) IssueFederatedToken(ctx context.Context, user *models.Usernow := time.Now()accessTokenExpiry := now.Add(time.Duration(ttlSeconds) * time.Second)- session, err := s.sessionService.CreateFederatedSession(ctx, user.ID, accessTokenExpiry, credentialID)+ federatedSession, err := s.sessionService.CreateFederatedSession(ctx, user.ID, accessTokenExpiry, credentialID)if err != nil {return nil, err}@@ -1020,11 +1021,11 @@ func (s *AuthService) IssueFederatedToken(ctx context.Context, user *models.UserIssuedAt: jwt.NewNumericDate(now),ExpiresAt: jwt.NewNumericDate(accessTokenExpiry),},- SessionID: session.ID,+ SessionID: federatedSession.ID,UserID: user.ID,Username: user.Username,AppVersion: config.Version,- TokenType: models.UserSessionSourceFederated,+ TokenType: session.UserSessionSourceFederated,FederatedCredentialID: credentialID,}diff --git a/backend/internal/auth/service_test.go b/backend/internal/auth/service_test.goindex f40a4209c..fd1522f7f 100644--- a/backend/internal/auth/service_test.go+++ b/backend/internal/auth/service_test.go@@ -1,6 +1,12 @@package authimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"++ "github.com/getarcaneapp/arcane/backend/v2/internal/role"++ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"+"context""crypto/rand""testing"@@ -15,7 +21,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user"@@ -35,15 +40,15 @@ func setupAuthServiceTestDB(t *testing.T) *database.DB {require.NoError(t, err)sqlDB.SetMaxOpenConns(1)require.NoError(t, db.AutoMigrate(- &models.SettingVariable{},- &models.User{},- &models.UserSession{},- &models.Environment{},- &models.Role{},- &models.UserRoleAssignment{},- &models.ApiKey{},- &models.ApiKeyPermission{},- &models.OidcRoleMapping{},+ &settings.SettingVariable{},+ &common.User{},+ &session.UserSession{},+ &environment.Environment{},+ &role.Role{},+ &role.UserRoleAssignment{},+ &apikey.ApiKey{},+ &role.ApiKeyPermission{},+ &role.OidcRoleMapping{},))return &database.DB{DB: db}}@@ -153,7 +158,7 @@ func makeRefreshToken(t *testing.T, secret []byte, subject string, id string, exreturn signed}-func createTestSession(t *testing.T, db *database.DB, userID string, expiresAt time.Time) (*models.UserSession, string) {+func createTestSession(t *testing.T, db *database.DB, userID string, expiresAt time.Time) (*session.UserSession, string) {t.Helper()sessionSvc := session.NewSessionService(db)session, refreshJTI, err := sessionSvc.CreateSession(context.Background(), userID, expiresAt, auth.SessionMeta{@@ -183,8 +188,8 @@ func TestVerifyToken_ValidClaims(t *testing.T) {s.sessionService = session.NewSessionService(db)// Create user in DB- user := &models.User{- BaseModel: models.BaseModel{ID: "u123"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u123"},Username: "alice",Email: new("[email protected]"),DisplayName: new("Alice"),@@ -245,8 +250,8 @@ func TestVerifyToken_Expired(t *testing.T) {s.sessionService = session.NewSessionService(db)// Create user in DB- user := &models.User{- BaseModel: models.BaseModel{ID: "u1"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "bob",}_, err := userSvc.CreateUser(context.Background(), user)@@ -319,7 +324,7 @@ func TestGenerateUsernameFromEmail(t *testing.T) {func TestPersistOidcTokens_SetsFields(t *testing.T) {s := newTestAuthService("")- user := &models.User{}+ user := &common.User{}start := time.Now()resp := &auth.OidcTokenResponse{AccessToken: "at-123",@@ -374,8 +379,8 @@ func TestRefreshToken_Valid(t *testing.T) {s.settingsService = settingsSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-refresh"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-refresh"},Username: "refresh-user",}_, err = userSvc.CreateUser(context.Background(), user)@@ -405,8 +410,8 @@ func TestRefreshToken_VersionMismatchRotates(t *testing.T) {s.settingsService = settingsSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-versionmismatch"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-versionmismatch"},Username: "versionmismatch-user",}_, err = userSvc.CreateUser(context.Background(), user)@@ -451,8 +456,8 @@ func TestVerifyToken_RejectsRevokedSession(t *testing.T) {s.userService = userSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-revoked"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-revoked"},Username: "revoked-user",}_, err := userSvc.CreateUser(context.Background(), user)@@ -474,8 +479,8 @@ func TestVerifyToken_RejectsMissingSessionID(t *testing.T) {s.userService = userSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-no-sid"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-no-sid"},Username: "no-sid-user",}_, err := userSvc.CreateUser(context.Background(), user)@@ -494,8 +499,8 @@ func TestRevokeSessionThenVerifyTokenFails(t *testing.T) {s.userService = userSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-logout"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-logout"},Username: "logout-user",}_, err := userSvc.CreateUser(context.Background(), user)@@ -517,8 +522,8 @@ func TestVerifyToken_RejectsRevokedCachedSession(t *testing.T) {s.userService = userSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-cached-revoked"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-cached-revoked"},Username: "cached-revoked-user",}_, err := userSvc.CreateUser(context.Background(), user)@@ -546,8 +551,8 @@ func TestRefreshToken_RotatesJTI(t *testing.T) {s.settingsService = settingsSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-rotate"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-rotate"},Username: "rotate-user",}_, err = userSvc.CreateUser(context.Background(), user)@@ -575,8 +580,8 @@ func TestRefreshToken_RejectsRevokedSession(t *testing.T) {s.settingsService = settingsSvcs.sessionService = session.NewSessionService(db)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-refresh-revoked"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-refresh-revoked"},Username: "refresh-revoked-user",}_, err = userSvc.CreateUser(context.Background(), user)@@ -600,8 +605,8 @@ func TestChangePassword_RevokesAllSessions(t *testing.T) {passwordHash, err := userSvc.HashPassword("old-password")require.NoError(t, err)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-password"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-password"},Username: "password-user",PasswordHash: passwordHash,}@@ -630,8 +635,8 @@ func TestChangePassword_KeepsCurrentSessionAlive(t *testing.T) {passwordHash, err := userSvc.HashPassword("old-password")require.NoError(t, err)- user := &models.User{- BaseModel: models.BaseModel{ID: "u-keep"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "u-keep"},Username: "keep-user",PasswordHash: passwordHash,}@@ -779,8 +784,8 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailNotVerified_WithExistingUser_RetuserSvc := user.NewUserService(db)// Seed an existing local user with matching emailemail := "[email protected]"- existing := &models.User{- BaseModel: models.BaseModel{ID: "u1"},+ existing := &common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "existing",Email: &email,}@@ -821,8 +826,8 @@ func TestFindOrCreateOidcUser_MergeEnabled_EmailVerificationMissing_WithExistinguserSvc := user.NewUserService(db)// Seed an existing local user with matching emailemail := "[email protected]"- existing := &models.User{- BaseModel: models.BaseModel{ID: "u1"},+ existing := &common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "existing",Email: &email,}@@ -866,13 +871,13 @@ func TestAuthenticateLocalPrimary_EmailFallback(t *testing.T) {require.NoError(t, err)dupHash, err := userSvc.HashPassword("dup-two-pass!")require.NoError(t, err)- for _, u := range []*models.User{- {BaseModel: models.BaseModel{ID: "u-email-login"}, Username: "bob", Email: new("[email protected]"), PasswordHash: hash},- {BaseModel: models.BaseModel{ID: "u-dup-1"}, Username: "dup1", Email: new("[email protected]"), PasswordHash: hash},- {BaseModel: models.BaseModel{ID: "u-dup-2"}, Username: "dup2", Email: new("[email protected]"), PasswordHash: dupHash},- {BaseModel: models.BaseModel{ID: "u-carol"}, Username: "[email protected]", Email: new("[email protected]"), PasswordHash: hash},- {BaseModel: models.BaseModel{ID: "u-col-a"}, Username: "[email protected]", PasswordHash: hash},- {BaseModel: models.BaseModel{ID: "u-col-b"}, Username: "colb", Email: new("[email protected]"), PasswordHash: dupHash},+ for _, u := range []*common.User{+ {BaseModel: database.BaseModel{ID: "u-email-login"}, Username: "bob", Email: new("[email protected]"), PasswordHash: hash},+ {BaseModel: database.BaseModel{ID: "u-dup-1"}, Username: "dup1", Email: new("[email protected]"), PasswordHash: hash},+ {BaseModel: database.BaseModel{ID: "u-dup-2"}, Username: "dup2", Email: new("[email protected]"), PasswordHash: dupHash},+ {BaseModel: database.BaseModel{ID: "u-carol"}, Username: "[email protected]", Email: new("[email protected]"), PasswordHash: hash},+ {BaseModel: database.BaseModel{ID: "u-col-a"}, Username: "[email protected]", PasswordHash: hash},+ {BaseModel: database.BaseModel{ID: "u-col-b"}, Username: "colb", Email: new("[email protected]"), PasswordHash: dupHash},} {_, err = userSvc.CreateUser(context.Background(), u)require.NoError(t, err)diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.goindex e9f2452e1..bcfb9f033 100644--- a/backend/internal/bootstrap/bootstrap.go+++ b/backend/internal/bootstrap/bootstrap.go@@ -289,7 +289,7 @@ func initializeStartupState(p initializeStartupStateParams) {)startup.CleanupUnknownSettings(appCtx, p.Settings)- runRoleStartupTasks(appCtx, p.Role, cfg, cfg.AgentMode)+ runRoleStartupTasks(appCtx, p.Role, p.ApiKey, cfg, cfg.AgentMode)// Auto-pair only applies in Edge mode (where the agent's outbound tunnel is the// only path to the manager). Direct mode is passive — the manager dials the agent's@@ -321,7 +321,7 @@ func initializeGitOpsStartupStateInternal(appCtx context.Context, gitOpsSync *gi}}-func runRoleStartupTasks(ctx context.Context, roleService *role.RoleService, cfg *config.Config, agentMode bool) {+func runRoleStartupTasks(ctx context.Context, roleService *role.RoleService, apiKeyService *apikey.ApiKeyService, cfg *config.Config, agentMode bool) {if roleService == nil {return}@@ -334,8 +334,10 @@ func runRoleStartupTasks(ctx context.Context, roleService *role.RoleService, cfgif err := roleService.BackfillLegacyRoleAssignments(ctx); err != nil {slog.ErrorContext(ctx, "Failed to backfill legacy users.roles into user_role_assignments", "error", err)}- if err := roleService.BackfillApiKeyPermissions(ctx); err != nil {- slog.WarnContext(ctx, "Failed to backfill API key permissions", "error", err)+ if apiKeyService != nil {+ if err := apiKeyService.BackfillApiKeyPermissions(ctx); err != nil {+ slog.WarnContext(ctx, "Failed to backfill API key permissions", "error", err)+ }}if cfg != nil {if err := roleService.ReconcileEnvOidcMappings(ctx, cfg.OidcRoleMappings); err != nil {diff --git a/backend/internal/bootstrap/edge_bootstrap.go b/backend/internal/bootstrap/edge_bootstrap.goindex 39b983371..9cb08eda1 100644--- a/backend/internal/bootstrap/edge_bootstrap.go+++ b/backend/internal/bootstrap/edge_bootstrap.go@@ -1,6 +1,8 @@package bootstrapimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""encoding/json/v2""fmt"@@ -13,7 +15,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"notificationdto "github.com/getarcaneapp/arcane/types/v2/notification"@@ -62,17 +63,17 @@ func registerEdgeTunnelRoutes(return errors.WrapIf(err, "failed to dispatch edge notification")}- var metadata models.JSON+ var metadata database.JSONif len(evt.MetadataJSON) > 0 {- metadata = models.JSON{}+ metadata = database.JSON{}if err := json.Unmarshal(evt.MetadataJSON, &metadata); err != nil {return errors.WrapIf(err, "failed to decode event metadata")}}req := event.CreateEventRequest{- Type: models.EventType(evt.Type),- Severity: models.EventSeverity(evt.Severity),+ Type: event.EventType(evt.Type),+ Severity: event.EventSeverity(evt.Severity),Title: evt.Title,Description: evt.Description,ResourceType: optionalStringPtr(evt.ResourceType),@@ -123,7 +124,7 @@ func registerEdgeTunnelRoutes(envIDCopy := envIDenvNameCopy := envName_, _ = eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeEnvironmentMTLSEnroll,+ Type: event.EventTypeEnvironmentMTLSEnroll,Severity: edgeMTLSEnrollmentSeverityInternal(reenrolled),Title: "Edge mTLS enrollment",Description: "Edge agent completed mTLS enrollment from " + remoteAddr,@@ -131,7 +132,7 @@ func registerEdgeTunnelRoutes(ResourceID: &envIDCopy,ResourceName: &envNameCopy,EnvironmentID: &envIDCopy,- Metadata: models.JSON{"remoteAddr": remoteAddr, "reenrollment": reenrolled},+ Metadata: database.JSON{"remoteAddr": remoteAddr, "reenrollment": reenrolled},})createEdgeMTLSIssueEventsInternal(ctx, eventService, envIDCopy, envNameCopy, remoteAddr, certIssued, caGenerated, reenrolled)})@@ -169,16 +170,16 @@ func createEdgeMTLSIssueEventsInternal(ctx context.Context, eventService *event.}if caGenerated {_, _ = eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeEnvironmentMTLSCAGenerated,- Severity: models.EventSeverityInfo,+ Type: event.EventTypeEnvironmentMTLSCAGenerated,+ Severity: event.EventSeverityInfo,Title: "Edge mTLS CA generated",Description: "Arcane generated a new edge mTLS certificate authority",- Metadata: models.JSON{"remoteAddr": remoteAddr, "kind": "ca"},+ Metadata: database.JSON{"remoteAddr": remoteAddr, "kind": "ca"},})}if certIssued {_, _ = eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeEnvironmentMTLSCertIssued,+ Type: event.EventTypeEnvironmentMTLSCertIssued,Severity: edgeMTLSCertIssuedSeverityInternal(reenrolled),Title: "Edge mTLS certificate issued",Description: fmt.Sprintf("Arcane issued an edge mTLS client certificate for environment '%s'", envName),@@ -186,23 +187,23 @@ func createEdgeMTLSIssueEventsInternal(ctx context.Context, eventService *event.ResourceID: &envID,ResourceName: &envName,EnvironmentID: &envID,- Metadata: models.JSON{"remoteAddr": remoteAddr, "kind": "client", "reenrollment": reenrolled},+ Metadata: database.JSON{"remoteAddr": remoteAddr, "kind": "client", "reenrollment": reenrolled},})}}-func edgeMTLSEnrollmentSeverityInternal(reenrolled bool) models.EventSeverity {+func edgeMTLSEnrollmentSeverityInternal(reenrolled bool) event.EventSeverity {if reenrolled {- return models.EventSeverityWarning+ return event.EventSeverityWarning}- return models.EventSeverityInfo+ return event.EventSeverityInfo}-func edgeMTLSCertIssuedSeverityInternal(reenrolled bool) models.EventSeverity {+func edgeMTLSCertIssuedSeverityInternal(reenrolled bool) event.EventSeverity {if reenrolled {- return models.EventSeverityWarning+ return event.EventSeverityWarning}- return models.EventSeverityInfo+ return event.EventSeverityInfo}func optionalStringPtr(value string) *string {@@ -234,8 +235,8 @@ func handleEdgeStatusChange(ctx context.Context, environmentService *environment// re-register without the environment ever having gone offline (session// replacement, transport reconnects), and those are not worth an event.alreadyInState := env != nil &&- ((connected && env.Status == string(models.EnvironmentStatusOnline)) ||- (!connected && env.Status == string(models.EnvironmentStatusOffline)))+ ((connected && env.Status == string(environment.EnvironmentStatusOnline)) ||+ (!connected && env.Status == string(environment.EnvironmentStatusOffline)))if !alreadyInState {if err := createEdgeConnectionEvent(ctx, eventService, envID, envName, connected); err != nil {slog.WarnContext(ctx, "Failed to create edge connection event", "environment_id", envID, "connected", connected, "error", err)@@ -253,16 +254,16 @@ func createEdgeConnectionEvent(ctx context.Context, eventService *event.EventSerreturn nil}- eventType := models.EventTypeEnvironmentDisconnect+ eventType := event.EventTypeEnvironmentDisconnecttitle := "Edge Agent Disconnected"description := fmt.Sprintf("Edge agent for environment '%s' disconnected", envName)- severity := models.EventSeverityWarning+ severity := event.EventSeverityWarningif connected {- eventType = models.EventTypeEnvironmentConnect+ eventType = event.EventTypeEnvironmentConnecttitle = "Edge Agent Connected"description = fmt.Sprintf("Edge agent for environment '%s' connected", envName)- severity = models.EventSeveritySuccess+ severity = event.EventSeveritySuccess}_, err := eventService.CreateEvent(ctx, event.CreateEventRequest{diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.goindex 2fb328a90..71923e062 100644--- a/backend/internal/bootstrap/jobs_bootstrap.go+++ b/backend/internal/bootstrap/jobs_bootstrap.go@@ -13,7 +13,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/gitops""github.com/getarcaneapp/arcane/backend/v2/internal/job"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/system""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -242,7 +241,7 @@ type settingsEffectsSchedulerInternal interface {}type timeoutSettingsEnvironmentInternal interface {- ListRemoteEnvironments(ctx context.Context) ([]models.Environment, error)+ ListRemoteEnvironments(ctx context.Context) ([]environment.Environment, error)ProxyRequest(ctx context.Context, envID string, method string, path string, body []byte) ([]byte, int, error)}diff --git a/backend/internal/bootstrap/jobs_bootstrap_test.go b/backend/internal/bootstrap/jobs_bootstrap_test.goindex ee6234094..1539fef99 100644--- a/backend/internal/bootstrap/jobs_bootstrap_test.go+++ b/backend/internal/bootstrap/jobs_bootstrap_test.go@@ -1,6 +1,10 @@package bootstrapimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""slices""testing"@@ -8,7 +12,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler""github.com/stretchr/testify/require"@@ -47,9 +50,9 @@ type timeoutSyncEnvironmentStubInternal struct {started chan struct{}}-func (s *timeoutSyncEnvironmentStubInternal) ListRemoteEnvironments(context.Context) ([]models.Environment, error) {- return []models.Environment{{- BaseModel: models.BaseModel{ID: "remote"},+func (s *timeoutSyncEnvironmentStubInternal) ListRemoteEnvironments(context.Context) ([]environment.Environment, error) {+ return []environment.Environment{{+ BaseModel: database.BaseModel{ID: "remote"},Name: "remote",}}, nil}diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex e0eca1d12..1bc82c94d 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -1,6 +1,10 @@package bootstrapimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""log/slog""net"@@ -22,7 +26,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/federated""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie"@@ -105,7 +108,7 @@ func requestLoggerMiddlewareInternal() echo.MiddlewareFunc {}func createAuthValidatorInternal(deps api.HandlerDeps) middleware.AuthValidator {- resolveUser := func(ctx context.Context, user *models.User) *authz.PermissionSet {+ resolveUser := func(ctx context.Context, user *common.User) *authz.PermissionSet {ps, err := deps.Role.Service().ResolvePermissions(ctx, user)if err != nil || ps == nil {slog.WarnContext(ctx, "failed to resolve user permissions for env proxy", "error", err)@@ -121,14 +124,14 @@ func createAuthValidatorInternal(deps api.HandlerDeps) middleware.AuthValidator}return ps}- return func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *models.User, bool) {+ return func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *common.User, bool) {req := c.Request()// Check for API key authenticationif apiKey := req.Header.Get("X-Api-Key"); apiKey != "" {// User-owned API key: personal keys inherit the owner's role// permissions; scoped keys are limited to their own grants.if user, key, err := deps.ApiKey.Service().ValidateApiKeyWithID(ctx, apiKey); err == nil && user != nil {- if key != nil && key.Kind != models.ApiKeyKindPersonal {+ if key != nil && key.Kind != apikey.ApiKeyKindPersonal {return resolveKey(ctx, key.ID), user, true}return resolveUser(ctx, user), user, truediff --git a/backend/internal/build/model.go b/backend/internal/build/model.gonew file mode 100644index 000000000..f1ae411ce--- /dev/null+++ b/backend/internal/build/model.go@@ -0,0 +1,55 @@+package build++import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"++ "time"+)++type ImageBuildStatus string++const (+ ImageBuildStatusRunning ImageBuildStatus = "running"+ ImageBuildStatusSuccess ImageBuildStatus = "success"+ ImageBuildStatusFailed ImageBuildStatus = "failed"+)++type ImageBuild struct {+ database.BaseModel++ BuildArgs database.JSON `json:"buildArgs,omitempty" gorm:"column:build_args;type:text"`+ Labels database.JSON `json:"labels,omitempty" gorm:"column:labels;type:text"`+ Ulimits database.JSON `json:"ulimits,omitempty" gorm:"column:ulimits;type:text"`+ UserID *string `json:"userId,omitempty" gorm:"column:user_id"`+ Username *string `json:"username,omitempty" gorm:"column:username"`+ Digest *string `json:"digest,omitempty" gorm:"column:digest"`+ ErrorMessage *string `json:"errorMessage,omitempty" gorm:"column:error_message"`+ Output *string `json:"output,omitempty" gorm:"column:output;type:text"`+ CompletedAt *time.Time `json:"completedAt,omitempty" gorm:"column:completed_at" sortable:"true"`+ DurationMs *int64 `json:"durationMs,omitempty" gorm:"column:duration_ms"`+ EnvironmentID string `json:"environmentId" gorm:"column:environment_id;index"`+ Status ImageBuildStatus `json:"status" gorm:"column:status;index" sortable:"true"`+ Provider string `json:"provider,omitempty" gorm:"column:provider"`+ ContextDir string `json:"contextDir" gorm:"column:context_dir"`+ Dockerfile string `json:"dockerfile,omitempty" gorm:"column:dockerfile"`+ Target string `json:"target,omitempty" gorm:"column:target"`+ BuildNetwork string `json:"network,omitempty" gorm:"column:build_network"`+ Isolation string `json:"isolation,omitempty" gorm:"column:isolation"`+ Tags database.StringSlice `json:"tags,omitempty" gorm:"column:tags;type:text"`+ Platforms database.StringSlice `json:"platforms,omitempty" gorm:"column:platforms;type:text"`+ CacheFrom database.StringSlice `json:"cacheFrom,omitempty" gorm:"column:cache_from;type:text"`+ CacheTo database.StringSlice `json:"cacheTo,omitempty" gorm:"column:cache_to;type:text"`+ Entitlements database.StringSlice `json:"entitlements,omitempty" gorm:"column:entitlements;type:text"`+ ExtraHosts database.StringSlice `json:"extraHosts,omitempty" gorm:"column:extra_hosts;type:text"`+ ShmSize int64 `json:"shmSize,omitempty" gorm:"column:shm_size"`+ NoCache bool `json:"noCache" gorm:"column:no_cache;default:false"`+ Pull bool `json:"pull" gorm:"column:pull;default:false"`+ Privileged bool `json:"privileged" gorm:"column:privileged;default:false"`+ Push bool `json:"push" gorm:"column:push"`+ Load bool `json:"load" gorm:"column:load"`+ OutputTruncated bool `json:"outputTruncated" gorm:"column:output_truncated;default:false"`+}++func (ImageBuild) TableName() string {+ return "image_builds"+}diff --git a/backend/internal/build/service.go b/backend/internal/build/service.goindex 76dcad151..e8a63dc49 100644--- a/backend/internal/build/service.go+++ b/backend/internal/build/service.go@@ -1,6 +1,8 @@package buildimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""io"@@ -19,7 +21,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"buildgit "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil"@@ -91,7 +92,7 @@ func (s *BuildService) BuildSettings() buildtypes.BuildSettings {}}-func (s *BuildService) BuildImage(ctx context.Context, environmentID string, req buildtypes.BuildRequest, progressWriter io.Writer, serviceName string, user *models.User) (*buildtypes.BuildResult, error) {+func (s *BuildService) BuildImage(ctx context.Context, environmentID string, req buildtypes.BuildRequest, progressWriter io.Writer, serviceName string, user *common.User) (*buildtypes.BuildResult, error) {if s.builder == nil {return nil, errors.New("build service not available")}@@ -155,10 +156,10 @@ func (s *BuildService) BuildImage(ctx context.Context, environmentID string, req}}- status := models.ImageBuildStatusSuccess+ status := ImageBuildStatusSuccessvar errMsg *stringif err != nil {- status = models.ImageBuildStatusFailed+ status = ImageBuildStatusFailederrMsg = new(err.Error())}@@ -174,7 +175,7 @@ func (s *BuildService) BuildImage(ctx context.Context, environmentID string, reqreturn result, err}-func (s *BuildService) logBuildFailureEventInternal(ctx context.Context, environmentID string, req buildtypes.BuildRequest, serviceName, buildRecordID string, err error, user *models.User) {+func (s *BuildService) logBuildFailureEventInternal(ctx context.Context, environmentID string, req buildtypes.BuildRequest, serviceName, buildRecordID string, err error, user *common.User) {if s.eventService == nil || err == nil {return}@@ -194,7 +195,7 @@ func (s *BuildService) logBuildFailureEventInternal(ctx context.Context, environusername = user.Username}- metadata := models.JSON{+ metadata := database.JSON{"action": "build","provider": s.effectiveBuildProviderInternal(req.Provider),"contextDir": sanitizeBuildContextForEventInternal(req.ContextDir),@@ -208,7 +209,7 @@ func (s *BuildService) logBuildFailureEventInternal(ctx context.Context, environmetadata["buildRecordId"] = buildRecordID}- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", resourceName, userID, username, environmentID, err, metadata)+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", resourceName, userID, username, environmentID, err, metadata)}func sanitizeBuildContextForEventInternal(raw string) string {@@ -404,10 +405,10 @@ func (s *BuildService) ListImageBuildsByEnvironmentPaginated(ctx context.Contextreturn nil, pagination.Response{}, errors.New("build history not available")}- var builds []models.ImageBuild+ var builds []ImageBuild// The list DTO never includes the build output (buildToRecord with// includeOutput=false), so skip reading the up-to-2-MiB output column.- q := s.db.WithContext(ctx).Model(&models.ImageBuild{}).Omit("output").Where("environment_id = ?", environmentID)+ q := s.db.WithContext(ctx).Model(&ImageBuild{}).Omit("output").Where("environment_id = ?", environmentID)if term := strings.TrimSpace(params.Search); term != "" {searchPattern := "%" + term + "%"@@ -442,7 +443,7 @@ func (s *BuildService) GetImageBuildByID(ctx context.Context, environmentID, buireturn nil, errors.New("build history not available")}- var build models.ImageBuild+ var build ImageBuildif err := s.db.WithContext(ctx).First(&build, "id = ? AND environment_id = ?", buildID, environmentID).Error; err != nil {return nil, err}@@ -450,7 +451,7 @@ func (s *BuildService) GetImageBuildByID(ctx context.Context, environmentID, buireturn new(buildToRecord(build, true)), nil}-func (s *BuildService) createBuildRecord(ctx context.Context, environmentID string, req buildtypes.BuildRequest, user *models.User) (*models.ImageBuild, error) {+func (s *BuildService) createBuildRecord(ctx context.Context, environmentID string, req buildtypes.BuildRequest, user *common.User) (*ImageBuild, error) {buildArgs := mapToJSON(req.BuildArgs)labels := mapToJSON(req.Labels)ulimits := mapToJSON(req.Ulimits)@@ -462,33 +463,33 @@ func (s *BuildService) createBuildRecord(ctx context.Context, environmentID striusername = &user.Username}- record := &models.ImageBuild{+ record := &ImageBuild{EnvironmentID: environmentID,UserID: userID,Username: username,- Status: models.ImageBuildStatusRunning,+ Status: ImageBuildStatusRunning,Provider: req.Provider,ContextDir: req.ContextDir,Dockerfile: req.Dockerfile,Target: req.Target,- Tags: models.StringSlice(req.Tags),- Platforms: models.StringSlice(req.Platforms),+ Tags: database.StringSlice(req.Tags),+ Platforms: database.StringSlice(req.Platforms),BuildArgs: buildArgs,Labels: labels,- CacheFrom: models.StringSlice(req.CacheFrom),- CacheTo: models.StringSlice(req.CacheTo),+ CacheFrom: database.StringSlice(req.CacheFrom),+ CacheTo: database.StringSlice(req.CacheTo),NoCache: req.NoCache,Pull: req.Pull,BuildNetwork: req.Network,Isolation: req.Isolation,ShmSize: req.ShmSize,Ulimits: ulimits,- Entitlements: models.StringSlice(req.Entitlements),+ Entitlements: database.StringSlice(req.Entitlements),Privileged: req.Privileged,- ExtraHosts: models.StringSlice(req.ExtraHosts),+ ExtraHosts: database.StringSlice(req.ExtraHosts),Push: req.Push,Load: req.Load,- BaseModel: models.BaseModel{+ BaseModel: database.BaseModel{CreatedAt: time.Now(),},}@@ -503,7 +504,7 @@ func (s *BuildService) createBuildRecord(ctx context.Context, environmentID strifunc (s *BuildService) completeBuildRecord(ctx context.Context,buildID string,- status models.ImageBuildStatus,+ status ImageBuildStatus,output *string,outputTruncated bool,errMsg *string,@@ -528,7 +529,7 @@ func (s *BuildService) completeBuildRecord(}return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- result := tx.Model(&models.ImageBuild{}).Where("id = ?", buildID).Updates(updates)+ result := tx.Model(&ImageBuild{}).Where("id = ?", buildID).Updates(updates)if result.Error != nil {return errors.WrapIf(result.Error, "failed to update build record")}@@ -539,7 +540,7 @@ func (s *BuildService) completeBuildRecord(})}-func buildToRecord(build models.ImageBuild, includeOutput bool) imagetypes.BuildRecord {+func buildToRecord(build ImageBuild, includeOutput bool) imagetypes.BuildRecord {buildArgs := jsonToStringMap(build.BuildArgs)labels := jsonToStringMap(build.Labels)ulimits := jsonToStringMap(build.Ulimits)@@ -586,12 +587,12 @@ func buildToRecord(build models.ImageBuild, includeOutput bool) imagetypes.Build}}-func mapToJSON(input map[string]string) models.JSON {+func mapToJSON(input map[string]string) database.JSON {if len(input) == 0 {return nil}- out := models.JSON{}+ out := database.JSON{}for key, value := range input {out[key] = value}@@ -603,7 +604,7 @@ func mapToJSON(input map[string]string) models.JSON {return out}-func jsonToStringMap(input models.JSON) map[string]string {+func jsonToStringMap(input database.JSON) map[string]string {out := map[string]string{}for key, value := range input {out[key] = fmt.Sprint(value)diff --git a/backend/internal/build/service_test.go b/backend/internal/build/service_test.goindex 9dd272b2e..19ab58614 100644--- a/backend/internal/build/service_test.go+++ b/backend/internal/build/service_test.go@@ -1,6 +1,8 @@package buildimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"bytes""context""encoding/json/v2"@@ -16,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"buildgit "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/libtnb/sqlite"@@ -175,7 +176,7 @@ func TestBuildService_ResolveBuildRequest_RejectsNonGitHTTPContextViaProbeFailurfunc TestBuildService_ResolveBuildRequest_UsesSavedGitCredentials(t *testing.T) {gormDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, gormDB.AutoMigrate(&models.GitRepository{}))+ require.NoError(t, gormDB.AutoMigrate(&gitrepo.GitRepository{}))crypto.InitEncryption(&crypto.Config{Environment: string(config.AppEnvironmentTest),EncryptionKey: "test-encryption-key-for-testing-32bytes-min",@@ -183,7 +184,7 @@ func TestBuildService_ResolveBuildRequest_UsesSavedGitCredentials(t *testing.T)db := &database.DB{DB: gormDB}repoService := gitrepo.NewGitRepositoryService(db, t.TempDir(), nil, nil)- createTestGitRepository(t, db, models.GitRepository{+ createTestGitRepository(t, db, gitrepo.GitRepository{Name: "private-http",URL: "https://github.com/getarcaneapp/private-build.git",AuthType: "http",@@ -192,7 +193,7 @@ func TestBuildService_ResolveBuildRequest_UsesSavedGitCredentials(t *testing.T)SSHHostKeyVerification: "accept_new",Enabled: true,})- createTestGitRepository(t, db, models.GitRepository{+ createTestGitRepository(t, db, gitrepo.GitRepository{Name: "private-ssh",URL: "[email protected]:getarcaneapp/private-ssh.git",AuthType: "ssh",@@ -290,7 +291,7 @@ func TestBuildService_BuildImage_PreservesRemoteSourceInHistory(t *testing.T) {require.NoError(t, err)assert.Equal(t, repoPath, captured.ContextDir)- var record models.ImageBuild+ var record ImageBuildrequire.NoError(t, db.WithContext(context.Background()).First(&record).Error)assert.Equal(t, req.ContextDir, record.ContextDir)}@@ -307,8 +308,8 @@ func TestBuildService_BuildImage_FailureRecordsHistoryAndEvent(t *testing.T) {err: buildErr,},}- user := &models.User{- BaseModel: models.BaseModel{ID: "user-1"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "user-1"},Username: "tester",}@@ -323,23 +324,23 @@ func TestBuildService_BuildImage_FailureRecordsHistoryAndEvent(t *testing.T) {_, err = svc.BuildImage(context.Background(), "0", req, nil, "web", user)require.ErrorIs(t, err, buildErr)- var record models.ImageBuild+ var record ImageBuildrequire.NoError(t, db.WithContext(context.Background()).First(&record).Error)- assert.Equal(t, models.ImageBuildStatusFailed, record.Status)+ assert.Equal(t, ImageBuildStatusFailed, record.Status)require.NotNil(t, record.ErrorMessage)assert.Contains(t, *record.ErrorMessage, "docker exporter")- var event models.Event- require.NoError(t, db.WithContext(context.Background()).First(&event, "type = ?", models.EventTypeImageError).Error)- assert.Equal(t, models.EventSeverityError, event.Severity)- require.NotNil(t, event.ResourceName)- assert.Equal(t, "arcane.local/demo:test", *event.ResourceName)- assert.Equal(t, "build", event.Metadata["action"])- assert.Equal(t, "local", event.Metadata["provider"])- assert.Equal(t, "/builds/demo", event.Metadata["contextDir"])- assert.Contains(t, event.Metadata["error"], "docker exporter")- require.NotEmpty(t, event.Metadata["buildRecordId"])- assert.Equal(t, record.ID, event.Metadata["buildRecordId"])+ var evt event.Event+ require.NoError(t, db.WithContext(context.Background()).First(&evt, "type = ?", event.EventTypeImageError).Error)+ assert.Equal(t, event.EventSeverityError, evt.Severity)+ require.NotNil(t, evt.ResourceName)+ assert.Equal(t, "arcane.local/demo:test", *evt.ResourceName)+ assert.Equal(t, "build", evt.Metadata["action"])+ assert.Equal(t, "local", evt.Metadata["provider"])+ assert.Equal(t, "/builds/demo", evt.Metadata["contextDir"])+ assert.Contains(t, evt.Metadata["error"], "docker exporter")+ require.NotEmpty(t, evt.Metadata["buildRecordId"])+ assert.Equal(t, record.ID, evt.Metadata["buildRecordId"])}func TestBuildService_BuildImage_FailureExporterErrorsAppearInOutputHistoryAndEvent(t *testing.T) {@@ -363,8 +364,8 @@ func TestBuildService_BuildImage_FailureExporterErrorsAppearInOutputHistoryAndEv},}- user := &models.User{- BaseModel: models.BaseModel{ID: "user-2"},+ user := &common.User{+ BaseModel: database.BaseModel{ID: "user-2"},Username: "registry-test",}@@ -379,31 +380,31 @@ func TestBuildService_BuildImage_FailureExporterErrorsAppearInOutputHistoryAndEv_, err = svc.BuildImage(context.Background(), "0", req, progress, "web", user)require.ErrorIs(t, err, buildErr)- var record models.ImageBuild+ var record ImageBuildrequire.NoError(t, db.WithContext(context.Background()).First(&record).Error)- assert.Equal(t, models.ImageBuildStatusFailed, record.Status)+ assert.Equal(t, ImageBuildStatusFailed, record.Status)require.NotNil(t, record.Output)assert.Contains(t, *record.Output, buildErr.Error())require.NotNil(t, record.ErrorMessage)assert.Contains(t, *record.ErrorMessage, "exporter \"image\"")- var event models.Event- require.NoError(t, db.WithContext(context.Background()).First(&event, "type = ?", models.EventTypeImageError).Error)- assert.Equal(t, models.EventSeverityError, event.Severity)- require.NotNil(t, event.ResourceName)- assert.Equal(t, "ghcr.io/getarcaneapp/arcane:test", *event.ResourceName)- assert.Equal(t, "build", event.Metadata["action"])- assert.Equal(t, "depot", event.Metadata["provider"])- assert.Equal(t, "/builds/demo", event.Metadata["contextDir"])- assert.Equal(t, buildErr.Error(), event.Metadata["error"])+ var evt event.Event+ require.NoError(t, db.WithContext(context.Background()).First(&evt, "type = ?", event.EventTypeImageError).Error)+ assert.Equal(t, event.EventSeverityError, evt.Severity)+ require.NotNil(t, evt.ResourceName)+ assert.Equal(t, "ghcr.io/getarcaneapp/arcane:test", *evt.ResourceName)+ assert.Equal(t, "build", evt.Metadata["action"])+ assert.Equal(t, "depot", evt.Metadata["provider"])+ assert.Equal(t, "/builds/demo", evt.Metadata["contextDir"])+ assert.Equal(t, buildErr.Error(), evt.Metadata["error"])// The progress writer is the wire transport: raw builder text arrives framed// as {"log":...} NDJSON lines.var frame map[string]stringrequire.NoError(t, json.Unmarshal([]byte(strings.TrimSpace(progress.String())), &frame))assert.Equal(t, buildErr.Error(), frame["log"])assert.Equal(t, buildErr.Error(), *record.ErrorMessage)- assert.NotEmpty(t, event.Metadata["buildRecordId"])- assert.Equal(t, record.ID, event.Metadata["buildRecordId"])+ assert.NotEmpty(t, evt.Metadata["buildRecordId"])+ assert.Equal(t, record.ID, evt.Metadata["buildRecordId"])}func TestSanitizeBuildContextForEventInternal_RedactsURLCredentials(t *testing.T) {@@ -445,10 +446,10 @@ func TestBuildService_ListImageBuilds_OmitsOutputColumn(t *testing.T) {svc := &BuildService{db: db}output := "large build output"- require.NoError(t, db.WithContext(context.Background()).Create(&models.ImageBuild{- BaseModel: models.BaseModel{ID: "build-omit-output"},+ require.NoError(t, db.WithContext(context.Background()).Create(&ImageBuild{+ BaseModel: database.BaseModel{ID: "build-omit-output"},EnvironmentID: "0",- Status: models.ImageBuildStatusSuccess,+ Status: ImageBuildStatusSuccess,ContextDir: "/ctx",Output: &output,}).Error)@@ -472,13 +473,13 @@ func setupBuildHistoryTestDB() (*database.DB, error) {if err != nil {return nil, err}- if err := db.AutoMigrate(&models.ImageBuild{}, &models.Event{}); err != nil {+ if err := db.AutoMigrate(&ImageBuild{}, &event.Event{}); err != nil {return nil, err}return &database.DB{DB: db}, nil}-func createTestGitRepository(t *testing.T, db *database.DB, repository models.GitRepository) {+func createTestGitRepository(t *testing.T, db *database.DB, repository gitrepo.GitRepository) {t.Helper()require.NoError(t, db.WithContext(context.Background()).Create(&repository).Error)}diff --git a/backend/internal/build/workspace_service_test.go b/backend/internal/build/workspace_service_test.goindex ca32362a9..de8c26f67 100644--- a/backend/internal/build/workspace_service_test.go+++ b/backend/internal/build/workspace_service_test.go@@ -9,7 +9,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/libtnb/sqlite""github.com/stretchr/testify/require"@@ -39,7 +38,7 @@ func setupSettingsTestDB(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))return &database.DB{DB: db}}diff --git a/backend/internal/models/errors.go b/backend/internal/common/api_error.gosimilarity index 89%rename from backend/internal/models/errors.gorename to backend/internal/common/api_error.goindex 43ee73080..0853cd4e6 100644--- a/backend/internal/models/errors.go+++ b/backend/internal/common/api_error.go@@ -1,12 +1,10 @@-package models+package commonimport (stderrors "errors""net/http""emperror.dev/errors"-- "github.com/getarcaneapp/arcane/backend/v2/internal/common")type APIErrorCode string@@ -98,7 +96,7 @@ func ToAPIError(err error) *APIError {}switch {- case errors.Is(err, common.ErrValidation):+ case errors.Is(err, ErrValidation):details := make(map[string]any)keyValues := errors.GetDetails(err)for i := 0; i+1 < len(keyValues); i += 2 {@@ -111,19 +109,19 @@ func ToAPIError(err error) *APIError {details = nil}return NewAPIErrorWithDetails(err.Error(), APIErrorCodeValidationError, http.StatusBadRequest, details)- case errors.Is(err, common.ErrBadRequest):+ case errors.Is(err, ErrBadRequest):return NewAPIError(err.Error(), APIErrorCodeBadRequest, http.StatusBadRequest)- case errors.Is(err, common.ErrUnauthorized):+ case errors.Is(err, ErrUnauthorized):return NewAPIError(err.Error(), APIErrorCodeUnauthorized, http.StatusUnauthorized)- case errors.Is(err, common.ErrForbidden):+ case errors.Is(err, ErrForbidden):return NewAPIError(err.Error(), APIErrorCodeForbidden, http.StatusForbidden)- case errors.Is(err, common.ErrNotFound):+ case errors.Is(err, ErrNotFound):return NewAPIError(err.Error(), APIErrorCodeNotFound, http.StatusNotFound)- case errors.Is(err, common.ErrConflict):+ case errors.Is(err, ErrConflict):return NewAPIError(err.Error(), APIErrorCodeConflict, http.StatusConflict)- case errors.Is(err, common.ErrTimeout):+ case errors.Is(err, ErrTimeout):return NewAPIError(err.Error(), APIErrorCodeTimeout, http.StatusGatewayTimeout)- case errors.Is(err, common.ErrUnavailable):+ case errors.Is(err, ErrUnavailable):return NewAPIError(err.Error(), APIErrorCodeInternalServerError, http.StatusServiceUnavailable)}diff --git a/backend/internal/models/errors_test.go b/backend/internal/common/api_error_test.gosimilarity index 80%rename from backend/internal/models/errors_test.gorename to backend/internal/common/api_error_test.goindex 7d31c248f..832e87c64 100644--- a/backend/internal/models/errors_test.go+++ b/backend/internal/common/api_error_test.go@@ -1,17 +1,16 @@-package models+package commonimport ("net/http""testing""emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/stretchr/testify/require")func TestToAPIErrorMapsClassifiedValidationDetails(t *testing.T) {err := errors.WithDetails(errors.New("Name is required"), "field", "name")- err = common.Classify(common.ErrValidation, err)+ err = Classify(ErrValidation, err)apiErr := ToAPIError(err)diff --git a/backend/internal/models/user.go b/backend/internal/common/user.gosimilarity index 85%rename from backend/internal/models/user.gorename to backend/internal/common/user.goindex e2bd31e7f..91b06e614 100644--- a/backend/internal/models/user.go+++ b/backend/internal/common/user.go@@ -1,6 +1,8 @@-package models+package commonimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""time"@@ -8,7 +10,7 @@ import ()type User struct {- BaseModel+ database.BaseModelUsername string `json:"username" sortable:"true"`PasswordHash string `json:"-" gorm:"column:password_hash"`@@ -38,7 +40,7 @@ func (User) TableName() string {}// CurrentUserContextKey is the context key holding the authenticated user-// model, set via context.WithValue(ctx, models.CurrentUserContextKey{}, user).+// model, set via context.WithValue(ctx, common.CurrentUserContextKey{}, user).// It lives here (rather than in transport middleware) so that services, which cannot// import the middleware package, can read the requesting user for per-user// preferences.@@ -50,3 +52,10 @@ func CurrentUserFromContext(ctx context.Context) (*User, bool) {u, ok := ctx.Value(CurrentUserContextKey{}).(*User)return u, ok}++// SystemUser is the actor recorded for work Arcane performs on its own behalf —+// scheduled jobs, startup reconciliation, GitOps syncs — rather than in response+// to a signed-in user.+var SystemUser = User{+ Username: "System",+}diff --git a/backend/internal/config/schema/schema.go b/backend/internal/config/schema/schema.goindex a2f7d07d6..14de524ab 100644--- a/backend/internal/config/schema/schema.go+++ b/backend/internal/config/schema/schema.go@@ -18,7 +18,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils")@@ -27,7 +26,7 @@ const (schemaVersion = 1sourceFileConfig = "backend/internal/config/config.go"sourceFileBuildablesConfig = "backend/internal/config/buildables_config.go"- sourceFileSettings = "backend/internal/models/settings.go"+ sourceFileSettings = "backend/internal/settings/model.go"sourceSymbolConfig = "config.Config"sourceSymbolBuildablesConfig = "config.BuildablesConfig")@@ -279,7 +278,7 @@ func parseStructEnvFieldsInternal(filename, structName string, opts envFieldOptifunc collectSettingEnvOverridesInternal() ([]SettingOverrideEntry, error) {defaults := settings.DefaultSettingsConfig()- settingsType := reflect.TypeFor[models.Settings]()+ settingsType := reflect.TypeFor[settings.Settings]()entries := make([]SettingOverrideEntry, 0, settingsType.NumField())for field := range settingsType.Fields() {@@ -331,9 +330,9 @@ func collectSettingEnvOverridesInternal() ([]SettingOverrideEntry, error) {Public: isPublic,Requires: requires,Note: rule.note,- Source: "models.Settings + settings.DefaultSettingsConfig",+ Source: "settings.Settings + settings.DefaultSettingsConfig",SourceFile: sourceFileSettings,- SourceSymbol: "models.Settings." + field.Name,+ SourceSymbol: "settings.Settings." + field.Name,})}diff --git a/backend/internal/config/schema/schema_test.go b/backend/internal/config/schema/schema_test.goindex 3739af693..10424d60a 100644--- a/backend/internal/config/schema/schema_test.go+++ b/backend/internal/config/schema/schema_test.go@@ -1,13 +1,14 @@package schemaimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"reflect""slices""sort""strings""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -64,7 +65,7 @@ func TestGenerate_SettingEnvOverridesMatchModelMetadata(t *testing.T) {assert.Equal(t, "30", dockerTimeout.DefaultValue)assert.Equal(t, "number", dockerTimeout.Type)assert.Equal(t, "timeouts", dockerTimeout.Category)- assert.Equal(t, "models.Settings + settings.DefaultSettingsConfig", dockerTimeout.Source)+ assert.Equal(t, "settings.Settings + settings.DefaultSettingsConfig", dockerTimeout.Source)oidcSecret, ok := entries["oidcClientSecret"]require.True(t, ok)@@ -168,7 +169,7 @@ func sortedCategoryEnvPairs(entries []SettingOverrideEntry) []string {}func countDocumentedSettingOverrides() int {- settingsType := reflect.TypeFor[models.Settings]()+ settingsType := reflect.TypeFor[settings.Settings]()count := 0for field := range settingsType.Fields() {diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.goindex c4abd3b71..e542841dc 100644--- a/backend/internal/container/handler.go+++ b/backend/internal/container/handler.go@@ -1,6 +1,10 @@package containerimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""fmt""io"@@ -9,12 +13,13 @@ import ("net/netip""strings"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -606,12 +611,12 @@ func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainerfunc (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{- ActivityType: models.ActivityTypeContainerStart,+ ActivityType: activitytypes.TypeContainerStart,Step: "Starting container",StartMessage: "Container start requested",CompleteMessage: "Container started",SuccessMessage: "Container started successfully",- Action: func(runtimeCtx context.Context, containerID string, user models.User) error {+ Action: func(runtimeCtx context.Context, containerID string, user common.User) error {return h.containerService.StartContainer(runtimeCtx, containerID, user)},Error: func(err error) error {@@ -622,12 +627,12 @@ func (h *ContainerHandler) StartContainer(ctx context.Context, input *ContainerAfunc (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{- ActivityType: models.ActivityTypeContainerStop,+ ActivityType: activitytypes.TypeContainerStop,Step: "Stopping container",StartMessage: "Container stop requested",CompleteMessage: "Container stopped",SuccessMessage: "Container stopped successfully",- Action: func(runtimeCtx context.Context, containerID string, user models.User) error {+ Action: func(runtimeCtx context.Context, containerID string, user common.User) error {return h.containerService.StopContainer(runtimeCtx, containerID, user)},Error: func(err error) error {@@ -638,12 +643,12 @@ func (h *ContainerHandler) StopContainer(ctx context.Context, input *ContainerAcfunc (h *ContainerHandler) RestartContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{- ActivityType: models.ActivityTypeContainerRestart,+ ActivityType: activitytypes.TypeContainerRestart,Step: "Restarting container",StartMessage: "Container restart requested",CompleteMessage: "Container restarted",SuccessMessage: "Container restarted successfully",- Action: func(runtimeCtx context.Context, containerID string, user models.User) error {+ Action: func(runtimeCtx context.Context, containerID string, user common.User) error {return h.containerService.RestartContainer(runtimeCtx, containerID, user)},Error: func(err error) error {@@ -655,12 +660,12 @@ func (h *ContainerHandler) RestartContainer(ctx context.Context, input *Containefunc (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContainerInput) (*ContainerActionOutput, error) {signal := strings.TrimSpace(input.Signal)return h.runContainerActionInternal(ctx, &ContainerActionInput{EnvironmentID: input.EnvironmentID, ContainerID: input.ContainerID}, containerActionConfigInternal{- ActivityType: models.ActivityTypeContainerKill,+ ActivityType: activitytypes.TypeContainerKill,Step: "Killing container",StartMessage: "Container kill requested",CompleteMessage: "Container killed",SuccessMessage: "Container killed successfully",- Action: func(runtimeCtx context.Context, containerID string, user models.User) error {+ Action: func(runtimeCtx context.Context, containerID string, user common.User) error {return h.containerService.KillContainer(runtimeCtx, containerID, signal, user)},Error: func(err error) error {@@ -671,12 +676,12 @@ func (h *ContainerHandler) KillContainer(ctx context.Context, input *KillContainfunc (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{- ActivityType: models.ActivityTypeContainerPause,+ ActivityType: activitytypes.TypeContainerPause,Step: "Pausing container",StartMessage: "Container pause requested",CompleteMessage: "Container paused",SuccessMessage: "Container paused successfully",- Action: func(runtimeCtx context.Context, containerID string, user models.User) error {+ Action: func(runtimeCtx context.Context, containerID string, user common.User) error {return h.containerService.PauseContainer(runtimeCtx, containerID, user)},Error: func(err error) error {@@ -687,12 +692,12 @@ func (h *ContainerHandler) PauseContainer(ctx context.Context, input *ContainerAfunc (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *ContainerActionInput) (*ContainerActionOutput, error) {return h.runContainerActionInternal(ctx, input, containerActionConfigInternal{- ActivityType: models.ActivityTypeContainerUnpause,+ ActivityType: activitytypes.TypeContainerUnpause,Step: "Unpausing container",StartMessage: "Container unpause requested",CompleteMessage: "Container unpaused",SuccessMessage: "Container unpaused successfully",- Action: func(runtimeCtx context.Context, containerID string, user models.User) error {+ Action: func(runtimeCtx context.Context, containerID string, user common.User) error {return h.containerService.UnpauseContainer(runtimeCtx, containerID, user)},Error: func(err error) error {@@ -702,12 +707,12 @@ func (h *ContainerHandler) UnpauseContainer(ctx context.Context, input *Containe}type containerActionConfigInternal struct {- ActivityType models.ActivityType+ ActivityType activitytypes.TypeStep stringStartMessage stringCompleteMessage stringSuccessMessage string- Action func(context.Context, string, models.User) error+ Action func(context.Context, string, common.User) errorError func(error) error}@@ -718,7 +723,7 @@ func (h *ContainerHandler) runContainerActionInternal(ctx context.Context, input}runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, cfg.ActivityType, "container", input.ContainerID, input.ContainerID, user, cfg.Step, cfg.StartMessage, models.JSON{"containerID": input.ContainerID}, false)+ activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, cfg.ActivityType, "container", input.ContainerID, input.ContainerID, user, cfg.Step, cfg.StartMessage, database.JSON{"containerID": input.ContainerID}, false)if err := cfg.Action(runtimeCtx, input.ContainerID, *user); err != nil {activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, cfg.CompleteMessage, err)return nil, cfg.Error(err)@@ -763,7 +768,7 @@ func (h *ContainerHandler) RedeployContainer(ctx context.Context, input *Contain}runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerRedeploy, "container", input.ContainerID, input.ContainerID, user, "Starting redeploy", "Container redeploy requested", models.JSON{"containerID": input.ContainerID}, true)+ activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeContainerRedeploy, "container", input.ContainerID, input.ContainerID, user, "Starting redeploy", "Container redeploy requested", database.JSON{"containerID": input.ContainerID}, true)activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, input.EnvironmentID)activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Redeploying container")redeployCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)@@ -809,7 +814,7 @@ func (h *ContainerHandler) DeleteContainer(ctx context.Context, input *DeleteCon}runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeContainerDelete, "container", input.ContainerID, input.ContainerID, user, "Deleting container", "Container delete requested", models.JSON{"containerID": input.ContainerID, "force": input.Force, "removeVolumes": input.RemoveVolumes}, false)+ activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeContainerDelete, "container", input.ContainerID, input.ContainerID, user, "Deleting container", "Container delete requested", database.JSON{"containerID": input.ContainerID, "force": input.Force, "removeVolumes": input.RemoveVolumes}, false)if err := h.containerService.DeleteContainer(runtimeCtx, input.ContainerID, input.Force, input.RemoveVolumes, *user); err != nil {activitylib.CompleteHandlerActivity(runtimeCtx, h.activityService, activityID, "Container deleted", err)return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete container").Error())diff --git a/backend/internal/container/service.go b/backend/internal/container/service.goindex 38cc290de..218068813 100644--- a/backend/internal/container/service.go+++ b/backend/internal/container/service.go@@ -1,6 +1,10 @@package containerimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""encoding/json/jsontext""encoding/json/v2"@@ -23,7 +27,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -157,7 +160,7 @@ func shouldStartRedeployedContainerInternal(containerInfo container.InspectResporeturn shouldStart}-func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerClient *client.Client, imageName, containerID, containerName string, user models.User) error {+func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerClient *client.Client, imageName, containerID, containerName string, user common.User) error {settings := s.settingsService.GetSettingsConfig()pullCtx, pullCancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.DockerImagePullTimeout.AsInt(), timeouts.DefaultDockerImagePull))defer pullCancel()@@ -182,7 +185,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, docker}if pullErr != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "redeploy","step": "pull_image_timeout","image": imageName,@@ -190,7 +193,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerreturn errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", imageName)}- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "redeploy","step": "pull_image","image": imageName,@@ -205,7 +208,7 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerstreamErr := dockerutils.RenderJSONMessageStream(reader, logWriter)if streamErr != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", streamErr, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "redeploy","step": "complete_pull","image": imageName,@@ -216,10 +219,10 @@ func (s *ContainerService) pullRedeployImageInternal(ctx context.Context, dockerreturn nil}-func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName string, wasRunning bool, user models.User) error {+func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName string, wasRunning bool, user common.User) error {if containerName != "" {if _, err := dockerClient.ContainerRename(ctx, containerID, client.ContainerRenameOptions{NewName: backupName}); err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "rename_old","backupName": backupName,@@ -239,24 +242,24 @@ func (s *ContainerService) prepareContainerForRedeployInternal(ctx context.Conteif containerName != "" {if _, renameErr := dockerClient.ContainerRename(ctx, containerID, client.ContainerRenameOptions{NewName: containerName}); renameErr != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", renameErr, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", renameErr, database.JSON{"action": "redeploy","step": "restore_name_after_stop_failure",})}}- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "stop",})return errors.WrapIf(err, "failed to stop container")}-func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName, failedStep string, wasRunning bool, user models.User) {+func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx context.Context, dockerClient *client.Client, containerID, containerName, backupName, failedStep string, wasRunning bool, user common.User) {if wasRunning {if _, startErr := dockerClient.ContainerStart(ctx, containerID, client.ContainerStartOptions{}); startErr != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", startErr, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", startErr, database.JSON{"action": "redeploy","step": "restore_start_original","failedStep": failedStep,@@ -269,7 +272,7 @@ func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx cont}if _, renameErr := dockerClient.ContainerRename(ctx, containerID, client.ContainerRenameOptions{NewName: containerName}); renameErr != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, backupName, user.ID, user.Username, "0", renameErr, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, backupName, user.ID, user.Username, "0", renameErr, database.JSON{"action": "redeploy","step": "restore_name","failedStep": failedStep,@@ -279,20 +282,20 @@ func (s *ContainerService) restoreContainerAfterRedeployFailureInternal(ctx conttype containerLifecycleActionInternal struct {action string- eventType models.EventType- metadata models.JSON+ eventType event.EventType+ metadata database.JSONwarnOnLogError boolrunContainerAction func(*client.Client) error}-func (s *ContainerService) runContainerLifecycleActionInternal(ctx context.Context, containerID string, user models.User, cfg containerLifecycleActionInternal) error {+func (s *ContainerService) runContainerLifecycleActionInternal(ctx context.Context, containerID string, user common.User, cfg containerLifecycleActionInternal) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": cfg.action})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": cfg.action})return errors.WrapIf(err, "failed to connect to Docker")}- metadata := models.JSON{+ metadata := database.JSON{"action": cfg.action,"containerId": containerID,}@@ -308,15 +311,15 @@ func (s *ContainerService) runContainerLifecycleActionInternal(ctx context.Conteerr = cfg.runContainerAction(dockerClient)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": cfg.action})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": cfg.action})}return err}-func (s *ContainerService) StartContainer(ctx context.Context, containerID string, user models.User) error {+func (s *ContainerService) StartContainer(ctx context.Context, containerID string, user common.User) error {return s.runContainerLifecycleActionInternal(ctx, containerID, user, containerLifecycleActionInternal{action: "start",- eventType: models.EventTypeContainerStart,+ eventType: event.EventTypeContainerStart,warnOnLogError: true,runContainerAction: func(dockerClient *client.Client) error {_, err := dockerClient.ContainerStart(ctx, containerID, client.ContainerStartOptions{})@@ -325,10 +328,10 @@ func (s *ContainerService) StartContainer(ctx context.Context, containerID strin})}-func (s *ContainerService) StopContainer(ctx context.Context, containerID string, user models.User) error {+func (s *ContainerService) StopContainer(ctx context.Context, containerID string, user common.User) error {return s.runContainerLifecycleActionInternal(ctx, containerID, user, containerLifecycleActionInternal{action: "stop",- eventType: models.EventTypeContainerStop,+ eventType: event.EventTypeContainerStop,runContainerAction: func(dockerClient *client.Client) error {_, err := dockerClient.ContainerStop(ctx, containerID, client.ContainerStopOptions{Timeout: new(30)})return err@@ -336,10 +339,10 @@ func (s *ContainerService) StopContainer(ctx context.Context, containerID string})}-func (s *ContainerService) RestartContainer(ctx context.Context, containerID string, user models.User) error {+func (s *ContainerService) RestartContainer(ctx context.Context, containerID string, user common.User) error {return s.runContainerLifecycleActionInternal(ctx, containerID, user, containerLifecycleActionInternal{action: "restart",- eventType: models.EventTypeContainerRestart,+ eventType: event.EventTypeContainerRestart,runContainerAction: func(dockerClient *client.Client) error {_, err := dockerClient.ContainerRestart(ctx, containerID, client.ContainerRestartOptions{})return err@@ -349,11 +352,11 @@ func (s *ContainerService) RestartContainer(ctx context.Context, containerID str// KillContainer sends a signal to the container's main process (default SIGKILL// when signal is empty) without removing the container.-func (s *ContainerService) KillContainer(ctx context.Context, containerID, signal string, user models.User) error {+func (s *ContainerService) KillContainer(ctx context.Context, containerID, signal string, user common.User) error {return s.runContainerLifecycleActionInternal(ctx, containerID, user, containerLifecycleActionInternal{action: "kill",- eventType: models.EventTypeContainerKill,- metadata: models.JSON{"signal": signal},+ eventType: event.EventTypeContainerKill,+ metadata: database.JSON{"signal": signal},warnOnLogError: true,runContainerAction: func(dockerClient *client.Client) error {_, err := dockerClient.ContainerKill(ctx, containerID, client.ContainerKillOptions{Signal: signal})@@ -363,10 +366,10 @@ func (s *ContainerService) KillContainer(ctx context.Context, containerID, signa}// PauseContainer suspends all processes in the container.-func (s *ContainerService) PauseContainer(ctx context.Context, containerID string, user models.User) error {+func (s *ContainerService) PauseContainer(ctx context.Context, containerID string, user common.User) error {return s.runContainerLifecycleActionInternal(ctx, containerID, user, containerLifecycleActionInternal{action: "pause",- eventType: models.EventTypeContainerPause,+ eventType: event.EventTypeContainerPause,warnOnLogError: true,runContainerAction: func(dockerClient *client.Client) error {_, err := dockerClient.ContainerPause(ctx, containerID, client.ContainerPauseOptions{})@@ -376,10 +379,10 @@ func (s *ContainerService) PauseContainer(ctx context.Context, containerID strin}// UnpauseContainer resumes a previously paused container.-func (s *ContainerService) UnpauseContainer(ctx context.Context, containerID string, user models.User) error {+func (s *ContainerService) UnpauseContainer(ctx context.Context, containerID string, user common.User) error {return s.runContainerLifecycleActionInternal(ctx, containerID, user, containerLifecycleActionInternal{action: "unpause",- eventType: models.EventTypeContainerUnpause,+ eventType: event.EventTypeContainerUnpause,warnOnLogError: true,runContainerAction: func(dockerClient *client.Client) error {_, err := dockerClient.ContainerUnpause(ctx, containerID, client.ContainerUnpauseOptions{})@@ -389,7 +392,7 @@ func (s *ContainerService) UnpauseContainer(ctx context.Context, containerID str}// CommitContainer creates an image from a container's current filesystem.-func (s *ContainerService) CommitContainer(ctx context.Context, containerID string, req containertypes.CommitRequest, user models.User) (*containertypes.CommitResult, error) {+func (s *ContainerService) CommitContainer(ctx context.Context, containerID string, req containertypes.CommitRequest, user common.User) (*containertypes.CommitResult, error) {containerID = strings.TrimSpace(containerID)if containerID == "" {return nil, errors.New("container ID is required")@@ -397,7 +400,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stridockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": "commit"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "commit"})return nil, errors.WrapIf(err, "failed to connect to Docker")}@@ -416,11 +419,11 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID striNoPause: req.NoPause,})if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "container", containerID, reference, user.ID, user.Username, "0", err, models.JSON{"action": "commit", "reference": reference})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "container", containerID, reference, user.ID, user.Username, "0", err, database.JSON{"action": "commit", "reference": reference})return nil, errors.WrapIf(err, "failed to commit container")}- metadata := models.JSON{+ metadata := database.JSON{"action": "commit","containerId": containerID,"imageId": result.ID,@@ -429,7 +432,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stri"reference": reference,"noPause": req.NoPause,}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageCommit, containerID, reference, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageCommit, containerID, reference, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log container commit action", "container", containerID, "image", result.ID, "error", logErr)}@@ -451,7 +454,7 @@ func (s *ContainerService) CommitContainer(ctx context.Context, containerID stri// - handled=true, err!=nil: compose path was attempted and failed. The// caller MUST surface the error and MUST NOT fall back to the standalone// path, which would clobber whatever partial state ComposeUp left behind.-func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Context, containerInfo container.InspectResponse, containerID, containerName string, user models.User) (string, bool, error) {+func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Context, containerInfo container.InspectResponse, containerID, containerName string, user common.User) (string, bool, error) {if s.projectService == nil || containerInfo.Config == nil {return "", false, nil}@@ -493,7 +496,7 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.Cont)if err := s.projectService.UpdateProjectServices(ctx, proj.ID, []string{serviceName}, user); err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "compose_update_services","project": projectName,@@ -511,7 +514,7 @@ func (s *ContainerService) tryRedeployViaComposeProjectInternal(ctx context.ContnewID = containerID}- if logErr := s.eventService.LogContainerEvent(ctx, models.EventTypeContainerDeploy, newID, containerName, user.ID, user.Username, "0", models.JSON{+ if logErr := s.eventService.LogContainerEvent(ctx, event.EventTypeContainerDeploy, newID, containerName, user.ID, user.Username, "0", database.JSON{"action": "redeploy","containerId": newID,"containerName": containerName,@@ -557,10 +560,10 @@ func (s *ContainerService) findComposeServiceContainerIDInternal(ctx context.Conreturn firstMatch}-func (s *ContainerService) RedeployContainer(ctx context.Context, containerID string, user models.User) (string, error) {+func (s *ContainerService) RedeployContainer(ctx context.Context, containerID string, user common.User) (string, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "get_client",})@@ -569,7 +572,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID stcontainerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, containerID, client.ContainerInspectOptions{})if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "inspect",})@@ -579,7 +582,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID stcontainerInfo := containerJSON.Containerif containerInfo.Config == nil {err = errors.New("container config is nil")- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "validate_config",})@@ -594,7 +597,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID stcurrentContainerID, currentContainerErr := cgroup.CurrentContainerID()if labels.ShouldDisableArcaneServerRedeploy(containerInfo.Config.Labels, containerInfo.ID, currentContainerID, currentContainerErr) {err = errors.New("arcane cannot redeploy itself; use the system upgrade flow (Settings -> Updates) instead")- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "self_redeploy_blocked",})@@ -613,7 +616,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID streturn newID, nil}- metadata := models.JSON{+ metadata := database.JSON{"action": "redeploy","containerId": containerID,"containerName": containerName,@@ -646,7 +649,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st}, apiVersion)if err != nil {s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerID, containerName, backupName, "create", wasRunning, user)- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "create","image": imageName,@@ -658,13 +661,13 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st_, err = dockerClient.ContainerStart(ctx, createResp.ID, client.ContainerStartOptions{})if err != nil {if _, removeErr := dockerClient.ContainerRemove(ctx, createResp.ID, client.ContainerRemoveOptions{Force: true}); removeErr != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", removeErr, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", removeErr, database.JSON{"action": "redeploy","step": "cleanup_failed_start",})}s.restoreContainerAfterRedeployFailureInternal(ctx, dockerClient, containerID, containerName, backupName, "start", wasRunning, user)- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", err, models.JSON{+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", createResp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "redeploy","step": "start","image": imageName,@@ -692,7 +695,7 @@ func (s *ContainerService) RedeployContainer(ctx context.Context, containerID st)}- if logErr := s.eventService.LogContainerEvent(ctx, models.EventTypeContainerDeploy, createResp.ID, containerName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogContainerEvent(ctx, event.EventTypeContainerDeploy, createResp.ID, containerName, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "failed to log deploy event", "err", logErr)}@@ -745,10 +748,10 @@ func (s *ContainerService) GetContainerNameByID(ctx context.Context, id string)return s.GetContainerNameByReference(ctx, id)}-func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force bool, removeVolumes bool, user models.User) error {+func (s *ContainerService) DeleteContainer(ctx context.Context, containerID string, force bool, removeVolumes bool, user common.User) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})return errors.WrapIf(err, "failed to connect to Docker")}@@ -772,7 +775,7 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID striRemoveLinks: false,})if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", containerID, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force, "removeVolumes": removeVolumes})return errors.WrapIf(err, "failed to delete container")}@@ -781,17 +784,17 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID strifor _, volumeName := range volumesToRemove {if _, removeErr := dockerClient.VolumeRemove(ctx, volumeName, client.VolumeRemoveOptions{Force: false}); removeErr != nil {// Log but don't fail if volume removal fails (might be in use by another container)- s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", volumeName, "", user.ID, user.Username, "0", removeErr, models.JSON{"action": "delete", "container": containerID})+ s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", volumeName, "", user.ID, user.Username, "0", removeErr, database.JSON{"action": "delete", "container": containerID})}}}- metadata := models.JSON{+ metadata := database.JSON{"action": "delete","containerId": containerID,}- err = s.eventService.LogContainerEvent(ctx, models.EventTypeContainerDelete, containerID, "name", user.ID, user.Username, "0", metadata)+ err = s.eventService.LogContainerEvent(ctx, event.EventTypeContainerDelete, containerID, "name", user.ID, user.Username, "0", metadata)if err != nil {return errors.WrapIf(err, "failed to log action")}@@ -799,10 +802,10 @@ func (s *ContainerService) DeleteContainer(ctx context.Context, containerID strireturn nil}-func (s *ContainerService) CreateContainer(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string, user models.User, credentials []containerregistry.Credential) (*container.InspectResponse, error) {+func (s *ContainerService) CreateContainer(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string, user common.User, credentials []containerregistry.Credential) (*container.InspectResponse, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image})return nil, errors.WrapIf(err, "failed to connect to Docker")}@@ -824,10 +827,10 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containereader, pullErr := dockerClient.ImagePull(pullCtx, config.Image, pullOptions)if pullErr != nil {if errors.Is(pullCtx.Err(), context.DeadlineExceeded) {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, models.JSON{"action": "create", "image": config.Image, "step": "pull_image_timeout"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "create", "image": config.Image, "step": "pull_image_timeout"})return nil, errors.Errorf("image pull timed out for %s (increase DOCKER_IMAGE_PULL_TIMEOUT or setting)", config.Image)}- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, models.JSON{"action": "create", "image": config.Image, "step": "pull_image"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", pullErr, database.JSON{"action": "create", "image": config.Image, "step": "pull_image"})return nil, errors.WrapIff(pullErr, "failed to pull image %s", config.Image)}defer func() { _ = reader.Close() }()@@ -837,7 +840,7 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containestreamErr := dockerutils.RenderJSONMessageStream(reader, logWriter)_ = logWriter.Close()if streamErr != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "create", "image": config.Image, "step": "complete_pull"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "create", "image": config.Image, "step": "complete_pull"})return nil, errors.WrapIf(streamErr, "failed to complete image pull")}}@@ -849,28 +852,28 @@ func (s *ContainerService) CreateContainer(ctx context.Context, config *containeName: containerName,})if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image, "step": "create"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", "", containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "create"})return nil, errors.WrapIf(err, "failed to create container")}- metadata := models.JSON{+ metadata := database.JSON{"action": "create","containerId": resp.ID,}- if logErr := s.eventService.LogContainerEvent(ctx, models.EventTypeContainerCreate, resp.ID, "name", user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogContainerEvent(ctx, event.EventTypeContainerCreate, resp.ID, "name", user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log container stop action", "error", logErr)}if _, err := dockerClient.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil {_, _ = dockerClient.ContainerRemove(ctx, resp.ID, client.ContainerRemoveOptions{Force: true})- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image, "step": "start"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "start"})return nil, errors.WrapIf(err, "failed to start container")}containerJSON, err := libarcane.ContainerInspectWithCompatibility(ctx, dockerClient, resp.ID, client.ContainerInspectOptions{})if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, models.JSON{"action": "create", "image": config.Image, "step": "inspect"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeContainerError, "container", resp.ID, containerName, user.ID, user.Username, "0", err, database.JSON{"action": "create", "image": config.Image, "step": "inspect"})return nil, errors.WrapIf(err, "failed to inspect created container")}diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.goindex f31bfb494..888dabcb3 100644--- a/backend/internal/container/service_test.go+++ b/backend/internal/container/service_test.go@@ -1,6 +1,14 @@package containerimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/project"++ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""encoding/json""net/http"@@ -12,7 +20,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"containertypes "github.com/getarcaneapp/arcane/types/v2/container"@@ -253,7 +260,7 @@ func TestContainerServiceCommitContainerCallsDockerAPIInternal(t *testing.T) {Tag: "snapshot",Comment: "manual snapshot",Author: "arcane",- }, models.SystemUser)+ }, common.SystemUser)require.NoError(t, err)require.NotNil(t, out)require.Equal(t, "sha256:new-image", out.ID)@@ -265,9 +272,9 @@ func TestContainerServiceCommitContainerCallsDockerAPIInternal(t *testing.T) {"author": "arcane",}, gotRequest)- var event models.Event- require.NoError(t, db.WithContext(context.Background()).Where("type = ?", models.EventTypeImageCommit).First(&event).Error)- require.Equal(t, "container-1", *event.ResourceID)+ var evt event.Event+ require.NoError(t, db.WithContext(context.Background()).Where("type = ?", event.EventTypeImageCommit).First(&evt).Error)+ require.Equal(t, "container-1", *evt.ResourceID)}func TestContainerServiceCommitContainerOmitsReferenceWhenRepositoryEmptyInternal(t *testing.T) {@@ -298,7 +305,7 @@ func TestContainerServiceCommitContainerOmitsReferenceWhenRepositoryEmptyInternaout, err := svc.CommitContainer(context.Background(), "container-1", containertypes.CommitRequest{Tag: "latest",- }, models.SystemUser)+ }, common.SystemUser)require.NoError(t, err)require.NotNil(t, out)require.Equal(t, "sha256:new-image", out.ID)@@ -355,7 +362,7 @@ func setupProjectTestDBInternal(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Project{}, &models.SettingVariable{}, &models.ImageUpdateRecord{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&project.Project{}, &settings.SettingVariable{}, &imageupdate.ImageUpdateRecord{}, &event.Event{}))return &database.DB{DB: db}}diff --git a/backend/internal/dashboard/handler.go b/backend/internal/dashboard/handler.goindex f5ee3c415..13997e7a1 100644--- a/backend/internal/dashboard/handler.go+++ b/backend/internal/dashboard/handler.go@@ -12,7 +12,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"@@ -171,7 +170,7 @@ func (h *DashboardHandler) RunLocalStreamProducer(ctx context.Context, debugAllG// or removed while the stream is open are picked up without a reconnect.func (h *DashboardHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz.PermissionSet, debugAllGood bool, events chan<- dashboardtypes.StreamEvent) {agg.ReconcilePollersByKey(ctx,- func(ctx context.Context) ([]models.Environment, error) {+ func(ctx context.Context) ([]environment.Environment, error) {environments, err := h.environmentService.ListRemoteEnvironments(ctx)if err != nil {return nil, err@@ -184,13 +183,13 @@ func (h *DashboardHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz}return allowed, nil},- func(environment models.Environment) string {+ func(environment environment.Environment) string {return environment.ID},dashboardStreamEnvironmentVersionInternal,dashboardStreamEnvReconcileInterval,"dashboard stream",- func(pollCtx context.Context, environment models.Environment) {+ func(pollCtx context.Context, environment environment.Environment) {// One shared poller per environment (and debug variant) serves// every connected client; this subscriber only forwards its// events onto this client's stream.@@ -208,14 +207,14 @@ func (h *DashboardHandler) RunRemoteStreamPollers(ctx context.Context, ps *authz})}-func dashboardStreamEnvironmentVersionInternal(environment models.Environment) string {+func dashboardStreamEnvironmentVersionInternal(environment environment.Environment) string {if environment.UpdatedAt == nil {return environment.ID}return environment.ID + ":" + environment.UpdatedAt.UTC().Format(time.RFC3339Nano)}-func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Context, environment models.Environment, debugAllGood bool, publish func(dashboardtypes.StreamEvent)) {+func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Context, environment environment.Environment, debugAllGood bool, publish func(dashboardtypes.StreamEvent)) {environmentID := environment.ID// Tell the client this environment is covered before the first poll// completes so it can hold skeletons instead of assuming no data exists.@@ -294,7 +293,7 @@ func (h *DashboardHandler) runRemoteDashboardStreamPollerInternal(ctx context.Co// endpoint directly through the environment service so the raw remenv error// survives for classification (proxyRemoteJSONInternal would translate it// into a huma error first).-func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Context, environment models.Environment, debugAllGood bool) (*dashboardtypes.Snapshot, error) {+func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Context, environment environment.Environment, debugAllGood bool) (*dashboardtypes.Snapshot, error) {path := "/api/environments/0/dashboard"if debugAllGood {path += "?debugAllGood=true"@@ -315,7 +314,7 @@ func (h *DashboardHandler) fetchRemoteDashboardSnapshotInternal(ctx context.Cont// agents have exposed for far longer than the aggregate dashboard endpoint.// Each piece is fetched independently so a partially compatible agent still// yields partial data; only when every piece fails is an error returned.-func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Context, environment models.Environment) (*dashboardtypes.Snapshot, error) {+func (h *DashboardHandler) fetchLegacyDashboardSnapshotInternal(ctx context.Context, environment environment.Environment) (*dashboardtypes.Snapshot, error) {snapshot := &dashboardtypes.Snapshot{ActionItems: dashboardtypes.ActionItems{Items: []dashboardtypes.ActionItem{}},}diff --git a/backend/internal/dashboard/service.go b/backend/internal/dashboard/service.goindex 6ccb9e69a..398238c12 100644--- a/backend/internal/dashboard/service.go+++ b/backend/internal/dashboard/service.go@@ -1,6 +1,10 @@package dashboardimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"++ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"+"context""sort""strconv"@@ -18,7 +22,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/image"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/version"@@ -414,7 +417,7 @@ func (s *DashboardService) getPendingContainerUpdatesCountForImageIDsInternal(ctvar count int64err := s.db.WithContext(ctx).- Model(&models.ImageUpdateRecord{}).+ Model(&imageupdate.ImageUpdateRecord{}).Where("id IN ? AND has_update = ?", imageIDs, true).Count(&count).Errorif err != nil {@@ -451,7 +454,7 @@ func (s *DashboardService) getExpiringAPIKeysCountInternal(ctx context.Context)var count int64err := s.db.WithContext(ctx).- Model(&models.ApiKey{}).+ Model(&apikey.ApiKey{}).Where("expires_at IS NOT NULL").Where("expires_at <= ?", time.Now().Add(defaultDashboardAPIKeyExpiryWindow)).Count(&count).Errordiff --git a/backend/internal/dashboard/service_test.go b/backend/internal/dashboard/service_test.goindex 21c8be690..276aec814 100644--- a/backend/internal/dashboard/service_test.go+++ b/backend/internal/dashboard/service_test.go@@ -1,6 +1,14 @@package dashboardimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/apikey"++ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""encoding/json""net/http"@@ -17,7 +25,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/image"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/volume"@@ -41,7 +48,7 @@ func setupDashboardServiceTestDB(t *testing.T) (*database.DB, *settings.Settingsdb, err := gorm.Open(sqlite.Open("file:"+t.Name()+"?mode=memory&cache=shared"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ApiKey{}, &models.Environment{}, &models.ImageUpdateRecord{}, &models.Project{}, &models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&apikey.ApiKey{}, &environment.Environment{}, &imageupdate.ImageUpdateRecord{}, &project.Project{}, &settings.SettingVariable{}))databaseDB := &database.DB{DB: db}settingsSvc, err := newSettingsServiceForTestInternal(context.Background(), t, databaseDB)@@ -50,12 +57,12 @@ func setupDashboardServiceTestDB(t *testing.T) (*database.DB, *settings.Settingsreturn databaseDB, settingsSvc}-func createDashboardTestAPIKey(t *testing.T, db *database.DB, key models.ApiKey) {+func createDashboardTestAPIKey(t *testing.T, db *database.DB, key apikey.ApiKey) {t.Helper()require.NoError(t, db.WithContext(context.Background()).Create(&key).Error)}-func createDashboardTestImageUpdateRecord(t *testing.T, db *database.DB, record models.ImageUpdateRecord) {+func createDashboardTestImageUpdateRecord(t *testing.T, db *database.DB, record imageupdate.ImageUpdateRecord) {t.Helper()require.NoError(t, db.WithContext(context.Background()).Create(&record).Error)}@@ -149,14 +156,14 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {{ID: "sha256:image-c", RepoTags: []string{"ghcr.io/getarcaneapp/arcane:latest"}, Created: 1730000000, Size: 175},}- createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{+ createDashboardTestImageUpdateRecord(t, db, imageupdate.ImageUpdateRecord{ID: "sha256:image-b",Repository: "docker.io/repo/worker",Tag: "latest",HasUpdate: true,})- createDashboardTestAPIKey(t, db, models.ApiKey{+ createDashboardTestAPIKey(t, db, apikey.ApiKey{Name: "expiring-soon",KeyHash: "hash-soon",KeyPrefix: "arc_test_snapshot",@@ -176,12 +183,12 @@ func TestDashboardService_GetSnapshot_ReturnsDashboardSnapshot(t *testing.T) {projectPath := createComposeProjectDirInternal(t, projectsDir, "project-with-update")require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: repo/worker:latest\n"), 0o644))dirName := "project-with-update"- require.NoError(t, db.WithContext(context.Background()).Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-with-update"},+ require.NoError(t, db.WithContext(context.Background()).Create(&project.Project{+ BaseModel: database.BaseModel{ID: "project-with-update"},Name: "project-with-update",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: project.ProjectStatusStopped,}).Error)projectSvc := project.NewProjectService(db, settingsSvc, nil, image.NewImageService(db, nil, nil, nil, nil, nil), nil, nil, nil, nil, config.Load())svc := NewDashboardService(db, dockerSvc, nil, projectSvc, nil, settingsSvc, nil, nil, nil, volume.NewVolumeService(db, nil, nil, nil, nil, nil))@@ -234,7 +241,7 @@ func TestDashboardService_GetSnapshot_DebugAllGoodOnlyClearsActionItems(t *testi{ID: "sha256:image-b", RepoTags: []string{"repo/worker:latest"}, Created: 1720000000, Size: 250},}- createDashboardTestImageUpdateRecord(t, db, models.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})+ createDashboardTestImageUpdateRecord(t, db, imageupdate.ImageUpdateRecord{ID: "sha256:image-b", HasUpdate: true})dockerSvc := newDashboardTestDockerService(t, settingsSvc, containers, images, nil)svc := NewDashboardService(db, dockerSvc, nil, nil, nil, settingsSvc, nil, nil, nil, nil)@@ -269,15 +276,15 @@ func createComposeProjectDirInternal(t *testing.T, root, name string) string {func createTestRemoteEnvironmentInternal(t *testing.T, db *database.DB, environmentID, name, apiURL, token string) {t.Helper()now := time.Now()- require.NoError(t, db.Create(&models.Environment{- BaseModel: models.BaseModel{+ require.NoError(t, db.Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: environmentID,CreatedAt: now,UpdatedAt: &now,},Name: name,ApiUrl: apiURL,- Status: string(models.EnvironmentStatusOnline),+ Status: string(environment.EnvironmentStatusOnline),Enabled: true,AccessToken: &token,}).Error)@@ -367,8 +374,8 @@ func TestDashboardService_GetSnapshot_CachesFullSnapshotsPerIconCatalog(t *testi// A user preferring another catalog must not be served the default-catalog// snapshot from the cache.- dashboardIconsUser := &models.User{Preferences: usertypes.Preferences{IconCatalog: new("dashboard-icons")}}- userCtx := context.WithValue(context.Background(), models.CurrentUserContextKey{}, dashboardIconsUser)+ dashboardIconsUser := &common.User{Preferences: usertypes.Preferences{IconCatalog: new("dashboard-icons")}}+ userCtx := context.WithValue(context.Background(), common.CurrentUserContextKey{}, dashboardIconsUser)userSnapshot, err := svc.GetSnapshot(userCtx, DashboardActionItemsOptions{}, true)require.NoError(t, err)require.NotSame(t, defaultSnapshot, userSnapshot)diff --git a/backend/internal/models/base.go b/backend/internal/database/model.gosimilarity index 98%rename from backend/internal/models/base.gorename to backend/internal/database/model.goindex 77b9610ee..3b7751a0f 100644--- a/backend/internal/models/base.go+++ b/backend/internal/database/model.go@@ -1,4 +1,4 @@-package models+package databaseimport ("database/sql/driver"diff --git a/backend/internal/di/di.go b/backend/internal/di/di.goindex 84e8dfeab..bd7301ac8 100644--- a/backend/internal/di/di.go+++ b/backend/internal/di/di.go@@ -11,7 +11,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/lifecycle""github.com/getarcaneapp/arcane/backend/v2/internal/network""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/oidc"@@ -73,7 +72,7 @@ var ServiceOptions = fx.Options(provideImageModuleInternal,build.NewBuildService,build.NewBuildWorkspaceService,- lifecycle.NewLifecycleService,+ project.NewLifecycleService,provideProjectServiceInternal,project.New,provideContainerModuleInternal,diff --git a/backend/internal/di/di_test.go b/backend/internal/di/di_test.goindex 4031d84c6..7452eadb3 100644--- a/backend/internal/di/di_test.go+++ b/backend/internal/di/di_test.go@@ -18,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/job""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/lifecycle""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry"@@ -67,7 +66,7 @@ type graphParams struct {Image *image.ImageServiceBuild *build.BuildServiceBuildWorkspace *build.BuildWorkspaceService- Lifecycle *lifecycle.LifecycleService+ Lifecycle *project.LifecycleServiceVolume *volume.ModuleNetwork *network.NetworkServicePort *port.PortServicediff --git a/backend/internal/di/providers.go b/backend/internal/di/providers.goindex a4a081b7f..9a0cfebac 100644--- a/backend/internal/di/providers.go+++ b/backend/internal/di/providers.go@@ -20,14 +20,12 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/job""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/lifecycle""github.com/getarcaneapp/arcane/backend/v2/internal/network""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/passkey""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/role"- "github.com/getarcaneapp/arcane/backend/v2/internal/search""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/swarm"@@ -147,9 +145,9 @@ func provideSettingsServiceInternal(ctx context.Context, lc fx.Lifecycle, db *dareturn service, nil}-func provideSettingsModuleInternal(service *settings.SettingsService, searchModule *search.Module, environment *environment.EnvironmentService, cfg *config.Config) *settings.Module {+func provideSettingsModuleInternal(service *settings.SettingsService, environment *environment.EnvironmentService, cfg *config.Config) *settings.Module {return settings.New(service, settings.Dependencies{- Search: searchModule.SettingsService(),+ Search: settings.NewSettingsSearchService(),ProxyRemoteJSON: environment.ProxyJSONRequest,Config: cfg,})@@ -264,8 +262,8 @@ func provideContainerRegistryServiceInternal(module *registry.Module) *registry.return module.Service()}-func provideProjectServiceInternal(db *database.DB, settings *settings.SettingsService, event *event.EventService, image *image.ImageService, docker *docker.DockerClientService, build *build.BuildService, lifecycle *lifecycle.LifecycleService, kv *kv.KVService, registry *registry.ContainerRegistryService, environment *environment.EnvironmentService, cfg *config.Config) *project.ProjectService {- return project.NewProjectService(db, settings, event, image, docker, build, lifecycle, registry, cfg).+func provideProjectServiceInternal(db *database.DB, settings *settings.SettingsService, event *event.EventService, image *image.ImageService, docker *docker.DockerClientService, build *build.BuildService, lifecycleService *project.LifecycleService, kv *kv.KVService, registry *registry.ContainerRegistryService, environment *environment.EnvironmentService, cfg *config.Config) *project.ProjectService {+ return project.NewProjectService(db, settings, event, image, docker, build, lifecycleService, registry, cfg).WithKVService(kv).WithRegistryCredentialsProvider(environment.GetEnabledRegistryCredentials)}diff --git a/backend/internal/environment/environment.go b/backend/internal/environment/environment.goindex 17eb830b1..0bbbb546c 100644--- a/backend/internal/environment/environment.go+++ b/backend/internal/environment/environment.go@@ -1,6 +1,8 @@package environmentimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/registry"+"context""fmt""log/slog"@@ -14,7 +16,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/entityjobs"@@ -100,7 +101,7 @@ func (s *EnvironmentService) ResolveEdgeEnvironmentByToken(ctx context.Context,return envID, nil}- var env models.Environment+ var env Environmentif err := s.db.WithContext(ctx).Select("id", "access_token").Where("is_edge = ?", true).@@ -133,8 +134,8 @@ func (s *EnvironmentService) logEdgeTokenResolveMissInternal(ctx context.Contextvar totalEdgeEnvs int64var edgeEnvsWithToken int64- totalEdgeEnvsErr := s.db.WithContext(ctx).Model(&models.Environment{}).Where("is_edge = ?", true).Count(&totalEdgeEnvs).Error- edgeEnvsWithTokenErr := s.db.WithContext(ctx).Model(&models.Environment{}).+ totalEdgeEnvsErr := s.db.WithContext(ctx).Model(&Environment{}).Where("is_edge = ?", true).Count(&totalEdgeEnvs).Error+ edgeEnvsWithTokenErr := s.db.WithContext(ctx).Model(&Environment{}).Where("is_edge = ?", true).Where("access_token IS NOT NULL AND access_token != ?", "").Count(&edgeEnvsWithToken).Error@@ -169,7 +170,7 @@ func (s *EnvironmentService) ResolveEnvironmentName(ctx context.Context, environ}func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl string) error {- var existingEnv models.Environment+ var existingEnv Environmenterr := s.db.WithContext(ctx).Where("id = ?", LocalEnvironmentID).First(&existingEnv).Errorif err == nil {@@ -189,15 +190,15 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrl// Create the local environmentnow := time.Now()- localEnv := &models.Environment{- BaseModel: models.BaseModel{+ localEnv := &Environment{+ BaseModel: database.BaseModel{ID: LocalEnvironmentID,CreatedAt: now,UpdatedAt: new(now),},Name: "Local Docker",ApiUrl: appUrl,- Status: string(models.EnvironmentStatusOnline),+ Status: string(EnvironmentStatusOnline),Enabled: true,}@@ -209,12 +210,12 @@ func (s *EnvironmentService) EnsureLocalEnvironment(ctx context.Context, appUrlreturn nil}-func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *models.Environment, userID, username *string) (*models.Environment, error) {+func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment *Environment, userID, username *string) (*Environment, error) {environment.ID = uuid.New().String()// Only set status to offline if not already set (e.g., API key flow sets it to pending)if environment.Status == "" {- environment.Status = string(models.EnvironmentStatusOffline)+ environment.Status = string(EnvironmentStatusOffline)}now := time.Now()@@ -226,7 +227,7 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environment}// Create event in background- go s.createEnvironmentEvent(context.WithoutCancel(ctx), environment.ID, environment.Name, models.EventTypeEnvironmentCreate, "Environment Created", fmt.Sprintf("Environment '%s' was created", environment.Name), models.EventSeveritySuccess, userID, username)+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), environment.ID, environment.Name, event.EventTypeEnvironmentCreate, "Environment Created", fmt.Sprintf("Environment '%s' was created", environment.Name), event.EventSeveritySuccess, userID, username)if environment.Enabled {s.registerHealthJobInternal(ctx, environment.ID)@@ -236,8 +237,8 @@ func (s *EnvironmentService) CreateEnvironment(ctx context.Context, environmentreturn environment, nil}-func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string) (*models.Environment, error) {- var envRecord models.Environment+func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string) (*Environment, error) {+ var envRecord Environmentif err := s.db.WithContext(ctx).Where("id = ?", id).First(&envRecord).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("environment not found")@@ -247,7 +248,7 @@ func (s *EnvironmentService) GetEnvironmentByID(ctx context.Context, id string)return &envRecord, nil}-func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]any, userID, username *string) (*models.Environment, error) {+func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, updates map[string]any, userID, username *string) (*Environment, error) {current, err := s.GetEnvironmentByID(ctx, id)if err != nil {return nil, err@@ -279,7 +280,7 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, uupdates["updated_at"] = new(time.Now())- if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {return nil, errors.WrapIf(err, "failed to update environment")}@@ -307,7 +308,7 @@ func (s *EnvironmentService) UpdateEnvironment(ctx context.Context, id string, u// Create event in background (skip for local environment)if id != "0" {- go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, updated.Name, models.EventTypeEnvironmentUpdate, "Environment Updated", fmt.Sprintf("Environment '%s' was updated", updated.Name), models.EventSeverityInfo, userID, username)+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, updated.Name, event.EventTypeEnvironmentUpdate, "Environment Updated", fmt.Sprintf("Environment '%s' was updated", updated.Name), event.EventSeverityInfo, userID, username)}return updated, nil@@ -325,24 +326,24 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, uvar syncIDs []stringif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- if err := tx.Model(&models.GitOpsSync{}).+ if err := tx.Table("gitops_syncs").Where("environment_id = ?", id).Pluck("id", &syncIDs).Error; err != nil {return errors.WrapIf(err, "failed to list environment gitops syncs")}if len(syncIDs) > 0 {- if err := tx.Model(&models.Project{}).+ if err := tx.Table("projects").Where("gitops_managed_by IN ?", syncIDs).Update("gitops_managed_by", nil).Error; err != nil {return errors.WrapIf(err, "failed to clear environment gitops project references")}- if err := tx.Where("environment_id = ?", id).Delete(&models.GitOpsSync{}).Error; err != nil {+ if err := tx.Exec("DELETE FROM gitops_syncs WHERE environment_id = ?", id).Error; err != nil {return errors.WrapIf(err, "failed to delete environment gitops syncs")}}- if err := tx.Delete(&models.Environment{}, "id = ?", id).Error; err != nil {+ if err := tx.Delete(&Environment{}, "id = ?", id).Error; err != nil {return errors.WrapIf(err, "failed to delete environment")}@@ -367,12 +368,12 @@ func (s *EnvironmentService) DeleteEnvironment(ctx context.Context, id string, us.remoteEnvs.remove(id)// Create event in background- go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, env.Name, models.EventTypeEnvironmentDelete, "Environment Deleted", fmt.Sprintf("Environment '%s' was deleted", env.Name), models.EventSeverityWarning, userID, username)+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), id, env.Name, event.EventTypeEnvironmentDelete, "Environment Deleted", fmt.Sprintf("Environment '%s' was deleted", env.Name), event.EventSeverityWarning, userID, username)return nil}-func (s *EnvironmentService) createEnvironmentEvent(ctx context.Context, envID, envName string, eventType models.EventType, title, description string, severity models.EventSeverity, userID, username *string) {+func (s *EnvironmentService) createEnvironmentEvent(ctx context.Context, envID, envName string, eventType event.EventType, title, description string, severity event.EventSeverity, userID, username *string) {if s == nil || s.eventService == nil {return}@@ -401,11 +402,11 @@ func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, enupdates := map[string]any{"api_key_id": newApiKeyID,"access_token": apiKey,- "status": string(models.EnvironmentStatusPending),+ "status": string(EnvironmentStatusPending),"last_seen": nil, // Clear last seen time}- result := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates)+ result := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", envID).Updates(updates)if result.Error != nil {return errors.WrapIf(result.Error, "failed to update environment with new API key")}@@ -417,16 +418,16 @@ func (s *EnvironmentService) RegenerateEnvironmentApiKey(ctx context.Context, ens.edgeTokens.sync(envID, apiKey)now := time.Now()- s.remoteEnvs.update(envID, func(environment *models.Environment) {+ s.remoteEnvs.update(envID, func(environment *Environment) {environment.ApiKeyID = &newApiKeyIDenvironment.AccessToken = &apiKey- environment.Status = string(models.EnvironmentStatusPending)+ environment.Status = string(EnvironmentStatusPending)environment.LastSeen = nilenvironment.UpdatedAt = &now})// Create event log in background- go s.createEnvironmentEvent(context.WithoutCancel(ctx), envID, envName, models.EventTypeEnvironmentApiKeyRegenerated, "API Key Regenerated", "Environment API key was regenerated and status set to pending", models.EventSeverityInfo, new(userID), new(username))+ go s.createEnvironmentEvent(context.WithoutCancel(ctx), envID, envName, event.EventTypeEnvironmentApiKeyRegenerated, "API Key Regenerated", "Environment API key was regenerated and status set to pending", event.EventSeverityInfo, new(userID), new(username))return nil}@@ -435,13 +436,13 @@ func (s *EnvironmentService) GetDB() *database.DB {return s.db}-func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*models.Environment, error) {+func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Context, token string) (*Environment, error) {token = strings.TrimSpace(token)if token == "" {return nil, ErrEnvironmentAccessTokenRequired}- var env models.Environment+ var env Environmentif err := s.db.WithContext(ctx).Where("access_token = ?", token).First(&env).Error; err != nil {@@ -455,7 +456,7 @@ func (s *EnvironmentService) ResolveEnvironmentByAccessToken(ctx context.Context}func (s *EnvironmentService) GetEnabledRegistryCredentials(ctx context.Context) ([]containerregistry.Credential, error) {- var registries []models.ContainerRegistry+ var registries []registry.ContainerRegistryif err := s.db.WithContext(ctx).Where("enabled = ?", true).Find(®istries).Error; err != nil {return nil, errors.WrapIf(err, "failed to get enabled container registries")}diff --git a/backend/internal/environment/environment_caches.go b/backend/internal/environment/environment_caches.goindex 5555d4e5c..31faf7289 100644--- a/backend/internal/environment/environment_caches.go+++ b/backend/internal/environment/environment_caches.go@@ -7,8 +7,6 @@ import ("github.com/samber/hot""github.com/samber/mo"-- "github.com/getarcaneapp/arcane/backend/v2/internal/models")const edgeTokenCacheTTL = time.Minute@@ -26,7 +24,7 @@ type edgeTokenCacheInternal struct {// enabled, visible, non-local environment, so hot paths avoid a DB round trip.type remoteEnvSnapshotCacheInternal struct {mu sync.RWMutex- envs map[string]models.Environment+ envs map[string]Environment}// runtimeWatchersInternal fans a coalesced wake-up out to everyone watching for@@ -48,7 +46,7 @@ func newEdgeTokenCacheInternal() *edgeTokenCacheInternal {}func newRemoteEnvSnapshotCacheInternal() *remoteEnvSnapshotCacheInternal {- return &remoteEnvSnapshotCacheInternal{envs: make(map[string]models.Environment)}+ return &remoteEnvSnapshotCacheInternal{envs: make(map[string]Environment)}}func (c *edgeTokenCacheInternal) environmentID(token string) mo.Option[string] {@@ -117,30 +115,30 @@ func (c *edgeTokenCacheInternal) sync(envID string, token string) {}}-func isActiveRemoteEnvironmentInternal(environment models.Environment) bool {+func isActiveRemoteEnvironmentInternal(environment Environment) bool {return environment.ID != "" && environment.ID != "0" && environment.Enabled && !environment.Hidden}-func (c *remoteEnvSnapshotCacheInternal) get(environmentID string) mo.Option[models.Environment] {+func (c *remoteEnvSnapshotCacheInternal) get(environmentID string) mo.Option[Environment] {if c == nil || environmentID == "" {- return mo.None[models.Environment]()+ return mo.None[Environment]()}c.mu.RLock()envRecord, ok := c.envs[environmentID]c.mu.RUnlock()if !ok || !isActiveRemoteEnvironmentInternal(envRecord) {- return mo.None[models.Environment]()+ return mo.None[Environment]()}return mo.Some(envRecord)}-func (c *remoteEnvSnapshotCacheInternal) replace(environments []models.Environment) {+func (c *remoteEnvSnapshotCacheInternal) replace(environments []Environment) {if c == nil {return}- next := make(map[string]models.Environment, len(environments))+ next := make(map[string]Environment, len(environments))for _, envRecord := range environments {if isActiveRemoteEnvironmentInternal(envRecord) {next[envRecord.ID] = envRecord@@ -152,7 +150,7 @@ func (c *remoteEnvSnapshotCacheInternal) replace(environments []models.Environmec.mu.Unlock()}-func (c *remoteEnvSnapshotCacheInternal) put(environment models.Environment) {+func (c *remoteEnvSnapshotCacheInternal) put(environment Environment) {if c == nil {return}@@ -177,7 +175,7 @@ func (c *remoteEnvSnapshotCacheInternal) remove(environmentID string) {c.mu.Unlock()}-func (c *remoteEnvSnapshotCacheInternal) update(environmentID string, update func(*models.Environment)) {+func (c *remoteEnvSnapshotCacheInternal) update(environmentID string, update func(*Environment)) {if c == nil || environmentID == "" || update == nil {return}@@ -199,9 +197,9 @@ func (c *remoteEnvSnapshotCacheInternal) update(environmentID string, update fun// GetActiveRemoteEnvironmentSnapshot returns the latest in-process snapshot for// an enabled, visible, non-local remote environment.-func (s *EnvironmentService) GetActiveRemoteEnvironmentSnapshot(environmentID string) mo.Option[models.Environment] {+func (s *EnvironmentService) GetActiveRemoteEnvironmentSnapshot(environmentID string) mo.Option[Environment] {if s == nil {- return mo.None[models.Environment]()+ return mo.None[Environment]()}return s.remoteEnvs.get(environmentID)}diff --git a/backend/internal/environment/environment_health.go b/backend/internal/environment/environment_health.goindex 2bb791bdd..8428e9cb9 100644--- a/backend/internal/environment/environment_health.go+++ b/backend/internal/environment/environment_health.go@@ -10,7 +10,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/types/v2/environment"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"@@ -182,7 +181,7 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custhealthURL, err := buildEnvironmentEndpointURLInternal(apiUrl, "/api/health")if err != nil {if customApiUrl == nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))}return connectionFailure("offline", errors.WrapIf(err, "invalid environment API URL"))}@@ -192,14 +191,14 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custreq, err := http.NewRequestWithContext(reqCtx, http.MethodGet, healthURL, nil)if err != nil {if customApiUrl == nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))}return connectionFailure("offline", errors.WrapIf(err, "failed to create request"))}resp, err := s.httpClient.Do(req)if err != nil {if customApiUrl == nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))}return connectionFailure("offline", errors.WrapIf(err, "connection failed"))}@@ -207,13 +206,13 @@ func (s *EnvironmentService) TestConnection(ctx context.Context, id string, custif resp.StatusCode == http.StatusOK {if customApiUrl == nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOnline))}return "online", nil}if customApiUrl == nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusError))}return connectionFailure("error", errors.Errorf("unexpected status code: %d", resp.StatusCode))}@@ -226,7 +225,7 @@ func (s *EnvironmentService) testEdgeConnection(ctx context.Context, id string)edge.TouchTunnelDemand(id, edge.DefaultTunnelDemandTTL)if !edge.HasActiveTunnel(id) {if _, ok := edge.RequestTunnelAndWait(ctx, id, edge.DefaultTunnelDemandTTL, edge.DefaultTunnelAcquireTimeout()).Get(); !ok {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))return "offline", errors.New("edge agent is not connected")}}@@ -236,16 +235,16 @@ func (s *EnvironmentService) testEdgeConnection(ctx context.Context, id string)statusCode, _, err := edge.DoRequest(reqCtx, id, http.MethodGet, "/api/health", nil)if err != nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))return "offline", errors.WrapIf(err, "health check via tunnel failed")}if statusCode == http.StatusOK {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOnline))return "online", nil}- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusError))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusError))return "error", errors.Errorf("unexpected status code: %d", statusCode)}@@ -256,33 +255,33 @@ func (s *EnvironmentService) testLocalDockerConnection(ctx context.Context, id sdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))return "offline", errors.WrapIf(err, "failed to connect to Docker")}_, err = dockerClient.Ping(reqCtx, client.PingOptions{})if err != nil {- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOffline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOffline))return "offline", errors.WrapIf(err, "docker ping failed")}- _ = s.updateEnvironmentStatusInternal(ctx, id, string(models.EnvironmentStatusOnline))+ _ = s.updateEnvironmentStatusInternal(ctx, id, string(EnvironmentStatusOnline))return "online", nil}func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context, id, status string) error {- var currentEnv models.Environment+ var currentEnv Environmentif err := s.db.WithContext(ctx).Select("status", "is_edge").Where("id = ?", id).First(¤tEnv).Error; err != nil {return errors.WrapIf(err, "failed to check environment status")}- if currentEnv.Status == string(models.EnvironmentStatusPending) {+ if currentEnv.Status == string(EnvironmentStatusPending) {// Edge envs must complete pairing via the agent's outbound tunnel — manager// can't dial them directly, so a manager-side reachability check means nothing.// Direct envs are reachable from the manager, so a successful health check IS// the pairing signal. Don't promote on offline/error ticks though, or a transient// blip during initial setup would flip the env out of pending.- if currentEnv.IsEdge || status != string(models.EnvironmentStatusOnline) {+ if currentEnv.IsEdge || status != string(EnvironmentStatusOnline) {slog.DebugContext(ctx, "skipping status update for pending environment", "environment_id", id)return nil}@@ -295,7 +294,7 @@ func (s *EnvironmentService) updateEnvironmentStatusInternal(ctx context.Context"last_seen": &now,"updated_at": &now,}- if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {return errors.WrapIf(err, "failed to update environment status")}// Direct environments have no tunnel callback, so this health-check write is@@ -314,7 +313,7 @@ func (s *EnvironmentService) UpdateEnvironmentHeartbeat(ctx context.Context, idSET last_seen = ?, status = ?, updated_at = ?WHERE id = ?AND (last_seen IS NULL OR last_seen < ?)- `, new(now), string(models.EnvironmentStatusOnline), new(now), id, now.Add(-30*time.Second))+ `, new(now), string(EnvironmentStatusOnline), new(now), id, now.Add(-30*time.Second))if result.Error != nil {return errors.WrapIf(result.Error, "failed to update environment heartbeat")@@ -338,7 +337,7 @@ func (s *EnvironmentService) UpdateEnvironmentConnectionState(ctx context.Contex"updated_at": &now,}if connected {- updates["status"] = string(models.EnvironmentStatusOnline)+ updates["status"] = string(EnvironmentStatusOnline)updates["last_seen"] = &now// Remember the tunnel transport so the UI can keep showing it after// the tunnel drops or while the agent is poll-only.@@ -346,10 +345,10 @@ func (s *EnvironmentService) UpdateEnvironmentConnectionState(ctx context.Contexupdates["last_edge_transport"] = state.Transport}} else {- updates["status"] = string(models.EnvironmentStatusOffline)+ updates["status"] = string(EnvironmentStatusOffline)}- if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", id).Updates(updates).Error; err != nil {return errors.WrapIf(err, "failed to update environment connection state")}@@ -383,7 +382,7 @@ func ApplyEnvironmentRuntimeState(env *environment.Environment) {if runtimeState, ok := edge.GetTunnelRuntimeState(env.ID).Get(); ok {connected = trueenv.Connected = &connected- env.Status = string(models.EnvironmentStatusOnline)+ env.Status = string(EnvironmentStatusOnline)env.ConnectedAt = runtimeState.ConnectedAtenv.LastHeartbeat = runtimeState.LastHeartbeatif runtimeState.SecurityMode != "" {@@ -407,12 +406,12 @@ func ApplyEnvironmentRuntimeState(env *environment.Environment) {}if env.LastPollAt != nil {- env.Status = string(models.EnvironmentStatusStandby)+ env.Status = string(EnvironmentStatusStandby)return}- if env.Status != string(models.EnvironmentStatusPending) {- env.Status = string(models.EnvironmentStatusOffline)+ if env.Status != string(EnvironmentStatusPending) {+ env.Status = string(EnvironmentStatusOffline)}}@@ -420,12 +419,12 @@ func ApplyEnvironmentRuntimeState(env *environment.Environment) {// Live edge tunnels are process-local runtime state, so persisted "online" flags can be stale// after a restart until agents reconnect. Pending environments are left untouched.func (s *EnvironmentService) ReconcileEdgeStatusesOnStartup(ctx context.Context) error {- result := s.db.WithContext(ctx).Model(&models.Environment{}).+ result := s.db.WithContext(ctx).Model(&Environment{}).Where("is_edge = ?", true).- Where("status <> ?", string(models.EnvironmentStatusPending)).- Where("status <> ?", string(models.EnvironmentStatusOffline)).+ Where("status <> ?", string(EnvironmentStatusPending)).+ Where("status <> ?", string(EnvironmentStatusOffline)).Updates(map[string]any{- "status": string(models.EnvironmentStatusOffline),+ "status": string(EnvironmentStatusOffline),"updated_at": new(time.Now()),})if result.Error != nil {diff --git a/backend/internal/environment/environment_listing.go b/backend/internal/environment/environment_listing.goindex 57c3b1ad4..7595e6f17 100644--- a/backend/internal/environment/environment_listing.go+++ b/backend/internal/environment/environment_listing.go@@ -6,7 +6,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"@@ -18,8 +17,8 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, parareturn s.listEnvironmentsPaginatedWithRuntimeFiltersInternal(ctx, params, accessibleEnvIDs)}- var envs []models.Environment- q := s.db.WithContext(ctx).Model(&models.Environment{}).Where("hidden = ?", false)+ var envs []Environment+ q := s.db.WithContext(ctx).Model(&Environment{}).Where("hidden = ?", false)// accessibleEnvIDs == nil means "no restriction". A non-nil slice limits the// result to those environment IDs; an empty slice therefore matches nothing.switch {@@ -47,7 +46,7 @@ func (s *EnvironmentService) ListEnvironmentsPaginated(ctx context.Context, parareturn nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate environments")}- out, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)+ out, mapErr := mapper.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")}@@ -73,15 +72,15 @@ func filterEnvironmentsByIDInternal(items []environment.Environment, allowedIDs}func (s *EnvironmentService) listEnvironmentsPaginatedWithRuntimeFiltersInternal(ctx context.Context, params pagination.QueryParams, accessibleEnvIDs []string) ([]environment.Environment, pagination.Response, error) {- var envs []models.Environment+ var envs []Environmentif err := s.db.WithContext(ctx).- Model(&models.Environment{}).+ Model(&Environment{}).Where("hidden = ?", false).Find(&envs).Error; err != nil {return nil, pagination.Response{}, errors.WrapIf(err, "failed to list environments")}- items, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)+ items, mapErr := mapper.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map environments")}@@ -198,16 +197,16 @@ func environmentTypeKeyInternal(env environment.Environment) string {}func (s *EnvironmentService) ListVisibleEnvironments(ctx context.Context) ([]environment.Environment, error) {- var envs []models.Environment+ var envs []Environmentif err := s.db.WithContext(ctx).- Model(&models.Environment{}).+ Model(&Environment{}).Where("hidden = ?", false).Order("created_at asc, id asc").Find(&envs).Error; err != nil {return nil, errors.WrapIf(err, "failed to list visible environments")}- out, mapErr := mapper.MapSlice[models.Environment, environment.Environment](envs)+ out, mapErr := mapper.MapSlice[Environment, environment.Environment](envs)if mapErr != nil {return nil, errors.WrapIf(mapErr, "failed to map environments")}@@ -234,10 +233,10 @@ func (s *EnvironmentService) ListRemoteEnvironmentIDs(ctx context.Context) ([]st}// ListRemoteEnvironments returns all non-local, enabled environments for syncing purposes.-func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]models.Environment, error) {- var envs []models.Environment+func (s *EnvironmentService) ListRemoteEnvironments(ctx context.Context) ([]Environment, error) {+ var envs []Environmenterr := s.db.WithContext(ctx).- Model(&models.Environment{}).+ Model(&Environment{}).Where("id != ?", "0").Where("enabled = ?", true).Where("hidden = ?", false).diff --git a/backend/internal/environment/environment_proxy.go b/backend/internal/environment/environment_proxy.goindex 4ff08bdae..29f184c3b 100644--- a/backend/internal/environment/environment_proxy.go+++ b/backend/internal/environment/environment_proxy.go@@ -1,6 +1,8 @@package environmentimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"+"context""encoding/json/v2""log/slog"@@ -13,7 +15,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"@@ -78,7 +79,7 @@ func (s *EnvironmentService) resolveRemoteEnvironmentTargetInternal(ctx context.return s.remoteEnvironmentTargetFromModelInternal(*envRecord)}-func (s *EnvironmentService) remoteEnvironmentTargetFromModelInternal(environment models.Environment) (*remoteEnvironmentTargetInternal, error) {+func (s *EnvironmentService) remoteEnvironmentTargetFromModelInternal(environment Environment) (*remoteEnvironmentTargetInternal, error) {if environment.ID == "0" {return nil, errors.New("cannot proxy request to local environment")}@@ -197,7 +198,7 @@ func (s *EnvironmentService) ProxyJSONRequest(ctx context.Context, envID string,// ProxyJSONRequestForEnvironment sends a JSON request using an already-loaded// environment row, avoiding an extra environment lookup on hot stream paths.-func (s *EnvironmentService) ProxyJSONRequestForEnvironment(ctx context.Context, environment models.Environment, method string, path string, body []byte, out any) error {+func (s *EnvironmentService) ProxyJSONRequestForEnvironment(ctx context.Context, environment Environment, method string, path string, body []byte, out any) error {proxyCtx, cancel := s.getProxyRequestContextInternal(ctx)defer cancel()@@ -274,7 +275,7 @@ func doRemoteEnvironmentTunnelRequestInternal(// SyncRegistriesToEnvironment syncs all registries from this manager to a remote environmentfunc (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, environmentID string) error {return fanOutSyncToEnvironmentInternal(ctx, s, environmentID, "registries", "/api/container-registries/sync",- func(ctx context.Context, reg models.ContainerRegistry) (containerregistry.Sync, bool, error) {+ func(ctx context.Context, reg registry.ContainerRegistry) (containerregistry.Sync, bool, error) {registryType, typeErr := registry.NormalizeRegistryType(reg.RegistryType)if typeErr != nil {return containerregistry.Sync{}, false, errors.WrapIff(typeErr, "normalize registry type for sync %s", reg.ID)@@ -324,7 +325,7 @@ func (s *EnvironmentService) SyncRegistriesToEnvironment(ctx context.Context, en// SyncRepositoriesToEnvironment syncs all git repositories from this manager to a remote environmentfunc (s *EnvironmentService) SyncRepositoriesToEnvironment(ctx context.Context, environmentID string) error {return fanOutSyncToEnvironmentInternal(ctx, s, environmentID, "git repositories", "/api/git-repositories/sync",- func(ctx context.Context, repo models.GitRepository) (gitops.RepositorySync, bool, error) {+ func(ctx context.Context, repo gitrepo.GitRepository) (gitops.RepositorySync, bool, error) {item := gitops.RepositorySync{ID: repo.ID,Name: repo.Name,diff --git a/backend/internal/environment/environment_snippets.go b/backend/internal/environment/environment_snippets.goindex 7419e66ba..876d923a2 100644--- a/backend/internal/environment/environment_snippets.go+++ b/backend/internal/environment/environment_snippets.go@@ -1,13 +1,14 @@package environmentimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""fmt""log/slog""strings""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge")@@ -157,11 +158,11 @@ func (s *EnvironmentService) logGeneratedMTLSEventsInternal(ctx context.Context,}if assets.CAGenerated {if _, err := s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeEnvironmentMTLSCAGenerated,- Severity: models.EventSeverityInfo,+ Type: event.EventTypeEnvironmentMTLSCAGenerated,+ Severity: event.EventSeverityInfo,Title: "Edge mTLS CA generated",Description: "Arcane generated a new edge mTLS certificate authority",- Metadata: models.JSON{"kind": "ca"},+ Metadata: database.JSON{"kind": "ca"},}); err != nil {slog.WarnContext(ctx, "Failed to create edge mTLS CA generation event", "error", err)}@@ -169,15 +170,15 @@ func (s *EnvironmentService) logGeneratedMTLSEventsInternal(ctx context.Context,if assets.CertIssued {envIDCopy := envIDif _, err := s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeEnvironmentMTLSCertIssued,- Severity: models.EventSeverityInfo,+ Type: event.EventTypeEnvironmentMTLSCertIssued,+ Severity: event.EventSeverityInfo,Title: "Edge mTLS certificate issued",Description: fmt.Sprintf("Arcane issued an edge mTLS client certificate for environment '%s'", envName),ResourceType: new("environment"),ResourceID: &envIDCopy,ResourceName: new(envName),EnvironmentID: &envIDCopy,- Metadata: models.JSON{"kind": "client"},+ Metadata: database.JSON{"kind": "client"},}); err != nil {slog.WarnContext(ctx, "Failed to create edge mTLS certificate issuance event", "environment_id", envID, "error", err)}diff --git a/backend/internal/environment/environment_swarm_nodes.go b/backend/internal/environment/environment_swarm_nodes.goindex 5b4982010..66fad79e9 100644--- a/backend/internal/environment/environment_swarm_nodes.go+++ b/backend/internal/environment/environment_swarm_nodes.go@@ -9,14 +9,13 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/apikey"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""gorm.io/gorm")-func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context, parentEnvironmentID string) ([]models.Environment, error) {- var envs []models.Environment+func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context, parentEnvironmentID string) ([]Environment, error) {+ var envs []Environmentif err := s.db.WithContext(ctx).- Model(&models.Environment{}).+ Model(&Environment{}).Where("parent_environment_id = ?", parentEnvironmentID).Find(&envs).Error; err != nil {return nil, errors.WrapIf(err, "failed to list swarm node agent environments")@@ -27,10 +26,10 @@ func (s *EnvironmentService) ListSwarmNodeAgentEnvironments(ctx context.Context,// ListSwarmNodeCandidateEnvironments returns enabled visible environments that// can provide swarm-node coverage for a manager environment.-func (s *EnvironmentService) ListSwarmNodeCandidateEnvironments(ctx context.Context) ([]models.Environment, error) {- var envs []models.Environment+func (s *EnvironmentService) ListSwarmNodeCandidateEnvironments(ctx context.Context) ([]Environment, error) {+ var envs []Environmentif err := s.db.WithContext(ctx).- Model(&models.Environment{}).+ Model(&Environment{}).Where("hidden = ?", false).Where("enabled = ?", true).Where("id <> ?", "0").@@ -48,8 +47,8 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(ctx context.Context,parentEnvironmentID, nodeID, environmentID string,rebind bool,-) (*models.Environment, error) {- var envRecord models.Environment+) (*Environment, error) {+ var envRecord Environmenterr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Where("id = ?", environmentID).First(&envRecord).Error; err != nil {return errors.WrapIf(err, "failed to load environment for swarm node binding")@@ -68,7 +67,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(}var existingVisibleBindings int64- if err := tx.Model(&models.Environment{}).+ if err := tx.Model(&Environment{}).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ? AND id <> ?", false, parentEnvironmentID, nodeID, environmentID).Count(&existingVisibleBindings).Error; err != nil {return errors.WrapIf(err, "failed to inspect existing swarm node binding")@@ -77,14 +76,14 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(return errors.New("swarm node already has a visible environment binding; explicit rebinding is required")}if rebind {- if err := tx.Model(&models.Environment{}).+ if err := tx.Model(&Environment{}).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ? AND id <> ?", false, parentEnvironmentID, nodeID, environmentID).Updates(map[string]any{"parent_environment_id": nil, "swarm_node_id": nil, "updated_at": new(time.Now())}).Error; err != nil {return errors.WrapIf(err, "failed to clear previous swarm node binding")}}- if err := tx.Model(&models.Environment{}).Where("id = ?", environmentID).Updates(map[string]any{+ if err := tx.Model(&Environment{}).Where("id = ?", environmentID).Updates(map[string]any{"parent_environment_id": parentEnvironmentID,"swarm_node_id": nodeID,"updated_at": new(time.Now()),@@ -105,7 +104,7 @@ func (s *EnvironmentService) BindSwarmNodeEnvironment(// DetachSwarmNodeEnvironment clears a visible environment binding from a node.func (s *EnvironmentService) DetachSwarmNodeEnvironment(ctx context.Context, parentEnvironmentID, nodeID string) error {now := time.Now()- if err := s.db.WithContext(ctx).Model(&models.Environment{}).+ if err := s.db.WithContext(ctx).Model(&Environment{}).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ?", false, parentEnvironmentID, nodeID).Updates(map[string]any{"parent_environment_id": nil, "swarm_node_id": nil, "updated_at": &now}).Error; err != nil {return errors.WrapIf(err, "failed to detach swarm node environment")@@ -117,7 +116,7 @@ func (s *EnvironmentService) DetachSwarmNodeEnvironment(ctx context.Context, par// DeleteSwarmNodeAgentDeployment removes a dedicated hidden agent registration// while leaving visible remote environments untouched.func (s *EnvironmentService) DeleteSwarmNodeAgentDeployment(ctx context.Context, parentEnvironmentID, nodeID string, userID, username *string) error {- var envRecord models.Environment+ var envRecord Environmentif err := s.db.WithContext(ctx).Where("hidden = ? AND parent_environment_id = ? AND swarm_node_id = ?", true, parentEnvironmentID, nodeID).First(&envRecord).Error; err != nil {@@ -151,7 +150,7 @@ func buildSwarmNodeAgentURLInternal(nodeID string) string {func (s *EnvironmentService) applySwarmNodeAgentApiKeyInternal(ctx context.Context,- env *models.Environment,+ env *Environment,userID, username string,rotate bool,) (string, error) {@@ -201,7 +200,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(ctx context.Context,parentEnvironmentID, nodeID, hostname, userID, username string,rotate bool,-) (*models.Environment, string, error) {+) (*Environment, string, error) {if strings.TrimSpace(parentEnvironmentID) == "" {return nil, "", errors.New("parent environment ID is required")}@@ -209,7 +208,7 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(return nil, "", errors.New("swarm node ID is required")}- var env models.Environment+ var env Environment// Prefer an existing visible binding. Legacy hidden registrations remain// reusable, but all newly provisioned node agents are normal Remote// Environments so one token and one agent can serve both use cases.@@ -223,10 +222,10 @@ func (s *EnvironmentService) EnsureSwarmNodeAgentEnvironment(}if errors.Is(err, gorm.ErrRecordNotFound) {- createdEnv := &models.Environment{+ createdEnv := &Environment{Name: buildSwarmNodeAgentNameInternal(hostname, nodeID),ApiUrl: buildSwarmNodeAgentURLInternal(nodeID),- Status: string(models.EnvironmentStatusPending),+ Status: string(EnvironmentStatusPending),Enabled: true,IsEdge: true,Hidden: false,@@ -259,7 +258,7 @@ func (s *EnvironmentService) UpdateSwarmNodeIdentity(ctx context.Context, envID,"updated_at": new(time.Now()),}- if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&Environment{}).Where("id = ?", envID).Updates(updates).Error; err != nil {return errors.WrapIf(err, "failed to update swarm node identity")}diff --git a/backend/internal/environment/handler.go b/backend/internal/environment/handler.goindex 67f9213e3..9feb0d177 100644--- a/backend/internal/environment/handler.go+++ b/backend/internal/environment/handler.go@@ -1,6 +1,10 @@package environmentimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"archive/zip""bytes""context"@@ -21,7 +25,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"@@ -559,7 +562,7 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creatreturn nil, err}- env := &models.Environment{+ env := &Environment{ApiUrl: input.Body.ApiUrl,Enabled: true,}@@ -583,9 +586,9 @@ func (h *EnvironmentHandler) CreateEnvironment(ctx context.Context, input *Creatreturn h.createEnvironmentLegacyInternal(ctx, env, user, input.Body)}-func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Context, env *models.Environment, user *models.User) (*CreateEnvironmentOutput, error) {+func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Context, env *Environment, user *common.User) (*CreateEnvironmentOutput, error) {// New API key-based pairing flow- env.Status = string(models.EnvironmentStatusPending)+ env.Status = string(EnvironmentStatusPending)created, err := h.environmentService.CreateEnvironment(ctx, env, &user.ID, &user.Username)if err != nil {@@ -622,7 +625,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con}created = updated- out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)+ out, mapErr := mapper.MapOne[*Environment, environment.Environment](created)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -639,7 +642,7 @@ func (h *EnvironmentHandler) createEnvironmentWithApiKeyInternal(ctx context.Con}, nil}-func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Context, env *models.Environment, user *models.User, body environment.Create) (*CreateEnvironmentOutput, error) {+func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Context, env *Environment, user *common.User, body environment.Create) (*CreateEnvironmentOutput, error) {if body.AccessToken != nil && *body.AccessToken != "" {env.AccessToken = body.AccessToken}@@ -654,7 +657,7 @@ func (h *EnvironmentHandler) createEnvironmentLegacyInternal(ctx context.Contexth.triggerEnvironmentResourceSyncInternal(ctx, created.ID, created.Name, "environment creation")}- out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](created)+ out, mapErr := mapper.MapOne[*Environment, environment.Environment](created)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -677,7 +680,7 @@ func (h *EnvironmentHandler) GetEnvironment(ctx context.Context, input *GetEnvirreturn nil, huma.Error404NotFound("Environment not found")}- out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](env)+ out, mapErr := mapper.MapOne[*Environment, environment.Environment](env)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -703,7 +706,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updath.handleEnvironmentPairingInternal(ctx, input.ID, &input.Body, updates, isLocalEnv)- user, _ := models.CurrentUserFromContext(ctx)+ user, _ := common.CurrentUserFromContext(ctx)var userID, username *stringif user != nil {userID = new(user.ID)@@ -711,7 +714,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat}updated, updateErr := h.environmentService.UpdateEnvironment(ctx, input.ID, updates, userID, username)if updateErr != nil {- apiErr := models.ToAPIError(updateErr)+ apiErr := common.ToAPIError(updateErr)if apiErr.HTTPStatus() == http.StatusInternalServerError {return nil, huma.Error500InternalServerError("Failed to update environment")}@@ -720,7 +723,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updath.triggerPostUpdateTasksInternal(ctx, input.ID, updated, &input.Body)- out, mapErr := mapper.MapOne[*models.Environment, environment.Environment](updated)+ out, mapErr := mapper.MapOne[*Environment, environment.Environment](updated)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -776,7 +779,7 @@ func (h *EnvironmentHandler) UpdateEnvironment(ctx context.Context, input *Updat}// Re-map with updated environment data- out, mapErr = mapper.MapOne[*models.Environment, environment.Environment](updated)+ out, mapErr = mapper.MapOne[*Environment, environment.Environment](updated)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to map environment")}@@ -806,7 +809,7 @@ func (h *EnvironmentHandler) DeleteEnvironment(ctx context.Context, input *Deletreturn nil, huma.Error400BadRequest("Cannot delete local environment")}- user, _ := models.CurrentUserFromContext(ctx)+ user, _ := common.CurrentUserFromContext(ctx)var userID, username *stringif user != nil {userID = new(user.ID)@@ -845,7 +848,7 @@ func (h *EnvironmentHandler) TestConnection(ctx context.Context, input *TestConnif apiUrl == nil {resp.Message = new(err.Error())} else {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)err = huma.NewError(apiErr.HTTPStatus(), apiErr.Message)}return &TestConnectionOutput{@@ -962,7 +965,7 @@ func (h *EnvironmentHandler) handleEnvironmentPairingInternal(ctx context.Contex}}-func (h *EnvironmentHandler) triggerPostUpdateTasksInternal(ctx context.Context, environmentID string, updated *models.Environment, req *environment.Update) {+func (h *EnvironmentHandler) triggerPostUpdateTasksInternal(ctx context.Context, environmentID string, updated *Environment, req *environment.Update) {if updated.Enabled {detachedCtx := context.WithoutCancel(ctx)go func(syncCtx context.Context, envID string, envName string) {@@ -1029,12 +1032,12 @@ func (h *EnvironmentHandler) PairEnvironment(ctx context.Context, input *PairEnvreturn nil, huma.Error404NotFound("Environment not found")}- if env.Status != string(models.EnvironmentStatusPending) {+ if env.Status != string(EnvironmentStatusPending) {return nil, huma.Error400BadRequest("Environment is not in pending status")}updates := map[string]any{- "status": string(models.EnvironmentStatusOnline),+ "status": string(EnvironmentStatusOnline),}_, err = h.environmentService.UpdateEnvironment(ctx, *envID, updates, nil, nil)if err != nil {@@ -1240,10 +1243,10 @@ func (h *EnvironmentHandler) DownloadEdgeMTLSCA(ctx context.Context, _ *Downloadslog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS CA download", "fileName", fileName, "bytesWritten", written, "bytesExpected", len(caPEM), "error", writeErr)return}- h.logMTLSAuditEventInternal(humaCtx.Context(), nil, models.EventTypeEnvironmentMTLSDownload,+ h.logMTLSAuditEventInternal(humaCtx.Context(), nil, event.EventTypeEnvironmentMTLSDownload,"mTLS CA downloaded",fmt.Sprintf("Administrator downloaded edge mTLS CA %q", fileName),- models.JSON{+ database.JSON{"fileName": fileName,"kind": "ca",})@@ -1297,10 +1300,10 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSBundle(ctx context.Context,slog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS bundle download", "environmentID", input.ID, "fileName", fileName, "bytesWritten", written, "bytesExpected", archive.Len(), "error", writeErr)return}- h.logMTLSAuditEventInternal(humaCtx.Context(), env, models.EventTypeEnvironmentMTLSDownload,+ h.logMTLSAuditEventInternal(humaCtx.Context(), env, event.EventTypeEnvironmentMTLSDownload,"mTLS bundle downloaded",fmt.Sprintf("Administrator downloaded edge mTLS bundle %q (%d files)", fileName, len(files)),- models.JSON{+ database.JSON{"fileName": fileName,"kind": "bundle","fileCount": len(files),@@ -1328,10 +1331,10 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSFile(ctx context.Context, inslog.WarnContext(humaCtx.Context(), "Failed to stream edge mTLS asset download", "environmentID", input.ID, "fileName", file.Name, "bytesWritten", written, "bytesExpected", len(fileContent), "error", writeErr)return}- h.logMTLSAuditEventInternal(humaCtx.Context(), env, models.EventTypeEnvironmentMTLSDownload,+ h.logMTLSAuditEventInternal(humaCtx.Context(), env, event.EventTypeEnvironmentMTLSDownload,"mTLS asset downloaded",fmt.Sprintf("Administrator downloaded edge mTLS asset %q", file.Name),- models.JSON{+ database.JSON{"fileName": file.Name,"kind": "file","sensitive": isSensitiveMTLSAssetNameInternal(file.Name),@@ -1340,7 +1343,7 @@ func (h *EnvironmentHandler) DownloadEnvironmentMTLSFile(ctx context.Context, in}, nil}-func (h *EnvironmentHandler) loadEnvironmentMTLSEnvironmentInternal(ctx context.Context, environmentID string) (*models.Environment, error) {+func (h *EnvironmentHandler) loadEnvironmentMTLSEnvironmentInternal(ctx context.Context, environmentID string) (*Environment, error) {env, err := h.environmentService.GetEnvironmentByID(ctx, environmentID)if err != nil {return nil, huma.Error404NotFound("Environment not found")@@ -1361,7 +1364,7 @@ func (h *EnvironmentHandler) loadEnvironmentMTLSEnvironmentInternal(ctx context.return env, nil}-func (h *EnvironmentHandler) loadEnvironmentMTLSFilesInternal(ctx context.Context, environmentID string) (*models.Environment, []DeploymentSnippetFile, error) {+func (h *EnvironmentHandler) loadEnvironmentMTLSFilesInternal(ctx context.Context, environmentID string) (*Environment, []DeploymentSnippetFile, error) {env, err := h.loadEnvironmentMTLSEnvironmentInternal(ctx, environmentID)if err != nil {return nil, nil, err@@ -1385,7 +1388,7 @@ func (h *EnvironmentHandler) loadEnvironmentMTLSFilesInternal(ctx context.Contexreturn env, snippets.MTLS.Files, nil}-func (h *EnvironmentHandler) loadEnvironmentMTLSFileInternal(ctx context.Context, environmentID string, fileName string) (*models.Environment, DeploymentSnippetFile, error) {+func (h *EnvironmentHandler) loadEnvironmentMTLSFileInternal(ctx context.Context, environmentID string, fileName string) (*Environment, DeploymentSnippetFile, error) {env, files, err := h.loadEnvironmentMTLSFilesInternal(ctx, environmentID)if err != nil {return nil, DeploymentSnippetFile{}, err@@ -1409,7 +1412,7 @@ func isSensitiveMTLSAssetNameInternal(fileName string) bool {return strings.HasSuffix(name, ".key") || strings.HasSuffix(name, "-key.pem") || strings.HasSuffix(name, "_key.pem")}-func environmentMTLSDownloadBaseNameInternal(env *models.Environment) string {+func environmentMTLSDownloadBaseNameInternal(env *Environment) string {baseName := strings.TrimSpace(env.Name)if baseName == "" {baseName = "environment"@@ -1436,7 +1439,7 @@ func environmentMTLSDownloadBaseNameInternal(env *models.Environment) string {return baseName + "-" + env.ID}-func environmentMTLSAssetDownloadNameInternal(env *models.Environment, fileName string) string {+func environmentMTLSAssetDownloadNameInternal(env *Environment, fileName string) string {baseName := environmentMTLSDownloadBaseNameInternal(env)switch fileName {@@ -1462,12 +1465,12 @@ func environmentMTLSAssetFileModeInternal(file DeploymentSnippetFile) os.FileMod// logMTLSAuditEventInternal records an audit event for administrator-triggered// edge mTLS actions (downloads, bundle exports). Must never include raw// certificate content or private key material.-func (h *EnvironmentHandler) logMTLSAuditEventInternal(ctx context.Context, env *models.Environment, eventType models.EventType, title, description string, extra models.JSON) {+func (h *EnvironmentHandler) logMTLSAuditEventInternal(ctx context.Context, env *Environment, eventType event.EventType, title, description string, extra database.JSON) {if h == nil || h.eventService == nil {return}- user, _ := models.CurrentUserFromContext(ctx)+ user, _ := common.CurrentUserFromContext(ctx)var userID, username *stringif user != nil {userID = new(user.ID)@@ -1475,7 +1478,7 @@ func (h *EnvironmentHandler) logMTLSAuditEventInternal(ctx context.Context, env}if extra == nil {- extra = models.JSON{}+ extra = database.JSON{}}if remoteAddr := strings.TrimSpace(middleware.GetRemoteAddrFromContext(ctx)); remoteAddr != "" {extra["remoteAddr"] = remoteAddr@@ -1483,7 +1486,7 @@ func (h *EnvironmentHandler) logMTLSAuditEventInternal(ctx context.Context, envreq := event.CreateEventRequest{Type: eventType,- Severity: models.EventSeverityInfo,+ Severity: event.EventSeverityInfo,Title: title,Description: description,UserID: userID,diff --git a/backend/internal/models/environment.go b/backend/internal/environment/model.gosimilarity index 91%rename from backend/internal/models/environment.gorename to backend/internal/environment/model.goindex 8fb8ca1a6..d6e34216d 100644--- a/backend/internal/models/environment.go+++ b/backend/internal/environment/model.go@@ -1,9 +1,13 @@-package models+package environment-import "time"+import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"++ "time"+)type Environment struct {- BaseModel+ database.BaseModelName string `json:"name" sortable:"true"`ApiUrl string `json:"apiUrl" gorm:"column:api_url" sortable:"true"`diff --git a/backend/internal/environment/service_test.go b/backend/internal/environment/service_test.goindex b74075174..31fdf95c5 100644--- a/backend/internal/environment/service_test.go+++ b/backend/internal/environment/service_test.go@@ -1,6 +1,10 @@package environmentimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"++ "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"+"context""encoding/json""fmt"@@ -23,7 +27,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"@@ -95,6 +98,31 @@ func newAdmissionGateForEnvironmentTestInternal(t testing.TB) *actors.Gate[actorreturn gate}+// testProjectRow / testGitOpsSyncRow are minimal stand-ins for the project+// domain's models: the project package imports environment, so this in-package+// test cannot import it. Only the columns the cascade path touches are declared.+type testProjectRow struct {+ database.BaseModel+ Name string+ Path string+ Status string+ GitOpsManagedBy *string `gorm:"column:gitops_managed_by"`+}++func (testProjectRow) TableName() string { return "projects" }++type testGitOpsSyncRow struct {+ database.BaseModel+ Name string+ EnvironmentID string+ RepositoryID string+ ComposePath string+ ProjectName string+ SyncInterval int+}++func (testGitOpsSyncRow) TableName() string { return "gitops_syncs" }+func setupEnvironmentServiceTestDB(t *testing.T) *database.DB {t.Helper()@@ -102,13 +130,13 @@ func setupEnvironmentServiceTestDB(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.Environment{},- &models.ContainerRegistry{},- &models.SettingVariable{},- &models.User{},- &models.ApiKey{},- &models.Project{},- &models.GitOpsSync{},+ &Environment{},+ ®istry.ContainerRegistry{},+ &settings.SettingVariable{},+ &common.User{},+ &apikey.ApiKey{},+ &testProjectRow{},+ &testGitOpsSyncRow{},))sqlDB, err := db.DB()@@ -129,11 +157,11 @@ func setupEnvironmentServiceTestDB(t *testing.T) *database.DB {return &database.DB{DB: db}}-func createTestEnvironmentServiceUser(t *testing.T, ctx context.Context, userService *user.UserService, id string) *models.User {+func createTestEnvironmentServiceUser(t *testing.T, ctx context.Context, userService *user.UserService, id string) *common.User {t.Helper()- user := &models.User{- BaseModel: models.BaseModel{ID: id},+ user := &common.User{+ BaseModel: database.BaseModel{ID: id},Username: fmt.Sprintf("user-%s", id),}@@ -151,15 +179,15 @@ func createNamedTestEnvironmentInternal(t *testing.T, db *database.DB, id, name,t.Helper()now := time.Now()- env := &models.Environment{- BaseModel: models.BaseModel{+ env := &Environment{+ BaseModel: database.BaseModel{ID: id,CreatedAt: now,UpdatedAt: &now,},Name: name,ApiUrl: apiURL,- Status: string(models.EnvironmentStatusOnline),+ Status: string(EnvironmentStatusOnline),Enabled: true,AccessToken: accessToken,}@@ -171,8 +199,8 @@ func createTestEnvironmentWithState(t *testing.T, db *database.DB, id, apiURL, st.Helper()now := time.Now()- env := &models.Environment{- BaseModel: models.BaseModel{+ env := &Environment{+ BaseModel: database.BaseModel{ID: id,CreatedAt: now,UpdatedAt: &now,@@ -191,12 +219,12 @@ func createTestEnvironmentWithState(t *testing.T, db *database.DB, id, apiURL, sfunc TestEnvironmentService_DeleteEnvironment_CascadesGitOpsSyncs(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- require.NoError(t, db.AutoMigrate(&models.Project{}, &models.GitOpsSync{}))+ require.NoError(t, db.AutoMigrate(&testProjectRow{}, &testGitOpsSyncRow{}))createTestEnvironment(t, db, "env-delete-gitops", "http://env.example", nil)syncID := "sync-delete-env"- require.NoError(t, db.Create(&models.GitOpsSync{- BaseModel: models.BaseModel{ID: syncID},+ require.NoError(t, db.Create(&testGitOpsSyncRow{+ BaseModel: database.BaseModel{ID: syncID},Name: "delete-env-sync",EnvironmentID: "env-delete-gitops",RepositoryID: "repo-1",@@ -204,11 +232,11 @@ func TestEnvironmentService_DeleteEnvironment_CascadesGitOpsSyncs(t *testing.T)ProjectName: "demo",SyncInterval: 15,}).Error)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-managed-by-deleted-env"},+ require.NoError(t, db.Create(&testProjectRow{+ BaseModel: database.BaseModel{ID: "project-managed-by-deleted-env"},Name: "demo",Path: "/tmp/demo",- Status: models.ProjectStatusStopped,+ Status: "stopped",GitOpsManagedBy: &syncID,}).Error)@@ -219,10 +247,10 @@ func TestEnvironmentService_DeleteEnvironment_CascadesGitOpsSyncs(t *testing.T)require.NoError(t, svc.DeleteEnvironment(ctx, "env-delete-gitops", nil, nil))var syncCount int64- require.NoError(t, db.Model(&models.GitOpsSync{}).Where("id = ?", syncID).Count(&syncCount).Error)+ require.NoError(t, db.Model(&testGitOpsSyncRow{}).Where("id = ?", syncID).Count(&syncCount).Error)require.Zero(t, syncCount)- var project models.Project+ var project testProjectRowrequire.NoError(t, db.First(&project, "id = ?", "project-managed-by-deleted-env").Error)require.Nil(t, project.GitOpsManagedBy)require.Contains(t, scheduler.removed, entityjobs.GitOpsSyncJobPrefix+syncID)@@ -235,8 +263,8 @@ func createTestRegistry(t *testing.T, db *database.DB, id string) {require.NoError(t, err)now := time.Now()- registry := &models.ContainerRegistry{- BaseModel: models.BaseModel{+ registry := ®istry.ContainerRegistry{+ BaseModel: database.BaseModel{ID: id,CreatedAt: now,UpdatedAt: &now,@@ -261,8 +289,8 @@ func createTestECRRegistry(t *testing.T, db *database.DB, id string) {require.NoError(t, err)now := time.Now()- registry := &models.ContainerRegistry{- BaseModel: models.BaseModel{+ registry := ®istry.ContainerRegistry{+ BaseModel: database.BaseModel{ID: id,CreatedAt: now,UpdatedAt: &now,@@ -280,7 +308,7 @@ func createTestECRRegistry(t *testing.T, db *database.DB, id string) {require.NoError(t, db.WithContext(context.Background()).Create(registry).Error)}-func createTestGitRepository(t *testing.T, db *database.DB, repository models.GitRepository) {+func createTestGitRepository(t *testing.T, db *database.DB, repository gitrepo.GitRepository) {t.Helper()require.NoError(t, db.Create(&repository).Error)}@@ -429,11 +457,11 @@ func TestEnvironmentService_SyncRegistriesToEnvironment_IncludesECRFields(t *tesfunc TestEnvironmentService_SyncRepositoriesToEnvironment_UsesAgentHeaders(t *testing.T) {ctx := context.Background()db := setupEnvironmentServiceTestDB(t)- require.NoError(t, db.AutoMigrate(&models.GitRepository{}))+ require.NoError(t, db.AutoMigrate(&gitrepo.GitRepository{}))svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)- createTestGitRepository(t, db, models.GitRepository{- BaseModel: models.BaseModel{ID: "repo-1", CreatedAt: time.Now()},+ createTestGitRepository(t, db, gitrepo.GitRepository{+ BaseModel: database.BaseModel{ID: "repo-1", CreatedAt: time.Now()},Name: "repo-1",URL: "https://github.com/getarcaneapp/arcane.git",AuthType: "http",@@ -535,29 +563,29 @@ func TestEnvironmentService_ReconcileEdgeStatusesOnStartup(t *testing.T) {db := setupEnvironmentServiceTestDB(t)svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)- createTestEnvironmentWithState(t, db, "edge-online", "edge://online", string(models.EnvironmentStatusOnline), true, nil)- createTestEnvironmentWithState(t, db, "edge-error", "edge://error", string(models.EnvironmentStatusError), true, nil)- createTestEnvironmentWithState(t, db, "edge-pending", "edge://pending", string(models.EnvironmentStatusPending), true, nil)- createTestEnvironmentWithState(t, db, "remote-http", "http://remote.example", string(models.EnvironmentStatusOnline), false, nil)+ createTestEnvironmentWithState(t, db, "edge-online", "edge://online", string(EnvironmentStatusOnline), true, nil)+ createTestEnvironmentWithState(t, db, "edge-error", "edge://error", string(EnvironmentStatusError), true, nil)+ createTestEnvironmentWithState(t, db, "edge-pending", "edge://pending", string(EnvironmentStatusPending), true, nil)+ createTestEnvironmentWithState(t, db, "remote-http", "http://remote.example", string(EnvironmentStatusOnline), false, nil)err := svc.ReconcileEdgeStatusesOnStartup(ctx)require.NoError(t, err)- var edgeOnline models.Environment+ var edgeOnline Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "edge-online").First(&edgeOnline).Error)- require.Equal(t, string(models.EnvironmentStatusOffline), edgeOnline.Status)+ require.Equal(t, string(EnvironmentStatusOffline), edgeOnline.Status)- var edgeError models.Environment+ var edgeError Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "edge-error").First(&edgeError).Error)- require.Equal(t, string(models.EnvironmentStatusOffline), edgeError.Status)+ require.Equal(t, string(EnvironmentStatusOffline), edgeError.Status)- var edgePending models.Environment+ var edgePending Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "edge-pending").First(&edgePending).Error)- require.Equal(t, string(models.EnvironmentStatusPending), edgePending.Status)+ require.Equal(t, string(EnvironmentStatusPending), edgePending.Status)- var remoteHTTP models.Environment+ var remoteHTTP Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "remote-http").First(&remoteHTTP).Error)- require.Equal(t, string(models.EnvironmentStatusOnline), remoteHTTP.Status)+ require.Equal(t, string(EnvironmentStatusOnline), remoteHTTP.Status)}func TestEnvironmentService_UpdateEnvironmentConnectionState(t *testing.T) {@@ -565,14 +593,14 @@ func TestEnvironmentService_UpdateEnvironmentConnectionState(t *testing.T) {db := setupEnvironmentServiceTestDB(t)svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)- createTestEnvironmentWithState(t, db, "edge-runtime", "edge://runtime", string(models.EnvironmentStatusOffline), true, nil)+ createTestEnvironmentWithState(t, db, "edge-runtime", "edge://runtime", string(EnvironmentStatusOffline), true, nil)err := svc.UpdateEnvironmentConnectionState(ctx, "edge-runtime", true)require.NoError(t, err)- var env models.Environment+ var env Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "edge-runtime").First(&env).Error)- require.Equal(t, string(models.EnvironmentStatusOnline), env.Status)+ require.Equal(t, string(EnvironmentStatusOnline), env.Status)require.NotNil(t, env.LastSeen)lastSeen := env.LastSeen@@ -581,7 +609,7 @@ func TestEnvironmentService_UpdateEnvironmentConnectionState(t *testing.T) {require.NoError(t, err)require.NoError(t, db.WithContext(ctx).Where("id = ?", "edge-runtime").First(&env).Error)- require.Equal(t, string(models.EnvironmentStatusOffline), env.Status)+ require.Equal(t, string(EnvironmentStatusOffline), env.Status)require.NotNil(t, env.LastSeen)require.Equal(t, *lastSeen, *env.LastSeen)}@@ -591,13 +619,13 @@ func TestEnvironmentService_UpdateEnvironmentStatusInternal_PromotesPendingDirecdb := setupEnvironmentServiceTestDB(t)svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)- createTestEnvironmentWithState(t, db, "direct-pending", "http://agent:3553", string(models.EnvironmentStatusPending), false, nil)+ createTestEnvironmentWithState(t, db, "direct-pending", "http://agent:3553", string(EnvironmentStatusPending), false, nil)- require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "direct-pending", string(models.EnvironmentStatusOnline)))+ require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "direct-pending", string(EnvironmentStatusOnline)))- var env models.Environment+ var env Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "direct-pending").First(&env).Error)- require.Equal(t, string(models.EnvironmentStatusOnline), env.Status)+ require.Equal(t, string(EnvironmentStatusOnline), env.Status)require.NotNil(t, env.LastSeen)}@@ -606,17 +634,17 @@ func TestEnvironmentService_UpdateEnvironmentStatusInternal_DoesNotDemotePendingdb := setupEnvironmentServiceTestDB(t)svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)- createTestEnvironmentWithState(t, db, "direct-pending", "http://agent:3553", string(models.EnvironmentStatusPending), false, nil)+ createTestEnvironmentWithState(t, db, "direct-pending", "http://agent:3553", string(EnvironmentStatusPending), false, nil)// A transient health-check failure before pairing completes must NOT flip a// pending Direct env to offline/error — the env should stay pending so a later// successful tick can still promote it to online.- require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "direct-pending", string(models.EnvironmentStatusOffline)))- require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "direct-pending", string(models.EnvironmentStatusError)))+ require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "direct-pending", string(EnvironmentStatusOffline)))+ require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "direct-pending", string(EnvironmentStatusError)))- var env models.Environment+ var env Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "direct-pending").First(&env).Error)- require.Equal(t, string(models.EnvironmentStatusPending), env.Status)+ require.Equal(t, string(EnvironmentStatusPending), env.Status)require.Nil(t, env.LastSeen)}@@ -625,15 +653,15 @@ func TestEnvironmentService_UpdateEnvironmentStatusInternal_LeavesPendingEdgeEnvdb := setupEnvironmentServiceTestDB(t)svc := NewEnvironmentService(db, nil, nil, nil, nil, nil)- createTestEnvironmentWithState(t, db, "edge-pending", "edge://agent", string(models.EnvironmentStatusPending), true, nil)+ createTestEnvironmentWithState(t, db, "edge-pending", "edge://agent", string(EnvironmentStatusPending), true, nil)// Edge envs in pending must complete pairing via the agent's outbound tunnel;// a manager-side reachability tick must NOT promote them.- require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "edge-pending", string(models.EnvironmentStatusOnline)))+ require.NoError(t, svc.updateEnvironmentStatusInternal(ctx, "edge-pending", string(EnvironmentStatusOnline)))- var env models.Environment+ var env Environmentrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "edge-pending").First(&env).Error)- require.Equal(t, string(models.EnvironmentStatusPending), env.Status)+ require.Equal(t, string(EnvironmentStatusPending), env.Status)require.Nil(t, env.LastSeen)}@@ -644,7 +672,7 @@ func TestEnvironmentService_ResolveEdgeEnvironmentByToken_CachesAndInvalidatesOnoldToken := "edge-token-old"newToken := "edge-token-new"- createTestEnvironmentWithState(t, db, "edge-auth", "edge://auth", string(models.EnvironmentStatusPending), true, &oldToken)+ createTestEnvironmentWithState(t, db, "edge-auth", "edge://auth", string(EnvironmentStatusPending), true, &oldToken)envID, err := svc.ResolveEdgeEnvironmentByToken(ctx, oldToken)require.NoError(t, err)@@ -673,7 +701,7 @@ func TestEnvironmentService_UpdateEnvironment_ClearingAccessTokenInvalidatesCachsvc := NewEnvironmentService(db, nil, nil, nil, nil, nil)oldToken := "edge-token-clear"- createTestEnvironmentWithState(t, db, "edge-auth-clear", "edge://auth-clear", string(models.EnvironmentStatusPending), true, &oldToken)+ createTestEnvironmentWithState(t, db, "edge-auth-clear", "edge://auth-clear", string(EnvironmentStatusPending), true, &oldToken)envID, err := svc.ResolveEdgeEnvironmentByToken(ctx, oldToken)require.NoError(t, err)@@ -712,7 +740,7 @@ func TestEnvironmentServiceUpdateEnvironmentRejectsTargetChangeWithStoredTokenInrequire.ErrorIs(t, err, common.ErrValidation)require.NotContains(t, updates, "updated_at")- var stored models.Environment+ var stored Environmentrequire.NoError(t, db.WithContext(ctx).First(&stored, "id = ?", "env-target").Error)require.Equal(t, "http://agent.example:3553", stored.ApiUrl)require.Equal(t, oldToken, *stored.AccessToken)@@ -828,7 +856,7 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesVisibleEnvirorequire.False(t, createdEnv.Hidden)require.True(t, createdEnv.IsEdge)require.True(t, createdEnv.Enabled)- require.Equal(t, string(models.EnvironmentStatusPending), createdEnv.Status)+ require.Equal(t, string(EnvironmentStatusPending), createdEnv.Status)require.NotNil(t, createdEnv.ParentEnvironmentID)require.Equal(t, "manager-env", *createdEnv.ParentEnvironmentID)require.NotNil(t, createdEnv.SwarmNodeID)@@ -837,14 +865,14 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesVisibleEnvirorequire.Equal(t, createdToken, *createdEnv.AccessToken)require.NotNil(t, createdEnv.ApiKeyID)- var childEnvironments []models.Environment+ var childEnvironments []Environmentrequire.NoError(t, db.WithContext(ctx).Where("parent_environment_id = ?", "manager-env").Where("swarm_node_id = ?", "node-1234567890abcdef").Find(&childEnvironments).Error)require.Len(t, childEnvironments, 1)- var apiKeys []models.ApiKey+ var apiKeys []apikey.ApiKeyrequire.NoError(t, db.WithContext(ctx).Where("environment_id = ?", createdEnv.ID).Order("created_at asc").@@ -867,7 +895,7 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_CreatesVisibleEnvirorequire.Equal(t, createdToken, reusedToken)require.Equal(t, createdEnv.ApiKeyID, reusedEnv.ApiKeyID)- var apiKeysAfterReuse []models.ApiKey+ var apiKeysAfterReuse []apikey.ApiKeyrequire.NoError(t, db.WithContext(ctx).Where("environment_id = ?", createdEnv.ID).Order("created_at asc").@@ -882,11 +910,11 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenReparentEnvironmentID := "manager-env"nodeID := "legacy-node"token := "legacy-agent-token"- legacy := &models.Environment{- BaseModel: models.BaseModel{ID: "legacy-agent"},+ legacy := &Environment{+ BaseModel: database.BaseModel{ID: "legacy-agent"},Name: "Legacy node agent",ApiUrl: "edge://legacy-node",- Status: string(models.EnvironmentStatusOffline),+ Status: string(EnvironmentStatusOffline),Enabled: true,IsEdge: true,Hidden: true,@@ -922,7 +950,7 @@ func TestEnvironmentService_EnsureSwarmNodeAgentEnvironment_ReusesLegacyHiddenRerequire.Equal(t, token, reusedToken,"token = %q, want existing token", reusedToken)- var environments []models.Environment+ var environments []Environment{err := db.WithContext(ctx).Where("parent_environment_id = ? AND swarm_node_id = ?", parentEnvironmentID, nodeID).@@ -1046,7 +1074,7 @@ func TestEnvironmentService_ListMethods_ExcludeHiddenEnvironments(t *testing.T)createNamedTestEnvironmentInternal(t, db, "env-hidden", "Hidden Node Agent", "edge://swarm-node-hidden", new("hidden-token"))require.NoError(t, db.WithContext(ctx).- Model(&models.Environment{}).+ Model(&Environment{}).Where("id = ?", "env-hidden").Updates(map[string]any{"hidden": true,@@ -1122,51 +1150,51 @@ func TestEnvironmentService_ListEnvironmentsPaginated_FiltersByRuntimeType(t *tesvc := NewEnvironmentService(db, nil, nil, nil, nil, nil)now := time.Now()- envs := []models.Environment{+ envs := []Environment{{- BaseModel: models.BaseModel{ID: "0", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "0", CreatedAt: now, UpdatedAt: &now},Name: "Local",ApiUrl: "http://localhost:3552",- Status: string(models.EnvironmentStatusOnline),+ Status: string(EnvironmentStatusOnline),Enabled: true,},{- BaseModel: models.BaseModel{ID: "env-edge", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "env-edge", CreatedAt: now, UpdatedAt: &now},Name: "Edge",ApiUrl: "edge://agent",- Status: string(models.EnvironmentStatusOffline),+ Status: string(EnvironmentStatusOffline),Enabled: true,IsEdge: true,},{- BaseModel: models.BaseModel{ID: "env-grpc", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "env-grpc", CreatedAt: now, UpdatedAt: &now},Name: "gRPC",ApiUrl: "edge://grpc",- Status: string(models.EnvironmentStatusOffline),+ Status: string(EnvironmentStatusOffline),Enabled: true,IsEdge: true,},{- BaseModel: models.BaseModel{ID: "env-websocket", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "env-websocket", CreatedAt: now, UpdatedAt: &now},Name: "WebSocket",ApiUrl: "edge://websocket",- Status: string(models.EnvironmentStatusOffline),+ Status: string(EnvironmentStatusOffline),Enabled: true,IsEdge: true,},{- BaseModel: models.BaseModel{ID: "env-polling", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "env-polling", CreatedAt: now, UpdatedAt: &now},Name: "Polling",ApiUrl: "edge://polling",- Status: string(models.EnvironmentStatusOffline),+ Status: string(EnvironmentStatusOffline),Enabled: true,IsEdge: true,},{- BaseModel: models.BaseModel{ID: "env-last-ws", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "env-last-ws", CreatedAt: now, UpdatedAt: &now},Name: "LastWebsocket",ApiUrl: "edge://last-ws",- Status: string(models.EnvironmentStatusOffline),+ Status: string(EnvironmentStatusOffline),Enabled: true,IsEdge: true,LastEdgeTransport: new("websocket"),diff --git a/backend/internal/models/event.go b/backend/internal/event/model.gosimilarity index 97%rename from backend/internal/models/event.gorename to backend/internal/event/model.goindex bb08b2352..2dcd522d4 100644--- a/backend/internal/models/event.go+++ b/backend/internal/event/model.go@@ -1,6 +1,8 @@-package models+package eventimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"time")@@ -113,7 +115,7 @@ const ()type Event struct {- BaseModel+ database.BaseModelType EventType `json:"type" sortable:"true"`Severity EventSeverity `json:"severity" sortable:"true"`@@ -125,7 +127,7 @@ type Event struct {UserID *string `json:"userId,omitempty" sortable:"true"`Username *string `json:"username,omitempty" sortable:"true"`EnvironmentID *string `json:"environmentId,omitempty"`- Metadata JSON `json:"metadata,omitempty" gorm:"type:text"`+ Metadata database.JSON `json:"metadata,omitempty" gorm:"type:text"`Timestamp time.Time `json:"timestamp" sortable:"true"`}diff --git a/backend/internal/event/service.go b/backend/internal/event/service.goindex 6b46ef49e..49ccb20e6 100644--- a/backend/internal/event/service.go+++ b/backend/internal/event/service.go@@ -16,7 +16,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -49,27 +48,27 @@ func NewEventService(db *database.DB, cfg *config.Config, httpClient *http.Clien}type CreateEventRequest struct {- Type models.EventType `json:"type"`- Severity models.EventSeverity `json:"severity,omitempty"`- Title string `json:"title"`- Description string `json:"description,omitempty"`- ResourceType *string `json:"resourceType,omitempty"`- ResourceID *string `json:"resourceId,omitempty"`- ResourceName *string `json:"resourceName,omitempty"`- UserID *string `json:"userId,omitempty"`- Username *string `json:"username,omitempty"`- EnvironmentID *string `json:"environmentId,omitempty"`- Metadata models.JSON `json:"metadata,omitempty"`-}--func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest) (*models.Event, error) {+ Type EventType `json:"type"`+ Severity EventSeverity `json:"severity,omitempty"`+ Title string `json:"title"`+ Description string `json:"description,omitempty"`+ ResourceType *string `json:"resourceType,omitempty"`+ ResourceID *string `json:"resourceId,omitempty"`+ ResourceName *string `json:"resourceName,omitempty"`+ UserID *string `json:"userId,omitempty"`+ Username *string `json:"username,omitempty"`+ EnvironmentID *string `json:"environmentId,omitempty"`+ Metadata database.JSON `json:"metadata,omitempty"`+}++func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest) (*Event, error) {severity := req.Severityif severity == "" {- severity = models.EventSeverityInfo+ severity = EventSeverityInfo}userID, username := normalizeEventActor(req.UserID, req.Username)- eventRecord := &models.Event{+ eventRecord := &Event{Type: req.Type,Severity: severity,Title: req.Title,@@ -82,7 +81,7 @@ func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest)EnvironmentID: req.EnvironmentID,Metadata: req.Metadata,Timestamp: time.Now(),- BaseModel: models.BaseModel{+ BaseModel: database.BaseModel{CreatedAt: time.Now(),},}@@ -102,7 +101,7 @@ func (s *EventService) CreateEvent(ctx context.Context, req CreateEventRequest)return eventRecord, nil}-func (s *EventService) forwardEventToManager(ctx context.Context, eventModel *models.Event) {+func (s *EventService) forwardEventToManager(ctx context.Context, eventModel *Event) {if eventModel == nil || s.cfg == nil || !s.cfg.AgentMode {return}@@ -167,7 +166,7 @@ func (s *EventService) canForwardEventToManagerHTTP() bool {return strings.TrimSpace(s.cfg.GetManagerBaseURL()) != ""}-func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModel *models.Event) error {+func (s *EventService) forwardEventToManagerHTTP(ctx context.Context, eventModel *Event) error {if eventModel == nil {return errors.New("event is required")}@@ -286,8 +285,8 @@ func copyOptionalStringPtr(value *string) *string {}func (s *EventService) ListEventsPaginated(ctx context.Context, params pagination.QueryParams) ([]eventtypes.Event, pagination.Response, error) {- var events []models.Event- q := s.db.WithContext(ctx).Model(&models.Event{})+ var events []Event+ q := s.db.WithContext(ctx).Model(&Event{})if term := strings.TrimSpace(params.Search); term != "" {searchPattern := "%" + term + "%"@@ -308,7 +307,7 @@ func (s *EventService) ListEventsPaginated(ctx context.Context, params paginatioreturn nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")}- eventDtos, mapErr := mapper.MapSlice[models.Event, eventtypes.Event](events)+ eventDtos, mapErr := mapper.MapSlice[Event, eventtypes.Event](events)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")}@@ -317,8 +316,8 @@ func (s *EventService) ListEventsPaginated(ctx context.Context, params paginatio}func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]eventtypes.Event, pagination.Response, error) {- var events []models.Event- q := s.db.WithContext(ctx).Model(&models.Event{}).Where("environment_id = ?", environmentID)+ var events []Event+ q := s.db.WithContext(ctx).Model(&Event{}).Where("environment_id = ?", environmentID)if term := strings.TrimSpace(params.Search); term != "" {searchPattern := "%" + term + "%"@@ -338,7 +337,7 @@ func (s *EventService) GetEventsByEnvironmentPaginated(ctx context.Context, envireturn nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate events")}- eventDtos, mapErr := mapper.MapSlice[models.Event, eventtypes.Event](events)+ eventDtos, mapErr := mapper.MapSlice[Event, eventtypes.Event](events)if mapErr != nil {return nil, pagination.Response{}, errors.WrapIf(mapErr, "failed to map events")}@@ -395,7 +394,7 @@ func (s *EventService) GetEventSeverityCounts(ctx context.Context) (EventSeveritSeverity stringCount int64}- if err := s.db.WithContext(ctx).Model(&models.Event{}).+ if err := s.db.WithContext(ctx).Model(&Event{}).Select("severity, COUNT(*) AS count").Group("severity").Scan(&rows).Error; err != nil {@@ -404,14 +403,14 @@ func (s *EventService) GetEventSeverityCounts(ctx context.Context) (EventSeveritvar counts EventSeverityCountsfor _, r := range rows {- switch models.EventSeverity(r.Severity) {- case models.EventSeveritySuccess:+ switch EventSeverity(r.Severity) {+ case EventSeveritySuccess:counts.Success = r.Count- case models.EventSeverityWarning:+ case EventSeverityWarning:counts.Warning = r.Count- case models.EventSeverityError:+ case EventSeverityError:counts.Error = r.Count- case models.EventSeverityInfo:+ case EventSeverityInfo:counts.Info += r.Countdefault:// Unclassified severities fold into Info.@@ -424,7 +423,7 @@ func (s *EventService) GetEventSeverityCounts(ctx context.Context) (EventSeveritfunc (s *EventService) DeleteEvent(ctx context.Context, eventID string) error {return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- result := tx.Delete(&models.Event{}, "id = ?", eventID)+ result := tx.Delete(&Event{}, "id = ?", eventID)if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete event")}@@ -438,7 +437,7 @@ func (s *EventService) DeleteEvent(ctx context.Context, eventID string) error {func (s *EventService) DeleteOldEvents(ctx context.Context, olderThan time.Duration) error {cutoff := time.Now().Add(-olderThan)return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- result := tx.Where("timestamp < ?", cutoff).Delete(&models.Event{})+ result := tx.Where("timestamp < ?", cutoff).Delete(&Event{})if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete old events")}@@ -446,7 +445,7 @@ func (s *EventService) DeleteOldEvents(ctx context.Context, olderThan time.Durat})}-func (s *EventService) LogContainerEvent(ctx context.Context, eventType models.EventType, containerID, containerName, userID, username, environmentID string, metadata models.JSON) error {+func (s *EventService) LogContainerEvent(ctx context.Context, eventType EventType, containerID, containerName, userID, username, environmentID string, metadata database.JSON) error {title := s.generateEventTitle(eventType, containerName)description := s.generateEventDescription(eventType, "container", containerName)severity := s.getEventSeverity(eventType)@@ -467,7 +466,7 @@ func (s *EventService) LogContainerEvent(ctx context.Context, eventType models.Ereturn err}-func (s *EventService) LogImageEvent(ctx context.Context, eventType models.EventType, imageID, imageName, userID, username, environmentID string, metadata models.JSON) error {+func (s *EventService) LogImageEvent(ctx context.Context, eventType EventType, imageID, imageName, userID, username, environmentID string, metadata database.JSON) error {title := s.generateEventTitle(eventType, imageName)description := s.generateEventDescription(eventType, "image", imageName)severity := s.getEventSeverity(eventType)@@ -488,7 +487,7 @@ func (s *EventService) LogImageEvent(ctx context.Context, eventType models.Eventreturn err}-func (s *EventService) LogProjectEvent(ctx context.Context, eventType models.EventType, projectID, projectName, userID, username, environmentID string, metadata models.JSON) error {+func (s *EventService) LogProjectEvent(ctx context.Context, eventType EventType, projectID, projectName, userID, username, environmentID string, metadata database.JSON) error {title := s.generateEventTitle(eventType, projectName)description := s.generateEventDescription(eventType, "project", projectName)severity := s.getEventSeverity(eventType)@@ -509,7 +508,7 @@ func (s *EventService) LogProjectEvent(ctx context.Context, eventType models.Evereturn err}-func (s *EventService) LogUserEvent(ctx context.Context, eventType models.EventType, userID, username string, metadata models.JSON) error {+func (s *EventService) LogUserEvent(ctx context.Context, eventType EventType, userID, username string, metadata database.JSON) error {title := s.generateEventTitle(eventType, username)description := s.generateEventDescription(eventType, "user", username)severity := s.getEventSeverity(eventType)@@ -526,7 +525,7 @@ func (s *EventService) LogUserEvent(ctx context.Context, eventType models.EventTreturn err}-func (s *EventService) LogVolumeEvent(ctx context.Context, eventType models.EventType, volumeID, volumeName, userID, username, environmentID string, metadata models.JSON) error {+func (s *EventService) LogVolumeEvent(ctx context.Context, eventType EventType, volumeID, volumeName, userID, username, environmentID string, metadata database.JSON) error {title := s.generateEventTitle(eventType, volumeName)description := s.generateEventDescription(eventType, "volume", volumeName)severity := s.getEventSeverity(eventType)@@ -547,7 +546,7 @@ func (s *EventService) LogVolumeEvent(ctx context.Context, eventType models.Evenreturn err}-func (s *EventService) LogNetworkEvent(ctx context.Context, eventType models.EventType, networkID, networkName, userID, username, environmentID string, metadata models.JSON) error {+func (s *EventService) LogNetworkEvent(ctx context.Context, eventType EventType, networkID, networkName, userID, username, environmentID string, metadata database.JSON) error {title := s.generateEventTitle(eventType, networkName)description := s.generateEventDescription(eventType, "network", networkName)severity := s.getEventSeverity(eventType)@@ -568,7 +567,7 @@ func (s *EventService) LogNetworkEvent(ctx context.Context, eventType models.Evereturn err}-func (s *EventService) LogErrorEvent(ctx context.Context, eventType models.EventType, resourceType, resourceID, resourceName, userID, username, environmentID string, err error, metadata models.JSON) {+func (s *EventService) LogErrorEvent(ctx context.Context, eventType EventType, resourceType, resourceID, resourceName, userID, username, environmentID string, err error, metadata database.JSON) {if err == nil {return}@@ -590,7 +589,7 @@ func (s *EventService) LogErrorEvent(ctx context.Context, eventType models.Event_, logErr := s.CreateEvent(logCtx, CreateEventRequest{Type: eventType,- Severity: models.EventSeverityError,+ Severity: EventSeverityError,Title: title,Description: description,ResourceType: new(resourceType),@@ -606,12 +605,12 @@ func (s *EventService) LogErrorEvent(ctx context.Context, eventType models.Event}}-func cloneEventMetadataInternal(metadata models.JSON) models.JSON {+func cloneEventMetadataInternal(metadata database.JSON) database.JSON {if metadata == nil {- return models.JSON{}+ return database.JSON{}}- cloned := make(models.JSON, len(metadata))+ cloned := make(database.JSON, len(metadata))for k, v := range metadata {cloned[k] = cloneEventMetadataValueInternal(v)}@@ -620,7 +619,7 @@ func cloneEventMetadataInternal(metadata models.JSON) models.JSON {func cloneEventMetadataValueInternal(value any) any {switch typed := value.(type) {- case models.JSON:+ case database.JSON:return cloneEventMetadataInternal(typed)case map[string]any:return cloneEventMetadataInternal(typed)@@ -638,68 +637,68 @@ func cloneEventMetadataValueInternal(value any) any {type eventDefinition struct {TitleFormat stringDescriptionFormat string- Severity models.EventSeverity-}--var eventDefinitions = map[models.EventType]eventDefinition{- models.EventTypeContainerStart: {"Container started: %s", "Container '%s' has been started", models.EventSeveritySuccess},- models.EventTypeContainerStop: {"Container stopped: %s", "Container '%s' has been stopped", models.EventSeverityInfo},- models.EventTypeContainerRestart: {"Container restarted: %s", "Container '%s' has been restarted", models.EventSeverityInfo},- models.EventTypeContainerDelete: {"Container deleted: %s", "Container '%s' has been deleted", models.EventSeverityWarning},- models.EventTypeContainerCreate: {"Container created: %s", "Container '%s' has been created", models.EventSeveritySuccess},- models.EventTypeContainerScan: {"Container scanned: %s", "Security scan completed for container '%s'", models.EventSeverityInfo},- models.EventTypeContainerUpdate: {"Container updated: %s", "Container '%s' has been updated", models.EventSeverityInfo},- models.EventTypeContainerError: {"Container error: %s", "An error occurred with container '%s'", models.EventSeverityError},-- models.EventTypeImagePull: {"Image pulled: %s", "Image '%s' has been pulled", models.EventSeveritySuccess},- models.EventTypeImageLoad: {"Image loaded: %s", "Image '%s' has been loaded from archive", models.EventSeveritySuccess},- models.EventTypeImageDelete: {"Image deleted: %s", "Image '%s' has been deleted", models.EventSeverityWarning},- models.EventTypeImageScan: {"Image scanned: %s", "Security scan completed for image '%s'", models.EventSeverityInfo},- models.EventTypeImageError: {"Image error: %s", "An error occurred with image '%s'", models.EventSeverityError},-- models.EventTypeProjectDeploy: {"Project deployed: %s", "Project '%s' has been deployed", models.EventSeveritySuccess},- models.EventTypeProjectDelete: {"Project deleted: %s", "Project '%s' has been deleted", models.EventSeverityWarning},- models.EventTypeProjectStart: {"Project started: %s", "Project '%s' has been started", models.EventSeveritySuccess},- models.EventTypeProjectStop: {"Project stopped: %s", "Project '%s' has been stopped", models.EventSeverityInfo},- models.EventTypeProjectCreate: {"Project created: %s", "Project '%s' has been created", models.EventSeveritySuccess},- models.EventTypeProjectUpdate: {"Project updated: %s", "Project '%s' has been updated", models.EventSeverityInfo},- models.EventTypeProjectError: {"Project error: %s", "An error occurred with project '%s'", models.EventSeverityError},-- models.EventTypeVolumeCreate: {"Volume created: %s", "Volume '%s' has been created", models.EventSeveritySuccess},- models.EventTypeVolumeDelete: {"Volume deleted: %s", "Volume '%s' has been deleted", models.EventSeverityWarning},- models.EventTypeVolumeError: {"Volume error: %s", "An error occurred with volume '%s'", models.EventSeverityError},- models.EventTypeVolumeFileCreate: {"Volume file created: %s", "A file or directory was created in volume '%s'", models.EventSeveritySuccess},- models.EventTypeVolumeFileDelete: {"Volume file deleted: %s", "A file or directory was deleted in volume '%s'", models.EventSeverityWarning},- models.EventTypeVolumeFileUpload: {"Volume file uploaded: %s", "A file was uploaded to volume '%s'", models.EventSeveritySuccess},- models.EventTypeVolumeFileUpdate: {"Volume workspace updated: %s", "Files in volume '%s' were updated", models.EventSeverityInfo},- models.EventTypeVolumeWorkspaceUpdate: {"Volume workspace updated: %s", "Workspace files in volume '%s' were updated", models.EventSeverityInfo},- models.EventTypeVolumeBackupCreate: {"Volume backup created: %s", "A backup was created for volume '%s'", models.EventSeveritySuccess},- models.EventTypeVolumeBackupDelete: {"Volume backup deleted: %s", "A backup was deleted for volume '%s'", models.EventSeverityWarning},- models.EventTypeVolumeBackupRestore: {"Volume backup restored: %s", "A backup was restored for volume '%s'", models.EventSeverityWarning},- models.EventTypeVolumeBackupRestoreFiles: {"Volume backup files restored: %s", "Selected files were restored for volume '%s'", models.EventSeverityWarning},- models.EventTypeVolumeBackupDownload: {"Volume backup downloaded: %s", "A backup was downloaded for volume '%s'", models.EventSeverityInfo},-- models.EventTypeNetworkCreate: {"Network created: %s", "Network '%s' has been created", models.EventSeveritySuccess},- models.EventTypeNetworkDelete: {"Network deleted: %s", "Network '%s' has been deleted", models.EventSeverityWarning},- models.EventTypeNetworkError: {"Network error: %s", "An error occurred with network '%s'", models.EventSeverityError},-- models.EventTypeSystemPrune: {"System prune completed", "System resources have been pruned", models.EventSeverityInfo},- models.EventTypeSystemAutoUpdate: {"System auto-update completed", "System auto-update process has completed", models.EventSeverityInfo},- models.EventTypeSystemUpgrade: {"System upgrade completed", "System upgrade process has completed", models.EventSeverityInfo},-- models.EventTypeUserLogin: {"User logged in: %s", "User '%s' has logged in", models.EventSeverityInfo},- models.EventTypeUserLogout: {"User logged out: %s", "User '%s' has logged out", models.EventSeverityInfo},- models.EventTypeFederatedExchange: {"Federated credential exchange: %s", "Federated credential exchange for '%s'", models.EventSeverityInfo},-}--func (s *EventService) generateEventTitle(eventType models.EventType, resourceName string) string {+ Severity EventSeverity+}++var eventDefinitions = map[EventType]eventDefinition{+ EventTypeContainerStart: {"Container started: %s", "Container '%s' has been started", EventSeveritySuccess},+ EventTypeContainerStop: {"Container stopped: %s", "Container '%s' has been stopped", EventSeverityInfo},+ EventTypeContainerRestart: {"Container restarted: %s", "Container '%s' has been restarted", EventSeverityInfo},+ EventTypeContainerDelete: {"Container deleted: %s", "Container '%s' has been deleted", EventSeverityWarning},+ EventTypeContainerCreate: {"Container created: %s", "Container '%s' has been created", EventSeveritySuccess},+ EventTypeContainerScan: {"Container scanned: %s", "Security scan completed for container '%s'", EventSeverityInfo},+ EventTypeContainerUpdate: {"Container updated: %s", "Container '%s' has been updated", EventSeverityInfo},+ EventTypeContainerError: {"Container error: %s", "An error occurred with container '%s'", EventSeverityError},++ EventTypeImagePull: {"Image pulled: %s", "Image '%s' has been pulled", EventSeveritySuccess},+ EventTypeImageLoad: {"Image loaded: %s", "Image '%s' has been loaded from archive", EventSeveritySuccess},+ EventTypeImageDelete: {"Image deleted: %s", "Image '%s' has been deleted", EventSeverityWarning},+ EventTypeImageScan: {"Image scanned: %s", "Security scan completed for image '%s'", EventSeverityInfo},+ EventTypeImageError: {"Image error: %s", "An error occurred with image '%s'", EventSeverityError},++ EventTypeProjectDeploy: {"Project deployed: %s", "Project '%s' has been deployed", EventSeveritySuccess},+ EventTypeProjectDelete: {"Project deleted: %s", "Project '%s' has been deleted", EventSeverityWarning},+ EventTypeProjectStart: {"Project started: %s", "Project '%s' has been started", EventSeveritySuccess},+ EventTypeProjectStop: {"Project stopped: %s", "Project '%s' has been stopped", EventSeverityInfo},+ EventTypeProjectCreate: {"Project created: %s", "Project '%s' has been created", EventSeveritySuccess},+ EventTypeProjectUpdate: {"Project updated: %s", "Project '%s' has been updated", EventSeverityInfo},+ EventTypeProjectError: {"Project error: %s", "An error occurred with project '%s'", EventSeverityError},++ EventTypeVolumeCreate: {"Volume created: %s", "Volume '%s' has been created", EventSeveritySuccess},+ EventTypeVolumeDelete: {"Volume deleted: %s", "Volume '%s' has been deleted", EventSeverityWarning},+ EventTypeVolumeError: {"Volume error: %s", "An error occurred with volume '%s'", EventSeverityError},+ EventTypeVolumeFileCreate: {"Volume file created: %s", "A file or directory was created in volume '%s'", EventSeveritySuccess},+ EventTypeVolumeFileDelete: {"Volume file deleted: %s", "A file or directory was deleted in volume '%s'", EventSeverityWarning},+ EventTypeVolumeFileUpload: {"Volume file uploaded: %s", "A file was uploaded to volume '%s'", EventSeveritySuccess},+ EventTypeVolumeFileUpdate: {"Volume workspace updated: %s", "Files in volume '%s' were updated", EventSeverityInfo},+ EventTypeVolumeWorkspaceUpdate: {"Volume workspace updated: %s", "Workspace files in volume '%s' were updated", EventSeverityInfo},+ EventTypeVolumeBackupCreate: {"Volume backup created: %s", "A backup was created for volume '%s'", EventSeveritySuccess},+ EventTypeVolumeBackupDelete: {"Volume backup deleted: %s", "A backup was deleted for volume '%s'", EventSeverityWarning},+ EventTypeVolumeBackupRestore: {"Volume backup restored: %s", "A backup was restored for volume '%s'", EventSeverityWarning},+ EventTypeVolumeBackupRestoreFiles: {"Volume backup files restored: %s", "Selected files were restored for volume '%s'", EventSeverityWarning},+ EventTypeVolumeBackupDownload: {"Volume backup downloaded: %s", "A backup was downloaded for volume '%s'", EventSeverityInfo},++ EventTypeNetworkCreate: {"Network created: %s", "Network '%s' has been created", EventSeveritySuccess},+ EventTypeNetworkDelete: {"Network deleted: %s", "Network '%s' has been deleted", EventSeverityWarning},+ EventTypeNetworkError: {"Network error: %s", "An error occurred with network '%s'", EventSeverityError},++ EventTypeSystemPrune: {"System prune completed", "System resources have been pruned", EventSeverityInfo},+ EventTypeSystemAutoUpdate: {"System auto-update completed", "System auto-update process has completed", EventSeverityInfo},+ EventTypeSystemUpgrade: {"System upgrade completed", "System upgrade process has completed", EventSeverityInfo},++ EventTypeUserLogin: {"User logged in: %s", "User '%s' has logged in", EventSeverityInfo},+ EventTypeUserLogout: {"User logged out: %s", "User '%s' has logged out", EventSeverityInfo},+ EventTypeFederatedExchange: {"Federated credential exchange: %s", "Federated credential exchange for '%s'", EventSeverityInfo},+}++func (s *EventService) generateEventTitle(eventType EventType, resourceName string) string {definition, ok := eventDefinitions[eventType]return option.Map(func(def eventDefinition) string {return fmt.Sprintf(def.TitleFormat, resourceName)})(mo.TupleToOption(definition, ok)).OrElse("Event: " + string(eventType))}-func (s *EventService) generateEventDescription(eventType models.EventType, resourceType, resourceName string) string {+func (s *EventService) generateEventDescription(eventType EventType, resourceType, resourceName string) string {definition, ok := eventDefinitions[eventType]return option.Map(func(def eventDefinition) string {return fmt.Sprintf(def.DescriptionFormat, resourceName)@@ -708,9 +707,9 @@ func (s *EventService) generateEventDescription(eventType models.EventType, reso)}-func (s *EventService) getEventSeverity(eventType models.EventType) models.EventSeverity {+func (s *EventService) getEventSeverity(eventType EventType) EventSeverity {definition, ok := eventDefinitions[eventType]- return option.Map(func(def eventDefinition) models.EventSeverity {+ return option.Map(func(def eventDefinition) EventSeverity {return def.Severity- })(mo.TupleToOption(definition, ok)).OrElse(models.EventSeverityInfo)+ })(mo.TupleToOption(definition, ok)).OrElse(EventSeverityInfo)}diff --git a/backend/internal/event/service_test.go b/backend/internal/event/service_test.goindex 91e5501bc..07683784a 100644--- a/backend/internal/event/service_test.go+++ b/backend/internal/event/service_test.go@@ -11,7 +11,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/libtnb/sqlite"@@ -24,14 +23,14 @@ func setupEventServiceTestDB(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Event{}))+ require.NoError(t, db.AutoMigrate(&Event{}))return &database.DB{DB: db}}func TestCreateEventRequestJSONOmitempty(t *testing.T) {t.Run("includes optional fields when set", func(t *testing.T) {payload, err := json.Marshal(CreateEventRequest{- Type: models.EventTypeContainerStart,+ Type: EventTypeContainerStart,Title: "Container started",Description: "Container 'web' has been started",ResourceType: new("container"),@@ -54,7 +53,7 @@ func TestCreateEventRequestJSONOmitempty(t *testing.T) {t.Run("omits optional fields when nil", func(t *testing.T) {payload, err := json.Marshal(CreateEventRequest{- Type: models.EventTypeUserLogin,+ Type: EventTypeUserLogin,Title: "User logged in",})require.NoError(t, err)@@ -81,12 +80,12 @@ func TestEventService_LogEventsPersistOptionalPointers(t *testing.T) {db := setupEventServiceTestDB(t)svc := NewEventService(db, nil, nil)- metadata := models.JSON{"source": "test"}- err := svc.LogContainerEvent(ctx, models.EventTypeContainerStart, "container-1", "web", "user-1", "arcane", "0", metadata)+ metadata := database.JSON{"source": "test"}+ err := svc.LogContainerEvent(ctx, EventTypeContainerStart, "container-1", "web", "user-1", "arcane", "0", metadata)require.NoError(t, err)- var containerEvent models.Event- err = db.WithContext(ctx).Where("type = ?", models.EventTypeContainerStart).First(&containerEvent).Error+ var containerEvent Event+ err = db.WithContext(ctx).Where("type = ?", EventTypeContainerStart).First(&containerEvent).Errorrequire.NoError(t, err)require.NotNil(t, containerEvent.ResourceType)@@ -103,11 +102,11 @@ func TestEventService_LogEventsPersistOptionalPointers(t *testing.T) {require.Equal(t, "0", *containerEvent.EnvironmentID)require.Equal(t, "test", containerEvent.Metadata["source"])- err = svc.LogUserEvent(ctx, models.EventTypeUserLogin, "user-2", "arcane-user", nil)+ err = svc.LogUserEvent(ctx, EventTypeUserLogin, "user-2", "arcane-user", nil)require.NoError(t, err)- var userEvent models.Event- err = db.WithContext(ctx).Where("type = ?", models.EventTypeUserLogin).First(&userEvent).Error+ var userEvent Event+ err = db.WithContext(ctx).Where("type = ?", EventTypeUserLogin).First(&userEvent).Errorrequire.NoError(t, err)require.Nil(t, userEvent.ResourceType)@@ -120,7 +119,7 @@ func TestEventService_LogEventsPersistOptionalPointers(t *testing.T) {}func TestCloneEventMetadataInternal(t *testing.T) {- src := models.JSON{"a": "b"}+ src := database.JSON{"a": "b"}cloned := cloneEventMetadataInternal(src)require.Equal(t, "b", cloned["a"])@@ -131,7 +130,7 @@ func TestCloneEventMetadataInternal(t *testing.T) {require.NotNil(t, nilClone)require.Empty(t, nilClone)- nested := models.JSON{+ nested := database.JSON{"outer": map[string]any{"slice": []any{map[string]any{"k": "v"},@@ -142,11 +141,11 @@ func TestCloneEventMetadataInternal(t *testing.T) {require.NotNil(t, nestedClone["outer"])outer := nested["outer"].(map[string]any)- outerClone := nestedClone["outer"].(models.JSON)+ outerClone := nestedClone["outer"].(database.JSON)sliceOriginal := outer["slice"].([]any)sliceClone := outerClone["slice"].([]any)- sliceClone[0].(models.JSON)["k"] = "changed"+ sliceClone[0].(database.JSON)["k"] = "changed"require.Equal(t, "v", sliceOriginal[0].(map[string]any)["k"], "nested map inside slice should be deep-cloned")}@@ -155,10 +154,10 @@ func TestEventService_LogErrorEvent_DoesNotMutateInputMetadata(t *testing.T) {db := setupEventServiceTestDB(t)svc := NewEventService(db, nil, nil)- metadata := models.JSON{"phase": "pull"}+ metadata := database.JSON{"phase": "pull"}svc.LogErrorEvent(ctx,- models.EventTypeImageScan,+ EventTypeImageScan,"image","img-1","nginx:latest",@@ -172,10 +171,10 @@ func TestEventService_LogErrorEvent_DoesNotMutateInputMetadata(t *testing.T) {_, mutated := metadata["error"]require.False(t, mutated, "input metadata should not be mutated by LogErrorEvent")- var saved models.Event- err := db.WithContext(ctx).Where("type = ?", models.EventTypeImageScan).First(&saved).Error+ var saved Event+ err := db.WithContext(ctx).Where("type = ?", EventTypeImageScan).First(&saved).Errorrequire.NoError(t, err)- require.Equal(t, models.EventSeverityError, saved.Severity)+ require.Equal(t, EventSeverityError, saved.Severity)require.Equal(t, "pull", saved.Metadata["phase"])require.Equal(t, "pull failed", saved.Metadata["error"])}@@ -219,19 +218,19 @@ func TestEventService_CreateEvent_ForwardsToManagerAPIInAgentMode(t *testing.T)svc := NewEventService(db, cfg, server.Client())_, err := svc.CreateEvent(ctx, CreateEventRequest{- Type: models.EventTypeContainerStart,- Severity: models.EventSeverityInfo,+ Type: EventTypeContainerStart,+ Severity: EventSeverityInfo,Title: "Container started: web",Description: "Container 'web' has been started",EnvironmentID: new("0"),- Metadata: models.JSON{"source": "test"},+ Metadata: database.JSON{"source": "test"},})require.NoError(t, err)select {case payload := <-requests:- require.Equal(t, models.EventTypeContainerStart, payload.Type)- require.Equal(t, models.EventSeverityInfo, payload.Severity)+ require.Equal(t, EventTypeContainerStart, payload.Type)+ require.Equal(t, EventSeverityInfo, payload.Severity)require.Equal(t, "Container started: web", payload.Title)require.NotNil(t, payload.EnvironmentID)require.Equal(t, "0", *payload.EnvironmentID)@@ -248,8 +247,8 @@ func TestEventService_CreateEvent_NormalizesActor(t *testing.T) {t.Run("falls back to system when actor is missing", func(t *testing.T) {evt, err := svc.CreateEvent(ctx, CreateEventRequest{- Type: models.EventTypeSystemAutoUpdate,- Severity: models.EventSeverityInfo,+ Type: EventTypeSystemAutoUpdate,+ Severity: EventSeverityInfo,Title: "System task",})require.NoError(t, err)@@ -261,8 +260,8 @@ func TestEventService_CreateEvent_NormalizesActor(t *testing.T) {t.Run("copies user id to username when username is missing", func(t *testing.T) {evt, err := svc.CreateEvent(ctx, CreateEventRequest{- Type: models.EventTypeProjectDeploy,- Severity: models.EventSeverityInfo,+ Type: EventTypeProjectDeploy,+ Severity: EventSeverityInfo,Title: "Deploy",UserID: new("u-123"),})@@ -275,8 +274,8 @@ func TestEventService_CreateEvent_NormalizesActor(t *testing.T) {t.Run("copies username to user id when user id is missing", func(t *testing.T) {evt, err := svc.CreateEvent(ctx, CreateEventRequest{- Type: models.EventTypeProjectDeploy,- Severity: models.EventSeverityInfo,+ Type: EventTypeProjectDeploy,+ Severity: EventSeverityInfo,Title: "Deploy",Username: new("kmendell"),})@@ -293,15 +292,15 @@ func TestEventService_GetEventSeverityCounts(t *testing.T) {db := setupEventServiceTestDB(t)svc := NewEventService(db, nil, nil)- seed := []models.EventSeverity{- models.EventSeverityInfo,- models.EventSeverityInfo,- models.EventSeveritySuccess,- models.EventSeverityError,+ seed := []EventSeverity{+ EventSeverityInfo,+ EventSeverityInfo,+ EventSeveritySuccess,+ EventSeverityError,}for i, severity := range seed {_, err := svc.CreateEvent(ctx, CreateEventRequest{- Type: models.EventTypeContainerStart,+ Type: EventTypeContainerStart,Severity: severity,Title: "event",})@@ -318,10 +317,10 @@ func TestEventService_ListEventsPaginated_TypeCategoryFilter(t *testing.T) {db := setupEventServiceTestDB(t)svc := NewEventService(db, nil, nil)- for _, eventType := range []models.EventType{- models.EventTypeContainerStart,- models.EventTypeContainerStop,- models.EventTypeImagePull,+ for _, eventType := range []EventType{+ EventTypeContainerStart,+ EventTypeContainerStop,+ EventTypeImagePull,} {_, err := svc.CreateEvent(ctx, CreateEventRequest{Type: eventType, Title: "event"})require.NoError(t, err)diff --git a/backend/internal/federated/model.go b/backend/internal/federated/model.gonew file mode 100644index 000000000..71e678bab--- /dev/null+++ b/backend/internal/federated/model.go@@ -0,0 +1,55 @@+package federated++import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/role"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"++ "time"+)++const (+ FederatedCredentialMatchExact = "exact"+ FederatedCredentialMatchGlob = "glob"+)++type FederatedCredential struct {+ database.BaseModel++ Name string `json:"name" gorm:"column:name;not null" sortable:"true"`+ Description *string `json:"description,omitempty" gorm:"column:description"`+ Enabled bool `json:"enabled" gorm:"column:enabled;not null;default:false;index" sortable:"true"`+ IssuerURL string `json:"issuerUrl" gorm:"column:issuer_url;not null;index" sortable:"true"`+ Audiences database.StringSlice `json:"audiences" gorm:"column:audiences;type:text;not null"`+ SubjectClaim string `json:"subjectClaim" gorm:"column:subject_claim;not null;default:'sub'"`+ SubjectMatch string `json:"subjectMatch" gorm:"column:subject_match;not null"`+ MatchType string `json:"matchType" gorm:"column:match_type;not null;default:'exact'"`+ RoleID string `json:"roleId" gorm:"column:role_id;not null;index"`+ EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id;index"`+ IdentityUserID string `json:"identityUserId" gorm:"column:identity_user_id;not null;index"`+ TokenTTLSeconds int `json:"tokenTtlSeconds" gorm:"column:token_ttl_seconds;not null;default:900"`+ LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`+ ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`+ IdentityUser *common.User `json:"identityUser,omitempty" gorm:"foreignKey:IdentityUserID;constraint:OnDelete:CASCADE"`+ Role *role.Role `json:"role,omitempty" gorm:"foreignKey:RoleID;constraint:OnDelete:RESTRICT"`+ Environment *environment.Environment `json:"environment,omitempty" gorm:"foreignKey:EnvironmentID;constraint:OnDelete:SET NULL"`+}++func (FederatedCredential) TableName() string {+ return "federated_credentials"+}++type FederatedTokenReplay struct {+ database.BaseModel++ TokenHash string `json:"-" gorm:"column:token_hash;not null;uniqueIndex"`+ IssuerURL string `json:"issuerUrl" gorm:"column:issuer_url;not null;index"`+ ExpiresAt time.Time `json:"expiresAt" gorm:"column:expires_at;not null;index"`+}++func (FederatedTokenReplay) TableName() string {+ return "federated_token_replays"+}diff --git a/backend/internal/federated/playwright.go b/backend/internal/federated/playwright.goindex 73d20d5d0..76be40f25 100644--- a/backend/internal/federated/playwright.go+++ b/backend/internal/federated/playwright.go@@ -3,11 +3,14 @@package federatedimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/role"+"context""strings""emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/google/uuid""gorm.io/gorm")@@ -27,7 +30,7 @@ func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.Contvar credentialID stringerr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- serviceUser := models.User{+ serviceUser := common.User{Username: "svc_federated_e2e_" + strings.ReplaceAll(uuid.NewString(), "-", ""),IsServiceAccount: true,}@@ -35,14 +38,14 @@ func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.Contreturn errors.WrapIf(err, "failed to create federated e2e user")}- credential := models.FederatedCredential{+ credential := FederatedCredential{Name: "Playwright Federated Credential",Enabled: true,IssuerURL: strings.TrimRight(strings.TrimSpace(issuerURL), "/"),- Audiences: models.StringSlice(audiences),+ Audiences: database.StringSlice(audiences),SubjectClaim: "sub",SubjectMatch: strings.TrimSpace(subject),- MatchType: models.FederatedCredentialMatchExact,+ MatchType: FederatedCredentialMatchExact,RoleID: strings.TrimSpace(roleID),IdentityUserID: serviceUser.ID,TokenTTLSeconds: tokenTTLSeconds,@@ -51,10 +54,10 @@ func (s *FederatedCredentialService) CreatePlaywrightCredential(ctx context.Contreturn errors.WrapIf(err, "failed to create federated e2e credential")}- assignment := models.UserRoleAssignment{+ assignment := role.UserRoleAssignment{UserID: serviceUser.ID,RoleID: credential.RoleID,- Source: models.RoleAssignmentSourceManual,+ Source: role.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {return errors.WrapIf(err, "failed to create federated e2e role assignment")diff --git a/backend/internal/federated/service.go b/backend/internal/federated/service.goindex ea33d245f..e465fd6e9 100644--- a/backend/internal/federated/service.go+++ b/backend/internal/federated/service.go@@ -1,6 +1,8 @@package federatedimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"+"context""crypto/sha256""encoding/hex"@@ -24,7 +26,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/user"@@ -86,8 +87,8 @@ func (s *FederatedCredentialService) ExchangeToken(ctx context.Context, req fedeissuer, subject, audiences := unverifiedTokenExchangeMetadataInternal(req.SubjectToken)logResult := "failure"logReason := ""- var matchedCredential *models.FederatedCredential- var matchedUser *models.User+ var matchedCredential *FederatedCredential+ var matchedUser *common.Userdefer func() {s.logExchangeInternal(ctx, logResult, logReason, issuer, subject, audiences, matchedCredential, matchedUser)}()@@ -168,9 +169,9 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID streturn nil, err}- var created models.FederatedCredential+ var created FederatedCredentialerr = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- serviceUser := models.User{+ serviceUser := common.User{Username: "svc_federated_" + strings.ReplaceAll(uuid.NewString(), "-", ""),DisplayName: mo.EmptyableToOption(strings.TrimSpace("Federated: " + normalized.Name)).ToPointer(),IsServiceAccount: true,@@ -179,7 +180,7 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID streturn errors.WrapIf(err, "failed to create federated service user")}- created = models.FederatedCredential{+ created = FederatedCredential{Name: normalized.Name,Description: normalized.Description,Enabled: normalized.Enabled,@@ -198,11 +199,11 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID streturn errors.WrapIf(err, "failed to create federated credential")}- assignment := models.UserRoleAssignment{+ assignment := role.UserRoleAssignment{UserID: serviceUser.ID,RoleID: normalized.RoleID,EnvironmentID: normalized.EnvironmentID,- Source: models.RoleAssignmentSourceManual,+ Source: role.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {return errors.WrapIf(err, "failed to create federated role assignment")@@ -225,9 +226,9 @@ func (s *FederatedCredentialService) Create(ctx context.Context, callerUserID st}func (s *FederatedCredentialService) List(ctx context.Context, params pagination.QueryParams) ([]federatedtypes.FederatedCredential, pagination.Response, error) {- var credentials []models.FederatedCredential+ var credentials []FederatedCredentialquery := s.db.WithContext(ctx).- Model(&models.FederatedCredential{}).+ Model(&FederatedCredential{}).Preload("IdentityUser").Preload("Role").Preload("Environment")@@ -250,7 +251,7 @@ func (s *FederatedCredentialService) List(ctx context.Context, params pagination}func (s *FederatedCredentialService) Get(ctx context.Context, id string) (*federatedtypes.FederatedCredential, error) {- var credential models.FederatedCredential+ var credential FederatedCredentialif err := s.db.WithContext(ctx).Preload("IdentityUser").Preload("Role").@@ -266,7 +267,7 @@ func (s *FederatedCredentialService) Get(ctx context.Context, id string) (*feder}func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID string, id string, req federatedtypes.UpdateFederatedCredential) (*federatedtypes.FederatedCredential, error) {- var credential models.FederatedCredential+ var credential FederatedCredentialif err := s.db.WithContext(ctx).Where("id = ?", id).First(&credential).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))@@ -295,15 +296,15 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID st}}if roleChanged {- if err := tx.Where("user_id = ? AND source = ?", updated.IdentityUserID, models.RoleAssignmentSourceManual).- Delete(&models.UserRoleAssignment{}).Error; err != nil {+ if err := tx.Where("user_id = ? AND source = ?", updated.IdentityUserID, role.RoleAssignmentSourceManual).+ Delete(&role.UserRoleAssignment{}).Error; err != nil {return errors.WrapIf(err, "failed to clear federated role assignment")}- assignment := models.UserRoleAssignment{+ assignment := role.UserRoleAssignment{UserID: updated.IdentityUserID,RoleID: updated.RoleID,EnvironmentID: updated.EnvironmentID,- Source: models.RoleAssignmentSourceManual,+ Source: role.RoleAssignmentSourceManual,}if err := tx.Create(&assignment).Error; err != nil {return errors.WrapIf(err, "failed to update federated role assignment")@@ -322,7 +323,7 @@ func (s *FederatedCredentialService) Update(ctx context.Context, callerUserID st}func (s *FederatedCredentialService) Delete(ctx context.Context, id string) error {- var credential models.FederatedCredential+ var credential FederatedCredentialif err := s.db.WithContext(ctx).Where("id = ?", id).First(&credential).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrFederatedCredentialNotFound, errors.New("federated credential not found"))@@ -331,10 +332,10 @@ func (s *FederatedCredentialService) Delete(ctx context.Context, id string) erro}err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := tx.Delete(&models.FederatedCredential{}, "id = ?", credential.ID).Error; err != nil {+ if err := tx.Delete(&FederatedCredential{}, "id = ?", credential.ID).Error; err != nil {return errors.WrapIf(err, "failed to delete federated credential")}- if err := tx.Delete(&models.User{}, "id = ?", credential.IdentityUserID).Error; err != nil {+ if err := tx.Delete(&common.User{}, "id = ?", credential.IdentityUserID).Error; err != nil {return errors.WrapIf(err, "failed to delete federated service user")}return nil@@ -366,8 +367,8 @@ func validateTokenExchangeRequestInternal(req federatedtypes.TokenExchangeRequesreturn nil}-func (s *FederatedCredentialService) listEnabledCredentialsForIssuerInternal(ctx context.Context, issuer string) ([]models.FederatedCredential, error) {- var credentials []models.FederatedCredential+func (s *FederatedCredentialService) listEnabledCredentialsForIssuerInternal(ctx context.Context, issuer string) ([]FederatedCredential, error) {+ var credentials []FederatedCredentialif err := s.db.WithContext(ctx).Where("issuer_url = ? AND enabled = ?", issuer, true).Order("created_at ASC").@@ -415,11 +416,11 @@ func (s *FederatedCredentialService) recordTokenReplayGuardInternal(ctx context.now := time.Now()if err := s.db.WithContext(ctx).Where("expires_at < ?", now).- Delete(&models.FederatedTokenReplay{}).Error; err != nil {+ Delete(&FederatedTokenReplay{}).Error; err != nil {return errors.WrapIf(err, "failed to prune federated token replay records")}- replay := models.FederatedTokenReplay{+ replay := FederatedTokenReplay{TokenHash: federatedTokenReplayHashInternal(issuer, rawToken, claims),IssuerURL: issuer,ExpiresAt: expiresAt,@@ -484,7 +485,7 @@ func (s *FederatedCredentialService) providerForIssuerInternal(ctx context.Contereturn provider, nil}-func selectMatchingCredentialInternal(credentials []models.FederatedCredential, tokenAudiences []string, claims map[string]any) *models.FederatedCredential {+func selectMatchingCredentialInternal(credentials []FederatedCredential, tokenAudiences []string, claims map[string]any) *FederatedCredential {for i := range credentials {credential := &credentials[i]if !audienceMatchesInternal(tokenAudiences, credential.Audiences) {@@ -616,7 +617,7 @@ func normalizeCreateFederatedCredentialInternal(req federatedtypes.CreateFederatreturn req, nil}-func applyFederatedCredentialUpdateInternal(existing models.FederatedCredential, req federatedtypes.UpdateFederatedCredential) (models.FederatedCredential, bool, error) {+func applyFederatedCredentialUpdateInternal(existing FederatedCredential, req federatedtypes.UpdateFederatedCredential) (FederatedCredential, bool, error) {if req.Name != nil {name := strings.TrimSpace(*req.Name)if name == "" {@@ -677,7 +678,7 @@ func applyFederatedCredentialUpdateInternal(existing models.FederatedCredential,return existing, roleChanged, nil}-func applyFederatedRoleScopeUpdateInternal(existing *models.FederatedCredential, roleID *string, environmentID *string) (bool, error) {+func applyFederatedRoleScopeUpdateInternal(existing *FederatedCredential, roleID *string, environmentID *string) (bool, error) {if existing == nil {return false, common.Classify(common.ErrFederatedCredentialInvalid, errors.New("invalid federated credential"))}@@ -756,7 +757,7 @@ func revokeFederatedCredentialSessionsInternal(tx *gorm.DB, credentialID string)}now := time.Now()- if err := tx.Model(&models.UserSession{}).+ if err := tx.Model(&session.UserSession{}).Where("federated_credential_id = ? AND revoked_at IS NULL", credentialID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {return errors.WrapIf(err, "failed to revoke federated credential sessions")@@ -764,7 +765,7 @@ func revokeFederatedCredentialSessionsInternal(tx *gorm.DB, credentialID string)return nil}-func toFederatedCredentialDTOInternal(credential *models.FederatedCredential) federatedtypes.FederatedCredential {+func toFederatedCredentialDTOInternal(credential *FederatedCredential) federatedtypes.FederatedCredential {if credential == nil {return federatedtypes.FederatedCredential{}}@@ -805,7 +806,7 @@ func (s *FederatedCredentialService) markCredentialUsedAsyncInternal(ctx contextnow := time.Now()cutoff := now.Add(-federatedCredentialLastUsedWriteWindow)if err := s.db.WithContext(bgCtx).- Model(&models.FederatedCredential{}).+ Model(&FederatedCredential{}).Where("id = ? AND (last_used_at IS NULL OR last_used_at < ?)", credentialID, cutoff).Update("last_used_at", now).Error; err != nil {slog.WarnContext(bgCtx, "failed to update federated credential last_used_at", "credential_id", credentialID, "error", err)@@ -813,7 +814,7 @@ func (s *FederatedCredentialService) markCredentialUsedAsyncInternal(ctx context}()}-func (s *FederatedCredentialService) logExchangeInternal(ctx context.Context, result, reason, issuer, subject string, audiences []string, credential *models.FederatedCredential, user *models.User) {+func (s *FederatedCredentialService) logExchangeInternal(ctx context.Context, result, reason, issuer, subject string, audiences []string, credential *FederatedCredential, user *common.User) {credentialID := ""credentialName := ""if credential != nil {@@ -833,7 +834,7 @@ func (s *FederatedCredentialService) logExchangeInternal(ctx context.Context, rereturn}- metadata := models.JSON{+ metadata := database.JSON{"action": "federated_token_exchange","result": result,"reason": reason,@@ -849,17 +850,17 @@ func (s *FederatedCredentialService) logExchangeInternal(ctx context.Context, reuserID = user.IDusername = user.Username}- severity := models.EventSeverityInfo+ severity := event.EventSeverityInfotitle := "Federated credential token exchange"if result != "success" {- severity = models.EventSeverityWarning+ severity = event.EventSeverityWarningtitle = "Federated credential token exchange rejected"}go func() {bgCtx := context.WithoutCancel(ctx)_, err := s.eventService.CreateEvent(bgCtx, event.CreateEventRequest{- Type: models.EventTypeFederatedExchange,+ Type: event.EventTypeFederatedExchange,Severity: severity,Title: title,Description: "Workload identity federation token exchange",diff --git a/backend/internal/federated/service_test.go b/backend/internal/federated/service_test.goindex adb43a94a..1671f8d93 100644--- a/backend/internal/federated/service_test.go+++ b/backend/internal/federated/service_test.go@@ -27,7 +27,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/internal/settings"@@ -120,14 +119,14 @@ func setupFederatedCredentialServiceTestDBInternal(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.SettingVariable{},- &models.User{},- &models.UserSession{},- &models.Role{},- &models.UserRoleAssignment{},- &models.FederatedCredential{},- &models.FederatedTokenReplay{},- &models.Event{},+ &settings.SettingVariable{},+ &common.User{},+ &session.UserSession{},+ &role.Role{},+ &role.UserRoleAssignment{},+ &FederatedCredential{},+ &FederatedTokenReplay{},+ &event.Event{},))sqlDB, err := db.DB()@@ -155,34 +154,34 @@ func setupFederatedCredentialServiceInternal(t *testing.T, issuer *federatedTestservice := NewFederatedCredentialService(db, authSvc, userSvc, settingsSvc, eventSvc, issuer.server.Client()).WithRoleService(roleSvc)- role := models.Role{- BaseModel: models.BaseModel{ID: "role-federated-viewer"},+ viewerRole := role.Role{+ BaseModel: database.BaseModel{ID: "role-federated-viewer"},Name: "Federated Viewer",- Permissions: models.StringSlice{authz.PermProjectsList},+ Permissions: database.StringSlice{authz.PermProjectsList},}- require.NoError(t, db.WithContext(ctx).Create(&role).Error)+ require.NoError(t, db.WithContext(ctx).Create(&viewerRole).Error)- serviceUser := models.User{- BaseModel: models.BaseModel{ID: "user-federated-service"},+ serviceUser := common.User{+ BaseModel: database.BaseModel{ID: "user-federated-service"},Username: "svc-federated-demo",IsServiceAccount: true,}require.NoError(t, db.WithContext(ctx).Create(&serviceUser).Error)- require.NoError(t, db.WithContext(ctx).Create(&models.UserRoleAssignment{+ require.NoError(t, db.WithContext(ctx).Create(&role.UserRoleAssignment{UserID: serviceUser.ID,- RoleID: role.ID,+ RoleID: viewerRole.ID,}).Error)- credential := models.FederatedCredential{- BaseModel: models.BaseModel{ID: "cred-github-actions"},+ credential := FederatedCredential{+ BaseModel: database.BaseModel{ID: "cred-github-actions"},Name: "GitHub Actions",Enabled: true,IssuerURL: issuer.IssuerURL,- Audiences: models.StringSlice{"arcane-ci"},+ Audiences: database.StringSlice{"arcane-ci"},SubjectClaim: "sub",SubjectMatch: "repo:getarcaneapp/arcane:*",MatchType: federatedtypes.MatchTypeGlob,- RoleID: role.ID,+ RoleID: viewerRole.ID,IdentityUserID: serviceUser.ID,TokenTTLSeconds: 900,}@@ -247,11 +246,11 @@ func TestFederatedCredentialServiceExchangeToken(t *testing.T) {require.NoError(t, err)require.Equal(t, "user-federated-service", user.ID)- var session models.UserSession- require.NoError(t, db.WithContext(ctx).Where("id = ?", sessionID).First(&session).Error)- require.Equal(t, models.UserSessionSourceFederated, session.Source)- require.NotNil(t, session.FederatedCredentialID)- require.Equal(t, "cred-github-actions", *session.FederatedCredentialID)+ var userSession session.UserSession+ require.NoError(t, db.WithContext(ctx).Where("id = ?", sessionID).First(&userSession).Error)+ require.Equal(t, session.UserSessionSourceFederated, userSession.Source)+ require.NotNil(t, userSession.FederatedCredentialID)+ require.Equal(t, "cred-github-actions", *userSession.FederatedCredentialID)})}}@@ -295,7 +294,7 @@ func TestFederatedCredentialServiceExchangeTokenRejectsExpiredCredentialInternalservice, _, db := setupFederatedCredentialServiceInternal(t, issuer)expiredAt := time.Now().Add(-time.Minute)require.NoError(t, db.WithContext(context.Background()).- Model(&models.FederatedCredential{}).+ Model(&FederatedCredential{}).Where("id = ?", "cred-github-actions").Update("expires_at", expiredAt).Error)diff --git a/backend/internal/gitops/gitops_sync.go b/backend/internal/gitops/gitops_sync.goindex 8409e13c7..64434271b 100644--- a/backend/internal/gitops/gitops_sync.go+++ b/backend/internal/gitops/gitops_sync.go@@ -19,9 +19,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"- "github.com/getarcaneapp/arcane/backend/v2/internal/lifecycle"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"- "github.com/getarcaneapp/arcane/backend/v2/internal/project"+ projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/swarm""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -41,7 +39,7 @@ import (type GitOpsSyncService struct {db *database.DBrepoService *gitrepo.GitRepositoryService- projectService *project.ProjectService+ projectService *projectpkg.ProjectServiceswarmService *swarm.SwarmServiceeventService *event.EventServicesettingsService *settings.SettingsService@@ -81,7 +79,7 @@ type stagedDirectorySync struct {stageLogical stringprojectsDir stringcomposeFileName string- project *models.Project+ project *projectpkg.ProjectsyncedFiles []stringserviceCount intcontentsChanged bool@@ -120,11 +118,11 @@ type lifecycleConfigInputInternal struct {syncDirectory *bool}-func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context, current *models.GitOpsSync, in lifecycleConfigInputInternal) error {+func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context, current *projectpkg.GitOpsSync, in lifecycleConfigInputInternal) error {lifecycleFieldSet := in.scriptPath != nil || in.runnerImage != nil || in.env != nil || in.extraMounts != nil || in.timeoutSec != nil || in.networkMode != nilsyncDirectoryChanging := in.syncDirectory != niltargetTypeChanging := in.targetType != nil && strings.TrimSpace(*in.targetType) != resolveLifecycleEffectiveTargetTypeInternal(current, nil)- effectiveScriptPath := resolveLifecycleEffectiveStringInternal(currentStringInternal(current, func(c *models.GitOpsSync) *string { return c.PreDeployScriptPath }), in.scriptPath)+ effectiveScriptPath := resolveLifecycleEffectiveStringInternal(currentStringInternal(current, func(c *projectpkg.GitOpsSync) *string { return c.PreDeployScriptPath }), in.scriptPath)// If nothing lifecycle-related is being touched and the resulting state// has no script configured, there's nothing to validate.@@ -154,24 +152,24 @@ func (s *GitOpsSyncService) validateLifecycleConfigInternal(ctx context.Context,//nolint:revive // Preserve the existing API validation message.return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Timeout must be at least 1 second."), "field", "preDeployTimeoutSec"))}- maxTimeoutSec := s.settingsService.GetIntSetting(ctx, "lifecycleMaxTimeoutSec", lifecycle.DefaultMaxTimeoutSec)+ maxTimeoutSec := s.settingsService.GetIntSetting(ctx, "lifecycleMaxTimeoutSec", projectpkg.DefaultMaxTimeoutSec)if maxTimeoutSec > 0 && *in.timeoutSec > maxTimeoutSec {//nolint:revive // Preserve the existing API validation message.return common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("Timeout %ds exceeds the lifecycleMaxTimeoutSec setting (%ds).", *in.timeoutSec, maxTimeoutSec), "field", "preDeployTimeoutSec"))}}- if _, err := lifecycle.ParseEnvText(in.env); err != nil {+ if _, err := projectpkg.ParseEnvText(in.env); err != nil {return common.Classify(common.ErrValidation, errors.WithDetails(errors.New(err.Error()), "field", "preDeployEnv"))}- if _, err := lifecycle.ParseExtraMountsText(in.extraMounts); err != nil {+ if _, err := projectpkg.ParseExtraMountsText(in.extraMounts); err != nil {return common.Classify(common.ErrValidation, errors.WithDetails(errors.New(err.Error()), "field", "preDeployExtraMounts"))}return nil}-func (s *GitOpsSyncService) validateLifecycleScriptConfigInternal(ctx context.Context, current *models.GitOpsSync, in lifecycleConfigInputInternal, scriptPath string) error {+func (s *GitOpsSyncService) validateLifecycleScriptConfigInternal(ctx context.Context, current *projectpkg.GitOpsSync, in lifecycleConfigInputInternal, scriptPath string) error {if resolveLifecycleEffectiveTargetTypeInternal(current, in.targetType) == "swarm_stack" {//nolint:revive // Preserve the existing API validation message.return common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Pre-deploy lifecycle hooks are only supported for project syncs."), "field", "preDeployScriptPath"))@@ -193,7 +191,7 @@ func (s *GitOpsSyncService) validateLifecycleScriptConfigInternal(ctx context.Coreturn common.Classify(common.ErrValidation, errors.WithDetails(errors.New("Script path must not escape the project directory."), "field", "preDeployScriptPath"))}- effectiveRunnerImage := resolveLifecycleEffectiveStringInternal(currentStringInternal(current, func(c *models.GitOpsSync) *string { return c.PreDeployRunnerImage }), in.runnerImage)+ effectiveRunnerImage := resolveLifecycleEffectiveStringInternal(currentStringInternal(current, func(c *projectpkg.GitOpsSync) *string { return c.PreDeployRunnerImage }), in.runnerImage)defaultRunnerImage := strings.TrimSpace(s.settingsService.GetStringSetting(ctx, "lifecycleDefaultRunnerImage", ""))if effectiveRunnerImage == "" && defaultRunnerImage == "" {//nolint:revive // Preserve the existing API validation message.@@ -219,7 +217,7 @@ func resolveLifecycleEffectiveStringInternal(existing string, update *string) streturn strings.TrimSpace(existing)}-func currentStringInternal(sync *models.GitOpsSync, accessor func(*models.GitOpsSync) *string) string {+func currentStringInternal(sync *projectpkg.GitOpsSync, accessor func(*projectpkg.GitOpsSync) *string) string {if sync == nil {return ""}@@ -229,7 +227,7 @@ func currentStringInternal(sync *models.GitOpsSync, accessor func(*models.GitOpsreturn ""}-func resolveLifecycleEffectiveTargetTypeInternal(current *models.GitOpsSync, update *string) string {+func resolveLifecycleEffectiveTargetTypeInternal(current *projectpkg.GitOpsSync, update *string) string {if update != nil && strings.TrimSpace(*update) != "" {return strings.TrimSpace(*update)}@@ -243,7 +241,7 @@ func resolveLifecycleEffectiveTargetTypeInternal(current *models.GitOpsSync, upd// the SyncDirectory bool: a nil update keeps the existing value, a non-nil// update overrides it. On create (current=nil) and no update, defaults to// false to match the model's create-time default.-func resolveEffectiveSyncDirectoryInternal(current *models.GitOpsSync, update *bool) bool {+func resolveEffectiveSyncDirectoryInternal(current *projectpkg.GitOpsSync, update *bool) bool {if update != nil {return *update}@@ -257,7 +255,7 @@ func resolveEffectiveSyncDirectoryInternal(current *models.GitOpsSync, update *b// request into a new GitOpsSync row before insert. Strings are trimmed;// empty strings remain unset (nil pointer) except for fields that have a// non-null default at the DB level.-func applyLifecycleFieldsToSyncInternal(sync *models.GitOpsSync, in lifecycleConfigInputInternal) {+func applyLifecycleFieldsToSyncInternal(sync *projectpkg.GitOpsSync, in lifecycleConfigInputInternal) {sync.PreDeployScriptPath = nullableTrimmedStringInternal(in.scriptPath)sync.PreDeployRunnerImage = nullableTrimmedStringInternal(in.runnerImage)sync.PreDeployEnv = nullableTrimmedStringInternal(in.env)@@ -265,7 +263,7 @@ func applyLifecycleFieldsToSyncInternal(sync *models.GitOpsSync, in lifecycleConif in.timeoutSec != nil {sync.PreDeployTimeoutSec = *in.timeoutSec} else {- sync.PreDeployTimeoutSec = lifecycle.DefaultTimeoutSec+ sync.PreDeployTimeoutSec = projectpkg.DefaultTimeoutSec}if mode := normalizeLifecycleNetworkModeInternal(in.networkMode); mode != "" {sync.PreDeployNetworkMode = mode@@ -345,11 +343,11 @@ func megabytesToBytes(value int) int64 {return int64(value) * 1024 * 1024}-func hasEstablishedProjectBindingInternal(sync *models.GitOpsSync) bool {+func hasEstablishedProjectBindingInternal(sync *projectpkg.GitOpsSync) bool {return sync != nil && sync.ProjectID != nil && strings.TrimSpace(*sync.ProjectID) != ""}-func NewGitOpsSyncService(db *database.DB, repoService *gitrepo.GitRepositoryService, projectService *project.ProjectService, swarmService *swarm.SwarmService, eventService *event.EventService, settingsService *settings.SettingsService) *GitOpsSyncService {+func NewGitOpsSyncService(db *database.DB, repoService *gitrepo.GitRepositoryService, projectService *projectpkg.ProjectService, swarmService *swarm.SwarmService, eventService *event.EventService, settingsService *settings.SettingsService) *GitOpsSyncService {return &GitOpsSyncService{db: db,repoService: repoService,@@ -389,7 +387,7 @@ func (s *GitOpsSyncService) runScheduledSyncInternal(ctx context.Context, enviroif !syncRecord.AutoSync {return}- if _, err := s.PerformSync(ctx, environmentID, syncID, models.SystemUser); err != nil {+ if _, err := s.PerformSync(ctx, environmentID, syncID, common.SystemUser); err != nil {slog.ErrorContext(ctx, "gitops auto-sync run failed", "syncId", syncID, "error", err)}}@@ -416,7 +414,7 @@ func (s *GitOpsSyncService) unregisterSyncJobInternal(ctx context.Context, syncIfunc (s *GitOpsSyncService) kickSyncInternal(ctx context.Context, syncID, environmentID string) {ctx = s.jobs.Context(ctx)go func() {- if _, err := s.PerformSync(ctx, environmentID, syncID, models.SystemUser); err != nil {+ if _, err := s.PerformSync(ctx, environmentID, syncID, common.SystemUser); err != nil {slog.ErrorContext(ctx, "gitops immediate sync kick failed", "syncId", syncID, "error", err)}}()@@ -429,7 +427,7 @@ func (s *GitOpsSyncService) RegisterAutoSyncJobsOnStartup(ctx context.Context) {if !s.jobs.Enabled() {return}- var syncs []models.GitOpsSync+ var syncs []projectpkg.GitOpsSyncif err := s.db.WithContext(ctx).Where("auto_sync = ? AND environment_id IN (SELECT id FROM environments)", true).Find(&syncs).Error; err != nil {@@ -446,7 +444,7 @@ func (s *GitOpsSyncService) RegisterAutoSyncJobsOnStartup(ctx context.Context) {slog.InfoContext(ctx, "Registered gitops auto-sync jobs on startup", "count", len(syncs))}-func isGitOpsSyncOverdueInternal(sync *models.GitOpsSync) bool {+func isGitOpsSyncOverdueInternal(sync *projectpkg.GitOpsSync) bool {if sync.LastSyncAt == nil {return true}@@ -467,7 +465,7 @@ func (s *GitOpsSyncService) getEnvironmentSyncLimits(ctx context.Context) (int,return maxFiles, megabytesToBytes(maxTotalSizeMB), megabytesToBytes(maxBinarySizeMB)}-func (s *GitOpsSyncService) getEffectiveSyncLimits(ctx context.Context, sync *models.GitOpsSync) (int, int64, int64) {+func (s *GitOpsSyncService) getEffectiveSyncLimits(ctx context.Context, sync *projectpkg.GitOpsSync) (int, int64, int64) {environmentMaxFiles, environmentMaxTotalSize, environmentMaxBinarySize := s.getEnvironmentSyncLimits(ctx)if sync == nil {return environmentMaxFiles, environmentMaxTotalSize, environmentMaxBinarySize@@ -495,8 +493,8 @@ func (s *GitOpsSyncService) gitSyncLimitEnvOverrideActiveInternal(key string) bo}func (s *GitOpsSyncService) GetSyncsPaginated(ctx context.Context, environmentID string, params pagination.QueryParams) ([]gitops.GitOpsSync, pagination.Response, gitops.SyncCounts, error) {- var syncs []models.GitOpsSync- q := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).+ var syncs []projectpkg.GitOpsSync+ q := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("environment_id = ?", environmentID)if term := strings.TrimSpace(params.Search); term != "" {@@ -522,7 +520,7 @@ func (s *GitOpsSyncService) GetSyncsPaginated(ctx context.Context, environmentIDreturn nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(err, "failed to paginate gitops syncs")}- out, mapErr := mapper.MapSlice[models.GitOpsSync, gitops.GitOpsSync](syncs)+ out, mapErr := mapper.MapSlice[projectpkg.GitOpsSync, gitops.GitOpsSync](syncs)if mapErr != nil {return nil, pagination.Response{}, gitops.SyncCounts{}, errors.WrapIf(mapErr, "failed to map syncs")}@@ -553,7 +551,7 @@ func (s *GitOpsSyncService) getFilteredSyncCounts(query *gorm.DB) (gitops.SyncCo}, nil}-func (s *GitOpsSyncService) GetSyncByID(ctx context.Context, environmentID, id string) (*models.GitOpsSync, error) {+func (s *GitOpsSyncService) GetSyncByID(ctx context.Context, environmentID, id string) (*projectpkg.GitOpsSync, error) {syncRecord, err := s.getSyncByIDInternal(ctx, environmentID, id, true)if err != nil {if errors.Is(err, common.ErrNotFound) {@@ -566,8 +564,8 @@ func (s *GitOpsSyncService) GetSyncByID(ctx context.Context, environmentID, id sreturn syncRecord, nil}-func (s *GitOpsSyncService) getSyncByIDInternal(ctx context.Context, environmentID, id string, preloadAssociations bool) (*models.GitOpsSync, error) {- var syncRecord models.GitOpsSync+func (s *GitOpsSyncService) getSyncByIDInternal(ctx context.Context, environmentID, id string, preloadAssociations bool) (*projectpkg.GitOpsSync, error) {+ var syncRecord projectpkg.GitOpsSyncq := s.db.WithContext(ctx).Where("id = ?", id)if preloadAssociations {q = q.Preload("Repository").Preload("Project")@@ -584,11 +582,11 @@ func (s *GitOpsSyncService) getSyncByIDInternal(ctx context.Context, environmentreturn &syncRecord, nil}-func (s *GitOpsSyncService) getSyncRecordByIDInternal(ctx context.Context, environmentID, id string) (*models.GitOpsSync, error) {+func (s *GitOpsSyncService) getSyncRecordByIDInternal(ctx context.Context, environmentID, id string) (*projectpkg.GitOpsSync, error) {return s.getSyncByIDInternal(ctx, environmentID, id, false)}-func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string, req gitops.CreateSyncRequest, actor models.User) (*models.GitOpsSync, error) {+func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string, req gitops.CreateSyncRequest, actor common.User) (*projectpkg.GitOpsSync, error) {slog.InfoContext(ctx, "Creating GitOps sync", "environmentID", environmentID, "name", req.Name, "repositoryID", req.RepositoryID)// Validate repository exists@@ -607,7 +605,7 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID stringdefaultMaxFiles, defaultMaxTotalSize, defaultMaxBinarySize := s.getEnvironmentSyncLimits(ctx)- syncRecord := models.GitOpsSync{+ syncRecord := projectpkg.GitOpsSync{Name: req.Name,EnvironmentID: environmentID,RepositoryID: req.RepositoryID,@@ -671,8 +669,8 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID string// Log event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitSyncCreate,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeGitSyncCreate,+ Severity: event.EventSeveritySuccess,Title: "Git sync created",Description: fmt.Sprintf("Created git sync configuration '%s'", syncRecord.Name),ResourceType: new("git_sync"),@@ -697,7 +695,7 @@ func (s *GitOpsSyncService) CreateSync(ctx context.Context, environmentID stringreturn s.GetSyncByID(ctx, "", syncRecord.ID)}-func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id string, req gitops.UpdateSyncRequest, actor models.User) (*models.GitOpsSync, error) {+func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id string, req gitops.UpdateSyncRequest, actor common.User) (*projectpkg.GitOpsSync, error) {syncRecord, err := s.GetSyncByID(ctx, environmentID, id)if err != nil {return nil, err@@ -783,8 +781,8 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id st// Log event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitSyncUpdate,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeGitSyncUpdate,+ Severity: event.EventSeveritySuccess,Title: "Git sync updated",Description: fmt.Sprintf("Updated git sync configuration '%s'", syncRecord.Name),ResourceType: new("git_sync"),@@ -811,7 +809,7 @@ func (s *GitOpsSyncService) UpdateSync(ctx context.Context, environmentID, id streturn s.GetSyncByID(ctx, environmentID, id)}-func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id string, actor models.User) error {+func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id string, actor common.User) error {// Stop the recurring job first, unconditionally. Even a sync whose row can no// longer be loaded (corrupt or environment-mismatched) must stop firing; any// in-flight run re-reads the row and self-cancels once it is gone.@@ -826,7 +824,7 @@ func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id st// Clear gitops_managed_by for any project still pointing at this sync, keyed// on the sync id so orphaned managed flags are cleared even when the sync row// (and its ProjectID) could not be loaded.- if err := tx.Model(&models.Project{}).+ if err := tx.Model(&projectpkg.Project{}).Where("gitops_managed_by = ?", id).Update("gitops_managed_by", nil).Error; err != nil {return errors.WrapIf(err, "failed to clear gitops_managed_by")@@ -835,7 +833,7 @@ func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id st// Delete by id only (no environment scoping). The handler already enforced the// delete permission; env scoping is precisely what made env-mismatched corrupt// rows undeletable. A zero-row delete is treated as success (idempotent).- if err := tx.Where("id = ?", id).Delete(&models.GitOpsSync{}).Error; err != nil {+ if err := tx.Where("id = ?", id).Delete(&projectpkg.GitOpsSync{}).Error; err != nil {return errors.WrapIf(err, "failed to delete sync")}return nil@@ -854,8 +852,8 @@ func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id st// Log event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitSyncDelete,- Severity: models.EventSeverityInfo,+ Type: event.EventTypeGitSyncDelete,+ Severity: event.EventSeverityInfo,Title: "Git sync deleted",Description: fmt.Sprintf("Deleted git sync configuration '%s'", syncRecord.Name),ResourceType: new("git_sync"),@@ -869,7 +867,7 @@ func (s *GitOpsSyncService) DeleteSync(ctx context.Context, environmentID, id streturn nil}-func (s *GitOpsSyncService) PerformSync(ctx context.Context, environmentID, id string, actor models.User) (*gitops.SyncResult, error) {+func (s *GitOpsSyncService) PerformSync(ctx context.Context, environmentID, id string, actor common.User) (*gitops.SyncResult, error) {// Coalesce overlapping runs for the same sync (scheduled fire, startup/enable// kick, manual trigger, webhook) so they don't race the clone/redeploy.lease, admitted, err := s.jobs.TryAcquire(ctx, id)@@ -923,7 +921,7 @@ func (s *GitOpsSyncService) PerformSync(ctx context.Context, environmentID, id s// prepareSyncSource clones the source repository, validates that the configured// compose file exists, and reads the compose/env inputs for the sync flow.-func (s *GitOpsSyncService) prepareSyncSource(ctx context.Context, sync *models.GitOpsSync, result *gitops.SyncResult, actor models.User) (*preparedSyncSource, error) {+func (s *GitOpsSyncService) prepareSyncSource(ctx context.Context, sync *projectpkg.GitOpsSync, result *gitops.SyncResult, actor common.User) (*preparedSyncSource, error) {repository := sync.Repositoryif repository == nil {return nil, s.failSync(ctx, sync.ID, result, sync, actor, "Repository not found", "repository not found")@@ -1003,7 +1001,7 @@ func (s *GitOpsSyncService) prepareSyncSource(ctx context.Context, sync *models.// performDirectorySync runs the directory-sync path and only triggers a// redeploy when an already running project's synced contents changed.-func (s *GitOpsSyncService) performDirectorySync(ctx context.Context, sync *models.GitOpsSync, id string, actor models.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {+func (s *GitOpsSyncService) performDirectorySync(ctx context.Context, sync *projectpkg.GitOpsSync, id string, actor common.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {slog.InfoContext(ctx, "Using directory sync mode", "syncId", id, "composePath", sync.ComposePath)syncFiles, err := s.walkAndParseSyncDirectory(ctx, sync, source.repoPath)@@ -1044,7 +1042,7 @@ func (s *GitOpsSyncService) performDirectorySync(ctx context.Context, sync *mode// sync: the compose file's base name plus the override file name when one was// resolved. Shared by the compose-only and swarm-stack single-file paths so the// two never disagree on what a single-file sync tracked.-func singleFileSyncedFilesInternal(sync *models.GitOpsSync, source *preparedSyncSource) []string {+func singleFileSyncedFilesInternal(sync *projectpkg.GitOpsSync, source *preparedSyncSource) []string {syncedFiles := []string{filepath.Base(sync.ComposePath)}if source.overrideFileName != "" {syncedFiles = append(syncedFiles, source.overrideFileName)@@ -1053,7 +1051,7 @@ func singleFileSyncedFilesInternal(sync *models.GitOpsSync, source *preparedSync}// performSingleFileSyncInternal preserves the legacy compose-only Git sync behavior.-func (s *GitOpsSyncService) performSingleFileSyncInternal(ctx context.Context, sync *models.GitOpsSync, id string, actor models.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {+func (s *GitOpsSyncService) performSingleFileSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, actor common.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {slog.InfoContext(ctx, "Using single file sync mode", "syncId", id, "composePath", sync.ComposePath)syncedFiles := singleFileSyncedFilesInternal(sync, source)@@ -1076,7 +1074,7 @@ func (s *GitOpsSyncService) performSingleFileSyncInternal(ctx context.Context, s}// performSwarmStackSyncInternal executes a single file sync targeted at a Swarm Stack-func (s *GitOpsSyncService) performSwarmStackSyncInternal(ctx context.Context, sync *models.GitOpsSync, id string, actor models.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {+func (s *GitOpsSyncService) performSwarmStackSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, actor common.User, result *gitops.SyncResult, source *preparedSyncSource) (*gitops.SyncResult, error) {slog.InfoContext(ctx, "Deploying Swarm Stack from GitOps sync", "syncId", id, "stackName", sync.ProjectName)if s.swarmService == nil {@@ -1135,8 +1133,8 @@ func (s *GitOpsSyncService) performSwarmStackSyncInternal(ctx context.Context, s// Log event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitSyncRun,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeGitSyncRun,+ Severity: event.EventSeveritySuccess,Title: "Git sync completed for stack",Description: fmt.Sprintf("Successfully synced '%s' to swarm stack '%s'", sync.Name, sync.ProjectName),ResourceType: new("git_sync"),@@ -1155,12 +1153,12 @@ func (s *GitOpsSyncService) performSwarmStackSyncInternal(ctx context.Context, s// running and the latest sync actually changed managed content. Returns a// common.ErrRedeployAfterSyncFailed when the redeploy itself fails; callers// surface that on the sync row's LastSyncError.-func (s *GitOpsSyncService) redeployIfRunningAfterSync(ctx context.Context, project *models.Project, actor models.User, syncMode string) error {+func (s *GitOpsSyncService) redeployIfRunningAfterSync(ctx context.Context, project *projectpkg.Project, actor common.User, syncMode string) error {details, err := s.projectService.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{})if err != nil {return nil //nolint:nilerr // best-effort: skip post-sync redeploy when project state can't be determined}- if details.Status != string(models.ProjectStatusRunning) && details.Status != string(models.ProjectStatusPartiallyRunning) {+ if details.Status != string(projectpkg.ProjectStatusRunning) && details.Status != string(projectpkg.ProjectStatusPartiallyRunning) {return nil}@@ -1174,10 +1172,10 @@ func (s *GitOpsSyncService) redeployIfRunningAfterSync(ctx context.Context, proj// logSyncSuccess records the Git sync completion event once the filesystem and// sync-status updates have already succeeded.-func (s *GitOpsSyncService) logSyncSuccess(ctx context.Context, sync *models.GitOpsSync, project *models.Project, actor models.User) {+func (s *GitOpsSyncService) logSyncSuccess(ctx context.Context, sync *projectpkg.GitOpsSync, project *projectpkg.Project, actor common.User) {_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitSyncRun,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeGitSyncRun,+ Severity: event.EventSeveritySuccess,Title: "Git sync completed",Description: fmt.Sprintf("Successfully synced '%s' to project '%s'", sync.Name, project.Name),ResourceType: new("git_sync"),@@ -1206,7 +1204,7 @@ func (s *GitOpsSyncService) updateSyncStatus(ctx context.Context, id, status, erupdates["last_sync_commit"] = commitHash}- if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("id = ?", id).Updates(updates).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", id).Updates(updates).Error; err != nil {slog.ErrorContext(ctx, "Failed to update sync status", "error", err, "syncId", id)}}@@ -1275,7 +1273,7 @@ func (s *GitOpsSyncService) CleanupLeakedScratchDirsOnStartup(ctx context.Contexfunc (s *GitOpsSyncService) CleanupOrphanedSyncsOnStartup(ctx context.Context) error {var syncIDs []string- if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).+ if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("environment_id NOT IN (SELECT id FROM environments)").Pluck("id", &syncIDs).Error; err != nil {return errors.WrapIf(err, "failed to list orphaned gitops syncs")@@ -1285,12 +1283,12 @@ func (s *GitOpsSyncService) CleanupOrphanedSyncsOnStartup(ctx context.Context) e}if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- if err := tx.Model(&models.Project{}).+ if err := tx.Model(&projectpkg.Project{}).Where("gitops_managed_by IN ?", syncIDs).Update("gitops_managed_by", nil).Error; err != nil {return errors.WrapIf(err, "failed to clear orphaned gitops project references")}- if err := tx.Where("id IN ?", syncIDs).Delete(&models.GitOpsSync{}).Error; err != nil {+ if err := tx.Where("id IN ?", syncIDs).Delete(&projectpkg.GitOpsSync{}).Error; err != nil {return errors.WrapIf(err, "failed to delete orphaned gitops syncs")}return nil@@ -1303,7 +1301,7 @@ func (s *GitOpsSyncService) CleanupOrphanedSyncsOnStartup(ctx context.Context) e}func (s *GitOpsSyncService) ReconcileDirectorySyncProjectsOnStartup(ctx context.Context) error {- var syncs []models.GitOpsSync+ var syncs []projectpkg.GitOpsSyncif err := s.db.WithContext(ctx).Where("sync_directory = ?", true).Find(&syncs).Error; err != nil {@@ -1375,7 +1373,7 @@ func (s *GitOpsSyncService) BrowseFiles(ctx context.Context, environmentID, id s}, nil}-func (s *GitOpsSyncService) ImportSyncs(ctx context.Context, environmentID string, req []gitops.ImportGitOpsSyncRequest, actor models.User) (*gitops.ImportGitOpsSyncResponse, error) {+func (s *GitOpsSyncService) ImportSyncs(ctx context.Context, environmentID string, req []gitops.ImportGitOpsSyncRequest, actor common.User) (*gitops.ImportGitOpsSyncResponse, error) {response := &gitops.ImportGitOpsSyncResponse{SuccessCount: 0,FailedCount: 0,@@ -1417,10 +1415,10 @@ func (s *GitOpsSyncService) ImportSyncs(ctx context.Context, environmentID strinreturn response, nil}-func (s *GitOpsSyncService) logSyncError(ctx context.Context, sync *models.GitOpsSync, actor models.User, errorMsg string) {+func (s *GitOpsSyncService) logSyncError(ctx context.Context, sync *projectpkg.GitOpsSync, actor common.User, errorMsg string) {_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitSyncError,- Severity: models.EventSeverityError,+ Type: event.EventTypeGitSyncError,+ Severity: event.EventSeverityError,Title: "Git sync failed",Description: fmt.Sprintf("Failed to sync '%s': %s", sync.Name, errorMsg),ResourceType: new("git_sync"),@@ -1432,7 +1430,7 @@ func (s *GitOpsSyncService) logSyncError(ctx context.Context, sync *models.GitOp})}-func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *gitops.SyncResult, sync *models.GitOpsSync, actor models.User, message, errMsg string) error {+func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *gitops.SyncResult, sync *projectpkg.GitOpsSync, actor common.User, message, errMsg string) error {result.Message = messageresult.Error = new(errMsg)s.updateSyncStatus(ctx, id, "failed", errMsg, "")@@ -1445,7 +1443,7 @@ func (s *GitOpsSyncService) failSync(ctx context.Context, id string, result *git// lifecycle hook returning non-zero). The synced-files list and commit hash// are preserved on the row so operators can see what reached disk; the// error message surfaces the redeploy failure on LastSyncError.-func (s *GitOpsSyncService) markSyncRedeployFailedInternal(ctx context.Context, sync *models.GitOpsSync, id, commitHash string, syncedFiles []string, redeployErr error, actor models.User, result *gitops.SyncResult) {+func (s *GitOpsSyncService) markSyncRedeployFailedInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id, commitHash string, syncedFiles []string, redeployErr error, actor common.User, result *gitops.SyncResult) {errMsg := redeployErr.Error()result.Success = falseresult.Message = "Sync wrote files but redeploy failed"@@ -1454,12 +1452,12 @@ func (s *GitOpsSyncService) markSyncRedeployFailedInternal(ctx context.Context,s.logSyncError(ctx, sync, actor, errMsg)}-func (s *GitOpsSyncService) disableAutoSyncForBrokenBindingInternal(ctx context.Context, sync *models.GitOpsSync) {+func (s *GitOpsSyncService) disableAutoSyncForBrokenBindingInternal(ctx context.Context, sync *projectpkg.GitOpsSync) {if sync == nil || sync.ID == "" {return}if err := s.db.WithContext(ctx).- Model(&models.GitOpsSync{}).+ Model(&projectpkg.GitOpsSync{}).Where("id = ?", sync.ID).Update("auto_sync", false).Error; err != nil {slog.ErrorContext(ctx, "Failed to disable GitOps auto-sync after broken project binding", "syncId", sync.ID, "error", err)@@ -1468,14 +1466,14 @@ func (s *GitOpsSyncService) disableAutoSyncForBrokenBindingInternal(ctx context.s.unregisterSyncJobInternal(ctx, sync.ID)}-func (s *GitOpsSyncService) failSyncAndDisableAutoSyncInternal(ctx context.Context, id string, result *gitops.SyncResult, sync *models.GitOpsSync, actor models.User, message string, failure error) error {+func (s *GitOpsSyncService) failSyncAndDisableAutoSyncInternal(ctx context.Context, id string, result *gitops.SyncResult, sync *projectpkg.GitOpsSync, actor common.User, message string, failure error) error {errMsg := failure.Error()_ = s.failSync(ctx, id, result, sync, actor, message, errMsg)s.disableAutoSyncForBrokenBindingInternal(ctx, sync)return failure}-func (s *GitOpsSyncService) recordBrokenProjectBindingInternal(ctx context.Context, sync *models.GitOpsSync, actor models.User, err error) {+func (s *GitOpsSyncService) recordBrokenProjectBindingInternal(ctx context.Context, sync *projectpkg.GitOpsSync, actor common.User, err error) {if !errors.Is(err, common.ErrGitOpsSyncProjectBindingBroken) || sync == nil {return}@@ -1485,7 +1483,7 @@ func (s *GitOpsSyncService) recordBrokenProjectBindingInternal(ctx context.Contes.disableAutoSyncForBrokenBindingInternal(ctx, sync)}-func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sync *models.GitOpsSync, id string, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor models.User) (*models.Project, error) {+func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {// Use the non-suffixing create: a GitOps sync must never mint a "-N" duplicate.// A name collision means a project directory already exists for this name, so the// binding is broken — fail loudly and disable auto-sync instead of duplicating.@@ -1500,14 +1498,14 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, sy}// Update sync with project ID- if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("id = ?", id).Updates(map[string]any{+ if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", id).Updates(map[string]any{"project_id": project.ID,}).Error; err != nil {return nil, s.failSync(ctx, id, result, sync, actor, "Failed to update sync with project ID", err.Error())}// Mark project as GitOps-managed- if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", id).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&projectpkg.Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", id).Error; err != nil {return nil, s.failSync(ctx, id, result, sync, actor, "Failed to mark project as GitOps-managed", err.Error())}@@ -1520,8 +1518,8 @@ func (s *GitOpsSyncService) createProjectForSyncInternal(ctx context.Context, syreturn project, nil}-func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, sync *models.GitOpsSync, id string, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor models.User) (*models.Project, error) {- var project *models.Project+func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) (*projectpkg.Project, error) {+ var project *projectpkg.Projectif sync.ProjectID != nil && *sync.ProjectID != "" {var found bool@@ -1548,7 +1546,7 @@ func (s *GitOpsSyncService) getOrCreateProjectInternal(ctx context.Context, syncreturn project, nil}-func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, sync *models.GitOpsSync, id string, project *models.Project, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor models.User) error {+func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, id string, project *projectpkg.Project, composeContent string, envContent *string, overrideContent *string, overrideFileName string, result *gitops.SyncResult, actor common.User) error {// Get current content to see if it changedoldCompose, oldEnv, oldOverride, _ := s.projectService.GetProjectContent(ctx, project.ID)@@ -1567,7 +1565,7 @@ func (s *GitOpsSyncService) updateProjectForSyncInternal(ctx context.Context, sy// can reflect it on the sync row's LastSyncError.if contentChanged {details, err := s.projectService.GetProjectDetails(ctx, project.ID, projecttypes.DetailsOptions{})- if err == nil && (details.Status == string(models.ProjectStatusRunning) || details.Status == string(models.ProjectStatusPartiallyRunning)) {+ if err == nil && (details.Status == string(projectpkg.ProjectStatusRunning) || details.Status == string(projectpkg.ProjectStatusPartiallyRunning)) {slog.InfoContext(ctx, "Redeploying project due to content change from Git sync", "projectName", project.Name, "projectId", project.ID)if err := s.projectService.RedeployProject(ctx, project.ID, actor, nil); err != nil {slog.ErrorContext(ctx, "Failed to redeploy project after Git sync", "error", err, "projectId", project.ID)@@ -1615,7 +1613,7 @@ func marshalSyncedFiles(files []string) *string {// walkAndParseSyncDirectory walks the repository directory and returns all files with their contents.// Returns the list of SyncFile entries and an error if any; it fails if the compose file is missing.-func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, sync *models.GitOpsSync, repoPath string) ([]projects.SyncFile, error) {+func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, sync *projectpkg.GitOpsSync, repoPath string) ([]projects.SyncFile, error) {slog.InfoContext(ctx, "Starting directory walk", "syncId", sync.ID, "composePath", sync.ComposePath)// Walk the directory to get all files@@ -1659,7 +1657,7 @@ func (s *GitOpsSyncService) walkAndParseSyncDirectory(ctx context.Context, sync// syncProjectDirectoryInternal runs the new directory-sync path end to end:// stage files, validate the staged tree, then create or update the project.-func (s *GitOpsSyncService) syncProjectDirectoryInternal(ctx context.Context, sync *models.GitOpsSync, syncFiles []projects.SyncFile, actor models.User) (*models.Project, []string, bool, bool, error) {+func (s *GitOpsSyncService) syncProjectDirectoryInternal(ctx context.Context, sync *projectpkg.GitOpsSync, syncFiles []projects.SyncFile, actor common.User) (*projectpkg.Project, []string, bool, bool, error) {stage, err := s.stageDirectorySyncInternal(ctx, sync, syncFiles)if err != nil {s.recordBrokenProjectBindingInternal(ctx, sync, actor, err)@@ -1691,7 +1689,7 @@ func (s *GitOpsSyncService) syncProjectDirectoryInternal(ctx context.Context, sy// stageDirectorySyncInternal builds a temporary project tree that reflects the exact// repo layout after sync, including cleanup of files removed from the repo.-func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, sync *models.GitOpsSync, syncFiles []projects.SyncFile) (*stagedDirectorySync, error) {+func (s *GitOpsSyncService) stageDirectorySyncInternal(ctx context.Context, sync *projectpkg.GitOpsSync, syncFiles []projects.SyncFile) (*stagedDirectorySync, error) {projectsDir, err := s.projectService.GetProjectsDirectory(ctx)if err != nil {return nil, errors.WrapIf(err, "failed to get projects directory")@@ -1876,7 +1874,7 @@ func partitionReservedRootEnvFilesInternal(ctx context.Context, syncFiles []proj// expects values that the git repo intentionally does not provide. Only env// files are touched — other files would conflict with what WriteSyncedDirectory// is about to lay down from git.-func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Context, sync *models.GitOpsSync, projectsDir, stagePath string) error {+func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Context, sync *projectpkg.GitOpsSync, projectsDir, stagePath string) error {// The candidate may itself be a symlinked project directory, so it is probed// with os.Stat and then used as the confinement root for the reads below.candidatePath := filepath.Join(projectsDir, projects.SanitizeProjectName(sync.ProjectName))@@ -1960,8 +1958,8 @@ func (s *GitOpsSyncService) seedStageEnvFromCandidateDirInternal(ctx context.Conreturn nil}-func (s *GitOpsSyncService) lookupProjectByIDInternal(ctx context.Context, projectID string) (*models.Project, bool, error) {- var project models.Project+func (s *GitOpsSyncService) lookupProjectByIDInternal(ctx context.Context, projectID string) (*projectpkg.Project, bool, error) {+ var project projectpkg.Projectif err := s.db.WithContext(ctx).Where("id = ?", projectID).First(&project).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil@@ -1972,8 +1970,8 @@ func (s *GitOpsSyncService) lookupProjectByIDInternal(ctx context.Context, projereturn &project, true, nil}-func (s *GitOpsSyncService) lookupProjectByPathInternal(ctx context.Context, projectPath string) (*models.Project, bool, error) {- var project models.Project+func (s *GitOpsSyncService) lookupProjectByPathInternal(ctx context.Context, projectPath string) (*projectpkg.Project, bool, error) {+ var project projectpkg.Projectif err := s.db.WithContext(ctx).Where("path = ?", projectPath).First(&project).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil@@ -1984,15 +1982,15 @@ func (s *GitOpsSyncService) lookupProjectByPathInternal(ctx context.Context, proreturn &project, true, nil}-func (s *GitOpsSyncService) findRecoverableManagedProjectInternal(ctx context.Context, sync *models.GitOpsSync) (*models.Project, error) {- var managedProjects []models.Project+func (s *GitOpsSyncService) findRecoverableManagedProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync) (*projectpkg.Project, error) {+ var managedProjects []projectpkg.Projectif err := s.db.WithContext(ctx).Where("gitops_managed_by = ?", sync.ID).Find(&managedProjects).Error; err != nil {return nil, errors.WrapIff(err, "failed to list GitOps-managed projects for sync %s", sync.ID)}- matches := make([]models.Project, 0, len(managedProjects))+ matches := make([]projectpkg.Project, 0, len(managedProjects))for i := range managedProjects {project := managedProjects[i]if err := s.projectService.EnsureProjectPathUnderRoot(ctx, &project, true); err != nil {@@ -2017,7 +2015,7 @@ func (s *GitOpsSyncService) findRecoverableManagedProjectInternal(ctx context.Co}}-func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx context.Context, sync *models.GitOpsSync) (string, error) {+func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx context.Context, sync *projectpkg.GitOpsSync) (string, error) {projectsDir, err := s.projectService.GetProjectsDirectory(ctx)if err != nil {return "", err@@ -2070,12 +2068,12 @@ func (s *GitOpsSyncService) findUniqueProjectDirectoryCandidateInternal(ctx cont}}-func (s *GitOpsSyncService) createRecoveredProjectFromDirectoryInternal(ctx context.Context, sync *models.GitOpsSync, projectPath string) (*models.Project, error) {- project := &models.Project{+func (s *GitOpsSyncService) createRecoveredProjectFromDirectoryInternal(ctx context.Context, sync *projectpkg.GitOpsSync, projectPath string) (*projectpkg.Project, error) {+ project := &projectpkg.Project{Name: sync.ProjectName,DirName: new(filepath.Base(projectPath)),Path: projectPath,- Status: models.ProjectStatusUnknown,+ Status: projectpkg.ProjectStatusUnknown,StatusReason: new("Project recovered from existing GitOps-managed directory"),ServiceCount: 0,RunningCount: 0,@@ -2088,14 +2086,14 @@ func (s *GitOpsSyncService) createRecoveredProjectFromDirectoryInternal(ctx contslog.WarnContext(ctx, "Failed to count services while recovering GitOps project", "syncId", sync.ID, "path", projectPath, "error", err)}- if err := s.projectService.CreateGitOpsManagedProject(ctx, sync, project, models.User{}, false); err != nil {+ if err := s.projectService.CreateGitOpsManagedProject(ctx, sync, project, common.User{}, false); err != nil {return nil, err}return project, nil}-func (s *GitOpsSyncService) recoverProjectFromDirectoryCandidateInternal(ctx context.Context, sync *models.GitOpsSync) (*models.Project, error) {+func (s *GitOpsSyncService) recoverProjectFromDirectoryCandidateInternal(ctx context.Context, sync *projectpkg.GitOpsSync) (*projectpkg.Project, error) {projectPath, err := s.findUniqueProjectDirectoryCandidateInternal(ctx, sync)if err != nil || projectPath == "" {return nil, err@@ -2120,7 +2118,7 @@ func (s *GitOpsSyncService) recoverProjectFromDirectoryCandidateInternal(ctx con// getDirectorySyncProjectInternal resolves the linked project for a sync when one// exists, while tolerating deleted/stale project references.-func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context, sync *models.GitOpsSync) (*models.Project, error) {+func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync) (*projectpkg.Project, error) {if sync == nil {return nil, nil}@@ -2178,7 +2176,7 @@ func (s *GitOpsSyncService) getDirectorySyncProjectInternal(ctx context.Context,// createDirectorySyncProjectInternal promotes a validated staged tree into a new// managed project directory and links it back to the Git sync record.-func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Context, sync *models.GitOpsSync, stage *stagedDirectorySync, actor models.User) (*models.Project, error) {+func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync, stage *stagedDirectorySync, actor common.User) (*projectpkg.Project, error) {projectsDir, err := s.projectService.GetProjectsDirectory(ctx)if err != nil {return nil, errors.WrapIf(err, "failed to get projects directory")@@ -2210,11 +2208,11 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Conte}stage.stagePath = ""- project := &models.Project{+ project := &projectpkg.Project{Name: sync.ProjectName,DirName: new(folderName),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,ServiceCount: stage.serviceCount,RunningCount: 0,}@@ -2230,7 +2228,7 @@ func (s *GitOpsSyncService) createDirectorySyncProjectInternal(ctx context.Conte// updateDirectorySyncProjectInternal mirrors a validated staged tree into the// existing project path in place so running containers keep their bind-mount// inodes; a temporary backup copy allows rollback if promotion fails.-func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Context, sync *models.GitOpsSync, stage *stagedDirectorySync) (*models.Project, error) {+func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Context, sync *projectpkg.GitOpsSync, stage *stagedDirectorySync) (*projectpkg.Project, error) {project := stage.projectprojectPath := filepath.Clean(project.Path)backupPath := ""@@ -2295,7 +2293,7 @@ func (s *GitOpsSyncService) updateDirectorySyncProjectInternal(ctx context.Contereturn nil, errors.WrapIf(err, "failed to promote staged project directory")}- if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", project.ID).Updates(map[string]any{+ if err := s.db.WithContext(ctx).Model(&projectpkg.Project{}).Where("id = ?", project.ID).Updates(map[string]any{"service_count": stage.serviceCount,"gitops_managed_by": sync.ID,"updated_at": time.Now(),@@ -2326,7 +2324,7 @@ func (s *GitOpsSyncService) updateSyncStatusWithFiles(ctx context.Context, id, supdates["last_sync_commit"] = commitHash}- if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("id = ?", id).Updates(updates).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&projectpkg.GitOpsSync{}).Where("id = ?", id).Updates(updates).Error; err != nil {slog.ErrorContext(ctx, "Failed to update sync status with files", "error", err, "syncId", id)}}diff --git a/backend/internal/gitops/handler.go b/backend/internal/gitops/handler.goindex 02e1e0c78..1cce0f459 100644--- a/backend/internal/gitops/handler.go+++ b/backend/internal/gitops/handler.go@@ -1,12 +1,15 @@package gitopsimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/project"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"@@ -183,11 +186,11 @@ func (h *GitOpsSyncHandler) CreateSync(ctx context.Context, input *CreateGitOpsSsync, err := h.syncService.CreateSync(ctx, input.EnvironmentID, input.Body, actor)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to create GitOps sync").Error())}- body, mapErr := handlerutil.MapOneAPIResponse[*models.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {+ body, mapErr := handlerutil.MapOneAPIResponse[*project.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {return "Failed to map GitOps sync"})if mapErr != nil {@@ -220,11 +223,11 @@ func (h *GitOpsSyncHandler) ImportSyncs(ctx context.Context, input *ImportGitOpsfunc (h *GitOpsSyncHandler) GetSync(ctx context.Context, input *GetGitOpsSyncInput) (*GetGitOpsSyncOutput, error) {sync, err := h.syncService.GetSyncByID(ctx, input.EnvironmentID, input.SyncID)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to retrieve GitOps sync")}- body, mapErr := handlerutil.MapOneAPIResponse[*models.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {+ body, mapErr := handlerutil.MapOneAPIResponse[*project.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {return "Failed to map GitOps sync"})if mapErr != nil {@@ -246,11 +249,11 @@ func (h *GitOpsSyncHandler) UpdateSync(ctx context.Context, input *UpdateGitOpsSsync, err := h.syncService.UpdateSync(ctx, input.EnvironmentID, input.SyncID, input.Body, actor)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to update GitOps sync").Error())}- body, mapErr := handlerutil.MapOneAPIResponse[*models.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {+ body, mapErr := handlerutil.MapOneAPIResponse[*project.GitOpsSync, gitops.GitOpsSync](sync, func(err error) string {return "Failed to map GitOps sync"})if mapErr != nil {@@ -267,7 +270,7 @@ func (h *GitOpsSyncHandler) DeleteSync(ctx context.Context, input *DeleteGitOpsSactor := handlerutil.CurrentActor(ctx)if err := h.syncService.DeleteSync(ctx, input.EnvironmentID, input.SyncID, actor); err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete GitOps sync")}@@ -287,7 +290,7 @@ func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncIresult, err := h.syncService.PerformSync(ctx, input.EnvironmentID, input.SyncID, actor)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to perform GitOps sync")}@@ -303,7 +306,7 @@ func (h *GitOpsSyncHandler) PerformSync(ctx context.Context, input *PerformSyncIfunc (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusInput) (*GetSyncStatusOutput, error) {status, err := h.syncService.GetSyncStatus(ctx, input.EnvironmentID, input.SyncID)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to get GitOps sync status")}@@ -319,7 +322,7 @@ func (h *GitOpsSyncHandler) GetStatus(ctx context.Context, input *GetSyncStatusIfunc (h *GitOpsSyncHandler) BrowseFiles(ctx context.Context, input *BrowseSyncFilesInput) (*BrowseSyncFilesOutput, error) {response, err := h.syncService.BrowseFiles(ctx, input.EnvironmentID, input.SyncID, input.Path)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to browse GitOps sync files")}diff --git a/backend/internal/gitops/service_test.go b/backend/internal/gitops/service_test.goindex eecaa7688..b91e23976 100644--- a/backend/internal/gitops/service_test.go+++ b/backend/internal/gitops/service_test.go@@ -1,6 +1,10 @@package gitopsimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"++ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"+"context""encoding/json""os"@@ -15,9 +19,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"- "github.com/getarcaneapp/arcane/backend/v2/internal/lifecycle"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"- "github.com/getarcaneapp/arcane/backend/v2/internal/project"+ projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/settings"git "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -35,7 +37,7 @@ func setupGitOpsProjectTestDBInternal(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Project{}, &models.SettingVariable{}, &models.ImageUpdateRecord{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&projectpkg.Project{}, &settings.SettingVariable{}, &imageupdate.ImageUpdateRecord{}, &event.Event{}))return &database.DB{DB: db}}@@ -79,7 +81,7 @@ func setupGitOpsSyncDirectoryTestService(t *testing.T) (*GitOpsSyncService, *datctx := context.Background()db := setupGitOpsProjectTestDBInternal(t)- require.NoError(t, db.AutoMigrate(&models.GitOpsSync{}))+ require.NoError(t, db.AutoMigrate(&projectpkg.GitOpsSync{}))settingsService, err := newGitOpsSettingsServiceForTestInternal(t, ctx, db)require.NoError(t, err)@@ -88,7 +90,7 @@ func setupGitOpsSyncDirectoryTestService(t *testing.T) (*GitOpsSyncService, *datrequire.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsDir))eventService := event.NewEventService(db, config.Load(), nil)- projectService := project.NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())+ projectService := projectpkg.NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())return NewGitOpsSyncService(db, nil, projectService, nil, eventService, settingsService), db, projectsDir}@@ -107,7 +109,7 @@ func TestGitOpsSyncService_OverlappingSyncPreservesSuccessShapedSkipInternal(t *service := &GitOpsSyncService{jobs: entityjobs.New(entityjobs.GitOpsSyncJobPrefix, gitOpsSyncAdmissionScopeInternal)}require.NoError(t, service.SetScheduler(t.Context(), &gitOpsSyncTestSchedulerInternal{}, gate))- result, err := service.PerformSync(t.Context(), "0", "sync-id", models.User{})+ result, err := service.PerformSync(t.Context(), "0", "sync-id", common.User{})require.NoError(t, err)require.False(t, result.Success)require.Equal(t, "sync already in progress", result.Message)@@ -146,16 +148,16 @@ func writeFileInternal(t *testing.T, rootDir, relativePath string, content []byt}func TestApplyLifecycleFieldsToSyncInternal_DefaultsPreDeployTimeout(t *testing.T) {- var sync models.GitOpsSync+ var sync projectpkg.GitOpsSyncapplyLifecycleFieldsToSyncInternal(&sync, lifecycleConfigInputInternal{})- require.Equal(t, lifecycle.DefaultTimeoutSec, sync.PreDeployTimeoutSec)+ require.Equal(t, projectpkg.DefaultTimeoutSec, sync.PreDeployTimeoutSec)}func TestApplyLifecycleFieldsToSyncInternal_UsesExplicitPreDeployTimeout(t *testing.T) {timeoutSec := 90- var sync models.GitOpsSync+ var sync projectpkg.GitOpsSyncapplyLifecycleFieldsToSyncInternal(&sync, lifecycleConfigInputInternal{timeoutSec: &timeoutSec})@@ -174,16 +176,16 @@ func TestGitOpsSyncService_GetSyncByID_ReturnsNotFoundError(t *testing.T) {func TestGitOpsSyncService_CleanupOrphanedSyncsOnStartup_DeletesOnlyOrphans(t *testing.T) {ctx := context.Background()svc, db, _ := setupGitOpsSyncDirectoryTestService(t)- require.NoError(t, db.AutoMigrate(&models.Environment{}))+ require.NoError(t, db.AutoMigrate(&environment.Environment{}))- require.NoError(t, db.Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-live"},+ require.NoError(t, db.Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-live"},Name: "Live",}).Error)orphanSyncID := "sync-orphan"liveSyncID := "sync-live"- require.NoError(t, db.Create(&models.GitOpsSync{- BaseModel: models.BaseModel{ID: orphanSyncID},+ require.NoError(t, db.Create(&projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: orphanSyncID},Name: "orphan",EnvironmentID: "env-missing",RepositoryID: "repo-1",@@ -191,8 +193,8 @@ func TestGitOpsSyncService_CleanupOrphanedSyncsOnStartup_DeletesOnlyOrphans(t *tProjectName: "orphan",SyncInterval: 15,}).Error)- require.NoError(t, db.Create(&models.GitOpsSync{- BaseModel: models.BaseModel{ID: liveSyncID},+ require.NoError(t, db.Create(&projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: liveSyncID},Name: "live",EnvironmentID: "env-live",RepositoryID: "repo-1",@@ -200,25 +202,25 @@ func TestGitOpsSyncService_CleanupOrphanedSyncsOnStartup_DeletesOnlyOrphans(t *tProjectName: "live",SyncInterval: 15,}).Error)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-orphan"},+ require.NoError(t, db.Create(&projectpkg.Project{+ BaseModel: database.BaseModel{ID: "project-orphan"},Name: "orphan",Path: "/tmp/orphan",- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,GitOpsManagedBy: &orphanSyncID,}).Error)require.NoError(t, svc.CleanupOrphanedSyncsOnStartup(ctx))var orphanCount int64- require.NoError(t, db.Model(&models.GitOpsSync{}).Where("id = ?", orphanSyncID).Count(&orphanCount).Error)+ require.NoError(t, db.Model(&projectpkg.GitOpsSync{}).Where("id = ?", orphanSyncID).Count(&orphanCount).Error)require.Zero(t, orphanCount)var liveCount int64- require.NoError(t, db.Model(&models.GitOpsSync{}).Where("id = ?", liveSyncID).Count(&liveCount).Error)+ require.NoError(t, db.Model(&projectpkg.GitOpsSync{}).Where("id = ?", liveSyncID).Count(&liveCount).Error)require.EqualValues(t, 1, liveCount)- var project models.Project+ var project projectpkg.Projectrequire.NoError(t, db.First(&project, "id = ?", "project-orphan").Error)require.Nil(t, project.GitOpsManagedBy)}@@ -226,14 +228,14 @@ func TestGitOpsSyncService_CleanupOrphanedSyncsOnStartup_DeletesOnlyOrphans(t *tfunc TestGitOpsSyncService_RegisterAutoSyncJobsOnStartup_SkipsOrphans(t *testing.T) {ctx := context.Background()svc, db, _ := setupGitOpsSyncDirectoryTestService(t)- require.NoError(t, db.AutoMigrate(&models.Environment{}))+ require.NoError(t, db.AutoMigrate(&environment.Environment{}))- require.NoError(t, db.Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-live"},+ require.NoError(t, db.Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-live"},Name: "Live",}).Error)- require.NoError(t, db.Create(&models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-orphan"},+ require.NoError(t, db.Create(&projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-orphan"},Name: "orphan",EnvironmentID: "env-missing",RepositoryID: "repo-1",@@ -243,8 +245,8 @@ func TestGitOpsSyncService_RegisterAutoSyncJobsOnStartup_SkipsOrphans(t *testingSyncInterval: 15,}).Error)now := time.Now()- require.NoError(t, db.Create(&models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-live"},+ require.NoError(t, db.Create(&projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-live"},Name: "live",EnvironmentID: "env-live",RepositoryID: "repo-1",@@ -268,8 +270,8 @@ func TestGitOpsSyncService_DeleteSync_DeletesStaleProjectReference(t *testing.T)svc, db, _ := setupGitOpsSyncDirectoryTestService(t)missingProjectID := "missing-project"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-delete-stale-project"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-delete-stale-project"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -280,10 +282,10 @@ func TestGitOpsSyncService_DeleteSync_DeletesStaleProjectReference(t *testing.T)}require.NoError(t, db.Create(sync).Error)- require.NoError(t, svc.DeleteSync(ctx, "0", sync.ID, models.User{}))+ require.NoError(t, svc.DeleteSync(ctx, "0", sync.ID, common.User{}))var count int64- require.NoError(t, db.Model(&models.GitOpsSync{}).Where("id = ?", sync.ID).Count(&count).Error)+ require.NoError(t, db.Model(&projectpkg.GitOpsSync{}).Where("id = ?", sync.ID).Count(&count).Error)assert.Zero(t, count)}@@ -296,8 +298,8 @@ func TestGitOpsSyncService_DeleteSync_SucceedsWhenEnvironmentMismatched(t *testischeduler := &gitOpsSyncTestSchedulerInternal{}require.NoError(t, svc.SetScheduler(ctx, scheduler, newGitOpsAdmissionGateForTestInternal(t)))- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-env-mismatch"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-env-mismatch"},Name: "corrupt-sync",EnvironmentID: "5",ProjectName: "demo-project",@@ -305,10 +307,10 @@ func TestGitOpsSyncService_DeleteSync_SucceedsWhenEnvironmentMismatched(t *testi}require.NoError(t, db.Create(sync).Error)- require.NoError(t, svc.DeleteSync(ctx, "0", sync.ID, models.User{}))+ require.NoError(t, svc.DeleteSync(ctx, "0", sync.ID, common.User{}))var count int64- require.NoError(t, db.Model(&models.GitOpsSync{}).Where("id = ?", sync.ID).Count(&count).Error)+ require.NoError(t, db.Model(&projectpkg.GitOpsSync{}).Where("id = ?", sync.ID).Count(&count).Error)assert.Zero(t, count)assert.Contains(t, scheduler.removed, entityjobs.GitOpsSyncJobPrefix+sync.ID)}@@ -320,8 +322,8 @@ func TestGitOpsSyncService_DeleteSync_ClearsOrphanedManagedFlag(t *testing.T) {svc, db, _ := setupGitOpsSyncDirectoryTestService(t)syncID := "sync-orphan-flag"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: syncID},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: syncID},Name: "demo-sync",EnvironmentID: "0",ProjectName: "demo-project",@@ -329,17 +331,17 @@ func TestGitOpsSyncService_DeleteSync_ClearsOrphanedManagedFlag(t *testing.T) {}require.NoError(t, db.Create(sync).Error)- managed := &models.Project{- BaseModel: models.BaseModel{ID: "proj-managed"},+ managed := &projectpkg.Project{+ BaseModel: database.BaseModel{ID: "proj-managed"},Name: "managed",Path: filepath.Join(t.TempDir(), "managed"),GitOpsManagedBy: &syncID,}require.NoError(t, db.Create(managed).Error)- require.NoError(t, svc.DeleteSync(ctx, "0", syncID, models.User{}))+ require.NoError(t, svc.DeleteSync(ctx, "0", syncID, common.User{}))- var got models.Project+ var got projectpkg.Projectrequire.NoError(t, db.Where("id = ?", managed.ID).First(&got).Error)assert.Nil(t, got.GitOpsManagedBy)}@@ -400,8 +402,8 @@ func TestGitOpsSyncService_SyncProjectDirectory_RefusesDuplicateOnNameCollision(require.NoError(t, os.MkdirAll(filepath.Join(projectsDir, "Dozzle"), 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectsDir, "Dozzle", "unrelated.txt"), []byte("x"), 0o644))- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-dup-refuse"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-dup-refuse"},Name: "Dozzle",EnvironmentID: "0",ComposePath: "Dozzle/docker-compose.yaml",@@ -416,13 +418,13 @@ func TestGitOpsSyncService_SyncProjectDirectory_RefusesDuplicateOnNameCollision({RelativePath: "docker-compose.yaml", Content: []byte("services:\n app:\n image: nginx:alpine\n")},}- _, _, _, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ _, _, _, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)_, statErr := os.Stat(filepath.Join(projectsDir, "Dozzle-1"))require.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")- var got models.GitOpsSync+ var got projectpkg.GitOpsSyncrequire.NoError(t, db.Where("id = ?", sync.ID).First(&got).Error)assert.False(t, got.AutoSync, "auto-sync should be disabled on broken binding")}@@ -437,8 +439,8 @@ func TestGitOpsSyncService_GetOrCreateProject_RefusesDuplicateOnNameCollision(trequire.NoError(t, os.MkdirAll(filepath.Join(projectsDir, "Dozzle"), 0o755))- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-single-dup"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-single-dup"},Name: "Dozzle",EnvironmentID: "0",ComposePath: "docker-compose.yaml",@@ -449,13 +451,13 @@ func TestGitOpsSyncService_GetOrCreateProject_RefusesDuplicateOnNameCollision(trequire.NoError(t, db.Create(sync).Error)result := &gitops.SyncResult{}- _, err := svc.getOrCreateProjectInternal(ctx, sync, sync.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", result, models.User{})+ _, err := svc.getOrCreateProjectInternal(ctx, sync, sync.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", result, common.User{})require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)_, statErr := os.Stat(filepath.Join(projectsDir, "Dozzle-1"))require.ErrorIs(t, statErr, os.ErrNotExist, "must not mint a -N duplicate")- var got models.GitOpsSync+ var got projectpkg.GitOpsSyncrequire.NoError(t, db.Where("id = ?", sync.ID).First(&got).Error)assert.False(t, got.AutoSync, "auto-sync should be disabled on broken binding")}@@ -464,8 +466,8 @@ func TestGitOpsSyncService_SyncProjectDirectory_CreatesProjectPreservingRepoLayoctx := context.Background()svc, db, _ := setupGitOpsSyncDirectoryTestService(t)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-create"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-create"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -501,7 +503,7 @@ services:},}- project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, project)require.True(t, created)@@ -559,20 +561,20 @@ services:require.NoError(t, os.WriteFile(filepath.Join(projectPath, "keep.txt"), []byte("keep me\n"), 0o644))require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services: {}\n"), 0o644))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-directory-update"},+ project := &projectpkg.Project{+ BaseModel: database.BaseModel{ID: "proj-directory-update"},Name: "demo-project",DirName: new("demo-project"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)oldSyncedFilesJSON, err := json.Marshal([]string{"docker-compose.yaml", "meta.yaml", "old.txt"})require.NoError(t, err)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-update"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-update"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -603,7 +605,7 @@ services:},}- updatedProject, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ updatedProject, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, updatedProject)require.False(t, created)@@ -649,20 +651,20 @@ func TestGitOpsSyncService_SyncProjectDirectory_PreservesEnvOverrideAndAddsNewGirequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "project.env"), []byte("FOO=useredit\n"), 0o644))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("FOO=useredit\n"), 0o644))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-directory-env-preserve"},+ project := &projectpkg.Project{+ BaseModel: database.BaseModel{ID: "proj-directory-env-preserve"},Name: "demo-project",DirName: new("demo-project"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)oldSyncedFilesJSON, err := json.Marshal([]string{"docker-compose.yaml"})require.NoError(t, err)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-env-preserve"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-env-preserve"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -689,7 +691,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_PreservesEnvOverrideAndAddsNewGi},}- updatedProject, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ updatedProject, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, updatedProject)require.False(t, created)@@ -740,12 +742,12 @@ func TestGitOpsSyncService_SyncProjectDirectory_MigratesLegacyTrackedEnvOnFirstS`), 0o644))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("LOCAL_ONLY=1\n"), 0o644))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-directory-legacy-env-migrate"},+ project := &projectpkg.Project{+ BaseModel: database.BaseModel{ID: "proj-directory-legacy-env-migrate"},Name: "demo-project",DirName: new("demo-project"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -753,8 +755,8 @@ func TestGitOpsSyncService_SyncProjectDirectory_MigratesLegacyTrackedEnvOnFirstSoldSyncedFilesJSON, err := json.Marshal([]string{"docker-compose.yaml", ".env"})require.NoError(t, err)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-legacy-env-migrate"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-legacy-env-migrate"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -780,7 +782,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_MigratesLegacyTrackedEnvOnFirstS},}- updatedProject, _, created, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ updatedProject, _, created, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, updatedProject)require.False(t, created)@@ -803,8 +805,8 @@ func TestGitOpsSyncService_SyncProjectDirectory_IgnoresCommittedReservedEnvFilesctx := context.Background()svc, db, _ := setupGitOpsSyncDirectoryTestService(t)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-reserved-env"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-reserved-env"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -836,7 +838,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_IgnoresCommittedReservedEnvFiles},}- project, syncedFiles, created, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ project, syncedFiles, created, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, project)require.True(t, created)@@ -877,8 +879,8 @@ func TestGitOpsSyncService_DirectorySync_RealWalkWithNestedConfig(t *testing.T)rule: Host(`+"`"+`traefik.example.com`+"`"+`)`))- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-real-walk"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-real-walk"},Name: "traefik-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -898,7 +900,7 @@ func TestGitOpsSyncService_DirectorySync_RealWalkWithNestedConfig(t *testing.T)}assert.Contains(t, composeContent, "./config/dynamic_config.yml")- project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, project)require.True(t, created)@@ -949,17 +951,17 @@ func TestGitOpsSyncService_DirectorySync_OverwritesExistingDirectoryAtFilePath(trequire.NoError(t, os.MkdirAll(filepath.Join(projectPath, "logs"), 0o755))dirName := "traefik-project"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-directory-docker-dir-conflict"},+ project := &projectpkg.Project{+ BaseModel: database.BaseModel{ID: "proj-directory-docker-dir-conflict"},Name: "traefik-project",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-docker-dir-conflict"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-docker-dir-conflict"},Name: "traefik-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -973,7 +975,7 @@ func TestGitOpsSyncService_DirectorySync_OverwritesExistingDirectoryAtFilePath(tsyncFiles, err := svc.walkAndParseSyncDirectory(ctx, sync, repoPath)require.NoError(t, err)- updatedProject, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ updatedProject, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, updatedProject)require.False(t, created)@@ -1006,8 +1008,8 @@ func TestGitOpsSyncService_CreateDirectorySyncProjectInternal_RollsBackProjectOnctx := context.Background()svc, db, projectsDir := setupGitOpsSyncDirectoryTestService(t)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-tx-rollback"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-tx-rollback"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1039,16 +1041,16 @@ func TestGitOpsSyncService_CreateDirectorySyncProjectInternal_RollsBackProjectOn_ = db.Callback().Update().Remove(callbackName)}()- project, err := svc.createDirectorySyncProjectInternal(ctx, sync, stage, models.User{})+ project, err := svc.createDirectorySyncProjectInternal(ctx, sync, stage, common.User{})require.Error(t, err)require.Nil(t, project)assert.Contains(t, err.Error(), "failed to mark project as GitOps-managed")var projectCount int64- require.NoError(t, db.Model(&models.Project{}).Count(&projectCount).Error)+ require.NoError(t, db.Model(&projectpkg.Project{}).Count(&projectCount).Error)assert.Zero(t, projectCount)- var storedSync models.GitOpsSync+ var storedSync projectpkg.GitOpsSyncrequire.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)assert.Nil(t, storedSync.ProjectID)@@ -1086,8 +1088,8 @@ func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RelinksManagedProjectrequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "radarr.yaml"), []byte("services:\n app:\n image: lscr.io/linuxserver/radarr:latest\n"), 0o644))missingProjectID := "missing-project"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-relink"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-relink"},Name: "radarr-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1099,12 +1101,12 @@ func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RelinksManagedProjectrequire.NoError(t, db.Create(sync).Error)dirName := "Radarr-3"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-directory-relink"},+ project := &projectpkg.Project{+ BaseModel: database.BaseModel{ID: "proj-directory-relink"},Name: "Radarr",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,GitOpsManagedBy: &sync.ID,}require.NoError(t, db.Create(project).Error)@@ -1114,7 +1116,7 @@ func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RelinksManagedProjectrequire.NotNil(t, recovered)assert.Equal(t, project.ID, recovered.ID)- var storedSync models.GitOpsSync+ var storedSync projectpkg.GitOpsSyncrequire.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)require.NotNil(t, storedSync.ProjectID)assert.Equal(t, project.ID, *storedSync.ProjectID)@@ -1129,8 +1131,8 @@ func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RecoversUniqueDirectorequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "radarr.yaml"), []byte("services:\n app:\n image: lscr.io/linuxserver/radarr:latest\n"), 0o644))missingProjectID := "missing-project"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-disk-recovery"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-disk-recovery"},Name: "radarr-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1148,12 +1150,12 @@ func TestGitOpsSyncService_GetDirectorySyncProjectInternal_RecoversUniqueDirectorequire.NotNil(t, recovered.GitOpsManagedBy)assert.Equal(t, sync.ID, *recovered.GitOpsManagedBy)- var storedSync models.GitOpsSync+ var storedSync projectpkg.GitOpsSyncrequire.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)require.NotNil(t, storedSync.ProjectID)assert.Equal(t, recovered.ID, *storedSync.ProjectID)- var storedProject models.Project+ var storedProject projectpkg.Projectrequire.NoError(t, db.First(&storedProject, "id = ?", recovered.ID).Error)assert.Equal(t, projectPath, storedProject.Path)assert.Equal(t, 1, storedProject.ServiceCount)@@ -1170,8 +1172,8 @@ func TestGitOpsSyncService_ReconcileDirectorySyncProjectsOnStartup_SkipsAmbiguou}missingProjectID := "missing-project"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-ambiguous"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-ambiguous"},Name: "radarr-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1185,10 +1187,10 @@ func TestGitOpsSyncService_ReconcileDirectorySyncProjectsOnStartup_SkipsAmbiguourequire.NoError(t, svc.ReconcileDirectorySyncProjectsOnStartup(ctx))var projectsCount int64- require.NoError(t, db.Model(&models.Project{}).Count(&projectsCount).Error)+ require.NoError(t, db.Model(&projectpkg.Project{}).Count(&projectsCount).Error)assert.Zero(t, projectsCount)- var storedSync models.GitOpsSync+ var storedSync projectpkg.GitOpsSyncrequire.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)require.NotNil(t, storedSync.ProjectID)assert.Equal(t, "missing-project", *storedSync.ProjectID)@@ -1201,8 +1203,8 @@ func TestGitOpsSyncService_SyncProjectDirectory_FailsWhenBoundProjectMissing(t *require.NoError(t, svc.SetScheduler(ctx, testScheduler, newGitOpsAdmissionGateForTestInternal(t)))missingProjectID := "missing-project"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-missing-bound-project"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-missing-bound-project"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1224,7 +1226,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_FailsWhenBoundProjectMissing(t *},}- project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.Error(t, err)require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)require.Nil(t, project)@@ -1233,13 +1235,13 @@ func TestGitOpsSyncService_SyncProjectDirectory_FailsWhenBoundProjectMissing(t *assert.False(t, changed)var projectCount int64- require.NoError(t, db.Model(&models.Project{}).Count(&projectCount).Error)+ require.NoError(t, db.Model(&projectpkg.Project{}).Count(&projectCount).Error)assert.Zero(t, projectCount)_, statErr := os.Stat(filepath.Join(projectsDir, "demo-project"))require.ErrorIs(t, statErr, os.ErrNotExist)- var storedSync models.GitOpsSync+ var storedSync projectpkg.GitOpsSyncrequire.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)assert.False(t, storedSync.AutoSync)require.NotNil(t, storedSync.LastSyncStatus)@@ -1262,8 +1264,8 @@ func TestGitOpsSyncService_SyncProjectDirectory_DisablesAutoSyncWhenBoundProject}missingProjectID := "missing-project"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-directory-ambiguous-bound-project"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-directory-ambiguous-bound-project"},Name: "radarr-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1282,7 +1284,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_DisablesAutoSyncWhenBoundProject},}- project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ project, syncedFiles, created, changed, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.Error(t, err)require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)require.Nil(t, project)@@ -1291,10 +1293,10 @@ func TestGitOpsSyncService_SyncProjectDirectory_DisablesAutoSyncWhenBoundProjectassert.False(t, changed)var projectCount int64- require.NoError(t, db.Model(&models.Project{}).Count(&projectCount).Error)+ require.NoError(t, db.Model(&projectpkg.Project{}).Count(&projectCount).Error)assert.Zero(t, projectCount)- var storedSync models.GitOpsSync+ var storedSync projectpkg.GitOpsSyncrequire.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)assert.False(t, storedSync.AutoSync)require.NotNil(t, storedSync.LastSyncStatus)@@ -1311,8 +1313,8 @@ func TestGitOpsSyncService_GetOrCreateProjectInternal_FailsWhenBoundProjectMissirequire.NoError(t, svc.SetScheduler(ctx, testScheduler, newGitOpsAdmissionGateForTestInternal(t)))missingProjectID := "missing-project"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-file-missing-bound-project"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-file-missing-bound-project"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1324,13 +1326,13 @@ func TestGitOpsSyncService_GetOrCreateProjectInternal_FailsWhenBoundProjectMissirequire.NoError(t, db.Create(sync).Error)result := &gitops.SyncResult{}- project, err := svc.getOrCreateProjectInternal(ctx, sync, sync.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", result, models.User{})+ project, err := svc.getOrCreateProjectInternal(ctx, sync, sync.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", result, common.User{})require.Error(t, err)require.ErrorIs(t, err, common.ErrGitOpsSyncProjectBindingBroken)require.Nil(t, project)var projectCount int64- require.NoError(t, db.Model(&models.Project{}).Count(&projectCount).Error)+ require.NoError(t, db.Model(&projectpkg.Project{}).Count(&projectCount).Error)assert.Zero(t, projectCount)_, statErr := os.Stat(filepath.Join(projectsDir, "demo-project"))@@ -1338,7 +1340,7 @@ func TestGitOpsSyncService_GetOrCreateProjectInternal_FailsWhenBoundProjectMissi_, statErr = os.Stat(filepath.Join(projectsDir, "demo-project-1"))require.ErrorIs(t, statErr, os.ErrNotExist)- var storedSync models.GitOpsSync+ var storedSync projectpkg.GitOpsSyncrequire.NoError(t, db.First(&storedSync, "id = ?", sync.ID).Error)assert.False(t, storedSync.AutoSync)require.NotNil(t, storedSync.LastSyncStatus)@@ -1400,7 +1402,7 @@ func TestGitOpsSyncService_GetEffectiveSyncLimits(t *testing.T) {svc := &GitOpsSyncService{settingsService: settingsSvc}t.Run("preserves sync-specific limits when they exceed settings", func(t *testing.T) {- sync := &models.GitOpsSync{+ sync := &projectpkg.GitOpsSync{MaxSyncFiles: 500,MaxSyncTotalSize: 50 * 1024 * 1024,MaxSyncBinarySize: 10 * 1024 * 1024,@@ -1414,7 +1416,7 @@ func TestGitOpsSyncService_GetEffectiveSyncLimits(t *testing.T) {})t.Run("preserves sync-specific limits when they are below settings", func(t *testing.T) {- sync := &models.GitOpsSync{+ sync := &projectpkg.GitOpsSync{MaxSyncFiles: 75,MaxSyncTotalSize: 8 * 1024 * 1024,MaxSyncBinarySize: 2 * 1024 * 1024,@@ -1428,7 +1430,7 @@ func TestGitOpsSyncService_GetEffectiveSyncLimits(t *testing.T) {})t.Run("zero disables sync limits", func(t *testing.T) {- sync := &models.GitOpsSync{+ sync := &projectpkg.GitOpsSync{MaxSyncFiles: 0,MaxSyncTotalSize: 0,MaxSyncBinarySize: 0,@@ -1449,7 +1451,7 @@ func TestGitOpsSyncService_GetEffectiveSyncLimits(t *testing.T) {require.NoError(t, svcErr)svcEnv := &GitOpsSyncService{settingsService: settingsSvcEnv}- sync := &models.GitOpsSync{+ sync := &projectpkg.GitOpsSync{MaxSyncFiles: 500,MaxSyncTotalSize: 50 * 1024 * 1024,MaxSyncBinarySize: 10 * 1024 * 1024,@@ -1470,7 +1472,7 @@ func TestGitOpsSyncService_GetEffectiveSyncLimits(t *testing.T) {require.NoError(t, svcErr)svcEnv := &GitOpsSyncService{settingsService: settingsSvcEnv}- sync := &models.GitOpsSync{+ sync := &projectpkg.GitOpsSync{MaxSyncFiles: 75,MaxSyncTotalSize: 8 * 1024 * 1024,MaxSyncBinarySize: 2 * 1024 * 1024,@@ -1568,7 +1570,7 @@ func TestValidateLifecycleConfig_AcceptsScriptWithDefaultRunnerImageOnCreate(t *func TestValidateLifecycleConfig_AcceptsScriptWithExistingRunnerImageOnUpdate(t *testing.T) {svc, ctx := setupLifecycleValidationService(t)- existing := &models.GitOpsSync{SyncDirectory: true}+ existing := &projectpkg.GitOpsSync{SyncDirectory: true}existing.PreDeployRunnerImage = new("alpine:latest")require.NoError(t, svc.validateLifecycleConfigInternal(ctx, existing, lifecycleConfigInputInternal{scriptPath: new("scripts/deploy.sh"),@@ -1631,7 +1633,7 @@ func TestValidateLifecycleConfig_RejectsRelativeMountTarget(t *testing.T) {func TestValidateLifecycleConfig_AllowsClearingScriptWithoutImage(t *testing.T) {svc, ctx := setupLifecycleValidationService(t)- existing := &models.GitOpsSync{}+ existing := &projectpkg.GitOpsSync{}existing.PreDeployScriptPath = new("scripts/old.sh")existing.PreDeployRunnerImage = new("alpine:latest")// User clears the script (empty string in update); image clear is implied not required.@@ -1678,7 +1680,7 @@ func TestValidateLifecycleConfig_RejectsLifecycleHookForSwarmStack(t *testing.T)func TestValidateLifecycleConfig_RejectsSwarmTargetChangeWithExistingLifecycleHook(t *testing.T) {svc, ctx := setupLifecycleValidationService(t)- existing := &models.GitOpsSync{TargetType: "project", SyncDirectory: true}+ existing := &projectpkg.GitOpsSync{TargetType: "project", SyncDirectory: true}existing.PreDeployScriptPath = new("scripts/deploy.sh")existing.PreDeployRunnerImage = new("alpine:latest")err := svc.validateLifecycleConfigInternal(ctx, existing, lifecycleConfigInputInternal{@@ -1692,7 +1694,7 @@ func TestValidateLifecycleConfig_RejectsSwarmTargetChangeWithExistingLifecycleHofunc TestValidateLifecycleConfig_AcceptsScriptWhenExistingSyncHasSyncDirectory(t *testing.T) {svc, ctx := setupLifecycleValidationService(t)- existing := &models.GitOpsSync{SyncDirectory: true}+ existing := &projectpkg.GitOpsSync{SyncDirectory: true}require.NoError(t, svc.validateLifecycleConfigInternal(ctx, existing, lifecycleConfigInputInternal{scriptPath: new("scripts/deploy.sh"),runnerImage: new("alpine:latest"),@@ -1701,7 +1703,7 @@ func TestValidateLifecycleConfig_AcceptsScriptWhenExistingSyncHasSyncDirectory(tfunc TestValidateLifecycleConfig_RejectsSyncDirectoryToggleOffWhileScriptStillSet(t *testing.T) {svc, ctx := setupLifecycleValidationService(t)- existing := &models.GitOpsSync{SyncDirectory: true}+ existing := &projectpkg.GitOpsSync{SyncDirectory: true}existing.PreDeployScriptPath = new("scripts/deploy.sh")existing.PreDeployRunnerImage = new("alpine:latest")// Admin toggles syncDirectory off without clearing the script — should be rejected.@@ -1728,11 +1730,11 @@ func TestMarkSyncRedeployFailedInternal_PersistsErrorOnSyncRow(t *testing.T) {svc, db, _ := setupGitOpsSyncDirectoryTestService(t)// Event logging requires a real event.EventService; the shared setup leaves it// nil since most tests don't exercise the event path.- require.NoError(t, db.AutoMigrate(&models.Event{}))+ require.NoError(t, db.AutoMigrate(&event.Event{}))svc.eventService = event.NewEventService(db, config.Load(), nil)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-1"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-1"},Name: "redeploy-fail",EnvironmentID: "0",RepositoryID: "repo-1",@@ -1746,13 +1748,13 @@ func TestMarkSyncRedeployFailedInternal_PersistsErrorOnSyncRow(t *testing.T) {syncedFiles := []string{"compose.yml", "scripts/pre-deploy.sh"}hookErr := common.Classify(common.ErrRedeployAfterSyncFailed, errors.WrapIf(errors.New("pre-deploy hook failed: exit 1"), "redeploy failed"))- svc.markSyncRedeployFailedInternal(ctx, sync, sync.ID, "abc123", syncedFiles, hookErr, models.User{BaseModel: models.BaseModel{ID: "user"}, Username: "tester"}, result)+ svc.markSyncRedeployFailedInternal(ctx, sync, sync.ID, "abc123", syncedFiles, hookErr, common.User{BaseModel: database.BaseModel{ID: "user"}, Username: "tester"}, result)require.False(t, result.Success)require.NotNil(t, result.Error)require.Contains(t, *result.Error, "pre-deploy hook failed")- var stored models.GitOpsSync+ var stored projectpkg.GitOpsSyncrequire.NoError(t, db.WithContext(ctx).First(&stored, "id = ?", sync.ID).Error)require.NotNil(t, stored.LastSyncStatus)require.Equal(t, "failed", *stored.LastSyncStatus)diff --git a/backend/internal/gitops/service_unix_test.go b/backend/internal/gitops/service_unix_test.goindex 85d43d853..7ea8e869a 100644--- a/backend/internal/gitops/service_unix_test.go+++ b/backend/internal/gitops/service_unix_test.go@@ -3,13 +3,17 @@package gitopsimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+ projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""encoding/json""os""path/filepath""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -43,20 +47,20 @@ func TestGitOpsSyncService_SyncProjectDirectory_PreservesUnreadableBindMountDatarequire.NoError(t, os.Chmod(secretPath, 0o000))t.Cleanup(func() { _ = os.Chmod(secretPath, 0o644) })- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-unreadable-bindmount"},+ project := &projectpkg.Project{+ BaseModel: database.BaseModel{ID: "proj-unreadable-bindmount"},Name: "demo-project",DirName: new("demo-project"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: projectpkg.ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)oldSyncedFilesJSON, err := json.Marshal([]string{"docker-compose.yaml"})require.NoError(t, err)- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: "sync-unreadable-bindmount"},+ sync := &projectpkg.GitOpsSync{+ BaseModel: database.BaseModel{ID: "sync-unreadable-bindmount"},Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -78,7 +82,7 @@ func TestGitOpsSyncService_SyncProjectDirectory_PreservesUnreadableBindMountData},}- updatedProject, _, created, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, models.User{})+ updatedProject, _, created, _, err := svc.syncProjectDirectoryInternal(ctx, sync, syncFiles, common.User{})require.NoError(t, err)require.NotNil(t, updatedProject)require.False(t, created)diff --git a/backend/internal/gitrepo/handler.go b/backend/internal/gitrepo/handler.goindex ec1df5e07..306cf0666 100644--- a/backend/internal/gitrepo/handler.go+++ b/backend/internal/gitrepo/handler.go@@ -1,11 +1,12 @@package gitrepoimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""emperror.dev/errors""github.com/danielgtaylor/huma/v2"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"@@ -34,7 +35,7 @@ type ListGitRepositoriesOutput struct {}type CreateGitRepositoryInput struct {- Body models.CreateGitRepositoryRequest+ Body CreateGitRepositoryRequest}type CreateGitRepositoryOutput struct {@@ -51,7 +52,7 @@ type GetGitRepositoryOutput struct {type UpdateGitRepositoryInput struct {ID string `path:"id" doc:"Repository ID"`- Body models.UpdateGitRepositoryRequest+ Body UpdateGitRepositoryRequest}type UpdateGitRepositoryOutput struct {@@ -148,11 +149,11 @@ func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *Crearepo, err := h.repoService.CreateRepository(ctx, input.Body, actor)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to create git repository")}- body, mapErr := handlerutil.MapOneAPIResponse[*models.GitRepository, gitops.GitRepository](repo, func(err error) string {+ body, mapErr := handlerutil.MapOneAPIResponse[*GitRepository, gitops.GitRepository](repo, func(err error) string {return "Failed to map git repository"})if mapErr != nil {@@ -168,11 +169,11 @@ func (h *GitRepositoryHandler) CreateRepository(ctx context.Context, input *Creafunc (h *GitRepositoryHandler) GetRepository(ctx context.Context, input *GetGitRepositoryInput) (*GetGitRepositoryOutput, error) {repo, err := h.repoService.GetRepositoryByID(ctx, input.ID)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to retrieve git repository")}- body, mapErr := handlerutil.MapOneAPIResponse[*models.GitRepository, gitops.GitRepository](repo, func(err error) string {+ body, mapErr := handlerutil.MapOneAPIResponse[*GitRepository, gitops.GitRepository](repo, func(err error) string {return "Failed to map git repository"})if mapErr != nil {@@ -190,11 +191,11 @@ func (h *GitRepositoryHandler) UpdateRepository(ctx context.Context, input *Updarepo, err := h.repoService.UpdateRepository(ctx, input.ID, input.Body, actor)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to update git repository")}- body, mapErr := handlerutil.MapOneAPIResponse[*models.GitRepository, gitops.GitRepository](repo, func(err error) string {+ body, mapErr := handlerutil.MapOneAPIResponse[*GitRepository, gitops.GitRepository](repo, func(err error) string {return "Failed to map git repository"})if mapErr != nil {@@ -211,7 +212,7 @@ func (h *GitRepositoryHandler) DeleteRepository(ctx context.Context, input *Deleactor := handlerutil.CurrentActor(ctx)if err := h.repoService.DeleteRepository(ctx, input.ID, actor); err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), "Failed to delete git repository")}@@ -282,7 +283,7 @@ func (h *GitRepositoryHandler) BrowseFiles(ctx context.Context, input *BrowseFil// SyncRepositories syncs git repositories from a manager to this agent instance.func (h *GitRepositoryHandler) SyncRepositories(ctx context.Context, input *SyncGitRepositoriesInput) (*SyncGitRepositoriesOutput, error) {if err := h.repoService.SyncRepositories(ctx, input.Body.Repositories); err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync git repositories").Error())}diff --git a/backend/internal/models/git_repository.go b/backend/internal/gitrepo/model.gosimilarity index 95%rename from backend/internal/models/git_repository.gorename to backend/internal/gitrepo/model.goindex 94f48ad74..3884f3579 100644--- a/backend/internal/models/git_repository.go+++ b/backend/internal/gitrepo/model.go@@ -1,7 +1,9 @@-package models+package gitrepo++import "github.com/getarcaneapp/arcane/backend/v2/internal/database"type GitRepository struct {- BaseModel+ database.BaseModelName string `json:"name" sortable:"true" search:"git,repository,repo,source,version,control,github,gitlab,bitbucket"`URL string `json:"url" sortable:"true" search:"url,git,clone,remote,https,ssh"`diff --git a/backend/internal/gitrepo/service.go b/backend/internal/gitrepo/service.goindex 777aeb3df..9cd6482f4 100644--- a/backend/internal/gitrepo/service.go+++ b/backend/internal/gitrepo/service.go@@ -1,6 +1,8 @@package gitrepoimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""strings"@@ -9,7 +11,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"git "github.com/getarcaneapp/arcane/backend/v2/pkg/gitutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"@@ -41,15 +42,15 @@ func NewGitRepositoryService(db *database.DB, workDir string, eventService *even}func (s *GitRepositoryService) GetRepositoriesPaginated(ctx context.Context, params pagination.QueryParams) ([]gitops.GitRepository, pagination.Response, error) {- var repositories []models.GitRepository- q := s.db.WithContext(ctx).Model(&models.GitRepository{})+ var repositories []GitRepository+ q := s.db.WithContext(ctx).Model(&GitRepository{})q = pagination.ApplyLikeSearch(q, params.Search, "name LIKE ? OR url LIKE ? OR COALESCE(description, '') LIKE ?")q = pagination.ApplyBooleanFilter(q, "enabled", params.Filters["enabled"])q = pagination.ApplyFilter(q, "auth_type", params.Filters["authType"])- out, paginationResp, err := pagination.PaginateSortAndMapDB[models.GitRepository, gitops.GitRepository](params, q, &repositories)+ out, paginationResp, err := pagination.PaginateSortAndMapDB[GitRepository, gitops.GitRepository](params, q, &repositories)if err != nil {return nil, pagination.Response{}, errors.WrapIf(err, "failed to list git repositories")}@@ -57,8 +58,8 @@ func (s *GitRepositoryService) GetRepositoriesPaginated(ctx context.Context, parreturn out, paginationResp, nil}-func (s *GitRepositoryService) GetRepositoryByID(ctx context.Context, id string) (*models.GitRepository, error) {- var repository models.GitRepository+func (s *GitRepositoryService) GetRepositoryByID(ctx context.Context, id string) (*GitRepository, error) {+ var repository GitRepositoryif err := s.db.WithContext(ctx).Where("id = ?", id).First(&repository).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("repository not found")@@ -68,8 +69,8 @@ func (s *GitRepositoryService) GetRepositoryByID(ctx context.Context, id string)return &repository, nil}-func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name string) (*models.GitRepository, error) {- var repository models.GitRepository+func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name string) (*GitRepository, error) {+ var repository GitRepositoryif err := s.db.WithContext(ctx).Where("name = ?", name).First(&repository).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, errors.New("repository not found")@@ -79,7 +80,7 @@ func (s *GitRepositoryService) GetRepositoryByName(ctx context.Context, name strreturn &repository, nil}-func (s *GitRepositoryService) FindEnabledRepositoryByURL(ctx context.Context, rawURL string) (*models.GitRepository, error) {+func (s *GitRepositoryService) FindEnabledRepositoryByURL(ctx context.Context, rawURL string) (*GitRepository, error) {if s == nil || s.db == nil {return nil, nil}@@ -95,7 +96,7 @@ func (s *GitRepositoryService) FindEnabledRepositoryByURL(ctx context.Context, r}likePrefix = strings.TrimSuffix(likePrefix, "/")- var repositories []models.GitRepository+ var repositories []GitRepositoryquery := s.db.WithContext(ctx).Where("enabled = ?", true)if likePrefix != "" {query = query.Where("url = ? OR url = ? OR url LIKE ? OR url LIKE ?", rawURL, normalizedURL, likePrefix+"%", likePrefix+"/%")@@ -113,8 +114,8 @@ func (s *GitRepositoryService) FindEnabledRepositoryByURL(ctx context.Context, rreturn nil, nil}-func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.CreateGitRepositoryRequest, actor models.User) (*models.GitRepository, error) {- repository := models.GitRepository{+func (s *GitRepositoryService) CreateRepository(ctx context.Context, req CreateGitRepositoryRequest, actor common.User) (*GitRepository, error) {+ repository := GitRepository{Name: req.Name,URL: req.URL,AuthType: req.AuthType,@@ -156,8 +157,8 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.// Log event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitRepositoryCreate,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeGitRepositoryCreate,+ Severity: event.EventSeveritySuccess,Title: "Git repository created",Description: fmt.Sprintf("Created git repository '%s' (%s)", repository.Name, repository.URL),ResourceType: new("git_repository"),@@ -170,7 +171,7 @@ func (s *GitRepositoryService) CreateRepository(ctx context.Context, req models.return &repository, nil}-func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string, req models.UpdateGitRepositoryRequest, actor models.User) (*models.GitRepository, error) {+func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string, req UpdateGitRepositoryRequest, actor common.User) (*GitRepository, error) {repository, err := s.GetRepositoryByID(ctx, id)if err != nil {return nil, err@@ -248,8 +249,8 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,// Log event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitRepositoryUpdate,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeGitRepositoryUpdate,+ Severity: event.EventSeveritySuccess,Title: "Git repository updated",Description: fmt.Sprintf("Updated git repository '%s'", repository.Name),ResourceType: new("git_repository"),@@ -263,10 +264,10 @@ func (s *GitRepositoryService) UpdateRepository(ctx context.Context, id string,return s.GetRepositoryByID(ctx, id)}-func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string, actor models.User) error {+func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string, actor common.User) error {// Check if repository is used by any syncsvar count int64- if err := s.db.WithContext(ctx).Model(&models.GitOpsSync{}).Where("repository_id = ?", id).Count(&count).Error; err != nil {+ if err := s.db.WithContext(ctx).Table("gitops_syncs").Where("repository_id = ?", id).Count(&count).Error; err != nil {return errors.WrapIf(err, "failed to check repository usage")}@@ -280,14 +281,14 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,return err}- if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.GitRepository{}).Error; err != nil {+ if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&GitRepository{}).Error; err != nil {return errors.WrapIf(err, "failed to delete repository")}// Log event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitRepositoryDelete,- Severity: models.EventSeverityInfo,+ Type: event.EventTypeGitRepositoryDelete,+ Severity: event.EventSeverityInfo,Title: "Git repository deleted",Description: fmt.Sprintf("Deleted git repository '%s'", repository.Name),ResourceType: new("git_repository"),@@ -300,7 +301,7 @@ func (s *GitRepositoryService) DeleteRepository(ctx context.Context, id string,return nil}-func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, branch string, actor models.User) error {+func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, branch string, actor common.User) error {settings := s.settingsService.GetSettingsConfig()ctx, cancel := context.WithTimeout(ctx, timeouts.GetDuration(settings.GitOperationTimeout.AsInt(), timeouts.DefaultGitOperation))defer cancel()@@ -319,8 +320,8 @@ func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, brif err != nil {// Log error event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitRepositoryError,- Severity: models.EventSeverityError,+ Type: event.EventTypeGitRepositoryError,+ Severity: event.EventSeverityError,Title: "Git repository connection test failed",Description: fmt.Sprintf("Failed to connect to repository '%s': %s", repository.Name, err.Error()),ResourceType: new("git_repository"),@@ -334,8 +335,8 @@ func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, br// Log success event_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeGitRepositoryTest,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeGitRepositoryTest,+ Severity: event.EventSeveritySuccess,Title: "Git repository connection successful",Description: fmt.Sprintf("Successfully connected to repository '%s'", repository.Name),ResourceType: new("git_repository"),@@ -348,7 +349,7 @@ func (s *GitRepositoryService) TestConnection(ctx context.Context, id string, brreturn nil}-func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *models.GitRepository) (git.AuthConfig, error) {+func (s *GitRepositoryService) GetAuthConfig(ctx context.Context, repository *GitRepository) (git.AuthConfig, error) {authConfig := git.AuthConfig{AuthType: repository.AuthType,Username: repository.Username,@@ -467,20 +468,20 @@ func (s *GitRepositoryService) SyncRepositories(ctx context.Context, syncItems [return s.deleteUnsynced(ctx, existingMap, syncedIDs)}-func (s *GitRepositoryService) getExistingRepositoriesMap(ctx context.Context) (map[string]*models.GitRepository, error) {- var existing []models.GitRepository+func (s *GitRepositoryService) getExistingRepositoriesMap(ctx context.Context) (map[string]*GitRepository, error) {+ var existing []GitRepositoryif err := s.db.WithContext(ctx).Find(&existing).Error; err != nil {return nil, errors.WrapIf(err, "failed to get existing repositories")}- existingMap := make(map[string]*models.GitRepository)+ existingMap := make(map[string]*GitRepository)for i := range existing {existingMap[existing[i].ID] = &existing[i]}return existingMap, nil}-func (s *GitRepositoryService) processSyncItem(ctx context.Context, item gitops.RepositorySync, existingMap map[string]*models.GitRepository) error {+func (s *GitRepositoryService) processSyncItem(ctx context.Context, item gitops.RepositorySync, existingMap map[string]*GitRepository) error {existing, exists := existingMap[item.ID]if exists {return s.updateExistingRepository(ctx, item, existing)@@ -488,7 +489,7 @@ func (s *GitRepositoryService) processSyncItem(ctx context.Context, item gitops.return s.createNewRepository(ctx, item)}-func (s *GitRepositoryService) updateExistingRepository(ctx context.Context, item gitops.RepositorySync, existing *models.GitRepository) error {+func (s *GitRepositoryService) updateExistingRepository(ctx context.Context, item gitops.RepositorySync, existing *GitRepository) error {needsUpdate := s.checkRepositoryNeedsUpdate(item, existing)if needsUpdate {@@ -501,7 +502,7 @@ func (s *GitRepositoryService) updateExistingRepository(ctx context.Context, itereturn nil}-func (s *GitRepositoryService) checkRepositoryNeedsUpdate(item gitops.RepositorySync, existing *models.GitRepository) bool {+func (s *GitRepositoryService) checkRepositoryNeedsUpdate(item gitops.RepositorySync, existing *GitRepository) bool {needsUpdate := utils.ApplyChanged(&existing.Name, mo.Some(item.Name))needsUpdate = utils.ApplyChanged(&existing.URL, mo.Some(item.URL)) || needsUpdateneedsUpdate = utils.ApplyChanged(&existing.AuthType, mo.Some(item.AuthType)) || needsUpdate@@ -558,7 +559,7 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitsshHostKeyVerification = "accept_new"}- repo := models.GitRepository{+ repo := GitRepository{Name: item.Name,URL: item.URL,AuthType: item.AuthType,@@ -578,10 +579,10 @@ func (s *GitRepositoryService) createNewRepository(ctx context.Context, item gitreturn nil}-func (s *GitRepositoryService) deleteUnsynced(ctx context.Context, existingMap map[string]*models.GitRepository, syncedIDs map[string]bool) error {+func (s *GitRepositoryService) deleteUnsynced(ctx context.Context, existingMap map[string]*GitRepository, syncedIDs map[string]bool) error {for id := range existingMap {if !syncedIDs[id] {- if err := s.db.WithContext(ctx).Delete(&models.GitRepository{}, "id = ?", id).Error; err != nil {+ if err := s.db.WithContext(ctx).Delete(&GitRepository{}, "id = ?", id).Error; err != nil {return errors.WrapIff(err, "failed to delete repository %s", id)}}diff --git a/backend/internal/gitrepo/service_test.go b/backend/internal/gitrepo/service_test.goindex 72106e1ff..d72196706 100644--- a/backend/internal/gitrepo/service_test.go+++ b/backend/internal/gitrepo/service_test.go@@ -19,7 +19,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""go.getarcane.app/sys/crypto")@@ -31,11 +30,13 @@ func setupGitRepositoryServiceTestInternal(t *testing.T) (*GitRepositoryService,db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.GitRepository{},- &models.GitOpsSync{},- &models.Event{},- &models.SettingVariable{},+ &GitRepository{},+ &event.Event{},+ &settings.SettingVariable{},))+ // DeleteRepository only counts gitops_syncs rows; the model lives in the+ // project domain, which this package cannot import from an in-package test.+ require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS gitops_syncs (id text PRIMARY KEY, repository_id text)").Error)sqlDB, err := db.DB()require.NoError(t, err)@@ -75,11 +76,11 @@ func newSettingsServiceForTestInternal(t testing.TB, ctx context.Context, db *dareturn settings.NewSettingsService(ctx, db, executor, effects)}-func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepositoryService, req models.CreateGitRepositoryRequest) *models.GitRepository {+func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepositoryService, req CreateGitRepositoryRequest) *GitRepository {t.Helper()- repo, err := svc.CreateRepository(context.Background(), req, models.User{- BaseModel: models.BaseModel{ID: "admin-1"},+ repo, err := svc.CreateRepository(context.Background(), req, common.User{+ BaseModel: database.BaseModel{ID: "admin-1"},Username: "admin",})require.NoError(t, err)@@ -88,7 +89,7 @@ func createGitRepositoryServiceTestRepoInternal(t *testing.T, svc *GitRepositoryfunc TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWouldBeReused(t *testing.T) {svc, _ := setupGitRepositoryServiceTestInternal(t)- repo := createGitRepositoryServiceTestRepoInternal(t, svc, models.CreateGitRepositoryRequest{+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{Name: "prod-repo",URL: "https://github.com/acme/private.git",AuthType: "http",@@ -96,9 +97,9 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWoToken: "ghp_old_token",})- _, err := svc.UpdateRepository(context.Background(), repo.ID, models.UpdateGitRepositoryRequest{+ _, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{URL: new("https://attacker.tld/repo.git"),- }, models.User{})+ }, common.User{})require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)@@ -113,16 +114,16 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenWofunc TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyWouldBeReused(t *testing.T) {svc, _ := setupGitRepositoryServiceTestInternal(t)- repo := createGitRepositoryServiceTestRepoInternal(t, svc, models.CreateGitRepositoryRequest{+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{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, models.UpdateGitRepositoryRequest{+ _, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{URL: new("[email protected]:acme/private.git"),- }, models.User{})+ }, common.User{})require.Error(t, err)require.ErrorIs(t, err, common.ErrValidation)@@ -137,7 +138,7 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredSSHKeyWfunc TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAndSSHKeyWouldBeReused(t *testing.T) {svc, _ := setupGitRepositoryServiceTestInternal(t)- repo := createGitRepositoryServiceTestRepoInternal(t, svc, models.CreateGitRepositoryRequest{+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{Name: "hybrid-repo",URL: "https://github.com/acme/private.git",AuthType: "http",@@ -146,21 +147,21 @@ func TestGitRepositoryService_UpdateRepository_RejectsURLChangeWhenStoredTokenAnSSHKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nkey-material\n-----END OPENSSH PRIVATE KEY-----",})- _, err := svc.UpdateRepository(context.Background(), repo.ID, models.UpdateGitRepositoryRequest{+ _, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{URL: new("https://attacker.tld/repo.git"),- }, models.User{})+ }, common.User{})require.Error(t, err)- var apiErr *models.APIError+ var apiErr *common.APIErrorrequire.ErrorAs(t, err, &apiErr)- assert.Equal(t, models.APIErrorCodeValidationError, apiErr.Code)+ assert.Equal(t, common.APIErrorCodeValidationError, apiErr.Code)assert.Contains(t, apiErr.Message, "repository URL")assert.Equal(t, map[string]any{"fields": []string{"sshKey", "token"}}, apiErr.Details)}func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResupplied(t *testing.T) {svc, _ := setupGitRepositoryServiceTestInternal(t)- repo := createGitRepositoryServiceTestRepoInternal(t, svc, models.CreateGitRepositoryRequest{+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{Name: "prod-repo",URL: "https://github.com/acme/private.git",AuthType: "http",@@ -168,10 +169,10 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResupplToken: "ghp_old_token",})- updated, err := svc.UpdateRepository(context.Background(), repo.ID, models.UpdateGitRepositoryRequest{+ updated, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{URL: new("https://github.com/acme/private-rotated.git"),Token: new("ghp_new_token"),- }, models.User{})+ }, common.User{})require.NoError(t, err)assert.Equal(t, "https://github.com/acme/private-rotated.git", updated.URL)@@ -182,7 +183,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsResupplfunc TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsCleared(t *testing.T) {svc, _ := setupGitRepositoryServiceTestInternal(t)- repo := createGitRepositoryServiceTestRepoInternal(t, svc, models.CreateGitRepositoryRequest{+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{Name: "prod-repo",URL: "https://github.com/acme/private.git",AuthType: "http",@@ -190,10 +191,10 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsClearedToken: "ghp_old_token",})- updated, err := svc.UpdateRepository(context.Background(), repo.ID, models.UpdateGitRepositoryRequest{+ updated, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{URL: new("https://github.com/acme/public.git"),Token: new(""),- }, models.User{})+ }, common.User{})require.NoError(t, err)assert.Equal(t, "https://github.com/acme/public.git", updated.URL)@@ -202,7 +203,7 @@ func TestGitRepositoryService_UpdateRepository_AllowsURLChangeWhenTokenIsClearedfunc TestGitRepositoryService_UpdateRepository_AllowsSameURLWithoutCredentialResupply(t *testing.T) {svc, _ := setupGitRepositoryServiceTestInternal(t)- repo := createGitRepositoryServiceTestRepoInternal(t, svc, models.CreateGitRepositoryRequest{+ repo := createGitRepositoryServiceTestRepoInternal(t, svc, CreateGitRepositoryRequest{Name: "prod-repo",URL: "https://github.com/acme/private.git",AuthType: "http",@@ -210,10 +211,10 @@ func TestGitRepositoryService_UpdateRepository_AllowsSameURLWithoutCredentialResToken: "ghp_old_token",})- updated, err := svc.UpdateRepository(context.Background(), repo.ID, models.UpdateGitRepositoryRequest{+ updated, err := svc.UpdateRepository(context.Background(), repo.ID, UpdateGitRepositoryRequest{URL: new("https://github.com/acme/private.git"),Username: new("deploy-bot"),- }, models.User{})+ }, common.User{})require.NoError(t, err)assert.Equal(t, "deploy-bot", updated.Username)diff --git a/backend/internal/image/handler.go b/backend/internal/image/handler.goindex f4ac7d914..727088d2d 100644--- a/backend/internal/image/handler.go+++ b/backend/internal/image/handler.go@@ -1,6 +1,8 @@package imageimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""fmt""io"@@ -8,6 +10,8 @@ import ("net/url""strings"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors""github.com/containerd/platforms""github.com/danielgtaylor/huma/v2"@@ -16,7 +20,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -599,14 +602,14 @@ func (h *ImageHandler) PullImage(ctx context.Context, input *PullImageInput) (*hruntimeCtx,h.activityService,input.EnvironmentID,- models.ActivityTypeImagePull,+ activitytypes.TypeImagePull,"image","",fullImageName,user,"Pulling image","Image pull started",- models.JSON{"imageName": fullImageName},+ database.JSON{"imageName": fullImageName},true,)activitylib.WriteStartedLine(rawWriter, activityID)@@ -657,14 +660,14 @@ func (h *ImageHandler) BuildImage(ctx context.Context, input *BuildImageInput) (runtimeCtx,h.activityService,input.EnvironmentID,- models.ActivityTypeImageBuild,+ activitytypes.TypeImageBuild,"image","",resourceName,user,"Building image","Image build started",- models.JSON{"contextDir": input.Body.ContextDir, "tags": input.Body.Tags},+ database.JSON{"contextDir": input.Body.ContextDir, "tags": input.Body.Tags},true,)activitylib.WriteStartedLine(rawWriter, activityID)diff --git a/backend/internal/image/image.go b/backend/internal/image/image.goindex d9926efa1..3aad5902e 100644--- a/backend/internal/image/image.go+++ b/backend/internal/image/image.go@@ -1,6 +1,8 @@package imageimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""io""log/slog"@@ -16,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth"@@ -117,10 +118,10 @@ func (s *ImageService) GetImageDetail(ctx context.Context, id string) (*imagetypreturn &out, nil}-func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, user models.User) error {+func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, user common.User) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", id, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", id, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})return errors.WrapIf(err, "failed to connect to Docker")}@@ -139,13 +140,13 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, u_, err = dockerClient.ImageRemove(ctx, id, options)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", id, imageName, user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", id, imageName, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})return errors.WrapIf(err, "failed to remove image")}if s.db != nil {if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- return tx.Delete(&models.ImageUpdateRecord{}, "id = ?", id).Error+ return tx.Delete(&imageupdate.ImageUpdateRecord{}, "id = ?", id).Error}); err != nil {slog.WarnContext(ctx, "failed to delete image update record", "id", id, "error", err)}@@ -164,22 +165,22 @@ func (s *ImageService) RemoveImage(ctx context.Context, id string, force bool, u}}- metadata := models.JSON{+ metadata := database.JSON{"action": "delete","imageId": id,"force": force,}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageDelete, id, imageName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageDelete, id, imageName, user.ID, user.Username, "0", metadata); logErr != nil {slog.Warn("could not log image deletion action", "err", logErr, "image", imageName, "image_id", id)}return nil}-func (s *ImageService) PullImage(ctx context.Context, imageName string, progressWriter io.Writer, user models.User, externalCreds []containerregistry.Credential) error {+func (s *ImageService) PullImage(ctx context.Context, imageName string, progressWriter io.Writer, user common.User, externalCreds []containerregistry.Credential) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, models.JSON{"action": "pull"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, database.JSON{"action": "pull"})return errors.WrapIf(err, "failed to connect to Docker")}@@ -203,7 +204,7 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progress}if err != nil {slog.ErrorContext(ctx, "Docker ImagePull failed", "image", imageName, "hasAuth", pullOptions.RegistryAuth != "", "initialHasAuth", initialHasAuth, "retriedWithoutAuth", retriedWithoutAuth, "error", err.Error())- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, models.JSON{"action": "pull"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", err, database.JSON{"action": "pull"})return errors.WrapIff(err, "failed to initiate image pull for %s", imageName)}defer func() { _ = reader.Close() }()@@ -214,20 +215,20 @@ func (s *ImageService) PullImage(ctx context.Context, imageName string, progressif streamErr != nil {if errors.Is(streamErr, context.Canceled) || strings.Contains(streamErr.Error(), "context canceled") {slog.Debug("image pull stream canceled", "image", imageName, "err", streamErr)- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "pull", "step": "canceled"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "pull", "step": "canceled"})return errors.WrapIff(streamErr, "image pull stream canceled for %s", imageName)}- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "pull", "step": "read_stream"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", imageName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "pull", "step": "read_stream"})return errors.WrapIff(streamErr, "error reading image pull stream for %s", imageName)}slog.Debug("image pull stream completed", "image", imageName)- metadata := models.JSON{+ metadata := database.JSON{"action": "pull","imageName": imageName,}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImagePull, "", imageName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImagePull, "", imageName, user.ID, user.Username, "0", metadata); logErr != nil {slog.Warn("could not log image pull action", "err", logErr, "image", imageName)}if s.registryService != nil {@@ -248,7 +249,7 @@ func (s *ImageService) ReconcilePulledImageUpdate(ctx context.Context, imageName}// TagImage adds a repository tag to an existing image.-func (s *ImageService) TagImage(ctx context.Context, source string, req imagetypes.TagRequest, user models.User) error {+func (s *ImageService) TagImage(ctx context.Context, source string, req imagetypes.TagRequest, user common.User) error {source = strings.TrimSpace(source)repository := strings.TrimSpace(req.Repository)tag := strings.TrimSpace(req.Tag)@@ -266,24 +267,24 @@ func (s *ImageService) TagImage(ctx context.Context, source string, req imagetypdockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, models.JSON{"action": "tag", "target": target})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, database.JSON{"action": "tag", "target": target})return errors.WrapIf(err, "failed to connect to Docker")}_, err = dockerClient.ImageTag(ctx, client.ImageTagOptions{Source: source, Target: target})if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, models.JSON{"action": "tag", "target": target})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", source, user.ID, user.Username, "0", err, database.JSON{"action": "tag", "target": target})return errors.WrapIf(err, "failed to tag image")}- metadata := models.JSON{+ metadata := database.JSON{"action": "tag","imageName": source,"repository": repository,"tag": tag,"target": target,}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageTag, "", source, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageTag, "", source, user.ID, user.Username, "0", metadata); logErr != nil {slog.Warn("could not log image tag action", "err", logErr, "image", source, "target", target)}@@ -369,13 +370,13 @@ func (s *ImageService) ExportImage(ctx context.Context, imageName string) (io.Rereturn reader, nil}-func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Reader, fileName string, user models.User, maxSizeBytes int64) (*imagetypes.LoadResult, error) {+func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Reader, fileName string, user common.User, maxSizeBytes int64) (*imagetypes.LoadResult, error) {// Wrap reader with size limit enforcementlimitedReader := io.LimitReader(reader, maxSizeBytes+1)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, models.JSON{"action": "load"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, database.JSON{"action": "load"})return nil, errors.WrapIf(err, "failed to connect to Docker")}@@ -386,7 +387,7 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Readerif err.Error() == "unexpected EOF" || strings.Contains(err.Error(), "unexpected EOF") {return nil, errors.Errorf("file size exceeds maximum allowed size of %d MB", maxSizeBytes/(1024*1024))}- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, models.JSON{"action": "load", "file": fileName})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", err, database.JSON{"action": "load", "file": fileName})return nil, errors.WrapIf(err, "failed to load image from tar")}defer func() { _ = loadResp.Close() }()@@ -395,17 +396,17 @@ func (s *ImageService) LoadImageFromReader(ctx context.Context, reader io.Readervar responseBuilder strings.BuilderstreamErr := dockerutils.RenderJSONMessageStream(loadResp, &responseBuilder)if streamErr != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", streamErr, models.JSON{"action": "load", "file": fileName, "step": "read_response"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeImageError, "image", "", fileName, user.ID, user.Username, "0", streamErr, database.JSON{"action": "load", "file": fileName, "step": "read_response"})return nil, errors.WrapIf(streamErr, "failed to read load response")}result.Stream = responseBuilder.String()- metadata := models.JSON{+ metadata := database.JSON{"action": "load","fileName": fileName,}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageLoad, "", fileName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageLoad, "", fileName, user.ID, user.Username, "0", metadata); logErr != nil {slog.Warn("could not log image load action", "err", logErr, "file", fileName)}@@ -532,14 +533,14 @@ func (s *ImageService) PruneImages(ctx context.Context, options systemtypes.Pruns.cleanupVulnerabilityRecordsAfterPruneInternal(ctx, idsToDelete)s.cleanupOrphanedImageUpdatesAfterPruneInternal(ctx)- metadata := models.JSON{+ metadata := database.JSON{"action": "prune","mode": options.Mode,"until": options.Until,"imagesDeleted": len(pruneReport.ImagesDeleted),"spaceReclaimed": pruneReport.SpaceReclaimed,}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageDelete, "", "bulk_prune", models.SystemUser.ID, models.SystemUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageDelete, "", "bulk_prune", common.SystemUser.ID, common.SystemUser.Username, "0", metadata); logErr != nil {slog.Warn("could not log image prune action", "err", logErr)}@@ -570,7 +571,7 @@ func (s *ImageService) cleanupImageUpdateRecordsAfterPruneInternal(ctx context.C}if err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- return tx.Where("id IN ?", idsToDelete).Delete(&models.ImageUpdateRecord{}).Error+ return tx.Where("id IN ?", idsToDelete).Delete(&imageupdate.ImageUpdateRecord{}).Error}); err != nil {slog.WarnContext(ctx, "failed to clean up image update records after prune", "error", err)}@@ -603,7 +604,7 @@ func (s *ImageService) GetUpdateInfoByImageIDs(ctx context.Context, imageIDs []sreturn make(map[string]*imagetypes.UpdateInfo), nil}- var updateRecords []models.ImageUpdateRecord+ var updateRecords []imageupdate.ImageUpdateRecordif err := s.db.WithContext(ctx).Where("id IN ?", imageIDs).Find(&updateRecords).Error; err != nil {return nil, errors.WrapIf(err, "failed to fetch update records")}@@ -658,7 +659,7 @@ func (s *ImageService) GetUpdateInfoByImageRefs(ctx context.Context, imageRefs [return result, nil}- var updateRecords []models.ImageUpdateRecord+ var updateRecords []imageupdate.ImageUpdateRecordif err := s.db.WithContext(ctx).Where("tag IN ? AND repository IN ?", tags, repositoryCandidates).Order("check_time DESC").@@ -679,7 +680,7 @@ func (s *ImageService) ListImagesPaginated(ctx context.Context, params paginatiovar (dockerImages []image.Summarycontainers []container.Summary- updateRecords []models.ImageUpdateRecord+ updateRecords []imageupdate.ImageUpdateRecord)g, groupCtx := errgroup.WithContext(ctx)@@ -771,9 +772,9 @@ func buildImageRefUpdateLookupsInternal(imageRefs []string) []imageRefUpdateLookfunc selectLatestMatchingImageUpdateRecordInternal(lookup imageRefUpdateLookup,- updateRecords []models.ImageUpdateRecord,-) *models.ImageUpdateRecord {- var latest *models.ImageUpdateRecord+ updateRecords []imageupdate.ImageUpdateRecord,+) *imageupdate.ImageUpdateRecord {+ var latest *imageupdate.ImageUpdateRecordfor i := range updateRecords {record := &updateRecords[i]@@ -814,8 +815,11 @@ func (s *ImageService) loadProjectIDByNameCachedInternal(ctx context.Context) ma}stale, staleFound := s.projectIDCache.Peek(struct{}{})byName, found, err := s.projectIDCache.GetWithLoaders(struct{}{}, func(_ []struct{}) (map[struct{}]map[string]string, error) {- var projects []models.Project- if err := s.db.WithContext(ctx).Select("id", "name").Find(&projects).Error; err != nil {+ var projects []struct {+ ID string+ Name string+ }+ if err := s.db.WithContext(ctx).Table("projects").Select("id", "name").Find(&projects).Error; err != nil {return nil, err}@@ -924,8 +928,8 @@ func BuildVolumeUsageMap(containers []container.Summary, projectIDByName map[strreturn usageMap}-func buildUpdateMap(records []models.ImageUpdateRecord) map[string]*models.ImageUpdateRecord {- updateMap := make(map[string]*models.ImageUpdateRecord, len(records))+func buildUpdateMap(records []imageupdate.ImageUpdateRecord) map[string]*imageupdate.ImageUpdateRecord {+ updateMap := make(map[string]*imageupdate.ImageUpdateRecord, len(records))for i := range records {updateMap[records[i].ID] = &records[i]}@@ -1008,7 +1012,7 @@ func determineRepoAndTag(di image.Summary) (repo, tag string) {return "<none>", "<none>"}-func buildUpdateInfo(updateRecord *models.ImageUpdateRecord) *imagetypes.UpdateInfo {+func buildUpdateInfo(updateRecord *imageupdate.ImageUpdateRecord) *imagetypes.UpdateInfo {return &imagetypes.UpdateInfo{HasUpdate: updateRecord.HasUpdate,UpdateType: updateRecord.UpdateType,@@ -1026,7 +1030,7 @@ func buildUpdateInfo(updateRecord *models.ImageUpdateRecord) *imagetypes.UpdateI}}-func MapDockerImagesToDTOs(dockerImages []image.Summary, usageMap map[string][]imagetypes.UsedBy, updateMap map[string]*models.ImageUpdateRecord, vulnerabilityMap map[string]*vulnerabilitytypes.ScanSummary) []imagetypes.Summary {+func MapDockerImagesToDTOs(dockerImages []image.Summary, usageMap map[string][]imagetypes.UsedBy, updateMap map[string]*imageupdate.ImageUpdateRecord, vulnerabilityMap map[string]*vulnerabilitytypes.ScanSummary) []imagetypes.Summary {items := make([]imagetypes.Summary, 0, len(dockerImages))for _, di := range dockerImages {repo, tag := determineRepoAndTag(di)diff --git a/backend/internal/image/service_test.go b/backend/internal/image/service_test.goindex f97888188..c9ff17f06 100644--- a/backend/internal/image/service_test.go+++ b/backend/internal/image/service_test.go@@ -1,6 +1,12 @@package imageimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""encoding/json""errors"@@ -25,7 +31,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/types/v2/containerregistry"imagetypes "github.com/getarcaneapp/arcane/types/v2/image""github.com/getarcaneapp/arcane/types/v2/vulnerability"@@ -47,10 +52,10 @@ func setupImageProjectTestDBInternal(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.Project{},- &models.SettingVariable{},- &models.ImageUpdateRecord{},- &models.Event{},+ &testProjectRow{},+ &settings.SettingVariable{},+ &imageupdate.ImageUpdateRecord{},+ &event.Event{},))return &database.DB{DB: db}}@@ -90,12 +95,12 @@ func TestApplyVulnerabilitySummariesToItemsInternal(t *testing.T) {func TestImageService_GetUpdateInfoByImageRefs_MatchesCanonicalAndFamiliarRepos(t *testing.T) {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}))+ require.NoError(t, db.AutoMigrate(&imageupdate.ImageUpdateRecord{}))svc := &ImageService{db: &database.DB{DB: db}}now := time.Now().UTC()- records := []models.ImageUpdateRecord{+ records := []imageupdate.ImageUpdateRecord{{ID: "sha256:nginx-latest",Repository: "docker.io/library/nginx",@@ -140,7 +145,7 @@ func setupImageServiceAuthTest(t *testing.T) (*ImageService, *database.DB) {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ContainerRegistry{}, &models.KVEntry{}, &models.Project{}))+ require.NoError(t, db.AutoMigrate(®istry.ContainerRegistry{}, &kv.KVEntry{}, &testProjectRow{}))crypto.InitEncryption(&crypto.Config{Environment: string(config.AppEnvironmentTest),@@ -161,7 +166,7 @@ func createTestPullRegistry(t *testing.T, db *database.DB, url, username, tokenencryptedToken, err := crypto.Encrypt(token)require.NoError(t, err)- reg := &models.ContainerRegistry{+ reg := ®istry.ContainerRegistry{URL: url,Username: username,Token: encryptedToken,@@ -239,7 +244,7 @@ func TestImageServicePullImageRetriesAnonymouslyAfterAuthRejectedInternal(t *tesdockerService := &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}imageSvc := NewImageService(db, dockerService, nil, nil, nil, event.NewEventService(db, nil, nil))- err := imageSvc.PullImage(context.Background(), "registry.example.com/team/app:latest", io.Discard, models.SystemUser, []containerregistry.Credential{+ err := imageSvc.PullImage(context.Background(), "registry.example.com/team/app:latest", io.Discard, common.SystemUser, []containerregistry.Credential{{URL: "https://registry.example.com", Username: "external-user", Token: "external-token", Enabled: true},})require.NoError(t, err)@@ -264,7 +269,7 @@ func TestImageServiceTagImageCallsDockerAPIInternal(t *testing.T) {imageSvc := NewImageService(db, &docker.DockerClientService{Client: newTestDockerClientInternal(t, server)}, nil, nil, nil, event.NewEventService(db, nil, nil))- err := imageSvc.TagImage(context.Background(), "source:latest", imagetypes.TagRequest{Repository: "registry.example.com/team/app", Tag: "v2"}, models.SystemUser)+ err := imageSvc.TagImage(context.Background(), "source:latest", imagetypes.TagRequest{Repository: "registry.example.com/team/app", Tag: "v2"}, common.SystemUser)require.NoError(t, err)assert.Equal(t, "registry.example.com/team/app", gotRepo)assert.Equal(t, "v2", gotTag)@@ -449,3 +454,14 @@ func newImagePullServerWithObserverInternal(t *testing.T, inspectByRef map[strinreturn server}++// testProjectRow is a minimal stand-in for project.Project: the project+// package imports this one, so the in-package test cannot import it back.+type testProjectRow struct {+ database.BaseModel+ Name string+ Path string+ BuildImageRefsJSON *string `gorm:"column:build_image_refs_json"`+}++func (testProjectRow) TableName() string { return "projects" }diff --git a/backend/internal/imageupdate/image_update.go b/backend/internal/imageupdate/image_update.goindex 6f44443a8..7fb333eaf 100644--- a/backend/internal/imageupdate/image_update.go+++ b/backend/internal/imageupdate/image_update.go@@ -1,6 +1,10 @@package imageupdateimport (+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""log/slog"@@ -9,6 +13,8 @@ import ("sync""time"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"github.com/getarcaneapp/arcane/backend/v2/internal/registry""emperror.dev/emperror"@@ -20,7 +26,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/settings"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"@@ -117,8 +122,12 @@ func (s *ImageUpdateService) composeBuildImageRefsInternal(ctx context.Context)return buildRefs, nil}- var projectRows []models.Project+ var projectRows []struct {+ ID string+ BuildImageRefsJSON *string `gorm:"column:build_image_refs_json"`+ }if err := s.db.WithContext(ctx).+ Table("projects").Select("id", "build_image_refs_json").Where("build_image_refs_json IS NOT NULL AND build_image_refs_json <> ''").Find(&projectRows).Error; err != nil {@@ -150,13 +159,13 @@ func (s *ImageUpdateService) startImageUpdateActivityInternal(ctx context.Contex}activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{EnvironmentID: "0",- Type: models.ActivityTypeImageUpdateCheck,+ Type: activitytypes.TypeImageUpdateCheck,Queue: true,ResourceType: &resourceType,ResourceName: mo.EmptyableToOption(strings.TrimSpace(resourceName)).ToPointer(),Step: "Checking image updates",LatestMessage: "Image update check started",- Metadata: models.JSON{+ Metadata: database.JSON{"imageCount": count,},})@@ -167,12 +176,12 @@ func (s *ImageUpdateService) startImageUpdateActivityInternal(ctx context.Contexreturn activity.ID}-func (s *ImageUpdateService) appendImageUpdateActivityMessageInternal(ctx context.Context, activityID string, level models.ActivityMessageLevel, message string, progress int, step string) {+func (s *ImageUpdateService) appendImageUpdateActivityMessageInternal(ctx context.Context, activityID string, level activitytypes.MessageLevel, message string, progress int, step string) {if s.activityService == nil || activityID == "" || strings.TrimSpace(message) == "" {return}if level == "" {- level = models.ActivityMessageLevelInfo+ level = activitytypes.MessageLevelInfo}if _, err := s.activityService.AppendMessage(ctx, activityID, activity.AppendActivityMessageRequest{Level: level,@@ -188,13 +197,13 @@ func (s *ImageUpdateService) completeImageUpdateActivityInternal(ctx context.Conif s.activityService == nil || activityID == "" {return}- status := models.ActivityStatusSuccess+ status := activitytypes.StatusSuccessvar errMessage *stringif !success {- status = models.ActivityStatusFailed+ status = activitytypes.StatusFailederrMessage = mo.EmptyableToOption(strings.TrimSpace(message)).ToPointer()if activitylib.CancelledByContext(ctx) {- status = models.ActivityStatusCancelled+ status = activitytypes.StatusCancellederrMessage = nilmessage = "Image update check cancelled"}@@ -221,17 +230,17 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef striresult.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()s.recordDigestPinnedSkipInternal(ctx, activityID, imageRef, result, 100)if s.eventService != nil {- metadata := models.JSON{+ metadata := database.JSON{"action": "check_update","imageRef": imageRef,"hasUpdate": false,- "updateType": models.UpdateTypeDigest,+ "updateType": UpdateTypeDigest,"currentDigest": result.CurrentDigest,"latestDigest": result.LatestDigest,"responseTimeMs": result.ResponseTimeMs,"skippedReason": "digest_pinned",}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageScan, "", imageRef, models.SystemUser.ID, models.SystemUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageScan, "", imageRef, common.SystemUser.ID, common.SystemUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "Failed to log digest-pinned image update check event", "imageRef", imageRef, "error", logErr.Error())}}@@ -239,7 +248,7 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef strireturn result, nil}- s.appendImageUpdateActivityMessageInternal(ctx, activityID, models.ActivityMessageLevelInfo, "Checking "+imageRef, 20, "Checking remote digest")+ s.appendImageUpdateActivityMessageInternal(ctx, activityID, activitytypes.MessageLevelInfo, "Checking "+imageRef, 20, "Checking remote digest")parts := s.parseImageReference(imageRef)if parts == nil {@@ -269,13 +278,13 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef striResponseTimeMs: int(time.Since(startTime).Milliseconds()),ActivityID: mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer(),}- metadata := models.JSON{+ metadata := database.JSON{"action": "check_update","imageRef": imageRef,"error": err.Error(),"checkType": "digest",}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageScan, "", imageRef, models.SystemUser.ID, models.SystemUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageScan, "", imageRef, common.SystemUser.ID, common.SystemUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "Failed to log image update check error event", "imageRef", imageRef, "error", logErr.Error())}if saveErr := s.saveUpdateResultWithSnapshotInternal(ctx, imageRef, result, snapshot); saveErr != nil {@@ -287,10 +296,10 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef stridigestResult.ResponseTimeMs = int(time.Since(startTime).Milliseconds())digestResult.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()- if digestResult.UpdateType == models.UpdateTypeLocal {- s.appendImageUpdateActivityMessageInternal(ctx, activityID, models.ActivityMessageLevelInfo, imageRef+" — local build, registry check skipped", 100, "Skipping image update check")+ if digestResult.UpdateType == UpdateTypeLocal {+ s.appendImageUpdateActivityMessageInternal(ctx, activityID, activitytypes.MessageLevelInfo, imageRef+" — local build, registry check skipped", 100, "Skipping image update check")}- metadata := models.JSON{+ metadata := database.JSON{"action": "check_update","imageRef": imageRef,"hasUpdate": digestResult.HasUpdate,@@ -299,7 +308,7 @@ func (s *ImageUpdateService) CheckImageUpdate(ctx context.Context, imageRef stri"latestDigest": digestResult.LatestDigest,"responseTimeMs": digestResult.ResponseTimeMs,}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageScan, "", imageRef, models.SystemUser.ID, models.SystemUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageScan, "", imageRef, common.SystemUser.ID, common.SystemUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "Failed to log image update check event", "imageRef", imageRef, "error", logErr.Error())}if saveErr := s.saveUpdateResultWithSnapshotInternal(ctx, imageRef, digestResult, snapshot); saveErr != nil {@@ -328,7 +337,7 @@ func (s *ImageUpdateService) notifyImageUpdateInternal(ctx context.Context, imagreturn}- delivered, notifErr := s.notificationService.SendImageUpdateNotification(ctx, imageRef, digestResult, models.NotificationEventImageUpdate)+ delivered, notifErr := s.notificationService.SendImageUpdateNotification(ctx, imageRef, digestResult, notifications.NotificationEventImageUpdate)if notifErr != nil {slog.WarnContext(ctx, "Failed to send update notification", "imageRef", imageRef, "error", notifErr.Error())}@@ -376,7 +385,7 @@ func digestPinnedImageUpdateResultInternal(imageRef string) mo.Option[*imageupdareturn mo.Some(&imageupdate.Response{HasUpdate: false,- UpdateType: models.UpdateTypeDigest,+ UpdateType: UpdateTypeDigest,CurrentVersion: tag,LatestVersion: tag,CurrentDigest: pinnedDigest,@@ -431,7 +440,7 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.C// nothing local to compare, so report a distinct not-pulled state// rather than a failed check or an available update.return &imageupdate.Response{- UpdateType: models.UpdateTypeNotPulled,+ UpdateType: UpdateTypeNotPulled,LatestDigest: digestResult.Digest,CheckTime: time.Now(),ResponseTimeMs: int(elapsed.Milliseconds()),@@ -464,7 +473,7 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.Creturn &imageupdate.Response{HasUpdate: hasUpdate,- UpdateType: models.UpdateTypeDigest,+ UpdateType: UpdateTypeDigest,CurrentDigest: localDigest,LatestDigest: digestResult.Digest,CheckTime: time.Now(),@@ -479,7 +488,7 @@ func (s *ImageUpdateService) checkDigestUpdateWithSnapshotInternal(ctx context.Cfunc localBuildImageUpdateResultInternal(snapshot *localImageSnapshot, responseTimeMs int) *imageupdate.Response {return &imageupdate.Response{HasUpdate: false,- UpdateType: models.UpdateTypeLocal,+ UpdateType: UpdateTypeLocal,CurrentVersion: snapshot.Tag,CurrentDigest: snapshot.PrimaryDigest,CheckTime: time.Now(),@@ -493,7 +502,7 @@ func localBuildImageUpdateResultInternal(snapshot *localImageSnapshot, responseTfunc missingLocalBuildImageUpdateResultInternal(tag string, responseTimeMs int) *imageupdate.Response {return &imageupdate.Response{HasUpdate: false,- UpdateType: models.UpdateTypeLocal,+ UpdateType: UpdateTypeLocal,CurrentVersion: tag,CheckTime: time.Now(),ResponseTimeMs: responseTimeMs,@@ -849,12 +858,12 @@ func (s *ImageUpdateService) normalizeRepository(regHost, repo string) string {func (s *ImageUpdateService) CheckImageUpdateByID(ctx context.Context, imageID string) (*imageupdate.Response, error) {imageRef, err := s.getImageRefByIDInternal(ctx, imageID)if err != nil {- metadata := models.JSON{+ metadata := database.JSON{"action": "check_update_by_id","imageID": imageID,"error": err.Error(),}- if logErr := s.eventService.LogImageEvent(ctx, models.EventTypeImageScan, imageID, "", models.SystemUser.ID, models.SystemUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogImageEvent(ctx, event.EventTypeImageScan, imageID, "", common.SystemUser.ID, common.SystemUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "Failed to log image update check by ID error event", "imageID", imageID, "error", logErr.Error())}return nil, errors.WrapIf(err, "failed to get image reference")@@ -931,23 +940,23 @@ func countBatchResultOutcomesInternal(imageRefs []string, results map[string]*im// imageCheckResultMessageInternal derives an activity message level and text from// a per-image update check result: errors become ERROR, available updates become// SUCCESS, and up-to-date images stay INFO.-func imageCheckResultMessageInternal(imageRef string, res *imageupdate.Response) (models.ActivityMessageLevel, string) {+func imageCheckResultMessageInternal(imageRef string, res *imageupdate.Response) (activitytypes.MessageLevel, string) {if res == nil {- return models.ActivityMessageLevelError, imageRef + ": check failed"+ return activitytypes.MessageLevelError, imageRef + ": check failed"}if err := strings.TrimSpace(res.Error); err != "" {- return models.ActivityMessageLevelError, fmt.Sprintf("%s: %s", imageRef, err)+ return activitytypes.MessageLevelError, fmt.Sprintf("%s: %s", imageRef, err)}- if res.UpdateType == models.UpdateTypeLocal {- return models.ActivityMessageLevelInfo, imageRef + " — local build, registry check skipped"+ if res.UpdateType == UpdateTypeLocal {+ return activitytypes.MessageLevelInfo, imageRef + " — local build, registry check skipped"}- if res.UpdateType == models.UpdateTypeNotPulled {- return models.ActivityMessageLevelInfo, imageRef + " — not pulled locally, no local digest to compare"+ if res.UpdateType == UpdateTypeNotPulled {+ return activitytypes.MessageLevelInfo, imageRef + " — not pulled locally, no local digest to compare"}if res.HasUpdate {- return models.ActivityMessageLevelSuccess, imageRef + " — update available"+ return activitytypes.MessageLevelSuccess, imageRef + " — update available"}- return models.ActivityMessageLevelInfo, imageRef + " — up to date"+ return activitytypes.MessageLevelInfo, imageRef + " — up to date"}func extractRepoAndTagFromImage(dockerImage image.InspectResponse) (repo, tag string) {@@ -996,13 +1005,13 @@ func stringToPtr(s string) *string {return new(s)}-func buildImageUpdateRecord(imageID, repo, tag string, result *imageupdate.Response) *models.ImageUpdateRecord {+func buildImageUpdateRecord(imageID, repo, tag string, result *imageupdate.Response) *ImageUpdateRecord {currentVersion := result.CurrentVersionif currentVersion == "" {currentVersion = tag}- return &models.ImageUpdateRecord{+ return &ImageUpdateRecord{ID: imageID,Repository: repo,Tag: tag,@@ -1038,7 +1047,7 @@ func savePreparedUpdateResultWithTxInternal(tx *gorm.DB, imageID, repo, tag striupdateRecord := buildImageUpdateRecord(imageID, repo, tag, result)// Check if there's an existing record to compare state changes- var existingRecord models.ImageUpdateRecord+ var existingRecord ImageUpdateRecordhasExisting := tx.Where("id = ?", imageID).First(&existingRecord).Error == nil// A registry rate limit (429) is transient: keep the previous good result@@ -1134,7 +1143,7 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,checkTime := time.Now().UTC()result := &imageupdate.Response{HasUpdate: false,- UpdateType: models.UpdateTypeDigest,+ UpdateType: UpdateTypeDigest,CurrentVersion: snapshot.Tag,LatestVersion: snapshot.Tag,CurrentDigest: snapshot.PrimaryDigest,@@ -1151,7 +1160,7 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,// Only clear synthetic ref:: records, not real sha256 image ID records.// Clearing sha256 records would incorrectly mark containers that are still// running the old image as up-to-date (see: #2453).- if err := tx.Model(&models.ImageUpdateRecord{}).+ if err := tx.Model(&ImageUpdateRecord{}).Where("id LIKE 'ref::%' AND tag = ? AND repository IN ?", tag, repositories).Update("has_update", false).Error; err != nil {return errors.WrapIf(err, "clear stale image updates")@@ -1167,13 +1176,13 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,})}-func (s *ImageUpdateService) StoredUpdateByImageID(ctx context.Context, imageID string) (*models.ImageUpdateRecord, bool, error) {+func (s *ImageUpdateService) StoredUpdateByImageID(ctx context.Context, imageID string) (*ImageUpdateRecord, bool, error) {imageID = strings.TrimSpace(imageID)if s == nil || s.db == nil || imageID == "" {return nil, false, nil}- var record models.ImageUpdateRecord+ var record ImageUpdateRecordif err := s.db.WithContext(ctx).Where("id = ?", imageID).First(&record).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, false, nil@@ -1185,15 +1194,15 @@ func (s *ImageUpdateService) StoredUpdateByImageID(ctx context.Context, imageID}// GetUnnotifiedUpdates returns a map of image IDs that have updates but haven't been notified yet-func (s *ImageUpdateService) GetUnnotifiedUpdates(ctx context.Context) (map[string]*models.ImageUpdateRecord, error) {- var records []models.ImageUpdateRecord+func (s *ImageUpdateService) GetUnnotifiedUpdates(ctx context.Context) (map[string]*ImageUpdateRecord, error) {+ var records []ImageUpdateRecordif err := s.db.WithContext(ctx).Where("has_update = ? AND notification_sent = ?", true, false).Find(&records).Error; err != nil {return nil, errors.WrapIf(err, "failed to get unnotified updates")}- result := make(map[string]*models.ImageUpdateRecord)+ result := make(map[string]*ImageUpdateRecord)for i := range records {result[records[i].ID] = &records[i]}@@ -1207,7 +1216,7 @@ func (s *ImageUpdateService) MarkUpdatesAsNotified(ctx context.Context, imageIDs}return s.db.WithContext(ctx).- Model(&models.ImageUpdateRecord{}).+ Model(&ImageUpdateRecord{}).Where("id IN ?", imageIDs).Update("notification_sent", true).Error}@@ -1326,7 +1335,7 @@ func (s *ImageUpdateService) checkSingleImageInBatchInternal(ctx context.Context// local to compare, so report a distinct not-pulled state rather// than a failed check or an available update.return &imageupdate.Response{- UpdateType: models.UpdateTypeNotPulled,+ UpdateType: UpdateTypeNotPulled,LatestDigest: digestResult.Digest,CheckTime: time.Now(),ResponseTimeMs: int(time.Since(start).Milliseconds()),@@ -1360,7 +1369,7 @@ func (s *ImageUpdateService) checkSingleImageInBatchInternal(ctx context.Contextreturn &imageupdate.Response{HasUpdate: hasDigestUpdate,- UpdateType: models.UpdateTypeDigest,+ UpdateType: UpdateTypeDigest,CurrentDigest: localDigest,LatestDigest: digestResult.Digest,CheckTime: time.Now(),@@ -1470,7 +1479,7 @@ func (s *ImageUpdateService) recordBatchImageCheckInternal(ctx context.Context,// recordDigestPinnedSkipInternal notes a digest-pinned ref as skipped on the// activity stream and persists its unchanged result.func (s *ImageUpdateService) recordDigestPinnedSkipInternal(ctx context.Context, activityID, imageRef string, result *imageupdate.Response, progress int) {- s.appendImageUpdateActivityMessageInternal(ctx, activityID, models.ActivityMessageLevelInfo, imageRef+" — digest pinned, skipped", progress, "Skipping image update check")+ s.appendImageUpdateActivityMessageInternal(ctx, activityID, activitytypes.MessageLevelInfo, imageRef+" — digest pinned, skipped", progress, "Skipping image update check")if err := s.saveUpdateResultWithSnapshotInternal(ctx, imageRef, result, nil); err != nil {slog.WarnContext(ctx, "Failed to save digest-pinned update result", "imageRef", imageRef, "error", err.Error())}@@ -1534,7 +1543,7 @@ func (s *ImageUpdateService) CheckMultipleImages(ctx context.Context, imageRefsreturn results, slotErr}}- s.appendImageUpdateActivityMessageInternal(ctx, activityID, models.ActivityMessageLevelInfo, fmt.Sprintf("Checking %d image references", len(imageRefs)), 5, "Preparing image update check")+ s.appendImageUpdateActivityMessageInternal(ctx, activityID, activitytypes.MessageLevelInfo, fmt.Sprintf("Checking %d image references", len(imageRefs)), 5, "Preparing image update check")slog.DebugContext(ctx, "Starting batch image update check", "imageCount", len(imageRefs), "externalCredCount", len(externalCreds))regRepos, initialResults, images := s.parseAndGroupImagesInternal(imageRefs)@@ -1721,9 +1730,9 @@ func (s *ImageUpdateService) CleanupOrphanedRecords(ctx context.Context) error {var result *gorm.DBif len(dockerImageIDs) == 0 {- result = s.db.WithContext(ctx).Where("1 = 1").Delete(&models.ImageUpdateRecord{})+ result = s.db.WithContext(ctx).Where("1 = 1").Delete(&ImageUpdateRecord{})} else {- result = s.db.WithContext(ctx).Where("id NOT IN ?", dockerImageIDs).Delete(&models.ImageUpdateRecord{})+ result = s.db.WithContext(ctx).Where("id NOT IN ?", dockerImageIDs).Delete(&ImageUpdateRecord{})}if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete orphaned records")@@ -1770,7 +1779,7 @@ func (s *ImageUpdateService) getUpdateSummaryForImageIDsInternal(ctx context.ConErrorsCount int64 `gorm:"column:errors_count"`}if err := s.db.WithContext(ctx).- Model(&models.ImageUpdateRecord{}).+ Model(&ImageUpdateRecord{}).Select(`COALESCE(SUM(CASE WHEN has_update THEN 1 ELSE 0 END), 0) AS images_with_updates,COALESCE(SUM(CASE WHEN has_update AND update_type = ? THEN 1 ELSE 0 END), 0) AS digest_updates,diff --git a/backend/internal/models/image_update.go b/backend/internal/imageupdate/model.gosimilarity index 95%rename from backend/internal/models/image_update.gorename to backend/internal/imageupdate/model.goindex 015a01282..6c89a5d1a 100644--- a/backend/internal/models/image_update.go+++ b/backend/internal/imageupdate/model.go@@ -1,11 +1,13 @@-package models+package imageupdateimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"time")type ImageUpdateRecord struct {- BaseModel+ database.BaseModelCheckTime time.Time `json:"checkTime" gorm:"column:check_time"`LatestVersion *string `json:"latestVersion,omitempty" gorm:"column:latest_version"`diff --git a/backend/internal/imageupdate/service_test.go b/backend/internal/imageupdate/service_test.goindex 5bc97a6ff..eaf47e359 100644--- a/backend/internal/imageupdate/service_test.go+++ b/backend/internal/imageupdate/service_test.go@@ -1,6 +1,10 @@package imageupdateimport (+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"++ "github.com/getarcaneapp/arcane/backend/v2/internal/kv"+"context""encoding/json""errors"@@ -13,6 +17,8 @@ import ("testing""time"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"github.com/getarcaneapp/arcane/backend/v2/internal/registry"ref "github.com/distribution/reference"@@ -21,7 +27,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -80,11 +85,11 @@ func setupImageUpdateRegistryTestDBInternal(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.ContainerRegistry{},- &models.KVEntry{},- &models.Project{},- &models.ImageUpdateRecord{},- &models.Event{},+ ®istry.ContainerRegistry{},+ &kv.KVEntry{},+ &testProjectRow{},+ &ImageUpdateRecord{},+ &event.Event{},))crypto.InitEncryption(&crypto.Config{Environment: "test",@@ -97,7 +102,7 @@ func createImageUpdateTestPullRegistryInternal(t *testing.T, db *database.DB, urt.Helper()encryptedToken, err := crypto.Encrypt(token)require.NoError(t, err)- require.NoError(t, db.Create(&models.ContainerRegistry{+ require.NoError(t, db.Create(®istry.ContainerRegistry{URL: url,Username: username,Token: encryptedToken,@@ -418,7 +423,7 @@ func setupImageUpdateTestDB(t *testing.T) *database.DB {dsn := fmt.Sprintf("file:image-update-test-%d?mode=memory&cache=shared", time.Now().UnixNano())db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}, &models.Event{}, &models.Project{}))+ require.NoError(t, db.AutoMigrate(&ImageUpdateRecord{}, &event.Event{}, &testProjectRow{}))return &database.DB{DB: db}}@@ -427,8 +432,8 @@ func newComposeBuildImageUpdateServiceInternal(t *testing.T) (*ImageUpdateServicdb := setupImageUpdateTestDB(t)buildRefsJSON := `["test2:latest"]`- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "compose-build-project"},+ require.NoError(t, db.Create(&testProjectRow{+ BaseModel: database.BaseModel{ID: "compose-build-project"},Name: "compose-build-project",BuildImageRefsJSON: &buildRefsJSON,}).Error)@@ -463,14 +468,14 @@ func TestImageUpdateService_CheckImageUpdate_ComposeBuildSkipsRegistryWithRepoDiresult, err := svc.CheckImageUpdate(context.Background(), "test2:latest")require.NoError(t, err)require.NotNil(t, result)- assert.Equal(t, models.UpdateTypeLocal, result.UpdateType)+ assert.Equal(t, UpdateTypeLocal, result.UpdateType)assert.False(t, result.HasUpdate)assert.Empty(t, result.Error)assert.Zero(t, registryCalls.Load())- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrequire.NoError(t, svc.db.First(&saved, "id = ?", "sha256:local-image-id").Error)- assert.Equal(t, models.UpdateTypeLocal, saved.UpdateType)+ assert.Equal(t, UpdateTypeLocal, saved.UpdateType)assert.Nil(t, saved.LastError)}@@ -487,7 +492,7 @@ func TestImageUpdateService_CheckMultipleImages_ComposeBuildSkipsRegistryWithReprequire.NoError(t, err)result := results["test2:latest"]require.NotNil(t, result)- assert.Equal(t, models.UpdateTypeLocal, result.UpdateType)+ assert.Equal(t, UpdateTypeLocal, result.UpdateType)assert.False(t, result.HasUpdate)assert.Empty(t, result.Error)assert.Zero(t, registryCalls.Load())@@ -496,8 +501,8 @@ func TestImageUpdateService_CheckMultipleImages_ComposeBuildSkipsRegistryWithRepfunc TestImageUpdateService_CheckMultipleImages_ComposeBuildMissingLocallySkipsRegistry(t *testing.T) {db := setupImageUpdateTestDB(t)buildRefsJSON := `["test2:latest"]`- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "compose-build-missing-project"},+ require.NoError(t, db.Create(&testProjectRow{+ BaseModel: database.BaseModel{ID: "compose-build-missing-project"},Name: "compose-build-missing-project",BuildImageRefsJSON: &buildRefsJSON,}).Error)@@ -527,7 +532,7 @@ func TestImageUpdateService_CheckMultipleImages_ComposeBuildMissingLocallySkipsRrequire.NotNil(t, result)assert.Empty(t, result.Error)assert.False(t, result.HasUpdate)- assert.Equal(t, models.UpdateTypeLocal, result.UpdateType)+ assert.Equal(t, UpdateTypeLocal, result.UpdateType)assert.Zero(t, registryCalls.Load())}@@ -736,7 +741,7 @@ func TestImageUpdateService_CheckMultipleImages_SkippedDigestPinnedReferenceCleaimageRef := "ghcr.io/fosrl/newt@" + pinnedDigestrepository := "ghcr.io/fosrl/newt"recordID := fmt.Sprintf("ref::%s@latest", strings.ToLower(strings.TrimSpace(repository)))- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&ImageUpdateRecord{ID: recordID,Repository: repository,Tag: "latest",@@ -753,7 +758,7 @@ func TestImageUpdateService_CheckMultipleImages_SkippedDigestPinnedReferenceClearequire.Contains(t, results, imageRef)assert.Empty(t, results[imageRef].Error)- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", recordID).First(&saved).Error)assert.False(t, saved.HasUpdate)assert.Nil(t, saved.LastError)@@ -782,7 +787,7 @@ func TestImageUpdateService_CheckMultipleImages_DigestPinnedTagPreservedWhenLocaassert.False(t, results[imageRef].HasUpdate)assert.Empty(t, results[imageRef].Error)- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:pinned-local-id").First(&saved).Error)assert.Equal(t, "9", saved.Tag, "tag should come from the original tag@digest reference, not fall back to the RepoDigests-only placeholder")}@@ -840,7 +845,7 @@ func TestImageUpdateService_CheckImageUpdate_UsesRegistryFallback(t *testing.T)assert.Equal(t, "anonymous", result.AuthMethod)assert.Equal(t, serverURL.Host, result.AuthRegistry)- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)assert.Equal(t, remoteDigest, mo.PointerToOption(saved.LatestDigest).OrEmpty())}@@ -881,14 +886,14 @@ func TestImageUpdateService_CheckMultipleImages_UsesRegistryFallback(t *testing.assert.Equal(t, "anonymous", result.AuthMethod)assert.Equal(t, serverURL.Host, result.AuthRegistry)- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(&saved).Error)assert.Equal(t, remoteDigest, mo.PointerToOption(saved.LatestDigest).OrEmpty())}func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestContextCanceledInternal(t *testing.T) {db := setupImageUpdateTestDB(t)- require.NoError(t, db.AutoMigrate(&models.Activity{}, &models.ActivityMessage{}))+ require.NoError(t, db.AutoMigrate(&activity.Activity{}, &activity.ActivityMessage{}))activityService := activity.NewActivityService(db, nil)svc := NewImageUpdateService(db, nil, nil, nil, nil, nil, activityService)@@ -909,9 +914,9 @@ func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestConteerrCh <- err}()- var activity models.Activity+ var activity activity.Activityrequire.Eventually(t, func() bool {- return db.Where("type = ?", models.ActivityTypeImageUpdateCheck).First(&activity).Error == nil+ return db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&activity).Error == nil}, time.Second, 10*time.Millisecond)cancel()@@ -927,7 +932,7 @@ func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestConteif err := db.First(&activity, "id = ?", activity.ID).Error; err != nil {return false}- return activity.Status == models.ActivityStatusFailed+ return activity.Status == activitytypes.StatusFailed}, time.Second, 10*time.Millisecond)assert.Equal(t, "Image update check complete", activity.Step)assert.Contains(t, activity.LatestMessage, "Image update check failed")@@ -935,7 +940,7 @@ func TestImageUpdateService_CheckMultipleImagesCompletesActivityWhenRequestContefunc TestImageUpdateService_CheckMultipleImagesTimesOutStalledRegistryCheckInternal(t *testing.T) {db := setupImageUpdateTestDB(t)- require.NoError(t, db.AutoMigrate(&models.Activity{}, &models.ActivityMessage{}))+ require.NoError(t, db.AutoMigrate(&activity.Activity{}, &activity.ActivityMessage{}))settingsService := newImageUpdateTestSettingsServiceInternal(t, "1", "30")activityService := activity.NewActivityService(db, nil)@@ -965,9 +970,9 @@ func TestImageUpdateService_CheckMultipleImagesTimesOutStalledRegistryCheckInterrequire.NotNil(t, results["registry.example.com/team/app:1.2.3"])require.Contains(t, results["registry.example.com/team/app:1.2.3"].Error, context.DeadlineExceeded.Error())- var activity models.Activity- require.NoError(t, db.Where("type = ?", models.ActivityTypeImageUpdateCheck).First(&activity).Error)- require.Equal(t, models.ActivityStatusFailed, activity.Status)+ var activity activity.Activity+ require.NoError(t, db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&activity).Error)+ require.Equal(t, activitytypes.StatusFailed, activity.Status)require.NotNil(t, activity.EndedAt)require.NotNil(t, activity.DurationMs)require.Equal(t, "Image update check complete", activity.Step)@@ -976,7 +981,7 @@ func TestImageUpdateService_CheckMultipleImagesTimesOutStalledRegistryCheckInterfunc TestImageUpdateService_CheckMultipleImagesPanicMarksActivityFailedInternal(t *testing.T) {db := setupImageUpdateTestDB(t)- require.NoError(t, db.AutoMigrate(&models.Activity{}, &models.ActivityMessage{}))+ require.NoError(t, db.AutoMigrate(&activity.Activity{}, &activity.ActivityMessage{}))settingsService := newImageUpdateTestSettingsServiceInternal(t, "30", "30")activityService := activity.NewActivityService(db, nil)@@ -997,9 +1002,9 @@ func TestImageUpdateService_CheckMultipleImagesPanicMarksActivityFailedInternal(require.Contains(t, err.Error(), "image update check panicked")require.Contains(t, err.Error(), "registry check exploded")- var activity models.Activity- require.NoError(t, db.Where("type = ?", models.ActivityTypeImageUpdateCheck).First(&activity).Error)- require.Equal(t, models.ActivityStatusFailed, activity.Status)+ var activity activity.Activity+ require.NoError(t, db.Where("type = ?", activitytypes.TypeImageUpdateCheck).First(&activity).Error)+ require.Equal(t, activitytypes.StatusFailed, activity.Status)require.NotNil(t, activity.EndedAt)require.Contains(t, activity.LatestMessage, "Image update check failed")}@@ -1042,7 +1047,7 @@ func TestImageUpdateService_InspectLocalImageSnapshotUsesDockerAPITimeoutInternafunc TestImageUpdateService_CheckMultipleImages_UsesDockerHubCredentialsOnFirstAttempt(t *testing.T) {db := setupImageUpdateRegistryTestDBInternal(t)- require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}, &models.Event{}, &models.Project{}))+ require.NoError(t, db.AutoMigrate(&ImageUpdateRecord{}, &event.Event{}, &testProjectRow{}))createImageUpdateTestPullRegistryInternal(t, db, "https://index.docker.io/v1/", "docker-user", "docker-token")localDigest := digest.FromString("batchlocal-rate-limit").String()@@ -1123,16 +1128,16 @@ func TestImageUpdateService_CheckMultipleImages_ReportsNotPulledWhenLocalImageMirequire.NotNil(t, results[imageRef])assert.Empty(t, results[imageRef].Error)assert.False(t, results[imageRef].HasUpdate)- assert.Equal(t, models.UpdateTypeNotPulled, results[imageRef].UpdateType)+ assert.Equal(t, UpdateTypeNotPulled, results[imageRef].UpdateType)assert.Equal(t, remoteDigest, results[imageRef].LatestDigest)- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrepository := fmt.Sprintf("%s/library/nginx", serverURL.Host)require.NoError(t, db.WithContext(context.Background()).Where("id = ?", fmt.Sprintf("ref::%s@alpine", strings.ToLower(strings.TrimSpace(repository)))).First(&saved).Error)assert.Equal(t, repository, saved.Repository)assert.Equal(t, "alpine", saved.Tag)assert.False(t, saved.HasUpdate)- assert.Equal(t, models.UpdateTypeNotPulled, saved.UpdateType)+ assert.Equal(t, UpdateTypeNotPulled, saved.UpdateType)assert.Nil(t, saved.LastError)}@@ -1161,7 +1166,7 @@ func TestImageUpdateService_SaveUpdateResultWithSnapshotInternal_PersistsRegistrrequire.NoError(t, svc.saveUpdateResultWithSnapshotInternal(context.Background(), imageRef, result, nil))- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrepository := fmt.Sprintf("%s/library/nginx", serverURL.Host)require.NoError(t, db.WithContext(context.Background()).Where("id = ?", fmt.Sprintf("ref::%s@alpine", strings.ToLower(strings.TrimSpace(repository)))).First(&saved).Error)assert.Equal(t, repository, saved.Repository)@@ -1187,33 +1192,33 @@ func TestImageUpdateService_MarkImageRefUpToDateAfterPull_ClearsMatchingRecordsAnow := time.Now().UTC().Add(-time.Hour)// Real sha256 records for OTHER containers running the old image — must not be cleared.- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&ImageUpdateRecord{ID: "sha256:old-full",Repository: repository,Tag: "1.2.3",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: UpdateTypeDigest,CurrentVersion: "1.2.3",CheckTime: now,}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&ImageUpdateRecord{ID: "sha256:old-short",Repository: "team/app",Tag: "1.2.3",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: UpdateTypeDigest,CurrentVersion: "1.2.3",CheckTime: now.Add(time.Minute),}).Error)// Synthetic ref:: record — must be cleared when new image is pulled.syntheticID := "ref::" + repository + "@1.2.3"- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&ImageUpdateRecord{ID: syntheticID,Repository: repository,Tag: "1.2.3",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: UpdateTypeDigest,CurrentVersion: "1.2.3",CheckTime: now,}).Error)@@ -1223,21 +1228,21 @@ func TestImageUpdateService_MarkImageRefUpToDateAfterPull_ClearsMatchingRecordsArequire.NoError(t, svc.MarkImageRefUpToDateAfterPull(context.Background(), imageRef))// Sha256 records for old images that other containers are still running must stay HasUpdate=true.- var fullRecord models.ImageUpdateRecord+ var fullRecord ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:old-full").First(&fullRecord).Error)assert.True(t, fullRecord.HasUpdate, "sha256 record for old image still in use must not be cleared")- var shortRecord models.ImageUpdateRecord+ var shortRecord ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:old-short").First(&shortRecord).Error)assert.True(t, shortRecord.HasUpdate, "sha256 record for old image still in use must not be cleared")// Synthetic ref:: record must be cleared since a fresh image was pulled.- var synthRecord models.ImageUpdateRecord+ var synthRecord ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", syntheticID).First(&synthRecord).Error)assert.False(t, synthRecord.HasUpdate, "synthetic ref:: record must be cleared after pull")// The newly pulled image record must be saved as up-to-date.- var currentRecord models.ImageUpdateRecord+ var currentRecord ImageUpdateRecordrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", "sha256:local-image-id").First(¤tRecord).Error)assert.False(t, currentRecord.HasUpdate)assert.Equal(t, repository, currentRecord.Repository)@@ -1278,7 +1283,7 @@ func TestImageUpdateService_NotificationSentLogic(t *testing.T) {require.NoError(t, err)// Verify it was saved correctly- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecorderr = db.First(&saved, "id = ?", imageID).Errorrequire.NoError(t, err)assert.False(t, saved.NotificationSent)@@ -1295,14 +1300,14 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {tests := []struct {name string- existingRecord *models.ImageUpdateRecord+ existingRecord *ImageUpdateRecordnewResult *imageupdate.ResponseexpectNotifReset boolreason string}{{name: "digest changed - should reset",- existingRecord: &models.ImageUpdateRecord{+ existingRecord: &ImageUpdateRecord{ID: imageID,Repository: repo,Tag: tag,@@ -1325,7 +1330,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {},{name: "version changed - should reset",- existingRecord: &models.ImageUpdateRecord{+ existingRecord: &ImageUpdateRecord{ID: imageID,Repository: repo,Tag: tag,@@ -1348,7 +1353,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {},{name: "update state changed - should reset",- existingRecord: &models.ImageUpdateRecord{+ existingRecord: &ImageUpdateRecord{ID: imageID,Repository: repo,Tag: tag,@@ -1369,7 +1374,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {},{name: "nothing changed - should keep flag",- existingRecord: &models.ImageUpdateRecord{+ existingRecord: &ImageUpdateRecord{ID: imageID,Repository: repo,Tag: tag,@@ -1404,7 +1409,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {require.NoError(t, err)// Verify it was marked as notified- var check models.ImageUpdateRecord+ var check ImageUpdateRecorderr = db.First(&check, "id = ?", imageID).Errorrequire.NoError(t, err)assert.True(t, check.NotificationSent, "existing record should be marked as notified")@@ -1412,7 +1417,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {// Simulate comparison logic from saveUpdateResultByIDInternalupdateRecord := buildImageUpdateRecord(imageID, repo, tag, tt.newResult)- var existingRecord models.ImageUpdateRecord+ var existingRecord ImageUpdateRecorderr = db.Where("id = ?", imageID).First(&existingRecord).Errorrequire.NoError(t, err)@@ -1432,7 +1437,7 @@ func TestImageUpdateService_NotificationSentReset(t *testing.T) {require.NoError(t, err)// Verify the result- var updated models.ImageUpdateRecord+ var updated ImageUpdateRecorderr = db.First(&updated, "id = ?", imageID).Errorrequire.NoError(t, err)@@ -1474,7 +1479,7 @@ func TestImageUpdateService_RateLimitErrorPreservesPreviousResult(t *testing.T)t.Run(tt.name, func(t *testing.T) {db.Exec("DELETE FROM image_updates WHERE id = ?", imageID)- existing := &models.ImageUpdateRecord{+ existing := &ImageUpdateRecord{ID: imageID,Repository: repo,Tag: tag,@@ -1492,7 +1497,7 @@ func TestImageUpdateService_RateLimitErrorPreservesPreviousResult(t *testing.T)}require.NoError(t, savePreparedUpdateResultWithTxInternal(db.DB, imageID, repo, tag, result))- var saved models.ImageUpdateRecord+ var saved ImageUpdateRecordrequire.NoError(t, db.First(&saved, "id = ?", imageID).Error)if tt.expectPreserved {@@ -1514,7 +1519,7 @@ func TestImageUpdateService_GetUnnotifiedUpdates(t *testing.T) {svc := &ImageUpdateService{db: db}// Create test records- records := []models.ImageUpdateRecord{+ records := []ImageUpdateRecord{{ID: "sha256:img1",Repository: "nginx",@@ -1571,7 +1576,7 @@ func TestImageUpdateService_MarkUpdatesAsNotified(t *testing.T) {// Create test recordsimageIDs := []string{"sha256:img1", "sha256:img2", "sha256:img3"}for _, id := range imageIDs {- rec := models.ImageUpdateRecord{+ rec := ImageUpdateRecord{ID: id,Repository: "test/repo",Tag: "latest",@@ -1587,18 +1592,18 @@ func TestImageUpdateService_MarkUpdatesAsNotified(t *testing.T) {require.NoError(t, err)// Verify img1 and img2 are marked- var img1 models.ImageUpdateRecord+ var img1 ImageUpdateRecorderr = db.First(&img1, "id = ?", "sha256:img1").Errorrequire.NoError(t, err)assert.True(t, img1.NotificationSent)- var img2 models.ImageUpdateRecord+ var img2 ImageUpdateRecorderr = db.First(&img2, "id = ?", "sha256:img2").Errorrequire.NoError(t, err)assert.True(t, img2.NotificationSent)// Verify img3 is still false- var img3 models.ImageUpdateRecord+ var img3 ImageUpdateRecorderr = db.First(&img3, "id = ?", "sha256:img3").Errorrequire.NoError(t, err)assert.False(t, img3.NotificationSent)@@ -1624,7 +1629,7 @@ func TestImageUpdateService_MarkUpdatesAsNotified_EmptyList(t *testing.T) {// with "context canceled" so notifications were never dispatched (issue #2920).func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *testing.T) {db := setupImageUpdateTestDB(t)- require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}))+ require.NoError(t, db.AutoMigrate(¬ification.NotificationSettings{}))// A provider that actually delivers (returns 200), so the record is only marked// notified when the send genuinely reaches it.@@ -1634,10 +1639,10 @@ func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *tew.WriteHeader(http.StatusOK)}))defer server.Close()- require.NoError(t, db.Create(&models.NotificationSettings{- Provider: models.NotificationProviderGeneric,+ require.NoError(t, db.Create(¬ification.NotificationSettings{+ Provider: notifications.NotificationProviderGeneric,Enabled: true,- Config: models.JSON{+ Config: database.JSON{"webhookUrl": server.URL,"method": "POST","contentType": "application/json",@@ -1647,7 +1652,7 @@ func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *tenotif := notification.NewNotificationService(db, nil, nil, nil)svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)- rec := models.ImageUpdateRecord{+ rec := ImageUpdateRecord{ID: "sha256:img1",Repository: "test/repo",Tag: "latest",@@ -1669,7 +1674,7 @@ func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *te// GetUnnotifiedUpdates + the send + MarkUpdatesAsNotified ran despite the canceled// parent ctx (issue #2920).require.EqualValues(t, 1, calls.Load())- var reloaded models.ImageUpdateRecord+ var reloaded ImageUpdateRecordrequire.NoError(t, db.First(&reloaded, "id = ?", "sha256:img1").Error)assert.True(t, reloaded.NotificationSent)}@@ -1681,12 +1686,12 @@ func TestImageUpdateService_SendBatchNotifications_DetachesCanceledContext(t *te// update is permanently suppressed (it only re-surfaces on a future digest change).func TestImageUpdateService_SendBatchNotifications_NoEligibleProviders_LeavesUnnotified(t *testing.T) {db := setupImageUpdateTestDB(t)- require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}))+ require.NoError(t, db.AutoMigrate(¬ification.NotificationSettings{}))notif := notification.NewNotificationService(db, nil, nil, nil)svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)- rec := models.ImageUpdateRecord{+ rec := ImageUpdateRecord{ID: "sha256:img-no-provider",Repository: "test/repo",Tag: "latest",@@ -1697,7 +1702,7 @@ func TestImageUpdateService_SendBatchNotifications_NoEligibleProviders_LeavesUnnsvc.SendBatchUpdateNotifications(context.Background())- var reloaded models.ImageUpdateRecord+ var reloaded ImageUpdateRecordrequire.NoError(t, db.First(&reloaded, "id = ?", "sha256:img-no-provider").Error)assert.False(t, reloaded.NotificationSent)@@ -1712,7 +1717,7 @@ func TestImageUpdateService_SendBatchNotifications_NoEligibleProviders_LeavesUnn// re-sends the same update on every poll until the broken provider is fixed.func TestImageUpdateService_SendBatchNotifications_PartialFailureStillMarksNotified(t *testing.T) {db := setupImageUpdateTestDB(t)- require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}))+ require.NoError(t, db.AutoMigrate(¬ification.NotificationSettings{}))healthy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {w.WriteHeader(http.StatusOK)@@ -1724,10 +1729,10 @@ func TestImageUpdateService_SendBatchNotifications_PartialFailureStillMarksNotifdefer broken.Close()for _, serverURL := range []string{healthy.URL, broken.URL} {- require.NoError(t, db.Create(&models.NotificationSettings{- Provider: models.NotificationProviderGeneric,+ require.NoError(t, db.Create(¬ification.NotificationSettings{+ Provider: notifications.NotificationProviderGeneric,Enabled: true,- Config: models.JSON{+ Config: database.JSON{"webhookUrl": serverURL,"method": "POST","contentType": "application/json",@@ -1738,7 +1743,7 @@ func TestImageUpdateService_SendBatchNotifications_PartialFailureStillMarksNotifnotif := notification.NewNotificationService(db, nil, nil, nil)svc := NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)- rec := models.ImageUpdateRecord{+ rec := ImageUpdateRecord{ID: "sha256:img-partial",Repository: "test/repo",Tag: "latest",@@ -1749,7 +1754,7 @@ func TestImageUpdateService_SendBatchNotifications_PartialFailureStillMarksNotifsvc.SendBatchUpdateNotifications(context.Background())- var reloaded models.ImageUpdateRecord+ var reloaded ImageUpdateRecordrequire.NoError(t, db.First(&reloaded, "id = ?", "sha256:img-partial").Error)assert.True(t, reloaded.NotificationSent)}@@ -1760,7 +1765,7 @@ func TestImageUpdateService_GetUpdateSummaryForImageIDs_FiltersToLiveImages(t *tsvc := &ImageUpdateService{db: db}now := time.Now()- records := []models.ImageUpdateRecord{+ records := []ImageUpdateRecord{{ID: "sha256:live-1",Repository: "docker.io/library/nginx",@@ -1858,7 +1863,7 @@ func newImageUpdateTestSettingsServiceInternal(t *testing.T, registryTimeout, doctx := context.Background()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))dbWrap := &database.DB{DB: db}lifecycle := fxtest.NewLifecycle(t)runtime, err := actors.NewRuntime(t.Context(), lifecycle)@@ -2248,3 +2253,14 @@ func TestImageUpdateService_GetAllImageRefsFallsBackWhenContainerDiscoveryFailsIrequire.NoError(t, err)assert.Equal(t, []string{firstRef, secondRef}, got)}++// testProjectRow is a minimal stand-in for project.Project: the project+// package imports this one, so the in-package test cannot import it back.+type testProjectRow struct {+ database.BaseModel+ Name string+ Path string+ BuildImageRefsJSON *string `gorm:"column:build_image_refs_json"`+}++func (testProjectRow) TableName() string { return "projects" }diff --git a/backend/internal/job/service_test.go b/backend/internal/job/service_test.goindex 3b659e961..fca9032c0 100644--- a/backend/internal/job/service_test.go+++ b/backend/internal/job/service_test.go@@ -9,7 +9,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/types/v2/jobschedule"schedulertypes "github.com/getarcaneapp/arcane/types/v2/scheduler"@@ -23,7 +22,7 @@ func setupSettingsTestDBInternal(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))return &database.DB{DB: db}}@@ -283,7 +282,7 @@ func TestJobService_UpdateJobSchedules_RestoresPreviousScheduleWhenRescheduleFairequire.ErrorContains(t, err, "scheduler unavailable")require.Equal(t, "0 0 0 * * *", settingsSvc.GetStringSetting(ctx, "autoUpdateInterval", ""))- var persisted models.SettingVariable+ var persisted settings.SettingVariablerequire.NoError(t, db.WithContext(ctx).First(&persisted, "key = ?", "autoUpdateInterval").Error)require.Equal(t, "0 0 0 * * *", persisted.Value)}diff --git a/backend/internal/models/kv.go b/backend/internal/kv/model.gosimilarity index 96%rename from backend/internal/models/kv.gorename to backend/internal/kv/model.goindex dbc41d5a3..a6a0bbc6c 100644--- a/backend/internal/models/kv.go+++ b/backend/internal/kv/model.go@@ -1,4 +1,4 @@-package models+package kvimport "time"diff --git a/backend/internal/kv/prefix_test.go b/backend/internal/kv/prefix_test.goindex f1770bfa3..5072101ad 100644--- a/backend/internal/kv/prefix_test.go+++ b/backend/internal/kv/prefix_test.go@@ -4,7 +4,6 @@ import ("context""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/require")@@ -41,7 +40,7 @@ func TestKVService_ListByPrefix_EscapesLikeWildcards(t *testing.T) {require.ElementsMatch(t, []string{`path\prefix:real`}, kvEntryKeysForPrefixTestInternal(pathEntries))}-func kvEntryKeysForPrefixTestInternal(entries []models.KVEntry) []string {+func kvEntryKeysForPrefixTestInternal(entries []KVEntry) []string {keys := make([]string, 0, len(entries))for _, entry := range entries {keys = append(keys, entry.Key)diff --git a/backend/internal/kv/service.go b/backend/internal/kv/service.goindex f9f6e2e3f..969e32d79 100644--- a/backend/internal/kv/service.go+++ b/backend/internal/kv/service.go@@ -8,7 +8,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""gorm.io/gorm""gorm.io/gorm/clause")@@ -23,7 +22,7 @@ func NewKVService(db *database.DB) *KVService {}func (s *KVService) Get(ctx context.Context, key string) (string, bool, error) {- var entry models.KVEntry+ var entry KVEntryerr := s.db.WithContext(ctx).Where("key = ?", key).First(&entry).Errorif errors.Is(err, gorm.ErrRecordNotFound) {return "", false, nil@@ -36,7 +35,7 @@ func (s *KVService) Get(ctx context.Context, key string) (string, bool, error) {}func (s *KVService) Set(ctx context.Context, key, value string) error {- entry := models.KVEntry{Key: key, Value: value}+ entry := KVEntry{Key: key, Value: value}err := s.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "key"}},@@ -51,14 +50,14 @@ func (s *KVService) Set(ctx context.Context, key, value string) error {}func (s *KVService) Delete(ctx context.Context, key string) error {- if err := s.db.WithContext(ctx).Delete(&models.KVEntry{}, "key = ?", key).Error; err != nil {+ if err := s.db.WithContext(ctx).Delete(&KVEntry{}, "key = ?", key).Error; err != nil {return errors.WrapIff(err, "failed to delete kv entry %q", key)}return nil}-func (s *KVService) ListByPrefix(ctx context.Context, prefix string) ([]models.KVEntry, error) {- var entries []models.KVEntry+func (s *KVService) ListByPrefix(ctx context.Context, prefix string) ([]KVEntry, error) {+ var entries []KVEntryescapedPrefix := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(prefix)if err := s.db.WithContext(ctx).Where("key LIKE ? ESCAPE '\\'", escapedPrefix+"%").Find(&entries).Error; err != nil {return nil, errors.WrapIff(err, "failed to list kv entries with prefix %q", prefix)@@ -107,11 +106,11 @@ func (s *KVService) GetInt64(ctx context.Context, key string, defaultValue int64func (s *KVService) IncrementInt64(ctx context.Context, key string, delta int64) (int64, error) {var nextValue int64err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var entry models.KVEntry+ var entry KVEntryerr := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("key = ?", key).First(&entry).Errorif errors.Is(err, gorm.ErrRecordNotFound) {nextValue = delta- return tx.Create(&models.KVEntry{+ return tx.Create(&KVEntry{Key: key,Value: strconv.FormatInt(nextValue, 10),}).Errordiff --git a/backend/internal/kv/service_test.go b/backend/internal/kv/service_test.goindex cec121f79..b7158c4bf 100644--- a/backend/internal/kv/service_test.go+++ b/backend/internal/kv/service_test.go@@ -1,11 +1,12 @@package kvimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""testing""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/libtnb/sqlite""github.com/stretchr/testify/require""gorm.io/gorm"@@ -15,7 +16,7 @@ func setupKVServiceInternal(t *testing.T) *KVService {t.Helper()db := setupSettingsTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&KVEntry{}))return NewKVService(db)}@@ -53,6 +54,6 @@ func setupSettingsTestDB(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))return &database.DB{DB: db}}diff --git a/backend/internal/middleware/csrf_middleware.go b/backend/internal/middleware/csrf_middleware.goindex 8ed0ed934..28f09edbd 100644--- a/backend/internal/middleware/csrf_middleware.go+++ b/backend/internal/middleware/csrf_middleware.go@@ -1,12 +1,13 @@package middlewareimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"log/slog""net/http""strings""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/labstack/echo/v5")@@ -71,8 +72,8 @@ func (m *CSRFMiddleware) Add() echo.MiddlewareFunc {"origin", req.Header.Get("Origin"),"sec_fetch_site", req.Header.Get("Sec-Fetch-Site"),)- return c.JSON(http.StatusForbidden, models.APIError{- Code: models.APIErrorCodeForbidden,+ return c.JSON(http.StatusForbidden, common.APIError{+ Code: common.APIErrorCodeForbidden,Message: "Cross-origin request blocked",})}diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.goindex ee3b5bd9e..a7bf271b1 100644--- a/backend/internal/middleware/environment_middleware.go+++ b/backend/internal/middleware/environment_middleware.go@@ -17,7 +17,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"wsutil "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/ws"@@ -64,7 +63,7 @@ type EnvResolver func(ctx context.Context, id string) (string, *string, bool, er// per-user context (e.g. the icon catalog preference) can travel with the// proxied request; it is nil for callers that are not a user (environment// bootstrap keys).-type AuthValidator func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *models.User, bool)+type AuthValidator func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *common.User, bool)// EnvironmentMiddleware proxies requests for remote environments to their respective agents.type EnvironmentMiddleware struct {@@ -127,7 +126,7 @@ func (m *EnvironmentMiddleware) Handle(c *echo.Context, next echo.HandlerFunc) e// SECURITY: Validate authentication BEFORE proxying to remote environments.var perms *authz.PermissionSet- var user *models.User+ var user *common.Userif m.authValidator != nil {ps, u, ok := m.authValidator(c.Request().Context(), c)if !ok {@@ -198,7 +197,7 @@ func (m *EnvironmentMiddleware) Handle(c *echo.Context, next echo.HandlerFunc) e//// SECURITY: the header is always cleared first, so a browser-supplied value// never rides through; only the server-resolved preference is forwarded.-func (m *EnvironmentMiddleware) setIconCatalogHeaderInternal(c *echo.Context, user *models.User) {+func (m *EnvironmentMiddleware) setIconCatalogHeaderInternal(c *echo.Context, user *common.User) {c.Request().Header.Del(utils.HeaderIconCatalog)if user == nil || user.Preferences.IconCatalog == nil || *user.Preferences.IconCatalog == "" {returndiff --git a/backend/internal/middleware/environment_middleware_test.go b/backend/internal/middleware/environment_middleware_test.goindex 1e22b4b43..11da650d1 100644--- a/backend/internal/middleware/environment_middleware_test.go+++ b/backend/internal/middleware/environment_middleware_test.go@@ -1,12 +1,13 @@package middlewareimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""net/http""net/http/httptest""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -23,7 +24,7 @@ func newTestEnvironmentMiddleware() *EnvironmentMiddleware {_ = ctxreturn "edge://oracle-1", nil, true, nil},- authValidator: func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *models.User, bool) {+ authValidator: func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *common.User, bool) {_ = ctx_ = creturn authz.SudoPermissionSet(), nil, true@@ -246,7 +247,7 @@ func TestEnvironmentMiddleware_LocalEnvironmentSkipsProxyPermissionCheck(t *testlocalID: "0",paramName: "id",matcher: matcher,- authValidator: func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *models.User, bool) {+ authValidator: func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *common.User, bool) {_ = ctx_ = creturn authz.NewPermissionSet(), nil, true@@ -357,9 +358,9 @@ func TestEnvironmentMiddleware_ForwardsResolvedIconCatalogHeaderOnly(t *testing._, _ = ctx, idreturn backend.URL, nil, true, nil},- authValidator: func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *models.User, bool) {+ authValidator: func(ctx context.Context, c *echo.Context) (*authz.PermissionSet, *common.User, bool) {_, _ = ctx, c- u := &models.User{}+ u := &common.User{}u.Preferences.IconCatalog = tt.catalogreturn authz.SudoPermissionSet(), u, true},diff --git a/backend/internal/middleware/role.go b/backend/internal/middleware/role.goindex db0eeac10..9d580a116 100644--- a/backend/internal/middleware/role.go+++ b/backend/internal/middleware/role.go@@ -1,6 +1,8 @@package middlewareimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""log/slog""net/http"@@ -8,7 +10,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/labstack/echo/v5"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz")@@ -44,7 +45,7 @@ func RequireEchoPermission(perm string) echo.MiddlewareFunc {envID = authz.EnvIDFromPath(c.Request().URL.Path)}if !ps.Allows(perm, envID) {- return c.JSON(http.StatusForbidden, models.APIError{+ return c.JSON(http.StatusForbidden, common.APIError{Code: "FORBIDDEN",Message: "permission denied: " + perm,})diff --git a/backend/internal/models/activity.go b/backend/internal/models/activity.godeleted file mode 100644index 1a3a0eb5f..000000000--- a/backend/internal/models/activity.go+++ /dev/null@@ -1,90 +0,0 @@-package models--import "time"--type (- ActivityType string- ActivityStatus string- ActivityMessageLevel string-)--const (- ActivityStatusQueued ActivityStatus = "queued"- ActivityStatusRunning ActivityStatus = "running"- ActivityStatusSuccess ActivityStatus = "success"- ActivityStatusFailed ActivityStatus = "failed"- ActivityStatusCancelled ActivityStatus = "cancelled"-)--const (- ActivityTypeImagePull ActivityType = "image_pull"- ActivityTypeImageBuild ActivityType = "image_build"- ActivityTypeImageUpdateCheck ActivityType = "image_update_check"- ActivityTypeProjectPull ActivityType = "project_pull"- ActivityTypeProjectBuild ActivityType = "project_build"- ActivityTypeProjectDeploy ActivityType = "project_deploy"- ActivityTypeProjectRedeploy ActivityType = "project_redeploy"- ActivityTypeProjectDown ActivityType = "project_down"- ActivityTypeProjectRestart ActivityType = "project_restart"- ActivityTypeProjectDestroy ActivityType = "project_destroy"- ActivityTypeContainerStart ActivityType = "container_start"- ActivityTypeContainerStop ActivityType = "container_stop"- ActivityTypeContainerRestart ActivityType = "container_restart"- ActivityTypeContainerRedeploy ActivityType = "container_redeploy"- ActivityTypeContainerDelete ActivityType = "container_delete"- ActivityTypeContainerKill ActivityType = "container_kill"- ActivityTypeContainerPause ActivityType = "container_pause"- ActivityTypeContainerUnpause ActivityType = "container_unpause"- ActivityTypeVulnerabilityScan ActivityType = "vulnerability_scan"- ActivityTypeAutoUpdate ActivityType = "auto_update"- ActivityTypeSystemPrune ActivityType = "system_prune"- ActivityTypeResourceAction ActivityType = "resource_action"-)--const (- ActivityMessageLevelInfo ActivityMessageLevel = "info"- ActivityMessageLevelWarning ActivityMessageLevel = "warning"- ActivityMessageLevelError ActivityMessageLevel = "error"- ActivityMessageLevelSuccess ActivityMessageLevel = "success"-)--type Activity struct {- BaseModel-- EnvironmentID string `json:"environmentId" gorm:"column:environment_id;not null;index" sortable:"true"`- BatchID *string `json:"batchId,omitempty" gorm:"column:batch_id;index"`- Type ActivityType `json:"type" gorm:"column:type;not null;index" sortable:"true"`- Status ActivityStatus `json:"status" gorm:"column:status;not null;index" sortable:"true"`- ResourceType *string `json:"resourceType,omitempty" gorm:"column:resource_type;index" sortable:"true"`- ResourceID *string `json:"resourceId,omitempty" gorm:"column:resource_id;index"`- ResourceName *string `json:"resourceName,omitempty" gorm:"column:resource_name" sortable:"true"`- Progress *int `json:"progress,omitempty" gorm:"column:progress"`- Step string `json:"step,omitempty" gorm:"column:step"`- LatestMessage string `json:"latestMessage,omitempty" gorm:"column:latest_message"`- StartedByUserID *string `json:"startedByUserId,omitempty" gorm:"column:started_by_user_id;index"`- StartedByUsername *string `json:"startedByUsername,omitempty" gorm:"column:started_by_username"`- StartedByDisplayName *string `json:"startedByDisplayName,omitempty" gorm:"column:started_by_display_name"`- StartedAt time.Time `json:"startedAt" gorm:"column:started_at;not null" sortable:"true"`- EndedAt *time.Time `json:"endedAt,omitempty" gorm:"column:ended_at" sortable:"true"`- DurationMs *int64 `json:"durationMs,omitempty" gorm:"column:duration_ms" sortable:"true"`- Error *string `json:"error,omitempty" gorm:"column:error"`- Metadata JSON `json:"metadata,omitempty" gorm:"type:text"`-}--func (Activity) TableName() string {- return "activities"-}--type ActivityMessage struct {- BaseModel-- ActivityID string `json:"activityId" gorm:"column:activity_id;not null;index"`- Level ActivityMessageLevel `json:"level" gorm:"column:level;not null"`- Message string `json:"message" gorm:"column:message;not null"`- Payload JSON `json:"payload,omitempty" gorm:"type:text"`- Activity *Activity `json:"-" gorm:"foreignKey:ActivityID;constraint:OnDelete:CASCADE"`-}--func (ActivityMessage) TableName() string {- return "activity_messages"-}diff --git a/backend/internal/models/api_key.go b/backend/internal/models/api_key.godeleted file mode 100644index 438b992cd..000000000--- a/backend/internal/models/api_key.go+++ /dev/null@@ -1,33 +0,0 @@-package models--import (- "time"-)--const (- // ApiKeyKindScoped keys carry their own permission grant rows.- ApiKeyKindScoped = "scoped"- // ApiKeyKindPersonal keys have no grants; they inherit the owner's role- // permissions at authentication time.- ApiKeyKindPersonal = "personal"-)--type ApiKey struct {- BaseModel-- Name string `json:"name" gorm:"column:name;not null" sortable:"true"`- Description *string `json:"description,omitempty" gorm:"column:description"`- KeyHash string `json:"-" gorm:"column:key_hash;not null"`- KeyPrefix string `json:"keyPrefix" gorm:"column:key_prefix;not null"`- ManagedBy *string `json:"-" gorm:"column:managed_by"`- Kind string `json:"kind" gorm:"column:kind;not null;default:scoped"`- UserID *string `json:"userId,omitempty" gorm:"column:user_id"`- EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id"`- ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`- LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`- PermissionGrants []ApiKeyPermission `json:"-" gorm:"foreignKey:ApiKeyID;references:ID;constraint:OnDelete:CASCADE"`-}--func (ApiKey) TableName() string {- return "api_keys"-}diff --git a/backend/internal/models/federated_credential.go b/backend/internal/models/federated_credential.godeleted file mode 100644index 11a6a2a9a..000000000--- a/backend/internal/models/federated_credential.go+++ /dev/null@@ -1,34 +0,0 @@-package models--import "time"--const (- FederatedCredentialMatchExact = "exact"- FederatedCredentialMatchGlob = "glob"-)--type FederatedCredential struct {- BaseModel-- Name string `json:"name" gorm:"column:name;not null" sortable:"true"`- Description *string `json:"description,omitempty" gorm:"column:description"`- Enabled bool `json:"enabled" gorm:"column:enabled;not null;default:false;index" sortable:"true"`- IssuerURL string `json:"issuerUrl" gorm:"column:issuer_url;not null;index" sortable:"true"`- Audiences StringSlice `json:"audiences" gorm:"column:audiences;type:text;not null"`- SubjectClaim string `json:"subjectClaim" gorm:"column:subject_claim;not null;default:'sub'"`- SubjectMatch string `json:"subjectMatch" gorm:"column:subject_match;not null"`- MatchType string `json:"matchType" gorm:"column:match_type;not null;default:'exact'"`- RoleID string `json:"roleId" gorm:"column:role_id;not null;index"`- EnvironmentID *string `json:"environmentId,omitempty" gorm:"column:environment_id;index"`- IdentityUserID string `json:"identityUserId" gorm:"column:identity_user_id;not null;index"`- TokenTTLSeconds int `json:"tokenTtlSeconds" gorm:"column:token_ttl_seconds;not null;default:900"`- LastUsedAt *time.Time `json:"lastUsedAt,omitempty" gorm:"column:last_used_at" sortable:"true"`- ExpiresAt *time.Time `json:"expiresAt,omitempty" gorm:"column:expires_at" sortable:"true"`- IdentityUser *User `json:"identityUser,omitempty" gorm:"foreignKey:IdentityUserID;constraint:OnDelete:CASCADE"`- Role *Role `json:"role,omitempty" gorm:"foreignKey:RoleID;constraint:OnDelete:RESTRICT"`- Environment *Environment `json:"environment,omitempty" gorm:"foreignKey:EnvironmentID;constraint:OnDelete:SET NULL"`-}--func (FederatedCredential) TableName() string {- return "federated_credentials"-}diff --git a/backend/internal/models/federated_token_replay.go b/backend/internal/models/federated_token_replay.godeleted file mode 100644index cae6c530e..000000000--- a/backend/internal/models/federated_token_replay.go+++ /dev/null@@ -1,15 +0,0 @@-package models--import "time"--type FederatedTokenReplay struct {- BaseModel-- TokenHash string `json:"-" gorm:"column:token_hash;not null;uniqueIndex"`- IssuerURL string `json:"issuerUrl" gorm:"column:issuer_url;not null;index"`- ExpiresAt time.Time `json:"expiresAt" gorm:"column:expires_at;not null;index"`-}--func (FederatedTokenReplay) TableName() string {- return "federated_token_replays"-}diff --git a/backend/internal/models/image_build.go b/backend/internal/models/image_build.godeleted file mode 100644index 3998e2270..000000000--- a/backend/internal/models/image_build.go+++ /dev/null@@ -1,51 +0,0 @@-package models--import "time"--type ImageBuildStatus string--const (- ImageBuildStatusRunning ImageBuildStatus = "running"- ImageBuildStatusSuccess ImageBuildStatus = "success"- ImageBuildStatusFailed ImageBuildStatus = "failed"-)--type ImageBuild struct {- BaseModel-- BuildArgs JSON `json:"buildArgs,omitempty" gorm:"column:build_args;type:text"`- Labels JSON `json:"labels,omitempty" gorm:"column:labels;type:text"`- Ulimits JSON `json:"ulimits,omitempty" gorm:"column:ulimits;type:text"`- UserID *string `json:"userId,omitempty" gorm:"column:user_id"`- Username *string `json:"username,omitempty" gorm:"column:username"`- Digest *string `json:"digest,omitempty" gorm:"column:digest"`- ErrorMessage *string `json:"errorMessage,omitempty" gorm:"column:error_message"`- Output *string `json:"output,omitempty" gorm:"column:output;type:text"`- CompletedAt *time.Time `json:"completedAt,omitempty" gorm:"column:completed_at" sortable:"true"`- DurationMs *int64 `json:"durationMs,omitempty" gorm:"column:duration_ms"`- EnvironmentID string `json:"environmentId" gorm:"column:environment_id;index"`- Status ImageBuildStatus `json:"status" gorm:"column:status;index" sortable:"true"`- Provider string `json:"provider,omitempty" gorm:"column:provider"`- ContextDir string `json:"contextDir" gorm:"column:context_dir"`- Dockerfile string `json:"dockerfile,omitempty" gorm:"column:dockerfile"`- Target string `json:"target,omitempty" gorm:"column:target"`- BuildNetwork string `json:"network,omitempty" gorm:"column:build_network"`- Isolation string `json:"isolation,omitempty" gorm:"column:isolation"`- Tags StringSlice `json:"tags,omitempty" gorm:"column:tags;type:text"`- Platforms StringSlice `json:"platforms,omitempty" gorm:"column:platforms;type:text"`- CacheFrom StringSlice `json:"cacheFrom,omitempty" gorm:"column:cache_from;type:text"`- CacheTo StringSlice `json:"cacheTo,omitempty" gorm:"column:cache_to;type:text"`- Entitlements StringSlice `json:"entitlements,omitempty" gorm:"column:entitlements;type:text"`- ExtraHosts StringSlice `json:"extraHosts,omitempty" gorm:"column:extra_hosts;type:text"`- ShmSize int64 `json:"shmSize,omitempty" gorm:"column:shm_size"`- NoCache bool `json:"noCache" gorm:"column:no_cache;default:false"`- Pull bool `json:"pull" gorm:"column:pull;default:false"`- Privileged bool `json:"privileged" gorm:"column:privileged;default:false"`- Push bool `json:"push" gorm:"column:push"`- Load bool `json:"load" gorm:"column:load"`- OutputTruncated bool `json:"outputTruncated" gorm:"column:output_truncated;default:false"`-}--func (ImageBuild) TableName() string {- return "image_builds"-}diff --git a/backend/internal/models/mfa_methods.go b/backend/internal/models/mfa_methods.godeleted file mode 100644index c057fd679..000000000--- a/backend/internal/models/mfa_methods.go+++ /dev/null@@ -1,8 +0,0 @@-package models--const (- // PasskeyMFAMethod and RecoveryCodeMFAMethod name the second factor a login- // completed with, recorded on the session for auditing.- PasskeyMFAMethod = "passkey"- RecoveryCodeMFAMethod = "recovery_code"-)diff --git a/backend/internal/models/project.go b/backend/internal/models/project.godeleted file mode 100644index 46affeaf4..000000000--- a/backend/internal/models/project.go+++ /dev/null@@ -1,37 +0,0 @@-package models--import "time"--type ProjectStatus string--const (- ProjectStatusRunning ProjectStatus = "running"- ProjectStatusStopped ProjectStatus = "stopped"- ProjectStatusPartiallyRunning ProjectStatus = "partially running"- ProjectStatusUnknown ProjectStatus = "unknown"- ProjectStatusDeploying ProjectStatus = "deploying"- ProjectStatusStopping ProjectStatus = "stopping"- ProjectStatusRestarting ProjectStatus = "restarting"-)--type Project struct {- BaseModel-- Name string `json:"name" sortable:"true" gorm:"index:idx_projects_name"`- DirName *string `json:"dir_name"`- Path string `json:"path" sortable:"true" gorm:"uniqueIndex"`- Status ProjectStatus `json:"status" sortable:"true"`- StatusReason *string `json:"status_reason"`- ServiceCount int `json:"service_count" sortable:"true"`- RunningCount int `json:"running_count" sortable:"true"`- GitOpsManagedBy *string `json:"gitops_managed_by,omitempty" gorm:"column:gitops_managed_by"`- ComposeProjectName *string `json:"compose_project_name,omitempty" gorm:"column:compose_project_name"`- ImageRefsJSON string `json:"image_refs_json,omitempty" gorm:"column:image_refs_json"`- BuildImageRefsJSON *string `json:"-" gorm:"column:build_image_refs_json"`- IsArchived bool `json:"is_archived" gorm:"column:is_archived;default:false;index"`- ArchivedAt *time.Time `json:"archived_at,omitempty" gorm:"column:archived_at"`-}--func (Project) TableName() string {- return "projects"-}diff --git a/backend/internal/models/project_tag.go b/backend/internal/models/project_tag.godeleted file mode 100644index f267fa12d..000000000--- a/backend/internal/models/project_tag.go+++ /dev/null@@ -1,14 +0,0 @@-package models--// ProjectTag stores one normalized tag association and its management source.-type ProjectTag struct {- ProjectID string `json:"projectId" gorm:"column:project_id;primaryKey"`- Name string `json:"name" gorm:"column:name;primaryKey"`- Source string `json:"source" gorm:"column:source;primaryKey"`- Color string `json:"color" gorm:"column:color;not null;default:gray"`-}--// TableName returns the database table used for project tag associations.-func (ProjectTag) TableName() string {- return "project_tags"-}diff --git a/backend/internal/models/system_user.go b/backend/internal/models/system_user.godeleted file mode 100644index c0e7bc55e..000000000--- a/backend/internal/models/system_user.go+++ /dev/null@@ -1,8 +0,0 @@-package models--// SystemUser is the actor recorded for work Arcane performs on its own behalf —-// scheduled jobs, startup reconciliation, GitOps syncs — rather than in response-// to a signed-in user.-var SystemUser = User{- Username: "System",-}diff --git a/backend/internal/models/updater.go b/backend/internal/models/updater.godeleted file mode 100644index c517e1096..000000000--- a/backend/internal/models/updater.go+++ /dev/null@@ -1,3 +0,0 @@-package models--// Reserved for future persisted updater state or config overrides specific to the updater module.diff --git a/backend/internal/models/user_session.go b/backend/internal/models/user_session.godeleted file mode 100644index cb03805d7..000000000--- a/backend/internal/models/user_session.go+++ /dev/null@@ -1,32 +0,0 @@-package models--import "time"--const (- UserSessionSourceLocal = "local"- UserSessionSourceOidc = "oidc"- UserSessionSourceFederated = "federated"- UserSessionSourcePasskey = "passkey"-)--type UserSession struct {- BaseModel-- UserID string `json:"userId" gorm:"column:user_id;not null;index"`- User *User `json:"user,omitempty" gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`- RefreshTokenHash string `json:"-" gorm:"column:refresh_token_hash;not null;uniqueIndex"`- UserAgent *string `json:"userAgent,omitempty" gorm:"column:user_agent"`- IPAddress *string `json:"ipAddress,omitempty" gorm:"column:ip_address"`- Source string `json:"source,omitempty" gorm:"column:source"`- FederatedCredentialID *string `json:"federatedCredentialId,omitempty" gorm:"column:federated_credential_id;index"`- FederatedCredential *FederatedCredential `json:"federatedCredential,omitempty" gorm:"foreignKey:FederatedCredentialID;constraint:OnDelete:SET NULL"`- LastUsedAt time.Time `json:"lastUsedAt" gorm:"column:last_used_at;not null"`- ExpiresAt time.Time `json:"expiresAt" gorm:"column:expires_at;not null;index"`- RevokedAt *time.Time `json:"revokedAt,omitempty" gorm:"column:revoked_at"`- MFAMethod *string `json:"mfaMethod,omitempty" gorm:"column:mfa_method"`- MFAVerifiedAt *time.Time `json:"mfaVerifiedAt,omitempty" gorm:"column:mfa_verified_at"`-}--func (UserSession) TableName() string {- return "user_sessions"-}diff --git a/backend/internal/models/vulnerability_ignore.go b/backend/internal/models/vulnerability_ignore.godeleted file mode 100644index 4c1e530f7..000000000--- a/backend/internal/models/vulnerability_ignore.go+++ /dev/null@@ -1,59 +0,0 @@-package models--import (- "time"-- "github.com/google/uuid"- "gorm.io/gorm"-)--// VulnerabilityIgnore stores ignored vulnerability records-type VulnerabilityIgnore struct {- // ID is the unique identifier for this ignore record- ID string `json:"id" gorm:"primaryKey;type:text"`-- // EnvironmentID is the environment where this ignore applies- EnvironmentID string `json:"environmentId" gorm:"column:environment_id;index"`-- // ImageID is the Docker image ID- ImageID string `json:"imageId" gorm:"column:image_id;index"`-- // VulnerabilityID is the CVE or vulnerability identifier (e.g., CVE-2023-1234)- VulnerabilityID string `json:"vulnerabilityId" gorm:"column:vulnerability_id;index"`-- // PkgName is the package name containing the vulnerability- PkgName string `json:"pkgName" gorm:"column:pkg_name"`-- // InstalledVersion is the version of the package with the vulnerability- InstalledVersion string `json:"installedVersion" gorm:"column:installed_version"`-- // Reason is an optional reason for ignoring this vulnerability- Reason *string `json:"reason,omitempty" gorm:"column:reason"`-- // CreatedBy is the user ID who created this ignore record- CreatedBy string `json:"createdBy" gorm:"column:created_by"`-- // CreatedAt is when this ignore record was created- CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`-}--func (v *VulnerabilityIgnore) TableName() string {- return "vulnerability_ignores"-}--// BeforeCreate sets the ID and CreatedAt before inserting-func (v *VulnerabilityIgnore) BeforeCreate(db *gorm.DB) error {- if v.ID == "" {- v.ID = uuid.New().String()- }- if v.CreatedAt.IsZero() {- v.CreatedAt = time.Now()- }- return nil-}--// CompositeKey generates a composite key for deduplication.-// This helps prevent duplicate ignore records for the same vulnerability.-func (v *VulnerabilityIgnore) CompositeKey() string {- return v.EnvironmentID + ":" + v.ImageID + ":" + v.VulnerabilityID + ":" + v.PkgName + ":" + v.InstalledVersion-}diff --git a/backend/internal/network/handler.go b/backend/internal/network/handler.goindex 7a2f89489..760973dd2 100644--- a/backend/internal/network/handler.go+++ b/backend/internal/network/handler.go@@ -1,6 +1,8 @@package networkimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"bytes""context""net"@@ -8,12 +10,13 @@ import ("sort""strings"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -224,7 +227,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "network",ResourceID: input.Body.Name,ResourceName: input.Body.Name,@@ -232,7 +235,7 @@ func (h *NetworkHandler) CreateNetwork(ctx context.Context, input *CreateNetworkStep: "Creating network",Message: "Creating network",SuccessMessage: "Network created successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "create_network","driver": input.Body.Options.Driver,},@@ -370,7 +373,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "network",ResourceID: input.NetworkID,ResourceName: input.NetworkID,@@ -378,7 +381,7 @@ func (h *NetworkHandler) DeleteNetwork(ctx context.Context, input *DeleteNetworkStep: "Removing network",Message: "Removing network",SuccessMessage: "Network removed successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "remove_network",},}, func(runtimeCtx context.Context) error {@@ -401,12 +404,12 @@ func (h *NetworkHandler) PruneNetworks(ctx context.Context, input *PruneNetworksruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "network",Step: "Pruning unused networks",Message: "Pruning unused networks",SuccessMessage: "Networks pruned successfully",- Metadata: models.JSON{"action": "prune_networks"},+ Metadata: database.JSON{"action": "prune_networks"},}, func(runtimeCtx context.Context) error {var pruneErr errorreport, pruneErr = h.networkService.PruneNetworks(runtimeCtx)diff --git a/backend/internal/network/service.go b/backend/internal/network/service.goindex 9b2f4ea45..c4d61146b 100644--- a/backend/internal/network/service.go+++ b/backend/internal/network/service.go@@ -1,6 +1,8 @@package networkimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""log/slog"@@ -11,7 +13,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -176,25 +177,25 @@ func (s *NetworkService) GetNetworkTopology(ctx context.Context) (*networktypes.return topology, nil}-func (s *NetworkService) CreateNetwork(ctx context.Context, name string, options client.NetworkCreateOptions, user models.User) (*network.CreateResponse, error) {+func (s *NetworkService) CreateNetwork(ctx context.Context, name string, options client.NetworkCreateOptions, user common.User) (*network.CreateResponse, error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})return nil, errors.WrapIf(err, "failed to connect to Docker")}response, err := dockerClient.NetworkCreate(ctx, name, options)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", "", name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})return nil, errors.WrapIf(err, "failed to create network")}- metadata := models.JSON{+ metadata := database.JSON{"action": "create","driver": options.Driver,"name": name,}- if logErr := s.eventService.LogNetworkEvent(ctx, models.EventTypeNetworkCreate, response.ID, name, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogNetworkEvent(ctx, event.EventTypeNetworkCreate, response.ID, name, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log network creation action", "error", logErr)}@@ -211,10 +212,10 @@ func (s *NetworkService) CreateNetwork(ctx context.Context, name string, optionsreturn &out, nil}-func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user models.User) error {+func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user common.User) error {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", id, "", user.ID, user.Username, "0", err, models.JSON{"action": "delete"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", id, "", user.ID, user.Username, "0", err, database.JSON{"action": "delete"})return errors.WrapIf(err, "failed to connect to Docker")}@@ -227,15 +228,15 @@ func (s *NetworkService) RemoveNetwork(ctx context.Context, id string, user mode}if _, err := dockerClient.NetworkRemove(ctx, id, client.NetworkRemoveOptions{}); err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeNetworkError, "network", id, networkName, user.ID, user.Username, "0", err, models.JSON{"action": "delete"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeNetworkError, "network", id, networkName, user.ID, user.Username, "0", err, database.JSON{"action": "delete"})return errors.WrapIf(err, "failed to remove network")}- metadata := models.JSON{+ metadata := database.JSON{"action": "delete","networkId": id,}- if logErr := s.eventService.LogNetworkEvent(ctx, models.EventTypeNetworkDelete, id, networkName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogNetworkEvent(ctx, event.EventTypeNetworkDelete, id, networkName, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log network delete action", "error", logErr)}@@ -256,11 +257,11 @@ func (s *NetworkService) PruneNetworks(ctx context.Context) (*network.PruneRepor}pruneReport := report.Report- metadata := models.JSON{+ metadata := database.JSON{"action": "prune","networksDeleted": len(pruneReport.NetworksDeleted),}- if logErr := s.eventService.LogNetworkEvent(ctx, models.EventTypeNetworkDelete, "", "bulk_prune", models.SystemUser.ID, models.SystemUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogNetworkEvent(ctx, event.EventTypeNetworkDelete, "", "bulk_prune", common.SystemUser.ID, common.SystemUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log network prune action", "error", logErr)}diff --git a/backend/internal/notification/handler.go b/backend/internal/notification/handler.goindex a5e8ad2a4..71b43e568 100644--- a/backend/internal/notification/handler.go+++ b/backend/internal/notification/handler.go@@ -1,6 +1,12 @@package notificationimport (+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""net/http""strings"@@ -10,7 +16,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"@@ -186,7 +191,7 @@ func (h *NotificationHandler) GetNotificationSettings(ctx context.Context, inputif err := h.rejectIfAgentModeInternal(); err != nil {return nil, err}- provider := models.NotificationProvider(input.Provider)+ provider := notifications.NotificationProvider(input.Provider)settings, err := h.notificationService.GetSettingsByProvider(ctx, provider)if err != nil {@@ -207,8 +212,8 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Conif err := h.rejectIfAgentModeInternal(); err != nil {return nil, err}- provider := models.NotificationProvider(input.Body.Provider)- if !models.IsValidNotificationProvider(provider) {+ provider := notifications.NotificationProvider(input.Body.Provider)+ if !notifications.IsValidNotificationProvider(provider) {return nil, huma.Error400BadRequest("invalid provider")}@@ -216,10 +221,10 @@ func (h *NotificationHandler) CreateOrUpdateNotificationSettings(ctx context.Conctx,provider,input.Body.Enabled,- models.JSON(input.Body.Config),+ database.JSON(input.Body.Config),)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)if apiErr.HTTPStatus() == http.StatusInternalServerError {return nil, huma.Error500InternalServerError("Failed to update notification settings")}@@ -240,7 +245,7 @@ func (h *NotificationHandler) DeleteNotificationSettings(ctx context.Context, inif err := h.rejectIfAgentModeInternal(); err != nil {return nil, err}- provider := models.NotificationProvider(input.Provider)+ provider := notifications.NotificationProvider(input.Provider)if err := h.notificationService.DeleteSettings(ctx, provider); err != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to delete notification settings").Error())@@ -258,7 +263,7 @@ func (h *NotificationHandler) TestNotification(ctx context.Context, input *TestNif err := h.rejectIfAgentModeInternal(); err != nil {return nil, err}- provider := models.NotificationProvider(input.Provider)+ provider := notifications.NotificationProvider(input.Provider)testType := normalizeNotificationTestType(input.Type)if !isSupportedNotificationTestType(testType) {return nil, huma.Error400BadRequest("invalid notification test type")diff --git a/backend/internal/notification/model.go b/backend/internal/notification/model.gonew file mode 100644index 000000000..d278ca60f--- /dev/null+++ b/backend/internal/notification/model.go@@ -0,0 +1,21 @@+package notification++import (+ "time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"+)++type NotificationSettings struct {+ ID uint `json:"id" gorm:"primaryKey"`+ Provider notifications.NotificationProvider `json:"provider" gorm:"not null;index;type:varchar(50)"`+ Enabled bool `json:"enabled" gorm:"default:false"`+ Config database.JSON `json:"config" gorm:"type:jsonb"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`+}++func (NotificationSettings) TableName() string {+ return "notification_settings"+}diff --git a/backend/internal/notification/notification.go b/backend/internal/notification/notification.goindex 819004962..126cd6ad5 100644--- a/backend/internal/notification/notification.go+++ b/backend/internal/notification/notification.go@@ -22,7 +22,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation"@@ -33,27 +32,27 @@ import ("go.getarcane.app/sys/crypto")-var notificationCredentialFieldsByProviderInternal = map[models.NotificationProvider][]string{- models.NotificationProviderDiscord: {"token"},- models.NotificationProviderEmail: {"smtpPassword"},- models.NotificationProviderTelegram: {"botToken"},- models.NotificationProviderSignal: {"password", "token"},- models.NotificationProviderSlack: {"token"},- models.NotificationProviderNtfy: {"password"},- models.NotificationProviderPushover: {"token"},- models.NotificationProviderGotify: {"token"},- models.NotificationProviderMatrix: {"password"},+var notificationCredentialFieldsByProviderInternal = map[notifications.NotificationProvider][]string{+ notifications.NotificationProviderDiscord: {"token"},+ notifications.NotificationProviderEmail: {"smtpPassword"},+ notifications.NotificationProviderTelegram: {"botToken"},+ notifications.NotificationProviderSignal: {"password", "token"},+ notifications.NotificationProviderSlack: {"token"},+ notifications.NotificationProviderNtfy: {"password"},+ notifications.NotificationProviderPushover: {"token"},+ notifications.NotificationProviderGotify: {"token"},+ notifications.NotificationProviderMatrix: {"password"},// The Google Chat incoming webhook URL embeds the key and token query// parameters, so the whole URL is treated as a credential.- models.NotificationProviderGoogleChat: {"webhookUrl"},+ notifications.NotificationProviderGoogleChat: {"webhookUrl"},}-var notificationTargetFieldByProviderInternal = map[models.NotificationProvider]string{- models.NotificationProviderEmail: "smtpHost",- models.NotificationProviderSignal: "host",- models.NotificationProviderNtfy: "host",- models.NotificationProviderGotify: "host",- models.NotificationProviderMatrix: "host",+var notificationTargetFieldByProviderInternal = map[notifications.NotificationProvider]string{+ notifications.NotificationProviderEmail: "smtpHost",+ notifications.NotificationProviderSignal: "host",+ notifications.NotificationProviderNtfy: "host",+ notifications.NotificationProviderGotify: "host",+ notifications.NotificationProviderMatrix: "host",}const ErrUnauthorizedNotificationDispatch = errors.Sentinel("unauthorized notification dispatch")@@ -253,7 +252,7 @@ func (s *NotificationService) dispatchForTargetInternal(ctx context.Context, tarreturn notificationdto.DispatchResponse{}, errors.New("image update payload is required")}logManagerDispatchNotificationInternal(ctx, target, payload.Kind)- dispatchResponse.Delivered, err = s.sendImageUpdateNotificationForTargetInternal(ctx, target, payload.ImageUpdate.ImageRef, &payload.ImageUpdate.UpdateInfo, models.NotificationEventImageUpdate)+ dispatchResponse.Delivered, err = s.sendImageUpdateNotificationForTargetInternal(ctx, target, payload.ImageUpdate.ImageRef, &payload.ImageUpdate.UpdateInfo, notifications.NotificationEventImageUpdate)return dispatchResponse, errcase notificationdto.DispatchKindBatchImageUpdate:if payload.BatchImageUpdate == nil {@@ -299,25 +298,25 @@ func (s *NotificationService) dispatchForTargetInternal(ctx context.Context, tar}}-func (s *NotificationService) GetAllSettings(ctx context.Context) ([]models.NotificationSettings, error) {- var settings []models.NotificationSettings+func (s *NotificationService) GetAllSettings(ctx context.Context) ([]NotificationSettings, error) {+ var settings []NotificationSettingsif err := s.db.WithContext(ctx).Find(&settings).Error; err != nil {return nil, errors.WrapIf(err, "failed to get notification settings")}return settings, nil}-func (s *NotificationService) GetSettingsByProvider(ctx context.Context, provider models.NotificationProvider) (*models.NotificationSettings, error) {- var setting models.NotificationSettings+func (s *NotificationService) GetSettingsByProvider(ctx context.Context, provider notifications.NotificationProvider) (*NotificationSettings, error) {+ var setting NotificationSettingsif err := s.db.WithContext(ctx).Where("provider = ?", provider).First(&setting).Error; err != nil {return nil, err}return &setting, nil}-func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provider models.NotificationProvider, enabled bool, config models.JSON) (*models.NotificationSettings, error) {- if provider == models.NotificationProviderGeneric {- genericConfig, decodeErr := notifications.DecodeConfig[models.GenericConfig](config, "Generic")+func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provider notifications.NotificationProvider, enabled bool, config database.JSON) (*NotificationSettings, error) {+ if provider == notifications.NotificationProviderGeneric {+ genericConfig, decodeErr := notifications.DecodeConfig[notifications.GenericConfig](config, "Generic")if decodeErr != nil {return nil, decodeErr}@@ -329,10 +328,10 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provid}}- var setting models.NotificationSettings+ var setting NotificationSettingserr := s.db.WithContext(ctx).Where("provider = ?", provider).First(&setting).Error- existingConfig := models.JSON(nil)+ existingConfig := database.JSON(nil)if err == nil {existingConfig = setting.Config}@@ -344,7 +343,7 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, providconfig = encryptedConfigif err != nil {- setting = models.NotificationSettings{+ setting = NotificationSettings{Provider: provider,Enabled: enabled,Config: config,@@ -364,7 +363,7 @@ func (s *NotificationService) CreateOrUpdateSettings(ctx context.Context, provid}// RedactNotificationConfigCredentials returns a copy of config with provider credential fields blanked for API responses.-func RedactNotificationConfigCredentials(provider models.NotificationProvider, config models.JSON) models.JSON {+func RedactNotificationConfigCredentials(provider notifications.NotificationProvider, config database.JSON) database.JSON {redacted := cloneNotificationConfigInternal(config)for _, field := range notificationCredentialFieldsByProviderInternal[provider] {value, ok := redacted[field]@@ -380,13 +379,13 @@ func RedactNotificationConfigCredentials(provider models.NotificationProvider, creturn redacted}-func encryptNotificationConfigCredentialsInternal(provider models.NotificationProvider, config models.JSON, existingConfig models.JSON) (models.JSON, error) {+func encryptNotificationConfigCredentialsInternal(provider notifications.NotificationProvider, config database.JSON, existingConfig database.JSON) (database.JSON, error) {encryptedConfig := cloneNotificationConfigInternal(config)preserveConfig := existingConfig- if provider == models.NotificationProviderSignal {+ if provider == notifications.NotificationProviderSignal {preserveConfig = signalCredentialPreservationConfigInternal(config, existingConfig)}- if provider == models.NotificationProviderEmail {+ if provider == notifications.NotificationProviderEmail {preserveConfig = emailCredentialPreservationConfigInternal(config, existingConfig)}if targetField := notificationTargetFieldByProviderInternal[provider]; targetField != "" {@@ -437,7 +436,7 @@ func encryptNotificationConfigCredentialsInternal(provider models.NotificationPrreturn encryptedConfig, nil}-func signalCredentialPreservationConfigInternal(config models.JSON, existingConfig models.JSON) models.JSON {+func signalCredentialPreservationConfigInternal(config database.JSON, existingConfig database.JSON) database.JSON {preserveConfig := cloneNotificationConfigInternal(existingConfig)user, _ := config["user"].(string)password, _ := config["password"].(string)@@ -453,9 +452,9 @@ func signalCredentialPreservationConfigInternal(config models.JSON, existingConfreturn preserveConfig}-func emailCredentialPreservationConfigInternal(config models.JSON, existingConfig models.JSON) models.JSON {+func emailCredentialPreservationConfigInternal(config database.JSON, existingConfig database.JSON) database.JSON {preserveConfig := cloneNotificationConfigInternal(existingConfig)- if authMode, _ := config["authMode"].(string); authMode == string(models.EmailAuthModeNone) {+ if authMode, _ := config["authMode"].(string); authMode == string(notifications.EmailAuthModeNone) {delete(preserveConfig, "smtpPassword")}return preserveConfig@@ -471,17 +470,17 @@ func encryptNotificationCredentialInternal(value string) (string, error) {return crypto.Encrypt(value)}-func cloneNotificationConfigInternal(config models.JSON) models.JSON {+func cloneNotificationConfigInternal(config database.JSON) database.JSON {if config == nil {- return models.JSON{}+ return database.JSON{}}- cloned := make(models.JSON, len(config))+ cloned := make(database.JSON, len(config))maps.Copy(cloned, config)return cloned}-func (s *NotificationService) DeleteSettings(ctx context.Context, provider models.NotificationProvider) error {- if err := s.db.WithContext(ctx).Where("provider = ?", provider).Delete(&models.NotificationSettings{}).Error; err != nil {+func (s *NotificationService) DeleteSettings(ctx context.Context, provider notifications.NotificationProvider) error {+ if err := s.db.WithContext(ctx).Where("provider = ?", provider).Delete(&NotificationSettings{}).Error; err != nil {return errors.WrapIf(err, "failed to delete notification settings")}return nil@@ -489,7 +488,7 @@ func (s *NotificationService) DeleteSettings(ctx context.Context, provider model// SendImageUpdateNotification dispatches a single-image update notification and-func (s *NotificationService) isEventEnabled(config models.JSON, eventType models.NotificationEventType) bool {+func (s *NotificationService) isEventEnabled(config database.JSON, eventType notifications.NotificationEventType) bool {events, ok := config["events"].(map[string]any)if !ok {return true // If no events config, default to enabled@@ -505,16 +504,16 @@ func (s *NotificationService) isEventEnabled(config models.JSON, eventType model// logNotification records a delivery attempt in the event log so sends and// failures are visible alongside every other Arcane event.-func (s *NotificationService) logNotification(ctx context.Context, environmentID string, provider models.NotificationProvider, subject, status string, errMsg *string, metadata models.JSON) {+func (s *NotificationService) logNotification(ctx context.Context, environmentID string, provider notifications.NotificationProvider, subject, status string, errMsg *string, metadata database.JSON) {if s.eventSvc == nil {return}- severity := models.EventSeveritySuccess+ severity := event.EventSeveritySuccesstitle := fmt.Sprintf("Notification sent via %s", provider)description := subjectif errMsg != nil {- severity = models.EventSeverityError+ severity = event.EventSeverityErrortitle = fmt.Sprintf("Notification failed via %s", provider)description = fmt.Sprintf("%s: %s", subject, *errMsg)}@@ -526,7 +525,7 @@ func (s *NotificationService) logNotification(ctx context.Context, environmentIDresourceType := "notification"providerName := string(provider)if _, err := s.eventSvc.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeNotificationSend,+ Type: event.EventTypeNotificationSend,Severity: severity,Title: title,Description: description,@@ -550,10 +549,10 @@ func (s *NotificationService) logNotification(ctx context.Context, environmentIDfunc (s *NotificationService) notifyEnabledProvidersInternal(ctx context.Context,target NotificationTarget,- eventType models.NotificationEventType,+ eventType notifications.NotificationEventType,logRef string,- metadata models.JSON,- dispatch func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (handled bool, err error),+ metadata database.JSON,+ dispatch func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (handled bool, err error),) (int, error) {settings, err := s.GetAllSettings(ctx)if err != nil {@@ -590,7 +589,7 @@ func (s *NotificationService) notifyEnabledProvidersInternal(return delivered, nil}-func collectNotificationSendResultInternal(errors *[]string, provider models.NotificationProvider, sendErr error) (string, *string) {+func collectNotificationSendResultInternal(errors *[]string, provider notifications.NotificationProvider, sendErr error) (string, *string) {if sendErr == nil {return "success", nil}@@ -765,7 +764,7 @@ func (s *NotificationService) autoHealNotificationContentInternal(environmentNam// SendImageUpdateNotification dispatches a single-image update notification and// returns the number of eligible providers it was delivered to (0 means no// provider has this event enabled, so callers must not mark the update notified).-func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, eventType models.NotificationEventType) (int, error) {+func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, imageRef string, updateInfo *imageupdate.Response, eventType notifications.NotificationEventType) (int, error) {if updateInfo == nil {return 0, errors.New("updateInfo is required")}@@ -792,8 +791,8 @@ func (s *NotificationService) SendImageUpdateNotification(ctx context.Context, ireturn s.sendImageUpdateNotificationForTargetInternal(ctx, target, imageRef, updateInfo, eventType)}-func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, imageRef string, updateInfo *imageupdate.Response, eventType models.NotificationEventType) (int, error) {- metadata := models.JSON{+func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, imageRef string, updateInfo *imageupdate.Response, eventType notifications.NotificationEventType) (int, error) {+ metadata := database.JSON{"hasUpdate": updateInfo.HasUpdate,"currentDigest": updateInfo.CurrentDigest,"latestDigest": updateInfo.LatestDigest,@@ -802,7 +801,7 @@ func (s *NotificationService) sendImageUpdateNotificationForTargetInternal(ctx c}content := s.imageUpdateNotificationContentInternal(target.EnvironmentName, imageRef, updateInfo)content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, eventType)- return s.notifyEnabledProvidersInternal(ctx, target, eventType, imageRef, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {+ return s.notifyEnabledProvidersInternal(ctx, target, eventType, imageRef, metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})}@@ -830,15 +829,15 @@ func (s *NotificationService) SendContainerUpdateNotification(ctx context.Contex}func (s *NotificationService) sendContainerUpdateNotificationForTargetInternal(ctx context.Context, target NotificationTarget, containerName, imageRef, oldDigest, newDigest string) error {- metadata := models.JSON{+ metadata := database.JSON{"containerName": containerName,"oldDigest": oldDigest,"newDigest": newDigest,- "eventType": string(models.NotificationEventContainerUpdate),+ "eventType": string(notifications.NotificationEventContainerUpdate),}content := s.containerUpdateNotificationContentInternal(target.EnvironmentName, containerName, imageRef, oldDigest, newDigest)- content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventContainerUpdate)- _, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventContainerUpdate, imageRef, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventContainerUpdate)+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventContainerUpdate, imageRef, metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})return err@@ -881,15 +880,15 @@ func (s *NotificationService) SendVulnerabilityNotification(ctx context.Context,}func (s *NotificationService) sendVulnerabilityNotificationForTargetInternal(ctx context.Context, target NotificationTarget, payload VulnerabilityNotificationPayload) error {- metadata := models.JSON{+ metadata := database.JSON{"cveId": payload.CVEID,"severity": payload.Severity,"fixedVersion": payload.FixedVersion,- "eventType": string(models.NotificationEventVulnerabilityFound),+ "eventType": string(notifications.NotificationEventVulnerabilityFound),}content := s.vulnerabilityNotificationContentInternal(target.EnvironmentName, payload)- content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventVulnerabilityFound)- _, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventVulnerabilityFound, payload.ImageName, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventVulnerabilityFound)+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventVulnerabilityFound, payload.ImageName, metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})return err@@ -947,14 +946,14 @@ func (s *NotificationService) sendBatchImageUpdateNotificationForTargetInternal(imageRefs = append(imageRefs, ref)}- metadata := models.JSON{+ metadata := database.JSON{"updateCount": len(updatesWithChanges),- "eventType": string(models.NotificationEventImageUpdate),+ "eventType": string(notifications.NotificationEventImageUpdate),"batch": true,}content := s.batchImageUpdateNotificationContentInternal(target.EnvironmentName, updatesWithChanges)- content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventImageUpdate)- return s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventImageUpdate, strings.Join(imageRefs, ", "), metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventImageUpdate)+ return s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventImageUpdate, strings.Join(imageRefs, ", "), metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})}@@ -994,13 +993,13 @@ func (s *NotificationService) sendPruneReportNotificationForTargetInternal(ctx chasChanges := pruneResultHasChangesInternal(result)hasErrors := len(result.Errors) > 0- metadata := models.JSON{+ metadata := database.JSON{"spaceReclaimed": result.SpaceReclaimed,- "eventType": string(models.NotificationEventPruneReport),+ "eventType": string(notifications.NotificationEventPruneReport),}content := s.pruneReportNotificationContentInternal(target.EnvironmentName, result)- content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventPruneReport)- _, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventPruneReport, "System Prune Report", metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventPruneReport)+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventPruneReport, "System Prune Report", metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})if err != nil {@@ -1050,13 +1049,13 @@ func (s *NotificationService) SendAutoHealNotification(ctx context.Context, cont}func (s *NotificationService) sendAutoHealNotificationForTargetInternal(ctx context.Context, target NotificationTarget, containerName, containerID string) error {- metadata := models.JSON{+ metadata := database.JSON{"containerID": containerID,- "eventType": string(models.NotificationEventAutoHeal),+ "eventType": string(notifications.NotificationEventAutoHeal),}content := s.autoHealNotificationContentInternal(target.EnvironmentName, containerName)- content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, models.NotificationEventAutoHeal)- _, err := s.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventAutoHeal, containerName, metadata, func(ctx context.Context, provider models.NotificationProvider, config models.JSON) (bool, error) {+ content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, notifications.NotificationEventAutoHeal)+ _, err := s.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventAutoHeal, containerName, metadata, func(ctx context.Context, provider notifications.NotificationProvider, config database.JSON) (bool, error) {return notifications.Deliver(ctx, provider, config, content)})return err@@ -1066,16 +1065,16 @@ func (s *NotificationService) sendAutoHealNotificationForTargetInternal(ctx cont// notificationEventTypeForTestTypeInternal maps a test type to the event type a// real notification of that kind would be gated on ("" = no event gate).-func notificationEventTypeForTestTypeInternal(testType string) models.NotificationEventType {+func notificationEventTypeForTestTypeInternal(testType string) notifications.NotificationEventType {switch testType {case notificationTestTypeImageUpdate, notificationTestTypeBatchImageUpdate:- return models.NotificationEventImageUpdate+ return notifications.NotificationEventImageUpdatecase notificationTestTypeVulnerability:- return models.NotificationEventVulnerabilityFound+ return notifications.NotificationEventVulnerabilityFoundcase notificationTestTypePruneReport:- return models.NotificationEventPruneReport+ return notifications.NotificationEventPruneReportcase notificationTestTypeAutoHeal:- return models.NotificationEventAutoHeal+ return notifications.NotificationEventAutoHealdefault:return ""}@@ -1084,7 +1083,7 @@ func notificationEventTypeForTestTypeInternal(testType string) models.Notificati// testNotificationWarningInternal reports why a real notification would not send// even though the test did: the provider is disabled, or the tested event type is// unsubscribed. Empty means real notifications would send.-func (s *NotificationService) testNotificationWarningInternal(setting *models.NotificationSettings, testType string) string {+func (s *NotificationService) testNotificationWarningInternal(setting *NotificationSettings, testType string) string {if !setting.Enabled {return fmt.Sprintf("%s is disabled, so real notifications will not send", setting.Provider)}@@ -1166,7 +1165,7 @@ func (s *NotificationService) testNotificationContentInternal(environmentName, t// TestNotification sends a test message to the provider regardless of its enabled// state (testing before enabling is legitimate) and returns a warning when a real// notification of the tested kind would not send.-func (s *NotificationService) TestNotification(ctx context.Context, environmentID string, provider models.NotificationProvider, testType string) (string, error) {+func (s *NotificationService) TestNotification(ctx context.Context, environmentID string, provider notifications.NotificationProvider, testType string) (string, error) {setting, err := s.GetSettingsByProvider(ctx, provider)if err != nil {return "", errors.Errorf("please save your %s settings before testing", provider)@@ -1185,7 +1184,7 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentIreturn "", err}- if provider == models.NotificationProviderEmail && testType == notificationTestTypeSimple {+ if provider == notifications.NotificationProviderEmail && testType == notificationTestTypeSimple {return warning, s.sendTestEmail(ctx, target.EnvironmentName, setting.Config)}@@ -1195,7 +1194,7 @@ func (s *NotificationService) TestNotification(ctx context.Context, environmentI// reports that event type.testEventType := notificationEventTypeForTestTypeInternal(testType)if testEventType == "" {- testEventType = models.NotificationEventImageUpdate+ testEventType = notifications.NotificationEventImageUpdate}content.Vars = notifications.EventVars(target.EnvironmentName, target.EnvironmentID, testEventType)handled, sendErr := notifications.Deliver(ctx, provider, setting.Config, content)@@ -1302,8 +1301,8 @@ func (s *NotificationService) renderContainerUpdateEmailTemplate(environmentNamereturn htmlBuf.String(), textBuf.String(), nil}-func (s *NotificationService) sendTestEmail(ctx context.Context, environmentName string, config models.JSON) error {- var emailConfig models.EmailConfig+func (s *NotificationService) sendTestEmail(ctx context.Context, environmentName string, config database.JSON) error {+ var emailConfig notifications.EmailConfigconfigBytes, err := json.Marshal(config)if err != nil {return errors.WrapIf(err, "failed to marshal email config")diff --git a/backend/internal/notification/service_test.go b/backend/internal/notification/service_test.goindex 9b5b70b8d..c1cf1fa68 100644--- a/backend/internal/notification/service_test.go+++ b/backend/internal/notification/service_test.go@@ -1,6 +1,8 @@package notificationimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"bytes""context""encoding/base64"@@ -23,7 +25,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications""github.com/getarcaneapp/arcane/types/v2/imageupdate"notificationdto "github.com/getarcaneapp/arcane/types/v2/notification"@@ -36,7 +37,7 @@ func setupNotificationTestDB(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.NotificationSettings{}, &models.SettingVariable{}, &models.Environment{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&NotificationSettings{}, &settings.SettingVariable{}, &environment.Environment{}, &event.Event{}))// Initialize crypto for tests (requires 32+ byte key)testCfg := &config.Config{@@ -99,12 +100,12 @@ func TestNotificationService_ResolveNotificationTargetInternal_UsesEnvironmentRerequire.Equal(t, "Local Docker", target.EnvironmentName)now := time.Now()- require.NoError(t, db.WithContext(ctx).Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},+ require.NoError(t, db.WithContext(ctx).Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},Name: "Remote Alpha",ApiUrl: "http://remote.example",Enabled: true,- Status: string(models.EnvironmentStatusOnline),+ Status: string(environment.EnvironmentStatusOnline),}).Error)target, err = svc.resolveNotificationTargetInternal(ctx, "env-remote")@@ -119,12 +120,12 @@ func TestNotificationService_ResolveNotificationTargetForAccessTokenInternal_Usetoken := "remote-token"now := time.Now()- require.NoError(t, db.WithContext(ctx).Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},+ require.NoError(t, db.WithContext(ctx).Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},Name: "Remote Edge",ApiUrl: "http://remote.example",Enabled: true,- Status: string(models.EnvironmentStatusOnline),+ Status: string(environment.EnvironmentStatusOnline),AccessToken: &token,}).Error)@@ -156,12 +157,12 @@ func TestNotificationService_DispatchNotification_UnsupportedKindReturnsSentineltoken := "remote-token"now := time.Now()- require.NoError(t, db.WithContext(ctx).Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},+ require.NoError(t, db.WithContext(ctx).Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},Name: "Remote Edge",ApiUrl: "http://remote.example",Enabled: true,- Status: string(models.EnvironmentStatusOnline),+ Status: string(environment.EnvironmentStatusOnline),AccessToken: &token,}).Error)@@ -183,12 +184,12 @@ func TestNotificationService_DispatchNotification_LogsManagerDispatchForAgent(ttoken := "remote-token"now := time.Now()- require.NoError(t, db.WithContext(ctx).Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},+ require.NoError(t, db.WithContext(ctx).Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-remote", CreatedAt: now, UpdatedAt: &now},Name: "Remote Edge",ApiUrl: "http://remote.example",Enabled: true,- Status: string(models.EnvironmentStatusOnline),+ Status: string(environment.EnvironmentStatusOnline),AccessToken: &token,}).Error)@@ -250,7 +251,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeDispatchesToMaManagerApiUrl: server.URL,}, envSvc, nil)- delivered, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", newNotificationTestUpdateInfoInternal(), models.NotificationEventImageUpdate)+ delivered, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", newNotificationTestUpdateInfoInternal(), notifications.NotificationEventImageUpdate)require.NoError(t, err)require.Equal(t, 2, delivered)require.EqualValues(t, 1, calls.Load())@@ -317,7 +318,7 @@ func TestNotificationService_SendImageUpdateNotification_AgentModeRequiresUpdateAgentMode: true,}, envSvc, nil)- _, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", nil, models.NotificationEventImageUpdate)+ _, err := svc.SendImageUpdateNotification(ctx, "nginx:latest", nil, notifications.NotificationEventImageUpdate)require.Error(t, err)require.Contains(t, err.Error(), "updateInfo is required")}@@ -555,15 +556,15 @@ func TestNotificationService_CreateOrUpdateSettingsEncryptsCredentialFieldsInterdb := setupNotificationTestDB(t)svc := NewNotificationService(db, &config.Config{}, nil, nil)- _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderDiscord, true, models.JSON{+ _, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderDiscord, true, database.JSON{"webhookId": "123456789","token": "discord-secret-token","username": "Arcane",})require.NoError(t, err)- var stored models.NotificationSettings- require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderDiscord).First(&stored).Error)+ var stored NotificationSettings+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", notifications.NotificationProviderDiscord).First(&stored).Error)require.Equal(t, "123456789", stored.Config["webhookId"])require.Equal(t, "Arcane", stored.Config["username"])require.NotEqual(t, "discord-secret-token", stored.Config["token"])@@ -578,22 +579,22 @@ func TestNotificationService_CreateOrUpdateSettingsPreservesStoredCredentialWhendb := setupNotificationTestDB(t)svc := NewNotificationService(db, &config.Config{}, nil, nil)- _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{+ _, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{"host": "gotify.example","token": "initial-gotify-token","title": "Initial",})require.NoError(t, err)- _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{+ _, err = svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{"host": "gotify.example","token": "","title": "Updated",})require.NoError(t, err)- var stored models.NotificationSettings- require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderGotify).First(&stored).Error)+ var stored NotificationSettings+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", notifications.NotificationProviderGotify).First(&stored).Error)require.Equal(t, "Updated", stored.Config["title"])decrypted, err := crypto.Decrypt(stored.Config["token"].(string))@@ -606,7 +607,7 @@ func TestNotificationService_CreateOrUpdateSettingsRejectsTargetChangeWithStoreddb := setupNotificationTestDB(t)svc := NewNotificationService(db, &config.Config{}, nil, nil)- created, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{+ created, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{"host": "gotify.example","port": 443,"token": "initial-gotify-token",@@ -614,19 +615,19 @@ func TestNotificationService_CreateOrUpdateSettingsRejectsTargetChangeWithStoredrequire.NoError(t, err)originalToken := created.Config["token"]- _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{+ _, err = svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{"host": "attacker.example","port": 443,"token": "",})require.ErrorIs(t, err, common.ErrValidation)- var stored models.NotificationSettings- require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderGotify).First(&stored).Error)+ var stored NotificationSettings+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", notifications.NotificationProviderGotify).First(&stored).Error)require.Equal(t, "gotify.example", stored.Config["host"])require.Equal(t, originalToken, stored.Config["token"])- updated, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{+ updated, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{"host": "gotify.example","port": 8443,"token": "",@@ -641,22 +642,22 @@ func TestNotificationService_CreateOrUpdateSettingsClearsEmailPasswordWhenAuthModb := setupNotificationTestDB(t)svc := NewNotificationService(db, &config.Config{}, nil, nil)- _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderEmail, true, models.JSON{+ _, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderEmail, true, database.JSON{"smtpHost": "smtp.example","smtpPassword": "stale-password","authMode": "auto",})require.NoError(t, err)- _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderEmail, true, models.JSON{+ _, err = svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderEmail, true, database.JSON{"smtpHost": "smtp.example","smtpPassword": "",- "authMode": string(models.EmailAuthModeNone),+ "authMode": string(notifications.EmailAuthModeNone),})require.NoError(t, err)- var stored models.NotificationSettings- require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderEmail).First(&stored).Error)+ var stored NotificationSettings+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", notifications.NotificationProviderEmail).First(&stored).Error)require.Empty(t, stored.Config["smtpPassword"])}@@ -665,25 +666,25 @@ func TestNotificationService_CreateOrUpdateSettingsPreservesCredentialAcrossDisadb := setupNotificationTestDB(t)svc := NewNotificationService(db, &config.Config{}, nil, nil)- _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{+ _, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{"host": "gotify.example","token": "initial-gotify-token","title": "Initial",})require.NoError(t, err)- _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, false, models.JSON{})+ _, err = svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, false, database.JSON{})require.NoError(t, err)- _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderGotify, true, models.JSON{+ _, err = svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderGotify, true, database.JSON{"host": "gotify.example","token": "","title": "Re-enabled",})require.NoError(t, err)- var stored models.NotificationSettings- require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderGotify).First(&stored).Error)+ var stored NotificationSettings+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", notifications.NotificationProviderGotify).First(&stored).Error)require.Equal(t, "Re-enabled", stored.Config["title"])decrypted, err := crypto.Decrypt(stored.Config["token"].(string))@@ -696,7 +697,7 @@ func TestNotificationService_CreateOrUpdateSettingsKeepsConfigWhenDisabledInterndb := setupNotificationTestDB(t)svc := NewNotificationService(db, &config.Config{}, nil, nil)- _, err := svc.CreateOrUpdateSettings(ctx, models.NotificationProviderNtfy, true, models.JSON{+ _, err := svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderNtfy, true, database.JSON{"host": "ntfy.example","topic": "arcane","events": map[string]any{@@ -707,7 +708,7 @@ func TestNotificationService_CreateOrUpdateSettingsKeepsConfigWhenDisabledInternrequire.NoError(t, err)// Disabling submits the same config back; it must survive the toggle.- _, err = svc.CreateOrUpdateSettings(ctx, models.NotificationProviderNtfy, false, models.JSON{+ _, err = svc.CreateOrUpdateSettings(ctx, notifications.NotificationProviderNtfy, false, database.JSON{"host": "ntfy.example","topic": "arcane","events": map[string]any{@@ -717,8 +718,8 @@ func TestNotificationService_CreateOrUpdateSettingsKeepsConfigWhenDisabledIntern})require.NoError(t, err)- var stored models.NotificationSettings- require.NoError(t, db.WithContext(ctx).Where("provider = ?", models.NotificationProviderNtfy).First(&stored).Error)+ var stored NotificationSettings+ require.NoError(t, db.WithContext(ctx).Where("provider = ?", notifications.NotificationProviderNtfy).First(&stored).Error)require.False(t, stored.Enabled)require.Equal(t, "ntfy.example", stored.Config["host"])require.Equal(t, "arcane", stored.Config["topic"])@@ -732,43 +733,43 @@ func TestNotificationService_NotifyEnabledProvidersInternal_SkipsFiltersAndAggredb := setupNotificationTestDB(t)svc := NewNotificationService(db, &config.Config{}, nil, event.NewEventService(db, nil, nil))- rows := []models.NotificationSettings{- {Provider: models.NotificationProviderDiscord, Enabled: false, Config: models.JSON{}},- {Provider: models.NotificationProviderSlack, Enabled: true, Config: models.JSON{- "events": map[string]any{string(models.NotificationEventPruneReport): false},+ rows := []NotificationSettings{+ {Provider: notifications.NotificationProviderDiscord, Enabled: false, Config: database.JSON{}},+ {Provider: notifications.NotificationProviderSlack, Enabled: true, Config: database.JSON{+ "events": map[string]any{string(notifications.NotificationEventPruneReport): false},}},- {Provider: models.NotificationProviderGotify, Enabled: true, Config: models.JSON{}},- {Provider: models.NotificationProviderNtfy, Enabled: true, Config: models.JSON{}},+ {Provider: notifications.NotificationProviderGotify, Enabled: true, Config: database.JSON{}},+ {Provider: notifications.NotificationProviderNtfy, Enabled: true, Config: database.JSON{}},}for i := range rows {require.NoError(t, db.WithContext(ctx).Create(&rows[i]).Error)}- var dispatched []models.NotificationProvider+ var dispatched []notifications.NotificationProvidertarget := NotificationTarget{EnvironmentID: "0", EnvironmentName: "Local Docker"}- delivered, err := svc.notifyEnabledProvidersInternal(ctx, target, models.NotificationEventPruneReport, "loop-test", models.JSON{"eventType": "prune_report"},- func(_ context.Context, provider models.NotificationProvider, _ models.JSON) (bool, error) {+ delivered, err := svc.notifyEnabledProvidersInternal(ctx, target, notifications.NotificationEventPruneReport, "loop-test", database.JSON{"eventType": "prune_report"},+ func(_ context.Context, provider notifications.NotificationProvider, _ database.JSON) (bool, error) {dispatched = append(dispatched, provider)- if provider == models.NotificationProviderNtfy {+ if provider == notifications.NotificationProviderNtfy {return true, errors.New("boom")}return true, nil})// Disabled and event-disabled rows are never dispatched.- require.Equal(t, []models.NotificationProvider{models.NotificationProviderGotify, models.NotificationProviderNtfy}, dispatched)+ require.Equal(t, []notifications.NotificationProvider{notifications.NotificationProviderGotify, notifications.NotificationProviderNtfy}, dispatched)require.Equal(t, 1, delivered)require.Error(t, err)require.Contains(t, err.Error(), "notification errors: ntfy: boom")// Each dispatched attempt lands in the event log.- var events []models.Event- require.NoError(t, db.WithContext(ctx).Where("type = ?", models.EventTypeNotificationSend).Order("created_at").Find(&events).Error)+ var events []event.Event+ require.NoError(t, db.WithContext(ctx).Where("type = ?", event.EventTypeNotificationSend).Order("created_at").Find(&events).Error)require.Len(t, events, 2)- require.Equal(t, models.EventSeveritySuccess, events[0].Severity)+ require.Equal(t, event.EventSeveritySuccess, events[0].Severity)require.Equal(t, "Notification sent via gotify", events[0].Title)require.Equal(t, "loop-test", events[0].Description)- require.Equal(t, models.EventSeverityError, events[1].Severity)+ require.Equal(t, event.EventSeverityError, events[1].Severity)require.Equal(t, "Notification failed via ntfy", events[1].Title)require.Contains(t, events[1].Description, "boom")}@@ -797,8 +798,8 @@ func TestNotificationService_DispatchNotificationForEnvironment_ResolvesTunnelSedb, _, svc := setupNotificationTestServiceInternal(t)now := time.Now()- require.NoError(t, db.WithContext(ctx).Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-edge", CreatedAt: now, UpdatedAt: &now},+ require.NoError(t, db.WithContext(ctx).Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-edge", CreatedAt: now, UpdatedAt: &now},Name: "edge-env",ApiUrl: "http://edge:3553",Enabled: true,diff --git a/backend/internal/oidc/handler.go b/backend/internal/oidc/handler.goindex 49c80f28a..e155a991f 100644--- a/backend/internal/oidc/handler.go+++ b/backend/internal/oidc/handler.go@@ -1,6 +1,10 @@package oidcimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""log/slog""net/http"@@ -14,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/passkey""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/user"@@ -378,7 +381,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcCclearStateCookie := cookie.BuildClearOidcStateCookieString(cookie.SecureCookieFromContext(ctx))setCookies := []string{clearStateCookie}if userModel.PasskeyMFAEnabled {- challenge, err := h.passkeyService.BeginMFAAuthentication(ctx, userModel.ID, meta, models.UserSessionSourceOidc)+ challenge, err := h.passkeyService.BeginMFAAuthentication(ctx, userModel.ID, meta, session.UserSessionSourceOidc)if err != nil {return nil, huma.Error500InternalServerError("Authentication failed")}@@ -391,7 +394,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC},}, nil}- tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, models.UserSessionSourceOidc, "", models.JSON{+ tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, session.UserSessionSourceOidc, "", database.JSON{"newUser": isNewUser,"subject": userInfo.Subject,})@@ -480,7 +483,7 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDeif userModel.PasskeyMFAEnabled {return nil, huma.Error403Forbidden("mfa_required")}- tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, models.UserSessionSourceOidc, "", models.JSON{+ tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, session.UserSessionSourceOidc, "", database.JSON{"newUser": isNewUser,"subject": userInfo.Subject,})@@ -596,7 +599,7 @@ func (h *OidcHandler) DeleteOidcRoleMapping(ctx context.Context, input *DeleteOireturn out, nil}-func toOidcMappingDTO(m *models.OidcRoleMapping) roletypes.OidcRoleMapping {+func toOidcMappingDTO(m *role.OidcRoleMapping) roletypes.OidcRoleMapping {return roletypes.OidcRoleMapping{ID: m.ID,ClaimValue: m.ClaimValue,diff --git a/backend/internal/oidc/service.go b/backend/internal/oidc/service.goindex 6517d98a4..096220788 100644--- a/backend/internal/oidc/service.go+++ b/backend/internal/oidc/service.go@@ -24,7 +24,6 @@ import ("golang.org/x/oauth2""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/jwtclaims"@@ -74,7 +73,7 @@ func NewOidcService(authService *auth.AuthService, settingsService *settings.Setreturn service}-func (s *OidcService) getEffectiveConfigInternal(ctx context.Context) (*models.OidcConfig, error) {+func (s *OidcService) getEffectiveConfigInternal(ctx context.Context) (*settings.OidcConfig, error) {oidcConfig, err := s.authService.GetOidcConfig(ctx)if err != nil {return nil, errors.WrapIf(err, "failed to get OIDC config")@@ -149,11 +148,11 @@ func (s *OidcService) ensureOpenIDScopeInternal(scopes []string) []string {return scopes}-func (s *OidcService) hasManualEndpointsInternal(cfg *models.OidcConfig) bool {+func (s *OidcService) hasManualEndpointsInternal(cfg *settings.OidcConfig) bool {return cfg.AuthorizationEndpoint != "" || cfg.TokenEndpoint != "" || cfg.UserinfoEndpoint != ""}-func (s *OidcService) getOauth2ConfigInternal(cfg *models.OidcConfig, provider *oidc.Provider, origin, mobileRedirectURI string) (oauth2.Config, error) {+func (s *OidcService) getOauth2ConfigInternal(cfg *settings.OidcConfig, provider *oidc.Provider, origin, mobileRedirectURI string) (oauth2.Config, error) {scopes := strings.Fields(cfg.Scopes)if len(scopes) == 0 {scopes = []string{"email", "profile"}@@ -279,7 +278,7 @@ func (s *OidcService) GetOidcRedirectURL(origin string) string {return baseUrl + "/auth/oidc/callback"}-func (s *OidcService) getOrDiscoverProviderInternal(ctx context.Context, cfg *models.OidcConfig) (*oidc.Provider, error) {+func (s *OidcService) getOrDiscoverProviderInternal(ctx context.Context, cfg *settings.OidcConfig) (*oidc.Provider, error) {if s.providerCache == nil {s.providerCache = hot.NewHotCache[oidcProviderKey, *oidc.Provider](hot.LRU, 4).Build()}@@ -330,7 +329,7 @@ func (s *OidcService) discoverProviderInternal(ctx context.Context, issuer strinreturn nil, issuer, err}-func (s *OidcService) exchangeTokenInternal(ctx context.Context, cfg *models.OidcConfig, provider *oidc.Provider, code string, verifier string, origin string, mobileRedirectURI string) (*oauth2.Token, error) {+func (s *OidcService) exchangeTokenInternal(ctx context.Context, cfg *settings.OidcConfig, provider *oidc.Provider, code string, verifier string, origin string, mobileRedirectURI string) (*oauth2.Token, error) {oauth2Config, err := s.getOauth2ConfigInternal(cfg, provider, origin, mobileRedirectURI)if err != nil {return nil, err@@ -347,7 +346,7 @@ func (s *OidcService) exchangeTokenInternal(ctx context.Context, cfg *models.Oidreturn token, nil}-func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *models.OidcConfig, provider *oidc.Provider, token *oauth2.Token, idToken *oidc.IDToken) (map[string]any, error) {+func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *settings.OidcConfig, provider *oidc.Provider, token *oauth2.Token, idToken *oidc.IDToken) (map[string]any, error) {providerCtx := oidc.ClientContext(ctx, s.getHttpClientInternal(cfg.SkipTlsVerify))var claims map[string]any@@ -407,7 +406,7 @@ func (s *OidcService) fetchClaimsInternal(ctx context.Context, cfg *models.OidcCreturn claims, nil}-func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *models.OidcConfig, token *oauth2.Token) (map[string]any, error) {+func (s *OidcService) fetchUserInfoClaimsInternal(ctx context.Context, cfg *settings.OidcConfig, token *oauth2.Token) (map[string]any, error) {if cfg.UserinfoEndpoint == "" {return nil, errors.New("userinfo endpoint not configured")}@@ -500,7 +499,7 @@ func (s *OidcService) validateStateInternal(state, storedState string) (*OidcStareturn stateData, nil}-func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.Provider, cfg *models.OidcConfig, token *oauth2.Token, nonce string) (*oidc.IDToken, string, error) {+func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.Provider, cfg *settings.OidcConfig, token *oauth2.Token, nonce string) (*oidc.IDToken, string, error) {var rawIDToken stringif idTokenValue := token.Extra("id_token"); idTokenValue != nil {if idTokenStr, ok := idTokenValue.(string); ok {@@ -557,7 +556,7 @@ func (s *OidcService) verifyIDTokenInternal(ctx context.Context, provider *oidc.return idToken, rawIDToken, nil}-func (s *OidcService) buildUserInfoInternal(ctx context.Context, provider *oidc.Provider, cfg *models.OidcConfig, token *oauth2.Token, idToken *oidc.IDToken, rawIDToken string) (*authtypes.OidcUserInfo, *authtypes.OidcTokenResponse, error) {+func (s *OidcService) buildUserInfoInternal(ctx context.Context, provider *oidc.Provider, cfg *settings.OidcConfig, token *oauth2.Token, idToken *oidc.IDToken, rawIDToken string) (*authtypes.OidcUserInfo, *authtypes.OidcTokenResponse, error) {claims, err := s.fetchClaimsInternal(ctx, cfg, provider, token, idToken)if err != nil {slog.Error("HandleCallback: failed to fetch claims", "error", err)@@ -690,7 +689,7 @@ func (s *OidcService) InitiateDeviceAuth(ctx context.Context) (*authtypes.OidcDe}// getDeviceAuthorizationEndpointInternal discovers or returns the configured device authorization endpoint.-func (s *OidcService) getDeviceAuthorizationEndpointInternal(ctx context.Context, cfg *models.OidcConfig) (string, error) {+func (s *OidcService) getDeviceAuthorizationEndpointInternal(ctx context.Context, cfg *settings.OidcConfig) (string, error) {if cfg.DeviceAuthorizationEndpoint != "" {return cfg.DeviceAuthorizationEndpoint, nil}diff --git a/backend/internal/oidc/service_test.go b/backend/internal/oidc/service_test.goindex a245e2a50..c7b0e18d8 100644--- a/backend/internal/oidc/service_test.go+++ b/backend/internal/oidc/service_test.go@@ -8,7 +8,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/libtnb/sqlite""github.com/stretchr/testify/require"@@ -111,7 +110,7 @@ func setupSettingsTestDB(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))return &database.DB{DB: db}}diff --git a/backend/internal/passkey/handler.go b/backend/internal/passkey/handler.goindex 830a1649f..923bcfd48 100644--- a/backend/internal/passkey/handler.go+++ b/backend/internal/passkey/handler.go@@ -1,6 +1,10 @@package passkeyimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context"stdjson "encoding/json""net/http"@@ -12,7 +16,6 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/user""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/cookie""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"@@ -412,7 +415,7 @@ func (h *PasskeyHandler) FinishPasskeyLogin(ctx context.Context, input *PasskeyLreturn nil, passkeyHTTPErrorInternal(err)}meta := authtypes.SessionMeta{UserAgent: input.UserAgent, IPAddress: middleware.GetRemoteAddrFromContext(ctx)}- tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, models.UserSessionSourcePasskey, "")+ tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, session.UserSessionSourcePasskey, "")if err != nil {return nil, huma.Error500InternalServerError("authentication failed")}@@ -444,7 +447,7 @@ func (h *PasskeyHandler) ExchangeMobilePasskeyLogin(ctx context.Context, input *return nil, passkeyHTTPErrorInternal(err)}meta := authtypes.SessionMeta{UserAgent: input.UserAgent, IPAddress: middleware.GetRemoteAddrFromContext(ctx)}- tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, models.UserSessionSourcePasskey, "")+ tokenPair, err := h.authService.CompleteLogin(ctx, userModel, meta, session.UserSessionSourcePasskey, "")if err != nil {return nil, huma.Error500InternalServerError("authentication failed")}@@ -685,7 +688,7 @@ func (h *PasskeyHandler) RegenerateRecoveryCodes(ctx context.Context, input *MFAreturn &MFARecoveryCodesOutput{Body: base.ApiResponse[RecoveryCodesResponse]{Success: true, Data: RecoveryCodesResponse{Codes: codes}}}, nil}-func (h *PasskeyHandler) authenticationResponseInternal(ctx context.Context, userModel *models.User, tokenPair *auth.TokenPair) (*authtypes.AuthenticationResponse, error) {+func (h *PasskeyHandler) authenticationResponseInternal(ctx context.Context, userModel *common.User, tokenPair *auth.TokenPair) (*authtypes.AuthenticationResponse, error) {if userModel == nil || tokenPair == nil {return nil, huma.Error500InternalServerError("authentication failed")}@@ -704,7 +707,7 @@ func (h *PasskeyHandler) authenticationResponseInternal(ctx context.Context, use}, nil}-func requireInteractiveSessionInternal(ctx context.Context) (*models.User, string, error) {+func requireInteractiveSessionInternal(ctx context.Context) (*common.User, string, error) {userModel, err := handlerutil.RequireUser(ctx)if err != nil {return nil, "", errdiff --git a/backend/internal/models/passkey.go b/backend/internal/passkey/model.gosimilarity index 67%rename from backend/internal/models/passkey.gorename to backend/internal/passkey/model.goindex 4e68c0da4..47db74f22 100644--- a/backend/internal/models/passkey.go+++ b/backend/internal/passkey/model.go@@ -1,29 +1,35 @@-package models+package passkey-import "time"+import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"++ "time"+)// Passkey stores the WebAuthn credential record required to validate future// assertions. The raw attestation fields are retained so the credential can// be audited or revalidated if the WebAuthn library's verification policy// evolves.type Passkey struct {- BaseModel-- UserID string `json:"userId" gorm:"column:user_id;not null;index"`- User *User `json:"-" gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`-- RPID string `json:"rpId" gorm:"column:rp_id;not null"`- CredentialID []byte `json:"-" gorm:"column:credential_id;not null"`- PublicKey []byte `json:"-" gorm:"column:public_key;not null"`- AttestationType string `json:"attestationType,omitempty" gorm:"column:attestation_type"`- AttestationFormat string `json:"attestationFormat,omitempty" gorm:"column:attestation_format"`- Transports StringSlice `json:"transports,omitempty" gorm:"column:transports;type:text"`- AAGUID []byte `json:"-" gorm:"column:aaguid"`- SignCount uint32 `json:"signCount" gorm:"column:sign_count;not null;default:0"`- BackupEligible bool `json:"backupEligible" gorm:"column:backup_eligible;not null;default:false"`- BackupState bool `json:"backupState" gorm:"column:backup_state;not null;default:false"`- CloneWarning bool `json:"cloneWarning" gorm:"column:clone_warning;not null;default:false"`- AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty" gorm:"column:authenticator_attachment"`+ database.BaseModel++ UserID string `json:"userId" gorm:"column:user_id;not null;index"`+ User *common.User `json:"-" gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`++ RPID string `json:"rpId" gorm:"column:rp_id;not null"`+ CredentialID []byte `json:"-" gorm:"column:credential_id;not null"`+ PublicKey []byte `json:"-" gorm:"column:public_key;not null"`+ AttestationType string `json:"attestationType,omitempty" gorm:"column:attestation_type"`+ AttestationFormat string `json:"attestationFormat,omitempty" gorm:"column:attestation_format"`+ Transports database.StringSlice `json:"transports,omitempty" gorm:"column:transports;type:text"`+ AAGUID []byte `json:"-" gorm:"column:aaguid"`+ SignCount uint32 `json:"signCount" gorm:"column:sign_count;not null;default:0"`+ BackupEligible bool `json:"backupEligible" gorm:"column:backup_eligible;not null;default:false"`+ BackupState bool `json:"backupState" gorm:"column:backup_state;not null;default:false"`+ CloneWarning bool `json:"cloneWarning" gorm:"column:clone_warning;not null;default:false"`+ AuthenticatorAttachment string `json:"authenticatorAttachment,omitempty" gorm:"column:authenticator_attachment"`AttestationClientDataJSON []byte `json:"-" gorm:"column:attestation_client_data_json"`AttestationClientDataHash []byte `json:"-" gorm:"column:attestation_client_data_hash"`@@ -42,7 +48,7 @@ func (Passkey) TableName() string {// PasskeyCeremony holds the opaque server-side state between WebAuthn begin// and finish calls. It is intentionally never serialized to the client.type PasskeyCeremony struct {- BaseModel+ database.BaseModelPurpose string `json:"purpose" gorm:"column:purpose;not null;index"`UserID *string `json:"userId,omitempty" gorm:"column:user_id;index"`@@ -62,7 +68,7 @@ func (PasskeyCeremony) TableName() string {// passkey MFA or step-up ceremony. The client receives only ID/secret values;// primary credentials and WebAuthn SessionData remain server-side.type AuthTransaction struct {- BaseModel+ database.BaseModelKind string `json:"kind" gorm:"column:kind;not null;index"`UserID string `json:"userId" gorm:"column:user_id;not null;index"`@@ -83,7 +89,7 @@ func (AuthTransaction) TableName() string {// PasskeyRecoveryCode stores only a one-way digest of a recovery code. The// plaintext is returned once during generation and is never recoverable.type PasskeyRecoveryCode struct {- BaseModel+ database.BaseModelUserID string `json:"userId" gorm:"column:user_id;not null;index"`CodeHash string `json:"-" gorm:"column:code_hash;not null;uniqueIndex"`diff --git a/backend/internal/passkey/service.go b/backend/internal/passkey/service.goindex e7fb532bb..a03310290 100644--- a/backend/internal/passkey/service.go+++ b/backend/internal/passkey/service.go@@ -1,6 +1,10 @@package passkeyimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""crypto/rand""crypto/sha256"@@ -19,7 +23,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/resources""github.com/getarcaneapp/arcane/types/v2/auth""github.com/go-webauthn/webauthn/protocol"@@ -125,7 +128,7 @@ type StepUpGrant struct {// an MFA transaction so the eventual session cannot be assigned client-chosen// source or network metadata.type AuthenticationCompletion struct {- User *models.User+ User *common.UserMeta auth.SessionMetaSource string}@@ -193,7 +196,7 @@ func (s *passkeyService) readyInternal() error {}type webAuthnUser struct {- model models.User+ model common.Usercredentials []webauthn.CredentialcredentialModelIDs map[string]string}@@ -222,7 +225,7 @@ func (s *passkeyService) loadWebAuthnUserInternal(ctx context.Context, userID streturn nil, ErrPasskeyTransaction}- var user models.User+ var user common.Userif err := s.db.WithContext(ctx).Where("id = ?", userID).First(&user).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrPasskeyTransaction@@ -230,7 +233,7 @@ func (s *passkeyService) loadWebAuthnUserInternal(ctx context.Context, userID streturn nil, errors.WrapIf(err, "failed to load passkey user")}- var rows []models.Passkey+ var rows []Passkeyif err := s.db.WithContext(ctx).Where("user_id = ? AND rp_id = ?", user.ID, s.rpID).Order("created_at ASC").Find(&rows).Error; err != nil {return nil, errors.WrapIf(err, "failed to load passkeys")}@@ -245,7 +248,7 @@ func (s *passkeyService) loadWebAuthnUserInternal(ctx context.Context, userID streturn &webAuthnUser{model: user, credentials: credentials, credentialModelIDs: credentialModelIDs}, nil}-func credentialFromModelInternal(row models.Passkey) webauthn.Credential {+func credentialFromModelInternal(row Passkey) webauthn.Credential {transports := make([]protocol.AuthenticatorTransport, len(row.Transports))for i, transport := range row.Transports {transports[i] = protocol.AuthenticatorTransport(transport)@@ -349,7 +352,7 @@ func (s *passkeyService) BeginMFAForTransaction(ctx context.Context, transactionreturn s.beginMFAForTransactionInternal(ctx, transaction)}-func (s *passkeyService) beginMFAForTransactionInternal(ctx context.Context, transaction *models.AuthTransaction) (*auth.MFAChallenge, error) {+func (s *passkeyService) beginMFAForTransactionInternal(ctx context.Context, transaction *AuthTransaction) (*auth.MFAChallenge, error) {if transaction == nil {return nil, ErrPasskeyTransaction}@@ -364,25 +367,25 @@ func (s *passkeyService) beginMFAForTransactionInternal(ctx context.Context, tra// pending ceremony prevents a client from accumulating reusable challenges.if err := s.db.WithContext(ctx).Where("auth_transaction_id = ? AND purpose = ? AND consumed_at IS NULL", transaction.ID, passkeyCeremonyPurposeMFA).- Delete(&models.PasskeyCeremony{}).Error; err != nil {+ Delete(&PasskeyCeremony{}).Error; err != nil {return nil, errors.WrapIf(err, "failed to replace MFA ceremony")}- assertion, session, err := s.webAuthn.BeginLogin(adapter, webauthn.WithUserVerification(protocol.VerificationRequired))+ assertion, webSession, err := s.webAuthn.BeginLogin(adapter, webauthn.WithUserVerification(protocol.VerificationRequired))if err != nil {return nil, errors.WrapIf(err, "failed to begin MFA passkey ceremony")}transactionID := transaction.IDuserIDPointer := transaction.UserID- ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeMFA, &userIDPointer, nil, &transactionID, session)+ ceremony, err := s.createCeremonyInternal(ctx, passkeyCeremonyPurposeMFA, &userIDPointer, nil, &transactionID, webSession)if err != nil {return nil, err}return &auth.MFAChallenge{TransactionID: transaction.ID,- Method: models.PasskeyMFAMethod,+ Method: session.PasskeyMFAMethod,Options: assertion.Response,ExpiresAt: ceremony.ExpiresAt,}, nil@@ -407,7 +410,7 @@ func (s *passkeyService) BeginStepUp(ctx context.Context, userID, sessionID strireturn nil, ErrPasskeyNoCredential}- transaction := newAuthTransactionInternal(userID, authTransactionKindStepUp, models.UserSessionSourceLocal, meta, &sessionID, passkeyStepUpTTL)+ transaction := newAuthTransactionInternal(userID, authTransactionKindStepUp, session.UserSessionSourceLocal, meta, &sessionID, passkeyStepUpTTL)if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {return nil, errors.WrapIf(err, "failed to create step-up transaction")}@@ -520,7 +523,7 @@ func (s *passkeyService) FinishRegistration(ctx context.Context, userID, sessionreturn &summary, nil}-func (s *passkeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID string, payload []byte) (*models.User, error) {+func (s *passkeyService) FinishPasskeyLogin(ctx context.Context, ceremonyID string, payload []byte) (*common.User, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -572,7 +575,7 @@ func (s *passkeyService) FinishMobilePasskeyLogin(ctx context.Context, ceremonyIreturn nil, err}- transaction := newAuthTransactionInternal(user.ID, authTransactionKindMobilePasskey, models.UserSessionSourcePasskey, auth.SessionMeta{}, nil, passkeyStepUpTTL)+ transaction := newAuthTransactionInternal(user.ID, authTransactionKindMobilePasskey, session.UserSessionSourcePasskey, auth.SessionMeta{}, nil, passkeyStepUpTTL)transaction.SecretHash = &codeChallengeif err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {return nil, errors.WrapIf(err, "failed to create mobile passkey transaction")@@ -580,7 +583,7 @@ func (s *passkeyService) FinishMobilePasskeyLogin(ctx context.Context, ceremonyIreturn &auth.MobilePasskeyCompletion{TransactionID: transaction.ID, ExpiresAt: transaction.ExpiresAt}, nil}-func (s *passkeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transactionID, codeVerifier string) (*models.User, error) {+func (s *passkeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transactionID, codeVerifier string) (*common.User, error) {if err := s.readyInternal(); err != nil {return nil, err}@@ -589,7 +592,7 @@ func (s *passkeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transacreturn nil, err}- var transaction models.AuthTransaction+ var transaction AuthTransactionerr = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Where("id = ? AND kind = ? AND status = ? AND secret_hash = ? AND expires_at > ?", transactionID, authTransactionKindMobilePasskey, authTransactionPending, codeChallenge, time.Now()).First(&transaction).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {@@ -599,7 +602,7 @@ func (s *passkeyService) ExchangeMobilePasskeyLogin(ctx context.Context, transac}now := time.Now()- result := tx.Model(&models.AuthTransaction{}).+ result := tx.Model(&AuthTransaction{}).Where("id = ? AND status = ? AND expires_at > ?", transaction.ID, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted, "completed_at": now, "updated_at": now})if result.Error != nil {@@ -632,7 +635,7 @@ func (s *passkeyService) FinishMFA(ctx context.Context, transactionID string, panow := time.Now()return &AuthenticationCompletion{User: user,- Meta: transactionSessionMetaInternal(transaction, models.PasskeyMFAMethod, &now),+ Meta: transactionSessionMetaInternal(transaction, session.PasskeyMFAMethod, &now),Source: transaction.Source,}, nil}@@ -647,7 +650,7 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,}hash := hashSecretInternal(normalized)- var transaction models.AuthTransaction+ var transaction AuthTransactionerr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ? AND kind = ? AND status = ? AND expires_at > ?", transactionID, authTransactionKindMFA, authTransactionPending, time.Now()).First(&transaction).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {@@ -655,12 +658,12 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,}return errors.WrapIf(err, "failed to lock MFA transaction")}- var recoveryCodes []models.PasskeyRecoveryCode+ var recoveryCodes []PasskeyRecoveryCodeif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ? AND used_at IS NULL", transaction.UserID).Find(&recoveryCodes).Error; err != nil {return errors.WrapIf(err, "failed to load recovery codes")}- var matched *models.PasskeyRecoveryCode+ var matched *PasskeyRecoveryCodefor i := range recoveryCodes {if subtle.ConstantTimeCompare([]byte(recoveryCodes[i].CodeHash), []byte(hash)) == 1 {matched = &recoveryCodes[i]@@ -671,7 +674,7 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,return ErrPasskeyRecoveryCode}now := time.Now()- result := tx.Model(&models.PasskeyRecoveryCode{}).+ result := tx.Model(&PasskeyRecoveryCode{}).Where("id = ? AND used_at IS NULL", matched.ID).Updates(map[string]any{"used_at": now, "updated_at": now})if result.Error != nil {@@ -681,7 +684,7 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,return ErrPasskeyRecoveryCode}now = time.Now()- result = tx.Model(&models.AuthTransaction{}).+ result = tx.Model(&AuthTransaction{}).Where("id = ? AND status = ? AND expires_at > ?", transaction.ID, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted, "completed_at": now, "updated_at": now})if result.Error != nil {@@ -702,7 +705,7 @@ func (s *passkeyService) FinishRecoveryCode(ctx context.Context, transactionID,now := time.Now()return &AuthenticationCompletion{User: user,- Meta: transactionSessionMetaInternal(&transaction, models.RecoveryCodeMFAMethod, &now),+ Meta: transactionSessionMetaInternal(&transaction, session.RecoveryCodeMFAMethod, &now),Source: transaction.Source,}, nil}@@ -731,7 +734,7 @@ func (s *passkeyService) CreatePasswordStepUpGrant(ctx context.Context, userID,if err := s.ensureActiveSessionInternal(ctx, userID, sessionID); err != nil {return nil, err}- transaction := newAuthTransactionInternal(userID, authTransactionKindStepUp, models.UserSessionSourceLocal, auth.SessionMeta{}, &sessionID, passkeyStepUpTTL)+ transaction := newAuthTransactionInternal(userID, authTransactionKindStepUp, session.UserSessionSourceLocal, auth.SessionMeta{}, &sessionID, passkeyStepUpTTL)if err := s.db.WithContext(ctx).Create(transaction).Error; err != nil {return nil, errors.WrapIf(err, "failed to create password step-up transaction")}@@ -754,7 +757,7 @@ func (s *passkeyService) VerifyStepUpToken(ctx context.Context, userID, sessionI}hash := hashSecretInternal(token)var count int64- if err := s.db.WithContext(ctx).Model(&models.AuthTransaction{}).+ if err := s.db.WithContext(ctx).Model(&AuthTransaction{}).Where("user_id = ? AND session_id = ? AND kind = ? AND status = ? AND secret_hash = ? AND expires_at > ?", userID, sessionID, authTransactionKindStepUp, authTransactionCompleted, hash, time.Now()).Count(&count).Error; err != nil {return errors.WrapIf(err, "failed to verify step-up grant")@@ -769,7 +772,7 @@ func (s *passkeyService) ListPasskeys(ctx context.Context, userID string) ([]Pasif err := s.readyInternal(); err != nil {return nil, err}- var rows []models.Passkey+ var rows []Passkeyif err := s.db.WithContext(ctx).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Order("created_at ASC").Find(&rows).Error; err != nil {return nil, errors.WrapIf(err, "failed to list passkeys")}@@ -816,7 +819,7 @@ func (s *passkeyService) RenamePasskey(ctx context.Context, userID, passkeyID, nif err != nil {return nil, err}- var row models.Passkey+ var row Passkeyresult := s.db.WithContext(ctx).Where("id = ? AND user_id = ? AND rp_id = ?", passkeyID, userID, s.rpID).First(&row)if errors.Is(result.Error, gorm.ErrRecordNotFound) {return nil, ErrPasskeyNotFound@@ -842,12 +845,12 @@ func (s *passkeyService) DeletePasskey(ctx context.Context, userID, passkeyID, sreturn err}return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var user models.User+ var user common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {return errors.WrapIf(err, "failed to lock user for passkey deletion")}var count int64- if err := tx.Model(&models.Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {+ if err := tx.Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {return errors.WrapIf(err, "failed to count passkeys")}if user.PasskeyMFAEnabled && count <= 1 {@@ -860,7 +863,7 @@ func (s *passkeyService) DeletePasskey(ctx context.Context, userID, passkeyID, sreturn ErrPasskeyLastCredential}}- result := tx.Where("id = ? AND user_id = ? AND rp_id = ?", passkeyID, userID, s.rpID).Delete(&models.Passkey{})+ result := tx.Where("id = ? AND user_id = ? AND rp_id = ?", passkeyID, userID, s.rpID).Delete(&Passkey{})if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete passkey")}@@ -884,7 +887,7 @@ func (s *passkeyService) GetMFAStatus(ctx context.Context, userID string) (*MFASreturn nil, err}var recoveryCodes int64- if err := s.db.WithContext(ctx).Model(&models.PasskeyRecoveryCode{}).Where("user_id = ? AND used_at IS NULL", userID).Count(&recoveryCodes).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&PasskeyRecoveryCode{}).Where("user_id = ? AND used_at IS NULL", userID).Count(&recoveryCodes).Error; err != nil {return nil, errors.WrapIf(err, "failed to count recovery codes")}return &MFAStatus{Enabled: user.PasskeyMFAEnabled, PasskeyCount: passkeyCount, RecoveryCodesRemaining: int(recoveryCodes)}, nil@@ -902,12 +905,12 @@ func (s *passkeyService) EnableMFA(ctx context.Context, userID, sessionID, stepUreturn nil, err}err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var user models.User+ var user common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {return errors.WrapIf(err, "failed to lock user for MFA enable")}var count int64- if err := tx.Model(&models.Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {+ if err := tx.Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {return errors.WrapIf(err, "failed to count passkeys for MFA enable")}if count == 0 {@@ -916,10 +919,10 @@ func (s *passkeyService) EnableMFA(ctx context.Context, userID, sessionID, stepUif user.PasskeyMFAEnabled {return ErrPasskeyMFAAlreadyEnabled}- if err := tx.Model(&models.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", true).Error; err != nil {+ if err := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", true).Error; err != nil {return errors.WrapIf(err, "failed to enable passkey MFA")}- if err := tx.Where("user_id = ?", userID).Delete(&models.PasskeyRecoveryCode{}).Error; err != nil {+ if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {return errors.WrapIf(err, "failed to replace recovery codes")}if err := tx.Create(&rows).Error; err != nil {@@ -941,21 +944,21 @@ func (s *passkeyService) DisableMFA(ctx context.Context, userID, sessionID, stepreturn err}err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var user models.User+ var user common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {return errors.WrapIf(err, "failed to lock user for MFA disable")}if !user.PasskeyMFAEnabled {return ErrPasskeyMFANotEnabled}- if err := tx.Model(&models.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", false).Error; err != nil {+ if err := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", false).Error; err != nil {return errors.WrapIf(err, "failed to disable passkey MFA")}- if err := tx.Where("user_id = ?", userID).Delete(&models.PasskeyRecoveryCode{}).Error; err != nil {+ if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {return errors.WrapIf(err, "failed to delete recovery codes")}now := time.Now()- query := tx.Model(&models.UserSession{}).Where("user_id = ? AND revoked_at IS NULL", userID)+ query := tx.Model(&session.UserSession{}).Where("user_id = ? AND revoked_at IS NULL", userID)if strings.TrimSpace(sessionID) != "" {query = query.Where("id <> ?", sessionID)}@@ -979,14 +982,14 @@ func (s *passkeyService) RegenerateRecoveryCodes(ctx context.Context, userID, sereturn nil, err}err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var user models.User+ var user common.Userif err := tx.Where("id = ?", userID).First(&user).Error; err != nil {return errors.WrapIf(err, "failed to load user for recovery code regeneration")}if !user.PasskeyMFAEnabled {return ErrPasskeyMFANotEnabled}- if err := tx.Where("user_id = ?", userID).Delete(&models.PasskeyRecoveryCode{}).Error; err != nil {+ if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {return errors.WrapIf(err, "failed to replace recovery codes")}return errors.WrapIf(tx.Create(&rows).Error, "failed to create recovery codes")@@ -1004,34 +1007,34 @@ func (s *passkeyService) ResetMFAForUser(ctx context.Context, userID string) errreturn err}return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var user models.User+ var user common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).First(&user).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return ErrPasskeyTransaction}return errors.WrapIf(err, "failed to load user for MFA reset")}- if err := tx.Model(&models.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", false).Error; err != nil {+ if err := tx.Model(&common.User{}).Where("id = ?", userID).Update("passkey_mfa_enabled", false).Error; err != nil {return errors.WrapIf(err, "failed to disable passkey MFA")}- if err := tx.Where("user_id = ?", userID).Delete(&models.PasskeyRecoveryCode{}).Error; err != nil {+ if err := tx.Where("user_id = ?", userID).Delete(&PasskeyRecoveryCode{}).Error; err != nil {return errors.WrapIf(err, "failed to delete recovery codes")}- if err := tx.Where("user_id = ?", userID).Delete(&models.PasskeyCeremony{}).Error; err != nil {+ if err := tx.Where("user_id = ?", userID).Delete(&PasskeyCeremony{}).Error; err != nil {return errors.WrapIf(err, "failed to delete passkey ceremonies")}- if err := tx.Where("user_id = ?", userID).Delete(&models.AuthTransaction{}).Error; err != nil {+ if err := tx.Where("user_id = ?", userID).Delete(&AuthTransaction{}).Error; err != nil {return errors.WrapIf(err, "failed to delete authentication transactions")}now := time.Now()- if err := tx.Model(&models.UserSession{}).Where("user_id = ? AND revoked_at IS NULL", userID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {+ if err := tx.Model(&session.UserSession{}).Where("user_id = ? AND revoked_at IS NULL", userID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {return errors.WrapIf(err, "failed to revoke sessions after MFA reset")}return nil})}-func (s *passkeyService) createCeremonyInternal(ctx context.Context, purpose string, userID, sessionID, transactionID *string, session *webauthn.SessionData) (*models.PasskeyCeremony, error) {+func (s *passkeyService) createCeremonyInternal(ctx context.Context, purpose string, userID, sessionID, transactionID *string, session *webauthn.SessionData) (*PasskeyCeremony, error) {if session == nil {return nil, ErrPasskeyCeremony}@@ -1043,8 +1046,8 @@ func (s *passkeyService) createCeremonyInternal(ctx context.Context, purpose strif expiresAt.IsZero() {expiresAt = time.Now().Add(passkeyCeremonyTTL)}- ceremony := &models.PasskeyCeremony{- BaseModel: models.BaseModel{ID: uuid.NewString()},+ ceremony := &PasskeyCeremony{+ BaseModel: database.BaseModel{ID: uuid.NewString()},Purpose: purpose,UserID: userID,SessionID: sessionID,@@ -1063,17 +1066,17 @@ func (s *passkeyService) sweepCeremoniesInternal(ctx context.Context) error {now := time.Now()if err := s.db.WithContext(ctx).Where("expires_at <= ? OR consumed_at IS NOT NULL", now).- Delete(&models.PasskeyCeremony{}).Error; err != nil {+ Delete(&PasskeyCeremony{}).Error; err != nil {return errors.WrapIf(err, "failed to sweep passkey ceremonies")}return nil}-func (s *passkeyService) consumeCeremonyInternal(ctx context.Context, ceremonyID, purpose string) (*models.PasskeyCeremony, error) {+func (s *passkeyService) consumeCeremonyInternal(ctx context.Context, ceremonyID, purpose string) (*PasskeyCeremony, error) {if strings.TrimSpace(ceremonyID) == "" {return nil, ErrPasskeyCeremony}- var ceremony models.PasskeyCeremony+ var ceremony PasskeyCeremonynow := time.Now()if err := s.db.WithContext(ctx).Where("id = ? AND purpose = ? AND consumed_at IS NULL AND expires_at > ?", ceremonyID, purpose, now).First(&ceremony).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {@@ -1081,7 +1084,7 @@ func (s *passkeyService) consumeCeremonyInternal(ctx context.Context, ceremonyID}return nil, errors.WrapIf(err, "failed to load passkey ceremony")}- result := s.db.WithContext(ctx).Model(&models.PasskeyCeremony{}).+ result := s.db.WithContext(ctx).Model(&PasskeyCeremony{}).Where("id = ? AND purpose = ? AND consumed_at IS NULL AND expires_at > ?", ceremonyID, purpose, now).Updates(map[string]any{"consumed_at": now, "updated_at": now})if result.Error != nil {@@ -1094,11 +1097,11 @@ func (s *passkeyService) consumeCeremonyInternal(ctx context.Context, ceremonyIDreturn &ceremony, nil}-func (s *passkeyService) loadPendingTransactionInternal(ctx context.Context, transactionID, kind string) (*models.AuthTransaction, error) {+func (s *passkeyService) loadPendingTransactionInternal(ctx context.Context, transactionID, kind string) (*AuthTransaction, error) {if strings.TrimSpace(transactionID) == "" {return nil, ErrPasskeyTransaction}- var transaction models.AuthTransaction+ var transaction AuthTransactionif err := s.db.WithContext(ctx).Where("id = ? AND kind = ? AND status = ? AND expires_at > ?", transactionID, kind, authTransactionPending, time.Now()).First(&transaction).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrPasskeyTransaction@@ -1108,7 +1111,7 @@ func (s *passkeyService) loadPendingTransactionInternal(ctx context.Context, trareturn &transaction, nil}-func (s *passkeyService) finishKnownUserAssertionInternal(ctx context.Context, transaction *models.AuthTransaction, purpose string, payload []byte) (*models.User, error) {+func (s *passkeyService) finishKnownUserAssertionInternal(ctx context.Context, transaction *AuthTransaction, purpose string, payload []byte) (*common.User, error) {if transaction == nil || len(payload) == 0 || len(payload) > maxPasskeyPayloadBytes {return nil, ErrPasskeyResponse}@@ -1142,7 +1145,7 @@ func (s *passkeyService) finishKnownUserAssertionInternal(ctx context.Context, t}func ceremonyIDForTransactionInternal(ctx context.Context, db *database.DB, transactionID, purpose string) string {- var ceremony models.PasskeyCeremony+ var ceremony PasskeyCeremonyif db == nil || db.WithContext(ctx).Where("auth_transaction_id = ? AND purpose = ? AND consumed_at IS NULL", transactionID, purpose).Order("created_at DESC").First(&ceremony).Error != nil {return ""}@@ -1151,7 +1154,7 @@ func ceremonyIDForTransactionInternal(ctx context.Context, db *database.DB, tranfunc (s *passkeyService) completeTransactionInternal(ctx context.Context, transactionID string) error {now := time.Now()- result := s.db.WithContext(ctx).Model(&models.AuthTransaction{}).+ result := s.db.WithContext(ctx).Model(&AuthTransaction{}).Where("id = ? AND status = ? AND expires_at > ?", transactionID, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted, "completed_at": now, "updated_at": now})if result.Error != nil {@@ -1169,7 +1172,7 @@ func (s *passkeyService) issueStepUpGrantInternal(ctx context.Context, transactireturn nil, errors.WrapIf(err, "failed to create step-up grant")}now := time.Now()- result := s.db.WithContext(ctx).Model(&models.AuthTransaction{}).+ result := s.db.WithContext(ctx).Model(&AuthTransaction{}).Where("id = ? AND kind = ? AND status = ? AND expires_at > ?", transactionID, authTransactionKindStepUp, authTransactionPending, now).Updates(map[string]any{"status": authTransactionCompleted,@@ -1183,7 +1186,7 @@ func (s *passkeyService) issueStepUpGrantInternal(ctx context.Context, transactiif result.RowsAffected != 1 {return nil, ErrPasskeyTransaction}- var transaction models.AuthTransaction+ var transaction AuthTransactionif err := s.db.WithContext(ctx).Where("id = ?", transactionID).First(&transaction).Error; err != nil {return nil, errors.WrapIf(err, "failed to load step-up grant")}@@ -1204,8 +1207,8 @@ func (s *passkeyService) authorizeManagementInternal(ctx context.Context, userIDreturn s.VerifyStepUpToken(ctx, userID, sessionID, stepUpToken)}-func (s *passkeyService) loadUserModelInternal(ctx context.Context, userID string) (*models.User, error) {- var user models.User+func (s *passkeyService) loadUserModelInternal(ctx context.Context, userID string) (*common.User, error) {+ var user common.Userif err := s.db.WithContext(ctx).Where("id = ?", userID).First(&user).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, ErrPasskeyTransaction@@ -1219,7 +1222,7 @@ func (s *passkeyService) ensureActiveSessionInternal(ctx context.Context, userIDif strings.TrimSpace(userID) == "" || strings.TrimSpace(sessionID) == "" {return ErrPasskeyStepUpRequired}- var session models.UserSession+ var session session.UserSessionif err := s.db.WithContext(ctx).Where("id = ? AND user_id = ? AND revoked_at IS NULL AND expires_at > ?", sessionID, userID, time.Now()).First(&session).Error; err != nil {@@ -1233,17 +1236,17 @@ func (s *passkeyService) ensureActiveSessionInternal(ctx context.Context, userIDfunc (s *passkeyService) countPasskeysInternal(ctx context.Context, userID string) (int, error) {var count int64- if err := s.db.WithContext(ctx).Model(&models.Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&Passkey{}).Where("user_id = ? AND rp_id = ?", userID, s.rpID).Count(&count).Error; err != nil {return 0, errors.WrapIf(err, "failed to count passkeys")}return int(count), nil}-func (s *passkeyService) persistCredentialInternal(ctx context.Context, userID string, credential *webauthn.Credential, name string) (*models.Passkey, error) {+func (s *passkeyService) persistCredentialInternal(ctx context.Context, userID string, credential *webauthn.Credential, name string) (*Passkey, error) {if credential == nil || len(credential.ID) == 0 || len(credential.PublicKey) == 0 {return nil, ErrPasskeyResponse}- var existing models.Passkey+ var existing Passkeyresult := s.db.WithContext(ctx).Where("rp_id = ? AND credential_id = ?", s.rpID, credential.ID).First(&existing)if result.Error == nil {return nil, ErrPasskeyExists@@ -1251,12 +1254,12 @@ func (s *passkeyService) persistCredentialInternal(ctx context.Context, userID sif !errors.Is(result.Error, gorm.ErrRecordNotFound) {return nil, errors.WrapIf(result.Error, "failed to check existing passkey")}- transports := make(models.StringSlice, len(credential.Transport))+ transports := make(database.StringSlice, len(credential.Transport))for i, transport := range credential.Transport {transports[i] = string(transport)}- row := &models.Passkey{- BaseModel: models.BaseModel{ID: uuid.NewString()},+ row := &Passkey{+ BaseModel: database.BaseModel{ID: uuid.NewString()},UserID: userID,RPID: s.rpID,CredentialID: append([]byte(nil), credential.ID...),@@ -1295,7 +1298,7 @@ func (s *passkeyService) updateCredentialAfterAssertionInternal(ctx context.Contreturn ErrPasskeyResponse}now := time.Now()- result := s.db.WithContext(ctx).Model(&models.Passkey{}).+ result := s.db.WithContext(ctx).Model(&Passkey{}).Where("id = ? AND user_id = ? AND rp_id = ?", credentialModelID, adapter.model.ID, s.rpID).Updates(map[string]any{"sign_count": credential.Authenticator.SignCount,@@ -1314,12 +1317,12 @@ func (s *passkeyService) updateCredentialAfterAssertionInternal(ctx context.Contreturn nil}-func newAuthTransactionInternal(userID, kind, source string, meta auth.SessionMeta, sessionID *string, ttl time.Duration) *models.AuthTransaction {+func newAuthTransactionInternal(userID, kind, source string, meta auth.SessionMeta, sessionID *string, ttl time.Duration) *AuthTransaction {if strings.TrimSpace(source) == "" {- source = models.UserSessionSourceLocal+ source = session.UserSessionSourceLocal}- return &models.AuthTransaction{- BaseModel: models.BaseModel{ID: uuid.NewString()},+ return &AuthTransaction{+ BaseModel: database.BaseModel{ID: uuid.NewString()},Kind: kind,UserID: userID,SessionID: sessionID,@@ -1331,7 +1334,7 @@ func newAuthTransactionInternal(userID, kind, source string, meta auth.SessionMe}}-func transactionSessionMetaInternal(transaction *models.AuthTransaction, method string, verifiedAt *time.Time) auth.SessionMeta {+func transactionSessionMetaInternal(transaction *AuthTransaction, method string, verifiedAt *time.Time) auth.SessionMeta {meta := auth.SessionMeta{Source: transaction.Source, MFAMethod: method, MFAVerifiedAt: verifiedAt}if transaction.UserAgent != nil {meta.UserAgent = *transaction.UserAgent@@ -1342,7 +1345,7 @@ func transactionSessionMetaInternal(transaction *models.AuthTransaction, methodreturn meta}-func passkeySummaryInternal(row models.Passkey) PasskeySummary {+func passkeySummaryInternal(row Passkey) PasskeySummary {transports := append([]string(nil), row.Transports...)return PasskeySummary{ID: row.ID,@@ -1408,9 +1411,9 @@ func loadAuthenticatorNamesInternal() {}}-func generateRecoveryCodeRowsInternal(userID string) ([]string, []models.PasskeyRecoveryCode, error) {+func generateRecoveryCodeRowsInternal(userID string) ([]string, []PasskeyRecoveryCode, error) {codes := make([]string, recoveryCodeCount)- rows := make([]models.PasskeyRecoveryCode, recoveryCodeCount)+ rows := make([]PasskeyRecoveryCode, recoveryCodeCount)for i := range codes {raw := make([]byte, 16)if _, err := rand.Read(raw); err != nil {@@ -1419,7 +1422,7 @@ func generateRecoveryCodeRowsInternal(userID string) ([]string, []models.Passkeyencoded := strings.TrimRight(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(raw), "=")codes[i] = groupRecoveryCodeInternal(encoded)hash := hashSecretInternal(strings.ToUpper(strings.ReplaceAll(codes[i], "-", "")))- rows[i] = models.PasskeyRecoveryCode{BaseModel: models.BaseModel{ID: uuid.NewString()}, UserID: userID, CodeHash: hash}+ rows[i] = PasskeyRecoveryCode{BaseModel: database.BaseModel{ID: uuid.NewString()}, UserID: userID, CodeHash: hash}}return codes, rows, nil}diff --git a/backend/internal/passkey/service_test.go b/backend/internal/passkey/service_test.goindex 39c961faa..6a6a1fba7 100644--- a/backend/internal/passkey/service_test.go+++ b/backend/internal/passkey/service_test.go@@ -1,6 +1,8 @@package passkeyimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""testing""time"@@ -12,7 +14,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/types/v2/auth")@@ -22,12 +23,12 @@ func newPasskeyServiceTestDB(t *testing.T) *database.DB {gormDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, gormDB.AutoMigrate(- &models.User{},- &models.UserSession{},- &models.Passkey{},- &models.PasskeyCeremony{},- &models.AuthTransaction{},- &models.PasskeyRecoveryCode{},+ &common.User{},+ &session.UserSession{},+ &Passkey{},+ &PasskeyCeremony{},+ &AuthTransaction{},+ &PasskeyRecoveryCode{},))db := &database.DB{DB: gormDB}@@ -42,10 +43,10 @@ func newPasskeyServiceForTest(t *testing.T, db *database.DB) *PasskeyService {return NewPasskeyService(db, &config.Config{AppUrl: "https://arcane.example.test"})}-func createPasskeyTestUser(t *testing.T, db *database.DB, id string) *models.User {+func createPasskeyTestUser(t *testing.T, db *database.DB, id string) *common.User {t.Helper()- user := &models.User{- BaseModel: models.BaseModel{ID: id},+ user := &common.User{+ BaseModel: database.BaseModel{ID: id},Username: id,PasswordHash: "stored-password-hash",}@@ -53,15 +54,15 @@ func createPasskeyTestUser(t *testing.T, db *database.DB, id string) *models.Usereturn user}-func createPasskeyTestCredential(t *testing.T, db *database.DB, service *PasskeyService, userID, id string) *models.Passkey {+func createPasskeyTestCredential(t *testing.T, db *database.DB, service *PasskeyService, userID, id string) *Passkey {t.Helper()- credential := &models.Passkey{- BaseModel: models.BaseModel{ID: id},+ credential := &Passkey{+ BaseModel: database.BaseModel{ID: id},UserID: userID,RPID: service.rpID,CredentialID: []byte("credential-" + id),PublicKey: []byte("public-key-" + id),- Transports: models.StringSlice{"internal"},+ Transports: database.StringSlice{"internal"},Name: "Test passkey",}require.NoError(t, db.Create(credential).Error)@@ -78,7 +79,7 @@ func TestPasskeyService_BeginPasskeyLoginStoresAndConsumesCeremony(t *testing.T)require.NotEmpty(t, challenge.CeremonyID)require.NotNil(t, challenge.Options)- var ceremony models.PasskeyCeremony+ var ceremony PasskeyCeremonyrequire.NoError(t, db.Where("id = ?", challenge.CeremonyID).First(&ceremony).Error)require.Equal(t, passkeyCeremonyPurposeLogin, ceremony.Purpose)require.Equal(t, service.rpID, ceremony.RPID)@@ -89,7 +90,7 @@ func TestPasskeyService_BeginPasskeyLoginStoresAndConsumesCeremony(t *testing.T)_, err = service.FinishPasskeyLogin(ctx, challenge.CeremonyID, []byte(`{}`))require.ErrorIs(t, err, ErrPasskeyResponse)- var consumed models.PasskeyCeremony+ var consumed PasskeyCeremonyrequire.NoError(t, db.Where("id = ?", challenge.CeremonyID).First(&consumed).Error)require.NotNil(t, consumed.ConsumedAt)@@ -134,7 +135,7 @@ func TestPasskeyService_DefaultPasskeyNameUsesAAGUIDCatalog(t *testing.T) {require.Equal(t, aaguid.String(), formatAAGUIDInternal(aaguid[:]))require.Equal(t, "New Passkey", defaultPasskeyNameInternal([]byte{0xff, 0xff, 0xff, 0xff}))- summary := passkeySummaryInternal(models.Passkey{AAGUID: aaguid[:]})+ summary := passkeySummaryInternal(Passkey{AAGUID: aaguid[:]})require.Equal(t, aaguid.String(), summary.AAGUID)}@@ -175,7 +176,7 @@ func TestPasskeyService_RecoveryCodeConsumptionIsAtomicAndSingleUse(t *testing.Trequire.Len(t, codes, recoveryCodeCount)require.NoError(t, db.Create(&rows).Error)- transaction := newAuthTransactionInternal(user.ID, authTransactionKindMFA, models.UserSessionSourceLocal, auth.SessionMeta{+ transaction := newAuthTransactionInternal(user.ID, authTransactionKindMFA, session.UserSessionSourceLocal, auth.SessionMeta{UserAgent: "test-agent",IPAddress: "127.0.0.1",}, nil, passkeyStepUpTTL)@@ -184,25 +185,25 @@ func TestPasskeyService_RecoveryCodeConsumptionIsAtomicAndSingleUse(t *testing.T_, err = service.FinishRecoveryCode(ctx, transaction.ID, "not-a-recovery-code")require.ErrorIs(t, err, ErrPasskeyRecoveryCode)- var pending models.AuthTransaction+ var pending AuthTransactionrequire.NoError(t, db.Where("id = ?", transaction.ID).First(&pending).Error)require.Equal(t, authTransactionPending, pending.Status)completion, err := service.FinishRecoveryCode(ctx, transaction.ID, codes[0])require.NoError(t, err)require.Equal(t, user.ID, completion.User.ID)- require.Equal(t, models.UserSessionSourceLocal, completion.Source)- require.Equal(t, models.RecoveryCodeMFAMethod, completion.Meta.MFAMethod)+ require.Equal(t, session.UserSessionSourceLocal, completion.Source)+ require.Equal(t, session.RecoveryCodeMFAMethod, completion.Meta.MFAMethod)require.Equal(t, "test-agent", completion.Meta.UserAgent)require.Equal(t, "127.0.0.1", completion.Meta.IPAddress)require.NotNil(t, completion.Meta.MFAVerifiedAt)- var completed models.AuthTransaction+ var completed AuthTransactionrequire.NoError(t, db.Where("id = ?", transaction.ID).First(&completed).Error)require.Equal(t, authTransactionCompleted, completed.Status)require.NotNil(t, completed.CompletedAt)- var consumed models.PasskeyRecoveryCode+ var consumed PasskeyRecoveryCoderequire.NoError(t, db.Where("user_id = ? AND code_hash = ?", user.ID, rows[0].CodeHash).First(&consumed).Error)require.NotNil(t, consumed.UsedAt)@@ -228,21 +229,21 @@ func TestPasskeyService_EnableAndDisableMFAManagesCodesAndSessions(t *testing.T)require.NoError(t, err)require.Len(t, codes, recoveryCodeCount)- var enabledUser models.User+ var enabledUser common.Userrequire.NoError(t, db.Where("id = ?", user.ID).First(&enabledUser).Error)require.True(t, enabledUser.PasskeyMFAEnabled)var recoveryCodeCountInDB int64- require.NoError(t, db.Model(&models.PasskeyRecoveryCode{}).Where("user_id = ? AND used_at IS NULL", user.ID).Count(&recoveryCodeCountInDB).Error)+ require.NoError(t, db.Model(&PasskeyRecoveryCode{}).Where("user_id = ? AND used_at IS NULL", user.ID).Count(&recoveryCodeCountInDB).Error)require.Equal(t, int64(recoveryCodeCount), recoveryCodeCountInDB)disableGrant, err := service.CreatePasswordStepUpGrant(ctx, user.ID, currentSession.ID)require.NoError(t, err)require.NoError(t, service.DisableMFA(ctx, user.ID, currentSession.ID, disableGrant.Token))- var disabledUser models.User+ var disabledUser common.Userrequire.NoError(t, db.Where("id = ?", user.ID).First(&disabledUser).Error)require.False(t, disabledUser.PasskeyMFAEnabled)- require.NoError(t, db.Model(&models.PasskeyRecoveryCode{}).Where("user_id = ?", user.ID).Count(&recoveryCodeCountInDB).Error)+ require.NoError(t, db.Model(&PasskeyRecoveryCode{}).Where("user_id = ?", user.ID).Count(&recoveryCodeCountInDB).Error)require.Zero(t, recoveryCodeCountInDB)current, err := sessionService.GetSessionByID(ctx, currentSession.ID)@@ -270,10 +271,10 @@ func TestPasskeyService_ResetMFARevokesSessionsAndPreservesPasskeys(t *testing.T_, rows, err := generateRecoveryCodeRowsInternal(user.ID)require.NoError(t, err)require.NoError(t, db.Create(&rows).Error)- transaction := newAuthTransactionInternal(user.ID, authTransactionKindMFA, models.UserSessionSourceLocal, auth.SessionMeta{}, nil, passkeyStepUpTTL)+ transaction := newAuthTransactionInternal(user.ID, authTransactionKindMFA, session.UserSessionSourceLocal, auth.SessionMeta{}, nil, passkeyStepUpTTL)require.NoError(t, db.Create(transaction).Error)- ceremony := &models.PasskeyCeremony{- BaseModel: models.BaseModel{ID: "reset-ceremony"},+ ceremony := &PasskeyCeremony{+ BaseModel: database.BaseModel{ID: "reset-ceremony"},Purpose: passkeyCeremonyPurposeMFA,UserID: new(user.ID),AuthTransactionID: new(transaction.ID),@@ -285,18 +286,18 @@ func TestPasskeyService_ResetMFARevokesSessionsAndPreservesPasskeys(t *testing.Trequire.NoError(t, service.ResetMFAForUser(ctx, user.ID))- var resetUser models.User+ var resetUser common.Userrequire.NoError(t, db.Where("id = ?", user.ID).First(&resetUser).Error)require.False(t, resetUser.PasskeyMFAEnabled)var remaining int64- require.NoError(t, db.Model(&models.PasskeyRecoveryCode{}).Where("user_id = ?", user.ID).Count(&remaining).Error)+ require.NoError(t, db.Model(&PasskeyRecoveryCode{}).Where("user_id = ?", user.ID).Count(&remaining).Error)require.Zero(t, remaining)- require.NoError(t, db.Model(&models.PasskeyCeremony{}).Where("user_id = ?", user.ID).Count(&remaining).Error)+ require.NoError(t, db.Model(&PasskeyCeremony{}).Where("user_id = ?", user.ID).Count(&remaining).Error)require.Zero(t, remaining)- require.NoError(t, db.Model(&models.AuthTransaction{}).Where("user_id = ?", user.ID).Count(&remaining).Error)+ require.NoError(t, db.Model(&AuthTransaction{}).Where("user_id = ?", user.ID).Count(&remaining).Error)require.Zero(t, remaining)- var preserved models.Passkey+ var preserved Passkeyrequire.NoError(t, db.Where("id = ?", passkey.ID).First(&preserved).Error)require.Equal(t, passkey.ID, preserved.ID)diff --git a/backend/internal/project/handler.go b/backend/internal/project/handler.goindex adfbbb11a..c64e0b8f6 100644--- a/backend/internal/project/handler.go+++ b/backend/internal/project/handler.go@@ -1,6 +1,8 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context"stderrors "errors""fmt"@@ -11,12 +13,13 @@ import ("strings""time"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"@@ -513,7 +516,7 @@ func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProjruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "project",ResourceID: input.ProjectID,ResourceName: input.ProjectID,@@ -521,7 +524,7 @@ func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProjStep: "Updating project tags",Message: "Updating project tags",SuccessMessage: "Project tags updated",- Metadata: models.JSON{"action": "update_tags", "tag": input.Body.Name, "attached": input.Body.Attached},+ Metadata: database.JSON{"action": "update_tags", "tag": input.Body.Name, "attached": input.Body.Attached},}, func(runtimeCtx context.Context) error {var updateErr errortags, updateErr = h.projectService.UpdateProjectTag(runtimeCtx, input.ProjectID, input.Body.Name, input.Body.Color, input.Body.Attached, *user)@@ -552,13 +555,13 @@ func (h *ProjectHandler) UpdateProjectTag(ctx context.Context, input *UpdateProj// operation (deploy, redeploy, pull, build): the activity it records and the// action whose raw docker CLI output is streamed to the client.type projectStreamOperationConfigInternal struct {- ActivityType models.ActivityType+ ActivityType activitytypes.TypeStep stringStartMessage stringWriterStep stringFailureMessage stringSuccessMessage string- Metadata models.JSON+ Metadata database.JSON// Action runs the operation. ctx carries the stream writer under// dockerutils.ProgressWriterKey; it is also passed directly for actions// that take a writer parameter.@@ -569,7 +572,7 @@ type projectStreamOperationConfigInternal struct {// project endpoints: NDJSON headers, activity lifecycle (started frame, queue// slot, completion), the activity-teeing writer, and the terminal done/error// frames.-func (h *ProjectHandler) streamProjectOperationInternal(environmentID, projectID string, user *models.User, cfg projectStreamOperationConfigInternal) *huma.StreamResponse {+func (h *ProjectHandler) streamProjectOperationInternal(environmentID, projectID string, user *common.User, cfg projectStreamOperationConfigInternal) *huma.StreamResponse {return &huma.StreamResponse{Body: func(humaCtx huma.Context) {httpx.SetJSONStreamHeaders(humaCtx)@@ -578,7 +581,7 @@ func (h *ProjectHandler) streamProjectOperationInternal(environmentID, projectIDrawWriter := humaCtx.BodyWriter()metadata := cfg.Metadataif metadata == nil {- metadata = models.JSON{"projectID": projectID}+ metadata = database.JSON{"projectID": projectID}}activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx,@@ -631,7 +634,7 @@ func (h *ProjectHandler) DeployProject(ctx context.Context, input *DeployProject}return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx- ActivityType: models.ActivityTypeProjectDeploy,+ ActivityType: activitytypes.TypeProjectDeploy,Step: "Starting deployment",StartMessage: "Project deployment started",WriterStep: "Deploying project",@@ -651,7 +654,7 @@ func (h *ProjectHandler) DownProject(ctx context.Context, input *DownProjectInpu}runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectDown, "project", input.ProjectID, input.ProjectID, user, "Stopping project", "Project stop requested", models.JSON{"projectID": input.ProjectID}, false)+ activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeProjectDown, "project", input.ProjectID, input.ProjectID, user, "Stopping project", "Project stop requested", database.JSON{"projectID": input.ProjectID}, false)activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Stopping project")downCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)if err := h.projectService.DownProject(downCtx, input.ProjectID, *user); err != nil {@@ -727,11 +730,11 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectreturn nil, err}- var proj *models.Project+ var proj *ProjectruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "project",ResourceID: projectInput.Name,ResourceName: projectInput.Name,@@ -739,7 +742,7 @@ func (h *ProjectHandler) CreateProject(ctx context.Context, input *CreateProjectStep: "Creating project",Message: "Creating project",SuccessMessage: "Project created successfully",- Metadata: models.JSON{"action": "create_project"},+ Metadata: database.JSON{"action": "create_project"},}, func(runtimeCtx context.Context) error {var createErr errorproj, createErr = h.projectService.CreateProject(runtimeCtx, projectInput.Name, projectInput.ComposeContent, projectInput.EnvContent, manifest, uploads, projectInput.Tags, projectInput.TagColors, *user)@@ -852,7 +855,7 @@ func (h *ProjectHandler) RedeployProject(ctx context.Context, input *RedeployPro}return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx- ActivityType: models.ActivityTypeProjectRedeploy,+ ActivityType: activitytypes.TypeProjectRedeploy,Step: "Starting redeploy",StartMessage: "Project redeploy started",WriterStep: "Redeploying project",@@ -888,7 +891,7 @@ func (h *ProjectHandler) DestroyProject(ctx context.Context, input *DestroyProje}runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)- activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, models.ActivityTypeProjectDestroy, "project", input.ProjectID, input.ProjectID, user, "Destroying project", "Project destroy requested", models.JSON{"projectID": input.ProjectID, "removeFiles": removeFiles, "removeVolumes": removeVolumes}, false)+ activityID, runtimeCtx := activitylib.StartHandlerActivity(runtimeCtx, h.activityService, input.EnvironmentID, activitytypes.TypeProjectDestroy, "project", input.ProjectID, input.ProjectID, user, "Destroying project", "Project destroy requested", database.JSON{"projectID": input.ProjectID, "removeFiles": removeFiles, "removeVolumes": removeVolumes}, false)activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, "Destroying project")destroyCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)if err := h.projectService.DestroyProject(destroyCtx, input.ProjectID, removeFiles, removeVolumes, *user); err != nil {@@ -924,7 +927,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "project",ResourceID: input.ProjectID,ResourceName: mo.PointerToOption(input.Body.Name).OrEmpty(),@@ -932,7 +935,7 @@ func (h *ProjectHandler) UpdateProject(ctx context.Context, input *UpdateProjectStep: "Updating project",Message: "Updating project",SuccessMessage: "Project updated successfully",- Metadata: models.JSON{"action": "update_project", "projectID": input.ProjectID},+ Metadata: database.JSON{"action": "update_project", "projectID": input.ProjectID},}, func(runtimeCtx context.Context) error {_, updateErr := h.projectService.UpdateProject(runtimeCtx, input.ProjectID, input.Body.Name, input.Body.ComposeContent, input.Body.EnvContent, input.Body.OverrideContent, *user)return updateErr@@ -996,7 +999,7 @@ func (h *ProjectHandler) UpdateProjectServices(ctx context.Context, input *Updat}type projectActivityActionConfigInternal struct {- ActivityType models.ActivityType+ ActivityType activitytypes.TypeStep stringStartMessage stringWriterStep string@@ -1006,13 +1009,13 @@ type projectActivityActionConfigInternal struct {// Queue routes the activity through the per-environment concurrency// limiter; set for long-running deploy-like actions, not quick restarts.Queue bool- Action func(context.Context, string, models.User) error+ Action func(context.Context, string, common.User) errorError func(error) error}func (h *ProjectHandler) updateProjectServicesActivityConfigInternal(services []string) projectActivityActionConfigInternal {return projectActivityActionConfigInternal{- ActivityType: models.ActivityTypeAutoUpdate,+ ActivityType: activitytypes.TypeAutoUpdate,Step: "Updating project services",StartMessage: "Project services update requested",WriterStep: "Updating project services",@@ -1020,7 +1023,7 @@ func (h *ProjectHandler) updateProjectServicesActivityConfigInternal(services []SuccessComplete: "Project services updated",SuccessMessage: "Project services updated successfully",Queue: true,- Action: func(runtimeCtx context.Context, projectID string, user models.User) error {+ Action: func(runtimeCtx context.Context, projectID string, user common.User) error {return h.projectService.UpdateProjectServices(runtimeCtx, projectID, services, user)},Error: projectArchivedActionErrorInternal(func(err error) error {@@ -1031,14 +1034,14 @@ func (h *ProjectHandler) updateProjectServicesActivityConfigInternal(services []func (h *ProjectHandler) restartProjectActivityConfigInternal(services []string) projectActivityActionConfigInternal {return projectActivityActionConfigInternal{- ActivityType: models.ActivityTypeProjectRestart,+ ActivityType: activitytypes.TypeProjectRestart,Step: "Restarting project",StartMessage: "Project restart requested",WriterStep: "Restarting project",FailureMessage: "Project restarted",SuccessComplete: "Project restarted",SuccessMessage: "Project restarted successfully",- Action: func(runtimeCtx context.Context, projectID string, user models.User) error {+ Action: func(runtimeCtx context.Context, projectID string, user common.User) error {return h.projectService.RestartProject(runtimeCtx, projectID, services, user)},Error: projectArchivedActionErrorInternal(func(err error) error {@@ -1086,10 +1089,10 @@ func (h *ProjectHandler) runProjectActivityActionInternal(ctx context.Context, eruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)var activityID stringif cfg.Queue {- activityID, runtimeCtx = activitylib.StartHandlerActivity(runtimeCtx, h.activityService, environmentID, cfg.ActivityType, "project", projectID, projectID, user, cfg.Step, cfg.StartMessage, models.JSON{"projectID": projectID}, true)+ activityID, runtimeCtx = activitylib.StartHandlerActivity(runtimeCtx, h.activityService, environmentID, cfg.ActivityType, "project", projectID, projectID, user, cfg.Step, cfg.StartMessage, database.JSON{"projectID": projectID}, true)activitylib.AwaitHandlerActivitySlot(runtimeCtx, h.activityService, activityID, environmentID)} else {- activityID, runtimeCtx = activitylib.StartHandlerActivity(runtimeCtx, h.activityService, environmentID, cfg.ActivityType, "project", projectID, projectID, user, cfg.Step, cfg.StartMessage, models.JSON{"projectID": projectID}, false)+ activityID, runtimeCtx = activitylib.StartHandlerActivity(runtimeCtx, h.activityService, environmentID, cfg.ActivityType, "project", projectID, projectID, user, cfg.Step, cfg.StartMessage, database.JSON{"projectID": projectID}, false)}activityWriter := activitylib.NewWriter(runtimeCtx, h.activityService, activityID, io.Discard, cfg.WriterStep)actionCtx := context.WithValue(runtimeCtx, dockerutils.ProgressWriterKey{}, activityWriter)@@ -1166,7 +1169,7 @@ func (h *ProjectHandler) PullProjectImages(ctx context.Context, input *PullProje}return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx- ActivityType: models.ActivityTypeProjectPull,+ ActivityType: activitytypes.TypeProjectPull,Step: "Pulling project images",StartMessage: "Project image pull started",WriterStep: "Pulling project images",@@ -1198,13 +1201,13 @@ func (h *ProjectHandler) BuildProjectImages(ctx context.Context, input *BuildPro}return h.streamProjectOperationInternal(input.EnvironmentID, input.ProjectID, user, projectStreamOperationConfigInternal{ //nolint:contextcheck // the stream body runs on humaCtx.Context(), not the handler ctx- ActivityType: models.ActivityTypeProjectBuild,+ ActivityType: activitytypes.TypeProjectBuild,Step: "Building project images",StartMessage: "Project image build started",WriterStep: "Building project images",FailureMessage: "Project image build failed",SuccessMessage: "Project image build completed",- Metadata: models.JSON{"projectID": input.ProjectID, "services": options.Services},+ Metadata: database.JSON{"projectID": input.ProjectID, "services": options.Services},Action: func(opCtx context.Context, writer io.Writer) error {return h.projectService.BuildProjectServices(opCtx, input.ProjectID, options, writer, user)},diff --git a/backend/internal/lifecycle/service.go b/backend/internal/project/lifecycle.gosimilarity index 97%rename from backend/internal/lifecycle/service.gorename to backend/internal/project/lifecycle.goindex 0390eb250..f1b4598f7 100644--- a/backend/internal/lifecycle/service.go+++ b/backend/internal/project/lifecycle.go@@ -1,6 +1,8 @@-package lifecycle+package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"bufio""context""fmt"@@ -28,7 +30,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -108,7 +109,7 @@ func NewLifecycleService(db *database.DB, settingsService *settings.SettingsServ// returns an error that aborts the deploy. The last-run state on the// GitOpsSync row is updated on every invocation that reaches the run step,// regardless of outcome.-func (s *LifecycleService) RunPreDeploy(ctx context.Context, project *models.Project, actor models.User) error {+func (s *LifecycleService) RunPreDeploy(ctx context.Context, project *Project, actor common.User) error {if project == nil || project.GitOpsManagedBy == nil || *project.GitOpsManagedBy == "" {return nil}@@ -127,7 +128,7 @@ func (s *LifecycleService) RunPreDeploy(ctx context.Context, project *models.Proreturn s.executePreDeployInternal(ctx, project, sync, actor)}-func (s *LifecycleService) executePreDeployInternal(ctx context.Context, project *models.Project, sync *models.GitOpsSync, actor models.User) error {+func (s *LifecycleService) executePreDeployInternal(ctx context.Context, project *Project, sync *GitOpsSync, actor common.User) error {runnerImage := s.resolveRunnerImageInternal(ctx, sync)if runnerImage == "" {return errors.Errorf("pre-deploy script %q is configured but no runner image is set on the GitOps sync or lifecycleDefaultRunnerImage setting", *sync.PreDeployScriptPath)@@ -188,7 +189,7 @@ func (s *LifecycleService) executePreDeployInternal(ctx context.Context, projectreturn nil}-func (s *LifecycleService) resolveRunnerImageInternal(ctx context.Context, sync *models.GitOpsSync) string {+func (s *LifecycleService) resolveRunnerImageInternal(ctx context.Context, sync *GitOpsSync) string {if sync != nil {runnerImage := strings.TrimSpace(mo.PointerToOption(sync.PreDeployRunnerImage).OrEmpty())if runnerImage != "" {@@ -389,7 +390,7 @@ func (s *LifecycleService) resolveTimeoutInternal(ctx context.Context, perSyncTifunc (s *LifecycleService) persistLastRunInternal(ctx context.Context, syncID, status, output string, runAt time.Time) {persistCtx := context.WithoutCancel(ctx)err := s.db.WithContext(persistCtx).- Model(&models.GitOpsSync{}).+ Model(&GitOpsSync{}).Where("id = ?", syncID).Updates(map[string]any{"pre_deploy_last_run_at": runAt,@@ -403,27 +404,27 @@ func (s *LifecycleService) persistLastRunInternal(ctx context.Context, syncID, sfunc (s *LifecycleService) emitLifecycleEventInternal(ctx context.Context,- project *models.Project,- sync *models.GitOpsSync,+ project *Project,+ sync *GitOpsSync,runnerImage string,status string,exitCode int64,durationMs int64,runErr error,- actor models.User,+ actor common.User,) {- severity := models.EventSeveritySuccess+ severity := event.EventSeveritySuccesstitle := "Pre-deploy lifecycle hook succeeded: " + project.Namedescription := fmt.Sprintf("Script %s exited with code %d in %dms", mo.PointerToOption(sync.PreDeployScriptPath).OrEmpty(), exitCode, durationMs)if status != lifecycleStatusSuccess {- severity = models.EventSeverityWarning+ severity = event.EventSeverityWarningtitle = fmt.Sprintf("Pre-deploy lifecycle hook %s: %s", status, project.Name)if runErr != nil {description = runErr.Error()}}- metadata := models.JSON{+ metadata := database.JSON{"scriptPath": mo.PointerToOption(sync.PreDeployScriptPath).OrEmpty(),"runnerImage": runnerImage,"exitCode": exitCode,@@ -433,7 +434,7 @@ func (s *LifecycleService) emitLifecycleEventInternal(}_, err := s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeLifecycleExecute,+ Type: event.EventTypeLifecycleExecute,Severity: severity,Title: title,Description: description,@@ -453,12 +454,12 @@ func (s *LifecycleService) emitLifecycleEventInternal(// loadGitOpsSyncForProjectInternal returns the GitOps sync linked to the// given project, or nil if the project is not GitOps-managed. A nil sync// with nil error is a normal outcome, not a failure.-func (s *LifecycleService) loadGitOpsSyncForProjectInternal(ctx context.Context, projectID string) (*models.GitOpsSync, error) {+func (s *LifecycleService) loadGitOpsSyncForProjectInternal(ctx context.Context, projectID string) (*GitOpsSync, error) {if projectID == "" {return nil, nil}- var sync models.GitOpsSync+ var sync GitOpsSyncerr := s.db.WithContext(ctx).Where("project_id = ?", projectID).First(&sync).Errordiff --git a/backend/internal/lifecycle/service_test.go b/backend/internal/project/lifecycle_test.gosimilarity index 94%rename from backend/internal/lifecycle/service_test.gorename to backend/internal/project/lifecycle_test.goindex 130fa74f7..f74064707 100644--- a/backend/internal/lifecycle/service_test.go+++ b/backend/internal/project/lifecycle_test.go@@ -1,6 +1,8 @@-package lifecycle+package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""errors""os"@@ -17,7 +19,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings")@@ -26,10 +27,10 @@ func setupLifecycleTestDB(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.SettingVariable{},- &models.Project{},- &models.GitOpsSync{},- &models.Event{},+ &settings.SettingVariable{},+ &Project{},+ &GitOpsSync{},+ &event.Event{},))return &database.DB{DB: db}}@@ -267,7 +268,7 @@ func TestCombineLifecycleOutput(t *testing.T) {func TestRunPreDeploy_NilProject(t *testing.T) {db := setupLifecycleTestDB(t)svc, _ := newLifecycleTestService(t, db)- require.NoError(t, svc.RunPreDeploy(context.Background(), nil, models.User{}))+ require.NoError(t, svc.RunPreDeploy(context.Background(), nil, common.User{}))}func TestRunPreDeploy_ProjectNotGitOpsManaged(t *testing.T) {@@ -275,12 +276,12 @@ func TestRunPreDeploy_ProjectNotGitOpsManaged(t *testing.T) {svc, settings := newLifecycleTestService(t, db)require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleEnabled", "true"))- project := &models.Project{+ project := &Project{Name: "demo",Path: t.TempDir(),GitOpsManagedBy: nil,}- require.NoError(t, svc.RunPreDeploy(context.Background(), project, models.User{}))+ require.NoError(t, svc.RunPreDeploy(context.Background(), project, common.User{}))}func TestRunPreDeploy_KillSwitchDisabled(t *testing.T) {@@ -288,7 +289,7 @@ func TestRunPreDeploy_KillSwitchDisabled(t *testing.T) {svc, _ := newLifecycleTestService(t, db)syncID := "sync-1"- project := &models.Project{+ project := &Project{Name: "demo",Path: t.TempDir(),GitOpsManagedBy: &syncID,@@ -298,7 +299,7 @@ func TestRunPreDeploy_KillSwitchDisabled(t *testing.T) {scriptPath := "pre-deploy.sh"runnerImage := "alpine:latest"- sync := &models.GitOpsSync{+ sync := &GitOpsSync{Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -313,7 +314,7 @@ func TestRunPreDeploy_KillSwitchDisabled(t *testing.T) {sync.ID = syncIDrequire.NoError(t, db.Create(sync).Error)- require.NoError(t, svc.RunPreDeploy(context.Background(), project, models.User{}))+ require.NoError(t, svc.RunPreDeploy(context.Background(), project, common.User{}))}func TestRunPreDeploy_NoScriptConfigured(t *testing.T) {@@ -322,7 +323,7 @@ func TestRunPreDeploy_NoScriptConfigured(t *testing.T) {require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleEnabled", "true"))syncID := "sync-1"- project := &models.Project{+ project := &Project{Name: "demo",Path: t.TempDir(),GitOpsManagedBy: &syncID,@@ -330,7 +331,7 @@ func TestRunPreDeploy_NoScriptConfigured(t *testing.T) {project.ID = "proj-1"require.NoError(t, db.Create(project).Error)- sync := &models.GitOpsSync{+ sync := &GitOpsSync{Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -343,7 +344,7 @@ func TestRunPreDeploy_NoScriptConfigured(t *testing.T) {sync.ID = syncIDrequire.NoError(t, db.Create(sync).Error)- require.NoError(t, svc.RunPreDeploy(context.Background(), project, models.User{}))+ require.NoError(t, svc.RunPreDeploy(context.Background(), project, common.User{}))}func TestRunPreDeploy_MissingRunnerImage(t *testing.T) {@@ -354,7 +355,7 @@ func TestRunPreDeploy_MissingRunnerImage(t *testing.T) {syncID := "sync-1"projectDir := writeLifecycleProjectDirWithScript(t, "pre-deploy.sh", "echo hi\n")- project := &models.Project{+ project := &Project{Name: "demo",Path: projectDir,GitOpsManagedBy: &syncID,@@ -363,7 +364,7 @@ func TestRunPreDeploy_MissingRunnerImage(t *testing.T) {require.NoError(t, db.Create(project).Error)scriptPath := "pre-deploy.sh"- sync := &models.GitOpsSync{+ sync := &GitOpsSync{Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -377,7 +378,7 @@ func TestRunPreDeploy_MissingRunnerImage(t *testing.T) {sync.ID = syncIDrequire.NoError(t, db.Create(sync).Error)- err := svc.RunPreDeploy(context.Background(), project, models.User{})+ err := svc.RunPreDeploy(context.Background(), project, common.User{})require.Error(t, err)assert.Contains(t, err.Error(), "runner image")}@@ -387,10 +388,10 @@ func TestResolveRunnerImage_UsesSettingDefault(t *testing.T) {svc, settings := newLifecycleTestService(t, db)require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleDefaultRunnerImage", "alpine:latest"))- assert.Equal(t, "alpine:latest", svc.resolveRunnerImageInternal(context.Background(), &models.GitOpsSync{}))+ assert.Equal(t, "alpine:latest", svc.resolveRunnerImageInternal(context.Background(), &GitOpsSync{}))override := "debian:stable-slim"- assert.Equal(t, override, svc.resolveRunnerImageInternal(context.Background(), &models.GitOpsSync{+ assert.Equal(t, override, svc.resolveRunnerImageInternal(context.Background(), &GitOpsSync{PreDeployRunnerImage: &override,}))}@@ -401,7 +402,7 @@ func TestRunPreDeploy_PathTraversalRejected(t *testing.T) {require.NoError(t, settings.SetStringSetting(context.Background(), "lifecycleEnabled", "true"))syncID := "sync-1"- project := &models.Project{+ project := &Project{Name: "demo",Path: t.TempDir(),GitOpsManagedBy: &syncID,@@ -411,7 +412,7 @@ func TestRunPreDeploy_PathTraversalRejected(t *testing.T) {scriptPath := "../etc/passwd"runnerImage := "alpine:latest"- sync := &models.GitOpsSync{+ sync := &GitOpsSync{Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -426,7 +427,7 @@ func TestRunPreDeploy_PathTraversalRejected(t *testing.T) {sync.ID = syncIDrequire.NoError(t, db.Create(sync).Error)- err := svc.RunPreDeploy(context.Background(), project, models.User{})+ err := svc.RunPreDeploy(context.Background(), project, common.User{})require.Error(t, err)assert.Contains(t, err.Error(), "script path")}@@ -443,7 +444,7 @@ func TestPersistLastRun_UpdatesGitOpsSyncRow(t *testing.T) {db := setupLifecycleTestDB(t)svc, _ := newLifecycleTestService(t, db)- sync := &models.GitOpsSync{+ sync := &GitOpsSync{Name: "demo-sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -458,7 +459,7 @@ func TestPersistLastRun_UpdatesGitOpsSyncRow(t *testing.T) {now := time.Now().UTC().Truncate(time.Second)svc.persistLastRunInternal(context.Background(), sync.ID, lifecycleStatusSuccess, "all good", now)- var got models.GitOpsSync+ var got GitOpsSyncrequire.NoError(t, db.Where("id = ?", sync.ID).First(&got).Error)require.NotNil(t, got.PreDeployLastRunAt)require.NotNil(t, got.PreDeployLastRunStatus)diff --git a/backend/internal/models/gitops_sync.go b/backend/internal/project/model.gosimilarity index 53%rename from backend/internal/models/gitops_sync.gorename to backend/internal/project/model.goindex 3faf4cbbd..d34cb31e0 100644--- a/backend/internal/models/gitops_sync.go+++ b/backend/internal/project/model.go@@ -1,21 +1,72 @@-package models+package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"+ "github.com/getarcaneapp/arcane/backend/v2/internal/gitrepo"+"time")+type ProjectStatus string++const (+ ProjectStatusRunning ProjectStatus = "running"+ ProjectStatusStopped ProjectStatus = "stopped"+ ProjectStatusPartiallyRunning ProjectStatus = "partially running"+ ProjectStatusUnknown ProjectStatus = "unknown"+ ProjectStatusDeploying ProjectStatus = "deploying"+ ProjectStatusStopping ProjectStatus = "stopping"+ ProjectStatusRestarting ProjectStatus = "restarting"+)++type Project struct {+ database.BaseModel++ Name string `json:"name" sortable:"true" gorm:"index:idx_projects_name"`+ DirName *string `json:"dir_name"`+ Path string `json:"path" sortable:"true" gorm:"uniqueIndex"`+ Status ProjectStatus `json:"status" sortable:"true"`+ StatusReason *string `json:"status_reason"`+ ServiceCount int `json:"service_count" sortable:"true"`+ RunningCount int `json:"running_count" sortable:"true"`+ GitOpsManagedBy *string `json:"gitops_managed_by,omitempty" gorm:"column:gitops_managed_by"`+ ComposeProjectName *string `json:"compose_project_name,omitempty" gorm:"column:compose_project_name"`+ ImageRefsJSON string `json:"image_refs_json,omitempty" gorm:"column:image_refs_json"`+ BuildImageRefsJSON *string `json:"-" gorm:"column:build_image_refs_json"`+ IsArchived bool `json:"is_archived" gorm:"column:is_archived;default:false;index"`+ ArchivedAt *time.Time `json:"archived_at,omitempty" gorm:"column:archived_at"`+}++func (Project) TableName() string {+ return "projects"+}++// ProjectTag stores one normalized tag association and its management source.+type ProjectTag struct {+ ProjectID string `json:"projectId" gorm:"column:project_id;primaryKey"`+ Name string `json:"name" gorm:"column:name;primaryKey"`+ Source string `json:"source" gorm:"column:source;primaryKey"`+ Color string `json:"color" gorm:"column:color;not null;default:gray"`+}++// TableName returns the database table used for project tag associations.+func (ProjectTag) TableName() string {+ return "project_tags"+}+type GitOpsSync struct {- BaseModel-- Environment *Environment `json:"environment,omitempty" gorm:"foreignKey:EnvironmentID"`- Repository *GitRepository `json:"repository,omitempty" gorm:"foreignKey:RepositoryID"`- ProjectID *string `json:"projectId,omitempty" sortable:"true"` // Set after project is created- Project *Project `json:"project,omitempty" gorm:"foreignKey:ProjectID"`- SyncedFiles *string `json:"syncedFiles,omitempty" gorm:"column:synced_files"` // JSON array of synced file paths- LastSyncAt *time.Time `json:"lastSyncAt,omitempty" sortable:"true"`- LastSyncStatus *string `json:"lastSyncStatus,omitempty" search:"status,success,failed,pending,error"`- LastSyncError *string `json:"lastSyncError,omitempty"`- LastSyncCommit *string `json:"lastSyncCommit,omitempty" search:"commit,hash,sha,revision"`+ database.BaseModel++ Environment *environment.Environment `json:"environment,omitempty" gorm:"foreignKey:EnvironmentID"`+ Repository *gitrepo.GitRepository `json:"repository,omitempty" gorm:"foreignKey:RepositoryID"`+ ProjectID *string `json:"projectId,omitempty" sortable:"true"` // Set after project is created+ Project *Project `json:"project,omitempty" gorm:"foreignKey:ProjectID"`+ SyncedFiles *string `json:"syncedFiles,omitempty" gorm:"column:synced_files"` // JSON array of synced file paths+ LastSyncAt *time.Time `json:"lastSyncAt,omitempty" sortable:"true"`+ LastSyncStatus *string `json:"lastSyncStatus,omitempty" search:"status,success,failed,pending,error"`+ LastSyncError *string `json:"lastSyncError,omitempty"`+ LastSyncCommit *string `json:"lastSyncCommit,omitempty" search:"commit,hash,sha,revision"`// Pre-deploy lifecycle hook (configuration)// When PreDeployScriptPath is set, the named script is executed in adiff --git a/backend/internal/lifecycle/path_diagnostics_other.go b/backend/internal/project/path_diagnostics_other.gosimilarity index 96%rename from backend/internal/lifecycle/path_diagnostics_other.gorename to backend/internal/project/path_diagnostics_other.goindex 0a9bf0491..01c529ac1 100644--- a/backend/internal/lifecycle/path_diagnostics_other.go+++ b/backend/internal/project/path_diagnostics_other.go@@ -1,6 +1,6 @@//go:build !unix-package lifecycle+package projectimport "fmt"diff --git a/backend/internal/lifecycle/path_diagnostics_unix.go b/backend/internal/project/path_diagnostics_unix.gosimilarity index 99%rename from backend/internal/lifecycle/path_diagnostics_unix.gorename to backend/internal/project/path_diagnostics_unix.goindex 30465d118..5e995e2d1 100644--- a/backend/internal/lifecycle/path_diagnostics_unix.go+++ b/backend/internal/project/path_diagnostics_unix.go@@ -1,6 +1,6 @@//go:build unix-package lifecycle+package projectimport ("fmt"diff --git a/backend/internal/lifecycle/path_diagnostics_unix_test.go b/backend/internal/project/path_diagnostics_unix_test.gosimilarity index 99%rename from backend/internal/lifecycle/path_diagnostics_unix_test.gorename to backend/internal/project/path_diagnostics_unix_test.goindex ea0d5f50b..c01a7a926 100644--- a/backend/internal/lifecycle/path_diagnostics_unix_test.go+++ b/backend/internal/project/path_diagnostics_unix_test.go@@ -1,6 +1,6 @@//go:build unix-package lifecycle+package projectimport ("fmt"diff --git a/backend/internal/project/project.go b/backend/internal/project/project.goindex 9bc91289b..86eed29d6 100644--- a/backend/internal/project/project.go+++ b/backend/internal/project/project.go@@ -1,6 +1,8 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""io""log/slog"@@ -10,7 +12,6 @@ import ("sync""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/lifecycle""github.com/getarcaneapp/arcane/backend/v2/internal/registry""emperror.dev/errors"@@ -21,7 +22,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/types/v2/containerregistry"@@ -34,7 +34,7 @@ import ()type buildServiceInternal interface {- BuildImage(ctx context.Context, environmentID string, req buildtypes.BuildRequest, progressWriter io.Writer, serviceName string, user *models.User) (*buildtypes.BuildResult, error)+ BuildImage(ctx context.Context, environmentID string, req buildtypes.BuildRequest, progressWriter io.Writer, serviceName string, user *common.User) (*buildtypes.BuildResult, error)BuildSettings() buildtypes.BuildSettings}@@ -45,7 +45,7 @@ type ProjectService struct {imageService *image.ImageServicedockerService *docker.DockerClientServicebuildService buildServiceInternal- lifecycleService *lifecycle.LifecycleService+ lifecycleService *LifecycleServicekvService *kv.KVServicecontainerRegistryService *registry.ContainerRegistryServiceconfig *config.Config@@ -66,7 +66,7 @@ type ProjectService struct {// EnsureGitOpsProjectLinked persists the bidirectional GitOps/project binding// and refreshes the compose-name cache as one domain operation.-func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *models.GitOpsSync, project *models.Project) error {+func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *GitOpsSync, project *Project) error {if sync == nil || project == nil {return nil}@@ -97,12 +97,12 @@ func (s *ProjectService) EnsureGitOpsProjectLinked(ctx context.Context, sync *moif err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if len(updatesSync) > 0 {- if err := tx.Model(&models.GitOpsSync{}).Where("id = ?", sync.ID).Updates(updatesSync).Error; err != nil {+ if err := tx.Model(&GitOpsSync{}).Where("id = ?", sync.ID).Updates(updatesSync).Error; err != nil {return errors.WrapIff(err, "failed to relink GitOps sync %s", sync.ID)}}if len(updatesProject) > 0 {- if err := tx.Model(&models.Project{}).Where("id = ?", project.ID).Updates(updatesProject).Error; err != nil {+ if err := tx.Model(&Project{}).Where("id = ?", project.ID).Updates(updatesProject).Error; err != nil {return errors.WrapIff(err, "failed to relink project %s to GitOps sync %s", project.ID, sync.ID)}}@@ -153,7 +153,7 @@ func (s *ProjectService) ValidateComposeDirectory(ctx context.Context, projectNa// CreateGitOpsManagedProject persists a promoted GitOps project, links both// records, updates the compose-name cache, and records the creation event.-func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, sync *models.GitOpsSync, project *models.Project, actor models.User, logEventOptions ...bool) error {+func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, sync *GitOpsSync, project *Project, actor common.User, logEventOptions ...bool) error {if sync == nil || project == nil {return errors.New("GitOps sync and project are required")}@@ -161,10 +161,10 @@ func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, sync *mif err := tx.Create(project).Error; err != nil {return errors.WrapIf(err, "failed to create project")}- if err := tx.Model(&models.GitOpsSync{}).Where("id = ?", sync.ID).Update("project_id", project.ID).Error; err != nil {+ if err := tx.Model(&GitOpsSync{}).Where("id = ?", sync.ID).Update("project_id", project.ID).Error; err != nil {return errors.WrapIf(err, "failed to update sync with project ID")}- if err := tx.Model(&models.Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", sync.ID).Error; err != nil {+ if err := tx.Model(&Project{}).Where("id = ?", project.ID).Update("gitops_managed_by", sync.ID).Error; err != nil {return errors.WrapIf(err, "failed to mark project as GitOps-managed")}return nil@@ -183,8 +183,8 @@ func (s *ProjectService) CreateGitOpsManagedProject(ctx context.Context, sync *mlogEvent = logEventOptions[0]}if logEvent && s.eventService != nil {- metadata := models.JSON{"action": "create", "projectID": project.ID, "projectName": project.Name, "path": project.Path}- if err := s.eventService.LogProjectEvent(ctx, models.EventTypeProjectCreate, project.ID, project.Name, actor.ID, actor.Username, "0", metadata); err != nil {+ metadata := database.JSON{"action": "create", "projectID": project.ID, "projectName": project.Name, "path": project.Path}+ if err := s.eventService.LogProjectEvent(ctx, event.EventTypeProjectCreate, project.ID, project.Name, actor.ID, actor.Username, "0", metadata); err != nil {slog.ErrorContext(ctx, "could not log project creation", "error", err)}}@@ -205,7 +205,7 @@ const projectMetadataTTL = 5 * time.Secondtype registryCredentialsProviderInternal func(context.Context) ([]containerregistry.Credential, error)-func NewProjectService(db *database.DB, settingsService *settings.SettingsService, eventService *event.EventService, imageService *image.ImageService, dockerService *docker.DockerClientService, buildService buildServiceInternal, lifecycleService *lifecycle.LifecycleService, containerRegistryService *registry.ContainerRegistryService, cfg *config.Config) *ProjectService {+func NewProjectService(db *database.DB, settingsService *settings.SettingsService, eventService *event.EventService, imageService *image.ImageService, dockerService *docker.DockerClientService, buildService buildServiceInternal, lifecycleService *LifecycleService, containerRegistryService *registry.ContainerRegistryService, cfg *config.Config) *ProjectService {return &ProjectService{db: db,settingsService: settingsService,@@ -277,7 +277,7 @@ func (s *ProjectService) GetProjectsDirectory(ctx context.Context) (string, erroreturn filepath.Clean(projectsDir), nil}-func getProjectsDirectoryOrDefaultInternal(ctx context.Context, cfg *models.Settings) string {+func getProjectsDirectoryOrDefaultInternal(ctx context.Context, cfg *settings.Settings) string {projectsDirectory, err := projects.GetProjectsDirectory(ctx, strings.TrimSpace(cfg.ProjectsDirectory.Value))if err != nil {slog.WarnContext(ctx, "unable to determine projects directory; using default", "error", err)@@ -286,7 +286,7 @@ func getProjectsDirectoryOrDefaultInternal(ctx context.Context, cfg *models.Settreturn projectsDirectory}-func (s *ProjectService) getMutableProjectInternal(ctx context.Context, projectID string) (*models.Project, error) {+func (s *ProjectService) getMutableProjectInternal(ctx context.Context, projectID string) (*Project, error) {proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {return nil, err@@ -297,7 +297,7 @@ func (s *ProjectService) getMutableProjectInternal(ctx context.Context, projectIreturn proj, nil}-func (s *ProjectService) logProjectEventInternal(ctx context.Context, eventType models.EventType, projectID, projectName string, user models.User, metadata models.JSON, action string) {+func (s *ProjectService) logProjectEventInternal(ctx context.Context, eventType event.EventType, projectID, projectName string, user common.User, metadata database.JSON, action string) {if s.eventService == nil {return}@@ -334,8 +334,8 @@ func getProjectRelativePathInternal(projectsDir, projectPath string) string {return filepath.ToSlash(relativePath)}-func (s *ProjectService) GetProjectFromDatabaseByID(ctx context.Context, id string) (*models.Project, error) {- var projectModel models.Project+func (s *ProjectService) GetProjectFromDatabaseByID(ctx context.Context, id string) (*Project, error) {+ var projectModel Projectif err := s.db.WithContext(ctx).Where("id = ?", id).First(&projectModel).Error; err != nil {if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {return nil, errors.New("request canceled or timed out")@@ -348,13 +348,13 @@ func (s *ProjectService) GetProjectFromDatabaseByID(ctx context.Context, id strireturn &projectModel, nil}-func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name string) (*models.Project, error) {+func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name string) (*Project, error) {if name == "" {return nil, errors.New("project name is empty")}normalized := projects.NormalizeProjectName(name)- var proj models.Project+ var proj Projecterr := s.db.WithContext(ctx).Where("name = ? OR name = ?", name, normalized).First(&proj).Errorif err == nil {s.composeNames.put(normalized, proj.ID)@@ -386,7 +386,7 @@ func (s *ProjectService) GetProjectByComposeName(ctx context.Context, name strin// EnsureProjectPathUnderRoot validates that the project's path is a safe subdirectory of the configured projects root.// If not, it normalizes the path to `<projectsRoot>/<dirName or sanitized project name>`. When persist=true, it saves// the updated project path to the database.-func (s *ProjectService) EnsureProjectPathUnderRoot(ctx context.Context, proj *models.Project, persist bool) error {+func (s *ProjectService) EnsureProjectPathUnderRoot(ctx context.Context, proj *Project, persist bool) error {projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {return errors.WrapIf(err, "failed to get projects directory")diff --git a/backend/internal/project/project_compose_cache.go b/backend/internal/project/project_compose_cache.goindex 24d562f40..0f8d75cd9 100644--- a/backend/internal/project/project_compose_cache.go+++ b/backend/internal/project/project_compose_cache.go@@ -1,6 +1,8 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""log/slog""os"@@ -13,7 +15,6 @@ import (composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/moby/moby/client"@@ -100,13 +101,13 @@ func (c *parsedComposeCacheInternal) invalidate(projectID string) {c.entries.Delete(projectID)}-func (s *ProjectService) lookupProjectByCachedComposeNameInternal(ctx context.Context, normalizedName string) (*models.Project, bool, error) {+func (s *ProjectService) lookupProjectByCachedComposeNameInternal(ctx context.Context, normalizedName string) (*Project, bool, error) {projectID, ok := s.composeNames.projectID(normalizedName).Get()if !ok {return nil, false, nil}- var projectModel models.Project+ var projectModel Projectif err := s.db.WithContext(ctx).Where("id = ?", projectID).First(&projectModel).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {s.composeNames.invalidate(normalizedName)@@ -126,7 +127,7 @@ func (s *ProjectService) lookupProjectByCachedComposeNameInternal(ctx context.Co}func (s *ProjectService) rebuildComposeNameCacheInternal(ctx context.Context) error {- var projectModels []models.Project+ var projectModels []Projectif err := s.db.WithContext(ctx).Select("id", "name").Find(&projectModels).Error; err != nil {return err}@@ -147,13 +148,13 @@ func (s *ProjectService) rebuildComposeNameCacheInternal(ctx context.Context) erreturn nil}-func (s *ProjectService) ResolveProjectComposeFile(ctx context.Context, proj *models.Project) (string, error) {+func (s *ProjectService) ResolveProjectComposeFile(ctx context.Context, proj *Project) (string, error) {if proj == nil {return "", errors.New("project is nil")}if proj.GitOpsManagedBy != nil && strings.TrimSpace(*proj.GitOpsManagedBy) != "" {- var syncRecord models.GitOpsSync+ var syncRecord GitOpsSyncif err := s.db.WithContext(ctx).Select("compose_path").Where("id = ?", *proj.GitOpsManagedBy).@@ -185,7 +186,7 @@ func (s *ProjectService) ResolveProjectComposeFile(ctx context.Context, proj *moreturn composeFile, nil}-func (s *ProjectService) loadComposeProjectForProjectInternal(ctx context.Context, proj *models.Project, cfg *models.Settings) (*composetypes.Project, string, error) {+func (s *ProjectService) loadComposeProjectForProjectInternal(ctx context.Context, proj *Project, cfg *settings.Settings) (*composetypes.Project, string, error) {composeFileFullPath, err := s.ResolveProjectComposeFile(ctx, proj)if err != nil {return nil, "", err@@ -215,7 +216,7 @@ func (s *ProjectService) loadComposeProjectForProjectInternal(ctx context.Contexreturn composeProject, composeFileFullPath, nil}-func (s *ProjectService) getCachedComposeProjectInternal(ctx context.Context, proj *models.Project, cfg *models.Settings) (*composetypes.Project, error) {+func (s *ProjectService) getCachedComposeProjectInternal(ctx context.Context, proj *Project, cfg *settings.Settings) (*composetypes.Project, error) {if proj == nil {return nil, errors.New("project is nil")}@@ -296,7 +297,7 @@ func validComposeCacheEntryInternal(entry composeCacheEntry) bool {return true}-func (s *ProjectService) refreshComposeProjectNameInternal(ctx context.Context, proj *models.Project) {+func (s *ProjectService) refreshComposeProjectNameInternal(ctx context.Context, proj *Project) {if proj == nil {return}@@ -326,7 +327,7 @@ func (s *ProjectService) refreshComposeProjectNameInternal(ctx context.Context,updates["updated_at"] = time.Now()if err := s.db.WithContext(ctx).- Model(&models.Project{}).+ Model(&Project{}).Where("id = ?", proj.ID).Updates(updates).Error; err != nil {slog.WarnContext(ctx, "failed to persist refreshed compose project name", "projectID", proj.ID, "error", err)diff --git a/backend/internal/project/project_details.go b/backend/internal/project/project_details.goindex 0b73e2496..fe186419d 100644--- a/backend/internal/project/project_details.go+++ b/backend/internal/project/project_details.go@@ -1,6 +1,10 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"bufio""context""io"@@ -13,7 +17,6 @@ import ("emperror.dev/errors"composetypes "github.com/compose-spec/compose-go/v2/types"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/iconcatalog"@@ -51,7 +54,7 @@ func getServiceCounts(services []ProjectServiceInfo) (total int, running int) {return total, running}-func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Context, projectID string, status models.ProjectStatus) error {+func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Context, projectID string, status ProjectStatus) error {services, err := s.GetProjectServices(ctx, projectID)if err != nil {slog.Error("GetProjectServices failed during status update", "projectID", projectID, "error", err)@@ -60,7 +63,7 @@ func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.ContexserviceCount, runningCount := getServiceCounts(services)- if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", projectID).Updates(map[string]any{+ if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{"status": status,"service_count": serviceCount,"running_count": runningCount,@@ -72,9 +75,9 @@ func (s *ProjectService) updateProjectStatusandCountsInternal(ctx context.Contexreturn nil}-func (s *ProjectService) updateProjectStatusInternal(ctx context.Context, id string, status models.ProjectStatus) error {+func (s *ProjectService) updateProjectStatusInternal(ctx context.Context, id string, status ProjectStatus) error {now := time.Now()- res := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", id).Updates(map[string]any{+ res := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", id).Updates(map[string]any{"status": status,"updated_at": now,})@@ -362,7 +365,7 @@ func (s *ProjectService) enrichProjectUpdateInfoInternal(ctx context.Context, refunc (s *ProjectService) enrichProjectsWithUpdateInfoInternal(ctx context.Context,- projectsList []models.Project,+ projectsList []Project,details []project.Details,) {if len(projectsList) == 0 || len(details) == 0 {@@ -391,7 +394,7 @@ func (s *ProjectService) enrichProjectsWithUpdateInfoInternal(}wg.Add(1)- go func(proj models.Project) {+ go func(proj Project) {defer wg.Done()select {@@ -434,7 +437,7 @@ func (s *ProjectService) enrichProjectsWithUpdateInfoInternal(}}-func (s *ProjectService) getProjectImageRefsFromComposeInternal(ctx context.Context, proj models.Project, cfg *models.Settings) ([]string, []string, error) {+func (s *ProjectService) getProjectImageRefsFromComposeInternal(ctx context.Context, proj Project, cfg *settings.Settings) ([]string, []string, error) {composeProject, err := s.getCachedComposeProjectInternal(ctx, &proj, cfg)if err != nil {return nil, nil, errors.WrapIf(err, "load compose project")@@ -477,7 +480,7 @@ func buildProjectUpdateInfoSummaryInternal(summary.ImagesWithUpdates++summary.UpdatedImageRefs = append(summary.UpdatedImageRefs, imageRef)}- if info.UpdateType == models.UpdateTypeNotPulled {+ if info.UpdateType == imageupdate.UpdateTypeNotPulled {summary.ImagesNotPulled++summary.NotPulledImageRefs = append(summary.NotPulledImageRefs, imageRef)}@@ -510,9 +513,9 @@ func buildProjectUpdateInfoSummaryInternal(return summary}-func (s *ProjectService) enrichWithGitOpsInfo(ctx context.Context, proj *models.Project, resp *project.Details) {+func (s *ProjectService) enrichWithGitOpsInfo(ctx context.Context, proj *Project, resp *project.Details) {if proj.GitOpsManagedBy != nil {- var syncRecord models.GitOpsSync+ var syncRecord GitOpsSyncif err := s.db.WithContext(ctx).Preload("Repository").Where("id = ?", *proj.GitOpsManagedBy).First(&syncRecord).Error; err == nil {resp.LastSyncCommit = syncRecord.LastSyncCommitif syncRecord.Repository != nil {@@ -522,7 +525,7 @@ func (s *ProjectService) enrichWithGitOpsInfo(ctx context.Context, proj *models.}}-func (s *ProjectService) enrichWithComposeServiceConfigs(ctx context.Context, proj *models.Project, composeFile string, resp *project.Details) {+func (s *ProjectService) enrichWithComposeServiceConfigs(ctx context.Context, proj *Project, composeFile string, resp *project.Details) {composeProj, loadErr := s.getCachedComposeProjectInternal(ctx, proj, nil)if loadErr != nil {slog.WarnContext(ctx, "failed to load compose service configs", "path", composeFile, "error", loadErr)@@ -597,7 +600,7 @@ func (s *ProjectService) StreamProjectLogs(ctx context.Context, projectID stringreturn nil}-func (s *ProjectService) CountServicesFromCompose(ctx context.Context, p models.Project) (int, error) {+func (s *ProjectService) CountServicesFromCompose(ctx context.Context, p Project) (int, error) {proj, _, err := s.loadComposeProjectForProjectInternal(ctx, &p, nil)if err != nil {return 0, err@@ -606,9 +609,9 @@ func (s *ProjectService) CountServicesFromCompose(ctx context.Context, p models.return len(proj.Services), nil}-func calculateProjectStatus(services []ProjectServiceInfo) models.ProjectStatus {+func calculateProjectStatus(services []ProjectServiceInfo) ProjectStatus {if len(services) == 0 {- return models.ProjectStatusUnknown+ return ProjectStatusUnknown}runningCount := 0@@ -625,13 +628,13 @@ func calculateProjectStatus(services []ProjectServiceInfo) models.ProjectStatus}if runningCount == len(services) {- return models.ProjectStatusRunning+ return ProjectStatusRunning}if runningCount > 0 {- return models.ProjectStatusPartiallyRunning+ return ProjectStatusPartiallyRunning}if stoppedCount > 0 {- return models.ProjectStatusStopped+ return ProjectStatusStopped}- return models.ProjectStatusUnknown+ return ProjectStatusUnknown}diff --git a/backend/internal/project/project_lifecycle.go b/backend/internal/project/project_lifecycle.goindex 0e441901d..bef5a4715 100644--- a/backend/internal/project/project_lifecycle.go+++ b/backend/internal/project/project_lifecycle.go@@ -1,6 +1,10 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context"stderrors "errors""fmt"@@ -15,7 +19,6 @@ import (composetypes "github.com/compose-spec/compose-go/v2/types""github.com/docker/compose/v5/pkg/api""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -60,7 +63,7 @@ func (s *ProjectService) composePullSelectedServicesInternal(ctx context.Context,compProj *composetypes.Project,servicesToUpdate []string,- user models.User,+ user common.User,credentials []containerregistry.Credential,) error {if compProj == nil {@@ -86,7 +89,7 @@ func (s *ProjectService) pullAndReconcileImageInternal(ctx context.Context,imageRef string,progressWriter io.Writer,- user models.User,+ user common.User,credentials []containerregistry.Credential,) error {if s == nil || s.imageService == nil {@@ -109,7 +112,7 @@ func (s *ProjectService) pullAndReconcileImageInternal(return nil}-func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID string, servicesToUpdate []string, user models.User) error {+func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID string, servicesToUpdate []string, user common.User) error {projectFromDb, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {return err@@ -123,7 +126,7 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID st}// 2. Set status to deploying/restarting- if err := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusDeploying); err != nil {+ if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusDeploying); err != nil {return err}@@ -155,29 +158,29 @@ func (s *ProjectService) UpdateProjectServices(ctx context.Context, projectID st}// 6. Finalize status- if err := s.updateProjectStatusandCountsInternal(ctx, projectID, models.ProjectStatusRunning); err != nil {+ if err := s.updateProjectStatusandCountsInternal(ctx, projectID, ProjectStatusRunning); err != nil {return err}- metadata := models.JSON{+ metadata := database.JSON{"action": "update_services","projectID": projectID,"projectName": projectFromDb.Name,"services": append([]string(nil), servicesToUpdate...),}- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, projectID, projectFromDb.Name, user, metadata, "could not log project service update action")+ s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, projectID, projectFromDb.Name, user, metadata, "could not log project service update action")return nil}-func ensureProjectMutableInternal(proj *models.Project) error {+func ensureProjectMutableInternal(proj *Project) error {if proj != nil && proj.IsArchived {return common.Classify(common.ErrProjectArchived, errors.New("project is archived and must be unarchived before this action"))}return nil}-func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, user models.User) error {+func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, user common.User) error {proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {return err@@ -201,20 +204,20 @@ func (s *ProjectService) ArchiveProject(ctx context.Context, projectID string, u}now := time.Now()- if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", projectID).Updates(map[string]any{+ if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{"is_archived": true,"archived_at": now,}).Error; err != nil {return errors.WrapIf(err, "failed to archive project")}- metadata := models.JSON{"action": "archived", "projectID": projectID, "projectName": proj.Name}- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, projectID, proj.Name, user, metadata, "could not log project archive action")+ metadata := database.JSON{"action": "archived", "projectID": projectID, "projectName": proj.Name}+ s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, projectID, proj.Name, user, metadata, "could not log project archive action")return nil}-func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string, user models.User) error {+func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string, user common.User) error {proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {return err@@ -223,15 +226,15 @@ func (s *ProjectService) UnarchiveProject(ctx context.Context, projectID string,return nil}- if err := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", projectID).Updates(map[string]any{+ if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{"is_archived": false,"archived_at": gorm.Expr("NULL"),}).Error; err != nil {return errors.WrapIf(err, "failed to unarchive project")}- metadata := models.JSON{"action": "unarchived", "projectID": projectID, "projectName": proj.Name}- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, projectID, proj.Name, user, metadata, "could not log project unarchive action")+ metadata := database.JSON{"action": "unarchived", "projectID": projectID, "projectName": proj.Name}+ s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, projectID, proj.Name, user, metadata, "could not log project unarchive action")return nil}@@ -249,7 +252,7 @@ func resolveRemoveOrphansInternal(gitOpsManaged bool, options *project.DeployOptreturn gitOpsManaged || (options != nil && options.RemoveOrphans)}-func (s *ProjectService) DeployProject(ctx context.Context, projectID string, user models.User, options *project.DeployOptions) error {+func (s *ProjectService) DeployProject(ctx context.Context, projectID string, user common.User, options *project.DeployOptions) error {projectFromDb, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {return errors.WrapIf(err, "failed to get project")@@ -273,7 +276,7 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, usresolvedPullPolicy = "missing"}- if err := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusDeploying); err != nil {+ if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusDeploying); err != nil {return errors.WrapIf(err, "failed to update project status to deploying")}@@ -327,17 +330,17 @@ func (s *ProjectService) DeployProject(ctx context.Context, projectID string, us}slog.Info("compose up completed successfully", "projectID", projectID, "projectName", projectModel.Name)- metadata := models.JSON{"action": "deploy", "projectID": projectID, "projectName": projectModel.Name}- s.logProjectEventInternal(ctx, models.EventTypeProjectDeploy, projectID, projectModel.Name, user, metadata, "could not log project deployment action")+ metadata := database.JSON{"action": "deploy", "projectID": projectID, "projectName": projectModel.Name}+ s.logProjectEventInternal(ctx, event.EventTypeProjectDeploy, projectID, projectModel.Name, user, metadata, "could not log project deployment action")- err = s.updateProjectStatusandCountsInternal(ctx, projectID, models.ProjectStatusRunning)+ err = s.updateProjectStatusandCountsInternal(ctx, projectID, ProjectStatusRunning)if err != nil {slog.Error("failed to update project status and counts after deploy", "projectID", projectID, "error", err)}return err}-func (s *ProjectService) DownProject(ctx context.Context, projectID string, user models.User) error {+func (s *ProjectService) DownProject(ctx context.Context, projectID string, user common.User) error {projectFromDb, err := s.getMutableProjectInternal(ctx, projectID)if err != nil {return err@@ -345,27 +348,27 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, userproj, _, lerr := s.loadComposeProjectForProjectInternal(ctx, projectFromDb, nil)if lerr != nil {- _ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)+ _ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)return errors.WrapIf(lerr, "failed to load compose project")}- if err := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusStopped); err != nil {+ if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusStopped); err != nil {return errors.WrapIf(err, "failed to update project status to stopping")}if err := projects.ComposeDown(ctx, proj, false); err != nil {- _ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)+ _ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)return errors.WrapIf(err, "failed to bring down project")}- metadata := models.JSON{+ metadata := database.JSON{"action": "down","projectID": projectID,"projectName": projectFromDb.Name,}- s.logProjectEventInternal(ctx, models.EventTypeProjectStop, projectID, projectFromDb.Name, user, metadata, "could not log project down action")+ s.logProjectEventInternal(ctx, event.EventTypeProjectStop, projectID, projectFromDb.Name, user, metadata, "could not log project down action")- return s.updateProjectStatusandCountsInternal(ctx, projectID, models.ProjectStatusStopped)+ return s.updateProjectStatusandCountsInternal(ctx, projectID, ProjectStatusStopped)}// CreateProject creates a project's directory, files, and DB row. When@@ -373,7 +376,7 @@ func (s *ProjectService) DownProject(ctx context.Context, projectID string, user// "-N" (the interactive default). When false a collision returns// projects.ErrProjectDirExists (wrapped) so GitOps creates fail loudly instead of// minting runaway "-N" duplicate projects on a broken binding.-func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, manifest project.CreateProjectWorkspaceManifest, uploads map[int][]byte, uiTags []string, uiTagColors map[string]project.TagColor, user models.User, allowNameSuffixOptions ...bool) (*models.Project, error) {+func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent string, envContent *string, manifest project.CreateProjectWorkspaceManifest, uploads map[int][]byte, uiTags []string, uiTagColors map[string]project.TagColor, user common.User, allowNameSuffixOptions ...bool) (*Project, error) {normalizedUITags, err := projects.NormalizeProjectTags(uiTags)if err != nil {return nil, errors.WrapIf(err, "invalid project tags")@@ -413,11 +416,11 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContentreturn nil, errors.WrapIf(err, "failed to resolve created project directory")}- proj := &models.Project{+ proj := &Project{Name: name,DirName: &folderName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,ServiceCount: 0,RunningCount: 0,}@@ -482,13 +485,13 @@ func (s *ProjectService) CreateProject(ctx context.Context, name, composeContent)}- metadata := models.JSON{"action": "create", "projectID": proj.ID, "projectName": proj.Name, "path": projectPath}- s.logProjectEventInternal(ctx, models.EventTypeProjectCreate, proj.ID, proj.Name, user, metadata, "could not log project creation")+ metadata := database.JSON{"action": "create", "projectID": proj.ID, "projectName": proj.Name, "path": projectPath}+ s.logProjectEventInternal(ctx, event.EventTypeProjectCreate, proj.ID, proj.Name, user, metadata, "could not log project creation")return proj, nil}-func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, removeFiles bool, removeVolumes bool, user models.User) error {+func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, removeFiles bool, removeVolumes bool, user common.User) error {slog.DebugContext(ctx, "DestroyProject service called","projectID", projectID,"removeFiles", removeFiles,@@ -505,7 +508,7 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, r"projectName", proj.Name,"projectPath", proj.Path)- if err := s.DownProject(ctx, projectID, models.SystemUser); err != nil {+ if err := s.DownProject(ctx, projectID, common.SystemUser); err != nil {slog.WarnContext(ctx, "failed to bring down project", "error", err)}@@ -551,13 +554,13 @@ func (s *ProjectService) DestroyProject(ctx context.Context, projectID string, r}s.parsedCompose.invalidate(projectID)- metadata := models.JSON{"action": "destroy", "projectID": projectID, "projectName": proj.Name, "removeFiles": removeFiles, "removeVolumes": removeVolumes}- s.logProjectEventInternal(ctx, models.EventTypeProjectDelete, projectID, proj.Name, user, metadata, "could not log project destroy action")+ metadata := database.JSON{"action": "destroy", "projectID": projectID, "projectName": proj.Name, "removeFiles": removeFiles, "removeVolumes": removeVolumes}+ s.logProjectEventInternal(ctx, event.EventTypeProjectDelete, projectID, proj.Name, user, metadata, "could not log project destroy action")return nil}-func (s *ProjectService) RedeployProject(ctx context.Context, projectID string, user models.User, options *project.DeployOptions) error {+func (s *ProjectService) RedeployProject(ctx context.Context, projectID string, user common.User, options *project.DeployOptions) error {proj, err := s.getMutableProjectInternal(ctx, projectID)if err != nil {return err@@ -581,13 +584,13 @@ func (s *ProjectService) RedeployProject(ctx context.Context, projectID string,slog.WarnContext(ctx, "failed to pull project images", "error", err)}- metadata := models.JSON{"action": "redeploy", "projectID": projectID, "projectName": proj.Name}- s.logProjectEventInternal(ctx, models.EventTypeProjectDeploy, projectID, proj.Name, user, metadata, "could not log project redeploy action")+ metadata := database.JSON{"action": "redeploy", "projectID": projectID, "projectName": proj.Name}+ s.logProjectEventInternal(ctx, event.EventTypeProjectDeploy, projectID, proj.Name, user, metadata, "could not log project redeploy action")return s.DeployProject(ctx, projectID, user, options)}-func (s *ProjectService) projectRedeployDisabledInternal(ctx context.Context, proj models.Project) bool {+func (s *ProjectService) projectRedeployDisabledInternal(ctx context.Context, proj Project) bool {containers, err := s.listGlobalComposeContainersInternal(ctx)if err != nil {slog.WarnContext(ctx, "could not list compose containers to check self-redeploy guard; skipping guard", "error", err)@@ -606,7 +609,7 @@ func (s *ProjectService) projectRedeployDisabledInternal(ctx context.Context, prreturn false}-func (s *ProjectService) PullProjectImages(ctx context.Context, projectID string, progressWriter io.Writer, user models.User, credentials []containerregistry.Credential) error {+func (s *ProjectService) PullProjectImages(ctx context.Context, projectID string, progressWriter io.Writer, user common.User, credentials []containerregistry.Credential) error {proj, err := s.getMutableProjectInternal(ctx, projectID)if err != nil {return err@@ -644,7 +647,7 @@ func (s *ProjectService) PullProjectImages(ctx context.Context, projectID stringreturn nil}-func (s *ProjectService) BuildProjectServices(ctx context.Context, projectID string, options ProjectBuildOptions, progressWriter io.Writer, user *models.User) error {+func (s *ProjectService) BuildProjectServices(ctx context.Context, projectID string, options ProjectBuildOptions, progressWriter io.Writer, user *common.User) error {projectFromDb, err := s.getMutableProjectInternal(ctx, projectID)if err != nil {return err@@ -663,7 +666,7 @@ func (s *ProjectService) BuildProjectServices(ctx context.Context, projectID str// - always/refresh: always pull// - missing/if_not_present/default: pull only if local image is missing// - never: never pull (fails early if image is missing locally)-func (s *ProjectService) EnsureProjectImagesPresent(ctx context.Context, projectID string, progressWriter io.Writer, user models.User, credentials []containerregistry.Credential) error {+func (s *ProjectService) EnsureProjectImagesPresent(ctx context.Context, projectID string, progressWriter io.Writer, user common.User, credentials []containerregistry.Credential) error {proj, err := s.getMutableProjectInternal(ctx, projectID)if err != nil {return err@@ -679,7 +682,7 @@ func (s *ProjectService) EnsureProjectImagesPresent(ctx context.Context, projectreturn s.ensureImagesPresent(ctx, pullPlan, progressWriter, credentials, user)}-func (s *ProjectService) ensureImagesPresent(ctx context.Context, pullPlan map[string]projects.ImagePullMode, progressWriter io.Writer, credentials []containerregistry.Credential, user models.User) error {+func (s *ProjectService) ensureImagesPresent(ctx context.Context, pullPlan map[string]projects.ImagePullMode, progressWriter io.Writer, credentials []containerregistry.Credential, user common.User) error {for img, mode := range pullPlan {exists, ierr := s.imageService.ImageExistsLocally(ctx, img)if ierr != nil && mode != projects.ImagePullModeAlways {@@ -717,7 +720,7 @@ func (s *ProjectService) prepareProjectImagesForDeploy(project *composetypes.Project,progressWriter io.Writer,credentials []containerregistry.Credential,- user *models.User,+ user *common.User,pullPolicyOverride string,) error {if project == nil {@@ -777,7 +780,7 @@ func (s *ProjectService) ensureDeployServiceImageReady(decision projects.DeployImageDecision,progressWriter io.Writer,credentials []containerregistry.Credential,- user *models.User,+ user *common.User,) error {if decision.Build {return s.buildServiceImageForDeploy(ctx, projectID, project, serviceName, svc, progressWriter, user)@@ -799,7 +802,7 @@ func (s *ProjectService) ensureDeployServiceImageReady(return nil}- err = s.pullAndReconcileImageInternal(ctx, imageName, progressWriter, models.SystemUser, credentials)+ err = s.pullAndReconcileImageInternal(ctx, imageName, progressWriter, common.SystemUser, credentials)if err == nil {return nil}@@ -817,7 +820,7 @@ func (s *ProjectService) buildServiceImageForDeploy(serviceName string,svc composetypes.ServiceConfig,progressWriter io.Writer,- user *models.User,+ user *common.User,) error {if s.buildService == nil {return errors.Errorf("build service not available for service %s", serviceName)@@ -937,7 +940,7 @@ func (s *ProjectService) restoreProjectStatusAfterFailedDeployInternal(ctx conteif err == nil {serviceCount, runningCount := getServiceCounts(services)status := calculateProjectStatus(services)- updateErr := s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", projectID).Updates(map[string]any{+ updateErr := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", projectID).Updates(map[string]any{"status": status,"service_count": serviceCount,"running_count": runningCount,@@ -951,12 +954,12 @@ func (s *ProjectService) restoreProjectStatusAfterFailedDeployInternal(ctx conteslog.WarnContext(ctx, "failed to inspect project services after deploy failure", "projectID", projectID, "error", err)}- if updateErr := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusStopped); updateErr != nil {+ if updateErr := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusStopped); updateErr != nil {slog.WarnContext(ctx, "failed to set stopped status after deploy failure", "projectID", projectID, "error", updateErr)}}-func (s *ProjectService) buildProjectServicesInternal(ctx context.Context, projectID string, project *composetypes.Project, options ProjectBuildOptions, progressWriter io.Writer, user *models.User) error {+func (s *ProjectService) buildProjectServicesInternal(ctx context.Context, projectID string, project *composetypes.Project, options ProjectBuildOptions, progressWriter io.Writer, user *common.User) error {if s.buildService == nil {return nil}@@ -996,13 +999,13 @@ func (s *ProjectService) buildProjectServicesInternal(ctx context.Context, projereturn nil}-func (s *ProjectService) RestartProject(ctx context.Context, projectID string, services []string, user models.User) error {+func (s *ProjectService) RestartProject(ctx context.Context, projectID string, services []string, user common.User) error {proj, err := s.getMutableProjectInternal(ctx, projectID)if err != nil {return err}- if err := s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRestarting); err != nil {+ if err := s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRestarting); err != nil {return errors.WrapIf(err, "failed to update project status to restarting")}@@ -1023,16 +1026,16 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, scompProj, _, lerr := projects.LoadComposeProjectFromDir(ctx, proj.Path, projects.NormalizeProjectName(proj.Name), projectsDirectory, utils.BoolOrDefault(cfg.AutoInjectEnv.Value, false), pathMapper)if lerr != nil {- _ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)+ _ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)return errors.WrapIf(lerr, "failed to load compose project")}if err := projects.ComposeRestart(ctx, compProj, services); err != nil {- _ = s.updateProjectStatusInternal(ctx, projectID, models.ProjectStatusRunning)+ _ = s.updateProjectStatusInternal(ctx, projectID, ProjectStatusRunning)return errors.WrapIf(err, "failed to restart project")}- metadata := models.JSON{+ metadata := database.JSON{"action": "restart","projectID": projectID,"projectName": proj.Name,@@ -1040,7 +1043,7 @@ func (s *ProjectService) RestartProject(ctx context.Context, projectID string, sif len(services) > 0 {metadata["services"] = append([]string(nil), services...)}- s.logProjectEventInternal(ctx, models.EventTypeProjectStart, projectID, proj.Name, user, metadata, "could not log project restart action")+ s.logProjectEventInternal(ctx, event.EventTypeProjectStart, projectID, proj.Name, user, metadata, "could not log project restart action")- return s.updateProjectStatusandCountsInternal(ctx, projectID, models.ProjectStatusRunning)+ return s.updateProjectStatusandCountsInternal(ctx, projectID, ProjectStatusRunning)}diff --git a/backend/internal/project/project_listing.go b/backend/internal/project/project_listing.goindex 9ecbd108d..f24bba13e 100644--- a/backend/internal/project/project_listing.go+++ b/backend/internal/project/project_listing.go@@ -1,6 +1,8 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""log/slog""maps"@@ -11,7 +13,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/image"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -56,7 +57,7 @@ func groupComposeContainersByProjectInternal(containers []container.Summary) map// lookupProjectContainers returns containers matched to a project, trying the// normalized directory name first and falling back to the effective compose// project name (from COMPOSE_PROJECT_NAME) when it differs.-func lookupProjectContainers(p models.Project, containersByProject map[string][]container.Summary) []container.Summary {+func lookupProjectContainers(p Project, containersByProject map[string][]container.Summary) []container.Summary {normName := projects.NormalizeProjectName(p.Name)if c := containersByProject[normName]; len(c) > 0 {return c@@ -67,8 +68,8 @@ func lookupProjectContainers(p models.Project, containersByProject map[string][]return nil}-func (s *ProjectService) ListAllProjects(ctx context.Context) ([]models.Project, error) {- var items []models.Project+func (s *ProjectService) ListAllProjects(ctx context.Context) ([]Project, error) {+ var items []Projectif err := s.db.WithContext(ctx).Find(&items).Error; err != nil {return nil, errors.WrapIf(err, "list projects")}@@ -104,13 +105,13 @@ func (s *ProjectService) countProjectFolders(ctx context.Context) (int, error) {return len(discoveredProjects), nil}-func incrementStatusCounts(status models.ProjectStatus, running, stopped *int) {+func incrementStatusCounts(status ProjectStatus, running, stopped *int) {switch status {- case models.ProjectStatusRunning, models.ProjectStatusPartiallyRunning, models.ProjectStatusDeploying, models.ProjectStatusRestarting:+ case ProjectStatusRunning, ProjectStatusPartiallyRunning, ProjectStatusDeploying, ProjectStatusRestarting:*running++- case models.ProjectStatusStopped, models.ProjectStatusStopping:+ case ProjectStatusStopped, ProjectStatusStopping:*stopped++- case models.ProjectStatusUnknown:+ case ProjectStatusUnknown:// Don't count unknown}}@@ -118,7 +119,7 @@ func incrementStatusCounts(status models.ProjectStatus, running, stopped *int) {func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCount, runningProjects, stoppedProjects, totalProjects, archivedProjects int, err error) {folderCount, _ = s.countProjectFolders(ctx)- var projectsList []models.Project+ var projectsList []Projectif err := s.db.WithContext(ctx).Find(&projectsList).Error; err != nil {return folderCount, 0, 0, 0, 0, errors.WrapIf(err, "failed to list projects")}@@ -126,7 +127,7 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCountotalProjects = len(projectsList)runningProjects = 0stoppedProjects = 0- activeProjects := make([]models.Project, 0, len(projectsList))+ activeProjects := make([]Project, 0, len(projectsList))for _, p := range projectsList {if p.IsArchived {archivedProjects++@@ -161,9 +162,9 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCoun})}- var status models.ProjectStatus+ var status ProjectStatusif len(services) == 0 {- status = models.ProjectStatusStopped+ status = ProjectStatusStopped} else {status = calculateProjectStatus(services)}@@ -175,7 +176,7 @@ func (s *ProjectService) GetProjectStatusCounts(ctx context.Context) (folderCoun}func (s *ProjectService) ListProjects(ctx context.Context, params pagination.QueryParams) ([]project.Details, pagination.Response, error) {- query := s.db.WithContext(ctx).Model(&models.Project{})+ query := s.db.WithContext(ctx).Model(&Project{})statusFilter := ""updatesFilter := ""archivedFilter := ""@@ -198,7 +199,7 @@ func (s *ProjectService) ListProjects(ctx context.Context, params pagination.Quequery = pagination.ApplyFilter(query, "status", params.Filters["status"])- var projectsArray []models.Project+ var projectsArray []ProjectpaginationResp, err := pagination.PaginateAndSortDB(params, query, &projectsArray)if err != nil {return nil, pagination.Response{}, errors.WrapIf(err, "failed to paginate projects")@@ -294,7 +295,7 @@ func (s *ProjectService) filterProjectsWithDerivedFiltersInternal(params pagination.QueryParams,query *gorm.DB,) (pagination.FilterResult[project.Details], error) {- var projectsArray []models.Project+ var projectsArray []Projectif term := strings.TrimSpace(params.Search); term != "" {query = applyProjectSearchDBFilterInternal(query, term)}@@ -324,7 +325,7 @@ func withoutProjectDBFiltersInternal(params pagination.QueryParams) pagination.Qfunc (s *ProjectService) appendDiscoveredComposeProjectUpdatesInternal(ctx context.Context,params pagination.QueryParams,- projectsArray []models.Project,+ projectsArray []Project,items []project.Details,) []project.Details {if !shouldIncludeDiscoveredComposeProjectUpdatesInternal(params) {@@ -357,7 +358,7 @@ func shouldIncludeDiscoveredComposeProjectUpdatesInternal(params pagination.Quer// buildKnownComposeProjectNameSetInternal collects every project name Arcane// tracks. projectsArrayIsComplete tells it the caller already loaded the full// table (not a filtered page), so the catch-all re-query can be skipped.-func (s *ProjectService) buildKnownComposeProjectNameSetInternal(ctx context.Context, projectsArray []models.Project, projectsArrayIsComplete bool) map[string]struct{} {+func (s *ProjectService) buildKnownComposeProjectNameSetInternal(ctx context.Context, projectsArray []Project, projectsArrayIsComplete bool) map[string]struct{} {known := make(map[string]struct{}, len(projectsArray)*2)for _, proj := range projectsArray {addKnownComposeProjectNameInternal(known, proj.Name)@@ -370,7 +371,7 @@ func (s *ProjectService) buildKnownComposeProjectNameSetInternal(ctx context.Conreturn known}- var allProjects []models.Project+ var allProjects []Projectif err := s.db.WithContext(ctx).Select("name", "compose_project_name").Find(&allProjects).Error; err != nil {slog.WarnContext(ctx, "failed to load known project names for compose update discovery", "error", err)return known@@ -575,13 +576,13 @@ func buildDiscoveredRuntimeServicesInternal(containers []container.Summary, iconfunc resolveDiscoveredProjectStatusInternal(serviceCount int, runningCount int) string {switch {case serviceCount == 0:- return string(models.ProjectStatusUnknown)+ return string(ProjectStatusUnknown)case runningCount >= serviceCount:- return string(models.ProjectStatusRunning)+ return string(ProjectStatusRunning)case runningCount > 0:- return string(models.ProjectStatusPartiallyRunning)+ return string(ProjectStatusPartiallyRunning)default:- return string(models.ProjectStatusStopped)+ return string(ProjectStatusStopped)}}@@ -717,12 +718,12 @@ func (s *ProjectService) CountProjectsWithPendingUpdates(ctx context.Context, al// One full scan: archived projects are excluded from the update count but// still mark their compose stacks as known during discovery, so loading// everything here saves the known-name pass its own table scan.- var allProjects []models.Project+ var allProjects []Projectif err := s.db.WithContext(ctx).Find(&allProjects).Error; err != nil {return 0, errors.WrapIf(err, "failed to list projects for update count")}- activeProjects := make([]models.Project, 0, len(allProjects))+ activeProjects := make([]Project, 0, len(allProjects))for _, proj := range allProjects {if !proj.IsArchived {activeProjects = append(activeProjects, proj)@@ -751,7 +752,7 @@ func (s *ProjectService) CountProjectsWithPendingUpdates(ctx context.Context, al// the daemon that Arcane does not track but that have a pending image update, so// the dashboard badge matches the projects table. Errors are logged and counted// as zero: a missing container list should degrade the badge, not fail the load.-func (s *ProjectService) countDiscoveredComposeProjectUpdatesInternal(ctx context.Context, projectsArray []models.Project, projectsArrayIsComplete bool, allContainers []container.Summary) int {+func (s *ProjectService) countDiscoveredComposeProjectUpdatesInternal(ctx context.Context, projectsArray []Project, projectsArrayIsComplete bool, allContainers []container.Summary) int {if allContainers == nil {var err errorallContainers, err = s.listGlobalComposeContainersInternal(ctx)@@ -778,7 +779,7 @@ func (s *ProjectService) countDiscoveredComposeProjectUpdatesInternal(ctx contex// fetchProjectStatusConcurrently fetches live Docker status for multiple projects in parallel// Optimized to use a single Docker API call instead of N calls + N file reads-func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, projectsList []models.Project) []project.Details {+func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, projectsList []Project) []project.Details {projectsDir, err := s.GetProjectsDirectory(ctx)if err != nil {slog.WarnContext(ctx, "failed to resolve projects directory for relative project paths", "error", err)@@ -807,7 +808,7 @@ func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, prometa := s.ProjectMetadata(ctx, p, metaEnv)applyResolvedProjectIconInternal(&results[i], iconcatalog.Resolve(IconCatalogForContext(ctx), meta.ProjectIcon))results[i].URLs = meta.ProjectURLS- results[i].Status = string(models.ProjectStatusUnknown)+ results[i].Status = string(ProjectStatusUnknown)}return results}@@ -825,7 +826,7 @@ func (s *ProjectService) fetchProjectStatusConcurrently(ctx context.Context, proreturn results}-func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string, p models.Project, containersByProject map[string][]container.Summary, currentContainerID string, currentContainerErr error, metaEnv *projectMetadataEnvInternal) project.Details {+func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string, p Project, containersByProject map[string][]container.Summary, currentContainerID string, currentContainerErr error, metaEnv *projectMetadataEnvInternal) project.Details {var resp project.Details_ = mapper.MapStruct(p, &resp)@@ -915,7 +916,7 @@ func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir stringresp.ServiceCount = len(services)// Persist the inferred count so later list loads do not need compose parsing.go func(ctx context.Context, pid string, count int) {- s.db.WithContext(ctx).Model(&models.Project{}).Where("id = ?", pid).Update("service_count", count)+ s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", pid).Update("service_count", count)}(context.WithoutCancel(ctx), p.ID, resp.ServiceCount)}@@ -932,15 +933,15 @@ func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string// live container/service list as the source of truth.actualServiceCount := len(services)if actualServiceCount == 0 {- resp.Status = string(models.ProjectStatusStopped)+ resp.Status = string(ProjectStatusStopped)} else {switch {case runningCount >= actualServiceCount:- resp.Status = string(models.ProjectStatusRunning)+ resp.Status = string(ProjectStatusRunning)case runningCount > 0:- resp.Status = string(models.ProjectStatusPartiallyRunning)+ resp.Status = string(ProjectStatusPartiallyRunning)default:- resp.Status = string(models.ProjectStatusStopped)+ resp.Status = string(ProjectStatusStopped)}}@@ -955,7 +956,7 @@ func (s *ProjectService) mapProjectToDto(ctx context.Context, projectsDir string// env may be nil, in which case the projects directory and autoInjectEnv setting// are resolved here; callers iterating over many projects should resolve them// once and pass them in.-func (s *ProjectService) ProjectMetadata(ctx context.Context, p models.Project, env *projectMetadataEnvInternal) projects.ArcaneComposeMetadata {+func (s *ProjectService) ProjectMetadata(ctx context.Context, p Project, env *projectMetadataEnvInternal) projects.ArcaneComposeMetadata {if s.metaCache != nil && p.ID != "" {if meta, ok, _ := s.metaCache.Get(p.ID); ok {return meta@@ -998,7 +999,7 @@ func (s *ProjectService) ProjectMetadata(ctx context.Context, p models.Project,// is populated from the X-Arcane-Icon-Catalog header the manager forwards.// Background jobs have no user attached and fall back to the default catalog.func IconCatalogForContext(ctx context.Context) string {- if u, ok := models.CurrentUserFromContext(ctx); ok && u != nil && u.Preferences.IconCatalog != nil && *u.Preferences.IconCatalog != "" {+ if u, ok := common.CurrentUserFromContext(ctx); ok && u != nil && u.Preferences.IconCatalog != nil && *u.Preferences.IconCatalog != "" {return *u.Preferences.IconCatalog}return iconcatalog.DefaultCatalogdiff --git a/backend/internal/project/project_rename_journal.go b/backend/internal/project/project_rename_journal.goindex f8853827f..3d5b7713b 100644--- a/backend/internal/project/project_rename_journal.go+++ b/backend/internal/project/project_rename_journal.go@@ -12,7 +12,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumes""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -164,7 +163,7 @@ func (s *ProjectService) completeProjectRenameJournalForUpdateInternal(ctx conte*journalActive = false}-func withProjectRenameRollback(ctx context.Context, proj *models.Project, projectStateCommitted *bool, run func() error) error {+func withProjectRenameRollback(ctx context.Context, proj *Project, projectStateCommitted *bool, run func() error) error {originalPath := proj.PathoriginalDirName := proj.DirName@@ -200,7 +199,7 @@ func withProjectRenameRollback(ctx context.Context, proj *models.Project, projecreturn nil}-func (s *ProjectService) prepareProjectRenameJournalInternal(proj *models.Project, name *string, projectsDirectory string, migration volumes.Migration) *projectRenameJournalInternal {+func (s *ProjectService) prepareProjectRenameJournalInternal(proj *Project, name *string, projectsDirectory string, migration volumes.Migration) *projectRenameJournalInternal {if s == nil || s.kvService == nil || proj == nil || name == nil {return nil}@@ -358,7 +357,7 @@ func (s *ProjectService) recoverProjectRenameJournalInternal(ctx context.Contextreturn nil}- var proj models.Project+ var proj ProjectdbErr := s.db.WithContext(ctx).First(&proj, "id = ?", journal.ProjectID).Errorif dbErr != nil && !errors.Is(dbErr, gorm.ErrRecordNotFound) {return errors.WrapIf(dbErr, "load project for rename recovery")@@ -421,7 +420,7 @@ func (s *ProjectService) rollbackProjectRenameJournalInternal(ctx context.ContexvolumeErr := s.rollbackProjectRenameJournalVolumesInternal(ctx, journal)- if err := s.db.WithContext(ctx).Model(&models.Project{}).+ if err := s.db.WithContext(ctx).Model(&Project{}).Where("id = ?", journal.ProjectID).Updates(map[string]any{"name": journal.OldName,@@ -482,7 +481,7 @@ func (s *ProjectService) recoverProjectRenameRollbackCleanupInternal(ctx contextreturn s.clearProjectRenameRollbackCleanupInternal(ctx, cleanup.ProjectID)}- var proj models.Project+ var proj ProjectdbErr := s.db.WithContext(ctx).First(&proj, "id = ?", cleanup.ProjectID).Errorif dbErr != nil {if errors.Is(dbErr, gorm.ErrRecordNotFound) {diff --git a/backend/internal/project/project_sync.go b/backend/internal/project/project_sync.goindex 4375a398a..7622036f5 100644--- a/backend/internal/project/project_sync.go+++ b/backend/internal/project/project_sync.go@@ -11,7 +11,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/moby/moby/client"@@ -22,7 +21,7 @@ import (// projectCleanupDecision records a project the reconcile pass intends to delete,// alongside the reason logged when the deletion is carried out.type projectCleanupDecision struct {- project models.Project+ project Projectreason string}@@ -33,7 +32,7 @@ type composeSyncMetadataInternal struct {explicitProjectName bool}-func (s *ProjectService) refreshProjectImageRefsInternal(ctx context.Context, proj *models.Project) {+func (s *ProjectService) refreshProjectImageRefsInternal(ctx context.Context, proj *Project) {if proj == nil || proj.ID == "" {return}@@ -42,7 +41,7 @@ func (s *ProjectService) refreshProjectImageRefsInternal(ctx context.Context, prrefs, buildRefs, err := s.getProjectImageRefsFromComposeInternal(ctx, *proj, nil)if err != nil {if dbErr := s.db.WithContext(ctx).- Model(&models.Project{}).+ Model(&Project{}).Where("id = ?", proj.ID).Updates(map[string]any{"image_refs_json": "",@@ -61,7 +60,7 @@ func (s *ProjectService) refreshProjectImageRefsInternal(ctx context.Context, prbuildImageRefsJSON = "[]"}if err := s.db.WithContext(ctx).- Model(&models.Project{}).+ Model(&Project{}).Where("id = ?", proj.ID).Updates(map[string]any{"image_refs_json": imageRefsJSON,@@ -98,7 +97,7 @@ func (s *ProjectService) BackfillProjectImageRefs(ctx context.Context) (int, errreturn 0, nil}- var projectsList []models.Project+ var projectsList []Projectif err := s.db.WithContext(ctx).Where("build_image_refs_json IS NULL").Find(&projectsList).Error; err != nil {@@ -113,14 +112,14 @@ func (s *ProjectService) BackfillProjectImageRefs(ctx context.Context) (int, errreturn len(projectsList), nil}-func (s *ProjectService) resolveProjectsByChangedPathsInternal(ctx context.Context, paths []string) ([]models.Project, error) {- var projectsList []models.Project+func (s *ProjectService) resolveProjectsByChangedPathsInternal(ctx context.Context, paths []string) ([]Project, error) {+ var projectsList []Projectif err := s.db.WithContext(ctx).Find(&projectsList).Error; err != nil {return nil, errors.WrapIf(err, "list projects for changed paths")}seen := make(map[string]struct{})- affected := make([]models.Project, 0)+ affected := make([]Project, 0)for _, changedPath := range paths {cleanChangedPath := filepath.Clean(changedPath)for _, proj := range projectsList {@@ -183,7 +182,7 @@ func (s *ProjectService) SyncProjectsFromFileSystem(ctx context.Context) error {}func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPath string) error {- var existing models.Project+ var existing Projecterr := s.db.WithContext(ctx).Where("path = ?", dirPath).First(&existing).Error@@ -193,11 +192,11 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPaif errors.Is(err, gorm.ErrRecordNotFound) {// Create a minimal project entryreason := "Project discovered from filesystem, status pending Docker service query"- proj := &models.Project{+ proj := &Project{Name: composeMetadata.resolvedProjectName,DirName: new(dirName),Path: dirPath,- Status: models.ProjectStatusUnknown,+ Status: ProjectStatusUnknown,StatusReason: new(reason),ServiceCount: composeMetadata.serviceCount,RunningCount: 0,@@ -250,7 +249,7 @@ func (s *ProjectService) upsertProjectForDir(ctx context.Context, dirName, dirPaupdates["updated_at"] = time.Now()if uerr := s.db.WithContext(ctx).- Model(&models.Project{}).+ Model(&Project{}).Where("id = ?", existing.ID).Updates(updates).Error; uerr != nil {return errors.WrapIff(uerr, "update project %s failed", existing.ID)@@ -268,7 +267,7 @@ func (s *ProjectService) warnDuplicateComposeNameForPathInternal(ctx context.Convar count int64if err := s.db.WithContext(ctx).- Model(&models.Project{}).+ Model(&Project{}).Where("name = ? AND path <> ? AND id <> ?", composeProjectName, dirPath, projectID).Count(&count).Error; err != nil {slog.WarnContext(ctx, "failed to check duplicate compose project names during project sync", "composeProjectName", composeProjectName, "path", dirPath, "error", err)@@ -280,7 +279,7 @@ func (s *ProjectService) warnDuplicateComposeNameForPathInternal(ctx context.Con}func (s *ProjectService) cleanupDBProjectsInternal(ctx context.Context, seen map[string]struct{}, followProjectSymlinks bool, projectsDir string, maxDepth int) error {- var all []models.Project+ var all []Projectif err := s.db.WithContext(ctx).Find(&all).Error; err != nil {return errors.WrapIf(err, "list projects for cleanup failed")}@@ -350,7 +349,7 @@ func cleanupWouldMassWipeInternal(ctx context.Context, candidates, deleteCount ireturn true}-func skipProjectCleanupInternal(p models.Project, seen map[string]struct{}) bool {+func skipProjectCleanupInternal(p Project, seen map[string]struct{}) bool {// Skip paths seen in this pass.if _, ok := seen[p.Path]; ok {return true@@ -367,7 +366,7 @@ func skipProjectCleanupInternal(p models.Project, seen map[string]struct{}) bool// sync-stage/backup). Such rows are never real user projects — a crash or restart// mid-operation can leak the scratch dir, which the filesystem discovery then imports.// They are force-removed during cleanup regardless of whether the dir still exists.-func isInternalScratchProjectInternal(p models.Project) bool {+func isInternalScratchProjectInternal(p Project) bool {if projects.IsInternalScratchDirName(p.Name) || projects.IsInternalScratchDirName(filepath.Base(p.Path)) {return true}@@ -378,7 +377,7 @@ func isInternalScratchProjectInternal(p models.Project) bool {// the current filesystem pass should be pruned. It performs only read-only checks// (warning in place for the "keep" cases); the actual deletion is deferred to the// caller so the mass-wipe guard can veto an entire suspicious pass.-func (s *ProjectService) evaluateProjectCleanupInternal(ctx context.Context, p models.Project, followProjectSymlinks bool, projectsDir string, maxDepth int) mo.Option[projectCleanupDecision] {+func (s *ProjectService) evaluateProjectCleanupInternal(ctx context.Context, p Project, followProjectSymlinks bool, projectsDir string, maxDepth int) mo.Option[projectCleanupDecision] {if s.projectExceedsScanDepthInternal(p, projectsDir, maxDepth) {return mo.Some(projectCleanupDecision{project: p, reason: "removed project: directory is beyond the configured scan depth"})}@@ -394,7 +393,7 @@ func (s *ProjectService) evaluateProjectCleanupInternal(ctx context.Context, p mreturn s.evaluateProjectComposeFileInternal(ctx, p)}-func (s *ProjectService) projectExceedsScanDepthInternal(p models.Project, projectsDir string, maxDepth int) bool {+func (s *ProjectService) projectExceedsScanDepthInternal(p Project, projectsDir string, maxDepth int) bool {// Remove projects that still exist on disk but now fall outside the configured// scan depth (e.g. after PROJECT_SCAN_MAX_DEPTH was lowered). They are no// longer discovered, so they must not linger in the list. Projects at the@@ -408,7 +407,7 @@ func (s *ProjectService) projectExceedsScanDepthInternal(p models.Project, projereturn rel != "" && strings.Count(rel, "/")+1 > maxDepth}-func evaluateProjectPathErrorInternal(ctx context.Context, p models.Project, err error) mo.Option[projectCleanupDecision] {+func evaluateProjectPathErrorInternal(ctx context.Context, p Project, err error) mo.Option[projectCleanupDecision] {if os.IsNotExist(err) {return mo.Some(projectCleanupDecision{project: p, reason: "removed project: directory no longer exists"})}@@ -417,7 +416,7 @@ func evaluateProjectPathErrorInternal(ctx context.Context, p models.Project, errreturn mo.None[projectCleanupDecision]()}-func (s *ProjectService) evaluateProjectComposeFileInternal(ctx context.Context, p models.Project) mo.Option[projectCleanupDecision] {+func (s *ProjectService) evaluateProjectComposeFileInternal(ctx context.Context, p Project) mo.Option[projectCleanupDecision] {_, err := s.ResolveProjectComposeFile(ctx, &p)if err == nil {return mo.None[projectCleanupDecision]()@@ -443,7 +442,7 @@ func (s *ProjectService) evaluateProjectComposeFileInternal(ctx context.Context,// stale during the filesystem reconcile. Every removal is logged (WARN on// success, ERROR on failure) so this destructive operation always leaves an// audit trail — previously successful deletions were silent.-func (s *ProjectService) deleteProjectDuringCleanupInternal(ctx context.Context, p models.Project, reason string, attrs ...any) {+func (s *ProjectService) deleteProjectDuringCleanupInternal(ctx context.Context, p Project, reason string, attrs ...any) {logAttrs := make([]any, 0, 6+len(attrs))logAttrs = append(logAttrs, "projectID", p.ID, "name", p.Name, "path", p.Path)logAttrs = append(logAttrs, attrs...)diff --git a/backend/internal/project/project_tags.go b/backend/internal/project/project_tags.goindex 970e924bc..b32ba3144 100644--- a/backend/internal/project/project_tags.go+++ b/backend/internal/project/project_tags.go@@ -1,12 +1,17 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""sort""strings""emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"projectpkg "github.com/getarcaneapp/arcane/backend/v2/pkg/projects"projecttypes "github.com/getarcaneapp/arcane/types/v2/project""gorm.io/gorm"@@ -26,7 +31,7 @@ func (s *ProjectService) GetProjectTags(ctx context.Context, projectID string) (// ListProjectTagOptions returns the distinct tag names and colors available in the current environment.func (s *ProjectService) ListProjectTagOptions(ctx context.Context) ([]projecttypes.TagOption, error) {- var rows []models.ProjectTag+ var rows []ProjectTagif err := s.db.WithContext(ctx).Order("name, source DESC, color").Find(&rows).Error; err != nil {return nil, errors.WrapIf(err, "list project tag options")}@@ -41,7 +46,7 @@ func (s *ProjectService) ListProjectTagOptions(ctx context.Context) ([]projectty}// UpdateProjectTag attaches or detaches a UI-managed tag and rejects Compose-owned names.-func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name string, color projecttypes.TagColor, attached bool, user models.User) ([]projecttypes.Tag, error) {+func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name string, color projecttypes.TagColor, attached bool, user common.User) ([]projecttypes.Tag, error) {normalized, err := projectpkg.NormalizeProjectTag(name)if err != nil {return nil, err@@ -54,14 +59,14 @@ func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name s}}- var projectModel models.Project+ var projectModel Projecterr = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&projectModel, "id = ?", projectID).Error; err != nil {return errors.WrapIf(err, "find project for tag update")}var composeCount int64- if err := tx.Model(&models.ProjectTag{}).+ if err := tx.Model(&ProjectTag{}).Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceCompose).Count(&composeCount).Error; err != nil {return errors.WrapIf(err, "check Compose tag source")@@ -72,7 +77,7 @@ func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name sif attached {var existing int64- if err := tx.Model(&models.ProjectTag{}).+ if err := tx.Model(&ProjectTag{}).Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).Count(&existing).Error; err != nil {return errors.WrapIf(err, "check UI tag source")@@ -81,7 +86,7 @@ func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name sreturn nil}var count int64- if err := tx.Model(&models.ProjectTag{}).+ if err := tx.Model(&ProjectTag{}).Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceUI).Count(&count).Error; err != nil {return errors.WrapIf(err, "count UI project tags")@@ -93,19 +98,19 @@ func (s *ProjectService) UpdateProjectTag(ctx context.Context, projectID, name sif err != nil {return err}- row := models.ProjectTag{ProjectID: projectID, Name: normalized, Source: string(projecttypes.TagSourceUI), Color: string(resolvedColor)}+ row := ProjectTag{ProjectID: projectID, Name: normalized, Source: string(projecttypes.TagSourceUI), Color: string(resolvedColor)}return errors.WrapIf(tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&row).Error, "attach UI project tag")}return errors.WrapIf(tx.Where("project_id = ? AND name = ? AND source = ?", projectID, normalized, projecttypes.TagSourceUI).- Delete(&models.ProjectTag{}).Error, "detach UI project tag")+ Delete(&ProjectTag{}).Error, "detach UI project tag")})if err != nil {return nil, err}- metadata := models.JSON{"action": "update_tags", "projectID": projectID, "projectName": projectModel.Name, "tag": normalized, "attached": attached}- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, projectID, projectModel.Name, user, metadata, "could not log project tag update")+ metadata := database.JSON{"action": "update_tags", "projectID": projectID, "projectName": projectModel.Name, "tag": normalized, "attached": attached}+ s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, projectID, projectModel.Name, user, metadata, "could not log project tag update")return s.GetProjectTags(ctx, projectID)}@@ -115,19 +120,19 @@ func (s *ProjectService) reconcileComposeProjectTagsInternal(ctx context.Contextreturn err}return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var projectModel models.Project+ var projectModel Projectif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Select("id").First(&projectModel, "id = ?", projectID).Error; err != nil {return errors.WrapIf(err, "find project for Compose tag reconciliation")}- if err := tx.Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceCompose).Delete(&models.ProjectTag{}).Error; err != nil {+ if err := tx.Where("project_id = ? AND source = ?", projectID, projecttypes.TagSourceCompose).Delete(&ProjectTag{}).Error; err != nil {return errors.WrapIf(err, "clear Compose project tags")}if len(normalized) == 0 {return nil}- rows := make([]models.ProjectTag, 0, len(normalized))+ rows := make([]ProjectTag, 0, len(normalized))for _, tag := range normalized {- rows = append(rows, models.ProjectTag{ProjectID: projectID, Name: tag.Name, Source: string(projecttypes.TagSourceCompose), Color: string(tag.Color)})+ rows = append(rows, ProjectTag{ProjectID: projectID, Name: tag.Name, Source: string(projecttypes.TagSourceCompose), Color: string(tag.Color)})}return errors.WrapIf(tx.Create(&rows).Error, "replace Compose project tags")})@@ -164,19 +169,19 @@ func createUIProjectTagsInternal(tx *gorm.DB, projectID string, tags []string, cif len(tags) == 0 {return nil}- rows := make([]models.ProjectTag, 0, len(tags))+ rows := make([]ProjectTag, 0, len(tags))for _, tag := range tags {color, err := resolveProjectTagColorInternal(tx, tag, colors[tag])if err != nil {return err}- rows = append(rows, models.ProjectTag{ProjectID: projectID, Name: tag, Source: string(projecttypes.TagSourceUI), Color: string(color)})+ rows = append(rows, ProjectTag{ProjectID: projectID, Name: tag, Source: string(projecttypes.TagSourceUI), Color: string(color)})}return errors.WrapIf(tx.Create(&rows).Error, "attach initial project tags")}func resolveProjectTagColorInternal(tx *gorm.DB, name string, fallback projecttypes.TagColor) (projecttypes.TagColor, error) {- var row models.ProjectTag+ var row ProjectTagerr := tx.Where("name = ?", name).Order("source DESC, color").First(&row).Errorswitch {case err == nil:@@ -219,13 +224,13 @@ func excludeComposeOwnedUITagsInternal(uiTags []string, composeTags []projecttyp}func deleteProjectWithTagsInternal(tx *gorm.DB, projectID string) error {- if err := tx.Where("project_id = ?", projectID).Delete(&models.ProjectTag{}).Error; err != nil {+ if err := tx.Where("project_id = ?", projectID).Delete(&ProjectTag{}).Error; err != nil {return errors.WrapIf(err, "delete project tags")}- return errors.WrapIf(tx.Delete(&models.Project{}, "id = ?", projectID).Error, "delete project")+ return errors.WrapIf(tx.Delete(&Project{}, "id = ?", projectID).Error, "delete project")}-func (s *ProjectService) reconcileComposeTagsForProjectInternal(ctx context.Context, projectModel *models.Project) error {+func (s *ProjectService) reconcileComposeTagsForProjectInternal(ctx context.Context, projectModel *Project) error {if projectModel == nil {return nil}@@ -252,7 +257,7 @@ func (s *ProjectService) loadProjectTagsInternal(ctx context.Context, projectIDsif len(projectIDs) == 0 {return result, nil}- var rows []models.ProjectTag+ var rows []ProjectTagif err := s.db.WithContext(ctx).Where("project_id IN ?", projectIDs).Order("project_id, name, source, color").Find(&rows).Error; err != nil {return nil, errors.WrapIf(err, "load project tags")}diff --git a/backend/internal/project/project_tags_test.go b/backend/internal/project/project_tags_test.goindex 897bcb219..2140b7240 100644--- a/backend/internal/project/project_tags_test.go+++ b/backend/internal/project/project_tags_test.go@@ -1,10 +1,13 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"projecttypes "github.com/getarcaneapp/arcane/types/v2/project""github.com/stretchr/testify/require")@@ -13,17 +16,17 @@ func TestProjectTags_ReconcilePreservesUIAndComposeOwnershipIsReadOnly(t *testindb := setupProjectTestDB(t)service := &ProjectService{db: db}ctx := context.Background()- projectModel := models.Project{- BaseModel: models.BaseModel{ID: "project-tags"},+ projectModel := Project{+ BaseModel: database.BaseModel{ID: "project-tags"},Name: "tagged",Path: "/tmp/tagged",- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,IsArchived: true,GitOpsManagedBy: new("gitops-1"),}require.NoError(t, db.Create(&projectModel).Error)- tags, err := service.UpdateProjectTag(ctx, projectModel.ID, " Database ", projecttypes.TagColorPurple, true, models.User{})+ tags, err := service.UpdateProjectTag(ctx, projectModel.ID, " Database ", projecttypes.TagColorPurple, true, common.User{})require.NoError(t, err)require.Equal(t, []projecttypes.Tag{{Name: "database", Color: projecttypes.TagColorPurple, Sources: []projecttypes.TagSource{projecttypes.TagSourceUI}}}, tags)@@ -38,13 +41,13 @@ func TestProjectTags_ReconcilePreservesUIAndComposeOwnershipIsReadOnly(t *testin{Name: "maintenance-window", Color: projecttypes.TagColorOrange, Sources: []projecttypes.TagSource{projecttypes.TagSourceCompose}},}, tags)- _, err = service.UpdateProjectTag(ctx, projectModel.ID, "database", "", false, models.User{})+ _, err = service.UpdateProjectTag(ctx, projectModel.ID, "database", "", false, common.User{})require.ErrorIs(t, err, errComposeTagReadOnly)- _, err = service.UpdateProjectTag(ctx, projectModel.ID, "maintenance-window", projecttypes.TagColorBlue, true, models.User{})+ _, err = service.UpdateProjectTag(ctx, projectModel.ID, "maintenance-window", projecttypes.TagColorBlue, true, common.User{})require.ErrorIs(t, err, errComposeTagReadOnly)require.NoError(t, service.reconcileComposeProjectTagsInternal(ctx, projectModel.ID, nil))- tags, err = service.UpdateProjectTag(ctx, projectModel.ID, "database", "", false, models.User{})+ tags, err = service.UpdateProjectTag(ctx, projectModel.ID, "database", "", false, common.User{})require.NoError(t, err)require.Empty(t, tags)}@@ -52,27 +55,27 @@ func TestProjectTags_ReconcilePreservesUIAndComposeOwnershipIsReadOnly(t *testinfunc TestProjectTags_FilterUsesExactORNames(t *testing.T) {db := setupProjectTestDB(t)ctx := context.Background()- projects := []models.Project{- {BaseModel: models.BaseModel{ID: "one"}, Name: "one", Path: "/tmp/one", Status: models.ProjectStatusStopped},- {BaseModel: models.BaseModel{ID: "two"}, Name: "two", Path: "/tmp/two", Status: models.ProjectStatusStopped},- {BaseModel: models.BaseModel{ID: "three"}, Name: "three", Path: "/tmp/three", Status: models.ProjectStatusStopped},+ projects := []Project{+ {BaseModel: database.BaseModel{ID: "one"}, Name: "one", Path: "/tmp/one", Status: ProjectStatusStopped},+ {BaseModel: database.BaseModel{ID: "two"}, Name: "two", Path: "/tmp/two", Status: ProjectStatusStopped},+ {BaseModel: database.BaseModel{ID: "three"}, Name: "three", Path: "/tmp/three", Status: ProjectStatusStopped},}require.NoError(t, db.Create(&projects).Error)- require.NoError(t, db.Create(&[]models.ProjectTag{+ require.NoError(t, db.Create(&[]ProjectTag{{ProjectID: "one", Name: "database", Source: string(projecttypes.TagSourceUI)},{ProjectID: "two", Name: "maintenance", Source: string(projecttypes.TagSourceCompose)},{ProjectID: "three", Name: "database-prod", Source: string(projecttypes.TagSourceUI)},}).Error)- var result []models.Project- err := applyProjectTagsDBFilterInternal(db.WithContext(ctx).Model(&models.Project{}), " DATABASE,maintenance ").Order("id").Find(&result).Error+ var result []Project+ err := applyProjectTagsDBFilterInternal(db.WithContext(ctx).Model(&Project{}), " DATABASE,maintenance ").Order("id").Find(&result).Errorrequire.NoError(t, err)require.Len(t, result, 2)require.ElementsMatch(t, []string{"one", "two"}, []string{result[0].ID, result[1].ID})require.NotContains(t, []string{result[0].ID, result[1].ID}, "three")result = nil- err = applyProjectSearchDBFilterInternal(db.WithContext(ctx).Model(&models.Project{}), "MAINT").Find(&result).Error+ err = applyProjectSearchDBFilterInternal(db.WithContext(ctx).Model(&Project{}), "MAINT").Find(&result).Errorrequire.NoError(t, err)require.Len(t, result, 1)require.Equal(t, "two", result[0].ID)diff --git a/backend/internal/project/project_update.go b/backend/internal/project/project_update.goindex c0d2967be..1cab8f547 100644--- a/backend/internal/project/project_update.go+++ b/backend/internal/project/project_update.go@@ -1,6 +1,10 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context"stderrors "errors""log/slog"@@ -15,7 +19,6 @@ import (composetypes "github.com/compose-spec/compose-go/v2/types""github.com/docker/compose/v5/pkg/api""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumes""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -24,7 +27,7 @@ import ("gorm.io/gorm")-func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent, overrideContent *string, user models.User) (*models.Project, error) {+func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, name *string, composeContent, envContent, overrideContent *string, user common.User) (*Project, error) {proj, projectsDirectory, err := s.getProjectForUpdate(ctx, projectID)if err != nil {return nil, err@@ -89,7 +92,7 @@ func (s *ProjectService) UpdateProject(ctx context.Context, projectID string, na// the compose file is authoritative over the submitted project name. For// name-only renames, it checks the compose file on disk so the lock can't be// bypassed via the API.-func resolveAuthoritativeProjectNameInternal(proj *models.Project, name *string, composeContent *string) *string {+func resolveAuthoritativeProjectNameInternal(proj *Project, name *string, composeContent *string) *string {if composeContent != nil {if yamlName := projects.ComposeContentProjectName(*composeContent); yamlName != "" {return &yamlName@@ -131,7 +134,7 @@ func (s *ProjectService) prepareProjectUpdateBackupInternal(ctx context.Context,return backup, func() { _ = acfs.RemoveAll(cleanupCtx, projectsDirectory, backupLogical) }, nil}-func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context.Context, proj *models.Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, volumeMigration volumes.Migration, renameJournal *projectRenameJournalInternal, journalActive *bool, projectStateCommitted *bool) (err error) {+func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx context.Context, proj *Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string, volumeMigration volumes.Migration, renameJournal *projectRenameJournalInternal, journalActive *bool, projectStateCommitted *bool) (err error) {volumeMigrationApplied := falsedefer func() {stateCommitted := projectStateCommitted != nil && *projectStateCommitted@@ -161,7 +164,7 @@ func (s *ProjectService) applyProjectUpdateWithRenameJournalInternal(ctx contextreturn nil}-func (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *models.Project) error {+func (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *Project) error {tx := s.db.WithContext(ctx).Begin()if tx.Error != nil {return errors.WrapIf(tx.Error, "failed to start project update transaction")@@ -184,7 +187,7 @@ func (s *ProjectService) saveProjectUpdateInternal(ctx context.Context, proj *moreturn nil}-func (s *ProjectService) handleProjectUpdateFailureInternal(ctx context.Context, projectID, projectsDirectory string, proj *models.Project, backup *projects.ProjectUpdateBackup, journalActive *bool, projectStateCommitted bool, err error) error {+func (s *ProjectService) handleProjectUpdateFailureInternal(ctx context.Context, projectID, projectsDirectory string, proj *Project, backup *projects.ProjectUpdateBackup, journalActive *bool, projectStateCommitted bool, err error) error {if projectStateCommitted {return err}@@ -204,8 +207,8 @@ func (s *ProjectService) handleProjectUpdateFailureInternal(ctx context.Context,return err}-func (s *ProjectService) logProjectUpdateEventInternal(ctx context.Context, proj *models.Project, composeContent, envContent, overrideContent *string, user models.User) {- metadata := models.JSON{+func (s *ProjectService) logProjectUpdateEventInternal(ctx context.Context, proj *Project, composeContent, envContent, overrideContent *string, user common.User) {+ metadata := database.JSON{"action": "update","projectID": proj.ID,"projectName": proj.Name,@@ -219,10 +222,10 @@ func (s *ProjectService) logProjectUpdateEventInternal(ctx context.Context, projif overrideContent != nil {metadata["overrideUpdated"] = true}- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, proj.ID, proj.Name, user, metadata, "could not log project update action")+ s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, proj.ID, proj.Name, user, metadata, "could not log project update action")}-func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Context, proj *models.Project, composeContent, overrideContent *string) {+func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Context, proj *Project, composeContent, overrideContent *string) {if composeContent == nil && overrideContent == nil {return}@@ -237,7 +240,7 @@ func (s *ProjectService) refreshProjectAfterContentUpdateInternal(ctx context.Co}}-func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID string, composeContent string, gitEnvContent *string, gitOverrideContent *string, gitOverrideFileName string, user models.User) (*models.Project, error) {+func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectID string, composeContent string, gitEnvContent *string, gitOverrideContent *string, gitOverrideFileName string, user common.User) (*Project, error) {proj, projectsDirectory, err := s.getProjectForUpdate(ctx, projectID)if err != nil {return nil, err@@ -278,7 +281,7 @@ func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectIDslog.WarnContext(ctx, "failed to update service counts after git sync", "projectID", proj.ID, "error", err)}- metadata := models.JSON{+ metadata := database.JSON{"action": "git_sync_update","projectID": proj.ID,"projectName": proj.Name,@@ -289,33 +292,33 @@ func (s *ProjectService) ApplyGitSyncProjectFiles(ctx context.Context, projectIDif gitEnvContent == nil {metadata["envSourceRemoved"] = true}- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, proj.ID, proj.Name, user, metadata, "could not log git sync project update action")+ s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, proj.ID, proj.Name, user, metadata, "could not log git sync project update action")return &proj, nil}-func (s *ProjectService) getProjectForUpdate(ctx context.Context, projectID string) (models.Project, string, error) {- var proj models.Project+func (s *ProjectService) getProjectForUpdate(ctx context.Context, projectID string) (Project, string, error) {+ var proj Projectif err := s.db.WithContext(ctx).First(&proj, "id = ?", projectID).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {- return models.Project{}, "", errors.New("project not found")+ return Project{}, "", errors.New("project not found")}- return models.Project{}, "", errors.WrapIf(err, "failed to get project")+ return Project{}, "", errors.WrapIf(err, "failed to get project")}projectsDirectory, err := projects.GetProjectsDirectory(ctx, s.settingsService.GetStringSetting(ctx, "projectsDirectory", "/app/data/projects"))if err != nil {- return models.Project{}, "", errors.WrapIf(err, "failed to get projects directory")+ return Project{}, "", errors.WrapIf(err, "failed to get projects directory")}if err := s.EnsureProjectPathUnderRoot(ctx, &proj, false); err != nil {- return models.Project{}, "", err+ return Project{}, "", err}return proj, projectsDirectory, nil}-func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctx context.Context, proj *models.Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string) (volumes.Migration, error) {+func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctx context.Context, proj *Project, name *string, projectsDirectory string, composeContent, envContent, overrideContent *string) (volumes.Migration, error) {if !isProjectRenameRequestedInternal(proj, name) {return nil, nil}@@ -352,7 +355,7 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationForUpdateInternal(ctreturn s.prepareProjectRenameVolumeMigrationInternal(ctx, &previewProject, name)}-func (s *ProjectService) prepareProjectRenameVolumeMigrationInternal(ctx context.Context, proj *models.Project, name *string) (volumes.Migration, error) {+func (s *ProjectService) prepareProjectRenameVolumeMigrationInternal(ctx context.Context, proj *Project, name *string) (volumes.Migration, error) {oldComposeName, newComposeName, ok := projectRenameVolumeMigrationComposeNamesInternal(s, proj, name)if !ok {return nil, nil@@ -374,13 +377,13 @@ func (s *ProjectService) prepareProjectRenameVolumeMigrationInternal(ctx contextreturn volumes.PlanMigration(ctx, dockerClient, composeProject, oldComposeName, newComposeName)}-func projectRenameVolumeMigrationComposeNamesInternal(s *ProjectService, proj *models.Project, name *string) (string, string, bool) {+func projectRenameVolumeMigrationComposeNamesInternal(s *ProjectService, proj *Project, name *string) (string, string, bool) {if s == nil || s.dockerService == nil || proj == nil || name == nil {return "", "", false}newProjectName := strings.TrimSpace(*name)- if newProjectName == "" || proj.Name == newProjectName || proj.Status != models.ProjectStatusStopped {+ if newProjectName == "" || proj.Name == newProjectName || proj.Status != ProjectStatusStopped {return "", "", false}@@ -393,7 +396,7 @@ func projectRenameVolumeMigrationComposeNamesInternal(s *ProjectService, proj *mreturn oldComposeName, newComposeName, true}-func isProjectRenameRequestedInternal(proj *models.Project, name *string) bool {+func isProjectRenameRequestedInternal(proj *Project, name *string) bool {if proj == nil || name == nil {return false}@@ -472,7 +475,7 @@ func restoreProjectDirectoryBackupInternal(ctx context.Context, projectsDirectorreturn nil}-func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *models.Project, projectsDirectory string, composeContent, envContent, overrideContent *string) error {+func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *Project, projectsDirectory string, composeContent, envContent, overrideContent *string) error {switch {case composeContent != nil:effectiveEnvContent, err := s.resolveEffectiveEnvContentForUpdateInternal(proj.Path, envContent)@@ -514,7 +517,7 @@ func (s *ProjectService) persistUpdatedProjectFiles(ctx context.Context, proj *m// on-disk base merged with the requested override so a base that is only valid// *with* its override still validates, and a delete that would break the base// fails before touching disk.-func (s *ProjectService) persistOverrideOnlyUpdateInternal(ctx context.Context, proj *models.Project, projectsDirectory string, envContent, overrideContent *string) error {+func (s *ProjectService) persistOverrideOnlyUpdateInternal(ctx context.Context, proj *Project, projectsDirectory string, envContent, overrideContent *string) error {baseContent, _, err := projects.ReadProjectFiles(proj.Path, "")if err != nil {return errors.WrapIf(err, "failed to read project files")@@ -594,11 +597,11 @@ func validateComposeContentForUpdate(ctx context.Context, projectsDirectory, proreturn err}-func (s *ProjectService) ensureProjectStoppedForRenameInternal(ctx context.Context, proj *models.Project, name *string) error {+func (s *ProjectService) ensureProjectStoppedForRenameInternal(ctx context.Context, proj *Project, name *string) error {if !isProjectRenameRequestedInternal(proj, name) {return nil}- if proj.Status != models.ProjectStatusStopped && proj.Status != models.ProjectStatusUnknown {+ if proj.Status != ProjectStatusStopped && proj.Status != ProjectStatusUnknown {return errors.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)}@@ -609,19 +612,19 @@ func (s *ProjectService) ensureProjectStoppedForRenameInternal(ctx context.Conte}status := calculateProjectStatus(services)- if status != models.ProjectStatusStopped {+ if status != ProjectStatusStopped {return errors.Errorf("project must be stopped before renaming (current status: %s)", status)}serviceCount, runningCount := getServiceCounts(services)- proj.Status = models.ProjectStatusStopped+ proj.Status = ProjectStatusStoppedproj.StatusReason = nilproj.ServiceCount = serviceCountproj.RunningCount = runningCountreturn nil}-func (s *ProjectService) applyProjectRenameIfNeeded(ctx context.Context, proj *models.Project, name *string, projectsDirectory string) error {+func (s *ProjectService) applyProjectRenameIfNeeded(ctx context.Context, proj *Project, name *string, projectsDirectory string) error {if name == nil {return nil}@@ -631,7 +634,7 @@ func (s *ProjectService) applyProjectRenameIfNeeded(ctx context.Context, proj *mreturn nil}- if proj.Status != models.ProjectStatusStopped {+ if proj.Status != ProjectStatusStopped {return errors.Errorf("project must be stopped before renaming (current status: %s)", proj.Status)}diff --git a/backend/internal/project/service_test.go b/backend/internal/project/service_test.goindex 9440704b7..04bc80d57 100644--- a/backend/internal/project/service_test.go+++ b/backend/internal/project/service_test.go@@ -53,14 +53,13 @@ import ("gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models")type testBuildBuilder struct {err error}-func (b testBuildBuilder) BuildImage(_ context.Context, _ string, _ buildtypes.BuildRequest, _ io.Writer, _ string, _ *models.User) (*buildtypes.BuildResult, error) {+func (b testBuildBuilder) BuildImage(_ context.Context, _ string, _ buildtypes.BuildRequest, _ io.Writer, _ string, _ *common.User) (*buildtypes.BuildResult, error) {if b.err != nil {return nil, b.err}@@ -77,14 +76,14 @@ func setupProjectTestDB(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Project{}, &models.ProjectTag{}, &models.SettingVariable{}, &models.ImageUpdateRecord{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&Project{}, &ProjectTag{}, &settings.SettingVariable{}, &imageupdate.ImageUpdateRecord{}, &event.Event{}))return &database.DB{DB: db}}func TestUpdateProjectWorkspaceRejectsInvalidManifestBeforeProjectLookup(t *testing.T) {service := &ProjectService{}- _, err := service.UpdateProjectWorkspace(context.Background(), "missing", projecttypes.WorkspaceUpdateManifest{}, nil, models.User{})+ _, err := service.UpdateProjectWorkspace(context.Background(), "missing", projecttypes.WorkspaceUpdateManifest{}, nil, common.User{})require.ErrorIs(t, err, common.ErrProjectWorkspaceBadRequest)require.ErrorContains(t, err, "revision")}@@ -193,8 +192,8 @@ func TestProjectService_RefreshProjectImageRefs_PersistsBuildMetadata(t *testingimage: postgres:17`), 0o644))- proj := &models.Project{- BaseModel: models.BaseModel{ID: "project-build-image-refs"},+ proj := &Project{+ BaseModel: database.BaseModel{ID: "project-build-image-refs"},Name: "demo",Path: projectPath,}@@ -203,7 +202,7 @@ func TestProjectService_RefreshProjectImageRefs_PersistsBuildMetadata(t *testingsvc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())svc.refreshProjectImageRefsInternal(ctx, proj)- var saved models.Project+ var saved Projectrequire.NoError(t, db.First(&saved, "id = ?", proj.ID).Error)assert.ElementsMatch(t, []string{"test2:latest", "postgres:17"}, projects.ParseImageRefsJSON(saved.ImageRefsJSON))require.NotNil(t, saved.BuildImageRefsJSON)@@ -230,9 +229,9 @@ func TestProjectService_BackfillProjectImageRefs_RetriesOnlyMissingMetadata(t *timage: nginx:latest`), 0o644))- valid := &models.Project{BaseModel: models.BaseModel{ID: "backfill-valid"}, Name: "valid", Path: validPath}- invalid := &models.Project{BaseModel: models.BaseModel{ID: "backfill-invalid"}, Name: "invalid", Path: invalidPath}- regular := &models.Project{BaseModel: models.BaseModel{ID: "backfill-regular"}, Name: "regular", Path: regularPath}+ valid := &Project{BaseModel: database.BaseModel{ID: "backfill-valid"}, Name: "valid", Path: validPath}+ invalid := &Project{BaseModel: database.BaseModel{ID: "backfill-invalid"}, Name: "invalid", Path: invalidPath}+ regular := &Project{BaseModel: database.BaseModel{ID: "backfill-regular"}, Name: "regular", Path: regularPath}require.NoError(t, db.Create(valid).Error)require.NoError(t, db.Create(invalid).Error)require.NoError(t, db.Create(regular).Error)@@ -242,16 +241,16 @@ func TestProjectService_BackfillProjectImageRefs_RetriesOnlyMissingMetadata(t *trequire.NoError(t, err)require.Equal(t, 3, count)- var savedValid models.Project+ var savedValid Projectrequire.NoError(t, db.First(&savedValid, "id = ?", valid.ID).Error)require.NotNil(t, savedValid.BuildImageRefsJSON)assert.Equal(t, []string{"local-app:latest"}, projects.ParseImageRefsJSON(*savedValid.BuildImageRefsJSON))- var savedInvalid models.Project+ var savedInvalid Projectrequire.NoError(t, db.First(&savedInvalid, "id = ?", invalid.ID).Error)assert.Nil(t, savedInvalid.BuildImageRefsJSON)- var savedRegular models.Project+ var savedRegular Projectrequire.NoError(t, db.First(&savedRegular, "id = ?", regular.ID).Error)require.NotNil(t, savedRegular.BuildImageRefsJSON)assert.Equal(t, "[]", *savedRegular.BuildImageRefsJSON)@@ -293,16 +292,16 @@ func TestProjectService_DestroyProject_RemovesFilesWhenRequested(t *testing.T) {require.NoError(t, os.WriteFile(filepath.Join(projectPath, "project-data.txt"), []byte("keep until destroy\n"), 0o644))dirName := "demo-remove"- project := &models.Project{- BaseModel: models.BaseModel{ID: "project-destroy-remove-files"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "project-destroy-remove-files"},Name: "demo-remove",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- require.NoError(t, svc.DestroyProject(ctx, project.ID, true, false, models.User{}))+ require.NoError(t, svc.DestroyProject(ctx, project.ID, true, false, common.User{}))_, statErr := os.Stat(projectPath)assert.ErrorIs(t, statErr, os.ErrNotExist)@@ -318,16 +317,16 @@ func TestProjectService_DestroyProject_PreservesFilesWhenRequested(t *testing.T)require.NoError(t, os.WriteFile(projectDataPath, []byte("preserve on destroy\n"), 0o644))dirName := "demo-preserve"- project := &models.Project{- BaseModel: models.BaseModel{ID: "project-destroy-preserve-files"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "project-destroy-preserve-files"},Name: "demo-preserve",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- require.NoError(t, svc.DestroyProject(ctx, project.ID, false, false, models.User{}))+ require.NoError(t, svc.DestroyProject(ctx, project.ID, false, false, common.User{}))assert.NoDirExists(t, projectPath)assert.NoFileExists(t, projectDataPath)@@ -349,8 +348,8 @@ func TestProjectService_GetProjectFromDatabaseByID(t *testing.T) {svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())// Create test project- proj := &models.Project{- BaseModel: models.BaseModel{+ proj := &Project{+ BaseModel: database.BaseModel{ID: "p1",},Name: "test-project",@@ -415,12 +414,12 @@ func TestProjectService_CalculateProjectStatus(t *testing.T) {tests := []struct {name stringservices []ProjectServiceInfo- want models.ProjectStatus+ want ProjectStatus}{{name: "empty",services: []ProjectServiceInfo{},- want: models.ProjectStatusUnknown,+ want: ProjectStatusUnknown,},{name: "all running",@@ -428,7 +427,7 @@ func TestProjectService_CalculateProjectStatus(t *testing.T) {{Status: "running"},{Status: "up"},},- want: models.ProjectStatusRunning,+ want: ProjectStatusRunning,},{name: "all stopped",@@ -436,7 +435,7 @@ func TestProjectService_CalculateProjectStatus(t *testing.T) {{Status: "exited"},{Status: "stopped"},},- want: models.ProjectStatusStopped,+ want: ProjectStatusStopped,},{name: "partial",@@ -444,7 +443,7 @@ func TestProjectService_CalculateProjectStatus(t *testing.T) {{Status: "running"},{Status: "exited"},},- want: models.ProjectStatusPartiallyRunning,+ want: ProjectStatusPartiallyRunning,},}@@ -461,20 +460,20 @@ func TestProjectService_UpdateProjectStatusInternal(t *testing.T) {ctx := context.Background()svc := NewProjectService(db, nil, nil, nil, nil, nil, nil, nil, config.Load())- proj := &models.Project{- BaseModel: models.BaseModel{+ proj := &Project{+ BaseModel: database.BaseModel{ID: "p1",},- Status: models.ProjectStatusUnknown,+ Status: ProjectStatusUnknown,}require.NoError(t, db.Create(proj).Error)- err := svc.updateProjectStatusInternal(ctx, "p1", models.ProjectStatusRunning)+ err := svc.updateProjectStatusInternal(ctx, "p1", ProjectStatusRunning)require.NoError(t, err)- var updated models.Project+ var updated Projectrequire.NoError(t, db.First(&updated, "id = ?", "p1").Error)- assert.Equal(t, models.ProjectStatusRunning, updated.Status)+ assert.Equal(t, ProjectStatusRunning, updated.Status)if updated.UpdatedAt != nil {assert.WithinDuration(t, time.Now(), *updated.UpdatedAt, time.Second)} else {@@ -486,15 +485,15 @@ func TestProjectService_IncrementStatusCounts(t *testing.T) {running := 0stopped := 0- incrementStatusCounts(models.ProjectStatusRunning, &running, &stopped)+ incrementStatusCounts(ProjectStatusRunning, &running, &stopped)assert.Equal(t, 1, running)assert.Equal(t, 0, stopped)- incrementStatusCounts(models.ProjectStatusStopped, &running, &stopped)+ incrementStatusCounts(ProjectStatusStopped, &running, &stopped)assert.Equal(t, 1, running)assert.Equal(t, 1, stopped)- incrementStatusCounts(models.ProjectStatusUnknown, &running, &stopped)+ incrementStatusCounts(ProjectStatusUnknown, &running, &stopped)assert.Equal(t, 1, running)assert.Equal(t, 1, stopped)}@@ -506,8 +505,8 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {db := setupProjectTestDB(t)svc := NewProjectService(db, nil, nil, nil, nil, nil, nil, nil, config.Load())- proj := &models.Project{- BaseModel: models.BaseModel{ID: "p1"},+ proj := &Project{+ BaseModel: database.BaseModel{ID: "p1"},Name: "myproject",Path: "/tmp/myproject",}@@ -522,8 +521,8 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {db := setupProjectTestDB(t)svc := NewProjectService(db, nil, nil, nil, nil, nil, nil, nil, config.Load())- proj := &models.Project{- BaseModel: models.BaseModel{ID: "p1"},+ proj := &Project{+ BaseModel: database.BaseModel{ID: "p1"},Name: "myproject",Path: "/tmp/myproject",}@@ -538,8 +537,8 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {db := setupProjectTestDB(t)svc := NewProjectService(db, nil, nil, nil, nil, nil, nil, nil, config.Load())- display := &models.Project{- BaseModel: models.BaseModel{ID: "p2"},+ display := &Project{+ BaseModel: database.BaseModel{ID: "p2"},Name: "My Project!",Path: "/tmp/my-project",}@@ -554,8 +553,8 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {db := setupProjectTestDB(t)svc := NewProjectService(db, nil, nil, nil, nil, nil, nil, nil, config.Load())- original := &models.Project{- BaseModel: models.BaseModel{ID: "p3"},+ original := &Project{+ BaseModel: database.BaseModel{ID: "p3"},Name: "My Project!",Path: "/tmp/my-project",}@@ -569,10 +568,10 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {require.True(t, cached)assert.Equal(t, original.ID, cachedProjectID)- require.NoError(t, db.Delete(&models.Project{}, "id = ?", original.ID).Error)+ require.NoError(t, db.Delete(&Project{}, "id = ?", original.ID).Error)- replacement := &models.Project{- BaseModel: models.BaseModel{ID: "p4"},+ replacement := &Project{+ BaseModel: database.BaseModel{ID: "p4"},Name: "My Project!",Path: "/tmp/my-project-recreated",}@@ -591,8 +590,8 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {db := setupProjectTestDB(t)svc := NewProjectService(db, nil, nil, nil, nil, nil, nil, nil, config.Load())- original := &models.Project{- BaseModel: models.BaseModel{ID: "p5"},+ original := &Project{+ BaseModel: database.BaseModel{ID: "p5"},Name: "My App!",Path: "/tmp/my-app",}@@ -606,7 +605,7 @@ func TestProjectService_GetProjectByComposeName(t *testing.T) {require.True(t, cached)assert.Equal(t, original.ID, cachedProjectID)- require.NoError(t, db.Model(&models.Project{}).Where("id = ?", original.ID).Updates(map[string]any{+ require.NoError(t, db.Model(&Project{}).Where("id = ?", original.ID).Updates(map[string]any{"name": "New Service","path": "/tmp/new-service",}).Error)@@ -656,63 +655,63 @@ func TestProjectService_PullProjectImages_UpdatesCurrentImageRecordAfterPull(t *require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(composeContent), 0o644))dirName := "compose-pull"- projectRecord := &models.Project{- BaseModel: models.BaseModel{ID: "project-pull"},+ projectRecord := &Project{+ BaseModel: database.BaseModel{ID: "project-pull"},Name: "compose-pull",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(projectRecord).Error)now := time.Now().UTC().Add(-time.Hour)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:old-full",Repository: repository,Tag: "1.2.3",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "1.2.3",CheckTime: now,}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:old-short",Repository: "team/app",Tag: "1.2.3",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "1.2.3",CheckTime: now.Add(time.Minute),}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:build-only",Repository: buildRepository,Tag: "latest",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "latest",CheckTime: now.Add(2 * time.Minute),}).Error)- require.NoError(t, svc.PullProjectImages(ctx, projectRecord.ID, io.Discard, models.SystemUser, nil))+ require.NoError(t, svc.PullProjectImages(ctx, projectRecord.ID, io.Discard, common.SystemUser, nil))// sha256:old-* records represent update records for OTHER containers still running// the old image. Pulling the image for one container must not mark them as up-to-date// (#2453: updating one container was incorrectly removing others from the update list).- var fullRecord models.ImageUpdateRecord+ var fullRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:old-full").First(&fullRecord).Error)assert.True(t, fullRecord.HasUpdate)- var shortRecord models.ImageUpdateRecord+ var shortRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:old-short").First(&shortRecord).Error)assert.True(t, shortRecord.HasUpdate)- var buildRecord models.ImageUpdateRecord+ var buildRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:build-only").First(&buildRecord).Error)assert.True(t, buildRecord.HasUpdate)// The newly pulled image itself is correctly marked as up-to-date.- var currentRecord models.ImageUpdateRecord+ var currentRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", imageID).First(¤tRecord).Error)assert.False(t, currentRecord.HasUpdate)assert.Equal(t, repository, currentRecord.Repository)@@ -747,27 +746,27 @@ func TestProjectService_EnsureImagesPresent_UpdatesCurrentImageRecordAfterPull(timageService := image.NewImageService(db, dockerService, nil, imageUpdateService, nil, eventService)svc := NewProjectService(db, settingsService, nil, imageService, dockerService, nil, nil, nil, config.Load())- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:old-api",Repository: repository,Tag: "2.0.0",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "2.0.0",CheckTime: time.Now().UTC().Add(-time.Hour),}).Error)require.NoError(t, svc.ensureImagesPresent(ctx, map[string]projects.ImagePullMode{imageRef: projects.ImagePullModeAlways,- }, io.Discard, nil, models.SystemUser))+ }, io.Discard, nil, common.SystemUser))// sha256:old-api may still be in use by another container — pulling for one container// must not clear it (fixes #2453).- var oldRecord models.ImageUpdateRecord+ var oldRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:old-api").First(&oldRecord).Error)assert.True(t, oldRecord.HasUpdate)- var currentRecord models.ImageUpdateRecord+ var currentRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", imageID).First(¤tRecord).Error)assert.False(t, currentRecord.HasUpdate)assert.Equal(t, imageDigest, mo.PointerToOption(currentRecord.LatestDigest).OrEmpty())@@ -799,24 +798,24 @@ func TestProjectService_PullImageForService_UpdatesCurrentImageRecordAfterPull(timageService := image.NewImageService(db, dockerService, nil, imageUpdateService, nil, eventService)svc := NewProjectService(db, settingsService, nil, imageService, dockerService, nil, nil, nil, config.Load())- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:old-worker",Repository: repository,Tag: "3.1.4",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "3.1.4",CheckTime: time.Now().UTC().Add(-time.Hour),}).Error)- require.NoError(t, svc.pullAndReconcileImageInternal(ctx, imageRef, io.Discard, models.SystemUser, nil))+ require.NoError(t, svc.pullAndReconcileImageInternal(ctx, imageRef, io.Discard, common.SystemUser, nil))// sha256:old-worker may still be in use by another container — must not be cleared (fixes #2453).- var oldRecord models.ImageUpdateRecord+ var oldRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:old-worker").First(&oldRecord).Error)assert.True(t, oldRecord.HasUpdate)- var currentRecord models.ImageUpdateRecord+ var currentRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", imageID).First(¤tRecord).Error)assert.False(t, currentRecord.HasUpdate)assert.Equal(t, imageDigest, mo.PointerToOption(currentRecord.LatestDigest).OrEmpty())@@ -885,21 +884,21 @@ func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSucc}now := time.Now().UTC().Add(-time.Hour)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:selected-old",Repository: privateRepository,Tag: "9.9.9",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "9.9.9",CheckTime: now,}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:sidecar-old",Repository: publicRepository,Tag: "1.27",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "1.27",CheckTime: now,}).Error)@@ -911,7 +910,7 @@ func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSuccEnabled: true,}}- require.NoError(t, svc.composePullSelectedServicesInternal(ctx, projectDef, []string{"app", "app-copy", "sidecar", "builder"}, models.SystemUser, credentials))+ require.NoError(t, svc.composePullSelectedServicesInternal(ctx, projectDef, []string{"app", "app-copy", "sidecar", "builder"}, common.SystemUser, credentials))assert.Equal(t, 1, pullsByRef[privateImageRef], "duplicate service refs should only be pulled once")assert.Equal(t, 1, pullsByRef[publicImageRef], "selected public image should still be pulled")assert.Len(t, pullsByRef, 2, "build-backed services should not trigger image pulls")@@ -923,20 +922,20 @@ func TestProjectService_ComposePullSelectedServicesInternal_ReconcilesOnlyOnSuccassert.Empty(t, authHeadersByRef[publicImageRef], "public image pull should not receive unrelated registry auth")// sha256:selected-old may still be used by another container — must not be cleared (fixes #2453).- var selectedRecord models.ImageUpdateRecord+ var selectedRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:selected-old").First(&selectedRecord).Error)assert.True(t, selectedRecord.HasUpdate)- var sidecarRecord models.ImageUpdateRecord+ var sidecarRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:sidecar-old").First(&sidecarRecord).Error)assert.True(t, sidecarRecord.HasUpdate)- var privateCurrentRecord models.ImageUpdateRecord+ var privateCurrentRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", privateImageID).First(&privateCurrentRecord).Error)assert.False(t, privateCurrentRecord.HasUpdate)assert.Equal(t, privateImageDigest, mo.PointerToOption(privateCurrentRecord.LatestDigest).OrEmpty())- var publicCurrentRecord models.ImageUpdateRecord+ var publicCurrentRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", publicImageID).First(&publicCurrentRecord).Error)assert.False(t, publicCurrentRecord.HasUpdate)assert.Equal(t, publicImageDigest, mo.PointerToOption(publicCurrentRecord.LatestDigest).OrEmpty())@@ -976,26 +975,26 @@ func TestProjectService_ComposePullSelectedServicesInternal_LeavesRecordsWhenPul},}- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:selected-old",Repository: repository,Tag: "9.9.9",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "9.9.9",CheckTime: time.Now().UTC().Add(-time.Hour),}).Error)- err = svc.composePullSelectedServicesInternal(ctx, projectDef, []string{"app"}, models.SystemUser, nil)+ err = svc.composePullSelectedServicesInternal(ctx, projectDef, []string{"app"}, common.SystemUser, nil)require.Error(t, err)require.ErrorContains(t, err, "failed to pull image")- var selectedRecord models.ImageUpdateRecord+ var selectedRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:selected-old").First(&selectedRecord).Error)assert.True(t, selectedRecord.HasUpdate)var count int64- require.NoError(t, db.WithContext(ctx).Model(&models.ImageUpdateRecord{}).Where("id = ?", "sha256:team-app-compose").Count(&count).Error)+ require.NoError(t, db.WithContext(ctx).Model(&imageupdate.ImageUpdateRecord{}).Where("id = ?", "sha256:team-app-compose").Count(&count).Error)assert.Zero(t, count)}@@ -1026,20 +1025,20 @@ func TestProjectService_UpdateProjectServicesHardFailsWhenPullFailsInternal(t *tprojectPath := createComposeProjectDir(t, projectsDir, "compose-update-pull-fail")require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: "+imageRef+"\n"), 0o644))- projectRecord := &models.Project{- BaseModel: models.BaseModel{ID: "project-update-pull-fail"},+ projectRecord := &Project{+ BaseModel: database.BaseModel{ID: "project-update-pull-fail"},Name: "compose-update-pull-fail",DirName: ptr("compose-update-pull-fail"),Path: projectPath,- Status: models.ProjectStatusRunning,+ Status: ProjectStatusRunning,}require.NoError(t, db.Create(projectRecord).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:selected-old",Repository: "registry.example.com/team/app",Tag: "9.9.9",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "9.9.9",CheckTime: time.Now().UTC().Add(-time.Hour),}).Error)@@ -1055,16 +1054,16 @@ func TestProjectService_UpdateProjectServicesHardFailsWhenPullFailsInternal(t *t}svc := NewProjectService(db, settingsService, nil, imageService, dockerService, nil, nil, nil, config.Load())- err = svc.UpdateProjectServices(ctx, projectRecord.ID, []string{"app"}, models.SystemUser)+ err = svc.UpdateProjectServices(ctx, projectRecord.ID, []string{"app"}, common.SystemUser)require.Error(t, err)require.ErrorContains(t, err, "pull updated service images")assert.False(t, upCalled, "compose up must not run after a pull failure")- var persistedProject models.Project+ var persistedProject Projectrequire.NoError(t, db.WithContext(ctx).Where("id = ?", projectRecord.ID).First(&persistedProject).Error)- assert.Equal(t, models.ProjectStatusRunning, persistedProject.Status)+ assert.Equal(t, ProjectStatusRunning, persistedProject.Status)- var persistedRecord models.ImageUpdateRecord+ var persistedRecord imageupdate.ImageUpdateRecordrequire.NoError(t, db.WithContext(ctx).Where("id = ?", "sha256:selected-old").First(&persistedRecord).Error)assert.True(t, persistedRecord.HasUpdate)}@@ -1099,12 +1098,12 @@ func TestProjectService_UpdateProjectServicesForcesRecreateInternal(t *testing.TprojectPath := createComposeProjectDir(t, projectsDir, "compose-update-force")require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: "+imageRef+"\n"), 0o644))- projectRecord := &models.Project{- BaseModel: models.BaseModel{ID: "project-update-force"},+ projectRecord := &Project{+ BaseModel: database.BaseModel{ID: "project-update-force"},Name: "compose-update-force",DirName: ptr("compose-update-force"),Path: projectPath,- Status: models.ProjectStatusRunning,+ Status: ProjectStatusRunning,}require.NoError(t, db.Create(projectRecord).Error)@@ -1128,7 +1127,7 @@ func TestProjectService_UpdateProjectServicesForcesRecreateInternal(t *testing.T}svc := NewProjectService(db, settingsService, nil, imageService, dockerService, nil, nil, nil, config.Load())- err = svc.UpdateProjectServices(ctx, projectRecord.ID, []string{"app"}, models.SystemUser)+ err = svc.UpdateProjectServices(ctx, projectRecord.ID, []string{"app"}, common.SystemUser)require.Error(t, err)assert.True(t, upCalled)assert.True(t, forceRecreate, "service updates must force recreate after pulling the updated image")@@ -1209,17 +1208,17 @@ func TestProjectService_UpdateProject_RenameFailsWhenVolumeMigrationPreparationForiginalPath := createComposeProjectDir(t, projectsDir, originalDirName)require.NoError(t, os.WriteFile(filepath.Join(originalPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n"), 0o644))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-volume-conflict"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-volume-conflict"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1228,7 +1227,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenVolumeMigrationPreparationFassert.DirExists(t, originalPath)assert.NoDirExists(t, filepath.Join(projectsDir, "bar"))- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "Foo", fromDB.Name)assert.Equal(t, originalPath, fromDB.Path)@@ -1252,12 +1251,12 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_AppliesVolumeMigratioriginalDirName := "Foo"originalPath := createComposeProjectDir(t, projectsDir, originalDirName)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-volume-success"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-volume-success"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -1275,7 +1274,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_AppliesVolumeMigratiassert.DirExists(t, filepath.Join(projectsDir, "bar"))assert.NoDirExists(t, originalPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "bar", fromDB.Name)assert.Equal(t, filepath.Join(projectsDir, "bar"), fromDB.Path)@@ -1327,12 +1326,12 @@ func TestProjectService_PrepareProjectRenameVolumeMigrationForUpdate_UsesComposeoldCompose := "services:\n app:\n image: nginx:alpine\n volumes:\n - data:/data\nvolumes:\n data:\n driver: local\n"require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(oldCompose), 0o644))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-preview-volume-rename"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-preview-volume-rename"},Name: "nginx",DirName: ptr("nginx"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}t.Run("skips volume made explicit in pending compose", func(t *testing.T) {@@ -1424,12 +1423,12 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_RollsBackVolumeMigraoriginalDirName := "Foo"originalPath := createComposeProjectDir(t, projectsDir, originalDirName)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-volume-save-fail"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-volume-save-fail"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -1469,12 +1468,12 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_SucceedsCommittedRenoriginalDirName := "Foo"originalPath := createComposeProjectDir(t, projectsDir, originalDirName)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-volume-cleanup-fail"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-volume-cleanup-fail"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -1492,7 +1491,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_SucceedsCommittedRenrequire.NoDirExists(t, originalPath)require.DirExists(t, filepath.Join(projectsDir, "bar"))- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "bar", fromDB.Name)require.Equal(t, filepath.Join(projectsDir, "bar"), fromDB.Path)@@ -1500,7 +1499,7 @@ func TestProjectService_ApplyProjectUpdateWithRenameJournal_SucceedsCommittedRenfunc TestProjectService_UpdateProject_ClearsJournalForNonRenameWhenRecoveryDockerUnavailable(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -1516,12 +1515,12 @@ func TestProjectService_UpdateProject_ClearsJournalForNonRenameWhenRecoveryDockeoldDir := "nginx"projectPath := createComposeProjectDir(t, projectsDir, oldDir)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-non-rename-recovery-docker-unavailable"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-non-rename-recovery-docker-unavailable"},Name: "nginx",DirName: &oldDir,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -1547,8 +1546,8 @@ func TestProjectService_UpdateProject_ClearsJournalForNonRenameWhenRecoveryDockerequire.NoError(t, kvService.Set(ctx, projectRenameJournalKeyPrefixInternal+project.ID, string(payload)))envContent := "FOO=bar\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &envContent, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &envContent, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1566,7 +1565,7 @@ func TestProjectService_UpdateProject_ClearsJournalForNonRenameWhenRecoveryDockefunc TestProjectService_UpdateProject_AllowsRenameAfterJournalRecoveryDockerUnavailable(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -1582,12 +1581,12 @@ func TestProjectService_UpdateProject_AllowsRenameAfterJournalRecoveryDockerUnavoldDir := "nginx"projectPath := createComposeProjectDir(t, projectsDir, oldDir)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-recovery-docker-unavailable"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-recovery-docker-unavailable"},Name: "nginx",DirName: &oldDir,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -1612,8 +1611,8 @@ func TestProjectService_UpdateProject_AllowsRenameAfterJournalRecoveryDockerUnavrequire.NoError(t, err)require.NoError(t, kvService.Set(ctx, projectRenameJournalKeyPrefixInternal+project.ID, string(payload)))- updated, err := svc.UpdateProject(ctx, project.ID, ptr("web"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, ptr("web"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1645,17 +1644,17 @@ func TestProjectService_UpdateProject_RenamesDirectoryWhenNameChanges(t *testingoriginalDirName := "Foo"originalPath := createComposeProjectDir(t, projectsDir, originalDirName)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-1"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-1"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1669,7 +1668,7 @@ func TestProjectService_UpdateProject_RenamesDirectoryWhenNameChanges(t *testingassert.NoDirExists(t, originalPath)assert.DirExists(t, expectedPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "bar", fromDB.Name)assert.Equal(t, expectedPath, fromDB.Path)@@ -1697,17 +1696,17 @@ func TestProjectService_UpdateProject_RenameFailsWhenTargetDirectoryExists(t *tetargetPath := filepath.Join(projectsDir, "bar")require.NoError(t, os.MkdirAll(targetPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-2"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-2"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1716,7 +1715,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenTargetDirectoryExists(t *teassert.DirExists(t, originalPath)assert.DirExists(t, targetPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "Foo", fromDB.Name)assert.Equal(t, originalPath, fromDB.Path)@@ -1741,17 +1740,17 @@ func TestProjectService_UpdateProject_RenameFailsWhenProjectRunning(t *testing.ToriginalPath := filepath.Join(projectsDir, originalDirName)require.NoError(t, os.MkdirAll(originalPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-3"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-3"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusRunning,+ Status: ProjectStatusRunning,}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1760,7 +1759,7 @@ func TestProjectService_UpdateProject_RenameFailsWhenProjectRunning(t *testing.Tassert.DirExists(t, originalPath)assert.NoDirExists(t, filepath.Join(projectsDir, "bar"))- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "Foo", fromDB.Name)assert.Equal(t, originalPath, fromDB.Path)@@ -1800,17 +1799,17 @@ func TestProjectService_UpdateProject_RenameRejectsStaleStoppedWhenRuntimeIsRunnoriginalDirName := "Foo"originalPath := createComposeProjectDir(t, projectsDir, originalDirName)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-stale-stopped-running-rename"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-stale-stopped-running-rename"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1819,11 +1818,11 @@ func TestProjectService_UpdateProject_RenameRejectsStaleStoppedWhenRuntimeIsRunnassert.DirExists(t, originalPath)assert.NoDirExists(t, filepath.Join(projectsDir, "bar"))- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "Foo", fromDB.Name)assert.Equal(t, originalPath, fromDB.Path)- assert.Equal(t, models.ProjectStatusStopped, fromDB.Status)+ assert.Equal(t, ProjectStatusStopped, fromDB.Status)}func TestProjectService_UpdateProject_RenameResolvesUnknownStoppedStatusBeforeVolumeMigration(t *testing.T) {@@ -1847,18 +1846,18 @@ func TestProjectService_UpdateProject_RenameResolvesUnknownStoppedStatusBeforeVooriginalPath := createComposeProjectDir(t, projectsDir, originalDirName)statusReason := "stale runtime status"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-unknown-stopped-rename"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-unknown-stopped-rename"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusUnknown,+ Status: ProjectStatusUnknown,StatusReason: &statusReason,}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1867,18 +1866,18 @@ func TestProjectService_UpdateProject_RenameResolvesUnknownStoppedStatusBeforeVoexpectedPath := filepath.Join(projectsDir, "bar")assert.Equal(t, "bar", updated.Name)assert.Equal(t, expectedPath, updated.Path)- assert.Equal(t, models.ProjectStatusStopped, updated.Status)+ assert.Equal(t, ProjectStatusStopped, updated.Status)assert.Nil(t, updated.StatusReason)assert.Equal(t, 1, updated.ServiceCount)assert.Equal(t, 0, updated.RunningCount)assert.NoDirExists(t, originalPath)assert.DirExists(t, expectedPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "bar", fromDB.Name)assert.Equal(t, expectedPath, fromDB.Path)- assert.Equal(t, models.ProjectStatusStopped, fromDB.Status)+ assert.Equal(t, ProjectStatusStopped, fromDB.Status)assert.Nil(t, fromDB.StatusReason)assert.Equal(t, 1, fromDB.ServiceCount)assert.Equal(t, 0, fromDB.RunningCount)@@ -1919,18 +1918,18 @@ func TestProjectService_UpdateProject_RenameRejectsUnknownWhenRuntimeIsRunning(toriginalPath := createComposeProjectDir(t, projectsDir, originalDirName)statusReason := "stale runtime status"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-unknown-running-rename"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-unknown-running-rename"},Name: "Foo",DirName: &originalDirName,Path: originalPath,- Status: models.ProjectStatusUnknown,+ Status: ProjectStatusUnknown,StatusReason: &statusReason,}require.NoError(t, db.Create(project).Error)- _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err = svc.UpdateProject(ctx, project.ID, new("bar"), nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -1939,11 +1938,11 @@ func TestProjectService_UpdateProject_RenameRejectsUnknownWhenRuntimeIsRunning(tassert.DirExists(t, originalPath)assert.NoDirExists(t, filepath.Join(projectsDir, "bar"))- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)assert.Equal(t, "Foo", fromDB.Name)assert.Equal(t, originalPath, fromDB.Path)- assert.Equal(t, models.ProjectStatusUnknown, fromDB.Status)+ assert.Equal(t, ProjectStatusUnknown, fromDB.Status)require.NotNil(t, fromDB.StatusReason)assert.Equal(t, statusReason, *fromDB.StatusReason)}@@ -1965,12 +1964,12 @@ func TestProjectService_UpdateProject_ValidatesComposeUsingExistingProjectName(tprojectPath := filepath.Join(projectsDir, dirName)require.NoError(t, os.MkdirAll(projectPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-compose-name"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-compose-name"},Name: "demo",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -1981,8 +1980,8 @@ services:`env := "COMPOSE_PROJECT_NAME=\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2008,12 +2007,12 @@ func TestProjectService_UpdateProject_AllowsMissingEnvFileDuringComposeValidatioprojectPath := filepath.Join(projectsDir, dirName)require.NoError(t, os.MkdirAll(projectPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-env-file"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-env-file"},Name: "env-required",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2024,8 +2023,8 @@ func TestProjectService_UpdateProject_AllowsMissingEnvFileDuringComposeValidatio- .env`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2053,12 +2052,12 @@ func TestProjectService_UpdateProject_AllowsMissingLocalIncludeDuringComposeValiprojectPath := filepath.Join(projectsDir, dirName)require.NoError(t, os.MkdirAll(projectPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-missing-include"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-missing-include"},Name: "include-new",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2069,8 +2068,8 @@ services:image: nginx:alpine`- updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, ptr(compose), nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2108,8 +2107,8 @@ services:image: nginx:alpine`- project, err := svc.CreateProject(ctx, "with-external-include", compose, nil, projecttypes.CreateProjectWorkspaceManifest{}, nil, nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ project, err := svc.CreateProject(ctx, "with-external-include", compose, nil, projecttypes.CreateProjectWorkspaceManifest{}, nil, nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2136,16 +2135,16 @@ func TestProjectService_UpdateProject_AllowsExternalInclude(t *testing.T) {require.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectsDir, "shared.yaml"), []byte("services: {}\n"), 0o644))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-external-include"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-external-include"},Name: "external-include",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- user := models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"}+ user := common.User{BaseModel: database.BaseModel{ID: "u1"}, Username: "tester"}compose := `include:- ../shared.yaml@@ -2187,7 +2186,7 @@ func TestProjectService_CreateProject_CommitsWorkspaceAndConfigurationTogether(tmap[int][]byte{0: []byte("workspace content\n")},nil,nil,- models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"},+ common.User{BaseModel: database.BaseModel{ID: "u1"}, Username: "tester"},)require.NoError(t, err)require.NotNil(t, created)@@ -2221,14 +2220,14 @@ func TestProjectService_CreateProject_RollsBackInvalidWorkspaceManifest(t *testinil,nil,nil,- models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"},+ common.User{BaseModel: database.BaseModel{ID: "u1"}, Username: "tester"},)require.Error(t, err)require.Nil(t, created)require.NoDirExists(t, filepath.Join(projectsDir, "invalid-workspace"))var count int64- require.NoError(t, db.Model(&models.Project{}).Where("name = ?", "invalid-workspace").Count(&count).Error)+ require.NoError(t, db.Model(&Project{}).Where("name = ?", "invalid-workspace").Count(&count).Error)require.Zero(t, count)}@@ -2250,12 +2249,12 @@ func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidationrequire.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("FOO=bar\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-existing-env-file"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-existing-env-file"},Name: "env-existing",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2266,8 +2265,8 @@ func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation- .env`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2281,7 +2280,7 @@ func TestProjectService_UpdateProject_UsesExistingEnvFileDuringComposeValidation// newProjectServiceForOverrideTestInternal builds a project with a base compose// file on disk and returns the service, the project record, and the project path.-func newProjectServiceForOverrideTestInternal(t *testing.T, dirName, baseCompose string) (*ProjectService, *models.Project, string) {+func newProjectServiceForOverrideTestInternal(t *testing.T, dirName, baseCompose string) (*ProjectService, *Project, string) {t.Helper()db := setupProjectTestDB(t)ctx := context.Background()@@ -2299,12 +2298,12 @@ func newProjectServiceForOverrideTestInternal(t *testing.T, dirName, baseComposerequire.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte(baseCompose), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-" + dirName},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-" + dirName},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2316,8 +2315,8 @@ func TestProjectService_UpdateProject_CreatesOverrideWithDefaultName(t *testing.svc, project, projectPath := newProjectServiceForOverrideTestInternal(t, "override-create", "services:\n app:\n image: nginx:alpine\n")override := "services:\n app:\n image: busybox:latest\n"- _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2343,8 +2342,8 @@ func TestProjectService_UpdateProject_PreservesExistingOverrideName(t *testing.Trequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "docker-compose.override.yml"), []byte("services:\n app:\n image: alpine:3\n"), 0o600))override := "services:\n app:\n image: busybox:latest\n"- _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(override), common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2363,8 +2362,8 @@ func TestProjectService_UpdateProject_DeletesOverrideOnBlank(t *testing.T) {require.NoError(t, os.WriteFile(overridePath, []byte("services:\n app:\n image: busybox:latest\n"), 0o600))// A non-nil blank override deletes the file so the deploy stops merging it.- _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(""), models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err := svc.UpdateProject(ctx, project.ID, nil, nil, nil, new(""), common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2381,8 +2380,8 @@ func TestProjectService_UpdateProject_MergedValidationFailureLeavesDiskUnchanged// backup/restore must leave both the base and the override untouched on disk.newCompose := "services:\n app:\n image: nginx:1.27\n"badOverride := "services:\n app:\n image: \"unterminated\n"- _, err := svc.UpdateProject(ctx, project.ID, nil, new(newCompose), nil, new(badOverride), models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err := svc.UpdateProject(ctx, project.ID, nil, new(newCompose), nil, new(badOverride), common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.Error(t, err)@@ -2410,12 +2409,12 @@ func TestProjectService_UpdateProject_UsesProvidedEnvContentDuringComposeValidatprojectPath := filepath.Join(projectsDir, dirName)require.NoError(t, os.MkdirAll(projectPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-new-env-file"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-new-env-file"},Name: "env-updated",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2427,8 +2426,8 @@ func TestProjectService_UpdateProject_UsesProvidedEnvContentDuringComposeValidat`env := "FOO=updated\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2457,12 +2456,12 @@ func TestProjectService_UpdateProject_ReturnsEnvParseErrorDuringComposeValidatioprojectPath := filepath.Join(projectsDir, dirName)require.NoError(t, os.MkdirAll(projectPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-invalid-env-file"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-invalid-env-file"},Name: "env-invalid",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2474,8 +2473,8 @@ func TestProjectService_UpdateProject_ReturnsEnvParseErrorDuringComposeValidatio`env := "BROKEN=${UNTERMINATED\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), new(env), nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2503,12 +2502,12 @@ func TestProjectService_UpdateProject_UsesGlobalEnvDuringComposeValidation(t *terequire.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectsDir, projects.GlobalEnvFileName), []byte("DATA_NAS_FOLDER=/srv/media\nMYPATH=/containers/\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-global-env-update"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-global-env-update"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2520,8 +2519,8 @@ func TestProjectService_UpdateProject_UsesGlobalEnvDuringComposeValidation(t *te- ${MYPATH}cats/templates:/app/templates`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2552,12 +2551,12 @@ func TestProjectService_UpdateProject_DoesNotResolveHostEnvThroughGlobalEnvDurinrequire.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectsDir, projects.GlobalEnvFileName), []byte("DATA_NAS_FOLDER=${HOST_ONLY_PATH}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-host-env-guard"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-host-env-guard"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2568,8 +2567,8 @@ func TestProjectService_UpdateProject_DoesNotResolveHostEnvThroughGlobalEnvDurin- ${DATA_NAS_FOLDER}:/data`- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(compose), nil, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2598,17 +2597,17 @@ func TestProjectService_UpdateProject_DerivesProjectOverrideEnvWhenGitSourceExisrequire.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("BASE=git\n"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env.git"), []byte("BASE=git\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-override-edit"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-override-edit"},Name: "override-edit",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=example\n"), nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=example\n"), nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2650,17 +2649,17 @@ func TestProjectService_UpdateProject_UnchangedGitEnvLeavesFilesUntouched(t *tesrequire.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env.git"), []byte(gitContent), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, "project.env"), []byte(overrideContent), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-unchanged-git-env"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-unchanged-git-env"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &effectiveContent, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &effectiveContent, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2743,17 +2742,17 @@ func TestProjectService_UpdateProject_DeletingGitBackedKeyFallsBackToGit(t *testrequire.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env.git"), []byte("BASE=git\nTOKEN=git\n"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, "project.env"), []byte("TOKEN=local\nLOCAL_ONLY=1\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-override-delete"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-override-delete"},Name: "override-delete",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=1\n"), nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, new("BASE=git\nLOCAL_ONLY=1\n"), nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -2791,18 +2790,18 @@ func TestProjectService_ApplyGitSyncProjectFiles_MigratesDirectEnvIntoProjectOverequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:alpine\n"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("TOKEN=stale-local\nLOCAL_ONLY=1\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-migrate"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-migrate"},Name: "git-sync-migrate",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)gitEnv := "TOKEN=git\nREMOTE_ONLY=1\n"- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", &gitEnv, nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", &gitEnv, nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2841,12 +2840,12 @@ func TestProjectService_ApplyGitSyncProjectFiles_PreservesGitEnvSyntax(t *testinrequire.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:alpine\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-env-syntax"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-env-syntax"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -2859,8 +2858,8 @@ func TestProjectService_ApplyGitSyncProjectFiles_PreservesGitEnvSyntax(t *testingitEnv := "# keep git formatting\nZ_LAST=last\nCLOUDFLARE_CLIENT_SECRET=$$pbkdf2-sha512$$310000$$XXX\nQUOTED_SECRET='$pbkdf2-sha512$310000$XXX'\nA_FIRST=first"for range 2 {- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, &gitEnv, nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, &gitEnv, nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2905,17 +2904,17 @@ func TestProjectService_ApplyGitSyncProjectFiles_NormalizesStaleCopiedGitOverridrequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "project.env"), []byte("BASE=git\nSHARED=1\nTOKEN=local\n"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("BASE=git\nSHARED=1\nTOKEN=local\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-normalize"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-normalize"},Name: "git-sync-normalize",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", new("BASE=git-updated\nSHARED=1\nREMOTE_ONLY=1\n"), nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", new("BASE=git-updated\nSHARED=1\nREMOTE_ONLY=1\n"), nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -2953,17 +2952,17 @@ func TestProjectService_ApplyGitSyncProjectFiles_RemovesLegacyDeletedGitMasks(trequire.NoError(t, os.WriteFile(filepath.Join(projectPath, "project.env"), []byte("TOKEN=\nLOCAL_ONLY=1\n"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("LOCAL_ONLY=1\nSHARED=1\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-delete-mask"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-delete-mask"},Name: "git-sync-delete-mask",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", new("TOKEN=git-updated\nSHARED=1\nREMOTE_ONLY=1\n"), nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", new("TOKEN=git-updated\nSHARED=1\nREMOTE_ONLY=1\n"), nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -3001,17 +3000,17 @@ func TestProjectService_ApplyGitSyncProjectFiles_RemovesGitEnvSource(t *testing.require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env"), []byte("BASE=git\n"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env.git"), []byte("BASE=git\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-remove"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-remove"},Name: "git-sync-remove",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -3043,18 +3042,18 @@ func TestProjectService_ApplyGitSyncProjectFiles_WritesAndRemovesComposeOverriderequire.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:alpine\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-override"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-override"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)overrideContent := "services:\n app:\n image: busybox:latest\n"- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", nil, new(overrideContent), "compose.override.yaml", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", nil, new(overrideContent), "compose.override.yaml", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -3065,8 +3064,8 @@ func TestProjectService_ApplyGitSyncProjectFiles_WritesAndRemovesComposeOverrideassert.Equal(t, overrideContent, string(overrideBytes))// A subsequent sync without an override removes the previously synced file.- updated, err = svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err = svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:alpine\n", nil, nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -3094,12 +3093,12 @@ func TestProjectService_ApplyGitSyncProjectFiles_UsesGlobalEnvDuringComposeValidrequire.NoError(t, os.MkdirAll(projectPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(projectsDir, projects.GlobalEnvFileName), []byte("DATA_NAS_FOLDER=/srv/media\nMYPATH=/containers/\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-global-env"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-global-env"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -3111,8 +3110,8 @@ func TestProjectService_ApplyGitSyncProjectFiles_UsesGlobalEnvDuringComposeValid- ${MYPATH}cats/templates:/app/templates`- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, nil, nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, nil, nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -3154,17 +3153,17 @@ func TestProjectService_ApplyGitSyncProjectFiles_TolerantOfUndefinedComposeVar(tcpus: "${CPU}"`- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-undefined-var"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-undefined-var"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, nil, nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, compose, nil, nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)@@ -3234,12 +3233,12 @@ func TestProjectService_GetProjectDetails_ReturnsEffectiveEnvContent(t *testing.require.NoError(t, os.WriteFile(filepath.Join(projectPath, ".env.git"), []byte("BASE=git\n"), 0o600))require.NoError(t, os.WriteFile(filepath.Join(projectPath, "project.env"), []byte("TOKEN=secret\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-details-override"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-details-override"},Name: "details-override",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -3315,7 +3314,7 @@ func TestBuildProjectUpdateInfoSummaryInternal(t *testing.T) {name: "not pulled when an image is missing locally and nothing else needs attention",imageRefs: []string{"nginx:latest", "redis:7"},updates: map[string]*imagetypes.UpdateInfo{- "nginx:latest": {HasUpdate: false, UpdateType: models.UpdateTypeNotPulled, CheckTime: now},+ "nginx:latest": {HasUpdate: false, UpdateType: imageupdate.UpdateTypeNotPulled, CheckTime: now},"redis:7": {HasUpdate: false, CheckTime: now.Add(-time.Minute)},},wantStatus: "not_pulled",@@ -3369,16 +3368,16 @@ func TestProjectService_GetProjectDetails_IncludesUpdateInfo(t *testing.T) {projectPath := createComposeProjectDir(t, projectsDir, "updates-demo")require.NoError(t, os.WriteFile(filepath.Join(projectPath, "compose.yaml"), []byte("services:\n app:\n image: nginx:latest\n"), 0o644))- projectRecord := &models.Project{- BaseModel: models.BaseModel{ID: "proj-update-info"},+ projectRecord := &Project{+ BaseModel: database.BaseModel{ID: "proj-update-info"},Name: "updates-demo",DirName: ptr("updates-demo"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(projectRecord).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:update-demo",Repository: "docker.io/library/nginx",Tag: "latest",@@ -3452,12 +3451,12 @@ func TestProjectService_GetProjectDetails_RefreshesRuntimeStatusWithoutRuntimeSe})t.Setenv("DOCKER_HOST", dockerHostFromProjectRuntimeServerURLInternal(t, server.URL))- projectRecord := &models.Project{- BaseModel: models.BaseModel{ID: "proj-runtime-refresh"},+ projectRecord := &Project{+ BaseModel: database.BaseModel{ID: "proj-runtime-refresh"},Name: "projectA",DirName: ptr("projectA"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,ServiceCount: 2,RunningCount: 0,}@@ -3467,7 +3466,7 @@ func TestProjectService_GetProjectDetails_RefreshesRuntimeStatusWithoutRuntimeSedetails, err := svc.GetProjectDetails(ctx, projectRecord.ID, projecttypes.DetailsOptions{})require.NoError(t, err)- assert.Equal(t, string(models.ProjectStatusRunning), details.Status)+ assert.Equal(t, string(ProjectStatusRunning), details.Status)assert.Equal(t, 2, details.ServiceCount)assert.Equal(t, 2, details.RunningCount)assert.Empty(t, details.RuntimeServices)@@ -3504,12 +3503,12 @@ func TestProjectService_GetProjectDetails_PopulatesRuntimeServicesFromComposePs(})t.Setenv("DOCKER_HOST", dockerHostFromProjectRuntimeServerURLInternal(t, server.URL))- projectRecord := &models.Project{- BaseModel: models.BaseModel{ID: "proj-runtime-services"},+ projectRecord := &Project{+ BaseModel: database.BaseModel{ID: "proj-runtime-services"},Name: "projectA",DirName: ptr("projectA"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,ServiceCount: 1,RunningCount: 0,}@@ -3520,7 +3519,7 @@ func TestProjectService_GetProjectDetails_PopulatesRuntimeServicesFromComposePs(details, err := svc.GetProjectDetails(ctx, projectRecord.ID, projecttypes.DetailsOptions{IncludeRuntimeServices: true})require.NoError(t, err)require.Len(t, details.RuntimeServices, 1)- assert.Equal(t, string(models.ProjectStatusRunning), details.Status)+ assert.Equal(t, string(ProjectStatusRunning), details.Status)assert.Equal(t, "server", details.RuntimeServices[0].Name)assert.Equal(t, "running", details.RuntimeServices[0].Status)assert.Equal(t, "server-container", details.RuntimeServices[0].ContainerID)@@ -3550,37 +3549,37 @@ func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {unknownPath := createComposeProjectDir(t, projectsDir, "unknown-demo")require.NoError(t, os.WriteFile(filepath.Join(unknownPath, "compose.yaml"), []byte("services:\n app:\n image: alpine:latest\n"), 0o644))- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-updated"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-updated"},Name: "updated-demo",DirName: ptr("updated-demo"),Path: updatedPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-current"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-current"},Name: "current-demo",DirName: ptr("current-demo"),Path: upToDatePath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-error"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-error"},Name: "error-demo",DirName: ptr("error-demo"),Path: errorPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-unknown"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-unknown"},Name: "unknown-demo",DirName: ptr("unknown-demo"),Path: unknownPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)now := time.Now().UTC()- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:updated-image",Repository: "docker.io/library/nginx",Tag: "latest",@@ -3589,7 +3588,7 @@ func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {CurrentVersion: "latest",CheckTime: now,}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:current-image",Repository: "docker.io/library/redis",Tag: "7",@@ -3598,7 +3597,7 @@ func TestProjectService_ListProjects_FiltersByUpdateStatus(t *testing.T) {CurrentVersion: "7",CheckTime: now.Add(-time.Minute),}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:error-image",Repository: "docker.io/library/busybox",Tag: "latest",@@ -3647,21 +3646,21 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal(t *testing.T) {imageService := image.NewImageService(db, nil, nil, nil, nil, nil)now := time.Now().UTC()- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:media-image",Repository: "docker.io/library/nginx",Tag: "latest",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "latest",CheckTime: now,}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:known-image",Repository: "docker.io/library/redis",Tag: "7",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "7",CheckTime: now,}).Error)@@ -3702,7 +3701,7 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal(t *testing.T) {assert.Equal(t, "compose:media", row.ID)assert.Equal(t, "media", row.Name)assert.True(t, row.IsDiscovered)- assert.Equal(t, string(models.ProjectStatusRunning), row.Status)+ assert.Equal(t, string(ProjectStatusRunning), row.Status)require.NotNil(t, row.UpdateInfo)assert.True(t, row.UpdateInfo.HasUpdate)assert.Equal(t, []string{"nginx:latest"}, row.UpdateInfo.UpdatedImageRefs)@@ -3715,12 +3714,12 @@ func TestBuildDiscoveredComposeProjectUpdateRowsInternal_FallsBackToImageID(t *tctx := context.Background()imageService := image.NewImageService(db, nil, nil, nil, nil, nil)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:media-image",Repository: "registry.example.test/custom/media",Tag: "latest",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "latest",CheckTime: time.Now().UTC(),}).Error)@@ -3753,19 +3752,19 @@ func TestProjectService_ListProjects_FiltersArchivedProjects(t *testing.T) {activePath := createComposeProjectDir(t, projectsRoot, "active-demo")archivedPath := createComposeProjectDir(t, projectsRoot, "archived-demo")- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-active"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-active"},Name: "active-demo",DirName: ptr("active-demo"),Path: activePath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-archived"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-archived"},Name: "archived-demo",DirName: ptr("archived-demo"),Path: archivedPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,IsArchived: true,ArchivedAt: new(time.Now().UTC()),}).Error)@@ -3814,12 +3813,12 @@ func TestProjectService_ArchiveProject_RequiresStoppedProject(t *testing.T) {projectPath := createComposeProjectDir(t, projectsRoot, "running-demo")// DB row says stopped; the live Docker state below is what must block the archive.- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-running"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-running"},Name: "running-demo",DirName: ptr("running-demo"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)configureProjectRuntimeDockerInternal(t, []container.Summary{@@ -3839,11 +3838,11 @@ func TestProjectService_ArchiveProject_RequiresStoppedProject(t *testing.T) {})svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())- err = svc.ArchiveProject(ctx, "project-running", models.User{BaseModel: models.BaseModel{ID: "user-1"}, Username: "tester"})+ err = svc.ArchiveProject(ctx, "project-running", common.User{BaseModel: database.BaseModel{ID: "user-1"}, Username: "tester"})require.Error(t, err)require.ErrorIs(t, err, common.ErrProjectMustBeStopped)- var stored models.Project+ var stored Projectrequire.NoError(t, db.First(&stored, "id = ?", "project-running").Error)assert.False(t, stored.IsArchived)assert.Nil(t, stored.ArchivedAt)@@ -3859,27 +3858,27 @@ func TestProjectService_ArchiveProject_TogglesArchiveFlag(t *testing.T) {require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot))projectPath := createComposeProjectDir(t, projectsRoot, "stopped-demo")- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-stopped"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-stopped"},Name: "stopped-demo",DirName: ptr("stopped-demo"),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)configureProjectRuntimeDockerInternal(t, nil)svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())- user := models.User{BaseModel: models.BaseModel{ID: "user-1"}, Username: "tester"}+ user := common.User{BaseModel: database.BaseModel{ID: "user-1"}, Username: "tester"}require.NoError(t, svc.ArchiveProject(ctx, "project-stopped", user))- var stored models.Project+ var stored Projectrequire.NoError(t, db.First(&stored, "id = ?", "project-stopped").Error)assert.True(t, stored.IsArchived)assert.NotNil(t, stored.ArchivedAt)require.NoError(t, svc.UnarchiveProject(ctx, "project-stopped", user))- var unarchived models.Project+ var unarchived Projectrequire.NoError(t, db.First(&unarchived, "id = ?", "project-stopped").Error)assert.False(t, unarchived.IsArchived)assert.Nil(t, unarchived.ArchivedAt)@@ -3895,37 +3894,37 @@ func TestProjectService_ArchiveProject_LiveVerificationErrorPolicy(t *testing.T)require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot))unreachablePath := createComposeProjectDir(t, projectsRoot, "unreachable-demo")- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-unreachable"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-unreachable"},Name: "unreachable-demo",DirName: ptr("unreachable-demo"),Path: unreachablePath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)noComposePath := filepath.Join(projectsRoot, "no-compose-demo")require.NoError(t, os.MkdirAll(noComposePath, 0o755))- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "project-no-compose"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "project-no-compose"},Name: "no-compose-demo",DirName: ptr("no-compose-demo"),Path: noComposePath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)t.Setenv("DOCKER_HOST", "tcp://127.0.0.1:1")svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())- user := models.User{BaseModel: models.BaseModel{ID: "user-1"}, Username: "tester"}+ user := common.User{BaseModel: database.BaseModel{ID: "user-1"}, Username: "tester"}err = svc.ArchiveProject(ctx, "project-unreachable", user)require.Error(t, err)- var stored models.Project+ var stored Projectrequire.NoError(t, db.First(&stored, "id = ?", "project-unreachable").Error)assert.False(t, stored.IsArchived)require.NoError(t, svc.ArchiveProject(ctx, "project-no-compose", user))- var archived models.Project+ var archived Projectrequire.NoError(t, db.First(&archived, "id = ?", "project-no-compose").Error)assert.True(t, archived.IsArchived)}@@ -3933,11 +3932,11 @@ func TestProjectService_ArchiveProject_LiveVerificationErrorPolicy(t *testing.T)func TestProjectService_MapProjectToDto_SetsRedeployDisabledFromRuntimeServices(t *testing.T) {projectPath := filepath.Join(t.TempDir(), "arcane")now := time.Now()- proj := models.Project{+ proj := Project{Name: "arcane",Path: projectPath,ServiceCount: 1,- BaseModel: models.BaseModel{+ BaseModel: database.BaseModel{ID: "project-arcane",CreatedAt: now,UpdatedAt: &now,@@ -4046,12 +4045,12 @@ func TestProjectService_ListProjects_WithDerivedStatusFilter_AllowsAllPageSizeSefor i := range 25 {projectPath := createComposeProjectDir(t, projectsRoot, fmt.Sprintf("stopped-%02d", i))- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: fmt.Sprintf("project-%02d", i)},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: fmt.Sprintf("project-%02d", i)},Name: fmt.Sprintf("stopped-%02d", i),DirName: ptr(fmt.Sprintf("stopped-%02d", i)),Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)}@@ -4059,7 +4058,7 @@ func TestProjectService_ListProjects_WithDerivedStatusFilter_AllowsAllPageSizeSeitems, page, err := svc.ListProjects(ctx, pagination.QueryParams{Filters: map[string]string{- "status": string(models.ProjectStatusStopped),+ "status": string(ProjectStatusStopped),},Params: pagination.Params{Limit: -1},SortParams: pagination.SortParams{Sort: "name", Order: pagination.SortAsc},@@ -4284,25 +4283,25 @@ func TestProjectService_DeployProject_StopsOnBuildPreparationError(t *testing.T)require.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte(composeContent), 0o644))require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot+":"+projectsRoot))- proj := &models.Project{- BaseModel: models.BaseModel{ID: "p1"},+ proj := &Project{+ BaseModel: database.BaseModel{ID: "p1"},Name: "demo",Path: projectDir,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(proj).Error)buildSvc := testBuildBuilder{err: errors.New("boom build")}svc := NewProjectService(db, settingsService, nil, nil, nil, buildSvc, nil, nil, config.Load())- err = svc.DeployProject(ctx, "p1", models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"}, nil)+ err = svc.DeployProject(ctx, "p1", common.User{BaseModel: database.BaseModel{ID: "u1"}, Username: "tester"}, nil)require.Error(t, err)assert.Contains(t, err.Error(), "failed to prepare project images for deploy")assert.Contains(t, err.Error(), "boom build")- var updated models.Project+ var updated Projectrequire.NoError(t, db.First(&updated, "id = ?", "p1").Error)- assert.Equal(t, models.ProjectStatusStopped, updated.Status)+ assert.Equal(t, ProjectStatusStopped, updated.Status)}func TestProjectService_DeployProject_BuildsGeneratedImageWithoutPull(t *testing.T) {@@ -4326,18 +4325,18 @@ func TestProjectService_DeployProject_BuildsGeneratedImageWithoutPull(t *testingrequire.NoError(t, os.WriteFile(filepath.Join(projectDir, "compose.yaml"), []byte(composeContent), 0o644))require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot+":"+projectsRoot))- proj := &models.Project{- BaseModel: models.BaseModel{ID: "p-generated"},+ proj := &Project{+ BaseModel: database.BaseModel{ID: "p-generated"},Name: "build-test",Path: projectDir,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(proj).Error)buildSvc := testBuildBuilder{err: errors.New("boom build")}svc := NewProjectService(db, settingsService, nil, nil, nil, buildSvc, nil, nil, config.Load())- err = svc.DeployProject(ctx, proj.ID, models.User{BaseModel: models.BaseModel{ID: "u1"}, Username: "tester"}, nil)+ err = svc.DeployProject(ctx, proj.ID, common.User{BaseModel: database.BaseModel{ID: "u1"}, Username: "tester"}, nil)require.Error(t, err)assert.Contains(t, err.Error(), "failed to prepare project images for deploy")assert.Contains(t, err.Error(), "boom build")@@ -4620,8 +4619,8 @@ func TestProjectService_SyncProjectsFromFileSystem_PrunesLeakedScratchRow(t *tesscratchName := ".gitops-backup-9"scratchPath := createComposeProjectDir(t, projectsRoot, scratchName)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "phantom-scratch"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "phantom-scratch"},Name: scratchName,DirName: &scratchName,Path: scratchPath,@@ -4656,10 +4655,10 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesProjectsWhenDirector// projects (the guard must not give small installs a free pass).const seeded = 3for i := range seeded {- require.NoError(t, db.WithContext(ctx).Create(&models.Project{+ require.NoError(t, db.WithContext(ctx).Create(&Project{Name: fmt.Sprintf("project-%d", i),Path: filepath.Join(projectsRoot, fmt.Sprintf("project-%d", i)),- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)}@@ -4820,12 +4819,12 @@ func TestProjectService_SyncProjectsFromFileSystem_DiscoversReadableProjectsDesp// Seed a DB row (bypassing the filesystem) whose Path sits under the// now-unreadable subtree, simulating a project Arcane previously knew about.strandedDirName := "stranded-project"- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: "stranded-under-unreadable"},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: "stranded-under-unreadable"},Name: "stranded-project",DirName: &strandedDirName,Path: filepath.Join(unreadableDir, "stranded-project"),- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}).Error)require.NoError(t, settingsService.SetStringSetting(ctx, "projectsDirectory", projectsRoot))@@ -4869,7 +4868,7 @@ func TestProjectService_SyncProjectsFromFileSystem_AllowsDuplicateLeafDirectoriesvc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())require.NoError(t, svc.SyncProjectsFromFileSystem(ctx))- var items []models.Project+ var items []Projectrequire.NoError(t, db.WithContext(ctx).Order("path asc").Find(&items).Error)require.Len(t, items, 2)@@ -4961,7 +4960,7 @@ func TestProjectService_SyncProjectsFromFileSystem_RefreshesServiceCountOnCompossvc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())require.NoError(t, svc.SyncProjectsFromFileSystem(ctx))- var project models.Project+ var project Projectrequire.NoError(t, db.WithContext(ctx).Where("path = ?", projectPath).First(&project).Error)assert.Equal(t, 1, project.ServiceCount)@@ -4993,7 +4992,7 @@ services:svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())require.NoError(t, svc.SyncProjectsFromFileSystem(ctx))- var project models.Project+ var project Projectrequire.NoError(t, db.WithContext(ctx).Where("path = ?", projectPath).First(&project).Error)assert.Equal(t, "ai_tools", project.Name)require.NotNil(t, project.DirName)@@ -5014,19 +5013,19 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesValidCustomNameWithoprojectPath := createComposeProjectDir(t, projectsRoot, "folder-name")dirName := "folder-name"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-custom-name"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-custom-name"},Name: "custom-name",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)svc := NewProjectService(db, settingsService, nil, nil, nil, nil, nil, nil, config.Load())require.NoError(t, svc.SyncProjectsFromFileSystem(ctx))- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.WithContext(ctx).Where("id = ?", project.ID).First(&fromDB).Error)assert.Equal(t, "custom-name", fromDB.Name)require.NotNil(t, fromDB.DirName)@@ -5037,7 +5036,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesValidCustomNameWithofunc TestProjectService_SyncProjectsFromFileSystem_PreservesGitOpsProjectWithCustomComposeFilename(t *testing.T) {db := setupProjectTestDB(t)ctx := context.Background()- require.NoError(t, db.AutoMigrate(&models.GitOpsSync{}))+ require.NoError(t, db.AutoMigrate(&GitOpsSync{}))settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)require.NoError(t, err)@@ -5049,8 +5048,8 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesGitOpsProjectWithCussyncProjectID := "proj-custom-compose"syncID := "sync-custom-compose"- sync := &models.GitOpsSync{- BaseModel: models.BaseModel{ID: syncID},+ sync := &GitOpsSync{+ BaseModel: database.BaseModel{ID: syncID},Name: "Radarr Sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -5061,12 +5060,12 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesGitOpsProjectWithCus}require.NoError(t, db.Create(sync).Error)- project := &models.Project{- BaseModel: models.BaseModel{ID: syncProjectID},+ project := &Project{+ BaseModel: database.BaseModel{ID: syncProjectID},Name: "Radarr",DirName: ptr("Radarr-3"),Path: projectDir,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,GitOpsManagedBy: &syncID,}require.NoError(t, db.Create(project).Error)@@ -5087,7 +5086,7 @@ func TestProjectService_SyncProjectsFromFileSystem_PreservesGitOpsProjectWithCusfunc TestProjectService_GetProjectDetails_UsesGitOpsCustomComposeFilename(t *testing.T) {db := setupProjectTestDB(t)ctx := context.Background()- require.NoError(t, db.AutoMigrate(&models.GitOpsSync{}))+ require.NoError(t, db.AutoMigrate(&GitOpsSync{}))settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)require.NoError(t, err)@@ -5101,8 +5100,8 @@ func TestProjectService_GetProjectDetails_UsesGitOpsCustomComposeFilename(t *tessyncProjectID := "proj-custom-compose-details"syncID := "sync-custom-compose-details"- require.NoError(t, db.Create(&models.GitOpsSync{- BaseModel: models.BaseModel{ID: syncID},+ require.NoError(t, db.Create(&GitOpsSync{+ BaseModel: database.BaseModel{ID: syncID},Name: "Radarr Sync",EnvironmentID: "0",RepositoryID: "repo-1",@@ -5112,12 +5111,12 @@ func TestProjectService_GetProjectDetails_UsesGitOpsCustomComposeFilename(t *tesSyncDirectory: true,}).Error)- require.NoError(t, db.Create(&models.Project{- BaseModel: models.BaseModel{ID: syncProjectID},+ require.NoError(t, db.Create(&Project{+ BaseModel: database.BaseModel{ID: syncProjectID},Name: "Radarr",DirName: ptr("Radarr-3"),Path: projectDir,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,GitOpsManagedBy: &syncID,}).Error)@@ -5157,20 +5156,20 @@ func TestProjectService_UpdateProject_WritesThroughSymlinkedProjectPath(t *testieventService := event.NewEventService(db, nil, nil)svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-symlink-update"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-symlink-update"},Name: "demo",DirName: new("demo"),Path: linkPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)updatedCompose := "services:\n app:\n image: nginx:1.27-alpine\n"updatedEnv := "FOO=updated\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, new(updatedCompose), new(updatedEnv), nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, new(updatedCompose), new(updatedEnv), nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -5212,18 +5211,18 @@ func TestProjectService_UpdateProject_WritesThroughExternalEnvSymlink(t *testingeventService := event.NewEventService(db, nil, nil)svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())dirName := "demo"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-external-env-symlink-update"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-external-env-symlink-update"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)updatedEnv := "FOO=updated\n"- updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})@@ -5271,12 +5270,12 @@ func TestProjectService_UpdateProject_RestoresExternalEnvSymlinkTargetWhenProjeceventService := event.NewEventService(db, nil, nil)svc := NewProjectService(db, settingsService, eventService, nil, nil, nil, nil, nil, config.Load())dirName := "demo"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-external-env-symlink-rollback"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-external-env-symlink-rollback"},Name: dirName,DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5287,8 +5286,8 @@ func TestProjectService_UpdateProject_RestoresExternalEnvSymlinkTargetWhenProjec}))updatedEnv := "FOO=updated\n"- _, err = svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, models.User{- BaseModel: models.BaseModel{ID: "u1"},+ _, err = svc.UpdateProject(ctx, project.ID, nil, nil, &updatedEnv, nil, common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.Error(t, err)@@ -5413,7 +5412,7 @@ func TestResolveRemoveOrphans(t *testing.T) {func TestProjectService_RecoverProjectRenameJournals_RollsBackUncommittedDirectoryRename(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -5424,12 +5423,12 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackUncommittedDirectorequire.NoError(t, os.MkdirAll(newPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(newPath, "compose.yaml"), []byte("services: {}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-recovery"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-recovery"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5457,7 +5456,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackUncommittedDirectorequire.NoError(t, err)require.False(t, ok)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -5467,7 +5466,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackUncommittedDirectofunc TestProjectService_RecoverProjectRenameJournals_StartedPhaseSkipsVolumeRollback(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -5478,12 +5477,12 @@ func TestProjectService_RecoverProjectRenameJournals_StartedPhaseSkipsVolumeRollrequire.NoError(t, os.MkdirAll(oldPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(oldPath, "compose.yaml"), []byte("services: {}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-started-volume-recovery"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-started-volume-recovery"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5518,7 +5517,7 @@ func TestProjectService_RecoverProjectRenameJournals_StartedPhaseSkipsVolumeRollrequire.NoError(t, err)require.False(t, ok)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -5528,7 +5527,7 @@ func TestProjectService_RecoverProjectRenameJournals_StartedPhaseSkipsVolumeRollfunc TestProjectService_RecoverProjectRenameJournals_RelocatesTargetWhenBothPathsExist(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -5541,12 +5540,12 @@ func TestProjectService_RecoverProjectRenameJournals_RelocatesTargetWhenBothPathrequire.NoError(t, os.MkdirAll(newPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(newPath, "compose.yaml"), []byte("services: {}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-both-paths"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-both-paths"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5579,7 +5578,7 @@ func TestProjectService_RecoverProjectRenameJournals_RelocatesTargetWhenBothPathrequire.Len(t, conflictPaths, 1)require.FileExists(t, filepath.Join(conflictPaths[0], "compose.yaml"))- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -5595,7 +5594,7 @@ func TestProjectService_RecoverProjectRenameJournals_RelocatesTargetWhenBothPathfunc TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDirectoryPathsMissing(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -5604,12 +5603,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDiroldPath := filepath.Join(projectsDir, oldDir)newPath := filepath.Join(projectsDir, newDir)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-missing-paths"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-missing-paths"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5640,7 +5639,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDirfunc TestProjectService_RecoverProjectRenameJournals_ClearsPreservedTargetJournalWhenPathExists(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -5650,12 +5649,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsPreservedTargetJournanewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(oldPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-preserved-target"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-preserved-target"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5721,7 +5720,7 @@ func TestProjectRenameJournalTargetsCopiedInternal(t *testing.T) {func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournal(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -5731,12 +5730,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournal(t *tnewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-committed"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-committed"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5766,17 +5765,17 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournal(t *tfunc TestProjectService_FinalizeProjectRenameAfterCommit_ClearsJournalAfterSourceCleanup(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()oldDir := "nginx"newDir := "web"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-old-volumes-removed"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-old-volumes-removed"},Name: "web",DirName: &newDir,Path: filepath.Join(t.TempDir(), newDir),- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5807,17 +5806,17 @@ func TestProjectService_FinalizeProjectRenameAfterCommit_ClearsJournalAfterSourcfunc TestProjectService_FinalizeProjectRenameAfterCommit_KeepsJournalWhenSourceCleanupFails(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()oldDir := "nginx"newDir := "web"- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-cleanup-failure"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-cleanup-failure"},Name: "web",DirName: &newDir,Path: filepath.Join(t.TempDir(), newDir),- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5854,7 +5853,7 @@ func TestProjectService_FinalizeProjectRenameAfterCommit_KeepsJournalWhenSourceCfunc TestProjectService_RecoverProjectRenameJournals_KeepsJournalWhenDirectoryRollbackFails(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var targetRemoved atomic.Bool@@ -5896,12 +5895,12 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsJournalWhenDirectoryRorequire.NoError(t, os.MkdirAll(newPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(newPath, "compose.yaml"), []byte("services: {}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-directory-rollback-fails"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-directory-rollback-fails"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -5940,7 +5939,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsJournalWhenDirectoryRorequire.FileExists(t, filepath.Join(newPath, "compose.yaml"), "failed directory rollback leaves the target path for retry")require.NoDirExists(t, oldPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -5959,7 +5958,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsJournalWhenDirectoryRofunc TestProjectService_RecoverProjectRenameJournals_CompletesCommittedVolumeJournalWithoutHelperImage(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var imageInspectCalled atomic.Bool@@ -5990,12 +5989,12 @@ func TestProjectService_RecoverProjectRenameJournals_CompletesCommittedVolumeJounewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-committed-with-volumes"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-committed-with-volumes"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6034,7 +6033,7 @@ func TestProjectService_RecoverProjectRenameJournals_CompletesCommittedVolumeJoufunc TestProjectService_RecoverProjectRenameJournals_RollsBackCommittedJournalWhenTargetMissingAndSourceExists(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var oldVolumeRemoved atomic.Bool@@ -6063,12 +6062,12 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackCommittedJournalWhnewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-missing-target-preserve-source"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-missing-target-preserve-source"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6106,7 +6105,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackCommittedJournalWhrequire.DirExists(t, oldPath)require.NoDirExists(t, newPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -6116,7 +6115,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackCommittedJournalWhfunc TestProjectService_RecoverProjectRenameJournals_ClearsJournalAfterDBRestoreWhenVolumeRollbackFails(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var targetRemoveAttempts atomic.Int32@@ -6173,12 +6172,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalAfterDBRestorerequire.NoError(t, os.MkdirAll(newPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(newPath, "compose.yaml"), []byte("services: {}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-rollback-volume-fail"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-rollback-volume-fail"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6225,7 +6224,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalAfterDBRestorerequire.FileExists(t, filepath.Join(oldPath, "compose.yaml"))require.NoDirExists(t, newPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -6243,7 +6242,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalAfterDBRestorefunc TestProjectService_RecoverProjectRenameJournals_KeepsRollbackCleanupWhenDockerUnavailable(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -6251,12 +6250,12 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsRollbackCleanupWhenDocoldPath := filepath.Join(projectsDir, oldDir)require.NoError(t, os.MkdirAll(oldPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-rollback-cleanup-docker-unavailable"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-rollback-cleanup-docker-unavailable"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6291,7 +6290,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsRollbackCleanupWhenDocfunc TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalWhenSourceAndTargetMissing(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -6313,12 +6312,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalWhenSnewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-missing-both-volumes"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-missing-both-volumes"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6355,7 +6354,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalWhenSrequire.DirExists(t, newPath)require.NoDirExists(t, oldPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "web", fromDB.Name)require.Equal(t, newPath, fromDB.Path)@@ -6363,7 +6362,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalWhenSfunc TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalAndCleansRemainingSourcesWhenSomeVolumesExternallyRemoved(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var cacheSourceRemoved atomic.Bool@@ -6399,12 +6398,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalAndClnewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-mixed-missing-volumes"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-mixed-missing-volumes"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6447,7 +6446,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalAndClrequire.DirExists(t, newPath)require.NoDirExists(t, oldPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "web", fromDB.Name)require.Equal(t, newPath, fromDB.Path)@@ -6455,7 +6454,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsCommittedJournalAndClfunc TestProjectService_RecoverProjectRenameJournals_MarksSourceCleanupPendingWhenCommittedCleanupFails(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var sourceRemoveAttempts atomic.Int32@@ -6482,12 +6481,12 @@ func TestProjectService_RecoverProjectRenameJournals_MarksSourceCleanupPendingWhnewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-source-cleanup-fail"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-source-cleanup-fail"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6532,7 +6531,7 @@ func TestProjectService_RecoverProjectRenameJournals_MarksSourceCleanupPendingWhrequire.DirExists(t, newPath)require.NoDirExists(t, oldPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "web", fromDB.Name)require.Equal(t, newPath, fromDB.Path)@@ -6540,7 +6539,7 @@ func TestProjectService_RecoverProjectRenameJournals_MarksSourceCleanupPendingWhfunc TestProjectService_RecoverProjectRenameJournals_ClearsSourceCleanupPendingJournalAfterCleanup(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var sourceRemoved atomic.Bool@@ -6567,12 +6566,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsSourceCleanupPendingJnewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-source-cleanup-pending-clear"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-source-cleanup-pending-clear"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6613,7 +6612,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsSourceCleanupPendingJfunc TestProjectService_RecoverProjectRenameJournals_RollsBackSourceCleanupPendingWhenTargetMissing(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var dataSourceRemoved atomic.Bool@@ -6666,12 +6665,12 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackSourceCleanupPendirequire.NoError(t, os.MkdirAll(newPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(newPath, "compose.yaml"), []byte("services: {}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-source-cleanup-target-missing"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-source-cleanup-target-missing"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6719,7 +6718,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackSourceCleanupPendirequire.FileExists(t, filepath.Join(oldPath, "compose.yaml"))require.NoDirExists(t, newPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -6729,7 +6728,7 @@ func TestProjectService_RecoverProjectRenameJournals_RollsBackSourceCleanupPendifunc TestProjectService_RecoverProjectRenameJournals_KeepsSourceCleanupPendingJournalWhenCleanupFails(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var sourceRemoveAttempts atomic.Int32@@ -6756,12 +6755,12 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsSourceCleanupPendingJonewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(newPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-source-cleanup-pending-fail"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-source-cleanup-pending-fail"},Name: "web",DirName: &newDir,Path: newPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6806,7 +6805,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsSourceCleanupPendingJorequire.DirExists(t, newPath)require.NoDirExists(t, oldPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "web", fromDB.Name)require.Equal(t, newPath, fromDB.Path)@@ -6814,7 +6813,7 @@ func TestProjectService_RecoverProjectRenameJournals_KeepsSourceCleanupPendingJofunc TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDirectoriesAreMissing(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()projectsDir := t.TempDir()@@ -6823,12 +6822,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDiroldPath := filepath.Join(projectsDir, oldDir)newPath := filepath.Join(projectsDir, newDir)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-missing-directories"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-missing-directories"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6859,7 +6858,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsStartedJournalWhenDirfunc TestProjectService_RecoverProjectRenameJournals_ClearsMissingPathJournalWhenTargetPreserved(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var targetRemoved atomic.Bool@@ -6892,12 +6891,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsMissingPathJournalWheoldPath := filepath.Join(projectsDir, oldDir)newPath := filepath.Join(projectsDir, newDir)- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-missing-path-preserved-target"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-missing-path-preserved-target"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -6934,7 +6933,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsMissingPathJournalWherequire.NoDirExists(t, oldPath)require.NoDirExists(t, newPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -6942,7 +6941,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsMissingPathJournalWhefunc TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackSourceInspectFails(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var targetRemoved atomic.Bool@@ -6966,12 +6965,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackSonewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(oldPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-source-inspect-preserve"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-source-inspect-preserve"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -7008,7 +7007,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackSorequire.DirExists(t, oldPath)require.NoDirExists(t, newPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -7016,7 +7015,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackSofunc TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackTargetInspectFails(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var targetRemoved atomic.Bool@@ -7045,12 +7044,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackTanewPath := filepath.Join(projectsDir, newDir)require.NoError(t, os.MkdirAll(oldPath, 0o755))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-target-inspect-preserve"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-target-inspect-preserve"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)@@ -7087,7 +7086,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackTarequire.DirExists(t, oldPath)require.NoDirExists(t, newPath)- var fromDB models.Project+ var fromDB Projectrequire.NoError(t, db.First(&fromDB, "id = ?", project.ID).Error)require.Equal(t, "nginx", fromDB.Name)require.Equal(t, oldPath, fromDB.Path)@@ -7095,7 +7094,7 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenRollbackTafunc TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenTargetPreservedAndDirectoryRolledBack(t *testing.T) {db := setupProjectTestDB(t)- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))ctx := context.Background()var targetRemoved atomic.Bool@@ -7130,12 +7129,12 @@ func TestProjectService_RecoverProjectRenameJournals_ClearsJournalWhenTargetPresrequire.NoError(t, os.MkdirAll(newPath, 0o755))require.NoError(t, os.WriteFile(filepath.Join(newPath, "compose.yaml"), []byte("services: {}\n"), 0o600))- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-rename-preserved-target-retry"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-rename-preserved-target-retry"},Name: "nginx",DirName: &oldDir,Path: oldPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)diff --git a/backend/internal/project/service_unix_test.go b/backend/internal/project/service_unix_test.goindex 0eba5c0ed..47f9e476f 100644--- a/backend/internal/project/service_unix_test.go+++ b/backend/internal/project/service_unix_test.go@@ -3,6 +3,10 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""os""path/filepath"@@ -10,7 +14,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -46,17 +49,17 @@ func TestProjectService_ApplyGitSyncProjectFiles_TolerantOfPermissionLockedEnv(trequire.NoError(t, os.Chmod(envPath, 0o000))t.Cleanup(func() { _ = os.Chmod(envPath, 0o644) })- project := &models.Project{- BaseModel: models.BaseModel{ID: "proj-git-sync-locked-env"},+ project := &Project{+ BaseModel: database.BaseModel{ID: "proj-git-sync-locked-env"},Name: "git-sync-locked-env",DirName: &dirName,Path: projectPath,- Status: models.ProjectStatusStopped,+ Status: ProjectStatusStopped,}require.NoError(t, db.Create(project).Error)- updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:1.27-alpine\n", new("FOO=fromgit\n"), nil, "", models.User{- BaseModel: models.BaseModel{ID: "u1"},+ updated, err := svc.ApplyGitSyncProjectFiles(ctx, project.ID, "services:\n app:\n image: nginx:1.27-alpine\n", new("FOO=fromgit\n"), nil, "", common.User{+ BaseModel: database.BaseModel{ID: "u1"},Username: "tester",})require.NoError(t, err)diff --git a/backend/internal/project/workspace.go b/backend/internal/project/workspace.goindex 97e4cbb0a..871014b03 100644--- a/backend/internal/project/workspace.go+++ b/backend/internal/project/workspace.go@@ -1,6 +1,10 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""io""net/http"@@ -11,7 +15,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"acfsutils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/acfs"@@ -110,7 +113,7 @@ func (s *ProjectService) DownloadProjectWorkspaceFile(ctx context.Context, projereturn file, size, filepath.Base(rel), nil}-func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID string, manifest projecttypes.WorkspaceUpdateManifest, uploads map[int][]byte, user models.User) (*workspacetypes.Workspace, error) {+func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID string, manifest projecttypes.WorkspaceUpdateManifest, uploads map[int][]byte, user common.User) (*workspacetypes.Workspace, error) {if err := workspacepkg.ValidateUpdateManifest(manifest.FileTreeRevision, len(manifest.FileChanges), 500); err != nil {return nil, common.Classify(common.ErrProjectWorkspaceBadRequest, err)}@@ -147,14 +150,14 @@ func (s *ProjectService) UpdateProjectWorkspace(ctx context.Context, projectID sif err := s.updateProjectStatusandCountsInternal(ctx, proj.ID, proj.Status); err != nil {return nil, errors.WrapIf(err, "refresh project after workspace update")}- s.logProjectEventInternal(ctx, models.EventTypeProjectUpdate, proj.ID, proj.Name, user, models.JSON{+ s.logProjectEventInternal(ctx, event.EventTypeProjectUpdate, proj.ID, proj.Name, user, database.JSON{"action": "update_project_workspace","fileChangeCount": len(manifest.FileChanges),}, "could not log project workspace update")return s.GetProjectWorkspace(ctx, projectID)}-func (s *ProjectService) resolveProjectWorkspacePathInternal(ctx context.Context, projectID, relativePath string) (*models.Project, string, string, acfstypes.Entry, error) {+func (s *ProjectService) resolveProjectWorkspacePathInternal(ctx context.Context, projectID, relativePath string) (*Project, string, string, acfstypes.Entry, error) {proj, err := s.GetProjectFromDatabaseByID(ctx, projectID)if err != nil {return nil, "", "", acfstypes.Entry{}, err@@ -200,7 +203,7 @@ func classifyProjectWorkspaceACFSErrorInternal(err error, operation string) erro}}-func (s *ProjectService) projectWorkspaceApplyOptionsInternal(ctx context.Context, proj *models.Project, expectedRevision string) projects.ProjectWorkspaceApplyOptions {+func (s *ProjectService) projectWorkspaceApplyOptionsInternal(ctx context.Context, proj *Project, expectedRevision string) projects.ProjectWorkspaceApplyOptions {composeFileName := projects.DefaultComposeFileNameif composeFile, err := s.ResolveProjectComposeFile(ctx, proj); err == nil {composeFileName = filepath.Base(composeFile)@@ -243,7 +246,7 @@ func (s *ProjectService) prepareProjectWorkspaceBackupInternal(ctx context.Contereturn backup, func() { _ = acfs.RemoveAll(ctx, projectsDirectory, backupLogical) }, nil}-func isGitOpsManagedProjectInternal(proj *models.Project) bool {+func isGitOpsManagedProjectInternal(proj *Project) bool {return proj != nil && proj.GitOpsManagedBy != nil && strings.TrimSpace(*proj.GitOpsManagedBy) != ""}diff --git a/backend/internal/project/workspace_handler.go b/backend/internal/project/workspace_handler.goindex 8166f143f..e8fa28f30 100644--- a/backend/internal/project/workspace_handler.go+++ b/backend/internal/project/workspace_handler.go@@ -1,6 +1,8 @@package projectimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""io""mime/multipart"@@ -8,10 +10,11 @@ import ("strconv""strings"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -130,9 +133,9 @@ func (h *ProjectHandler) UpdateProjectWorkspace(ctx context.Context, input *Updavar result *workspacetypes.WorkspaceruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{- EnvironmentID: input.EnvironmentID, Type: models.ActivityTypeResourceAction, ResourceType: "project", ResourceID: input.ProjectID, ResourceName: input.ProjectID, User: user,+ EnvironmentID: input.EnvironmentID, Type: activitytypes.TypeResourceAction, ResourceType: "project", ResourceID: input.ProjectID, ResourceName: input.ProjectID, User: user,Step: "Updating project workspace", Message: "Updating project workspace", SuccessMessage: "Project workspace updated successfully",- Metadata: models.JSON{"action": "update_project_workspace", "fileChangeCount": len(manifest.FileChanges)},+ Metadata: database.JSON{"action": "update_project_workspace", "fileChangeCount": len(manifest.FileChanges)},}, func(runtimeCtx context.Context) error {var updateErr errorresult, updateErr = h.projectService.UpdateProjectWorkspace(runtimeCtx, input.ProjectID, manifest, uploads, *user)diff --git a/backend/internal/registry/ecr_token.go b/backend/internal/registry/ecr_token.goindex a2c905119..795e6493c 100644--- a/backend/internal/registry/ecr_token.go+++ b/backend/internal/registry/ecr_token.go@@ -11,7 +11,6 @@ import ("github.com/aws/aws-sdk-go-v2/config""github.com/aws/aws-sdk-go-v2/credentials""github.com/aws/aws-sdk-go-v2/service/ecr"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""go.getarcane.app/sys/crypto")@@ -27,7 +26,7 @@ type ecrTokenResult struct {// validity window it is returned directly; otherwise a new token is obtained from the AWS// ECR API, persisted back to the DB, and returned.// Concurrent refreshes for the same registry are deduplicated via singleflight.-func (s *ContainerRegistryService) GetOrRefreshECRToken(ctx context.Context, reg *models.ContainerRegistry) (username, password string, err error) {+func (s *ContainerRegistryService) GetOrRefreshECRToken(ctx context.Context, reg *ContainerRegistry) (username, password string, err error) {// Fast path: return cached token if still valid.if reg.ECRTokenGeneratedAt != nil && time.Since(reg.ECRTokenGeneratedAt.UTC()) < ecrTokenTTL {if reg.ECRToken != "" {@@ -55,7 +54,7 @@ func (s *ContainerRegistryService) GetOrRefreshECRToken(ctx context.Context, regreturn r.username, r.password, nil}-func (s *ContainerRegistryService) refreshECRTokenInternal(ctx context.Context, reg *models.ContainerRegistry) (*ecrTokenResult, error) {+func (s *ContainerRegistryService) refreshECRTokenInternal(ctx context.Context, reg *ContainerRegistry) (*ecrTokenResult, error) {// Decrypt the stored AWS secret access key.secretKey, decErr := crypto.Decrypt(reg.AWSSecretAccessKey)if decErr != nil {diff --git a/backend/internal/registry/handler.go b/backend/internal/registry/handler.goindex 3abbcd233..3c8aec6d5 100644--- a/backend/internal/registry/handler.go+++ b/backend/internal/registry/handler.go@@ -1,6 +1,8 @@package registryimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""log/slog""strings"@@ -8,7 +10,6 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"@@ -40,7 +41,7 @@ type ListContainerRegistriesOutput struct {}type CreateContainerRegistryInput struct {- Body models.CreateContainerRegistryRequest+ Body CreateContainerRegistryRequest}type CreateContainerRegistryOutput struct {@@ -57,7 +58,7 @@ type GetContainerRegistryOutput struct {type UpdateContainerRegistryInput struct {ID string `path:"id" doc:"Registry ID"`- Body models.UpdateContainerRegistryRequest+ Body UpdateContainerRegistryRequest}type UpdateContainerRegistryOutput struct {@@ -232,13 +233,13 @@ func (h *ContainerRegistryHandler) GetPullUsage(ctx context.Context, input *strufunc (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *CreateContainerRegistryInput) (*CreateContainerRegistryOutput, error) {reg, err := h.registryService.CreateRegistry(ctx, input.Body)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to create registry").Error())}h.triggerRemoteRegistrySync(ctx, "registry creation")- out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)+ out, mapErr := mapper.MapOne[*ContainerRegistry, containerregistry.ContainerRegistry](reg)if mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}@@ -255,11 +256,11 @@ func (h *ContainerRegistryHandler) CreateRegistry(ctx context.Context, input *Crfunc (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetContainerRegistryInput) (*GetContainerRegistryOutput, error) {reg, err := h.registryService.GetRegistryByID(ctx, input.ID)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to retrieve registry").Error())}- out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)+ out, mapErr := mapper.MapOne[*ContainerRegistry, containerregistry.ContainerRegistry](reg)if mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}@@ -276,13 +277,13 @@ func (h *ContainerRegistryHandler) GetRegistry(ctx context.Context, input *GetCofunc (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *UpdateContainerRegistryInput) (*UpdateContainerRegistryOutput, error) {reg, err := h.registryService.UpdateRegistry(ctx, input.ID, input.Body)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to update registry").Error())}h.triggerRemoteRegistrySync(ctx, "registry update")- out, mapErr := mapper.MapOne[*models.ContainerRegistry, containerregistry.ContainerRegistry](reg)+ out, mapErr := mapper.MapOne[*ContainerRegistry, containerregistry.ContainerRegistry](reg)if mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map registry").Error())}@@ -298,7 +299,7 @@ func (h *ContainerRegistryHandler) UpdateRegistry(ctx context.Context, input *Up// DeleteRegistry deletes a container registry.func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *DeleteContainerRegistryInput) (*DeleteContainerRegistryOutput, error) {if err := h.registryService.DeleteRegistry(ctx, input.ID); err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to delete registry").Error())}@@ -318,7 +319,7 @@ func (h *ContainerRegistryHandler) DeleteRegistry(ctx context.Context, input *Defunc (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *TestContainerRegistryInput) (*TestContainerRegistryOutput, error) {reg, err := h.registryService.GetRegistryByID(ctx, input.ID)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to retrieve registry").Error())}@@ -364,7 +365,7 @@ func (h *ContainerRegistryHandler) TestRegistry(ctx context.Context, input *Test// SyncRegistries syncs container registries from a remote source.func (h *ContainerRegistryHandler) SyncRegistries(ctx context.Context, input *SyncContainerRegistriesInput) (*SyncContainerRegistriesOutput, error) {if err := h.registryService.SyncRegistries(ctx, input.Body.Registries); err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)return nil, huma.NewError(apiErr.HTTPStatus(), errors.WithMessage(err, "Failed to sync registries").Error())}diff --git a/backend/internal/models/container_registry.go b/backend/internal/registry/model.gosimilarity index 52%rename from backend/internal/models/container_registry.gorename to backend/internal/registry/model.goindex 0600d0eed..1c1fa2a09 100644--- a/backend/internal/models/container_registry.go+++ b/backend/internal/registry/model.go@@ -1,27 +1,29 @@-package models+package registryimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"time")type ContainerRegistry struct {- BaseModel+ database.BaseModel- URL string `json:"url" sortable:"true"`- Username string `json:"username" sortable:"true"`- Token string `json:"token"`- Description *string `json:"description,omitempty" sortable:"true"`- Insecure bool `json:"insecure" sortable:"true"`- Enabled bool `json:"enabled" sortable:"true"`- RegistryType string `json:"registryType" sortable:"true"`- RepositoryNames StringSlice `json:"repositoryNames" gorm:"column:repository_names;type:text;not null;default:'[]'"`- AWSAccessKeyID string `json:"awsAccessKeyId"`- AWSSecretAccessKey string `json:"awsSecretAccessKey"`- AWSRegion string `json:"awsRegion"`- ECRToken string `json:"ecrToken"`- ECRTokenGeneratedAt *time.Time `json:"ecrTokenGeneratedAt"`- CreatedAt time.Time `json:"createdAt" sortable:"true"`- UpdatedAt time.Time `json:"updatedAt" sortable:"true"`+ URL string `json:"url" sortable:"true"`+ Username string `json:"username" sortable:"true"`+ Token string `json:"token"`+ Description *string `json:"description,omitempty" sortable:"true"`+ Insecure bool `json:"insecure" sortable:"true"`+ Enabled bool `json:"enabled" sortable:"true"`+ RegistryType string `json:"registryType" sortable:"true"`+ RepositoryNames database.StringSlice `json:"repositoryNames" gorm:"column:repository_names;type:text;not null;default:'[]'"`+ AWSAccessKeyID string `json:"awsAccessKeyId"`+ AWSSecretAccessKey string `json:"awsSecretAccessKey"`+ AWSRegion string `json:"awsRegion"`+ ECRToken string `json:"ecrToken"`+ ECRTokenGeneratedAt *time.Time `json:"ecrTokenGeneratedAt"`+ CreatedAt time.Time `json:"createdAt" sortable:"true"`+ UpdatedAt time.Time `json:"updatedAt" sortable:"true"`}func (ContainerRegistry) TableName() string {diff --git a/backend/internal/registry/service.go b/backend/internal/registry/service.goindex cc0e182af..19155cc7d 100644--- a/backend/internal/registry/service.go+++ b/backend/internal/registry/service.go@@ -20,7 +20,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"utilsregistry "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/registryauth""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -140,8 +139,8 @@ func NewContainerRegistryService(db *database.DB, dockerClient registryDaemonGetreturn service}-func (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]models.ContainerRegistry, error) {- var registries []models.ContainerRegistry+func (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]ContainerRegistry, error) {+ var registries []ContainerRegistryif err := s.db.WithContext(ctx).Find(®istries).Error; err != nil {return nil, errors.WrapIf(err, "failed to get container registries")}@@ -149,15 +148,15 @@ func (s *ContainerRegistryService) GetAllRegistries(ctx context.Context) ([]mode}func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, params pagination.QueryParams) ([]containerregistry.ContainerRegistry, pagination.Response, error) {- var registries []models.ContainerRegistry- q := s.db.WithContext(ctx).Model(&models.ContainerRegistry{})+ var registries []ContainerRegistry+ q := s.db.WithContext(ctx).Model(&ContainerRegistry{})q = pagination.ApplyLikeSearch(q, params.Search, "url LIKE ? OR username LIKE ? OR COALESCE(description, '') LIKE ?")q = pagination.ApplyBooleanFilter(q, "enabled", params.Filters["enabled"])q = pagination.ApplyBooleanFilter(q, "insecure", params.Filters["insecure"])- out, paginationResp, err := pagination.PaginateSortAndMapDB[models.ContainerRegistry, containerregistry.ContainerRegistry](params, q, ®istries)+ out, paginationResp, err := pagination.PaginateSortAndMapDB[ContainerRegistry, containerregistry.ContainerRegistry](params, q, ®istries)if err != nil {return nil, pagination.Response{}, errors.WrapIf(err, "failed to list container registries")}@@ -165,15 +164,15 @@ func (s *ContainerRegistryService) GetRegistriesPaginated(ctx context.Context, preturn out, paginationResp, nil}-func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id string) (*models.ContainerRegistry, error) {- var registryRecord models.ContainerRegistry+func (s *ContainerRegistryService) GetRegistryByID(ctx context.Context, id string) (*ContainerRegistry, error) {+ var registryRecord ContainerRegistryif err := s.db.WithContext(ctx).Where("id = ?", id).First(®istryRecord).Error; err != nil {return nil, errors.WrapIf(err, "failed to get container registry")}return ®istryRecord, nil}-func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req models.CreateContainerRegistryRequest) (*models.ContainerRegistry, error) {+func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req CreateContainerRegistryRequest) (*ContainerRegistry, error) {registryType, err := NormalizeRegistryType(req.RegistryType)if err != nil {return nil, err@@ -183,7 +182,7 @@ func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req modelreturn nil, err}- registryRecord := &models.ContainerRegistry{+ registryRecord := &ContainerRegistry{URL: req.URL,Description: req.Description,Insecure: req.Insecure != nil && *req.Insecure,@@ -233,7 +232,7 @@ func (s *ContainerRegistryService) CreateRegistry(ctx context.Context, req modelreturn registryRecord, nil}-func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string, req models.UpdateContainerRegistryRequest) (*models.ContainerRegistry, error) {+func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id string, req UpdateContainerRegistryRequest) (*ContainerRegistry, error) {registryRecord, err := s.GetRegistryByID(ctx, id)if err != nil {return nil, err@@ -298,7 +297,7 @@ func (s *ContainerRegistryService) UpdateRegistry(ctx context.Context, id stringreturn registryRecord, nil}-func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *models.ContainerRegistry, registryType *string) error {+func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *ContainerRegistry, registryType *string) error {if registryType == nil {return nil}@@ -315,7 +314,7 @@ func (s *ContainerRegistryService) applyRegistryTypeUpdateInternal(registry *modreturn nil}-func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *models.ContainerRegistry, req models.UpdateContainerRegistryRequest) error {+func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *ContainerRegistry, req UpdateContainerRegistryRequest) error {utils.ApplyChanged(®istry.AWSAccessKeyID, mo.PointerToOption(req.AWSAccessKeyID))utils.ApplyChanged(®istry.AWSRegion, mo.PointerToOption(req.AWSRegion))@@ -345,7 +344,7 @@ func (s *ContainerRegistryService) updateECRRegistryFieldsInternal(registry *modreturn nil}-func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registry *models.ContainerRegistry, req models.UpdateContainerRegistryRequest) error {+func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registry *ContainerRegistry, req UpdateContainerRegistryRequest) error {utils.ApplyChanged(®istry.Username, mo.PointerToOption(req.Username))if req.Token != nil && *req.Token != "" {@@ -364,7 +363,7 @@ func (s *ContainerRegistryService) updateGenericRegistryFieldsInternal(registry}func (s *ContainerRegistryService) DeleteRegistry(ctx context.Context, id string) error {- if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.ContainerRegistry{}).Error; err != nil {+ if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&ContainerRegistry{}).Error; err != nil {return errors.WrapIf(err, "failed to delete container registry")}return nil@@ -386,8 +385,8 @@ func (s *ContainerRegistryService) GetDecryptedToken(ctx context.Context, id str}// GetEnabledRegistries returns all enabled registries-func (s *ContainerRegistryService) GetEnabledRegistries(ctx context.Context) ([]models.ContainerRegistry, error) {- var registries []models.ContainerRegistry+func (s *ContainerRegistryService) GetEnabledRegistries(ctx context.Context) ([]ContainerRegistry, error) {+ var registries []ContainerRegistryif err := s.db.WithContext(ctx).Where("enabled = ?", true).Find(®istries).Error; err != nil {return nil, errors.WrapIf(err, "failed to get enabled container registries")}@@ -544,7 +543,7 @@ func (s *ContainerRegistryService) GetRegistryPullUsage(ctx context.Context) (coreturn containerregistry.PullUsageResponse{Registries: results}, nil}-func (s *ContainerRegistryService) buildRegistryPullUsageInternal(ctx context.Context, reg models.ContainerRegistry) containerregistry.PullUsage {+func (s *ContainerRegistryService) buildRegistryPullUsageInternal(ctx context.Context, reg ContainerRegistry) containerregistry.PullUsage {registryHost := utilsregistry.NormalizeRegistryForComparison(reg.URL)usage := containerregistry.PullUsage{RegistryID: reg.ID,@@ -619,7 +618,7 @@ func (s *ContainerRegistryService) getObservedPullsInternal(ctx context.Context,return value}-func (s *ContainerRegistryService) dockerHubCredentialForRegistryInternal(reg models.ContainerRegistry) (*registry.Credentials, string, string, error) {+func (s *ContainerRegistryService) dockerHubCredentialForRegistryInternal(reg ContainerRegistry) (*registry.Credentials, string, string, error) {if reg.RegistryType != RegistryTypeGeneric {return nil, "anonymous", "", nil}@@ -789,7 +788,7 @@ func (s *ContainerRegistryService) TestRegistry(ctx context.Context, registryURL// TestECRRegistry tests connectivity for an ECR registry by generating an auth token// and attempting a Docker login.-func (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *models.ContainerRegistry) error {+func (s *ContainerRegistryService) TestECRRegistry(ctx context.Context, reg *ContainerRegistry) error {ecrUser, ecrPass, err := s.GetOrRefreshECRToken(ctx, reg)if err != nil {return errors.WrapIf(err, "failed to obtain ECR token")@@ -1161,13 +1160,13 @@ func (s *ContainerRegistryService) SyncRegistries(ctx context.Context, syncItemsreturn s.deleteUnsyncedInternal(ctx, existingMap, syncedIDs)}-func (s *ContainerRegistryService) getExistingRegistriesMapInternal(ctx context.Context) (map[string]*models.ContainerRegistry, error) {- var existingRegistries []models.ContainerRegistry+func (s *ContainerRegistryService) getExistingRegistriesMapInternal(ctx context.Context) (map[string]*ContainerRegistry, error) {+ var existingRegistries []ContainerRegistryif err := s.db.WithContext(ctx).Find(&existingRegistries).Error; err != nil {return nil, errors.WrapIf(err, "failed to get existing registries")}- existingMap := make(map[string]*models.ContainerRegistry)+ existingMap := make(map[string]*ContainerRegistry)for i := range existingRegistries {existingMap[existingRegistries[i].ID] = &existingRegistries[i]}@@ -1175,7 +1174,7 @@ func (s *ContainerRegistryService) getExistingRegistriesMapInternal(ctx context.return existingMap, nil}-func (s *ContainerRegistryService) processSyncItemInternal(ctx context.Context, item containerregistry.Sync, existingMap map[string]*models.ContainerRegistry) error {+func (s *ContainerRegistryService) processSyncItemInternal(ctx context.Context, item containerregistry.Sync, existingMap map[string]*ContainerRegistry) error {existing, exists := existingMap[item.ID]if exists {return s.updateExistingRegistryInternal(ctx, item, existing)@@ -1183,7 +1182,7 @@ func (s *ContainerRegistryService) processSyncItemInternal(ctx context.Context,return s.createNewRegistryInternal(ctx, item)}-func (s *ContainerRegistryService) updateExistingRegistryInternal(ctx context.Context, item containerregistry.Sync, existing *models.ContainerRegistry) error {+func (s *ContainerRegistryService) updateExistingRegistryInternal(ctx context.Context, item containerregistry.Sync, existing *ContainerRegistry) error {needsUpdate, err := s.checkRegistryNeedsUpdateInternal(item, existing)if err != nil {return err@@ -1199,7 +1198,7 @@ func (s *ContainerRegistryService) updateExistingRegistryInternal(ctx context.Coreturn nil}-func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item containerregistry.Sync, existing *models.ContainerRegistry) (bool, error) {+func (s *ContainerRegistryService) checkRegistryNeedsUpdateInternal(item containerregistry.Sync, existing *ContainerRegistry) (bool, error) {newType, err := NormalizeRegistryType(item.RegistryType)if err != nil {return false, err@@ -1281,8 +1280,8 @@ func (s *ContainerRegistryService) createNewRegistryInternal(ctx context.Contextreturn err}- newRegistry := &models.ContainerRegistry{- BaseModel: models.BaseModel{+ newRegistry := &ContainerRegistry{+ BaseModel: database.BaseModel{ID: item.ID,},URL: item.URL,@@ -1337,9 +1336,9 @@ func NormalizeRegistryType(value string) (string, error) {// normalizeRepositoryNamesInternal trims, filters and deduplicates the given// entries (preserving first-occurrence order) and validates what remains. It// returns a non-nil slice so that GORM always serializes to a JSON array.-func normalizeRepositoryNamesInternal(raw []string) (models.StringSlice, error) {+func normalizeRepositoryNamesInternal(raw []string) (database.StringSlice, error) {names := utils.UniqueNonEmptyStrings(raw)- result := make(models.StringSlice, 0, len(names))+ result := make(database.StringSlice, 0, len(names))for _, name := range names {// A repository name is only a path, so pair it with placeholder domain// and tag segments to validate it against the reference grammar.@@ -1352,10 +1351,10 @@ func normalizeRepositoryNamesInternal(raw []string) (models.StringSlice, error)return result, nil}-func (s *ContainerRegistryService) deleteUnsyncedInternal(ctx context.Context, existingMap map[string]*models.ContainerRegistry, syncedIDs map[string]bool) error {+func (s *ContainerRegistryService) deleteUnsyncedInternal(ctx context.Context, existingMap map[string]*ContainerRegistry, syncedIDs map[string]bool) error {for id := range existingMap {if !syncedIDs[id] {- if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&models.ContainerRegistry{}).Error; err != nil {+ if err := s.db.WithContext(ctx).Where("id = ?", id).Delete(&ContainerRegistry{}).Error; err != nil {return errors.WrapIff(err, "failed to delete registry %s", id)}}diff --git a/backend/internal/registry/service_test.go b/backend/internal/registry/service_test.goindex 0205aed2b..bc595cc4f 100644--- a/backend/internal/registry/service_test.go+++ b/backend/internal/registry/service_test.go@@ -14,7 +14,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/types/v2/containerregistry""github.com/libtnb/sqlite"dockerauthconfig "github.com/moby/moby/api/pkg/authconfig"@@ -38,7 +37,8 @@ func setupContainerRegistryTestDBInternal(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ContainerRegistry{}, &models.KVEntry{}, &models.Project{}))+ require.NoError(t, db.AutoMigrate(&ContainerRegistry{}, &kv.KVEntry{}))+ require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS projects (id text PRIMARY KEY, name text, path text)").Error)crypto.InitEncryption(&crypto.Config{Environment: "test",@@ -54,7 +54,7 @@ func createTestPullRegistryInternal(t *testing.T, db *database.DB, url, usernameencryptedToken, err := crypto.Encrypt(token)require.NoError(t, err)- record := &models.ContainerRegistry{+ record := &ContainerRegistry{URL: url,Username: username,Token: encryptedToken,@@ -218,7 +218,7 @@ func TestContainerRegistryService_NilService_RegistryAuthMethodsReturnEmpty(t *tfunc TestContainerRegistryService_GetRegistryPullUsage_AnonymousDockerHubLimit(t *testing.T) {db := setupContainerRegistryTestDBInternal(t)- require.NoError(t, db.WithContext(context.Background()).Create(&models.ContainerRegistry{+ require.NoError(t, db.WithContext(context.Background()).Create(&ContainerRegistry{URL: "docker.io",Enabled: true,RegistryType: RegistryTypeGeneric,@@ -347,7 +347,7 @@ func TestContainerRegistryService_GetRegistryPullUsage_CredentialErrorIsNonFatalfunc TestContainerRegistryService_RecordImagePull_IncrementsObservedRegistryCount(t *testing.T) {db := setupContainerRegistryTestDBInternal(t)- require.NoError(t, db.WithContext(context.Background()).Create(&models.ContainerRegistry{+ require.NoError(t, db.WithContext(context.Background()).Create(&ContainerRegistry{URL: "ghcr.io",Enabled: true,RegistryType: RegistryTypeGeneric,@@ -369,7 +369,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsUnsupportedRegistryType(db := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- _, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "registry.example.com",RegistryType: "ECR-ish",})@@ -383,7 +383,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyUsernameForGeneric(db := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- _, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "",Token: "my-token",@@ -398,7 +398,7 @@ func TestContainerRegistryService_CreateRegistry_RejectsEmptyTokenForGeneric(t *db := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- _, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "",@@ -413,7 +413,7 @@ func TestContainerRegistryService_CreateRegistry_AcceptsValidGenericCredentials(db := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- reg, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",@@ -427,14 +427,14 @@ func TestContainerRegistryService_UpdateRegistry_RejectsBlankingUsername(t *testdb := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- reg, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",})require.NoError(t, err)- _, err = svc.UpdateRegistry(context.Background(), reg.ID, models.UpdateContainerRegistryRequest{+ _, err = svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{Username: new(""),})require.Error(t, err)@@ -447,7 +447,7 @@ func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProviddb := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- reg, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",@@ -455,7 +455,7 @@ func TestContainerRegistryService_UpdateRegistry_KeepsExistingTokenWhenNotProvidrequire.NoError(t, err)originalToken := reg.Token- updated, err := svc.UpdateRegistry(context.Background(), reg.ID, models.UpdateContainerRegistryRequest{+ updated, err := svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{Username: new("updated-user"),})require.NoError(t, err)@@ -477,7 +477,7 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTodb := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- registry, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",@@ -485,7 +485,7 @@ func TestContainerRegistryService_UpdateRegistry_RejectsTargetChangeWhenStoredTorequire.NoError(t, err)originalToken := registry.Token- _, err = svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{+ _, err = svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{URL: new("https://attacker.example.com"),Token: tt.token,})@@ -506,7 +506,7 @@ func TestContainerRegistryService_UpdateRegistry_AllowsPathChangeOnSameHostWithodb := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- registry, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com/one",Username: "my-user",Token: "my-token",@@ -514,7 +514,7 @@ func TestContainerRegistryService_UpdateRegistry_AllowsPathChangeOnSameHostWithorequire.NoError(t, err)originalToken := registry.Token- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{URL: new("REGISTRY.EXAMPLE.COM/two"),})require.NoError(t, err)@@ -526,14 +526,14 @@ func TestContainerRegistryService_UpdateRegistry_AllowsTargetChangeWhenTokenIsRedb := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- registry, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",})require.NoError(t, err)- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{URL: new("https://registry.example.net"),Token: new("new-token"),})@@ -549,7 +549,7 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStoreddb := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- registry, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "123456789012.dkr.ecr.us-east-1.amazonaws.com",RegistryType: RegistryTypeECR,AWSAccessKeyID: "old-access-key",@@ -559,14 +559,14 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStoredrequire.NoError(t, err)originalSecret := registry.AWSSecretAccessKey- _, err = svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{+ _, err = svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),})require.Error(t, err)- var apiErr *models.APIError+ var apiErr *common.APIErrorrequire.ErrorAs(t, err, &apiErr)- require.Equal(t, models.APIErrorCodeValidationError, apiErr.Code)+ require.Equal(t, common.APIErrorCodeValidationError, apiErr.Code)require.ElementsMatch(t, []string{"awsAccessKeyId", "awsSecretAccessKey"}, apiErr.Details.(map[string]any)["fields"])stored, loadErr := svc.GetRegistryByID(context.Background(), registry.ID)@@ -574,7 +574,7 @@ func TestContainerRegistryService_UpdateRegistryRejectsECRTargetChangeWithStoredrequire.Equal(t, "123456789012.dkr.ecr.us-east-1.amazonaws.com", stored.URL)require.Equal(t, originalSecret, stored.AWSSecretAccessKey)- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{URL: new("999999999999.dkr.ecr.us-east-1.amazonaws.com"),AWSAccessKeyID: new("new-access-key"),AWSSecretAccessKey: new("new-secret-key"),@@ -591,14 +591,14 @@ func TestContainerRegistryService_UpdateRegistry_RejectsChangingRegistryType(t *db := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- reg, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",})require.NoError(t, err)- _, err = svc.UpdateRegistry(context.Background(), reg.ID, models.UpdateContainerRegistryRequest{+ _, err = svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{RegistryType: new("ecr"),})require.Error(t, err)@@ -611,14 +611,14 @@ func TestContainerRegistryService_UpdateRegistry_AllowsSameRegistryType(t *testidb := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- reg, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ reg, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",})require.NoError(t, err)- updated, err := svc.UpdateRegistry(context.Background(), reg.ID, models.UpdateContainerRegistryRequest{+ updated, err := svc.UpdateRegistry(context.Background(), reg.ID, UpdateContainerRegistryRequest{RegistryType: new("generic"),Username: new("updated-user"),})@@ -631,7 +631,7 @@ func TestContainerRegistryService_SyncRegistries_ClearsGenericTokenWhenManagerSedb := setupContainerRegistryTestDBInternal(t)createTestPullRegistryInternal(t, db, "https://registry.example.com", "registry-user", "old-token")- var existing models.ContainerRegistry+ var existing ContainerRegistryrequire.NoError(t, db.WithContext(context.Background()).First(&existing).Error)svc := NewContainerRegistryService(db, nil, nil)@@ -649,7 +649,7 @@ func TestContainerRegistryService_SyncRegistries_ClearsGenericTokenWhenManagerSe})require.NoError(t, err)- var updated models.ContainerRegistry+ var updated ContainerRegistryrequire.NoError(t, db.WithContext(context.Background()).First(&updated, "id = ?", existing.ID).Error)decryptedToken, err := crypto.Decrypt(updated.Token)@@ -1089,10 +1089,10 @@ func TestContainerRegistryService_InspectImageDigest_PreservesAnonymousUnauthoriassert.Contains(t, err.Error(), "failed to load enabled registries")}-func createRegistryWithRepositoryNames(t *testing.T, svc *ContainerRegistryService, repositoryNames ...string) *models.ContainerRegistry {+func createRegistryWithRepositoryNames(t *testing.T, svc *ContainerRegistryService, repositoryNames ...string) *ContainerRegistry {t.Helper()- registry, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ registry, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",Username: "my-user",Token: "my-token",@@ -1103,10 +1103,10 @@ func createRegistryWithRepositoryNames(t *testing.T, svc *ContainerRegistryServireturn registry}-func fetchRegistry(t *testing.T, db *database.DB, id string) models.ContainerRegistry {+func fetchRegistry(t *testing.T, db *database.DB, id string) ContainerRegistry {t.Helper()- var fetched models.ContainerRegistry+ var fetched ContainerRegistryrequire.NoError(t, db.WithContext(context.Background()).First(&fetched, "id = ?", id).Error)return fetched@@ -1119,15 +1119,15 @@ func TestContainerRegistryService_CreateRegistry_NormalizesAndPersistsRepository// Entries are trimmed, empties dropped and duplicates removed while// preserving first-occurrence order.registry := createRegistryWithRepositoryNames(t, svc, " team ", "", "team", "team/platform", " team ")- assert.Equal(t, models.StringSlice{"team", "team/platform"}, registry.RepositoryNames)- assert.Equal(t, models.StringSlice{"team", "team/platform"}, fetchRegistry(t, db, registry.ID).RepositoryNames)+ assert.Equal(t, database.StringSlice{"team", "team/platform"}, registry.RepositoryNames)+ assert.Equal(t, database.StringSlice{"team", "team/platform"}, fetchRegistry(t, db, registry.ID).RepositoryNames)}func TestContainerRegistryService_CreateRegistry_RejectsInvalidRepositoryName(t *testing.T) {db := setupContainerRegistryTestDBInternal(t)svc := NewContainerRegistryService(db, nil, nil)- _, err := svc.CreateRegistry(context.Background(), models.CreateContainerRegistryRequest{+ _, err := svc.CreateRegistry(context.Background(), CreateContainerRegistryRequest{URL: "https://registry.example.com",RepositoryNames: []string{"team:latest"},})@@ -1142,14 +1142,14 @@ func TestContainerRegistryService_UpdateRegistry_RepositoryNamesPointerSemanticsregistry := createRegistryWithRepositoryNames(t, svc, "team", "team/platform")// A nil pointer leaves the existing names untouched.- updated, err := svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{+ updated, err := svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{Username: new("updated-user"),})require.NoError(t, err)- assert.Equal(t, models.StringSlice{"team", "team/platform"}, updated.RepositoryNames)+ assert.Equal(t, database.StringSlice{"team", "team/platform"}, updated.RepositoryNames)// An empty slice clears them.- updated, err = svc.UpdateRegistry(context.Background(), registry.ID, models.UpdateContainerRegistryRequest{+ updated, err = svc.UpdateRegistry(context.Background(), registry.ID, UpdateContainerRegistryRequest{RepositoryNames: &[]string{},})require.NoError(t, err)diff --git a/backend/internal/role/handler.go b/backend/internal/role/handler.goindex 5ee59f5dd..764da5002 100644--- a/backend/internal/role/handler.go+++ b/backend/internal/role/handler.go@@ -8,7 +8,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"@@ -307,9 +306,9 @@ func (h *RoleHandler) ListUserRoleAssignments(ctx context.Context, input *ListUs}func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUserRoleAssignmentsInput) (*SetUserRoleAssignmentsOutput, error) {- desired := make([]models.UserRoleAssignment, len(input.Body.Assignments))+ desired := make([]UserRoleAssignment, len(input.Body.Assignments))for i, a := range input.Body.Assignments {- desired[i] = models.UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID}+ desired[i] = UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID}}if err := h.roleService.SetUserAssignments(ctx, input.UserID, desired); err != nil {switch {@@ -337,7 +336,7 @@ func (h *RoleHandler) SetUserRoleAssignments(ctx context.Context, input *SetUser// ---------- DTO mappers -----------func (h *RoleHandler) toRoleDTO(ctx context.Context, r *models.Role) roletypes.Role {+func (h *RoleHandler) toRoleDTO(ctx context.Context, r *Role) roletypes.Role {out := roletypes.Role{ID: r.ID,Name: r.Name,@@ -353,7 +352,7 @@ func (h *RoleHandler) toRoleDTO(ctx context.Context, r *models.Role) roletypes.Rreturn out}-func toAssignmentDTOInternal(r *models.UserRoleAssignment) roletypes.RoleAssignment {+func toAssignmentDTOInternal(r *UserRoleAssignment) roletypes.RoleAssignment {return roletypes.RoleAssignment{ID: r.ID,UserID: r.UserID,diff --git a/backend/internal/models/rbac.go b/backend/internal/role/model.gosimilarity index 83%rename from backend/internal/models/rbac.gorename to backend/internal/role/model.goindex 950f5ee97..f3bbfbec7 100644--- a/backend/internal/models/rbac.go+++ b/backend/internal/role/model.go@@ -1,14 +1,16 @@-package models+package role++import "github.com/getarcaneapp/arcane/backend/v2/internal/database"// Role is a named permission set. Built-in roles (Admin, Editor, Deployer,// Viewer) are seeded by migration 054 and cannot be edited or deleted.type Role struct {- BaseModel+ database.BaseModel- Name string `json:"name" gorm:"column:name;not null;uniqueIndex" sortable:"true"`- Description *string `json:"description,omitempty" gorm:"column:description"`- Permissions StringSlice `json:"permissions" gorm:"column:permissions;type:text;not null"`- BuiltIn bool `json:"builtIn" gorm:"column:built_in;not null;default:false" sortable:"true"`+ Name string `json:"name" gorm:"column:name;not null;uniqueIndex" sortable:"true"`+ Description *string `json:"description,omitempty" gorm:"column:description"`+ Permissions database.StringSlice `json:"permissions" gorm:"column:permissions;type:text;not null"`+ BuiltIn bool `json:"builtIn" gorm:"column:built_in;not null;default:false" sortable:"true"`}func (Role) TableName() string { return "roles" }@@ -20,7 +22,7 @@ func (Role) TableName() string { return "roles" }// Source distinguishes manual assignments (managed by admins via the UI) from// assignments synthesized from OIDC group mappings on every login.type UserRoleAssignment struct {- BaseModel+ database.BaseModelUserID string `json:"userId" gorm:"column:user_id;not null;index"`RoleID string `json:"roleId" gorm:"column:role_id;not null;index"`@@ -41,7 +43,7 @@ const (// column on api_keys) so we can index by (api_key_id, permission) for fast// lookups in the auth bridge.type ApiKeyPermission struct {- BaseModel+ database.BaseModelApiKeyID string `json:"apiKeyId" gorm:"column:api_key_id;not null;index"`Permission string `json:"permission" gorm:"column:permission;not null"`@@ -60,7 +62,7 @@ func (ApiKeyPermission) TableName() string { return "api_key_permissions" }// read-only via the API — they can only be changed by editing the env var// and restarting.type OidcRoleMapping struct {- BaseModel+ database.BaseModelClaimValue string `json:"claimValue" gorm:"column:claim_value;not null;index"`RoleID string `json:"roleId" gorm:"column:role_id;not null;index"`diff --git a/backend/internal/role/service.go b/backend/internal/role/service.goindex fb2c66a09..7c4ea3f5a 100644--- a/backend/internal/role/service.go+++ b/backend/internal/role/service.go@@ -14,7 +14,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil"@@ -72,11 +71,11 @@ func (s *RoleService) EnsureBuiltInRoles(ctx context.Context) error {return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {for id, spec := range builtIns {- role := models.Role{- BaseModel: models.BaseModel{ID: id},+ role := Role{+ BaseModel: database.BaseModel{ID: id},Name: spec.name,Description: new(spec.desc),- Permissions: models.StringSlice(spec.perm),+ Permissions: database.StringSlice(spec.perm),BuiltIn: true,}if err := tx.Save(&role).Error; err != nil {@@ -123,10 +122,10 @@ func (s *RoleService) BackfillLegacyRoleAssignments(ctx context.Context) error {if legacyRolesContainsAdminInternal(u.Roles) {roleID = authz.BuiltInRoleAdmin}- assignment := models.UserRoleAssignment{+ assignment := UserRoleAssignment{UserID: u.ID,RoleID: roleID,- Source: models.RoleAssignmentSourceManual,+ Source: RoleAssignmentSourceManual,}if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&assignment).Error; err != nil {return errors.WrapIff(err, "failed to backfill assignment for user %s", u.ID)@@ -167,122 +166,16 @@ func (s *RoleService) AssertGlobalAdminExists(ctx context.Context) error {}if count == 0 {return common.Classify(common.ErrNoGlobalAdminRemains, errors.-- // BackfillApiKeyPermissions populates api_key_permissions for every existing- // API key whose row has no permissions yet. Each key inherits a snapshot of- // its owner's current effective permissions (scoped per the key's- // environment_id when set). Idempotent: skips if the table is non-empty.- // BackfillApiKeyPermissions ensures every ownerless (bootstrap) API key has- // its expected permission grants. Called once per boot.- //- // Per-key, not all-or-nothing: a single bootstrap key with zero grants is- // repaired even if other keys are already populated. This recovers env-- // bootstrap keys that pre-date the per-key permission feature, or that were- // created on a deployment where the original SetApiKeyPermissions call failed- // (e.g., the api_key_permissions table didn't exist yet).- //- // User-owned keys are deliberately skipped. A user-owned key with zero grants- // is an intentional "no access" state; rehydrating from the owner's effective- // permissions on every boot would clobber that. User keys are seeded at- // creation time by CreateApiKey instead.New("At least one user must retain a global Admin role assignment"))}return nil}-func (s *RoleService) BackfillApiKeyPermissions(ctx context.Context) error {- // Bootstrap-class keys we'll repair if they have zero grants:- // - user_id IS NULL → env-bootstrap keys.- // - managed_by IS NOT NULL → admin-static (ADMIN_STATIC_API_KEY) keys,- // which DO have a user_id but are infrastructure-managed and must- // always carry full perms.- // Regular user-created keys are deliberately excluded — empty grants on- // those are an intentional "no access" state we must not overwrite.- var keys []models.ApiKey- if err := s.db.WithContext(ctx).Where("user_id IS NULL OR managed_by IS NOT NULL").Find(&keys).Error; err != nil {- return errors.WrapIf(err, "failed to list bootstrap api keys for backfill")- }- if len(keys) == 0 {- return nil- }-- return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- for _, key := range keys {- var existing int64- if err := tx.Model(&models.ApiKeyPermission{}).Where("api_key_id = ?", key.ID).Count(&existing).Error; err != nil {- return errors.WrapIff(err, "failed to count permissions for api key %s", key.ID)- }- if existing > 0 {- continue- }- perms, err := s.backfillPermsForKeyInternal(ctx, tx, key)- if err != nil {- return err- }- for _, p := range perms {- if err := tx.Create(&models.ApiKeyPermission{- ApiKeyID: key.ID,- Permission: p,- EnvironmentID: key.EnvironmentID,- }).Error; err != nil {- return errors.WrapIf(err, "failed to seed api key permission")- }- }- slog.InfoContext(ctx, "Backfilled missing permissions for bootstrap api key", "api_key_id", key.ID, "perm_count", len(perms), "env_id", key.EnvironmentID)- }- return nil- })-}--func (s *RoleService) backfillPermsForKeyInternal(ctx context.Context, tx *gorm.DB, key models.ApiKey) ([]string, error) {- // Static admin bootstrap keys (no owner, no env scope) get full access.- if key.UserID == nil && key.EnvironmentID == nil {- return authz.AllPermissions(), nil- }- // Environment bootstrap keys (key bound to a specific env, no owner) get- // full access scoped to that environment via the auth bridge — replicate- // that by granting all permissions scoped to that environment. Org-level- // permissions land in PerEnv[envID] and are unreachable via org-level- // checks (which always pass envID=""), so over-granting is harmless here.- if key.UserID == nil && key.EnvironmentID != nil {- return authz.AllPermissions(), nil- }- // Otherwise inherit the owner's current effective permissions.- var owner models.User- if err := tx.WithContext(ctx).Where("id = ?", *key.UserID).First(&owner).Error; err != nil {- if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, nil- }- return nil, errors.WrapIf(err, "failed to load api key owner")- }- ps, err := s.ResolveUserPermissionsInDB(ctx, tx, owner.ID)- if err != nil {- return nil, err- }- // Flatten ps into a deduplicated list of permissions for this key's scope.- seen := make(map[string]struct{}, len(ps.Global))- for p := range ps.Global {- seen[p] = struct{}{}- }- if key.EnvironmentID != nil {- if env, ok := ps.PerEnv[*key.EnvironmentID]; ok {- for p := range env {- seen[p] = struct{}{}- }- }- }- out := make([]string, 0, len(seen))- for p := range seen {- out = append(out, p)- }- return out, nil-}-// ---------- Role CRUD -----------func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParams) ([]models.Role, pagination.Response, error) {- var roles []models.Role- query := s.db.WithContext(ctx).Model(&models.Role{})+func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParams) ([]Role, pagination.Response, error) {+ var roles []Role+ query := s.db.WithContext(ctx).Model(&Role{})if term := strings.TrimSpace(params.Search); term != "" {pattern := "%" + term + "%"@@ -296,34 +189,34 @@ func (s *RoleService) ListRoles(ctx context.Context, params pagination.QueryParareturn roles, resp, nil}-func (s *RoleService) ListAllRoles(ctx context.Context) ([]models.Role, error) {- var roles []models.Role+func (s *RoleService) ListAllRoles(ctx context.Context) ([]Role, error) {+ var roles []Roleif err := s.db.WithContext(ctx).Order("name").Find(&roles).Error; err != nil {return nil, errors.WrapIf(err, "failed to list roles")}return roles, nil}-func (s *RoleService) GetRole(ctx context.Context, id string) (*models.Role, error) {- return dbutil.FirstWhere[models.Role](ctx, s.db.DB, common.Classify(common.ErrRoleNotFound, errors.New("Role not found")), "id = ?", id)+func (s *RoleService) GetRole(ctx context.Context, id string) (*Role, error) {+ return dbutil.FirstWhere[Role](ctx, s.db.DB, common.Classify(common.ErrRoleNotFound, errors.New("Role not found")), "id = ?", id)}-func (s *RoleService) CreateRole(ctx context.Context, name string, description *string, permissions []string) (*models.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")}if err := validatePermissionsInternal(permissions); err != nil {return nil, err}- role := &models.Role{+ role := &Role{Name: name,Description: description,- Permissions: models.StringSlice(permissions),+ 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(&models.Role{}).Where("name = ?", name).Count(&conflict).Error; err != nil {+ if err := tx.Model(&Role{}).Where("name = ?", name).Count(&conflict).Error; err != nil {return errors.WrapIf(err, "failed to check role name uniqueness")}if conflict > 0 {@@ -345,7 +238,7 @@ func (s *RoleService) CreateRole(ctx context.Context, name string, description *// Returns the affected user ids for post-commit cache invalidation.func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error) {var ids []string- if err := tx.Model(&models.UserRoleAssignment{}).+ if err := tx.Model(&UserRoleAssignment{}).Where("role_id = ?", roleID).Distinct("user_id").Pluck("user_id", &ids).Error; err != nil {@@ -355,7 +248,7 @@ func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error)return ids, nil}var locked []string- if err := tx.Model(&models.User{}).+ if err := tx.Model(&common.User{}).Clauses(clause.Locking{Strength: "UPDATE"}).Where("id IN ?", ids).Order("id").@@ -365,13 +258,13 @@ func lockAssignedUserRowsInternal(tx *gorm.DB, roleID string) ([]string, error)return ids, nil}-func (s *RoleService) UpdateRole(ctx context.Context, id, name string, description *string, permissions []string) (*models.Role, error) {+func (s *RoleService) UpdateRole(ctx context.Context, id, name string, description *string, permissions []string) (*Role, error) {if err := validatePermissionsInternal(permissions); err != nil {return nil, err}- var out models.Role+ var out Roleerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- var existing models.Role+ var existing Roleif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrRoleNotFound, errors.New("Role not found"))@@ -383,7 +276,7 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descripti}if name != existing.Name {var conflict int64- if err := tx.Model(&models.Role{}).Where("name = ? AND id <> ?", name, id).Count(&conflict).Error; err != nil {+ if err := tx.Model(&Role{}).Where("name = ? AND id <> ?", name, id).Count(&conflict).Error; err != nil {return errors.WrapIf(err, "failed to check role name uniqueness")}if conflict > 0 {@@ -412,7 +305,7 @@ func (s *RoleService) UpdateRole(ctx context.Context, id, name string, descriptifunc (s *RoleService) DeleteRole(ctx context.Context, id string) error {var affected []stringerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- var existing models.Role+ var existing Roleif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrRoleNotFound, errors.New("Role not found"))@@ -431,7 +324,7 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {return err}affected = ids- if err := tx.Delete(&models.Role{}, "id = ?", id).Error; err != nil {+ if err := tx.Delete(&Role{}, "id = ?", id).Error; err != nil {return errors.WrapIf(err, "failed to delete role")}return nil@@ -453,7 +346,7 @@ func (s *RoleService) DeleteRole(ctx context.Context, id string) error {func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID string) (int, error) {var count int64if err := s.db.WithContext(ctx).- Model(&models.UserRoleAssignment{}).+ Model(&UserRoleAssignment{}).Distinct("user_id").Where("role_id = ?", roleID).Count(&count).Error; err != nil {@@ -464,8 +357,8 @@ func (s *RoleService) CountUsersAssignedToRole(ctx context.Context, roleID strin// ---------- User role assignments -----------func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([]models.UserRoleAssignment, error) {- var out []models.UserRoleAssignment+func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([]UserRoleAssignment, error) {+ var out []UserRoleAssignmentif err := s.db.WithContext(ctx).Where("user_id = ?", userID).Order("source ASC, role_id ASC").@@ -481,7 +374,7 @@ func (s *RoleService) ListUserAssignments(ctx context.Context, userID string) ([// error (→ 400) rather than an opaque FK violation, and the global-admin guard// is enforced before commit. Shared by SetUserAssignments and// ReplaceOidcAssignments.-func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Context, userID, source string, desired []models.UserRoleAssignment) error {+func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Context, userID, source string, desired []UserRoleAssignment) error {for i := range desired {desired[i].UserID = userIDdesired[i].Source = source@@ -492,7 +385,7 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contex// checks lock the same row.if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).- First(&models.User{}).Error; err != nil {+ First(&common.User{}).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.ErrUserNotFound}@@ -502,7 +395,7 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contexreturn err}if err := tx.Where("user_id = ? AND source = ?", userID, source).- Delete(&models.UserRoleAssignment{}).Error; err != nil {+ Delete(&UserRoleAssignment{}).Error; err != nil {return errors.WrapIff(err, "failed to clear %s assignments", source)}if len(desired) > 0 {@@ -529,15 +422,15 @@ func (s *RoleService) replaceUserAssignmentsForSourceInternal(ctx context.Contex// SetUserAssignments replaces the user's source='manual' assignments with the// given desired set. Source='oidc' rows are preserved (use// ReplaceOidcAssignments for those). Enforces the global-admin guard.-func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error {- return s.replaceUserAssignmentsForSourceInternal(ctx, userID, models.RoleAssignmentSourceManual, desired)+func (s *RoleService) SetUserAssignments(ctx context.Context, userID string, desired []UserRoleAssignment) error {+ return s.replaceUserAssignmentsForSourceInternal(ctx, userID, RoleAssignmentSourceManual, desired)}// validateAssignmentsExistInternal verifies every distinct RoleID and// EnvironmentID referenced by `desired` exists in the database. Returns the// first missing reference wrapped in an InvalidRoleAssignmentError so the// handler can map it to a 400 with a descriptive message.-func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssignment) error {+func validateAssignmentsExistInternal(tx *gorm.DB, desired []UserRoleAssignment) error {roleIDSet := make(map[string]struct{}, len(desired))envIDSet := make(map[string]struct{}, len(desired))for _, a := range desired {@@ -553,7 +446,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssiroleIDs = append(roleIDs, id)}var found []string- if err := tx.Model(&models.Role{}).Where("id IN ?", roleIDs).Pluck("id", &found).Error; err != nil {+ if err := tx.Model(&Role{}).Where("id IN ?", roleIDs).Pluck("id", &found).Error; err != nil {return errors.WrapIf(err, "failed to verify role ids")}foundSet := make(map[string]struct{}, len(found))@@ -573,7 +466,7 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssienvIDs = append(envIDs, id)}var found []string- if err := tx.Model(&models.Environment{}).Where("id IN ?", envIDs).Pluck("id", &found).Error; err != nil {+ if err := tx.Table("environments").Where("id IN ?", envIDs).Pluck("id", &found).Error; err != nil {return errors.WrapIf(err, "failed to verify environment ids")}foundSet := make(map[string]struct{}, len(found))@@ -594,8 +487,8 @@ func validateAssignmentsExistInternal(tx *gorm.DB, desired []models.UserRoleAssi// environment fails with a typed error; the caller logs and continues login so// the user simply receives no OIDC-derived assignments. Enforces the// global-admin guard after the swap.-func (s *RoleService) ReplaceOidcAssignments(ctx context.Context, userID string, desired []models.UserRoleAssignment) error {- return s.replaceUserAssignmentsForSourceInternal(ctx, userID, models.RoleAssignmentSourceOidc, desired)+func (s *RoleService) ReplaceOidcAssignments(ctx context.Context, userID string, desired []UserRoleAssignment) error {+ return s.replaceUserAssignmentsForSourceInternal(ctx, userID, RoleAssignmentSourceOidc, desired)}// CountGlobalAdminsExcludingUser returns the number of non-service users (other@@ -653,7 +546,7 @@ func (s *RoleService) countEffectiveGlobalAdminsInternal(ctx context.Context, tx// ResolvePermissions returns the effective PermissionSet for a user, caching// the result per-user for permissionCacheTTL.-func (s *RoleService) ResolvePermissions(ctx context.Context, user *models.User) (*authz.PermissionSet, error) {+func (s *RoleService) ResolvePermissions(ctx context.Context, user *common.User) (*authz.PermissionSet, error) {if user == nil {return authz.NewPermissionSet(), nil}@@ -672,7 +565,7 @@ func (s *RoleService) ResolvePermissions(ctx context.Context, user *models.User)func (s *RoleService) ResolveUserPermissionsInDB(_ context.Context, tx *gorm.DB, userID string) (*authz.PermissionSet, error) {// Scan into raw string for the permissions JSON column to avoid GORM's// schema-introspection on anonymous local structs (which can't see the- // type tags needed to wire models.StringSlice's Scanner).+ // type tags needed to wire database.StringSlice's Scanner).type row struct {Permissions string `gorm:"column:permissions"`EnvironmentID *string `gorm:"column:environment_id"`@@ -719,7 +612,7 @@ func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID strif ps, ok, _ := s.apiKeyCache.Get(apiKeyID); ok {return ps, nil}- var perms []models.ApiKeyPermission+ var perms []ApiKeyPermissionif err := s.db.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Find(&perms).Error; err != nil {return nil, errors.WrapIf(err, "failed to resolve api key permissions")}@@ -738,7 +631,7 @@ func (s *RoleService) ResolveApiKeyPermissions(ctx context.Context, apiKeyID str// SetApiKeyPermissions replaces every permission row on the given API key// atomically. Validation that the granted permissions don't exceed the// creator's capabilities happens in the handler layer.-func (s *RoleService) SetApiKeyPermissions(ctx context.Context, apiKeyID string, grants []models.ApiKeyPermission) error {+func (s *RoleService) SetApiKeyPermissions(ctx context.Context, apiKeyID string, grants []ApiKeyPermission) error {err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {return s.SetApiKeyPermissionsInDB(ctx, tx, apiKeyID, grants)})@@ -750,11 +643,11 @@ func (s *RoleService) SetApiKeyPermissions(ctx context.Context, apiKeyID string,}// SetApiKeyPermissionsInDB replaces permission rows using the supplied transaction or database handle.-func (s *RoleService) SetApiKeyPermissionsInDB(ctx context.Context, tx *gorm.DB, apiKeyID string, grants []models.ApiKeyPermission) error {+func (s *RoleService) SetApiKeyPermissionsInDB(ctx context.Context, tx *gorm.DB, apiKeyID string, grants []ApiKeyPermission) error {for i := range grants {grants[i].ApiKeyID = apiKeyID}- if err := tx.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Delete(&models.ApiKeyPermission{}).Error; err != nil {+ if err := tx.WithContext(ctx).Where("api_key_id = ?", apiKeyID).Delete(&ApiKeyPermission{}).Error; err != nil {return errors.WrapIf(err, "failed to clear api key permissions")}if len(grants) > 0 {@@ -767,19 +660,19 @@ func (s *RoleService) SetApiKeyPermissionsInDB(ctx context.Context, tx *gorm.DB,// ---------- OIDC role mappings -----------func (s *RoleService) ListOidcMappings(ctx context.Context) ([]models.OidcRoleMapping, error) {- var out []models.OidcRoleMapping+func (s *RoleService) ListOidcMappings(ctx context.Context) ([]OidcRoleMapping, error) {+ var out []OidcRoleMappingif err := s.db.WithContext(ctx).Order("claim_value, role_id").Find(&out).Error; err != nil {return nil, errors.WrapIf(err, "failed to list oidc mappings")}return out, nil}-func (s *RoleService) GetOidcMapping(ctx context.Context, id string) (*models.OidcRoleMapping, error) {- return dbutil.FirstWhere[models.OidcRoleMapping](ctx, s.db.DB, common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found")), "id = ?", id)+func (s *RoleService) GetOidcMapping(ctx context.Context, id string) (*OidcRoleMapping, error) {+ return dbutil.FirstWhere[OidcRoleMapping](ctx, s.db.DB, common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found")), "id = ?", id)}-func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleID string, environmentID *string) (*models.OidcRoleMapping, error) {+func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleID string, environmentID *string) (*OidcRoleMapping, error) {claimValue = strings.TrimSpace(claimValue)roleID = strings.TrimSpace(roleID)if claimValue == "" {@@ -788,16 +681,16 @@ func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleIDif roleID == "" {return nil, errors.New("role id is required")}- var mapping models.OidcRoleMapping+ var mapping OidcRoleMappingerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := validateRoleIDsExistInternal(tx, []string{roleID}); err != nil {return err}- mapping = models.OidcRoleMapping{+ mapping = OidcRoleMapping{ClaimValue: claimValue,RoleID: roleID,EnvironmentID: environmentID,- Source: models.OidcMappingSourceManual,+ Source: OidcMappingSourceManual,}if err := tx.Create(&mapping).Error; err != nil {return errors.WrapIf(err, "failed to create oidc mapping")@@ -810,7 +703,7 @@ func (s *RoleService) CreateOidcMapping(ctx context.Context, claimValue, roleIDreturn &mapping, nil}-func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, roleID string, environmentID *string) (*models.OidcRoleMapping, error) {+func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, roleID string, environmentID *string) (*OidcRoleMapping, error) {claimValue = strings.TrimSpace(claimValue)roleID = strings.TrimSpace(roleID)if claimValue == "" {@@ -819,16 +712,16 @@ func (s *RoleService) UpdateOidcMapping(ctx context.Context, id, claimValue, rolif roleID == "" {return nil, errors.New("role id is required")}- var out models.OidcRoleMapping+ var out OidcRoleMappingerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- var existing models.OidcRoleMapping+ var existing OidcRoleMappingif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found"))}return errors.WrapIf(err, "failed to load mapping")}- if existing.Source == models.OidcMappingSourceEnv {+ if existing.Source == OidcMappingSourceEnv {return common.Classify(common.ErrOidcMappingEnvManaged, errors.New("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))}if err := validateRoleIDsExistInternal(tx, []string{roleID}); err != nil {@@ -866,7 +759,7 @@ func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {normalized = append(normalized, roleID)}var found []string- if err := tx.Model(&models.Role{}).Where("id IN ?", normalized).Pluck("id", &found).Error; err != nil {+ if err := tx.Model(&Role{}).Where("id IN ?", normalized).Pluck("id", &found).Error; err != nil {return errors.WrapIf(err, "failed to verify role ids")}foundSet := make(map[string]struct{}, len(found))@@ -883,17 +776,17 @@ func validateRoleIDsExistInternal(tx *gorm.DB, roleIDs []string) error {func (s *RoleService) DeleteOidcMapping(ctx context.Context, id string) error {return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- var existing models.OidcRoleMapping+ var existing OidcRoleMappingif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrOidcMappingNotFound, errors.New("OIDC role mapping not found"))}return errors.WrapIf(err, "failed to load mapping")}- if existing.Source == models.OidcMappingSourceEnv {+ if existing.Source == OidcMappingSourceEnv {return common.Classify(common.ErrOidcMappingEnvManaged, errors.New("OIDC role mapping is managed by OIDC_ROLE_MAPPINGS and cannot be edited at runtime"))}- if err := tx.Delete(&models.OidcRoleMapping{}, "id = ?", id).Error; err != nil {+ if err := tx.Delete(&OidcRoleMapping{}, "id = ?", id).Error; err != nil {return errors.WrapIf(err, "failed to delete mapping")}return nil@@ -934,7 +827,7 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri// role delete can't race past this check.for i, sp := range specs {var count int64- if err := tx.Model(&models.Role{}).Where("id = ?", sp.RoleID).Count(&count).Error; err != nil {+ if err := tx.Model(&Role{}).Where("id = ?", sp.RoleID).Count(&count).Error; err != nil {return errors.WrapIff(err, "OIDC_ROLE_MAPPINGS[%d]: failed to verify role", i)}if count == 0 {@@ -944,20 +837,20 @@ func (s *RoleService) ReconcileEnvOidcMappings(ctx context.Context, rawSpec stri// Declarative replace: drop every env-managed row, then insert the new// set. Manual rows are untouched.- if err := tx.Where("source = ?", models.OidcMappingSourceEnv).Delete(&models.OidcRoleMapping{}).Error; err != nil {+ if err := tx.Where("source = ?", OidcMappingSourceEnv).Delete(&OidcRoleMapping{}).Error; err != nil {return errors.WrapIf(err, "failed to clear env-managed mappings")}if len(specs) == 0 {slog.InfoContext(ctx, "OIDC_ROLE_MAPPINGS reconciled (empty)", "envManagedCount", 0)return nil}- rows := make([]models.OidcRoleMapping, len(specs))+ rows := make([]OidcRoleMapping, len(specs))for i, sp := range specs {- rows[i] = models.OidcRoleMapping{+ rows[i] = OidcRoleMapping{ClaimValue: sp.ClaimValue,RoleID: sp.RoleID,EnvironmentID: sp.EnvironmentID,- Source: models.OidcMappingSourceEnv,+ Source: OidcMappingSourceEnv,}}if err := tx.Create(&rows).Error; err != nil {@@ -987,7 +880,7 @@ func (s *RoleService) InvalidateApiKey(apiKeyID string) {func (s *RoleService) invalidateUsersAssignedToInternal(ctx context.Context, roleID string) {var userIDs []stringif err := s.db.WithContext(ctx).- Model(&models.UserRoleAssignment{}).+ Model(&UserRoleAssignment{}).Distinct("user_id").Where("role_id = ?", roleID).Pluck("user_id", &userIDs).Error; err != nil {diff --git a/backend/internal/role/service_test.go b/backend/internal/role/service_test.goindex c881c21a3..c12d60220 100644--- a/backend/internal/role/service_test.go+++ b/backend/internal/role/service_test.go@@ -1,6 +1,10 @@package roleimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""slices""testing"@@ -9,42 +13,12 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/libtnb/sqlite""github.com/stretchr/testify/require""gorm.io/gorm")-func TestBackfillPermsForKeyDeduplicatesGlobalAndEnvironmentPermissions(t *testing.T) {- ctx := context.Background()- userSvc, roleSvc := setupUserAndRoleServices(t)- admin := createTestUser(t, userSvc, "admin", "admin")- grantGlobalAdmin(t, roleSvc, admin.ID)- user := createTestUser(t, userSvc, "api-key-owner", "api-key-owner")- envID := "env-1"- createTestEnvironment(t, roleSvc.db, envID, "http://localhost:3552", nil)-- require.NoError(t, roleSvc.SetUserAssignments(ctx, user.ID, []models.UserRoleAssignment{- {RoleID: authz.BuiltInRoleViewer, EnvironmentID: nil},- {RoleID: authz.BuiltInRoleEditor, EnvironmentID: &envID},- }))-- perms, err := roleSvc.backfillPermsForKeyInternal(ctx, roleSvc.db.WithContext(ctx), models.ApiKey{- UserID: &user.ID,- EnvironmentID: &envID,- })- require.NoError(t, err)- require.Contains(t, perms, authz.PermContainersList)- require.Equal(t, 1, countPermissionInternal(perms, authz.PermContainersList))-}--func countPermissionInternal(perms []string, permission string) int {- return len(slices.DeleteFunc(slices.Clone(perms), func(p string) bool {- return p != permission- }))-}-func TestValidatePermissionsAgainstCallerRejectsEscalation(t *testing.T) {_, roleSvc := setupUserAndRoleServices(t)@@ -103,15 +77,15 @@ func TestEnsureBuiltInRolesMigratesVariablePermissionsWithoutBackfillingCustomGrcustomRole, err := roleSvc.CreateRole(ctx, "Template Reader", nil, []string{authz.PermTemplatesRead})require.NoError(t, err)owner := createTestUser(t, userSvc, "variable-migration-owner", "variable-migration-owner")- scopedKey := models.ApiKey{+ scopedKey := testApiKeyRow{Name: "Custom scoped key",KeyHash: "variable-migration-hash",KeyPrefix: "arc_vars",- Kind: models.ApiKeyKindScoped,+ Kind: "scoped",UserID: &owner.ID,}require.NoError(t, roleSvc.db.WithContext(ctx).Create(&scopedKey).Error)- require.NoError(t, roleSvc.db.WithContext(ctx).Create(&models.ApiKeyPermission{+ require.NoError(t, roleSvc.db.WithContext(ctx).Create(&ApiKeyPermission{ApiKeyID: scopedKey.ID,Permission: authz.PermTemplatesRead,}).Error)@@ -125,12 +99,11 @@ func TestEnsureBuiltInRolesMigratesVariablePermissionsWithoutBackfillingCustomGrauthz.PermVariablesSync,}, permission)})- require.NoError(t, roleSvc.db.WithContext(ctx).Model(&models.Role{}).+ require.NoError(t, roleSvc.db.WithContext(ctx).Model(&Role{}).Where("id = ?", authz.BuiltInRoleEditor).- Update("permissions", models.StringSlice(oldEditorPermissions)).Error)+ Update("permissions", database.StringSlice(oldEditorPermissions)).Error)require.NoError(t, roleSvc.EnsureBuiltInRoles(ctx))- require.NoError(t, roleSvc.BackfillApiKeyPermissions(ctx))allVariablePermissions := []string{authz.PermVariablesRead,@@ -164,7 +137,7 @@ func TestEnsureBuiltInRolesMigratesVariablePermissionsWithoutBackfillingCustomGrrequire.NoError(t, err)require.Equal(t, []string{authz.PermTemplatesRead}, []string(preservedCustomRole.Permissions))- var keyPermissions []models.ApiKeyPermission+ var keyPermissions []ApiKeyPermissionrequire.NoError(t, roleSvc.db.WithContext(ctx).Where("api_key_id = ?", scopedKey.ID).Find(&keyPermissions).Error)require.Len(t, keyPermissions, 1)require.Equal(t, authz.PermTemplatesRead, keyPermissions[0].Permission)@@ -175,7 +148,7 @@ func TestSetUserAssignmentsRejectsUnknownRole(t *testing.T) {userSvc, roleSvc := setupUserAndRoleServices(t)user := createTestUser(t, userSvc, "victim", "victim")- err := roleSvc.SetUserAssignments(ctx, user.ID, []models.UserRoleAssignment{+ err := roleSvc.SetUserAssignments(ctx, user.ID, []UserRoleAssignment{{RoleID: "role_does_not_exist"},})require.Error(t, err)@@ -187,7 +160,7 @@ func TestReplaceOidcAssignmentsRejectsUnknownRole(t *testing.T) {userSvc, roleSvc := setupUserAndRoleServices(t)user := createTestUser(t, userSvc, "oidc-user", "oidc-user")- err := roleSvc.ReplaceOidcAssignments(ctx, user.ID, []models.UserRoleAssignment{+ err := roleSvc.ReplaceOidcAssignments(ctx, user.ID, []UserRoleAssignment{{RoleID: "role_does_not_exist"},})require.Error(t, err)@@ -202,7 +175,7 @@ func TestReplaceOidcAssignmentsRejectsUnknownEnvironment(t *testing.T) {// A valid role scoped to a non-existent environment must fail existence// validation (mirrors SetUserAssignments) rather than attempting an insert.- err := roleSvc.ReplaceOidcAssignments(ctx, user.ID, []models.UserRoleAssignment{+ err := roleSvc.ReplaceOidcAssignments(ctx, user.ID, []UserRoleAssignment{{RoleID: authz.BuiltInRoleViewer, EnvironmentID: &missingEnv},})require.Error(t, err)@@ -216,7 +189,7 @@ func TestEffectiveGlobalAdminCountIncludesCustomAllPermissionsRole(t *testing.T)customRole, err := roleSvc.CreateRole(ctx, "Custom Admin", nil, authz.AllPermissions())require.NoError(t, err)- require.NoError(t, roleSvc.SetUserAssignments(ctx, user.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, user.ID, []UserRoleAssignment{{RoleID: customRole.ID, EnvironmentID: nil},}))@@ -240,20 +213,20 @@ func TestEffectiveGlobalAdminCountIgnoresEnvScopedAndServiceAccounts(t *testing.globalAdmin := createTestUser(t, userSvc, "global-admin", "global-admin")envScopedAdmin := createTestUser(t, userSvc, "env-scoped-admin", "env-scoped-admin")- serviceAdmin := &models.User{- BaseModel: models.BaseModel{ID: "service-admin"},+ serviceAdmin := &common.User{+ BaseModel: database.BaseModel{ID: "service-admin"},Username: "service-admin",IsServiceAccount: true,}require.NoError(t, roleSvc.db.WithContext(ctx).Create(serviceAdmin).Error)- require.NoError(t, roleSvc.SetUserAssignments(ctx, globalAdmin.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, globalAdmin.ID, []UserRoleAssignment{{RoleID: customRole.ID, EnvironmentID: nil},}))- require.NoError(t, roleSvc.SetUserAssignments(ctx, envScopedAdmin.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, envScopedAdmin.ID, []UserRoleAssignment{{RoleID: customRole.ID, EnvironmentID: &envID},}))- require.NoError(t, roleSvc.SetUserAssignments(ctx, serviceAdmin.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, serviceAdmin.ID, []UserRoleAssignment{{RoleID: customRole.ID, EnvironmentID: nil},}))@@ -267,15 +240,15 @@ func setupAuthServiceTestDB(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.SettingVariable{},- &models.User{},- &models.UserSession{},- &models.Environment{},- &models.Role{},- &models.UserRoleAssignment{},- &models.ApiKey{},- &models.ApiKeyPermission{},- &models.OidcRoleMapping{},+ &settings.SettingVariable{},+ &common.User{},+ &session.UserSession{},+ &testEnvironmentRow{},+ &Role{},+ &UserRoleAssignment{},+ &testApiKeyRow{},+ &ApiKeyPermission{},+ &OidcRoleMapping{},))return &database.DB{DB: db}}@@ -288,16 +261,16 @@ func setupUserAndRoleServices(t *testing.T) (*database.DB, *RoleService) {return db, roleService}-func createTestUser(t *testing.T, db *database.DB, id, username string) *models.User {+func createTestUser(t *testing.T, db *database.DB, id, username string) *common.User {t.Helper()- created := &models.User{BaseModel: models.BaseModel{ID: id}, Username: username}+ created := &common.User{BaseModel: database.BaseModel{ID: id}, Username: username}require.NoError(t, db.WithContext(context.Background()).Create(created).Error)return created}func grantGlobalAdmin(t *testing.T, roleService *RoleService, userID string) {t.Helper()- require.NoError(t, roleService.SetUserAssignments(context.Background(), userID, []models.UserRoleAssignment{+ require.NoError(t, roleService.SetUserAssignments(context.Background(), userID, []UserRoleAssignment{{RoleID: authz.BuiltInRoleAdmin},}))}@@ -305,12 +278,38 @@ func grantGlobalAdmin(t *testing.T, roleService *RoleService, userID string) {func createTestEnvironment(t *testing.T, db *database.DB, id, apiURL string, accessToken *string) {t.Helper()now := time.Now()- require.NoError(t, db.WithContext(context.Background()).Create(&models.Environment{- BaseModel: models.BaseModel{ID: id, CreatedAt: now, UpdatedAt: &now},+ require.NoError(t, db.WithContext(context.Background()).Create(&testEnvironmentRow{+ BaseModel: database.BaseModel{ID: id, CreatedAt: now, UpdatedAt: &now},Name: "env-" + id,ApiUrl: apiURL,- Status: string(models.EnvironmentStatusOnline),+ Status: "online",Enabled: true,AccessToken: accessToken,}).Error)}++// Minimal stand-ins for environment.Environment and apikey.ApiKey: both of+// those packages import role, so this in-package test cannot import them.+type testEnvironmentRow struct {+ database.BaseModel+ Name string+ ApiUrl string `gorm:"column:api_url"`+ Status string+ Enabled bool+ AccessToken *string `gorm:"column:access_token"`+}++func (testEnvironmentRow) TableName() string { return "environments" }++type testApiKeyRow struct {+ database.BaseModel+ Name string+ KeyHash string `gorm:"column:key_hash"`+ KeyPrefix string `gorm:"column:key_prefix"`+ Kind string+ UserID *string `gorm:"column:user_id"`+ EnvironmentID *string `gorm:"column:environment_id"`+ ManagedBy *string `gorm:"column:managed_by"`+}++func (testApiKeyRow) TableName() string { return "api_keys" }diff --git a/backend/internal/search/customize_service.go b/backend/internal/search/customize_service.goindex 710b51b88..5ef56373d 100644--- a/backend/internal/search/customize_service.go+++ b/backend/internal/search/customize_service.go@@ -7,7 +7,6 @@ import ("strings""sync"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/category""github.com/getarcaneapp/arcane/types/v2/meta"@@ -38,13 +37,13 @@ func (s *CustomizeSearchService) GetCustomizeCategories() []category.Category {func (s *CustomizeSearchService) buildCategoriesFromModel() []category.Category {// Extract category metadata from struct tags (catmeta)- catMetaMap := utils.ExtractCategoryMetadata(models.CustomizeItem{}, nil)+ catMetaMap := utils.ExtractCategoryMetadata(CustomizeItem{}, nil)// map category id -> list of customizationscategories := map[string][]meta.Metadata{}var categoryOrder []string // Track order from first appearance in struct- rt := reflect.TypeFor[models.CustomizeItem]()+ rt := reflect.TypeFor[CustomizeItem]()for field := range rt.Fields() {keyTag := field.Tag.Get("key")key, _, _ := strings.Cut(keyTag, ",")diff --git a/backend/internal/models/customize.go b/backend/internal/search/model.gosimilarity index 99%rename from backend/internal/models/customize.gorename to backend/internal/search/model.goindex 16500aa89..d246ac67e 100644--- a/backend/internal/models/customize.go+++ b/backend/internal/search/model.go@@ -1,4 +1,4 @@-package models+package search// CustomizeItem represents a customization configuration item// This struct uses reflection tags to define customization categories and metadatadiff --git a/backend/internal/search/module.go b/backend/internal/search/module.goindex 10f0c6471..034647aba 100644--- a/backend/internal/search/module.go+++ b/backend/internal/search/module.go@@ -4,28 +4,18 @@ package searchimport "github.com/danielgtaylor/huma/v2"-// Module owns both search indexes and mounts the customization search routes.+// Module owns the customization search index and mounts the customization search routes.type Module struct {- settings *SettingsSearchServicecustomize *CustomizeSearchService}-// New builds the settings and customization search indexes.+// New builds the customization search index.func New() *Module {return &Module{- settings: NewSettingsSearchService(),customize: NewCustomizeSearchService(),}}-// SettingsService exposes the settings search index to the settings domain.-func (m *Module) SettingsService() *SettingsSearchService {- if m == nil {- return nil- }- return m.settings-}-// CustomizeService exposes the customization search index to direct collaborators.func (m *Module) CustomizeService() *CustomizeSearchService {if m == nil {diff --git a/backend/internal/session/model.go b/backend/internal/session/model.gonew file mode 100644index 000000000..207e5b190--- /dev/null+++ b/backend/internal/session/model.go@@ -0,0 +1,46 @@+package session++import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"++ "time"+)++const (+ UserSessionSourceLocal = "local"+ UserSessionSourceOidc = "oidc"+ UserSessionSourceFederated = "federated"+ UserSessionSourcePasskey = "passkey"+)++type UserSession struct {+ database.BaseModel++ UserID string `json:"userId" gorm:"column:user_id;not null;index"`+ User *common.User `json:"user,omitempty" gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE"`+ RefreshTokenHash string `json:"-" gorm:"column:refresh_token_hash;not null;uniqueIndex"`+ UserAgent *string `json:"userAgent,omitempty" gorm:"column:user_agent"`+ IPAddress *string `json:"ipAddress,omitempty" gorm:"column:ip_address"`+ Source string `json:"source,omitempty" gorm:"column:source"`+ // FederatedCredentialID links federated sessions to their credential row;+ // the FK (ON DELETE SET NULL) lives in the SQL migrations.+ FederatedCredentialID *string `json:"federatedCredentialId,omitempty" gorm:"column:federated_credential_id;index"`+ LastUsedAt time.Time `json:"lastUsedAt" gorm:"column:last_used_at;not null"`+ ExpiresAt time.Time `json:"expiresAt" gorm:"column:expires_at;not null;index"`+ RevokedAt *time.Time `json:"revokedAt,omitempty" gorm:"column:revoked_at"`+ MFAMethod *string `json:"mfaMethod,omitempty" gorm:"column:mfa_method"`+ MFAVerifiedAt *time.Time `json:"mfaVerifiedAt,omitempty" gorm:"column:mfa_verified_at"`+}++func (UserSession) TableName() string {+ return "user_sessions"+}++const (+ // PasskeyMFAMethod and RecoveryCodeMFAMethod name the second factor a login+ // completed with, recorded on the session for auditing.+ PasskeyMFAMethod = "passkey"+ RecoveryCodeMFAMethod = "recovery_code"+)diff --git a/backend/internal/session/service.go b/backend/internal/session/service.goindex 8fe4d4abe..0d1debddb 100644--- a/backend/internal/session/service.go+++ b/backend/internal/session/service.go@@ -12,7 +12,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2/auth""github.com/google/uuid"@@ -28,16 +27,16 @@ func NewSessionService(db *database.DB) *SessionService {return &SessionService{db: db}}-func (s *SessionService) CreateSession(ctx context.Context, userID string, expiresAt time.Time, meta auth.SessionMeta) (*models.UserSession, string, error) {+func (s *SessionService) CreateSession(ctx context.Context, userID string, expiresAt time.Time, meta auth.SessionMeta) (*UserSession, string, error) {refreshJTI := uuid.NewString()refreshHash := hashRefreshJTIInternal(refreshJTI)now := time.Now()source := strings.TrimSpace(meta.Source)if source == "" {- source = models.UserSessionSourceLocal+ source = UserSessionSourceLocal}- session := &models.UserSession{+ session := &UserSession{UserID: userID,RefreshTokenHash: refreshHash,UserAgent: mo.EmptyableToOption(strings.TrimSpace(meta.UserAgent)).ToPointer(),@@ -56,14 +55,14 @@ func (s *SessionService) CreateSession(ctx context.Context, userID string, expirreturn session, refreshJTI, nil}-func (s *SessionService) CreateFederatedSession(ctx context.Context, userID string, expiresAt time.Time, credentialID string) (*models.UserSession, error) {+func (s *SessionService) CreateFederatedSession(ctx context.Context, userID string, expiresAt time.Time, credentialID string) (*UserSession, error) {refreshHash := hashRefreshJTIInternal(uuid.NewString())now := time.Now()- session := &models.UserSession{+ session := &UserSession{UserID: userID,RefreshTokenHash: refreshHash,- Source: models.UserSessionSourceFederated,+ Source: UserSessionSourceFederated,FederatedCredentialID: mo.EmptyableToOption(strings.TrimSpace(credentialID)).ToPointer(),LastUsedAt: now,ExpiresAt: expiresAt,@@ -76,12 +75,12 @@ func (s *SessionService) CreateFederatedSession(ctx context.Context, userID strireturn session, nil}-func (s *SessionService) GetSessionByID(ctx context.Context, sessionID string) (*models.UserSession, error) {+func (s *SessionService) GetSessionByID(ctx context.Context, sessionID string) (*UserSession, error) {if strings.TrimSpace(sessionID) == "" {return nil, common.ErrInvalidToken}- var session models.UserSession+ var session UserSessionif err := s.db.WithContext(ctx).Where("id = ?", sessionID).First(&session).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.ErrInvalidToken@@ -91,7 +90,7 @@ func (s *SessionService) GetSessionByID(ctx context.Context, sessionID string) (return &session, nil}-func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID string, refreshJTI string, meta auth.SessionMeta) (*models.UserSession, string, error) {+func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID string, refreshJTI string, meta auth.SessionMeta) (*UserSession, string, error) {if strings.TrimSpace(sessionID) == "" || strings.TrimSpace(refreshJTI) == "" {return nil, "", common.ErrInvalidToken}@@ -100,10 +99,10 @@ func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID strinnewHash := hashRefreshJTIInternal(newRefreshJTI)now := time.Now()- var rotated models.UserSession+ var rotated UserSessionerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- var session models.UserSession+ var session UserSessionif err := tx.Where("id = ?", sessionID).First(&session).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.ErrInvalidToken@@ -124,7 +123,7 @@ func (s *SessionService) RotateRefreshToken(ctx context.Context, sessionID strin"user_agent": mo.EmptyableToOption(strings.TrimSpace(meta.UserAgent)).ToPointer(),"ip_address": mo.EmptyableToOption(strings.TrimSpace(meta.IPAddress)).ToPointer(),}- result := tx.Model(&models.UserSession{}).+ result := tx.Model(&UserSession{}).Where("id = ? AND refresh_token_hash = ? AND revoked_at IS NULL", session.ID, session.RefreshTokenHash).Updates(updates)if result.Error != nil {@@ -155,7 +154,7 @@ func (s *SessionService) RevokeSession(ctx context.Context, sessionID string) er}now := time.Now()- if err := s.db.WithContext(ctx).Model(&models.UserSession{}).+ if err := s.db.WithContext(ctx).Model(&UserSession{}).Where("id = ? AND revoked_at IS NULL", sessionID).Updates(map[string]any{"revoked_at": now, "updated_at": now}).Error; err != nil {return errors.WrapIf(err, "failed to revoke user session")@@ -168,7 +167,7 @@ func (s *SessionService) DeleteExpiredSessions(ctx context.Context, revokedRetenrevokedCutoff := now.Add(-revokedRetention)result := s.db.WithContext(ctx).Where("expires_at < ? OR (revoked_at IS NOT NULL AND revoked_at < ?)", now, revokedCutoff).- Delete(&models.UserSession{})+ Delete(&UserSession{})if result.Error != nil {return 0, errors.WrapIf(result.Error, "failed to delete expired user sessions")}@@ -193,7 +192,7 @@ func RevokeAllUserSessionsExceptInDB(ctx context.Context, db *gorm.DB, userID, e}now := time.Now()- query := db.WithContext(ctx).Model(&models.UserSession{}).+ query := db.WithContext(ctx).Model(&UserSession{}).Where("user_id = ? AND revoked_at IS NULL", userID)if strings.TrimSpace(exceptSessionID) != "" {query = query.Where("id <> ?", exceptSessionID)@@ -205,7 +204,7 @@ func RevokeAllUserSessionsExceptInDB(ctx context.Context, db *gorm.DB, userID, e}// ValidateActive verifies that a persisted user session can still authorize requests.-func ValidateActive(userSession *models.UserSession) error {+func ValidateActive(userSession *UserSession) error {if userSession == nil {return common.ErrInvalidToken}diff --git a/backend/internal/session/service_test.go b/backend/internal/session/service_test.goindex 08a01eba4..103c31faa 100644--- a/backend/internal/session/service_test.go+++ b/backend/internal/session/service_test.go@@ -1,13 +1,16 @@package sessionimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/role"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""testing""time""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/types/v2/auth""github.com/libtnb/sqlite""github.com/stretchr/testify/require"@@ -17,8 +20,8 @@ import (func TestSessionService_RotateRefreshTokenRequiresCurrentHash(t *testing.T) {ctx := context.Background()db := setupAuthServiceTestDB(t)- require.NoError(t, db.Create(&models.User{- BaseModel: models.BaseModel{ID: "u-session"},+ require.NoError(t, db.Create(&common.User{+ BaseModel: database.BaseModel{ID: "u-session"},Username: "session-user",}).Error)@@ -39,8 +42,8 @@ func TestSessionService_RotateRefreshTokenRequiresCurrentHash(t *testing.T) {func TestSessionService_DeleteExpiredSessions(t *testing.T) {ctx := context.Background()db := setupAuthServiceTestDB(t)- require.NoError(t, db.Create(&models.User{- BaseModel: models.BaseModel{ID: "u-cleanup"},+ require.NoError(t, db.Create(&common.User{+ BaseModel: database.BaseModel{ID: "u-cleanup"},Username: "cleanup-user",}).Error)@@ -53,7 +56,7 @@ func TestSessionService_DeleteExpiredSessions(t *testing.T) {require.NoError(t, err)oldRevokedAt := time.Now().Add(-8 * 24 * time.Hour)- require.NoError(t, db.WithContext(ctx).Model(&models.UserSession{}).+ require.NoError(t, db.WithContext(ctx).Model(&UserSession{}).Where("id = ?", oldRevoked.ID).Update("revoked_at", oldRevokedAt).Error)@@ -61,13 +64,13 @@ func TestSessionService_DeleteExpiredSessions(t *testing.T) {require.NoError(t, err)require.EqualValues(t, 2, deleted)- var remaining []models.UserSession+ var remaining []UserSessionrequire.NoError(t, db.WithContext(ctx).Order("id").Find(&remaining).Error)require.Len(t, remaining, 1)require.Equal(t, active.ID, remaining[0].ID)var deletedCount int64- require.NoError(t, db.WithContext(ctx).Model(&models.UserSession{}).+ require.NoError(t, db.WithContext(ctx).Model(&UserSession{}).Where("id IN ?", []string{expired.ID, oldRevoked.ID}).Count(&deletedCount).Error)require.Zero(t, deletedCount)@@ -78,15 +81,17 @@ func setupAuthServiceTestDB(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.SettingVariable{},- &models.User{},- &models.UserSession{},- &models.Environment{},- &models.Role{},- &models.UserRoleAssignment{},- &models.ApiKey{},- &models.ApiKeyPermission{},- &models.OidcRoleMapping{},+ &settings.SettingVariable{},+ &common.User{},+ &UserSession{},+ &role.Role{},+ &role.UserRoleAssignment{},+ &role.ApiKeyPermission{},+ &role.OidcRoleMapping{},))+ // environments and api_keys live in packages that import this one; the+ // in-package tests only need the tables to exist.+ require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS environments (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, api_url text, status text, enabled numeric, is_edge numeric, hidden numeric, last_seen datetime, last_edge_transport text, access_token text, api_key_id text, parent_environment_id text, swarm_node_id text)").Error)+ require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, description text, key_hash text, key_prefix text, kind text, user_id text, environment_id text, managed_by text, expires_at datetime, last_used_at datetime)").Error)return &database.DB{DB: db}}diff --git a/backend/internal/settings/handler.go b/backend/internal/settings/handler.goindex 38993fb7e..54bc92092 100644--- a/backend/internal/settings/handler.go+++ b/backend/internal/settings/handler.go@@ -1,6 +1,8 @@package settingsimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""net/http"@@ -8,14 +10,11 @@ import ("strconv""strings"- "github.com/getarcaneapp/arcane/backend/v2/internal/search"-"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -36,7 +35,7 @@ const (// SettingsHandler provides Huma-based settings management endpoints.type SettingsHandler struct {settingsService *SettingsService- settingsSearchService *search.SettingsSearchService+ settingsSearchService *SettingsSearchServiceproxyRemoteJSON handlerutil.RemoteJSONProxycfg *config.Config}@@ -121,7 +120,7 @@ func validateAbsoluteDirectoryPathInternal(path string) error {}// RegisterSettings registers settings management routes using Huma.-func RegisterSettings(api huma.API, settingsService *SettingsService, settingsSearchService *search.SettingsSearchService, proxyRemoteJSON handlerutil.RemoteJSONProxy, cfg *config.Config) {+func RegisterSettings(api huma.API, settingsService *SettingsService, settingsSearchService *SettingsSearchService, proxyRemoteJSON handlerutil.RemoteJSONProxy, cfg *config.Config) {h := &SettingsHandler{settingsService: settingsService,settingsSearchService: settingsSearchService,@@ -284,7 +283,7 @@ func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublireturn &GetPublicSettingsOutput{Body: *settingsDto}, nil}- settingsList := h.settingsService.ListSettings(models.SettingVisibilityPublic)+ settingsList := h.settingsService.ListSettings(SettingVisibilityPublic)var settingsDto []settingstypes.PublicSettingif err := mapper.MapStructList(settingsList, &settingsDto); err != nil {@@ -298,9 +297,9 @@ func (h *SettingsHandler) GetPublicSettings(ctx context.Context, input *GetPublifunc (h *SettingsHandler) GetSettings(ctx context.Context, input *GetSettingsInput) (*GetSettingsOutput, error) {ps, _ := middleware.PermissionsFromContext(ctx)isAdmin := ps.IsGlobalAdmin()- visibility := models.SettingVisibilityNonAdmin+ visibility := SettingVisibilityNonAdminif isAdmin {- visibility = models.SettingVisibilityAll+ visibility = SettingVisibilityAll}if input.EnvironmentID != "0" {@@ -417,7 +416,7 @@ func (h *SettingsHandler) updateSettingsForLocalEnvironment(ctx context.Context,updatedSettings, err := h.settingsService.UpdateSettings(ctx, input)if err != nil {- apiErr := models.ToAPIError(err)+ apiErr := common.ToAPIError(err)if apiErr.HTTPStatus() == http.StatusInternalServerError {return nil, huma.Error500InternalServerError("Failed to update settings")}diff --git a/backend/internal/models/settings.go b/backend/internal/settings/model.gosimilarity index 99%rename from backend/internal/models/settings.gorename to backend/internal/settings/model.goindex b153ba23a..ce107a503 100644--- a/backend/internal/models/settings.go+++ b/backend/internal/settings/model.go@@ -1,4 +1,4 @@-package models+package settingsimport ("reflect"diff --git a/backend/internal/models/settings_test.go b/backend/internal/settings/model_test.gosimilarity index 99%rename from backend/internal/models/settings_test.gorename to backend/internal/settings/model_test.goindex 19a4c1ed0..462fde51d 100644--- a/backend/internal/models/settings_test.go+++ b/backend/internal/settings/model_test.go@@ -1,4 +1,4 @@-package models+package settingsimport ("testing"diff --git a/backend/internal/settings/module.go b/backend/internal/settings/module.goindex 46cef6cdf..ca502fb5b 100644--- a/backend/internal/settings/module.go+++ b/backend/internal/settings/module.go@@ -4,13 +4,12 @@ package settingsimport ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/config"- "github.com/getarcaneapp/arcane/backend/v2/internal/search""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil")// Dependencies are the handler-side collaborators for the settings domain.type Dependencies struct {- Search *search.SettingsSearchService+ Search *SettingsSearchServiceProxyRemoteJSON handlerutil.RemoteJSONProxyConfig *config.Config}diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.goindex f3df589ae..d8ea03c07 100644--- a/backend/internal/settings/service.go+++ b/backend/internal/settings/service.go@@ -24,7 +24,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -42,14 +41,14 @@ const (type SettingsService struct {db *database.DB- config atomic.Pointer[models.Settings]+ config atomic.Pointer[Settings]// effectiveConfig is the env-override-applied snapshot, rebuilt whenever// config is stored. Overrides are resolved once at startup and never// change, so materializing them here turns every read (GetSettings and// the typed getters — ~100 call sites, some in per-project loops) into a// pointer load instead of a full struct Clone plus a reflection pass.// The snapshot is shared: readers must never mutate it.- effectiveConfig atomic.Pointer[models.Settings]+ effectiveConfig atomic.Pointer[Settings]envOverrides []settingsEnvOverridewrites *actors.Executoreffects *actors.Executor@@ -58,7 +57,7 @@ type SettingsService struct {}type settingsUpdateResultInternal struct {- settings []models.SettingVariable+ settings []SettingVariablechanges []libarcane.SettingUpdate}@@ -156,7 +155,7 @@ func (s *SettingsService) NotifySettingsChanges(ctx context.Context, keys ...strreturn err}-func (s *SettingsService) GetSettingsConfig() *models.Settings {+func (s *SettingsService) GetSettingsConfig() *Settings {v := s.config.Load()if v == nil {panic("GetSettingsConfig called before Settings has been loaded")@@ -188,116 +187,116 @@ func (s *SettingsService) refreshSettingsCacheInternal(ctx context.Context) erroreturn nil}-func (s *SettingsService) getDefaultSettings() *models.Settings {+func (s *SettingsService) getDefaultSettings() *Settings {return DefaultSettingsConfig()}// DefaultSettingsConfig returns the canonical default settings model used by Arcane.-func DefaultSettingsConfig() *models.Settings {- return &models.Settings{- ProjectsDirectory: models.SettingVariable{Value: "/app/data/projects"},- TemplatesDirectory: models.SettingVariable{Value: "/app/data/templates"},- FollowProjectSymlinks: models.SettingVariable{Value: "false"},- SwarmStackSourcesDirectory: models.SettingVariable{Value: "/app/data/swarm/sources"},- DiskUsagePath: models.SettingVariable{Value: "/app/data/projects"},- AutoUpdate: models.SettingVariable{Value: "false"},- AutoUpdateInterval: models.SettingVariable{Value: "0 0 0 * * *"},- AutoUpdateExcludedContainers: models.SettingVariable{Value: ""},- PollingEnabled: models.SettingVariable{Value: "true"},- PollingInterval: models.SettingVariable{Value: "0 0 * * * *"},- ImageEventWatcherEnabled: models.SettingVariable{Value: "false"},- DockerClientRefreshInterval: models.SettingVariable{Value: "*/30 * * * * *"},- EventCleanupInterval: models.SettingVariable{Value: "0 0 */6 * * *"},- ExpiredSessionsCleanupInterval: models.SettingVariable{Value: "0 0 0 * * *"},- ActivityHistoryRetentionDays: models.SettingVariable{Value: "30"},- ActivityHistoryMaxEntries: models.SettingVariable{Value: "1000"},- MaxConcurrentActivities: models.SettingVariable{Value: "5"},- AutoInjectEnv: models.SettingVariable{Value: "false"},- DefaultDeployPullPolicy: models.SettingVariable{Value: "missing"},- ScheduledPruneEnabled: models.SettingVariable{Value: "false"},- ScheduledPruneInterval: models.SettingVariable{Value: "0 0 0 * * *"},- PruneContainerMode: models.SettingVariable{Value: "stopped"},- PruneContainerUntil: models.SettingVariable{Value: ""},- PruneImageMode: models.SettingVariable{Value: "dangling"},- PruneImageUntil: models.SettingVariable{Value: ""},- PruneVolumeMode: models.SettingVariable{Value: "none"},- PruneNetworkMode: models.SettingVariable{Value: "unused"},- PruneNetworkUntil: models.SettingVariable{Value: ""},- PruneBuildCacheMode: models.SettingVariable{Value: "none"},- PruneBuildCacheUntil: models.SettingVariable{Value: ""},- AutoHealEnabled: models.SettingVariable{Value: "false"},- AutoHealInterval: models.SettingVariable{Value: "*/30 * * * * *"},- AutoHealExcludedContainers: models.SettingVariable{Value: ""},- AutoHealMaxRestarts: models.SettingVariable{Value: "5"},- AutoHealRestartWindow: models.SettingVariable{Value: "30"},- VolumeHelperIdleTimeout: models.SettingVariable{Value: "10"},- BaseServerURL: models.SettingVariable{Value: "http://localhost"},- EnableGravatar: models.SettingVariable{Value: "true"},- AvatarMaxUploadSizeMb: models.SettingVariable{Value: "2"},- DefaultShell: models.SettingVariable{Value: "/bin/sh"},- DockerHost: models.SettingVariable{Value: "unix:///var/run/docker.sock"},- BuildsDirectory: models.SettingVariable{Value: "/builds"},- AuthLocalEnabled: models.SettingVariable{Value: "true"},- AuthSessionTimeout: models.SettingVariable{Value: "1440"},- AuthPasswordPolicy: models.SettingVariable{Value: "strong"},- VulnerabilityScanEnabled: models.SettingVariable{Value: "false"},- VulnerabilityScanInterval: models.SettingVariable{Value: "0 0 0 * * *"},- TrivyImage: models.SettingVariable{Value: DefaultTrivyImage},- TrivyNetwork: models.SettingVariable{Value: ""},- TrivySecurityOpts: models.SettingVariable{Value: ""},- TrivyPrivileged: models.SettingVariable{Value: "false"},- TrivyPreserveCacheOnVolumePrune: models.SettingVariable{Value: "true"},- TrivyResourceLimitsEnabled: models.SettingVariable{Value: "true"},- TrivyCpuLimit: models.SettingVariable{Value: "1"},- TrivyMemoryLimitMb: models.SettingVariable{Value: "0"},- TrivyConcurrentScanContainers: models.SettingVariable{Value: "1"},- TrivyServerEnabled: models.SettingVariable{Value: "false"},- TrivyServerUrl: models.SettingVariable{Value: ""},- TrivyServerToken: models.SettingVariable{Value: ""},- TrivyIgnoreUnfixed: models.SettingVariable{Value: "true"},- OidcEnabled: models.SettingVariable{Value: "false"},- OidcClientId: models.SettingVariable{Value: ""},- OidcClientSecret: models.SettingVariable{Value: ""},- OidcIssuerUrl: models.SettingVariable{Value: ""},- OidcAuthorizationEndpoint: models.SettingVariable{Value: ""},- OidcTokenEndpoint: models.SettingVariable{Value: ""},- OidcUserinfoEndpoint: models.SettingVariable{Value: ""},- OidcJwksEndpoint: models.SettingVariable{Value: ""},- OidcScopes: models.SettingVariable{Value: "openid email profile"},- OidcGroupsClaim: models.SettingVariable{Value: "groups"},- OidcSkipTlsVerify: models.SettingVariable{Value: "false"},- OidcAutoRedirectToProvider: models.SettingVariable{Value: "false"},- OidcMergeAccounts: models.SettingVariable{Value: "false"},- OidcProviderName: models.SettingVariable{Value: ""},- OidcProviderLogoUrl: models.SettingVariable{Value: ""},- OidcMobileRedirectUris: models.SettingVariable{Value: "arcane-mobile://oidc-callback"},- MaxImageUploadSize: models.SettingVariable{Value: "500"},- GitSyncMaxFiles: models.SettingVariable{Value: "500"},- GitSyncMaxTotalSizeMb: models.SettingVariable{Value: "50"},- GitSyncMaxBinarySizeMb: models.SettingVariable{Value: "10"},- EnvironmentHealthInterval: models.SettingVariable{Value: "0 */2 * * * *"},- LifecycleEnabled: models.SettingVariable{Value: "false"},- LifecycleDefaultRunnerImage: models.SettingVariable{Value: "alpine:latest"},- LifecycleMaxTimeoutSec: models.SettingVariable{Value: "300"},-- DockerAPITimeout: models.SettingVariable{Value: "30"},- DockerImagePullTimeout: models.SettingVariable{Value: "600"},- TrivyScanTimeout: models.SettingVariable{Value: "900"},- GitOperationTimeout: models.SettingVariable{Value: "300"},- HTTPClientTimeout: models.SettingVariable{Value: "30"},- RegistryTimeout: models.SettingVariable{Value: "30"},- ProxyRequestTimeout: models.SettingVariable{Value: "60"},- DeployWaitTimeout: models.SettingVariable{Value: "600"},- BuildProvider: models.SettingVariable{Value: "local"},- BuildTimeout: models.SettingVariable{Value: "1800"},- DepotProjectId: models.SettingVariable{Value: ""},- DepotToken: models.SettingVariable{Value: ""},-- InstanceID: models.SettingVariable{Value: ""},+func DefaultSettingsConfig() *Settings {+ return &Settings{+ ProjectsDirectory: SettingVariable{Value: "/app/data/projects"},+ TemplatesDirectory: SettingVariable{Value: "/app/data/templates"},+ FollowProjectSymlinks: SettingVariable{Value: "false"},+ SwarmStackSourcesDirectory: SettingVariable{Value: "/app/data/swarm/sources"},+ DiskUsagePath: SettingVariable{Value: "/app/data/projects"},+ AutoUpdate: SettingVariable{Value: "false"},+ AutoUpdateInterval: SettingVariable{Value: "0 0 0 * * *"},+ AutoUpdateExcludedContainers: SettingVariable{Value: ""},+ PollingEnabled: SettingVariable{Value: "true"},+ PollingInterval: SettingVariable{Value: "0 0 * * * *"},+ ImageEventWatcherEnabled: SettingVariable{Value: "false"},+ DockerClientRefreshInterval: SettingVariable{Value: "*/30 * * * * *"},+ EventCleanupInterval: SettingVariable{Value: "0 0 */6 * * *"},+ ExpiredSessionsCleanupInterval: SettingVariable{Value: "0 0 0 * * *"},+ ActivityHistoryRetentionDays: SettingVariable{Value: "30"},+ ActivityHistoryMaxEntries: SettingVariable{Value: "1000"},+ MaxConcurrentActivities: SettingVariable{Value: "5"},+ AutoInjectEnv: SettingVariable{Value: "false"},+ DefaultDeployPullPolicy: SettingVariable{Value: "missing"},+ ScheduledPruneEnabled: SettingVariable{Value: "false"},+ ScheduledPruneInterval: SettingVariable{Value: "0 0 0 * * *"},+ PruneContainerMode: SettingVariable{Value: "stopped"},+ PruneContainerUntil: SettingVariable{Value: ""},+ PruneImageMode: SettingVariable{Value: "dangling"},+ PruneImageUntil: SettingVariable{Value: ""},+ PruneVolumeMode: SettingVariable{Value: "none"},+ PruneNetworkMode: SettingVariable{Value: "unused"},+ PruneNetworkUntil: SettingVariable{Value: ""},+ PruneBuildCacheMode: SettingVariable{Value: "none"},+ PruneBuildCacheUntil: SettingVariable{Value: ""},+ AutoHealEnabled: SettingVariable{Value: "false"},+ AutoHealInterval: SettingVariable{Value: "*/30 * * * * *"},+ AutoHealExcludedContainers: SettingVariable{Value: ""},+ AutoHealMaxRestarts: SettingVariable{Value: "5"},+ AutoHealRestartWindow: SettingVariable{Value: "30"},+ VolumeHelperIdleTimeout: SettingVariable{Value: "10"},+ BaseServerURL: SettingVariable{Value: "http://localhost"},+ EnableGravatar: SettingVariable{Value: "true"},+ AvatarMaxUploadSizeMb: SettingVariable{Value: "2"},+ DefaultShell: SettingVariable{Value: "/bin/sh"},+ DockerHost: SettingVariable{Value: "unix:///var/run/docker.sock"},+ BuildsDirectory: SettingVariable{Value: "/builds"},+ AuthLocalEnabled: SettingVariable{Value: "true"},+ AuthSessionTimeout: SettingVariable{Value: "1440"},+ AuthPasswordPolicy: SettingVariable{Value: "strong"},+ VulnerabilityScanEnabled: SettingVariable{Value: "false"},+ VulnerabilityScanInterval: SettingVariable{Value: "0 0 0 * * *"},+ TrivyImage: SettingVariable{Value: DefaultTrivyImage},+ TrivyNetwork: SettingVariable{Value: ""},+ TrivySecurityOpts: SettingVariable{Value: ""},+ TrivyPrivileged: SettingVariable{Value: "false"},+ TrivyPreserveCacheOnVolumePrune: SettingVariable{Value: "true"},+ TrivyResourceLimitsEnabled: SettingVariable{Value: "true"},+ TrivyCpuLimit: SettingVariable{Value: "1"},+ TrivyMemoryLimitMb: SettingVariable{Value: "0"},+ TrivyConcurrentScanContainers: SettingVariable{Value: "1"},+ TrivyServerEnabled: SettingVariable{Value: "false"},+ TrivyServerUrl: SettingVariable{Value: ""},+ TrivyServerToken: SettingVariable{Value: ""},+ TrivyIgnoreUnfixed: SettingVariable{Value: "true"},+ OidcEnabled: SettingVariable{Value: "false"},+ OidcClientId: SettingVariable{Value: ""},+ OidcClientSecret: SettingVariable{Value: ""},+ OidcIssuerUrl: SettingVariable{Value: ""},+ OidcAuthorizationEndpoint: SettingVariable{Value: ""},+ OidcTokenEndpoint: SettingVariable{Value: ""},+ OidcUserinfoEndpoint: SettingVariable{Value: ""},+ OidcJwksEndpoint: SettingVariable{Value: ""},+ OidcScopes: SettingVariable{Value: "openid email profile"},+ OidcGroupsClaim: SettingVariable{Value: "groups"},+ OidcSkipTlsVerify: SettingVariable{Value: "false"},+ OidcAutoRedirectToProvider: SettingVariable{Value: "false"},+ OidcMergeAccounts: SettingVariable{Value: "false"},+ OidcProviderName: SettingVariable{Value: ""},+ OidcProviderLogoUrl: SettingVariable{Value: ""},+ OidcMobileRedirectUris: SettingVariable{Value: "arcane-mobile://oidc-callback"},+ MaxImageUploadSize: SettingVariable{Value: "500"},+ GitSyncMaxFiles: SettingVariable{Value: "500"},+ GitSyncMaxTotalSizeMb: SettingVariable{Value: "50"},+ GitSyncMaxBinarySizeMb: SettingVariable{Value: "10"},+ EnvironmentHealthInterval: SettingVariable{Value: "0 */2 * * * *"},+ LifecycleEnabled: SettingVariable{Value: "false"},+ LifecycleDefaultRunnerImage: SettingVariable{Value: "alpine:latest"},+ LifecycleMaxTimeoutSec: SettingVariable{Value: "300"},++ DockerAPITimeout: SettingVariable{Value: "30"},+ DockerImagePullTimeout: SettingVariable{Value: "600"},+ TrivyScanTimeout: SettingVariable{Value: "900"},+ GitOperationTimeout: SettingVariable{Value: "300"},+ HTTPClientTimeout: SettingVariable{Value: "30"},+ RegistryTimeout: SettingVariable{Value: "30"},+ ProxyRequestTimeout: SettingVariable{Value: "60"},+ DeployWaitTimeout: SettingVariable{Value: "600"},+ BuildProvider: SettingVariable{Value: "local"},+ BuildTimeout: SettingVariable{Value: "1800"},+ DepotProjectId: SettingVariable{Value: ""},+ DepotToken: SettingVariable{Value: ""},++ InstanceID: SettingVariable{Value: ""},}}-func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *database.DB) (*models.Settings, error) {+func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *database.DB) (*Settings, error) {if config.Load().UIConfigurationDisabled || config.Load().AgentMode {slog.DebugContext(ctx, "loadDatabaseSettingsInternal: using env path", "UIConfigurationDisabled", config.Load().UIConfigurationDisabled, "AgentMode", config.Load().AgentMode, "Environment", config.Load().Environment)return s.loadDatabaseConfigFromEnv(ctx, db)@@ -305,7 +304,7 @@ func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *dest := s.getDefaultSettings()- var loaded []models.SettingVariable+ var loaded []SettingVariablequeryCtx, queryCancel := context.WithTimeout(ctx, 10*time.Second)defer queryCancel()err := db.@@ -318,7 +317,7 @@ func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *for _, v := range loaded {err = dest.UpdateField(v.Key, v.Value, false)- if err != nil && !errors.Is(err, models.SettingKeyNotFoundError{}) {+ if err != nil && !errors.Is(err, SettingKeyNotFoundError{}) {return nil, errors.WrapIff(err, "failed to process settings for key '%s'", v.Key)}}@@ -329,11 +328,11 @@ func (s *SettingsService) loadDatabaseSettingsInternal(ctx context.Context, db *return dest, nil}-func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *database.DB) (*models.Settings, error) {+func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *database.DB) (*Settings, error) {dest := s.getDefaultSettings()// Fetch all settings once to avoid N+1 queries for internal keys- var allSettings []models.SettingVariable+ var allSettings []SettingVariableif err := db.WithContext(ctx).Find(&allSettings).Error; err != nil {return nil, errors.WrapIf(err, "failed to load settings for env config")}@@ -392,7 +391,7 @@ func (s *SettingsService) loadDatabaseConfigFromEnv(ctx context.Context, db *datreturn dest, nil}-func (s *SettingsService) applyEnvOverrides(ctx context.Context, dest *models.Settings) {+func (s *SettingsService) applyEnvOverrides(ctx context.Context, dest *Settings) {_ = ctxrv := reflect.ValueOf(dest).Elem()@@ -402,7 +401,7 @@ func (s *SettingsService) applyEnvOverrides(ctx context.Context, dest *models.Se}func resolveSettingsEnvOverridesInternal() []settingsEnvOverride {- rt := reflect.TypeFor[models.Settings]()+ rt := reflect.TypeFor[Settings]()overrides := make([]settingsEnvOverride, 0)for i := range rt.NumField() {@@ -450,7 +449,7 @@ func (s *SettingsService) IsEnvOverrideActive(key string) bool {// GetSettings returns the effective (env-override-applied) settings snapshot.// The snapshot is shared across callers and must be treated as read-only;// mutation flows go through UpdateSettings, which works on an explicit clone.-func (s *SettingsService) GetSettings(ctx context.Context) (*models.Settings, error) {+func (s *SettingsService) GetSettings(ctx context.Context) (*Settings, error) {settingsCfg := s.getEffectiveSettingsConfigInternal(ctx)return settingsCfg, nil}@@ -459,18 +458,18 @@ func (s *SettingsService) GetSettings(ctx context.Context) (*models.Settings, er// meaningfully recover from a settings load failure. It logs any error and guarantees a// non-nil *Settings (defaults: a zero-valued struct, which the SettingVariable helpers// like utils.BoolOrDefault treat as "use the caller's default").-func (s *SettingsService) GetSettingsOrDefaults(ctx context.Context) *models.Settings {+func (s *SettingsService) GetSettingsOrDefaults(ctx context.Context) *Settings {cfg, err := s.GetSettings(ctx)if err != nil {slog.WarnContext(ctx, "failed to load settings, falling back to defaults", "error", err)}if cfg == nil {- return &models.Settings{}+ return &Settings{}}return cfg}-func (s *SettingsService) getEffectiveSettingsConfigInternal(ctx context.Context) *models.Settings {+func (s *SettingsService) getEffectiveSettingsConfigInternal(ctx context.Context) *Settings {if effective := s.effectiveConfig.Load(); effective != nil {return effective}@@ -498,9 +497,9 @@ func (s *SettingsService) UpdateSetting(ctx context.Context, key, value string)// UpdateSettingValues persists a group of internal setting values atomically// and publishes the refreshed snapshot before returning.func (s *SettingsService) UpdateSettingValues(ctx context.Context, updates []libarcane.SettingUpdate) error {- values := make([]models.SettingVariable, 0, len(updates))+ values := make([]SettingVariable, 0, len(updates))for _, update := range updates {- values = append(values, models.SettingVariable{Key: update.Key, Value: update.Value})+ values = append(values, SettingVariable{Key: update.Key, Value: update.Value})}_, err := actors.Execute(ctx, s.writes, "update setting values", func(writeCtx context.Context) (actors.NoPayload, error) {if err := s.persistSettings(writeCtx, values); err != nil {@@ -513,7 +512,7 @@ func (s *SettingsService) UpdateSettingValues(ctx context.Context, updates []libfunc (s *SettingsService) updateSettingValueNoRefreshInternal(ctx context.Context, key, value string) error {return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- settingVar := &models.SettingVariable{+ settingVar := &SettingVariable{Key: key,Value: value,}@@ -523,7 +522,7 @@ 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) ([]models.SettingVariable, error) {+func (s *SettingsService) UpdateSettings(ctx context.Context, updates settingstypes.Update) ([]SettingVariable, error) {result, err := actors.Execute(ctx, s.writes, "update settings", func(writeCtx context.Context) (settingsUpdateResultInternal, error) {return s.updateSettingsInternal(writeCtx, updates)}, func(result settingsUpdateResultInternal, err error) {@@ -591,10 +590,10 @@ func (s *SettingsService) updateSettingsInternal(ctx context.Context, updates sereturn settingsUpdateResultInternal{}, err}if updates.OidcClientSecret != nil && *updates.OidcClientSecret != "" {- valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: "oidcClientSecret", Value: *updates.OidcClientSecret})+ valuesToUpdate = append(valuesToUpdate, SettingVariable{Key: "oidcClientSecret", Value: *updates.OidcClientSecret})}if trivyServerTokenUpdated {- valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: "trivyServerToken", Value: *updates.TrivyServerToken})+ valuesToUpdate = append(valuesToUpdate, SettingVariable{Key: "trivyServerToken", Value: *updates.TrivyServerToken})}if err := s.persistSettings(ctx, valuesToUpdate); err != nil {@@ -610,15 +609,15 @@ func (s *SettingsService) updateSettingsInternal(ctx context.Context, updates sechanges = append(changes, libarcane.SettingUpdate{Key: value.Key, Value: value.Value})}return settingsUpdateResultInternal{- settings: settingsCfg.ToSettingVariableSlice(models.SettingVisibilityNonAdmin, false),+ settings: settingsCfg.ToSettingVariableSlice(SettingVisibilityNonAdmin, false),changes: changes,}, nil}-func (s *SettingsService) prepareUpdateValues(updates settingstypes.Update, cfg, defaultCfg *models.Settings) ([]models.SettingVariable, error) {+func (s *SettingsService) prepareUpdateValues(updates settingstypes.Update, cfg, defaultCfg *Settings) ([]SettingVariable, error) {rt := reflect.TypeFor[settingstypes.Update]()rv := reflect.ValueOf(updates)- valuesToUpdate := make([]models.SettingVariable, 0)+ valuesToUpdate := make([]SettingVariable, 0)for i := range rt.NumField() {field := rt.Field(i)@@ -640,7 +639,7 @@ func (s *SettingsService) prepareUpdateValues(updates settingstypes.Update, cfg,return nil, errors.WrapIff(err, "failed to update in-memory config for key '%s'", key)}- valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: key, Value: value})+ valuesToUpdate = append(valuesToUpdate, SettingVariable{Key: key, Value: value})continue}@@ -661,14 +660,14 @@ func (s *SettingsService) prepareUpdateValues(updates settingstypes.Update, cfg,err = cfg.UpdateField(key, value, true)}- if errors.Is(err, models.SettingSensitiveForbiddenError{}) {+ if errors.Is(err, SettingSensitiveForbiddenError{}) {continue}if err != nil {return nil, errors.WrapIff(err, "failed to update in-memory config for key '%s'", key)}- valuesToUpdate = append(valuesToUpdate, models.SettingVariable{Key: key, Value: valueToSave})+ valuesToUpdate = append(valuesToUpdate, SettingVariable{Key: key, Value: valueToSave})}return valuesToUpdate, nil@@ -692,7 +691,7 @@ func extractUpdateValue(field reflect.StructField, fieldValue reflect.Value) (streturn key, value, true}-func (s *SettingsService) persistSettings(ctx context.Context, values []models.SettingVariable) error {+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 err := tx.Save(&setting).Error; err != nil {@@ -706,11 +705,11 @@ func (s *SettingsService) persistSettings(ctx context.Context, values []models.Sfunc (s *SettingsService) EnsureDefaultSettings(ctx context.Context) error {_, err := actors.Execute(ctx, s.writes, "ensure default settings", func(writeCtx context.Context) (actors.NoPayload, error) {defaultSettings := s.getDefaultSettings()- defaultSettingVars := defaultSettings.ToSettingVariableSlice(models.SettingVisibilityAll, false)+ defaultSettingVars := defaultSettings.ToSettingVariableSlice(SettingVisibilityAll, false)if err := s.db.WithContext(writeCtx).Transaction(func(tx *gorm.DB) error {for _, defaultSetting := range defaultSettingVars {- var existing models.SettingVariable+ var existing SettingVariableerr := tx.Where("key = ?", defaultSetting.Key).First(&existing).Errorswitch {@@ -747,7 +746,7 @@ func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {keys = append(keys, key)}- result := s.db.WithContext(writeCtx).Where("key NOT IN ?", keys).Delete(&models.SettingVariable{})+ result := s.db.WithContext(writeCtx).Where("key NOT IN ?", keys).Delete(&SettingVariable{})if result.Error != nil {return actors.NoPayload{}, errors.WrapIf(result.Error, "failed to prune unknown settings")}@@ -761,7 +760,7 @@ func (s *SettingsService) PruneUnknownSettings(ctx context.Context) error {func (s *SettingsService) PersistEnvSettingsIfMissing(ctx context.Context) error {_, err := actors.Execute(ctx, s.writes, "persist environment settings", func(writeCtx context.Context) (actors.NoPayload, error) {- rt := reflect.TypeFor[models.Settings]()+ rt := reflect.TypeFor[Settings]()appCfg := config.Load()isEnvOnlyMode := appCfg.AgentMode || appCfg.UIConfigurationDisabled@@ -783,7 +782,7 @@ func (s *SettingsService) PersistEnvSettingsIfMissing(ctx context.Context) errorfunc allowedSettingKeys() map[string]struct{} {allowed := make(map[string]struct{})- settingsType := reflect.TypeFor[models.Settings]()+ settingsType := reflect.TypeFor[Settings]()for field := range settingsType.Fields() {key, _, _ := strings.Cut(field.Tag.Get("key"), ",")if key == "" {@@ -833,12 +832,12 @@ func (s *SettingsService) shouldProcessField(key, attrs string, isEnvOnlyMode bo}func (s *SettingsService) upsertEnvSetting(ctx context.Context, tx *gorm.DB, key, envVal string) error {- var existing models.SettingVariable+ var existing SettingVariableerr := tx.Where("key = ?", key).First(&existing).Errorswitch {case errors.Is(err, gorm.ErrRecordNotFound):- newVar := models.SettingVariable{Key: key, Value: envVal}+ newVar := SettingVariable{Key: key, Value: envVal}if err := tx.Create(&newVar).Error; err != nil {return errors.WrapIff(err, "persist env setting %s", key)}@@ -857,13 +856,13 @@ func (s *SettingsService) upsertEnvSetting(ctx context.Context, tx *gorm.DB, keyreturn nil}-func (s *SettingsService) ListSettings(visibility models.SettingVisibility) []models.SettingVariable {+func (s *SettingsService) ListSettings(visibility SettingVisibility) []SettingVariable {return s.GetSettingsConfig().ToSettingVariableSlice(visibility, true)}// GetSettingType returns the type from the setting metadatafunc (s *SettingsService) GetSettingType(key string) string {- rt := reflect.TypeFor[models.Settings]()+ rt := reflect.TypeFor[Settings]()for field := range rt.Fields() {keyTag := field.Tag.Get("key")fieldKey, _, _ := strings.Cut(keyTag, ",")@@ -985,7 +984,7 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, errovar key stringerr := s.db.WithContext(writeCtx).Transaction(func(tx *gorm.DB) error {- var sv models.SettingVariable+ var sv SettingVariableerr := tx.Where("key = ?", keyName).First(&sv).Errorif err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {@@ -1007,13 +1006,13 @@ func (s *SettingsService) EnsureEncryptionKey(ctx context.Context) (string, errokey = generatedKeyif notFound {- if createErr := tx.Create(&models.SettingVariable{Key: keyName, Value: generatedKey}).Error; createErr != nil {+ if createErr := tx.Create(&SettingVariable{Key: keyName, Value: generatedKey}).Error; createErr != nil {return errors.WrapIf(createErr, "failed to persist encryption key")}return nil}- if updErr := tx.Model(&models.SettingVariable{}).+ if updErr := tx.Model(&SettingVariable{}).Where("key = ?", keyName).Update("value", generatedKey).Error; updErr != nil {return errors.WrapIf(updErr, "failed to update encryption key")@@ -1035,7 +1034,7 @@ func (s *SettingsService) NormalizeProjectsDirectory(ctx context.Context, projec}_, err := actors.Execute(ctx, s.writes, "normalize projects directory", func(writeCtx context.Context) (string, error) {- var projectsDirSetting models.SettingVariable+ var projectsDirSetting SettingVariableerr := s.db.WithContext(writeCtx).Where("key = ?", "projectsDirectory").First(&projectsDirSetting).Errorif errors.Is(err, gorm.ErrRecordNotFound) {slog.DebugContext(writeCtx, "No projectsDirectory setting found, skipping normalization")@@ -1083,7 +1082,7 @@ func (s *SettingsService) NormalizeBuildsDirectory(ctx context.Context) error {}_, err := actors.Execute(ctx, s.writes, "normalize builds directory", func(writeCtx context.Context) (string, error) {- var buildsDirSetting models.SettingVariable+ var buildsDirSetting SettingVariableerr := s.db.WithContext(writeCtx).Where("key = ?", buildsKey).First(&buildsDirSetting).Errorif errors.Is(err, gorm.ErrRecordNotFound) {slog.DebugContext(writeCtx, "No buildsDirectory setting found, skipping normalization")diff --git a/backend/internal/settings/service_test.go b/backend/internal/settings/service_test.goindex f46f7fb8d..bceb0b7c6 100644--- a/backend/internal/settings/service_test.go+++ b/backend/internal/settings/service_test.go@@ -17,7 +17,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"settingstypes "github.com/getarcaneapp/arcane/types/v2/settings")@@ -26,7 +25,7 @@ func setupSettingsTestDB(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&SettingVariable{}))return &database.DB{DB: db}}@@ -86,18 +85,18 @@ func TestSettingsService_EnsureDefaultSettings_Idempotent(t *testing.T) {require.NoError(t, svc.EnsureDefaultSettings(ctx))var count1 int64- require.NoError(t, svc.db.WithContext(ctx).Model(&models.SettingVariable{}).Count(&count1).Error)+ require.NoError(t, svc.db.WithContext(ctx).Model(&SettingVariable{}).Count(&count1).Error)require.Positive(t, count1)require.NoError(t, svc.EnsureDefaultSettings(ctx))var count2 int64- require.NoError(t, svc.db.WithContext(ctx).Model(&models.SettingVariable{}).Count(&count2).Error)+ require.NoError(t, svc.db.WithContext(ctx).Model(&SettingVariable{}).Count(&count2).Error)require.Equal(t, count1, count2)// Spot-check core and automation defaults exist with correct valuesfor _, key := range []string{"authLocalEnabled", "projectsDirectory", "followProjectSymlinks", "autoUpdateExcludedContainers", "imageEventWatcherEnabled", "vulnerabilityScanEnabled", "vulnerabilityScanInterval", "trivyImage", "trivyNetwork", "trivySecurityOpts", "trivyPrivileged", "trivyPreserveCacheOnVolumePrune", "trivyResourceLimitsEnabled", "trivyCpuLimit", "trivyMemoryLimitMb", "trivyConcurrentScanContainers", "gitSyncMaxFiles", "gitSyncMaxTotalSizeMb", "gitSyncMaxBinarySizeMb", "lifecycleDefaultRunnerImage"} {- var sv models.SettingVariable+ var sv SettingVariableerr := svc.db.WithContext(ctx).Where("key = ?", key).First(&sv).Errorrequire.NoErrorf(t, err, "missing default key %s", key)@@ -154,7 +153,7 @@ func TestSettingsService_ImageEventWatcherSettingPersists(t *testing.T) {require.NoError(t, err)require.True(t, svc.GetBoolSetting(ctx, "imageEventWatcherEnabled", false))- var stored models.SettingVariable+ var stored SettingVariablerequire.NoError(t, db.WithContext(ctx).Where("key = ?", "imageEventWatcherEnabled").First(&stored).Error)require.Equal(t, "true", stored.Value)}@@ -168,7 +167,7 @@ func TestSettingsService_EnsureDefaultSettings_OverridesExistingTrivyImage(t *terequire.NoError(t, svc.UpdateSetting(ctx, "trivyImage", "ghcr.io/aquasecurity/trivy:latest"))require.NoError(t, svc.EnsureDefaultSettings(ctx))- var sv models.SettingVariable+ var sv SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "trivyImage").First(&sv).Error)require.Equal(t, DefaultTrivyImage, sv.Value)}@@ -180,7 +179,7 @@ func TestSettingsService_GetSettings_UnknownKeysIgnored(t *testing.T) {require.NoError(t, err)require.NoError(t, svc.db.WithContext(ctx).- Create(&models.SettingVariable{Key: "someUnknownKey", Value: "x"}).Error)+ Create(&SettingVariable{Key: "someUnknownKey", Value: "x"}).Error)_, err = svc.GetSettings(ctx)require.NoError(t, err)@@ -350,15 +349,15 @@ func TestSettingsService_PruneUnknownSettings_RemovesStaleKeys(t *testing.T) {require.NoError(t, svc.PruneUnknownSettings(ctx))- var sv models.SettingVariable+ var sv SettingVariableerr = svc.db.WithContext(ctx).Where("key = ?", "unknownKey").First(&sv).Errorrequire.ErrorIs(t, err, gorm.ErrRecordNotFound)- var sv2 models.SettingVariable+ var sv2 SettingVariableerr = svc.db.WithContext(ctx).Where("key = ?", "projectsDirectory").First(&sv2).Errorrequire.NoError(t, err)- var sv3 models.SettingVariable+ var sv3 SettingVariableerr = svc.db.WithContext(ctx).Where("key = ?", "encryptionKey").First(&sv3).Errorrequire.NoError(t, err)}@@ -515,7 +514,7 @@ func TestSettingsService_UpdateSetting(t *testing.T) {require.NoError(t, svc.UpdateSetting(ctx, "pruneImageMode", "all"))- var sv models.SettingVariable+ var sv SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "pruneImageMode").First(&sv).Error)require.Equal(t, "all", sv.Value)}@@ -529,7 +528,7 @@ func TestSettingsService_UpdateSettingRejectsInvalidCronBeforePersistence(t *tesrequire.NoError(t, svc.UpdateSetting(ctx, "pollingInterval", "*/5 * * * * *"))require.Error(t, svc.UpdateSetting(ctx, "pollingInterval", "not a cron schedule"))- var setting models.SettingVariable+ var setting SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "pollingInterval").First(&setting).Error)require.Equal(t, "*/5 * * * * *", setting.Value)}@@ -727,7 +726,7 @@ func BenchmarkSettingsService_GetSettings(b *testing.B) {if err != nil {require.FailNowf(b, "benchmark database setup failed", "%v", err)}- if err := db.AutoMigrate(&models.SettingVariable{}); err != nil {+ if err := db.AutoMigrate(&SettingVariable{}); err != nil {require.FailNowf(b, "benchmark database migration failed", "%v", err)}settingsDB := &database.DB{DB: db}@@ -764,7 +763,7 @@ func TestSettingsService_EnsureEncryptionKey(t *testing.T) {require.NoError(t, err)require.Equal(t, k1, k2, "encryption key should be stable between calls")- var sv models.SettingVariable+ var sv SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "encryptionKey").First(&sv).Error)require.Equal(t, k1, sv.Value)}@@ -821,7 +820,7 @@ func TestSettingsService_PersistEnvSettingsIfMissing_DoesNotOverrideForcedTrivyIrequire.NoError(t, svc.PersistEnvSettingsIfMissing(ctx))- var sv models.SettingVariable+ var sv SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "trivyImage").First(&sv).Error)require.Equal(t, DefaultTrivyImage, sv.Value)require.Equal(t, DefaultTrivyImage, svc.GetSettingsConfig().TrivyImage.Value)@@ -843,7 +842,7 @@ func TestSettingsService_UpdateSettings_RefreshesCache(t *testing.T) {require.NoError(t, err)// ListSettings uses the cached snapshot; should reflect updated value- list := svc.ListSettings(models.SettingVisibilityAll)+ list := svc.ListSettings(SettingVisibilityAll)found := falsefor _, sv := range list {if sv.Key == "projectsDirectory" {@@ -1036,7 +1035,7 @@ func TestSettingsService_UpdateSettings_TrivyPreserveCacheOnVolumePrunePersists(require.NoError(t, err)require.False(t, current.TrivyPreserveCacheOnVolumePrune.IsTrue())- var stored models.SettingVariable+ var stored SettingVariableerr = svc.db.WithContext(ctx).Where("key = ?", "trivyPreserveCacheOnVolumePrune").First(&stored).Errorrequire.NoError(t, err)require.Equal(t, "false", stored.Value)@@ -1070,7 +1069,7 @@ func TestSettingsService_LoadDatabaseSettings_InternalKeys_EnvMode(t *testing.T)// Pre-populate an internal setting in the DBinternalKey := "instanceId"internalVal := "test-instance-id"- require.NoError(t, db.DB.Create(&models.SettingVariable{Key: internalKey, Value: internalVal}).Error)+ require.NoError(t, db.DB.Create(&SettingVariable{Key: internalKey, Value: internalVal}).Error)svc, err := newSettingsServiceForTestInternal(t, ctx, db)require.NoError(t, err)@@ -1097,7 +1096,7 @@ func TestSettingsService_NormalizeProjectsDirectory_ConvertsRelativeToAbsolute(trequire.NoError(t, err)// Verify it was updated to absolute path- var setting models.SettingVariable+ var setting SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "projectsDirectory").First(&setting).Error)// Should be converted to absolute path@@ -1120,7 +1119,7 @@ func TestSettingsService_NormalizeProjectsDirectory_SkipsWhenEnvSet(t *testing.Trequire.NoError(t, err)// Verify it was NOT changed- var setting models.SettingVariable+ var setting SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "projectsDirectory").First(&setting).Error)require.Equal(t, "data/projects", setting.Value, "should not change when env var is set")}@@ -1139,7 +1138,7 @@ func TestSettingsService_NormalizeProjectsDirectory_LeavesOtherPathsUnchanged(trequire.NoError(t, err)// Verify it was NOT changed- var setting models.SettingVariable+ var setting SettingVariablerequire.NoError(t, svc.db.WithContext(ctx).Where("key = ?", "projectsDirectory").First(&setting).Error)require.Equal(t, customPath, setting.Value, "should not change custom paths")}@@ -1214,8 +1213,8 @@ func TestSettingsServiceEffectiveSnapshotMaterializedInternal(t *testing.T) {t.Setenv("PROJECTS_DIRECTORY", "/env/projects")db := setupSettingsTestDB(t)- require.NoError(t, db.Create(&models.SettingVariable{Key: "projectsDirectory", Value: "/db/projects"}).Error)- require.NoError(t, db.Create(&models.SettingVariable{Key: "baseServerUrl", Value: "http://before.example"}).Error)+ require.NoError(t, db.Create(&SettingVariable{Key: "projectsDirectory", Value: "/db/projects"}).Error)+ require.NoError(t, db.Create(&SettingVariable{Key: "baseServerUrl", Value: "http://before.example"}).Error)svc, err := newSettingsServiceForTestInternal(t, ctx, db)require.NoError(t, err)diff --git a/backend/internal/search/settings_service.go b/backend/internal/settings/settings_search.gosimilarity index 97%rename from backend/internal/search/settings_service.gorename to backend/internal/settings/settings_search.goindex faac25d45..472850445 100644--- a/backend/internal/search/settings_service.go+++ b/backend/internal/settings/settings_search.go@@ -1,4 +1,4 @@-package search+package settingsimport ("reflect"@@ -7,7 +7,6 @@ import ("strings""sync"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/types/v2/category""github.com/getarcaneapp/arcane/types/v2/meta"@@ -38,13 +37,13 @@ func (s *SettingsSearchService) GetSettingsCategories() []category.Category {func (s *SettingsSearchService) buildCategoriesFromModel() []category.Category {// Extract category metadata from struct tags (catmeta)- catMetaMap := utils.ExtractCategoryMetadata(models.Settings{}, nil)+ catMetaMap := utils.ExtractCategoryMetadata(Settings{}, nil)// map category id -> list of settingscategories := map[string][]meta.Metadata{}var categoryOrder []string // Track order from first appearance in struct- rt := reflect.TypeFor[models.Settings]()+ rt := reflect.TypeFor[Settings]()for field := range rt.Fields() {keyTag := field.Tag.Get("key")key, _, _ := strings.Cut(keyTag, ",")diff --git a/backend/internal/swarm/handler.go b/backend/internal/swarm/handler.goindex 64c875272..9315dd315 100644--- a/backend/internal/swarm/handler.go+++ b/backend/internal/swarm/handler.go@@ -1,6 +1,8 @@package swarmimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""log/slog""maps"@@ -15,7 +17,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -1831,7 +1832,7 @@ func (h *SwarmHandler) auditSwarmMutation(ctx context.Context, environmentID, acvar userID *stringvar username *string- if user, ok := models.CurrentUserFromContext(ctx); ok {+ if user, ok := common.CurrentUserFromContext(ctx); ok {userID = new(user.ID)username = new(user.Username)}@@ -1855,12 +1856,12 @@ func (h *SwarmHandler) auditSwarmMutation(ctx context.Context, environmentID, ac}envPtr := &env- meta := models.JSON{"action": action}+ meta := database.JSON{"action": action}maps.Copy(meta, metadata)_, err := h.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventType("swarm." + action),- Severity: models.EventSeverityInfo,+ Type: event.EventType("swarm." + action),+ Severity: event.EventSeverityInfo,Title: "Swarm operation: " + action,Description: "Swarm operation '" + action + "' completed",ResourceType: resourceTypePtr,diff --git a/backend/internal/swarm/service_test.go b/backend/internal/swarm/service_test.goindex b36dc03bb..5215fcb9c 100644--- a/backend/internal/swarm/service_test.go+++ b/backend/internal/swarm/service_test.go@@ -15,7 +15,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"swarmtypes "github.com/getarcaneapp/arcane/types/v2/swarm""github.com/libtnb/sqlite"@@ -32,7 +31,7 @@ func setupSwarmServiceTestDBInternal(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}, &models.Environment{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}, &environment.Environment{}))return &database.DB{DB: db}}@@ -58,8 +57,8 @@ func newSettingsServiceForSwarmTestInternal(t testing.TB, ctx context.Context, dfunc createSwarmTestEnvironmentInternal(t *testing.T, db *database.DB, id, apiURL, status string, isEdge bool, accessToken *string) {t.Helper()now := time.Now()- require.NoError(t, db.Create(&models.Environment{- BaseModel: models.BaseModel{ID: id, CreatedAt: now, UpdatedAt: &now},+ require.NoError(t, db.Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: id, CreatedAt: now, UpdatedAt: &now},Name: "env-" + id,ApiUrl: apiURL,Status: status,@@ -131,7 +130,7 @@ func TestSwarmService_FetchSwarmNodeIdentityViaEdgeInternal_UsesEnvironmentAccesdb,"env-1",server.URL,- string(models.EnvironmentStatusOnline),+ string(environment.EnvironmentStatusOnline),false,&accessToken,)@@ -430,37 +429,37 @@ func TestSwarmService_BuildNodeAgentStatusInternal(t *testing.T) {tests := []struct {name string- env *models.Environment+ env *environment.Environmentruntime swarmNodeAgentRuntimewant swarmtypes.NodeAgentState}{{name: "poll-mode check-in reports connected despite stale pending status",- env: &models.Environment{Status: string(models.EnvironmentStatusPending)},+ env: &environment.Environment{Status: string(environment.EnvironmentStatusPending)},runtime: swarmNodeAgentRuntime{lastPollAt: &now},want: swarmtypes.NodeAgentStateConnected,},{name: "no runtime activity and never paired stays pending",- env: &models.Environment{Status: string(models.EnvironmentStatusPending)},+ env: &environment.Environment{Status: string(environment.EnvironmentStatusPending)},runtime: swarmNodeAgentRuntime{},want: swarmtypes.NodeAgentStatePending,},{name: "tunnel with mismatched identity reports mismatched",- env: &models.Environment{Status: string(models.EnvironmentStatusOnline)},+ env: &environment.Environment{Status: string(environment.EnvironmentStatusOnline)},runtime: swarmNodeAgentRuntime{connected: true, identity: &SwarmNodeIdentity{SwarmNodeID: "other-node", SwarmActive: true}},want: swarmtypes.NodeAgentStateMismatched,},{name: "tunnel connected without identity probe reports connected",- env: &models.Environment{Status: string(models.EnvironmentStatusPending)},+ env: &environment.Environment{Status: string(environment.EnvironmentStatusPending)},runtime: swarmNodeAgentRuntime{connected: true},want: swarmtypes.NodeAgentStateConnected,},{name: "previously seen agent with no activity reports offline",- env: &models.Environment{Status: string(models.EnvironmentStatusOnline), LastSeen: &now},+ env: &environment.Environment{Status: string(environment.EnvironmentStatusOnline), LastSeen: &now},runtime: swarmNodeAgentRuntime{},want: swarmtypes.NodeAgentStateOffline,},diff --git a/backend/internal/swarm/swarm.go b/backend/internal/swarm/swarm.goindex f30ff98f3..925168074 100644--- a/backend/internal/swarm/swarm.go+++ b/backend/internal/swarm/swarm.go@@ -25,7 +25,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/edge"@@ -98,8 +97,8 @@ type swarmNodeAgentRuntime struct {type swarmNodeAgentCoverage struct {runtimeByEnvID map[string]swarmNodeAgentRuntime- boundEnvsByNodeID map[string][]models.Environment- candidatesByNodeID map[string][]models.Environment+ boundEnvsByNodeID map[string][]environment.Environment+ candidatesByNodeID map[string][]environment.EnvironmentlocalIdentity *SwarmNodeIdentity// Resolved once per request rather than per node: the name is user-editable, and// applyNodeAgentCoverageInternal runs in a loop with no context to look it up.@@ -612,7 +611,7 @@ func (s *SwarmService) ReconcileNodeAgents(ctx context.Context, environmentID st// BindNodeAgent verifies that a visible environment currently reports the// requested node identity before persisting the binding.-func (s *SwarmService) BindNodeAgent(ctx context.Context, parentEnvironmentID, nodeID string, request swarmtypes.NodeAgentBindingRequest) (*models.Environment, error) {+func (s *SwarmService) BindNodeAgent(ctx context.Context, parentEnvironmentID, nodeID string, request swarmtypes.NodeAgentBindingRequest) (*environment.Environment, error) {environment, err := s.environmentService.GetEnvironmentByID(ctx, request.EnvironmentID)if err != nil {return nil, err@@ -695,7 +694,7 @@ func (s *SwarmService) resolveNodeAgentCoverageInternal(ctx context.Context, envcandidateEnvs = nil}- probeEnvsByID := make(map[string]models.Environment, len(agentEnvs)+len(candidateEnvs))+ probeEnvsByID := make(map[string]environment.Environment, len(agentEnvs)+len(candidateEnvs))for _, env := range candidateEnvs {probeEnvsByID[env.ID] = env}@@ -723,7 +722,7 @@ func (s *SwarmService) resolveNodeAgentCoverageInternal(ctx context.Context, envreturn nil, err}- boundEnvsByNodeID := make(map[string][]models.Environment, len(agentEnvs))+ boundEnvsByNodeID := make(map[string][]environment.Environment, len(agentEnvs))for _, env := range agentEnvs {if env.SwarmNodeID != nil && strings.TrimSpace(*env.SwarmNodeID) != "" {nodeID := strings.TrimSpace(*env.SwarmNodeID)@@ -731,7 +730,7 @@ func (s *SwarmService) resolveNodeAgentCoverageInternal(ctx context.Context, env}}- candidatesByNodeID := make(map[string][]models.Environment)+ candidatesByNodeID := make(map[string][]environment.Environment)for _, env := range candidateEnvs {runtime := runtimeByEnvID[env.ID]if runtime.identity == nil || !runtime.identity.SwarmActive {@@ -796,8 +795,8 @@ func (s *SwarmService) applyNodeAgentCoverageInternal(environmentID string, item}}-func preferredNodeAgentEnvironmentInternal(environments []models.Environment) models.Environment {- var preferred models.Environment+func preferredNodeAgentEnvironmentInternal(environments []environment.Environment) environment.Environment {+ var preferred environment.Environmentfor index, environment := range environments {if index == 0 {preferred = environment@@ -809,7 +808,7 @@ func preferredNodeAgentEnvironmentInternal(environments []models.Environment) moreturn preferred}-func buildNodeAgentCandidatesInternal(environments []models.Environment) []swarmtypes.NodeAgentCandidate {+func buildNodeAgentCandidatesInternal(environments []environment.Environment) []swarmtypes.NodeAgentCandidate {candidates := make([]swarmtypes.NodeAgentCandidate, 0, len(environments))for _, environment := range environments {environmentType := "direct"@@ -825,7 +824,7 @@ func buildNodeAgentCandidatesInternal(environments []models.Environment) []swarmreturn candidates}-func (s *SwarmService) resolveSwarmNodeAgentRuntimeInternal(ctx context.Context, env *models.Environment) swarmNodeAgentRuntime {+func (s *SwarmService) resolveSwarmNodeAgentRuntimeInternal(ctx context.Context, env *environment.Environment) swarmNodeAgentRuntime {if env == nil {return swarmNodeAgentRuntime{}}@@ -1070,7 +1069,7 @@ func (s *SwarmService) fetchSwarmNodeIdentityViaEdgeInternal(ctx context.Contextreturn &parsed.Data, nil}-func (s *SwarmService) buildNodeAgentStatusInternal(nodeID string, env *models.Environment, runtime swarmNodeAgentRuntime) swarmtypes.NodeAgentStatus {+func (s *SwarmService) buildNodeAgentStatusInternal(nodeID string, env *environment.Environment, runtime swarmNodeAgentRuntime) swarmtypes.NodeAgentStatus {if env == nil {return swarmtypes.NodeAgentStatus{State: swarmtypes.NodeAgentStateNone}}@@ -1131,7 +1130,7 @@ func (s *SwarmService) buildNodeAgentStatusInternal(nodeID string, env *models.E}// No live evidence: an unpaired agent stays pending; one seen before is offline.- if env.Status == string(models.EnvironmentStatusPending) || env.LastSeen == nil {+ if env.Status == string(environment.EnvironmentStatusPending) || env.LastSeen == nil {status.State = swarmtypes.NodeAgentStatePendingreturn status}diff --git a/backend/internal/system/handler.go b/backend/internal/system/handler.goindex ba7eec43c..8e5c31bba 100644--- a/backend/internal/system/handler.go+++ b/backend/internal/system/handler.go@@ -18,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"@@ -139,7 +138,7 @@ type TriggerUpdateAllInput struct {}type TriggerUpdateAllOutput struct {- Body base.ApiResponse[models.EnvironmentUpdateJob]+ Body base.ApiResponse[EnvironmentUpdateJob]}type UpdateAllStatusInput struct {@@ -147,7 +146,7 @@ type UpdateAllStatusInput struct {}type UpdateAllStatusOutput struct {- Body base.ApiResponse[models.EnvironmentUpdateJob]+ Body base.ApiResponse[EnvironmentUpdateJob]}// RegisterSystem registers system management endpoints using Huma.@@ -573,7 +572,7 @@ func (h *SystemHandler) TriggerUpdateAll(ctx context.Context, input *TriggerUpda}return &TriggerUpdateAllOutput{- Body: base.ApiResponse[models.EnvironmentUpdateJob]{+ Body: base.ApiResponse[EnvironmentUpdateJob]{Success: true,Data: *job,},@@ -595,7 +594,7 @@ func (h *SystemHandler) GetUpdateAllStatus(ctx context.Context, input *UpdateAll}return &UpdateAllStatusOutput{- Body: base.ApiResponse[models.EnvironmentUpdateJob]{+ Body: base.ApiResponse[EnvironmentUpdateJob]{Success: true,Data: *job,},diff --git a/backend/internal/models/environment_update_job.go b/backend/internal/system/model.gosimilarity index 98%rename from backend/internal/models/environment_update_job.gorename to backend/internal/system/model.goindex 8bfa20dd8..e686e7f5e 100644--- a/backend/internal/models/environment_update_job.go+++ b/backend/internal/system/model.go@@ -1,6 +1,8 @@-package models+package systemimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"database/sql/driver""encoding/json/v2""time"@@ -94,7 +96,7 @@ func (r *EnvironmentUpdateResults) Scan(value any) error {// survives the manager's final self-upgrade restart so the manager result can be// finalized on the next boot. See [EnvironmentUpdateJobStatus].type EnvironmentUpdateJob struct {- BaseModel+ database.BaseModelStatus EnvironmentUpdateJobStatus `json:"status" gorm:"column:status"`UserID string `json:"userId" gorm:"column:user_id"`diff --git a/backend/internal/system/system.go b/backend/internal/system/system.goindex 4b50b6bd2..7694fae30 100644--- a/backend/internal/system/system.go+++ b/backend/internal/system/system.go@@ -1,12 +1,18 @@package systemimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""log/slog""strings""sync"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/image"@@ -18,7 +24,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/volume"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -260,12 +265,12 @@ func (s *SystemService) startSystemPruneActivityInternal(ctx context.Context, en}activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{EnvironmentID: environmentID,- Type: models.ActivityTypeSystemPrune,+ Type: activitytypes.TypeSystemPrune,ResourceType: new("system"),ResourceName: new("Docker resources"),Step: "Preparing prune",LatestMessage: "System prune started",- Metadata: models.JSON{+ Metadata: database.JSON{"containers": req.Containers,"images": req.Images,"volumes": req.Volumes,@@ -285,7 +290,7 @@ func (s *SystemService) appendSystemPruneActivityMessageInternal(ctx context.Conreturn}if _, err := s.activityService.AppendMessage(ctx, activityID, activity.AppendActivityMessageRequest{- Level: models.ActivityMessageLevelInfo,+ Level: activitytypes.MessageLevelInfo,Message: message,Progress: &progress,Step: message,@@ -299,15 +304,15 @@ func (s *SystemService) completeSystemPruneActivityInternal(ctx context.Context,return}- status := models.ActivityStatusSuccess+ status := activitytypes.StatusSuccessmessage := "System prune completed"var errMessage *stringif !result.Success || len(result.Errors) > 0 {if activitylib.CancelledByContext(ctx) {- status = models.ActivityStatusCancelled+ status = activitytypes.StatusCancelledmessage = "System prune cancelled"} else {- status = models.ActivityStatusFailed+ status = activitytypes.StatusFailedmessage = "System prune completed with errors"errMessage = new(strings.Join(result.Errors, "; "))}@@ -387,7 +392,7 @@ type startMatchingContainersOptionsInternal struct {}func (s *SystemService) startMatchingContainersInternal(ctx context.Context, environmentID string, opts startMatchingContainersOptionsInternal) (*containertypes.ActionResult, error) {- activityID := s.startSystemContainerActivityInternal(ctx, environmentID, models.ActivityTypeContainerStart, opts.ResourceName, opts.StartMessage)+ activityID := s.startSystemContainerActivityInternal(ctx, environmentID, activitytypes.TypeContainerStart, opts.ResourceName, opts.StartMessage)ctx = s.activityService.Track(ctx, activityID)containers, _, _, _, err := s.dockerService.GetAllContainers(ctx)if err != nil {@@ -401,7 +406,7 @@ func (s *SystemService) startMatchingContainersInternal(ctx context.Context, env}result := s.performBatchContainerAction(ctx, containers, "start", opts.ShouldStart, func(ctx context.Context, id string) error {- return s.containerService.StartContainer(ctx, id, models.SystemUser)+ return s.containerService.StartContainer(ctx, id, common.SystemUser)})result.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()s.completeSystemContainerActivityInternal(ctx, activityID, opts.SuccessMessage, result)@@ -409,7 +414,7 @@ func (s *SystemService) startMatchingContainersInternal(ctx context.Context, env}func (s *SystemService) StopAllContainers(ctx context.Context, environmentID string) (*containertypes.ActionResult, error) {- activityID := s.startSystemContainerActivityInternal(ctx, environmentID, models.ActivityTypeContainerStop, "All containers", "Stopping all containers")+ activityID := s.startSystemContainerActivityInternal(ctx, environmentID, activitytypes.TypeContainerStop, "All containers", "Stopping all containers")ctx = s.activityService.Track(ctx, activityID)containers, _, _, _, err := s.dockerService.GetAllContainers(ctx)if err != nil {@@ -428,14 +433,14 @@ func (s *SystemService) StopAllContainers(ctx context.Context, environmentID strreturn !labels.IsArcaneContainer(c.Labels)},func(ctx context.Context, id string) error {- return s.containerService.StopContainer(ctx, id, models.SystemUser)+ return s.containerService.StopContainer(ctx, id, common.SystemUser)})result.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()s.completeSystemContainerActivityInternal(ctx, activityID, "Stopped all containers", result)return result, nil}-func (s *SystemService) startSystemContainerActivityInternal(ctx context.Context, environmentID string, activityType models.ActivityType, resourceName, message string) string {+func (s *SystemService) startSystemContainerActivityInternal(ctx context.Context, environmentID string, activityType activitytypes.Type, resourceName, message string) string {if s.activityService == nil {return ""}@@ -446,7 +451,7 @@ func (s *SystemService) startSystemContainerActivityInternal(ctx context.ContextResourceName: &resourceName,Step: message,LatestMessage: message,- Metadata: models.JSON{"scope": resourceName},+ Metadata: database.JSON{"scope": resourceName},})if err != nil {slog.DebugContext(ctx, "failed to start system container activity", "type", activityType, "error", err)@@ -460,11 +465,11 @@ func (s *SystemService) completeSystemContainerActivityInternal(ctx context.Contreturn}- status := models.ActivityStatusSuccess+ status := activitytypes.StatusSuccessmessage := successMessagevar errMessage *stringif !result.Success || len(result.Errors) > 0 {- status = models.ActivityStatusFailed+ status = activitytypes.StatusFailedmessage = strings.Join(result.Errors, "; ")errMessage = &message}@@ -542,7 +547,7 @@ func (s *SystemService) pruneImagesInternal(ctx context.Context, options system.// Batch delete update recordsif len(idsToDelete) > 0 && s.db != nil {- if err := s.db.WithContext(ctx).Where("id IN ?", idsToDelete).Delete(&models.ImageUpdateRecord{}).Error; err != nil {+ if err := s.db.WithContext(ctx).Where("id IN ?", idsToDelete).Delete(&imageupdate.ImageUpdateRecord{}).Error; err != nil {slog.WarnContext(ctx, "Failed to delete image update records", "count", len(idsToDelete), "error", err.Error())}}diff --git a/backend/internal/system/upgrade_service.go b/backend/internal/system/upgrade_service.goindex 18b770547..2faabd008 100644--- a/backend/internal/system/upgrade_service.go+++ b/backend/internal/system/upgrade_service.go@@ -21,7 +21,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/version"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -113,7 +112,7 @@ func (s *SystemUpgradeService) AlreadyOnNewestImage(ctx context.Context) bool {// own image tag; the updater engine passes an explicit target with the resolved new// image. Update-all uses the returned ID to tell an upgrade that recreated this// container from one that found nothing to do — see watchManagerUpgraderInternal.-func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user models.User, target updater.SelfUpdateTarget) (string, error) {+func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user common.User, target updater.SelfUpdateTarget) (string, error) {if !s.upgrading.CompareAndSwap(false, true) {return "", common.Classify(common.ErrUpgradeInProgress, errors.New("an upgrade is already in progress"))}@@ -145,14 +144,14 @@ func (s *SystemUpgradeService) TriggerUpgradeViaCLI(ctx context.Context, user motargetImage := strings.TrimSpace(target.NewImageRef)// Log upgrade event- metadata := models.JSON{+ metadata := database.JSON{"action": "system_upgrade_cli","containerId": containerId,"containerName": containerName,"method": "cli","targetImage": targetImage,}- if err := s.eventService.LogUserEvent(ctx, models.EventTypeSystemUpgrade, user.ID, user.Username, metadata); err != nil {+ if err := s.eventService.LogUserEvent(ctx, event.EventTypeSystemUpgrade, user.ID, user.Username, metadata); err != nil {slog.Warn("Failed to log upgrade event", "error", err)}@@ -478,7 +477,7 @@ const (// self-upgrade as its final step (job left pending_restart, finalized at next// boot). Every environment pulls the latest image, whether or not it reports an// update available.-func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user models.User, env *environment.EnvironmentService) (*models.EnvironmentUpdateJob, error) {+func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user common.User, env *environment.EnvironmentService) (*EnvironmentUpdateJob, error) {// Guard the check-then-create against concurrent callers (e.g. a double-click).// A dedicated flag rather than s.upgrading, because the manager branch below// calls TriggerUpgradeViaCLI which acquires s.upgrading itself. The persisted@@ -499,7 +498,7 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user models.Uinfo := s.versionService.GetAppVersionInfo(ctx)- managerResult := models.EnvironmentUpdateResult{+ managerResult := EnvironmentUpdateResult{EnvironmentID: environment.LocalEnvironmentID,EnvironmentName: env.ResolveEnvironmentName(ctx, environment.LocalEnvironmentID),FromVersion: info.CurrentVersion,@@ -510,7 +509,7 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user models.U// Best effort: the agents phase re-lists authoritatively and fills any gaps.remoteResults := s.seedRemoteResultsInternal(ctx, env)- job := &models.EnvironmentUpdateJob{+ job := &EnvironmentUpdateJob{UserID: user.ID,Username: user.Username,ManagerVersionAtStart: info.CurrentVersion,@@ -520,14 +519,14 @@ func (s *SystemUpgradeService) StartUpdateAll(ctx context.Context, user models.U// Manager upgrades LAST. Seed its row pending; the agents-phase goroutine// flips it to updating right before triggering the self-upgrade.- managerResult.Status = models.EnvironmentUpdateResultStatusPending+ managerResult.Status = EnvironmentUpdateResultStatusPendingmanagerResult.ToVersion = job.ManagerTargetVersion// Running from the start: the agents phase happens first, while the backend is// up and can report progress. The manager self-upgrade fires at the very end of// the agents goroutine.- job.Status = models.EnvironmentUpdateJobStatusRunning- job.Results = append(models.EnvironmentUpdateResults{managerResult}, remoteResults...)+ job.Status = EnvironmentUpdateJobStatusRunning+ job.Results = append(EnvironmentUpdateResults{managerResult}, remoteResults...)if err := s.db.WithContext(ctx).Create(job).Error; err != nil {return nil, errors.WrapIf(err, "create update-all job")@@ -555,7 +554,7 @@ func (s *SystemUpgradeService) ResumeUpdateAllOnStartup(ctx context.Context) {// A job left running means the manager died mid-agents-phase, before it reached// the manager step; we can't safely resume partial progress, so fail it.- if job.Status == models.EnvironmentUpdateJobStatusRunning {+ if job.Status == EnvironmentUpdateJobStatusRunning {s.markUpdateAllFailedInternal(ctx, job, "interrupted by manager restart")return}@@ -570,9 +569,9 @@ func (s *SystemUpgradeService) ResumeUpdateAllOnStartup(ctx context.Context) {// The agents phase already ran before the restart. Finalize the manager's own// result and close the job — do not re-run the agents phase.- managerStatus := models.EnvironmentUpdateResultStatusFailed+ managerStatus := EnvironmentUpdateResultStatusFailedif action.managerSucceeded {- managerStatus = models.EnvironmentUpdateResultStatusUpdated+ managerStatus = EnvironmentUpdateResultStatusUpdated}s.recordManagerResultInternal(job, managerStatus, info.CurrentVersion)s.finalizeUpdateAllJobInternal(ctx, job)@@ -591,7 +590,7 @@ type resumeActionInternal struct {// (digest covers non-semver, digest-pinned installs), or when the manager is already// on the recorded target — a force-update of an up-to-date manager recreates the// container without changing either.-func resolveResumeActionInternal(job *models.EnvironmentUpdateJob, currentVersion, currentDigest string, now time.Time) resumeActionInternal {+func resolveResumeActionInternal(job *EnvironmentUpdateJob, currentVersion, currentDigest string, now time.Time) resumeActionInternal {if now.Sub(job.CreatedAt) > updateAllStaleThresholdInternal {return resumeActionInternal{markStale: true}}@@ -611,7 +610,7 @@ func resolveResumeActionInternal(job *models.EnvironmentUpdateJob, currentVersio// persisting progress after each one so the status endpoint can report live// progress, then triggers the manager's own self-upgrade as the final step// (leaving the job pending_restart for the next boot to finalize).-func (s *SystemUpgradeService) runAgentsPhaseInternal(ctx context.Context, jobID string, env *environment.EnvironmentService, user models.User) {+func (s *SystemUpgradeService) runAgentsPhaseInternal(ctx context.Context, jobID string, env *environment.EnvironmentService, user common.User) {job, err := s.getUpdateAllJobByIDInternal(ctx, jobID)if err != nil || job == nil {slog.WarnContext(ctx, "update-all: failed to reload job for agents phase", "jobId", jobID, "error", err)@@ -629,7 +628,7 @@ func (s *SystemUpgradeService) runAgentsPhaseInternal(ctx context.Context, jobID// environment) and mark it updating so the dialog shows a live indicator on// the row currently being processed.idx := upsertPendingResultInternal(job, remote.ID, remote.Name)- job.Results[idx].Status = models.EnvironmentUpdateResultStatusUpdating+ job.Results[idx].Status = EnvironmentUpdateResultStatusUpdatingif err := s.persistUpdateAllJobInternal(ctx, job); err != nil {slog.WarnContext(ctx, "update-all: failed to persist updating status", "jobId", job.ID, "environmentId", remote.ID, "error", err)}@@ -649,11 +648,11 @@ func (s *SystemUpgradeService) runAgentsPhaseInternal(ctx context.Context, jobID// pending_restart and finalizes it.for i := range job.Results {if job.Results[i].EnvironmentID == environment.LocalEnvironmentID {- job.Results[i].Status = models.EnvironmentUpdateResultStatusUpdating+ job.Results[i].Status = EnvironmentUpdateResultStatusUpdatingbreak}}- job.Status = models.EnvironmentUpdateJobStatusPendingRestart+ job.Status = EnvironmentUpdateJobStatusPendingRestartif err := s.persistUpdateAllJobInternal(ctx, job); err != nil {slog.WarnContext(ctx, "update-all: failed to persist pending_restart before manager upgrade", "jobId", job.ID, "error", err)}@@ -704,7 +703,7 @@ func (s *SystemUpgradeService) watchManagerUpgraderInternal(ctx context.Context,slog.WarnContext(ctx, "update-all: failed to reload job after upgrader exit", "jobId", jobID, "error", err)return}- if job.Status != models.EnvironmentUpdateJobStatusPendingRestart {+ if job.Status != EnvironmentUpdateJobStatusPendingRestart {return}@@ -730,7 +729,7 @@ func (s *SystemUpgradeService) watchManagerUpgraderInternal(ctx context.Context,return}- s.recordManagerResultInternal(job, models.EnvironmentUpdateResultStatusUpToDate, info.CurrentVersion)+ s.recordManagerResultInternal(job, EnvironmentUpdateResultStatusUpToDate, info.CurrentVersion)slog.InfoContext(ctx, "Update-all: manager was already up to date; no restart needed", "jobId", job.ID, "version", info.CurrentVersion)s.finalizeUpdateAllJobInternal(ctx, job)}@@ -747,7 +746,7 @@ func (s *SystemUpgradeService) closeOutUnobservedUpgradeInternal(ctx context.Conslog.WarnContext(ctx, "update-all: failed to reload job after unobserved upgrader exit", "jobId", jobID, "error", err)return}- if job.Status != models.EnvironmentUpdateJobStatusPendingRestart {+ if job.Status != EnvironmentUpdateJobStatusPendingRestart {return}@@ -766,7 +765,7 @@ func (s *SystemUpgradeService) closeOutUnobservedUpgradeInternal(ctx context.Conslog.WarnContext(ctx, "update-all: failed to reload stale job", "jobId", jobID, "error", err)return}- if job.Status != models.EnvironmentUpdateJobStatusPendingRestart {+ if job.Status != EnvironmentUpdateJobStatusPendingRestart {return}@@ -844,18 +843,18 @@ func (s *SystemUpgradeService) waitForUpgraderExitInternal(ctx context.Context,// seedRemoteResultsInternal builds a pending result row for every remote environment// so the dialog can render the whole fleet immediately. Best effort: on error it// returns nil and the agents phase appends rows as it processes them.-func (s *SystemUpgradeService) seedRemoteResultsInternal(ctx context.Context, env *environment.EnvironmentService) models.EnvironmentUpdateResults {+func (s *SystemUpgradeService) seedRemoteResultsInternal(ctx context.Context, env *environment.EnvironmentService) EnvironmentUpdateResults {envs, err := env.ListRemoteEnvironments(ctx)if err != nil {slog.WarnContext(ctx, "update-all: failed to pre-list remote environments for seeding", "error", err)return nil}- results := make(models.EnvironmentUpdateResults, 0, len(envs))+ results := make(EnvironmentUpdateResults, 0, len(envs))for _, remote := range envs {- results = append(results, models.EnvironmentUpdateResult{+ results = append(results, EnvironmentUpdateResult{EnvironmentID: remote.ID,EnvironmentName: remote.Name,- Status: models.EnvironmentUpdateResultStatusPending,+ Status: EnvironmentUpdateResultStatusPending,})}return results@@ -864,16 +863,16 @@ func (s *SystemUpgradeService) seedRemoteResultsInternal(ctx context.Context, en// upsertPendingResultInternal returns the index of the existing result row for envID,// appending a new pending row when seeding missed it (e.g. the seed list failed, or a// new environment was registered after the job started).-func upsertPendingResultInternal(job *models.EnvironmentUpdateJob, envID, envName string) int {+func upsertPendingResultInternal(job *EnvironmentUpdateJob, envID, envName string) int {for i := range job.Results {if job.Results[i].EnvironmentID == envID {return i}}- job.Results = append(job.Results, models.EnvironmentUpdateResult{+ job.Results = append(job.Results, EnvironmentUpdateResult{EnvironmentID: envID,EnvironmentName: envName,- Status: models.EnvironmentUpdateResultStatusPending,+ Status: EnvironmentUpdateResultStatusPending,})return len(job.Results) - 1}@@ -881,7 +880,7 @@ func upsertPendingResultInternal(job *models.EnvironmentUpdateJob, envID, envNam// upgradeAgentInternal triggers and confirms a single remote environment's// self-upgrade, recording the outcome on result. The upgrade always runs — the// agent pulls the latest image even when it reports no update available.-func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *environment.EnvironmentService, envID string, result *models.EnvironmentUpdateResult) {+func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *environment.EnvironmentService, envID string, result *EnvironmentUpdateResult) {versionCtx, cancel := context.WithTimeout(ctx, updateAllAgentRequestTimeoutInternal)var info versiontypes.Infoerr := env.ProxyJSONRequest(versionCtx, envID, http.MethodGet, "/api/app-version", nil, &info)@@ -898,12 +897,12 @@ func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *enresp, err := env.ExecuteRemoteRequest(triggerCtx, envID, http.MethodPost, "/api/environments/0/system/upgrade", nil)cancel()if err != nil {- result.Status = models.EnvironmentUpdateResultStatusFailed+ result.Status = EnvironmentUpdateResultStatusFailedresult.Error = truncateUpdateAllErrorInternal(err)return}if err := resp.RequireSuccess(); err != nil {- result.Status = models.EnvironmentUpdateResultStatusFailed+ result.Status = EnvironmentUpdateResultStatusFailedresult.Error = truncateUpdateAllErrorInternal(err)return}@@ -913,16 +912,16 @@ func (s *SystemUpgradeService) upgradeAgentInternal(ctx context.Context, env *en// recreate. Confirming that would only burn the poll window waiting for a version// change that cannot come, so record it directly.if agentAlreadyOnTargetInternal(&info) {- result.Status = models.EnvironmentUpdateResultStatusUpToDate+ result.Status = EnvironmentUpdateResultStatusUpToDateresult.ToVersion = info.CurrentVersionreturn}if s.confirmAgentUpgradedInternal(ctx, env, envID, info) {- result.Status = models.EnvironmentUpdateResultStatusUpdated+ result.Status = EnvironmentUpdateResultStatusUpdated} else {// Upgrade fired but the new version was not confirmed within the wait window.- result.Status = models.EnvironmentUpdateResultStatusTriggered+ result.Status = EnvironmentUpdateResultStatusTriggered}}@@ -960,17 +959,17 @@ func agentAlreadyOnTargetInternal(info *versiontypes.Info) bool {// tunnel round-trip surfaces here as a deadline even though the agent is online.// Only errors that look like the environment was never reachable (no tunnel,// connection refused, DNS failure, …) stay an offline skip.-func updateAllAgentFailureStatusInternal(err error) models.EnvironmentUpdateResultStatus {+func updateAllAgentFailureStatusInternal(err error) EnvironmentUpdateResultStatus {// The tunnel/connection was established but the request did not finish: it// either timed out or was canceled (e.g. the parent context was aborted).if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {- return models.EnvironmentUpdateResultStatusFailed+ return EnvironmentUpdateResultStatusFailed}// The environment answered with a non-success status — reached, not offline.if _, ok := stderrors.AsType[*remenv.StatusError](err); ok {- return models.EnvironmentUpdateResultStatusFailed+ return EnvironmentUpdateResultStatusFailed}- return models.EnvironmentUpdateResultStatusSkippedOffline+ return EnvironmentUpdateResultStatusSkippedOffline}// confirmAgentUpgradedInternal polls the agent's version until it moves off the@@ -1012,8 +1011,8 @@ func (s *SystemUpgradeService) confirmAgentUpgradedInternal(ctx context.Context,}// GetLatestUpdateAllJob returns the most recently created update-all job, or nil.-func (s *SystemUpgradeService) GetLatestUpdateAllJob(ctx context.Context) (*models.EnvironmentUpdateJob, error) {- var jobs []models.EnvironmentUpdateJob+func (s *SystemUpgradeService) GetLatestUpdateAllJob(ctx context.Context) (*EnvironmentUpdateJob, error) {+ var jobs []EnvironmentUpdateJobif err := s.db.WithContext(ctx).Order("created_at DESC").Limit(1).@@ -1026,12 +1025,12 @@ func (s *SystemUpgradeService) GetLatestUpdateAllJob(ctx context.Context) (*modereturn &jobs[0], nil}-func (s *SystemUpgradeService) activeUpdateAllJobInternal(ctx context.Context) (*models.EnvironmentUpdateJob, error) {- var jobs []models.EnvironmentUpdateJob+func (s *SystemUpgradeService) activeUpdateAllJobInternal(ctx context.Context) (*EnvironmentUpdateJob, error) {+ var jobs []EnvironmentUpdateJobif err := s.db.WithContext(ctx).Where("status IN ?", []string{- string(models.EnvironmentUpdateJobStatusPendingRestart),- string(models.EnvironmentUpdateJobStatusRunning),+ string(EnvironmentUpdateJobStatusPendingRestart),+ string(EnvironmentUpdateJobStatusRunning),}).Order("created_at DESC").Limit(1).@@ -1044,8 +1043,8 @@ func (s *SystemUpgradeService) activeUpdateAllJobInternal(ctx context.Context) (return &jobs[0], nil}-func (s *SystemUpgradeService) getUpdateAllJobByIDInternal(ctx context.Context, id string) (*models.EnvironmentUpdateJob, error) {- var jobs []models.EnvironmentUpdateJob+func (s *SystemUpgradeService) getUpdateAllJobByIDInternal(ctx context.Context, id string) (*EnvironmentUpdateJob, error) {+ var jobs []EnvironmentUpdateJobif err := s.db.WithContext(ctx).Where("id = ?", id).Limit(1).@@ -1058,17 +1057,17 @@ func (s *SystemUpgradeService) getUpdateAllJobByIDInternal(ctx context.Context,return &jobs[0], nil}-func (s *SystemUpgradeService) persistUpdateAllJobInternal(ctx context.Context, job *models.EnvironmentUpdateJob) error {+func (s *SystemUpgradeService) persistUpdateAllJobInternal(ctx context.Context, job *EnvironmentUpdateJob) error {return s.db.WithContext(ctx).Save(job).Error}-func (s *SystemUpgradeService) markUpdateAllFailedInternal(ctx context.Context, job *models.EnvironmentUpdateJob, reason string) {- job.Status = models.EnvironmentUpdateJobStatusFailed+func (s *SystemUpgradeService) markUpdateAllFailedInternal(ctx context.Context, job *EnvironmentUpdateJob, reason string) {+ job.Status = EnvironmentUpdateJobStatusFailedjob.Error = &reasonjob.CompletedAt = new(time.Now())for i := range job.Results {- if job.Results[i].Status == models.EnvironmentUpdateResultStatusUpdating {- job.Results[i].Status = models.EnvironmentUpdateResultStatusFailed+ if job.Results[i].Status == EnvironmentUpdateResultStatusUpdating {+ job.Results[i].Status = EnvironmentUpdateResultStatusFailedjob.Results[i].Error = reason}}@@ -1080,13 +1079,13 @@ func (s *SystemUpgradeService) markUpdateAllFailedInternal(ctx context.Context,// logUpdateAllEventInternal. LogUserEvent hardcodes an info-severity "completed"// title, so create the event directly with error severity and the reason.if _, err := s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeSystemUpgrade,- Severity: models.EventSeverityError,+ Type: event.EventTypeSystemUpgrade,+ Severity: event.EventSeverityError,Title: "Update all environments failed",Description: reason,UserID: new(job.UserID),Username: new(job.Username),- Metadata: models.JSON{+ Metadata: database.JSON{"action": "update_all_environments","jobId": job.ID,"environments": len(job.Results),@@ -1102,21 +1101,21 @@ func (s *SystemUpgradeService) markUpdateAllFailedInternal(ctx context.Context,// recordManagerResultInternal sets the manager (env "0") entry to its final status:// updated after a confirmed restart, up_to_date when the pull found nothing to swap// in, or failed otherwise.-func (s *SystemUpgradeService) recordManagerResultInternal(job *models.EnvironmentUpdateJob, status models.EnvironmentUpdateResultStatus, currentVersion string) {+func (s *SystemUpgradeService) recordManagerResultInternal(job *EnvironmentUpdateJob, status EnvironmentUpdateResultStatus, currentVersion string) {for i := range job.Results {if job.Results[i].EnvironmentID != environment.LocalEnvironmentID {continue}job.Results[i].Status = statusswitch status {- case models.EnvironmentUpdateResultStatusUpdated, models.EnvironmentUpdateResultStatusUpToDate:+ case EnvironmentUpdateResultStatusUpdated, EnvironmentUpdateResultStatusUpToDate:job.Results[i].ToVersion = currentVersion- case models.EnvironmentUpdateResultStatusFailed:+ case EnvironmentUpdateResultStatusFailed:job.Results[i].Error = "manager version did not change after upgrade"- case models.EnvironmentUpdateResultStatusPending,- models.EnvironmentUpdateResultStatusUpdating,- models.EnvironmentUpdateResultStatusTriggered,- models.EnvironmentUpdateResultStatusSkippedOffline:+ case EnvironmentUpdateResultStatusPending,+ EnvironmentUpdateResultStatusUpdating,+ EnvironmentUpdateResultStatusTriggered,+ EnvironmentUpdateResultStatusSkippedOffline:// Nothing more to record: the row keeps the target version it was seeded// with, since none of these outcomes establishes what it ended up running.}@@ -1126,8 +1125,8 @@ func (s *SystemUpgradeService) recordManagerResultInternal(job *models.Environme// finalizeUpdateAllJobInternal closes a job out as completed and records the audit// event. The per-environment rows must already carry their final statuses.-func (s *SystemUpgradeService) finalizeUpdateAllJobInternal(ctx context.Context, job *models.EnvironmentUpdateJob) {- job.Status = models.EnvironmentUpdateJobStatusCompleted+func (s *SystemUpgradeService) finalizeUpdateAllJobInternal(ctx context.Context, job *EnvironmentUpdateJob) {+ job.Status = EnvironmentUpdateJobStatusCompletedjob.CompletedAt = new(time.Now())if err := s.persistUpdateAllJobInternal(ctx, job); err != nil {slog.WarnContext(ctx, "update-all: failed to finalize job", "jobId", job.ID, "error", err)@@ -1136,15 +1135,15 @@ func (s *SystemUpgradeService) finalizeUpdateAllJobInternal(ctx context.Context,s.logUpdateAllEventInternal(ctx, job)}-func (s *SystemUpgradeService) logUpdateAllEventInternal(ctx context.Context, job *models.EnvironmentUpdateJob) {+func (s *SystemUpgradeService) logUpdateAllEventInternal(ctx context.Context, job *EnvironmentUpdateJob) {failed := 0for _, r := range job.Results {- if r.Status == models.EnvironmentUpdateResultStatusFailed {+ if r.Status == EnvironmentUpdateResultStatusFailed {failed++}}- metadata := models.JSON{+ metadata := database.JSON{"action": "update_all_environments","jobId": job.ID,"environments": len(job.Results),@@ -1153,7 +1152,7 @@ func (s *SystemUpgradeService) logUpdateAllEventInternal(ctx context.Context, jo// All environments succeeded: log the standard completed (info) event.if failed == 0 {- if err := s.eventService.LogUserEvent(ctx, models.EventTypeSystemUpgrade, job.UserID, job.Username, metadata); err != nil {+ if err := s.eventService.LogUserEvent(ctx, event.EventTypeSystemUpgrade, job.UserID, job.Username, metadata); err != nil {slog.WarnContext(ctx, "Failed to log update-all event", "jobId", job.ID, "error", err)}return@@ -1162,8 +1161,8 @@ func (s *SystemUpgradeService) logUpdateAllEventInternal(ctx context.Context, jo// The job ran to completion but some environments failed to update — record a// warning-severity event so those failures still show in the audit log.if _, err := s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeSystemUpgrade,- Severity: models.EventSeverityWarning,+ Type: event.EventTypeSystemUpgrade,+ Severity: event.EventSeverityWarning,Title: "Update all environments completed with errors",Description: fmt.Sprintf("%d of %d environments failed to update", failed, len(job.Results)),UserID: new(job.UserID),diff --git a/backend/internal/system/upgrade_service_test.go b/backend/internal/system/upgrade_service_test.goindex 549476e57..cd3bd81b4 100644--- a/backend/internal/system/upgrade_service_test.go+++ b/backend/internal/system/upgrade_service_test.go@@ -8,7 +8,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"containertypes "github.com/moby/moby/api/types/container"mounttypes "github.com/moby/moby/api/types/mount"@@ -292,12 +291,12 @@ func TestUpdateAllAgentFailureStatus(t *testing.T) {tests := []struct {name stringerr error- want models.EnvironmentUpdateResultStatus+ want EnvironmentUpdateResultStatus}{- {"tunnel request timed out", tunnelTimeout, models.EnvironmentUpdateResultStatusFailed},- {"request canceled mid-flight", fmt.Errorf("tunnel request failed: %w", context.Canceled), models.EnvironmentUpdateResultStatusFailed},- {"non-success status from agent", &remenv.StatusError{StatusCode: 502}, models.EnvironmentUpdateResultStatusFailed},- {"agent never connected", &remenv.TransportError{Err: errors.New("edge agent is not connected")}, models.EnvironmentUpdateResultStatusSkippedOffline},+ {"tunnel request timed out", tunnelTimeout, EnvironmentUpdateResultStatusFailed},+ {"request canceled mid-flight", fmt.Errorf("tunnel request failed: %w", context.Canceled), EnvironmentUpdateResultStatusFailed},+ {"non-success status from agent", &remenv.StatusError{StatusCode: 502}, EnvironmentUpdateResultStatusFailed},+ {"agent never connected", &remenv.TransportError{Err: errors.New("edge agent is not connected")}, EnvironmentUpdateResultStatusSkippedOffline},}for _, tt := range tests {diff --git a/backend/internal/system/upgrade_update_all_test.go b/backend/internal/system/upgrade_update_all_test.goindex a0e8e8a66..aa63a94cc 100644--- a/backend/internal/system/upgrade_update_all_test.go+++ b/backend/internal/system/upgrade_update_all_test.go@@ -9,7 +9,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/version""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"versiontypes "github.com/getarcaneapp/arcane/types/v2/version""github.com/libtnb/sqlite""github.com/stretchr/testify/require"@@ -19,8 +18,8 @@ import (func TestUpdateAllResolveResumeAction(t *testing.T) {now := time.Now()- newJob := func(createdAt time.Time, versionAtStart, digestAtStart string) *models.EnvironmentUpdateJob {- job := &models.EnvironmentUpdateJob{+ newJob := func(createdAt time.Time, versionAtStart, digestAtStart string) *EnvironmentUpdateJob {+ job := &EnvironmentUpdateJob{ManagerVersionAtStart: versionAtStart,ManagerDigestAtStart: digestAtStart,}@@ -30,7 +29,7 @@ func TestUpdateAllResolveResumeAction(t *testing.T) {tests := []struct {name string- job *models.EnvironmentUpdateJob+ job *EnvironmentUpdateJobcurrentVersion stringcurrentDigest stringwantStale bool@@ -66,7 +65,7 @@ func TestUpdateAllResolveResumeAction(t *testing.T) {},{name: "unchanged but already on target means force-update succeeded",- job: func() *models.EnvironmentUpdateJob {+ job: func() *EnvironmentUpdateJob {job := newJob(now.Add(-5*time.Minute), "1.0.0", "sha256:a")job.ManagerTargetVersion = "v1.0.0"return job@@ -101,10 +100,10 @@ func TestUpdateAllTargetVersionFallsBackToCurrent(t *testing.T) {}func TestUpsertPendingResult(t *testing.T) {- job := &models.EnvironmentUpdateJob{- Results: models.EnvironmentUpdateResults{- {EnvironmentID: "0", EnvironmentName: "Local", Status: models.EnvironmentUpdateResultStatusUpdated},- {EnvironmentID: "abc", EnvironmentName: "palladium", Status: models.EnvironmentUpdateResultStatusPending},+ job := &EnvironmentUpdateJob{+ Results: EnvironmentUpdateResults{+ {EnvironmentID: "0", EnvironmentName: "Local", Status: EnvironmentUpdateResultStatusUpdated},+ {EnvironmentID: "abc", EnvironmentName: "palladium", Status: EnvironmentUpdateResultStatusPending},},}{@@ -133,7 +132,7 @@ func TestUpsertPendingResult(t *testing.T) {require.False(t, got.EnvironmentID != "xyz" || got.EnvironmentName != "oracle-cloud","appended row = %+v, want id=xyz name=oracle-cloud", got)- require.Equal(t, models.EnvironmentUpdateResultStatusPending, got.Status,+ require.Equal(t, EnvironmentUpdateResultStatusPending, got.Status,"appended row status = %q, want pending", got.Status)}@@ -144,18 +143,18 @@ func TestUpdateAllFailedJobMarksUpdatingResultsFailed(t *testing.T) {require.NoError(t, err)db := &database.DB{DB: gormDB}- require.NoError(t, db.AutoMigrate(&models.EnvironmentUpdateJob{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&EnvironmentUpdateJob{}, &event.Event{}))svc := NewSystemUpgradeService(db, nil, nil, event.NewEventService(db, nil, nil), nil)- job := &models.EnvironmentUpdateJob{- Status: models.EnvironmentUpdateJobStatusRunning,+ job := &EnvironmentUpdateJob{+ Status: EnvironmentUpdateJobStatusRunning,UserID: "user-1",Username: "arcane",- Results: models.EnvironmentUpdateResults{- {EnvironmentID: "0", EnvironmentName: "Local", Status: models.EnvironmentUpdateResultStatusUpdated},- {EnvironmentID: "remote-1", EnvironmentName: "palladium", Status: models.EnvironmentUpdateResultStatusUpdating},- {EnvironmentID: "remote-2", EnvironmentName: "oracle-cloud", Status: models.EnvironmentUpdateResultStatusPending},- {EnvironmentID: "remote-3", EnvironmentName: "parquetide", Status: models.EnvironmentUpdateResultStatusFailed, Error: "already failed"},+ Results: EnvironmentUpdateResults{+ {EnvironmentID: "0", EnvironmentName: "Local", Status: EnvironmentUpdateResultStatusUpdated},+ {EnvironmentID: "remote-1", EnvironmentName: "palladium", Status: EnvironmentUpdateResultStatusUpdating},+ {EnvironmentID: "remote-2", EnvironmentName: "oracle-cloud", Status: EnvironmentUpdateResultStatusPending},+ {EnvironmentID: "remote-3", EnvironmentName: "parquetide", Status: EnvironmentUpdateResultStatusFailed, Error: "already failed"},},}require.NoError(t, db.WithContext(ctx).Create(job).Error)@@ -163,24 +162,24 @@ func TestUpdateAllFailedJobMarksUpdatingResultsFailed(t *testing.T) {reason := "interrupted by manager restart"svc.markUpdateAllFailedInternal(ctx, job, reason)- var got models.EnvironmentUpdateJob+ var got EnvironmentUpdateJobrequire.NoError(t, db.WithContext(ctx).First(&got, "id = ?", job.ID).Error)- require.Equal(t, models.EnvironmentUpdateJobStatusFailed, got.Status)+ require.Equal(t, EnvironmentUpdateJobStatusFailed, got.Status)require.NotNil(t, got.Error)require.Equal(t, reason, *got.Error)require.NotNil(t, got.CompletedAt)require.Len(t, got.Results, 4)- require.Equal(t, models.EnvironmentUpdateResultStatusUpdated, got.Results[0].Status)+ require.Equal(t, EnvironmentUpdateResultStatusUpdated, got.Results[0].Status)require.Empty(t, got.Results[0].Error)- require.Equal(t, models.EnvironmentUpdateResultStatusFailed, got.Results[1].Status)+ require.Equal(t, EnvironmentUpdateResultStatusFailed, got.Results[1].Status)require.Equal(t, reason, got.Results[1].Error)- require.Equal(t, models.EnvironmentUpdateResultStatusPending, got.Results[2].Status)+ require.Equal(t, EnvironmentUpdateResultStatusPending, got.Results[2].Status)require.Empty(t, got.Results[2].Error)- require.Equal(t, models.EnvironmentUpdateResultStatusFailed, got.Results[3].Status)+ require.Equal(t, EnvironmentUpdateResultStatusFailed, got.Results[3].Status)require.Equal(t, "already failed", got.Results[3].Error)}@@ -193,37 +192,37 @@ func TestUpdateAllFinalizesUpToDateManagerWithoutRestart(t *testing.T) {require.NoError(t, err)db := &database.DB{DB: gormDB}- require.NoError(t, db.AutoMigrate(&models.EnvironmentUpdateJob{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&EnvironmentUpdateJob{}, &event.Event{}))svc := NewSystemUpgradeService(db, nil, nil, event.NewEventService(db, nil, nil), nil)- job := &models.EnvironmentUpdateJob{- Status: models.EnvironmentUpdateJobStatusPendingRestart,+ job := &EnvironmentUpdateJob{+ Status: EnvironmentUpdateJobStatusPendingRestart,UserID: "user-1",Username: "arcane",ManagerVersionAtStart: "v1.0.0",- Results: models.EnvironmentUpdateResults{- {EnvironmentID: "0", EnvironmentName: "Local", Status: models.EnvironmentUpdateResultStatusUpdating, FromVersion: "v1.0.0"},- {EnvironmentID: "remote-1", EnvironmentName: "palladium", Status: models.EnvironmentUpdateResultStatusUpToDate},+ Results: EnvironmentUpdateResults{+ {EnvironmentID: "0", EnvironmentName: "Local", Status: EnvironmentUpdateResultStatusUpdating, FromVersion: "v1.0.0"},+ {EnvironmentID: "remote-1", EnvironmentName: "palladium", Status: EnvironmentUpdateResultStatusUpToDate},},}require.NoError(t, db.WithContext(ctx).Create(job).Error)- svc.recordManagerResultInternal(job, models.EnvironmentUpdateResultStatusUpToDate, "v1.0.0")+ svc.recordManagerResultInternal(job, EnvironmentUpdateResultStatusUpToDate, "v1.0.0")svc.finalizeUpdateAllJobInternal(ctx, job)- var got models.EnvironmentUpdateJob+ var got EnvironmentUpdateJobrequire.NoError(t, db.WithContext(ctx).First(&got, "id = ?", job.ID).Error)// Nothing is left waiting on a restart that will never happen.- require.Equal(t, models.EnvironmentUpdateJobStatusCompleted, got.Status)+ require.Equal(t, EnvironmentUpdateJobStatusCompleted, got.Status)require.NotNil(t, got.CompletedAt)require.Nil(t, got.Error)require.Equal(t, "0", got.Results[0].EnvironmentID)- require.Equal(t, models.EnvironmentUpdateResultStatusUpToDate, got.Results[0].Status)+ require.Equal(t, EnvironmentUpdateResultStatusUpToDate, got.Results[0].Status)require.Equal(t, "v1.0.0", got.Results[0].ToVersion)require.Empty(t, got.Results[0].Error)- require.Equal(t, models.EnvironmentUpdateResultStatusUpToDate, got.Results[1].Status)+ require.Equal(t, EnvironmentUpdateResultStatusUpToDate, got.Results[1].Status)}// The up-to-date short-circuit must only fire when the version check is conclusive:@@ -297,7 +296,7 @@ func TestResumeUpdateAllFinalizesManagerWithoutRerunningAgents(t *testing.T) {require.NoError(t, err)db := &database.DB{DB: gormDB}- require.NoError(t, db.AutoMigrate(&models.EnvironmentUpdateJob{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&EnvironmentUpdateJob{}, &event.Event{}))// disabled=true keeps GetAppVersionInfo offline; nil docker => empty current digest.// The reported version differs from ManagerVersionAtStart, so the manager upgrade@@ -305,35 +304,35 @@ func TestResumeUpdateAllFinalizesManagerWithoutRerunningAgents(t *testing.T) {versionSvc := version.NewVersionService(nil, true, "v9.9.9-new", "", nil, nil, nil)svc := NewSystemUpgradeService(db, nil, versionSvc, event.NewEventService(db, nil, nil), nil)- job := &models.EnvironmentUpdateJob{- Status: models.EnvironmentUpdateJobStatusPendingRestart,+ job := &EnvironmentUpdateJob{+ Status: EnvironmentUpdateJobStatusPendingRestart,UserID: "user-1",Username: "arcane",ManagerVersionAtStart: "v1.0.0-old",- Results: models.EnvironmentUpdateResults{- {EnvironmentID: "0", EnvironmentName: "Local", Status: models.EnvironmentUpdateResultStatusUpdating},- {EnvironmentID: "remote-1", EnvironmentName: "palladium", Status: models.EnvironmentUpdateResultStatusUpdated},- {EnvironmentID: "remote-2", EnvironmentName: "oracle-cloud", Status: models.EnvironmentUpdateResultStatusSkippedOffline},+ Results: EnvironmentUpdateResults{+ {EnvironmentID: "0", EnvironmentName: "Local", Status: EnvironmentUpdateResultStatusUpdating},+ {EnvironmentID: "remote-1", EnvironmentName: "palladium", Status: EnvironmentUpdateResultStatusUpdated},+ {EnvironmentID: "remote-2", EnvironmentName: "oracle-cloud", Status: EnvironmentUpdateResultStatusSkippedOffline},},}require.NoError(t, db.WithContext(ctx).Create(job).Error)svc.ResumeUpdateAllOnStartup(ctx)- var got models.EnvironmentUpdateJob+ var got EnvironmentUpdateJobrequire.NoError(t, db.WithContext(ctx).First(&got, "id = ?", job.ID).Error)// Job is finalized in-process (no re-run, not left running/pending).- require.Equal(t, models.EnvironmentUpdateJobStatusCompleted, got.Status)+ require.Equal(t, EnvironmentUpdateJobStatusCompleted, got.Status)require.NotNil(t, got.CompletedAt)require.Len(t, got.Results, 3)// Manager row transitioned updating -> updated (version changed across the restart).require.Equal(t, "0", got.Results[0].EnvironmentID)- require.Equal(t, models.EnvironmentUpdateResultStatusUpdated, got.Results[0].Status)+ require.Equal(t, EnvironmentUpdateResultStatusUpdated, got.Results[0].Status)require.NotEmpty(t, got.Results[0].ToVersion)// Remote rows are untouched — proving the agents phase was NOT re-run on resume.- require.Equal(t, models.EnvironmentUpdateResultStatusUpdated, got.Results[1].Status)- require.Equal(t, models.EnvironmentUpdateResultStatusSkippedOffline, got.Results[2].Status)+ require.Equal(t, EnvironmentUpdateResultStatusUpdated, got.Results[1].Status)+ require.Equal(t, EnvironmentUpdateResultStatusSkippedOffline, got.Results[2].Status)}diff --git a/backend/internal/template/handler.go b/backend/internal/template/handler.goindex 283d27ebc..037e3f746 100644--- a/backend/internal/template/handler.go+++ b/backend/internal/template/handler.go@@ -9,7 +9,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"@@ -354,7 +353,7 @@ func (h *TemplateHandler) GetAllTemplates(ctx context.Context, _ *GetAllTemplatereturn nil, huma.Error500InternalServerError(errors.WithMessage(err, "Failed to get templates").Error())}- out, mapErr := mapper.MapSlice[models.ComposeTemplate, templatetypes.Template](templates)+ out, mapErr := mapper.MapSlice[ComposeTemplate, templatetypes.Template](templates)if mapErr != nil {return nil, huma.Error500InternalServerError(errors.WithMessage(mapErr, "Failed to map templates").Error())}@@ -431,7 +430,7 @@ func (h *TemplateHandler) GetTemplateContent(ctx context.Context, input *GetTemp// CreateTemplate creates a new templatetypes.func (h *TemplateHandler) CreateTemplate(ctx context.Context, input *CreateTemplateInput) (*CreateTemplateOutput, error) {- tmpl := &models.ComposeTemplate{+ tmpl := &ComposeTemplate{Name: input.Body.Name,Description: input.Body.Description,Content: input.Body.Content,@@ -470,7 +469,7 @@ func (h *TemplateHandler) UpdateTemplate(ctx context.Context, input *UpdateTemplreturn nil, huma.Error400BadRequest("Template ID is required")}- updates := &models.ComposeTemplate{+ updates := &ComposeTemplate{Name: input.Body.Name,Description: input.Body.Description,Content: input.Body.Content,@@ -621,7 +620,7 @@ func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegisreturn nil, huma.Error500InternalServerError("Failed to fetch registry")}- out, mapErr := mapper.MapSlice[models.TemplateRegistry, templatetypes.TemplateRegistry](registries)+ out, mapErr := mapper.MapSlice[TemplateRegistry, templatetypes.TemplateRegistry](registries)if mapErr != nil {return nil, huma.Error500InternalServerError("Failed to fetch registry")}@@ -646,7 +645,7 @@ func (h *TemplateHandler) GetRegistries(ctx context.Context, _ *GetTemplateRegis// CreateRegistry creates a new template registry.func (h *TemplateHandler) CreateRegistry(ctx context.Context, input *CreateTemplateRegistryInput) (*CreateTemplateRegistryOutput, error) {- registry := &models.TemplateRegistry{+ registry := &TemplateRegistry{Name: input.Body.Name,URL: input.Body.URL,Description: input.Body.Description,@@ -675,7 +674,7 @@ func (h *TemplateHandler) UpdateRegistry(ctx context.Context, input *UpdateTemplreturn nil, huma.Error400BadRequest("Registry ID is required")}- updates := &models.TemplateRegistry{+ updates := &TemplateRegistry{Name: input.Body.Name,URL: input.Body.URL,Description: input.Body.Description,diff --git a/backend/internal/models/template.go b/backend/internal/template/model.gosimilarity index 92%rename from backend/internal/models/template.gorename to backend/internal/template/model.goindex 16c9d9303..b22c8742b 100644--- a/backend/internal/models/template.go+++ b/backend/internal/template/model.go@@ -1,7 +1,9 @@-package models+package template++import "github.com/getarcaneapp/arcane/backend/v2/internal/database"type TemplateRegistry struct {- BaseModel+ database.BaseModelName string `json:"name"`URL string `json:"url"`@@ -10,7 +12,7 @@ type TemplateRegistry struct {}type ComposeTemplate struct {- BaseModel+ database.BaseModelName string `json:"name"`Description string `json:"description"`diff --git a/backend/internal/template/service.go b/backend/internal/template/service.goindex 42cef3402..74accea4d 100644--- a/backend/internal/template/service.go+++ b/backend/internal/template/service.go@@ -20,7 +20,6 @@ import (composetypes "github.com/compose-spec/compose-go/v2/types""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/projects"@@ -39,7 +38,7 @@ import (type registryFetchMeta struct {LastModified string- Templates []models.ComposeTemplate+ Templates []ComposeTemplate}type TemplateService struct {@@ -49,7 +48,7 @@ type TemplateService struct {lookupIP httputils.LookupIPFuncsettingsService *settings.SettingsService- remoteCache *hot.HotCache[struct{}, []models.ComposeTemplate]+ remoteCache *hot.HotCache[struct{}, []ComposeTemplate]registryMu sync.RWMutexregistryFetchMeta map[string]*registryFetchMeta@@ -87,7 +86,7 @@ func NewTemplateService(ctx context.Context, db *database.DB, httpClient *http.C}service.safeHTTPClient = service.newSafeHTTPClientInternal()revalidationCtx := context.WithoutCancel(ctx)- loader := func(_ []struct{}) (map[struct{}][]models.ComposeTemplate, error) {+ loader := func(_ []struct{}) (map[struct{}][]ComposeTemplate, error) {loadCtx, cancel := context.WithTimeout(revalidationCtx, 2*time.Minute)defer cancel()templates, err := service.loadRemoteTemplates(loadCtx)@@ -97,9 +96,9 @@ func NewTemplateService(ctx context.Context, db *database.DB, httpClient *http.Cif len(templates) == 0 {return nil, errNoRemoteTemplates}- return map[struct{}][]models.ComposeTemplate{{}: templates}, nil+ return map[struct{}][]ComposeTemplate{{}: templates}, nil}- service.remoteCache = hot.NewHotCache[struct{}, []models.ComposeTemplate](hot.LRU, 1).+ service.remoteCache = hot.NewHotCache[struct{}, []ComposeTemplate](hot.LRU, 1).WithTTL(remoteCacheDuration).WithLoaders(loader).WithRevalidation(24*time.Hour, loader).@@ -160,7 +159,7 @@ func (s *TemplateService) refreshRemoteTemplates(ctx context.Context) error {return nil}-func (s *TemplateService) GetAllTemplates(ctx context.Context) ([]models.ComposeTemplate, error) {+func (s *TemplateService) GetAllTemplates(ctx context.Context) ([]ComposeTemplate, error) {return s.getMergedTemplates(ctx)}@@ -239,12 +238,12 @@ func (s *TemplateService) GetAllTemplatesPaginated(ctx context.Context, params preturn result.Items, paginationResp, nil}-func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*models.ComposeTemplate, error) {+func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*ComposeTemplate, error) {if err := s.syncFilesystemTemplatesInternal(ctx); err != nil {slog.WarnContext(ctx, "failed to sync filesystem templates", "error", err)}- var template models.ComposeTemplate+ var template ComposeTemplateif err := s.db.WithContext(ctx).Preload("Registry").Where("id = ?", id).First(&template).Error; err == nil {return &template, nil} else if !errors.Is(err, gorm.ErrRecordNotFound) {@@ -276,7 +275,7 @@ func (s *TemplateService) GetTemplate(ctx context.Context, id string) (*models.Creturn nil, common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))}-func (s *TemplateService) lookupRemoteFromCacheInternal(id string) *models.ComposeTemplate {+func (s *TemplateService) lookupRemoteFromCacheInternal(id string) *ComposeTemplate {if s.remoteCache == nil {return nil}@@ -301,7 +300,7 @@ func (s *TemplateService) remoteCacheSizeInternal() int {return len(templates)}-func (s *TemplateService) CreateTemplate(ctx context.Context, template *models.ComposeTemplate) error {+func (s *TemplateService) CreateTemplate(ctx context.Context, template *ComposeTemplate) error {if template.ID == "" {template.ID = uuid.NewString()}@@ -316,9 +315,9 @@ func (s *TemplateService) CreateTemplate(ctx context.Context, template *models.C})}-func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updates *models.ComposeTemplate) error {+func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updates *ComposeTemplate) error {return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var existing models.ComposeTemplate+ var existing ComposeTemplateif err := tx.Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))@@ -346,7 +345,7 @@ func (s *TemplateService) UpdateTemplate(ctx context.Context, id string, updatesfunc (s *TemplateService) DeleteTemplate(ctx context.Context, id string) error {return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var existing models.ComposeTemplate+ var existing ComposeTemplateif err := tx.Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return common.Classify(common.ErrTemplateNotFound, errors.New("Template not found"))@@ -447,8 +446,8 @@ func (s *TemplateService) SaveEnvTemplate(ctx context.Context, content string) ereturn acfs.WriteFile(ctx, baseDir, "/.env.template", []byte(content), utils.FilePerm)}-func (s *TemplateService) GetRegistries(ctx context.Context) ([]models.TemplateRegistry, error) {- var registries []models.TemplateRegistry+func (s *TemplateService) GetRegistries(ctx context.Context) ([]TemplateRegistry, error) {+ var registries []TemplateRegistryerr := s.db.WithContext(ctx).Find(®istries).Errorif err != nil {return nil, errors.WrapIf(err, "failed to get registries")@@ -466,7 +465,7 @@ func (s *TemplateService) GetRegistryFetchErrors() map[string]string {return out}-func (s *TemplateService) CreateRegistry(ctx context.Context, registry *models.TemplateRegistry) error {+func (s *TemplateService) CreateRegistry(ctx context.Context, registry *TemplateRegistry) error {// Hydrate metadata if neededif registry.Name == "" || registry.Description == "" {if registry.URL == "" {@@ -502,9 +501,9 @@ func (s *TemplateService) CreateRegistry(ctx context.Context, registry *models.Treturn nil}-func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updates *models.TemplateRegistry) error {+func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updates *TemplateRegistry) error {err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var existing models.TemplateRegistry+ var existing TemplateRegistryif err := tx.Where("id = ?", id).First(&existing).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return errors.New("registry not found")@@ -516,7 +515,7 @@ func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updatesreturn err}- if err := tx.Model(&models.TemplateRegistry{}).Where("id = ?", id).+ if err := tx.Model(&TemplateRegistry{}).Where("id = ?", id).Select("Name", "URL", "Description", "Enabled").Updates(updates).Error; err != nil {return err@@ -531,7 +530,7 @@ func (s *TemplateService) UpdateRegistry(ctx context.Context, id string, updatesreturn nil}-func (s *TemplateService) hydrateRegistryUpdates(ctx context.Context, updates, existing *models.TemplateRegistry) error {+func (s *TemplateService) hydrateRegistryUpdates(ctx context.Context, updates, existing *TemplateRegistry) error {urlChanged := updates.URL != "" && updates.URL != existing.URLneedsHydration := updates.Name == "" || updates.Description == ""@@ -556,7 +555,7 @@ func (s *TemplateService) hydrateRegistryUpdates(ctx context.Context, updates, efunc (s *TemplateService) DeleteRegistry(ctx context.Context, id string) error {err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- result := tx.Where("id = ?", id).Delete(&models.TemplateRegistry{})+ result := tx.Where("id = ?", id).Delete(&TemplateRegistry{})if result.Error != nil {return result.Error}@@ -573,7 +572,7 @@ func (s *TemplateService) DeleteRegistry(ctx context.Context, id string) error {return nil}-func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]models.ComposeTemplate, error) {+func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]ComposeTemplate, error) {registries, err := s.GetRegistries(ctx)if err != nil {return nil, err@@ -581,7 +580,7 @@ func (s *TemplateService) loadRemoteTemplates(ctx context.Context) ([]models.Comvar (mu sync.Mutex- templates []models.ComposeTemplate+ templates []ComposeTemplate)g, groupCtx := errgroup.WithContext(ctx)@@ -654,7 +653,7 @@ func (s *TemplateService) doGET(ctx context.Context, url string) ([]byte, error)// fetchRegistryTemplates performs a conditional GET using If-Modified-Since.// If the server replies 304 Not Modified, cached templates for the registry are reused.-func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *models.TemplateRegistry) ([]models.ComposeTemplate, error) {+func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *TemplateRegistry) ([]ComposeTemplate, error) {s.registryMu.RLock()fetchMeta := s.registryFetchMeta[reg.ID]s.registryMu.RUnlock()@@ -693,7 +692,7 @@ func (s *TemplateService) fetchRegistryTemplates(ctx context.Context, reg *modelreturn nil, errors.WrapIf(err, "parse registry JSON")}- templates := make([]models.ComposeTemplate, 0, len(regDTO.Templates))+ templates := make([]ComposeTemplate, 0, len(regDTO.Templates))for _, remoteTemplate := range regDTO.Templates {templates = append(templates, s.convertRemoteToLocal(remoteTemplate, reg))}@@ -726,11 +725,11 @@ func (s *TemplateService) fetchRegistryManifest(ctx context.Context, url string)return ®, nil}-func (s *TemplateService) convertRemoteToLocal(remote tmpl.RemoteTemplate, registry *models.TemplateRegistry) models.ComposeTemplate {+func (s *TemplateService) convertRemoteToLocal(remote tmpl.RemoteTemplate, registry *TemplateRegistry) ComposeTemplate {publicID := fmt.Sprintf("%s:%s:%s", remoteIDPrefix, registry.ID, remote.ID)- return models.ComposeTemplate{- BaseModel: models.BaseModel{ID: publicID},+ return ComposeTemplate{+ BaseModel: database.BaseModel{ID: publicID},Name: remote.Name,Description: remote.Description,Content: "",@@ -739,7 +738,7 @@ func (s *TemplateService) convertRemoteToLocal(remote tmpl.RemoteTemplate, regisIsRemote: true,RegistryID: mo.EmptyableToOption(strings.TrimSpace(registry.ID)).ToPointer(),Registry: cloneRegistry(registry),- Metadata: &models.ComposeTemplateMetadata{+ Metadata: &ComposeTemplateMetadata{Version: mo.EmptyableToOption(strings.TrimSpace(remote.Version)).ToPointer(),Author: mo.EmptyableToOption(strings.TrimSpace(remote.Author)).ToPointer(),Tags: remote.Tags,@@ -750,7 +749,7 @@ func (s *TemplateService) convertRemoteToLocal(remote tmpl.RemoteTemplate, regis}}-func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *models.ComposeTemplate) (string, string, error) {+func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *ComposeTemplate) (string, string, error) {if !template.IsRemote {envContent := ""if template.EnvContent != nil {@@ -765,7 +764,7 @@ func (s *TemplateService) FetchTemplateContent(ctx context.Context, template *moreturn s.fetchRemoteTemplateFiles(ctx, template)}-func (s *TemplateService) fetchRemoteTemplateFiles(ctx context.Context, template *models.ComposeTemplate) (string, string, error) {+func (s *TemplateService) fetchRemoteTemplateFiles(ctx context.Context, template *ComposeTemplate) (string, string, error) {if template == nil || template.Metadata == nil || template.Metadata.RemoteURL == nil {return "", "", errors.New("not a remote template or missing remote URL")}@@ -787,7 +786,7 @@ func (s *TemplateService) fetchRemoteTemplateFiles(ctx context.Context, templatereturn composeContent, envContent, nil}-func (s *TemplateService) enrichRemoteTemplateIcons(ctx context.Context, templates []models.ComposeTemplate) {+func (s *TemplateService) enrichRemoteTemplateIcons(ctx context.Context, templates []ComposeTemplate) {if len(templates) == 0 {return}@@ -866,7 +865,7 @@ func (s *TemplateService) newSafeRequestInternal(ctx context.Context, method, rareturn client, req, nil}-func (s *TemplateService) DownloadTemplate(ctx context.Context, remoteTemplate *models.ComposeTemplate) (*models.ComposeTemplate, error) {+func (s *TemplateService) DownloadTemplate(ctx context.Context, remoteTemplate *ComposeTemplate) (*ComposeTemplate, error) {if !remoteTemplate.IsRemote {return nil, errors.New("template is not remote")}@@ -882,11 +881,11 @@ func (s *TemplateService) DownloadTemplate(ctx context.Context, remoteTemplate *return s.downloadTemplateTransaction(ctx, remoteTemplate, base, composePath, envPath, srcDesc)}-func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remoteTemplate *models.ComposeTemplate, base, composePath, envPath, srcDesc string) (*models.ComposeTemplate, error) {- var resultTemplate *models.ComposeTemplate+func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remoteTemplate *ComposeTemplate, base, composePath, envPath, srcDesc string) (*ComposeTemplate, error) {+ var resultTemplate *ComposeTemplateerr := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var existing models.ComposeTemplate+ var existing ComposeTemplateif err := tx.Where("is_remote = ? AND registry_id IS NULL AND (description = ? OR name = ?)", false, srcDesc, base).First(&existing).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {@@ -925,8 +924,8 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remotreturn werr}- localTemplate := &models.ComposeTemplate{- BaseModel: models.BaseModel{ID: uuid.NewString()},+ localTemplate := &ComposeTemplate{+ BaseModel: database.BaseModel{ID: uuid.NewString()},Name: base,Description: srcDesc,Content: composeContent,@@ -950,7 +949,7 @@ func (s *TemplateService) downloadTemplateTransaction(ctx context.Context, remotreturn resultTemplate, nil}-func (s *TemplateService) templateBaseFromRemote(remoteTemplate *models.ComposeTemplate) string {+func (s *TemplateService) templateBaseFromRemote(remoteTemplate *ComposeTemplate) string {base := projects.Slugify(remoteTemplate.Name)if base != "" {return base@@ -965,11 +964,11 @@ func (s *TemplateService) templateBaseFromRemote(remoteTemplate *models.ComposeTreturn base}-func cloneTemplateMetadata(meta *models.ComposeTemplateMetadata) *models.ComposeTemplateMetadata {+func cloneTemplateMetadata(meta *ComposeTemplateMetadata) *ComposeTemplateMetadata {if meta == nil {return nil}- return &models.ComposeTemplateMetadata{+ return &ComposeTemplateMetadata{Version: mo.EmptyableToOption(strings.TrimSpace(mo.PointerToOption(meta.Version).OrEmpty())).ToPointer(),Author: mo.EmptyableToOption(strings.TrimSpace(mo.PointerToOption(meta.Author).OrEmpty())).ToPointer(),Tags: append([]string(nil), meta.Tags...),@@ -980,12 +979,12 @@ func cloneTemplateMetadata(meta *models.ComposeTemplateMetadata) *models.Compose}}-func cloneRemoteTemplates(items []models.ComposeTemplate) []models.ComposeTemplate {+func cloneRemoteTemplates(items []ComposeTemplate) []ComposeTemplate {if len(items) == 0 {return nil}- cloned := make([]models.ComposeTemplate, len(items))+ cloned := make([]ComposeTemplate, len(items))for i := range items {cloned[i] = items[i]cloned[i].RegistryID = mo.EmptyableToOption(strings.TrimSpace(mo.PointerToOption(items[i].RegistryID).OrEmpty())).ToPointer()@@ -995,7 +994,7 @@ func cloneRemoteTemplates(items []models.ComposeTemplate) []models.ComposeTemplareturn cloned}-func cloneRegistry(registry *models.TemplateRegistry) *models.TemplateRegistry {+func cloneRegistry(registry *TemplateRegistry) *TemplateRegistry {if registry == nil {return nil}@@ -1021,7 +1020,7 @@ func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, deiconURL := s.resolveTemplateIconURL(ctx, compose, mo.PointerToOption(envPtr).OrEmpty())return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- var existing models.ComposeTemplate+ var existing ComposeTemplate// Match on description (which encodes the absolute compose path) OR name (folder name).// Matching on name as a fallback keeps a single row across templates-directory// reconfigurations or compose-filename renames within the same folder, but@@ -1047,8 +1046,8 @@ func (s *TemplateService) upsertFilesystemTemplate(ctx context.Context, name, dereturn errors.WrapIf(q.Error, "query existing template")}- tpl := &models.ComposeTemplate{- BaseModel: models.BaseModel{ID: uuid.NewString()},+ tpl := &ComposeTemplate{+ BaseModel: database.BaseModel{ID: uuid.NewString()},Name: name,Description: desc,Content: compose,@@ -1222,7 +1221,7 @@ func (s *TemplateService) resolveTemplateIconURL(ctx context.Context, composeConreturn mo.EmptyableToOption(strings.TrimSpace(icon)).ToPointer()}-func setTemplateIconURL(template *models.ComposeTemplate, iconURL *string) {+func setTemplateIconURL(template *ComposeTemplate, iconURL *string) {if template == nil {return}@@ -1231,7 +1230,7 @@ func setTemplateIconURL(template *models.ComposeTemplate, iconURL *string) {if iconURL == nil {return}- template.Metadata = &models.ComposeTemplateMetadata{}+ template.Metadata = &ComposeTemplateMetadata{}}template.Metadata.IconURL = iconURL@@ -1292,12 +1291,12 @@ func (s *TemplateService) GetTemplateContentWithParsedData(ctx context.Context,}, nil}-func (s *TemplateService) getMergedTemplates(ctx context.Context) ([]models.ComposeTemplate, error) {+func (s *TemplateService) getMergedTemplates(ctx context.Context) ([]ComposeTemplate, error) {if err := s.syncFilesystemTemplatesInternal(ctx); err != nil {slog.WarnContext(ctx, "failed to sync filesystem templates", "error", err)}- var templates []models.ComposeTemplate+ var templates []ComposeTemplate// Use Omit to avoid fetching heavy content fields which are not needed for listingif err := s.db.WithContext(ctx).Omit("Content", "EnvContent").Preload("Registry").Find(&templates).Error; err != nil {return nil, errors.WrapIf(err, "failed to get local templates")diff --git a/backend/internal/template/service_test.go b/backend/internal/template/service_test.goindex 23301701a..8ee15aeeb 100644--- a/backend/internal/template/service_test.go+++ b/backend/internal/template/service_test.go@@ -23,7 +23,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"httputils "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"@@ -35,7 +34,7 @@ func setupTemplateServiceTestDB(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.TemplateRegistry{}, &models.ComposeTemplate{}))+ require.NoError(t, db.AutoMigrate(&TemplateRegistry{}, &ComposeTemplate{}))return &database.DB{DB: db}}@@ -213,8 +212,8 @@ services:lookupIP: lookupIP,registryFetchMeta: make(map[string]*registryFetchMeta),}- registry := &models.TemplateRegistry{- BaseModel: models.BaseModel{ID: "reg-1"},+ registry := &TemplateRegistry{+ BaseModel: database.BaseModel{ID: "reg-1"},Name: "Demo Registry",URL: registryURL,Enabled: true,@@ -272,14 +271,14 @@ services:registryFetchMeta: make(map[string]*registryFetchMeta),}- remoteTemplate := &models.ComposeTemplate{- BaseModel: models.BaseModel{ID: "remote:reg-1:demo"},+ remoteTemplate := &ComposeTemplate{+ BaseModel: database.BaseModel{ID: "remote:reg-1:demo"},Name: "Demo Template",Description: "Remote template",IsRemote: true,IsCustom: false,RegistryID: mo.EmptyableToOption(strings.TrimSpace("reg-1")).ToPointer(),- Metadata: &models.ComposeTemplateMetadata{+ Metadata: &ComposeTemplateMetadata{RemoteURL: mo.EmptyableToOption(strings.TrimSpace(baseURL + "/compose.yaml")).ToPointer(),EnvURL: mo.EmptyableToOption(strings.TrimSpace(baseURL + "/template.env")).ToPointer(),IconURL: mo.EmptyableToOption(strings.TrimSpace("https://cdn.example/download.png")).ToPointer(),@@ -294,7 +293,7 @@ services:require.NotNil(t, downloaded.Metadata.IconURL)require.Equal(t, "https://cdn.example/download.png", *downloaded.Metadata.IconURL)- var stored models.ComposeTemplate+ var stored ComposeTemplaterequire.NoError(t, service.db.WithContext(context.Background()).First(&stored, "id = ?", downloaded.ID).Error)require.NotNil(t, stored.Metadata)require.NotNil(t, stored.Metadata.IconURL)@@ -307,9 +306,9 @@ func TestGetAllTemplatesPaginated_FiltersByType(t *testing.T) {now := time.Now()db := setupTemplateServiceTestDB(t)- localTemplates := []models.ComposeTemplate{+ localTemplates := []ComposeTemplate{{- BaseModel: models.BaseModel{ID: "local-one", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "local-one", CreatedAt: now, UpdatedAt: &now},Name: "Local One",Description: "Local template",Content: "services: {}",@@ -317,7 +316,7 @@ func TestGetAllTemplatesPaginated_FiltersByType(t *testing.T) {IsRemote: false,},{- BaseModel: models.BaseModel{ID: "local-two", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "local-two", CreatedAt: now, UpdatedAt: &now},Name: "Local Two",Description: "Local template",Content: "services: {}",@@ -328,9 +327,9 @@ func TestGetAllTemplatesPaginated_FiltersByType(t *testing.T) {require.NoError(t, db.WithContext(context.Background()).Create(&localTemplates).Error)service := NewTemplateService(context.Background(), db, http.DefaultClient, nil)- service.remoteCache.Set(struct{}{}, []models.ComposeTemplate{+ service.remoteCache.Set(struct{}{}, []ComposeTemplate{{- BaseModel: models.BaseModel{ID: "remote-one", CreatedAt: now, UpdatedAt: &now},+ BaseModel: database.BaseModel{ID: "remote-one", CreatedAt: now, UpdatedAt: &now},Name: "Remote One",Description: "Remote template",Content: "services: {}",@@ -406,7 +405,7 @@ services:require.NoError(t, service.syncFilesystemTemplatesInternal(context.Background()))- var stored models.ComposeTemplate+ var stored ComposeTemplaterequire.NoError(t, service.db.WithContext(context.Background()).First(&stored, "name = ?", "example").Error)require.NotNil(t, stored.Metadata)require.NotNil(t, stored.Metadata.IconURL)@@ -449,8 +448,8 @@ func TestGetTemplate_ForceRefreshesRemoteCacheOnMiss(t *testing.T) {client, lookupIP, baseURL := makePublicTestClient(t, server)db := setupTemplateServiceTestDB(t)- registry := &models.TemplateRegistry{- BaseModel: models.BaseModel{ID: "reg-1"},+ registry := &TemplateRegistry{+ BaseModel: database.BaseModel{ID: "reg-1"},Name: "Demo",URL: baseURL + "/registry.json",Enabled: true,@@ -485,7 +484,7 @@ func minimalSettingsServiceForTest(t *testing.T) *settings.SettingsService {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))svc, err := newSettingsServiceForTestInternal(t, context.Background(), &database.DB{DB: db})require.NoError(t, err)return svcdiff --git a/backend/internal/updater/handler.go b/backend/internal/updater/handler.goindex 14d16d9e1..09f5eca91 100644--- a/backend/internal/updater/handler.go+++ b/backend/internal/updater/handler.go@@ -7,7 +7,6 @@ import ("emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"@@ -55,7 +54,7 @@ type GetUpdaterHistoryInput struct {}type GetUpdaterHistoryOutput struct {- Body base.ApiResponse[[]models.AutoUpdateRecord]+ Body base.ApiResponse[[]AutoUpdateRecord]}// RegisterUpdater registers updater management routes using Huma.@@ -152,7 +151,7 @@ func (h *UpdaterHandler) GetUpdaterHistory(ctx context.Context, input *GetUpdate}return &GetUpdaterHistoryOutput{- Body: base.ApiResponse[[]models.AutoUpdateRecord]{+ Body: base.ApiResponse[[]AutoUpdateRecord]{Success: true,Data: history,},diff --git a/backend/internal/models/auto_update.go b/backend/internal/updater/model.gosimilarity index 79%rename from backend/internal/models/auto_update.gorename to backend/internal/updater/model.goindex ad194c977..8537e84f6 100644--- a/backend/internal/models/auto_update.go+++ b/backend/internal/updater/model.go@@ -1,6 +1,8 @@-package models+package updaterimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"time")@@ -17,7 +19,7 @@ const ()type AutoUpdateRecord struct {- BaseModel+ database.BaseModelResourceID string `json:"resourceId"`ResourceType string `json:"resourceType"`@@ -27,10 +29,10 @@ type AutoUpdateRecord struct {EndTime *time.Time `json:"endTime,omitempty"`UpdateAvailable bool `json:"updateAvailable"`UpdateApplied bool `json:"updateApplied"`- OldImageVersions JSON `json:"oldImageVersions,omitempty" gorm:"type:text"`- NewImageVersions JSON `json:"newImageVersions,omitempty" gorm:"type:text"`+ OldImageVersions database.JSON `json:"oldImageVersions,omitempty" gorm:"type:text"`+ NewImageVersions database.JSON `json:"newImageVersions,omitempty" gorm:"type:text"`Error *string `json:"error,omitempty"`- Details JSON `json:"details,omitempty" gorm:"type:text"`+ Details database.JSON `json:"details,omitempty" gorm:"type:text"`}func (AutoUpdateRecord) TableName() string {diff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.goindex d358b8765..4603078d2 100644--- a/backend/internal/updater/service.go+++ b/backend/internal/updater/service.go@@ -12,6 +12,8 @@ import ("sync""time"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors""github.com/compose-spec/compose-go/v2/loader"@@ -22,9 +24,8 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/notification"- "github.com/getarcaneapp/arcane/backend/v2/internal/project"+ projectpkg "github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil"@@ -58,7 +59,7 @@ type updaterDependenciesInternal struct {DB *database.DBDocker *docker.DockerClientServiceSettings *settings.SettingsService- Projects *project.ProjectService+ Projects *projectpkg.ProjectServiceImagePuller *image.ImageServiceImageUpdates *imageupdate.ImageUpdateServiceRegistryDigestResolver *registry.ContainerRegistryService@@ -66,14 +67,14 @@ type updaterDependenciesInternal struct {Notifications *notification.NotificationServiceSelfUpgrade selfUpgradeServiceInternalActivity *activity.ActivityService- SystemUser models.User+ SystemUser common.UserLogger *slog.Logger}type selfUpgradeServiceInternal interface {// TriggerUpgradeViaCLI returns the spawned upgrader container's ID, which this// service does not need — only update-all's manager step uses it.- TriggerUpgradeViaCLI(ctx context.Context, user models.User, target updater.SelfUpdateTarget) (string, error)+ TriggerUpgradeViaCLI(ctx context.Context, user common.User, target updater.SelfUpdateTarget) (string, error)}// NewUpdaterService constructs the Arcane updater facade.@@ -81,7 +82,7 @@ func NewUpdaterService(db *database.DB,settings *settings.SettingsService,docker *docker.DockerClientService,- projects *project.ProjectService,+ projects *projectpkg.ProjectService,imageUpdates *imageupdate.ImageUpdateService,registries *registry.ContainerRegistryService,events *event.EventService,@@ -103,7 +104,7 @@ func NewUpdaterService(Notifications: notifications,SelfUpgrade: upgrade,Activity: activityService,- SystemUser: models.SystemUser,+ SystemUser: common.SystemUser,},}engine, err := updater.New(service.configInternal())@@ -200,7 +201,7 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, options arcaneupdaterrunCtx, cancelRun := context.WithTimeout(ctx, timeouts.DefaultAutoUpdateApply)defer cancelRun()- s.recordAutoUpdateEventInternal(ctx, models.EventSeverityInfo, models.JSON{+ s.recordAutoUpdateEventInternal(ctx, event.EventSeverityInfo, database.JSON{"phase": "start","dryRun": options.DryRun,"forceUpdate": options.ForceUpdate,@@ -234,7 +235,7 @@ func (s *UpdaterService) ApplyPending(ctx context.Context, options arcaneupdater}}- s.recordAutoUpdateEventInternal(ctx, models.EventSeverityInfo, models.JSON{+ s.recordAutoUpdateEventInternal(ctx, event.EventSeverityInfo, database.JSON{"phase": "complete","checked": out.Checked,"updated": out.Updated,@@ -437,8 +438,8 @@ func (s *UpdaterService) GetStatus() arcaneupdater.Status {}// GetHistory returns the most recent auto-update history records, newest first.-func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]models.AutoUpdateRecord, error) {- var records []models.AutoUpdateRecord+func (s *UpdaterService) GetHistory(ctx context.Context, limit int) ([]AutoUpdateRecord, error) {+ var records []AutoUpdateRecordquery := s.deps.DB.WithContext(ctx).Order("start_time DESC")if limit > 0 {query = query.Limit(limit)@@ -478,13 +479,13 @@ func (s *UpdaterService) BeginProjectUpdate(projectID string) func() {return s.engineInternal().BeginProjectUpdate(projectID)}-func (s *UpdaterService) recordAutoUpdateEventInternal(ctx context.Context, severity models.EventSeverity, metadata models.JSON) {+func (s *UpdaterService) recordAutoUpdateEventInternal(ctx context.Context, severity event.EventSeverity, metadata database.JSON) {if s.deps.Events == nil {return}phase, _ := metadata["phase"].(string)_, err := s.deps.Events.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeSystemAutoUpdate,+ Type: event.EventTypeSystemAutoUpdate,Severity: severity,Title: autoUpdateEventTitleInternal(phase, metadata),ResourceType: mo.EmptyableToOption(strings.TrimSpace("system")).ToPointer(),@@ -504,7 +505,7 @@ func instanceTypeFromLabelsInternal(labelMap map[string]string) string {return "server"}-func autoUpdateEventTitleInternal(phase string, metadata models.JSON) string {+func autoUpdateEventTitleInternal(phase string, metadata database.JSON) string {switch phase {case "start":return "Auto-update run started"@@ -598,7 +599,7 @@ func (s *UpdaterService) PendingImageUpdates(ctx context.Context) ([]updater.Imareturn nil, common.Classify(common.ErrUnavailable, errors.New("database unavailable"))}- var records []models.ImageUpdateRecord+ var records []imageupdate.ImageUpdateRecordif err := s.deps.DB.WithContext(ctx).Where("has_update = ?", true).Find(&records).Error; err != nil {return nil, errors.WrapIf(err, "query pending image updates")}@@ -712,7 +713,7 @@ func (s *UpdaterService) markSelfUpdateTriggeredInternal(ctx context.Context, tamessage = "Self-update initiated — Arcane will restart with " + ref}s.appendAutoUpdateActivityMessageInternal(ctx, activityID, message, "Self-update", 90)- if err := s.deps.Activity.PatchActivityMetadata(ctx, activityID, models.JSON{"selfUpdateTriggered": true}); err != nil {+ if err := s.deps.Activity.PatchActivityMetadata(ctx, activityID, database.JSON{"selfUpdateTriggered": true}); err != nil {slog.DebugContext(ctx, "failed to mark self-update on activity", "activityId", activityID, "error", err)}}@@ -732,12 +733,12 @@ func (s *UpdaterService) Notify(ctx context.Context, notification updater.Notifi}// RecordEvent records updater lifecycle events in Arcane's event stream.-func (s *UpdaterService) RecordEvent(ctx context.Context, event updater.Event) error {+func (s *UpdaterService) RecordEvent(ctx context.Context, evt updater.Event) error {if s == nil {return nil}- eventType, ok := containerEventTypeInternal(event.Phase).Get()+ eventType, ok := containerEventTypeInternal(evt.Phase).Get()if ok {if s.deps.Events == nil {return nil@@ -745,43 +746,43 @@ func (s *UpdaterService) RecordEvent(ctx context.Context, event updater.Event) ereturn s.deps.Events.LogContainerEvent(ctx,eventType,- event.ResourceID,- event.ResourceName,+ evt.ResourceID,+ evt.ResourceName,s.deps.SystemUser.ID,s.deps.SystemUser.Username,"0",- event.Metadata,+ evt.Metadata,)}- severity := models.EventSeverityInfo- if strings.EqualFold(event.Severity, "error") {- severity = models.EventSeverityError+ severity := event.EventSeverityInfo+ if strings.EqualFold(evt.Severity, "error") {+ severity = event.EventSeverityError}- s.recordAutoUpdateEventInternal(ctx, severity, models.JSON{- "phase": event.Phase,- "resourceId": event.ResourceID,- "resourceName": event.ResourceName,- "resourceType": event.ResourceType,+ s.recordAutoUpdateEventInternal(ctx, severity, database.JSON{+ "phase": evt.Phase,+ "resourceId": evt.ResourceID,+ "resourceName": evt.ResourceName,+ "resourceType": evt.ResourceType,"time": time.Now().UTC().Format(time.RFC3339),})return nil}-func containerEventTypeInternal(phase string) mo.Option[models.EventType] {+func containerEventTypeInternal(phase string) mo.Option[event.EventType] {switch phase {case "container_stop":- return mo.Some(models.EventTypeContainerStop)+ return mo.Some(event.EventTypeContainerStop)case "container_delete":- return mo.Some(models.EventTypeContainerDelete)+ return mo.Some(event.EventTypeContainerDelete)case "container_create":- return mo.Some(models.EventTypeContainerCreate)+ return mo.Some(event.EventTypeContainerCreate)case "container_start":- return mo.Some(models.EventTypeContainerStart)+ return mo.Some(event.EventTypeContainerStart)case "container_update":- return mo.Some(models.EventTypeContainerUpdate)+ return mo.Some(event.EventTypeContainerUpdate)default:- return mo.None[models.EventType]()+ return mo.None[event.EventType]()}}@@ -809,13 +810,13 @@ func (s *UpdaterService) startAutoUpdateActivityInternal(ctx context.Context, dr}activity, err := s.deps.Activity.StartActivity(ctx, activitylib.StartRequest{EnvironmentID: "0",- Type: models.ActivityTypeAutoUpdate,+ Type: activitytypes.TypeAutoUpdate,Queue: true,ResourceType: mo.EmptyableToOption(strings.TrimSpace("system")).ToPointer(),ResourceName: mo.EmptyableToOption(strings.TrimSpace("Auto update")).ToPointer(),Step: "Planning updates",LatestMessage: "Auto-update run started",- Metadata: models.JSON{"dryRun": dryRun},+ Metadata: database.JSON{"dryRun": dryRun},})if err != nil {slog.DebugContext(ctx, "failed to start auto-update activity", "error", err)@@ -830,14 +831,14 @@ func (s *UpdaterService) startSingleContainerUpdateActivityInternal(ctx context.}activity, err := s.deps.Activity.StartActivity(ctx, activitylib.StartRequest{EnvironmentID: "0",- Type: models.ActivityTypeAutoUpdate,+ Type: activitytypes.TypeAutoUpdate,Queue: true,ResourceType: mo.EmptyableToOption(strings.TrimSpace("container")).ToPointer(),ResourceID: &containerID,ResourceName: mo.EmptyableToOption(strings.TrimSpace(containerID)).ToPointer(),Step: "Updating container",LatestMessage: "Container update started",- Metadata: models.JSON{"containerID": containerID},+ Metadata: database.JSON{"containerID": containerID},})if err != nil {slog.DebugContext(ctx, "failed to start container update activity", "containerID", containerID, "error", err)@@ -854,7 +855,7 @@ func (s *UpdaterService) appendAutoUpdateActivityMessageInternal(ctx context.Constep = message}if _, err := s.deps.Activity.AppendMessage(ctx, activityID, activitylib.AppendMessageRequest{- Level: models.ActivityMessageLevelInfo,+ Level: activitytypes.MessageLevelInfo,Message: message,Progress: &progress,Step: step,@@ -868,22 +869,22 @@ func (s *UpdaterService) completeAutoUpdateActivityInternal(ctx context.Context,return}- status := models.ActivityStatusSuccess+ status := activitytypes.StatusSuccessmessage := "Auto-update run completed"var errMessage *stringif applyErr != nil {- status = models.ActivityStatusFailed+ status = activitytypes.StatusFailederrText := applyErr.Error()errMessage = &errTextmessage = errText} else if result != nil && result.Failed > 0 {- status = models.ActivityStatusFailed+ status = activitytypes.StatusFailederrText := fmt.Sprintf("%d update action(s) failed", result.Failed)errMessage = &errTextmessage = errText}- if status == models.ActivityStatusFailed && activitylib.CancelledByContext(ctx) {- status = models.ActivityStatusCancelled+ if status == activitytypes.StatusFailed && activitylib.CancelledByContext(ctx) {+ status = activitytypes.StatusCancelledmessage = "Auto-update cancelled"errMessage = nil}@@ -902,7 +903,7 @@ func (s *UpdaterService) trackActivityInternal(ctx context.Context, activityID sreturn s.deps.Activity.Track(ctx, activityID)}-func imageUpdateRecordToModuleInternal(record models.ImageUpdateRecord) updater.ImageUpdateRecord {+func imageUpdateRecordToModuleInternal(record imageupdate.ImageUpdateRecord) updater.ImageUpdateRecord {return updater.ImageUpdateRecord{ID: record.ID,Repository: record.Repository,@@ -1002,11 +1003,11 @@ func statusFromModuleInternal(status updater.Status) arcaneupdater.Status {func (s *UpdaterService) recordRunInternal(ctx context.Context, item arcaneupdater.ResourceResult) error {now := time.Now()- record := &models.AutoUpdateRecord{+ record := &AutoUpdateRecord{ResourceID: item.ResourceID,ResourceType: item.ResourceType,ResourceName: item.ResourceName,- Status: models.AutoUpdateStatus(item.Status),+ Status: AutoUpdateStatus(item.Status),StartTime: now,EndTime: &now,UpdateAvailable: item.UpdateAvailable || item.Status == string(updater.StatusUpdated) || item.Status == string(updater.StatusUpdateAvailable),@@ -1026,29 +1027,29 @@ func (s *UpdaterService) clearImageUpdateRecordForModuleInternal(ctx context.Conreturn nil}- query := s.deps.DB.WithContext(ctx).Model(&models.ImageUpdateRecord{})+ query := s.deps.DB.WithContext(ctx).Model(&imageupdate.ImageUpdateRecord{})if strings.TrimSpace(record.ID) != "" {return query.Where("id = ?", record.ID).Update("has_update", false).Error}return query.Where("repository = ? AND tag = ?", record.Repository, record.Tag).Update("has_update", false).Error}-func mapToJSONInternal(values map[string]string) models.JSON {+func mapToJSONInternal(values map[string]string) database.JSON {if len(values) == 0 {return nil}- out := make(models.JSON, len(values))+ out := make(database.JSON, len(values))for key, value := range values {out[key] = value}return out}-func detailsToJSONInternal(values map[string]any) models.JSON {+func detailsToJSONInternal(values map[string]any) database.JSON {if len(values) == 0 {return nil}- out := make(models.JSON, len(values))+ out := make(database.JSON, len(values))maps.Copy(out, values)return out}@@ -1058,14 +1059,14 @@ func (s *UpdaterService) logResultItemsInternal(ctx context.Context, result *arcreturn}for _, item := range result.Items {- severity := models.EventSeverityInfo+ severity := event.EventSeverityInfoswitch item.Status {case string(updater.StatusFailed):- severity = models.EventSeverityError+ severity = event.EventSeverityErrorcase string(updater.StatusUpdated):- severity = models.EventSeveritySuccess+ severity = event.EventSeveritySuccess}- s.recordAutoUpdateEventInternal(ctx, severity, models.JSON{+ s.recordAutoUpdateEventInternal(ctx, severity, database.JSON{"phase": item.ResourceType,"resourceId": item.ResourceID,"resourceName": item.ResourceName,@@ -1258,13 +1259,13 @@ func (s *UpdaterService) collectUsedImagesFromProjectsInternal(ctx context.Contereturn nil}-func activeComposeProjectNameSetInternal(projects []models.Project) map[string]struct{} {+func activeComposeProjectNameSetInternal(projects []projectpkg.Project) map[string]struct{} {active := make(map[string]struct{})for _, project := range projects {if project.IsArchived {continue}- if project.Status != models.ProjectStatusRunning && project.Status != models.ProjectStatusPartiallyRunning {+ if project.Status != projectpkg.ProjectStatusRunning && project.Status != projectpkg.ProjectStatusPartiallyRunning {continue}diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.goindex 2ba487c23..d51293f15 100644--- a/backend/internal/updater/service_test.go+++ b/backend/internal/updater/service_test.go@@ -1,6 +1,12 @@package updaterimport (+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"bytes""context""encoding/json"@@ -22,7 +28,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/image""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/notification""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/registry"@@ -195,11 +200,11 @@ func newUpdaterApplyPendingDockerServerInternal(type mockSystemUpgradeServiceInternal struct {triggerCalled booltriggerError error- capturedUser *models.User+ capturedUser *common.UsercapturedTarget *updater.SelfUpdateTarget}-func (m *mockSystemUpgradeServiceInternal) TriggerUpgradeViaCLI(_ context.Context, user models.User, target updater.SelfUpdateTarget) (string, error) {+func (m *mockSystemUpgradeServiceInternal) TriggerUpgradeViaCLI(_ context.Context, user common.User, target updater.SelfUpdateTarget) (string, error) {m.triggerCalled = truem.capturedUser = &userm.capturedTarget = &target@@ -275,8 +280,8 @@ func TestUpdaterService_TriggerSelfUpdateViaCLIInternal(t *testing.T) {require.NoError(t, err)assert.True(t, mockUpgrade.triggerCalled)require.NotNil(t, mockUpgrade.capturedUser)- assert.Equal(t, models.SystemUser.ID, mockUpgrade.capturedUser.ID)- assert.Equal(t, models.SystemUser.Username, mockUpgrade.capturedUser.Username)+ assert.Equal(t, common.SystemUser.ID, mockUpgrade.capturedUser.ID)+ assert.Equal(t, common.SystemUser.Username, mockUpgrade.capturedUser.Username)require.NotNil(t, mockUpgrade.capturedTarget)assert.Equal(t, "container-1", mockUpgrade.capturedTarget.ContainerID)assert.Equal(t, "arcane", mockUpgrade.capturedTarget.ContainerName)@@ -416,7 +421,7 @@ func TestUpdaterService_PullImageAdapterInternal(t *testing.T) {t.Run("passes database registry credentials to Arcane image puller", func(t *testing.T) {db := setupProjectTestDBInternal(t)- require.NoError(t, db.AutoMigrate(&models.ContainerRegistry{}, &models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(®istry.ContainerRegistry{}, &kv.KVEntry{}))crypto.InitEncryption(&crypto.Config{Environment: string(config.AppEnvironmentTest),EncryptionKey: "test-encryption-key-for-testing-32bytes-min",@@ -459,12 +464,12 @@ func TestUpdaterService_PendingImageUpdatesAdapterInternal(t *testing.T) {latestDigest := "sha256:2222222222222222222222222222222222222222222222222222222222222222"lastError := "previous check failed"checkTime := time.Now().Add(-time.Hour).UTC()- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "pending",Repository: "registry.example.com/team/app",Tag: "1.2.3",HasUpdate: true,- UpdateType: models.UpdateTypeTag,+ UpdateType: imageupdate.UpdateTypeTag,CurrentVersion: "1.2.3",LatestVersion: &latest,CurrentDigest: ¤tDigest,@@ -472,12 +477,12 @@ func TestUpdaterService_PendingImageUpdatesAdapterInternal(t *testing.T) {CheckTime: checkTime,LastError: &lastError,}).Error)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "not-pending",Repository: "registry.example.com/team/old",Tag: "1.0.0",HasUpdate: false,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CheckTime: checkTime,}).Error)svc, svcErr := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)@@ -506,7 +511,7 @@ func TestUpdaterService_PendingImageUpdatesAdapterInternal(t *testing.T) {func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(t *testing.T) {ctx := context.Background()db := setupProjectTestDBInternal(t)- require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}, &models.NotificationSettings{}))+ require.NoError(t, db.AutoMigrate(&imageupdate.ImageUpdateRecord{}, ¬ification.NotificationSettings{}))var calls atomic.Int32server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {@@ -514,10 +519,10 @@ func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(tw.WriteHeader(http.StatusOK)}))defer server.Close()- require.NoError(t, db.Create(&models.NotificationSettings{- Provider: models.NotificationProviderGeneric,+ require.NoError(t, db.Create(¬ification.NotificationSettings{+ Provider: notifications.NotificationProviderGeneric,Enabled: true,- Config: models.JSON{+ Config: database.JSON{"webhookUrl": server.URL,"method": "POST","contentType": "application/json",@@ -529,7 +534,7 @@ func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(tsvc, svcErr := NewUpdaterService(db, nil, nil, nil, imageUpdates, nil, nil, nil, notif, nil, nil)require.NoError(t, svcErr)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:pending-unnotified",Repository: "test/repo",Tag: "latest",@@ -542,7 +547,7 @@ func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(trequire.NoError(t, err)require.Len(t, records, 1)require.EqualValues(t, 1, calls.Load())- var reloaded models.ImageUpdateRecord+ var reloaded imageupdate.ImageUpdateRecordrequire.NoError(t, db.First(&reloaded, "id = ?", "sha256:pending-unnotified").Error)assert.True(t, reloaded.NotificationSent)}@@ -553,14 +558,14 @@ func TestUpdaterService_PendingImageUpdatesFlushesPendingNotificationsInternal(tfunc TestUpdaterService_PendingImageUpdatesNoProvidersLeavesUnnotifiedInternal(t *testing.T) {ctx := context.Background()db := setupProjectTestDBInternal(t)- require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}, &models.NotificationSettings{}))+ require.NoError(t, db.AutoMigrate(&imageupdate.ImageUpdateRecord{}, ¬ification.NotificationSettings{}))notif := notification.NewNotificationService(db, nil, nil, nil)imageUpdates := imageupdate.NewImageUpdateService(db, nil, nil, nil, nil, notif, nil)svc, svcErr := NewUpdaterService(db, nil, nil, nil, imageUpdates, nil, nil, nil, notif, nil, nil)require.NoError(t, svcErr)- require.NoError(t, db.Create(&models.ImageUpdateRecord{+ require.NoError(t, db.Create(&imageupdate.ImageUpdateRecord{ID: "sha256:pending-no-provider",Repository: "test/repo",Tag: "latest",@@ -572,7 +577,7 @@ func TestUpdaterService_PendingImageUpdatesNoProvidersLeavesUnnotifiedInternal(trequire.NoError(t, err)require.Len(t, records, 1)- var reloaded models.ImageUpdateRecord+ var reloaded imageupdate.ImageUpdateRecordrequire.NoError(t, db.First(&reloaded, "id = ?", "sha256:pending-no-provider").Error)assert.False(t, reloaded.NotificationSent)}@@ -580,7 +585,7 @@ func TestUpdaterService_PendingImageUpdatesNoProvidersLeavesUnnotifiedInternal(tfunc TestUpdaterService_RecordUpdateRunAdapterInternal(t *testing.T) {ctx := context.Background()db := setupProjectTestDBInternal(t)- require.NoError(t, db.AutoMigrate(&models.AutoUpdateRecord{}))+ require.NoError(t, db.AutoMigrate(&AutoUpdateRecord{}))svc, svcErr := NewUpdaterService(db, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)require.NoError(t, svcErr)@@ -597,11 +602,11 @@ func TestUpdaterService_RecordUpdateRunAdapterInternal(t *testing.T) {})require.NoError(t, err)- var record models.AutoUpdateRecord+ var record AutoUpdateRecordrequire.NoError(t, db.First(&record, "resource_id = ?", "container-1").Error)assert.Equal(t, "web", record.ResourceName)assert.Equal(t, "container", record.ResourceType)- assert.Equal(t, models.AutoUpdateStatus(updater.StatusUpdated), record.Status)+ assert.Equal(t, AutoUpdateStatus(updater.StatusUpdated), record.Status)assert.True(t, record.UpdateAvailable)assert.True(t, record.UpdateApplied)assert.Equal(t, "nginx:1.2.3", record.OldImageVersions["main"])@@ -925,7 +930,7 @@ func createTestPullRegistryInternal(t *testing.T, db *database.DB, url, usernameencryptedToken, err := crypto.Encrypt(token)require.NoError(t, err)- reg := &models.ContainerRegistry{+ reg := ®istry.ContainerRegistry{URL: url,Username: username,Token: encryptedToken,@@ -1024,6 +1029,6 @@ func setupProjectTestDBInternal(t *testing.T) *database.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Project{}, &models.SettingVariable{}, &models.ImageUpdateRecord{}, &models.Event{}))+ require.NoError(t, db.AutoMigrate(&project.Project{}, &settings.SettingVariable{}, &imageupdate.ImageUpdateRecord{}, &event.Event{}))return &database.DB{DB: db}}diff --git a/backend/internal/user/handler.go b/backend/internal/user/handler.goindex 5540c90ac..71f52024d 100644--- a/backend/internal/user/handler.go+++ b/backend/internal/user/handler.go@@ -1,6 +1,8 @@package userimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""strings""time"@@ -10,7 +12,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"@@ -201,14 +202,14 @@ func (h *UserHandler) CreateUser(ctx context.Context, input *CreateUserInput) (*return nil, huma.Error500InternalServerError("Failed to hash password")}- userModel := &models.User{+ userModel := &common.User{Username: input.Body.Username,PasswordHash: hashedPassword,DisplayName: input.Body.DisplayName,Email: input.Body.Email,Locale: input.Body.Locale,TimeFormat: usertypes.TimeFormatAuto,- BaseModel: models.BaseModel{+ BaseModel: database.BaseModel{CreatedAt: time.Now(),},}@@ -338,7 +339,7 @@ func (h *UserHandler) DeleteUser(ctx context.Context, input *DeleteUserInput) (*// target. The service enforces the same check; this pre-check produces a// clean 403 without entering the delete path.callerPerms, _ := middleware.PermissionsFromContext(ctx)- caller, _ := models.CurrentUserFromContext(ctx)+ caller, _ := common.CurrentUserFromContext(ctx)if callerPerms != nil && !callerPerms.IsGlobalAdmin() && caller != nil && caller.ID != input.UserID {targetPerms, err := h.userService.ResolveUserPermissions(ctx, input.UserID)if err != nil {@@ -420,7 +421,7 @@ func NormalizeOptionalEmail(email *string) (*string, error) {// re-enforces the target-admin check.func (h *UserHandler) checkUpdateUserPrivilegesInternal(ctx context.Context, input *UpdateUserInput, targetID string) (*authz.PermissionSet, error) {callerPerms, _ := middleware.PermissionsFromContext(ctx)- caller, _ := models.CurrentUserFromContext(ctx)+ caller, _ := common.CurrentUserFromContext(ctx)if callerPerms != nil && !callerPerms.IsGlobalAdmin() {if input.Body.Password != nil && *input.Body.Password != "" && caller != nil && caller.ID != targetID {return nil, huma.Error403Forbidden(ErrInsufficientPrivilege.Error())diff --git a/backend/internal/models/user_avatar.go b/backend/internal/user/model.gosimilarity index 96%rename from backend/internal/models/user_avatar.gorename to backend/internal/user/model.goindex b02cdafba..773a49beb 100644--- a/backend/internal/models/user_avatar.go+++ b/backend/internal/user/model.go@@ -1,4 +1,4 @@-package models+package user// UserAvatar represents the raw profile picture data for a user.// Stored separately from the main User struct to preventdiff --git a/backend/internal/user/service.go b/backend/internal/user/service.goindex 09a772923..fbbcce189 100644--- a/backend/internal/user/service.go+++ b/backend/internal/user/service.go@@ -17,7 +17,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/internal/session""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"@@ -138,7 +137,7 @@ func (s *UserService) ValidatePassword(encodedHash, password string) error {return nil}-func (s *UserService) CreateUser(ctx context.Context, user *models.User) (*models.User, error) {+func (s *UserService) CreateUser(ctx context.Context, user *common.User) (*common.User, error) {err := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Create(user).Error; err != nil {return errors.WrapIf(err, "failed to create user")@@ -151,23 +150,23 @@ func (s *UserService) CreateUser(ctx context.Context, user *models.User) (*modelreturn user, nil}-func (s *UserService) GetUserByUsername(ctx context.Context, username string) (*models.User, error) {- return dbutil.FirstWhere[models.User](ctx, s.db.DB, common.ErrUserNotFound, "username = ?", username)+func (s *UserService) GetUserByUsername(ctx context.Context, username string) (*common.User, error) {+ return dbutil.FirstWhere[common.User](ctx, s.db.DB, common.ErrUserNotFound, "username = ?", username)}-func (s *UserService) GetUserByID(ctx context.Context, id string) (*models.User, error) {- return dbutil.FirstWhere[models.User](ctx, s.db.DB, common.ErrUserNotFound, "id = ?", id)+func (s *UserService) GetUserByID(ctx context.Context, id string) (*common.User, error) {+ return dbutil.FirstWhere[common.User](ctx, s.db.DB, common.ErrUserNotFound, "id = ?", id)}-func (s *UserService) GetUserByOidcSubjectId(ctx context.Context, subjectId string) (*models.User, error) {- return dbutil.FirstWhere[models.User](ctx, s.db.DB, common.ErrUserNotFound, "oidc_subject_id = ?", subjectId)+func (s *UserService) GetUserByOidcSubjectId(ctx context.Context, subjectId string) (*common.User, error) {+ return dbutil.FirstWhere[common.User](ctx, s.db.DB, common.ErrUserNotFound, "oidc_subject_id = ?", subjectId)}// GetUserByEmail returns the user with the given email. The schema does not// enforce email uniqueness, so a lookup matching more than one account returns// common.ErrAmbiguousUserEmail instead of arbitrarily selecting one.-func (s *UserService) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {- var users []models.User+func (s *UserService) GetUserByEmail(ctx context.Context, email string) (*common.User, error) {+ var users []common.Userif err := s.db.DB.WithContext(ctx).Where("email = ?", email).Limit(2).Find(&users).Error; err != nil {return nil, errors.WrapIf(err, "failed to query users by email")}@@ -187,7 +186,7 @@ func (s *UserService) ResolveUserPermissions(ctx context.Context, userID string)if s.roleService == nil {return nil, nil}- return s.roleService.ResolvePermissions(ctx, &models.User{BaseModel: models.BaseModel{ID: userID}})+ return s.roleService.ResolvePermissions(ctx, &common.User{BaseModel: database.BaseModel{ID: userID}})}// checkTargetPrivilegeInternal enforces actor-vs-target privilege ordering: a@@ -206,7 +205,7 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gormrevalidateActor := actorPerms != nil && !actorPerms.Sudo && actorPerms.IsGlobalAdmin() && s.roleService != nilactorID := ""if revalidateActor {- actor, ok := models.CurrentUserFromContext(ctx)+ actor, ok := common.CurrentUserFromContext(ctx)if !ok || actor == nil || actor.ID == "" {return ErrInsufficientPrivilege}@@ -217,7 +216,7 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gormif actorID != "" && actorID != targetID {userIDs = append(userIDs, actorID)}- var lockedUsers []models.User+ var lockedUsers []common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id IN ?", userIDs).@@ -263,7 +262,7 @@ func (s *UserService) checkTargetPrivilegeInternal(ctx context.Context, tx *gorm// UpdateUser persists the given user. actorPerms identifies the caller// 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 *models.User, actorPerms *authz.PermissionSet) (*models.User, error) {+func (s *UserService) UpdateUser(ctx context.Context, user *common.User, actorPerms *authz.PermissionSet) (*common.User, error) {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@@ -281,7 +280,7 @@ func (s *UserService) UpdateUser(ctx context.Context, user *models.User, actorPe// SetPassword hashes and persists a new password for the given user and clears// the first-login password-change requirement for trusted internal callers.-func (s *UserService) SetPassword(ctx context.Context, user *models.User, password string) (*models.User, error) {+func (s *UserService) SetPassword(ctx context.Context, user *common.User, password string) (*common.User, error) {if user == nil {return nil, errors.New("user is nil")}@@ -300,7 +299,7 @@ func (s *UserService) SetPassword(ctx context.Context, user *models.User, passwo// the first-login password-change requirement, and revokes every session for// the user except exceptSessionID. Pass an empty exceptSessionID to revoke all// sessions. This is for trusted internal callers.-func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, user *models.User, password, exceptSessionID string) (*models.User, error) {+func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, user *common.User, password, exceptSessionID string) (*common.User, error) {if user == nil {return nil, errors.New("user is nil")}@@ -313,7 +312,7 @@ func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, usreturn nil, errors.WrapIf(err, "failed to hash password")}- var updatedUser models.User+ var updatedUser common.Usererr = dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).@@ -347,10 +346,10 @@ func (s *UserService) SetPasswordAndRevokeSessionsExcept(ctx context.Context, us//// Note: The clause.Locking{Strength: "UPDATE"} statement is used to acquire a row-level lock.// This MUST be done inside a transaction to ensure the lock is held until the update is committed.-func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userID string, subject string, updateFn func(u *models.User)) (*models.User, error) {- var out *models.User+func (s *UserService) AttachOidcSubjectTransactional(ctx context.Context, userID string, subject string, updateFn func(u *common.User)) (*common.User, error) {+ var out *common.Usererr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- var u models.User+ var u common.Userif err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", userID).@@ -397,7 +396,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {// an account to `arcane` and get promoted on the next restart.if s.roleService != nil {var count int64- if err := s.db.WithContext(ctx).Model(&models.User{}).Count(&count).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&common.User{}).Count(&count).Error; err != nil {return errors.WrapIf(err, "failed to count users")}if count > 0 {@@ -417,7 +416,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {var adminUserID stringerr := dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {var count int64- if err := tx.Model(&models.User{}).Count(&count).Error; err != nil {+ if err := tx.Model(&common.User{}).Count(&count).Error; err != nil {return errors.WrapIf(err, "failed to count users")}@@ -428,7 +427,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {}email := "admin@localhost"displayName := "Arcane Admin"- userModel := &models.User{+ userModel := &common.User{Username: "arcane",Email: new(email),DisplayName: new(displayName),@@ -449,7 +448,7 @@ func (s *UserService) CreateDefaultAdmin(ctx context.Context) error {// Users exist but no global admin does (recovery only — the early// return above skips this path on healthy installs). See if `arcane`// is present; if not, leave the install alone.- var existing models.User+ var existing common.Usererr := tx.Where("username = ?", "arcane").First(&existing).Errorif err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {@@ -485,13 +484,13 @@ func (s *UserService) grantDefaultAdminRoleInternal(ctx context.Context, adminUsreturn nil // already has it}}- manual := make([]models.UserRoleAssignment, 0, len(assignments)+1)+ manual := make([]role.UserRoleAssignment, 0, len(assignments)+1)for _, a := range assignments {- if a.Source == models.RoleAssignmentSourceManual {- manual = append(manual, models.UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID})+ if a.Source == role.RoleAssignmentSourceManual {+ manual = append(manual, role.UserRoleAssignment{RoleID: a.RoleID, EnvironmentID: a.EnvironmentID})}}- manual = append(manual, models.UserRoleAssignment{+ manual = append(manual, role.UserRoleAssignment{RoleID: authz.BuiltInRoleAdmin,EnvironmentID: nil,})@@ -511,7 +510,7 @@ func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *aut// global admin, refuse the delete. Checked outside the transaction because// role.RoleService uses its own session and the guard spans rows.if s.roleService != nil {- ps, err := s.roleService.ResolvePermissions(ctx, &models.User{BaseModel: models.BaseModel{ID: id}})+ ps, err := s.roleService.ResolvePermissions(ctx, &common.User{BaseModel: database.BaseModel{ID: id}})if err != nil {return err}@@ -530,7 +529,7 @@ func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *autreturn err}- if err := tx.Delete(&models.User{}, "id = ?", id).Error; err != nil {+ if err := tx.Delete(&common.User{}, "id = ?", id).Error; err != nil {return errors.WrapIf(err, "failed to delete user")}return nil@@ -538,9 +537,9 @@ func (s *UserService) DeleteUser(ctx context.Context, id string, actorPerms *aut}func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.QueryParams) ([]user.User, pagination.Response, error) {- var users []models.User+ var users []common.Userquery := s.db.WithContext(ctx).- Model(&models.User{}).+ Model(&common.User{}).Where("is_service_account = ?", false)if term := strings.TrimSpace(params.Search); term != "" {@@ -561,11 +560,11 @@ func (s *UserService) ListUsersPaginated(ctx context.Context, params pagination.return result, paginationResp, nil}-func (s *UserService) ToUserResponseDto(ctx context.Context, u models.User) (user.User, error) {+func (s *UserService) ToUserResponseDto(ctx context.Context, u common.User) (user.User, error) {return s.toUserResponseDtoInternal(ctx, u), nil}-func (s *UserService) toUserResponseDtosInternal(ctx context.Context, users []models.User) []user.User {+func (s *UserService) toUserResponseDtosInternal(ctx context.Context, users []common.User) []user.User {result := make([]user.User, len(users))for i, u := range users {result[i] = s.toUserResponseDtoInternal(ctx, u)@@ -576,7 +575,7 @@ func (s *UserService) toUserResponseDtosInternal(ctx context.Context, users []mo// toUserResponseDtoInternal builds the public User DTO. RoleAssignments and// PermissionsByEnv come from the RBAC service. CanDelete is false when this// user is the only effective global admin.-func (s *UserService) toUserResponseDtoInternal(ctx context.Context, u models.User) user.User {+func (s *UserService) toUserResponseDtoInternal(ctx context.Context, u common.User) user.User {dto := user.User{ID: u.ID,Username: u.Username,@@ -658,13 +657,13 @@ func permissionSetToMap(ps *authz.PermissionSet) map[string][]string {return out}-func (s *UserService) GetUser(ctx context.Context, userID string) (*models.User, error) {+func (s *UserService) GetUser(ctx context.Context, userID string) (*common.User, error) {slog.Debug("GetUser called", "user_id", userID)return s.getUserInternal(ctx, userID, s.db.DB)}-func (s *UserService) getUserInternal(ctx context.Context, userID string, tx *gorm.DB) (*models.User, error) {- var userRecord models.User+func (s *UserService) getUserInternal(ctx context.Context, userID string, tx *gorm.DB) (*common.User, error) {+ var userRecord common.Usererr := tx.WithContext(ctx).Where("id = ?", userID).@@ -676,7 +675,7 @@ func (s *UserService) getUserInternal(ctx context.Context, userID string, tx *go// UploadAvatar stores avatar bytes for a user, replacing any existing avatar.func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []byte, mimeType string) error {return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- avatar := models.UserAvatar{+ avatar := UserAvatar{UserID: userID,Data: data,MimeType: mimeType,@@ -685,7 +684,7 @@ func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []byreturn errors.WrapIf(err, "failed to save avatar data")}- err := tx.Model(&models.User{}).+ err := tx.Model(&common.User{}).Where("id = ?", userID).Updates(map[string]any{"has_avatar": true,@@ -700,11 +699,11 @@ func (s *UserService) UploadAvatar(ctx context.Context, userID string, data []by// DeleteAvatar removes the avatar for a user.func (s *UserService) DeleteAvatar(ctx context.Context, userID string) error {return dbutil.WithTx(ctx, s.db.DB, func(tx *gorm.DB) error {- if err := tx.Where("user_id = ?", userID).Delete(&models.UserAvatar{}).Error; err != nil {+ if err := tx.Where("user_id = ?", userID).Delete(&UserAvatar{}).Error; err != nil {return errors.WrapIf(err, "failed to delete avatar data")}- err := tx.Model(&models.User{}).+ err := tx.Model(&common.User{}).Where("id = ?", userID).Updates(map[string]any{"has_avatar": false,@@ -726,7 +725,7 @@ func (s *UserService) GetAvatar(ctx context.Context, userID string) ([]byte, strif !u.HasAvatar {return nil, "", nil}- var avatar models.UserAvatar+ var avatar UserAvatarif err := s.db.DB.WithContext(ctx).Where("user_id = ?", userID).First(&avatar).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, "", nildiff --git a/backend/internal/user/service_test.go b/backend/internal/user/service_test.goindex 597e67b99..92799581f 100644--- a/backend/internal/user/service_test.go+++ b/backend/internal/user/service_test.go@@ -1,13 +1,16 @@package userimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/session"++ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""testing""time""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/role""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination"@@ -22,16 +25,18 @@ func setupAuthServiceTestDBInternal(t *testing.T) *database.DB {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.SettingVariable{},- &models.User{},- &models.UserSession{},- &models.Environment{},- &models.Role{},- &models.UserRoleAssignment{},- &models.ApiKey{},- &models.ApiKeyPermission{},- &models.OidcRoleMapping{},+ &settings.SettingVariable{},+ &common.User{},+ &session.UserSession{},+ &role.Role{},+ &role.UserRoleAssignment{},+ &role.ApiKeyPermission{},+ &role.OidcRoleMapping{},))+ // environments and api_keys live in packages that import this one; the+ // in-package tests only need the tables to exist.+ require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS environments (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, api_url text, status text, enabled numeric, is_edge numeric, hidden numeric, last_seen datetime, last_edge_transport text, access_token text, api_key_id text, parent_environment_id text, swarm_node_id text)").Error)+ require.NoError(t, db.Exec("CREATE TABLE IF NOT EXISTS api_keys (id text PRIMARY KEY, created_at datetime, updated_at datetime, name text, description text, key_hash text, key_prefix text, kind text, user_id text, environment_id text, managed_by text, expires_at datetime, last_used_at datetime)").Error)return &database.DB{DB: db}}@@ -46,10 +51,10 @@ func setupUserAndRoleServices(t *testing.T) (*UserService, *role.RoleService) {return userRecord, role}-func createTestUser(t *testing.T, svc *UserService, id, username string) *models.User {+func createTestUser(t *testing.T, svc *UserService, id, username string) *common.User {t.Helper()- created, err := svc.CreateUser(context.Background(), &models.User{- BaseModel: models.BaseModel{ID: id},+ created, err := svc.CreateUser(context.Background(), &common.User{+ BaseModel: database.BaseModel{ID: id},Username: username,})require.NoError(t, err)@@ -57,9 +62,9 @@ func createTestUser(t *testing.T, svc *UserService, id, username string) *models}// grantGlobalAdmin assigns the built-in Admin role globally to the user.-func grantGlobalAdmin(t *testing.T, role *role.RoleService, userID string) {+func grantGlobalAdmin(t *testing.T, roleSvc *role.RoleService, userID string) {t.Helper()- require.NoError(t, role.SetUserAssignments(context.Background(), userID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(context.Background(), userID, []role.UserRoleAssignment{{RoleID: authz.BuiltInRoleAdmin, EnvironmentID: nil},}))}@@ -85,8 +90,8 @@ func TestSetPasswordUpdatesHashAndClearsPasswordChangeRequirement(t *testing.T)oldHash, err := userSvc.HashPassword("old-password")require.NoError(t, err)- user, err := userSvc.CreateUser(ctx, &models.User{- BaseModel: models.BaseModel{ID: "password-user"},+ user, err := userSvc.CreateUser(ctx, &common.User{+ BaseModel: database.BaseModel{ID: "password-user"},Username: "password-user",PasswordHash: oldHash,RequiresPasswordChange: true,@@ -166,7 +171,7 @@ func TestDeleteUserRejectsDeletingOnlyCustomAllPermissionsAdmin(t *testing.T) {customAdmin := createTestUser(t, userSvc, "custom-admin", "custom-admin")customRole, err := roleSvc.CreateRole(ctx, "Custom Admin", nil, authz.AllPermissions())require.NoError(t, err)- require.NoError(t, roleSvc.SetUserAssignments(ctx, customAdmin.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, customAdmin.ID, []role.UserRoleAssignment{{RoleID: customRole.ID, EnvironmentID: nil},}))@@ -266,7 +271,7 @@ func TestUpdateUserRejectsNonAdminActorEditingAdmin(t *testing.T) {manager := createTestUser(t, userSvc, "mgr-1", "manager")managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})require.NoError(t, err)- require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []role.UserRoleAssignment{{RoleID: managerRole.ID, EnvironmentID: nil},}))managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)@@ -293,7 +298,7 @@ func TestUpdateUserAllowsGlobalAdminActorEditingAdmin(t *testing.T) {require.NoError(t, err)admin.DisplayName = new("Renamed Admin")- actorCtx := context.WithValue(ctx, models.CurrentUserContextKey{}, other)+ actorCtx := context.WithValue(ctx, common.CurrentUserContextKey{}, other)_, err = userSvc.UpdateUser(actorCtx, admin, otherPerms)require.NoError(t, err)}@@ -307,7 +312,7 @@ func TestUpdateUserAllowsNonAdminActorEditingNonAdmin(t *testing.T) {manager := createTestUser(t, userSvc, "mgr-1", "manager")managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersUpdate})require.NoError(t, err)- require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []role.UserRoleAssignment{{RoleID: managerRole.ID, EnvironmentID: nil},}))managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)@@ -329,7 +334,7 @@ func TestUpdateUserAllowsSelfEditByNonAdmin(t *testing.T) {require.NoError(t, err)admin.DisplayName = new("Self Rename")- actorCtx := context.WithValue(ctx, models.CurrentUserContextKey{}, admin)+ actorCtx := context.WithValue(ctx, common.CurrentUserContextKey{}, admin)_, err = userSvc.UpdateUser(actorCtx, admin, adminPerms)require.NoError(t, err)}@@ -345,7 +350,7 @@ func TestDeleteUserRejectsNonAdminActorDeletingAdmin(t *testing.T) {manager := createTestUser(t, userSvc, "mgr-1", "manager")managerRole, err := roleSvc.CreateRole(ctx, "User Manager", nil, []string{authz.PermUsersDelete})require.NoError(t, err)- require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []models.UserRoleAssignment{+ require.NoError(t, roleSvc.SetUserAssignments(ctx, manager.ID, []role.UserRoleAssignment{{RoleID: managerRole.ID, EnvironmentID: nil},}))managerPerms, err := roleSvc.ResolvePermissions(ctx, manager)@@ -372,7 +377,7 @@ func TestDeleteUserAllowsGlobalAdminActorDeletingAdmin(t *testing.T) {otherPerms, err := roleSvc.ResolvePermissions(ctx, other)require.NoError(t, err)- actorCtx := context.WithValue(ctx, models.CurrentUserContextKey{}, other)+ actorCtx := context.WithValue(ctx, common.CurrentUserContextKey{}, other)require.NoError(t, userSvc.DeleteUser(actorCtx, admin.ID, otherPerms))}diff --git a/backend/internal/models/global_variable.go b/backend/internal/variable/model.gosimilarity index 56%rename from backend/internal/models/global_variable.gorename to backend/internal/variable/model.goindex 75d67b466..a42156bef 100644--- a/backend/internal/models/global_variable.go+++ b/backend/internal/variable/model.go@@ -1,17 +1,22 @@-package models+package variable++import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/getarcaneapp/arcane/backend/v2/internal/environment"+)// GlobalVariable is a manager-level key/value variable materialized into each// environment's .env.global file. Value holds ciphertext when IsSecret is true.type GlobalVariable struct {- BaseModel+ database.BaseModelKey string `json:"key" gorm:"column:key" sortable:"true"`Value string `json:"-" gorm:"column:value"`IsSecret bool `json:"isSecret" gorm:"column:is_secret"`// No gorm default tag: a default:true tag would make GORM omit false on// insert and the column default would silently win.- AllEnvironments bool `json:"allEnvironments" gorm:"column:all_environments"`- Environments []Environment `json:"-" gorm:"many2many:global_variable_environments;joinForeignKey:GlobalVariableID;joinReferences:EnvironmentID"`+ AllEnvironments bool `json:"allEnvironments" gorm:"column:all_environments"`+ Environments []environment.Environment `json:"-" gorm:"many2many:global_variable_environments;joinForeignKey:GlobalVariableID;joinReferences:EnvironmentID"`}func (GlobalVariable) TableName() string { return "global_variables" }diff --git a/backend/internal/variable/service_test.go b/backend/internal/variable/service_test.goindex 7f50ae67f..7af9848ca 100644--- a/backend/internal/variable/service_test.go+++ b/backend/internal/variable/service_test.go@@ -20,7 +20,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/remenv"envtypes "github.com/getarcaneapp/arcane/types/v2/env"@@ -58,10 +57,10 @@ func setupVariableServiceTest(t *testing.T) (*VariableService, *database.DB, strdb, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)require.NoError(t, db.AutoMigrate(- &models.GlobalVariable{},- &models.Environment{},- &models.KVEntry{},- &models.SettingVariable{},+ &GlobalVariable{},+ &environment.Environment{},+ &kv.KVEntry{},+ &settings.SettingVariable{},))sqlDB, err := db.DB()@@ -86,8 +85,8 @@ func setupVariableServiceTest(t *testing.T) (*VariableService, *database.DB, strfunc createVariableTestEnvironment(t *testing.T, db *database.DB, id string) {t.Helper()- require.NoError(t, db.Create(&models.Environment{- BaseModel: models.BaseModel{ID: id},+ require.NoError(t, db.Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: id},Name: "env-" + id,ApiUrl: "http://env-" + id,Status: "online",@@ -108,7 +107,7 @@ func TestCreateVariable_SecretEncryptedAtRestAndRedactedOnList(t *testing.T) {require.NoError(t, err)require.Empty(t, created.Value, "mutation response must not echo the secret value")- var stored models.GlobalVariable+ var stored GlobalVariablerequire.NoError(t, db.First(&stored, "id = ?", created.ID).Error)require.NotEqual(t, "super-secret", stored.Value, "secret must not be stored as plaintext")decrypted, err := crypto.Decrypt(stored.Value)@@ -127,7 +126,7 @@ func TestUpdateVariable_OmittedSecretValuePreservesCiphertextAndRedactsResponse(ctx := context.Background()created := createMaterializedSecretVariableInternal(t, service, "API_TOKEN", "super-secret")- var before models.GlobalVariable+ var before GlobalVariablerequire.NoError(t, db.WithContext(ctx).First(&before, "id = ?", created.ID).Error)renamedKey := "RENAMED_API_TOKEN"updated, err := service.UpdateVariable(ctx, created.ID, envtypes.UpdateGlobalVariableRequest{Key: &renamedKey})@@ -135,7 +134,7 @@ func TestUpdateVariable_OmittedSecretValuePreservesCiphertextAndRedactsResponse(require.True(t, updated.IsSecret)require.Empty(t, updated.Value)- var after models.GlobalVariable+ var after GlobalVariablerequire.NoError(t, db.WithContext(ctx).First(&after, "id = ?", created.ID).Error)require.Equal(t, before.Value, after.Value, "omitting value must preserve the stored ciphertext")decrypted, err := crypto.Decrypt(after.Value)@@ -167,7 +166,7 @@ func TestUpdateVariable_SecretToPlainRequiresReplacementValue(t *testing.T) {require.False(t, updated.IsSecret)require.Equal(t, replacement, updated.Value)- var stored models.GlobalVariable+ var stored GlobalVariablerequire.NoError(t, db.WithContext(ctx).First(&stored, "id = ?", created.ID).Error)require.False(t, stored.IsSecret)require.Equal(t, replacement, stored.Value)@@ -280,11 +279,11 @@ func TestSyncEnvironment_DirectMaterializesSecretsThroughAgentRoute(t *testing.T}))defer server.Close()- require.NoError(t, db.Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-direct"},+ require.NoError(t, db.Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-direct"},Name: "Direct",ApiUrl: server.URL,- Status: string(models.EnvironmentStatusOnline),+ Status: string(environment.EnvironmentStatusOnline),Enabled: true,AccessToken: &token,}).Error)@@ -303,11 +302,11 @@ func TestSyncEnvironment_DirectMaterializesSecretsThroughAgentRoute(t *testing.Tfunc TestSyncEnvironment_EdgeMaterializesSecretsThroughAgentRoute(t *testing.T) {service, db, _ := setupVariableServiceTest(t)token := "edge-agent-token"- require.NoError(t, db.Create(&models.Environment{- BaseModel: models.BaseModel{ID: "env-edge"},+ require.NoError(t, db.Create(&environment.Environment{+ BaseModel: database.BaseModel{ID: "env-edge"},Name: "Edge",ApiUrl: "http://edge.invalid",- Status: string(models.EnvironmentStatusOnline),+ Status: string(environment.EnvironmentStatusOnline),Enabled: true,IsEdge: true,AccessToken: &token,diff --git a/backend/internal/variable/variable.go b/backend/internal/variable/variable.goindex cb6712f02..6f47e6390 100644--- a/backend/internal/variable/variable.go+++ b/backend/internal/variable/variable.go@@ -22,7 +22,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/projects""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -108,7 +107,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlob}}- variable := models.GlobalVariable{+ variable := GlobalVariable{Key: key,Value: value,IsSecret: req.IsSecret,@@ -134,7 +133,7 @@ func (s *VariableService) CreateVariable(ctx context.Context, req env.CreateGlob}func (s *VariableService) UpdateVariable(ctx context.Context, id string, req env.UpdateGlobalVariableRequest) (*env.GlobalVariable, error) {- var variable models.GlobalVariable+ var variable GlobalVariableif err := s.db.WithContext(ctx).Preload("Environments").First(&variable, "id = ?", id).Error; err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return nil, common.Classify(common.ErrGlobalVariableNotFound, errors.New("Global variable not found"))@@ -191,7 +190,7 @@ func (s *VariableService) UpdateVariable(ctx context.Context, id string, req env// resolveUpdatedValueInternal computes the stored value for an update:// encrypts when the result is secret and enforces that a secret cannot be// made readable without a replacement value (revealing the stored one).-func resolveUpdatedValueInternal(variable *models.GlobalVariable, reqValue *string, isSecret bool) (string, error) {+func resolveUpdatedValueInternal(variable *GlobalVariable, reqValue *string, isSecret bool) (string, error) {if variable.IsSecret && !isSecret && reqValue == nil {return "", common.Classify(common.ErrGlobalVariableSecretValueRequired, errors.New("A new value is required when making a secret variable readable"))}@@ -220,7 +219,7 @@ func resolveUpdatedValueInternal(variable *models.GlobalVariable, reqValue *stri// resolveUpdatedScopeInternal merges the requested scope change (if any) with// the variable's current scope and normalizes it.-func (s *VariableService) resolveUpdatedScopeInternal(ctx context.Context, variable *models.GlobalVariable, req env.UpdateGlobalVariableRequest) ([]string, bool, error) {+func (s *VariableService) resolveUpdatedScopeInternal(ctx context.Context, variable *GlobalVariable, req env.UpdateGlobalVariableRequest) ([]string, bool, error) {envIDs := scopedEnvironmentIDsInternal(variable.Environments)if req.AllEnvironments == nil && req.EnvironmentIDs == nil {return envIDs, variable.AllEnvironments, nil@@ -244,7 +243,7 @@ func (s *VariableService) resolveUpdatedScopeInternal(ctx context.Context, variafunc (s *VariableService) DeleteVariable(ctx context.Context, id string) error {err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- result := tx.Delete(&models.GlobalVariable{}, "id = ?", id)+ result := tx.Delete(&GlobalVariable{}, "id = ?", id)if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete global variable")}@@ -653,7 +652,7 @@ func (s *VariableService) importVariablesInternal(ctx context.Context, vars []encontinue}- variable := models.GlobalVariable{+ variable := GlobalVariable{Key: key,Value: entry.Value,AllEnvironments: scopeEnvID == "",@@ -681,8 +680,8 @@ func (s *VariableService) importVariablesInternal(ctx context.Context, vars []en// Helpers//-func (s *VariableService) loadVariablesInternal(ctx context.Context) ([]models.GlobalVariable, error) {- var variables []models.GlobalVariable+func (s *VariableService) loadVariablesInternal(ctx context.Context) ([]GlobalVariable, error) {+ var variables []GlobalVariableif err := s.db.WithContext(ctx).Preload("Environments").Order("key").Find(&variables).Error; err != nil {return nil, errors.WrapIf(err, "failed to load global variables")}@@ -710,7 +709,7 @@ func (s *VariableService) normalizeScopeInternal(ctx context.Context, allEnviron}var count int64- if err := s.db.WithContext(ctx).Model(&models.Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil {+ if err := s.db.WithContext(ctx).Model(&environment.Environment{}).Where("id IN ?", unique).Count(&count).Error; err != nil {return nil, errors.WrapIf(err, "Failed to update global variables")}if count != int64(len(unique)) {@@ -723,7 +722,7 @@ func (s *VariableService) normalizeScopeInternal(ctx context.Context, allEnviron// exist once per overlapping scope. The same key as both an all-environments// variable and an env-scoped variable is allowed (that is the override).func (s *VariableService) validateScopeConflictInternal(tx *gorm.DB, key string, excludeID string, allEnvironments bool, envIDs []string) error {- var others []models.GlobalVariable+ var others []GlobalVariablequery := tx.Preload("Environments").Where("key = ?", key)if excludeID != "" {query = query.Where("id <> ?", excludeID)@@ -773,7 +772,7 @@ func wrapVariableMutationErrorInternal(err error) error {return errors.WrapIf(err, "Failed to update global variables")}-func scopedEnvironmentIDsInternal(environments []models.Environment) []string {+func scopedEnvironmentIDsInternal(environments []environment.Environment) []string {ids := make([]string, 0, len(environments))for _, environment := range environments {ids = append(ids, environment.ID)@@ -781,15 +780,15 @@ func scopedEnvironmentIDsInternal(environments []models.Environment) []string {return ids}-func environmentsFromIDsInternal(envIDs []string) []models.Environment {- environments := make([]models.Environment, 0, len(envIDs))+func environmentsFromIDsInternal(envIDs []string) []environment.Environment {+ environments := make([]environment.Environment, 0, len(envIDs))for _, id := range envIDs {- environments = append(environments, models.Environment{BaseModel: models.BaseModel{ID: id}})+ environments = append(environments, environment.Environment{BaseModel: database.BaseModel{ID: id}})}return environments}-func globalVariableToDTOInternal(variable models.GlobalVariable) env.GlobalVariable {+func globalVariableToDTOInternal(variable GlobalVariable) env.GlobalVariable {value := variable.Valueif variable.IsSecret {value = ""diff --git a/backend/internal/version/service_test.go b/backend/internal/version/service_test.goindex 8adf2e5f7..441634dd1 100644--- a/backend/internal/version/service_test.go+++ b/backend/internal/version/service_test.go@@ -1,6 +1,10 @@package versionimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/project"++ "github.com/getarcaneapp/arcane/backend/v2/internal/event"+"context""encoding/json""fmt"@@ -16,7 +20,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/imageupdate"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/registry""github.com/google/go-containerregistry/pkg/name"ggcrregistry "github.com/google/go-containerregistry/pkg/registry"@@ -96,12 +99,12 @@ func TestVersionService_GetAppVersionInfoDoesNotUseStoredDigestUpdateForSemverBu}))defer server.Close()- require.NoError(t, db.WithContext(ctx).Create(&models.ImageUpdateRecord{+ require.NoError(t, db.WithContext(ctx).Create(&imageupdate.ImageUpdateRecord{ID: imageID,Repository: "ghcr.io/getarcaneapp/arcane",Tag: "latest",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "latest",CurrentDigest: ¤tDigest,LatestDigest: &latestDigest,@@ -158,7 +161,7 @@ func setupImageUpdateTestDB(t *testing.T) *database.DB {dsn := fmt.Sprintf("file:image-update-test-%d?mode=memory&cache=shared", time.Now().UnixNano())db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.ImageUpdateRecord{}, &models.Event{}, &models.Project{}))+ require.NoError(t, db.AutoMigrate(&imageupdate.ImageUpdateRecord{}, &event.Event{}, &project.Project{}))return &database.DB{DB: db}}@@ -283,12 +286,12 @@ func TestVersionService_GetAppVersionInfoNextChannelUsesImageLabelInternal(t *tecurrentDigest := digest.FromString("current-arcane").String()server := newNextChannelDockerServerInternal(t, containerID, imageID, repo, "next", currentDigest)- require.NoError(t, db.WithContext(ctx).Create(&models.ImageUpdateRecord{+ require.NoError(t, db.WithContext(ctx).Create(&imageupdate.ImageUpdateRecord{ID: imageID,Repository: repo,Tag: "next",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "next",CurrentDigest: ¤tDigest,LatestDigest: func() *string { s := imgDigest.String(); return &s }(),@@ -337,12 +340,12 @@ func TestVersionService_GetAppVersionInfoNextChannelLabelFailureFallsBackToDigeslatestDigest := digest.FromString("latest-arcane").String()server := newNextChannelDockerServerInternal(t, containerID, imageID, repo, "next", currentDigest)- require.NoError(t, db.WithContext(ctx).Create(&models.ImageUpdateRecord{+ require.NoError(t, db.WithContext(ctx).Create(&imageupdate.ImageUpdateRecord{ID: imageID,Repository: repo,Tag: "next",HasUpdate: true,- UpdateType: models.UpdateTypeDigest,+ UpdateType: imageupdate.UpdateTypeDigest,CurrentVersion: "next",CurrentDigest: ¤tDigest,LatestDigest: &latestDigest,diff --git a/backend/internal/volume/backup.go b/backend/internal/volume/backup.goindex bde9e48de..6042a7c78 100644--- a/backend/internal/volume/backup.go+++ b/backend/internal/volume/backup.go@@ -1,6 +1,12 @@package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"archive/tar""compress/gzip""context"@@ -14,7 +20,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"docker "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"@@ -217,7 +222,7 @@ func (s *VolumeService) ensureBackupVolumeInternal(ctx context.Context) error {return nil}-func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, user models.User) (*models.VolumeBackup, error) {+func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, user common.User) (*VolumeBackup, error) {slog.DebugContext(ctx, "volume service: create backup", "volume", volumeName, "user", user.ID)workspaceLock, _ := ctx.Value(volumeWorkspaceLockContextKeyInternal{}).(volumeWorkspaceLockContextInternal)if workspaceLock.service != s || workspaceLock.volumeName != volumeName {@@ -299,7 +304,7 @@ func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, usereturn nil, err}- backup := &models.VolumeBackup{+ backup := &VolumeBackup{VolumeName: volumeName,Size: size,CreatedAt: time.Now(),@@ -310,23 +315,23 @@ func (s *VolumeService) CreateBackup(ctx context.Context, volumeName string, usereturn nil, err}- metadata := models.JSON{+ metadata := database.JSON{"action": "backup_create","backup_id": backup.ID,"filename": filename,"size": size,}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeBackupCreate, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupCreate, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume backup create event", "volume", volumeName, "error", logErr.Error())}return backup, nil}-func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName string, params pagination.QueryParams) ([]models.VolumeBackup, pagination.Response, error) {+func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName string, params pagination.QueryParams) ([]VolumeBackup, pagination.Response, error) {slog.DebugContext(ctx, "volume service: list backups paginated", "volume", volumeName, "search", params.Search, "sort", params.Sort, "order", params.Order, "start", params.Start, "limit", params.Limit)- var backups []models.VolumeBackup- query := s.db.WithContext(ctx).Model(&models.VolumeBackup{}).Where("volume_name = ?", volumeName)+ var backups []VolumeBackup+ query := s.db.WithContext(ctx).Model(&VolumeBackup{}).Where("volume_name = ?", volumeName)if params.Search != "" {query = query.Where("id LIKE ?", "%"+params.Search+"%")@@ -371,16 +376,16 @@ func (s *VolumeService) ListBackupsPaginated(ctx context.Context, volumeName strreturn backups, paginationResp, nil}-func (s *VolumeService) ListBackups(ctx context.Context, volumeName string) ([]models.VolumeBackup, error) {+func (s *VolumeService) ListBackups(ctx context.Context, volumeName string) ([]VolumeBackup, error) {slog.DebugContext(ctx, "volume service: list backups", "volume", volumeName)- var backups []models.VolumeBackup+ var backups []VolumeBackuperr := s.db.WithContext(ctx).Where("volume_name = ?", volumeName).Order("created_at DESC").Find(&backups).Errorreturn backups, err}-func (s *VolumeService) DeleteBackup(ctx context.Context, backupID string, user *models.User) error {+func (s *VolumeService) DeleteBackup(ctx context.Context, backupID string, user *common.User) error {slog.DebugContext(ctx, "volume service: delete backup", "backup_id", backupID)- var backup models.VolumeBackup+ var backup VolumeBackupif err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {return err}@@ -409,22 +414,22 @@ func (s *VolumeService) DeleteBackup(ctx context.Context, backupID string, useractingUser := userif actingUser == nil {- actingUser = &models.SystemUser+ actingUser = &common.SystemUser}- metadata := models.JSON{+ metadata := database.JSON{"action": "backup_delete","backup_id": backupID,}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeBackupDelete, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupDelete, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume backup delete event", "volume", volumeName, "error", logErr.Error())}return nil}-func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupID string, user models.User) error {+func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupID string, user common.User) error {slog.DebugContext(ctx, "volume service: restore backup", "volume", volumeName, "backup_id", backupID, "user", user.ID)- var backup models.VolumeBackup+ var backup VolumeBackupif err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {return err}@@ -514,12 +519,12 @@ func (s *VolumeService) RestoreBackup(ctx context.Context, volumeName, backupIDreturn errors.Errorf("restore container exited with code %d (volume may be partially wiped)", waitBody.StatusCode)}- metadata := models.JSON{+ metadata := database.JSON{"action": "backup_restore","backup_id": backupID,"pre_restore_backupId": preBackup.ID,}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeBackupRestore, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupRestore, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume backup restore event", "volume", volumeName, "error", logErr.Error())}@@ -595,7 +600,7 @@ func (s *VolumeService) BackupHasPath(ctx context.Context, backupID string, filereturn false, err}- var backup models.VolumeBackup+ var backup VolumeBackupif err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {return false, err}@@ -652,7 +657,7 @@ func (s *VolumeService) ListBackupFiles(ctx context.Context, backupID string) ([return nil, err}- var backup models.VolumeBackup+ var backup VolumeBackupif err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {return nil, err}@@ -707,7 +712,7 @@ func (s *VolumeService) ListBackupFiles(ctx context.Context, backupID string) ([return files, nil}-func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backupID string, paths []string, user models.User) error {+func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backupID string, paths []string, user common.User) error {slog.DebugContext(ctx, "volume service: restore backup files", "volume", volumeName, "backup_id", backupID, "paths_count", len(paths), "user", user.ID)if len(paths) == 0 {return errors.New("no paths provided")@@ -717,7 +722,7 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backreturn err}- var backup models.VolumeBackup+ var backup VolumeBackupif err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {return err}@@ -802,7 +807,7 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backslog.DebugContext(ctx, "volume service: restore files stderr", "backup_id", backupID, "stderr", strings.TrimSpace(stderr))}- metadata := models.JSON{+ metadata := database.JSON{"action": "backup_restore_files","backup_id": backupID,"pre_restore_backupId": preBackup.ID,@@ -812,14 +817,14 @@ func (s *VolumeService) RestoreBackupFiles(ctx context.Context, volumeName, backlimit := min(len(cleanedPaths), 5)metadata["paths_sample"] = cleanedPaths[:limit]}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeBackupRestoreFiles, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupRestoreFiles, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume backup restore files event", "volume", volumeName, "error", logErr.Error())}return nil}-func (s *VolumeService) DownloadBackup(ctx context.Context, backupID string, user *models.User) (io.ReadCloser, int64, error) {+func (s *VolumeService) DownloadBackup(ctx context.Context, backupID string, user *common.User) (io.ReadCloser, int64, error) {slog.DebugContext(ctx, "volume service: download backup", "backup_id", backupID)filename, err := s.backupArchiveFilenameInternal(backupID)if err != nil {@@ -842,20 +847,20 @@ func (s *VolumeService) DownloadBackup(ctx context.Context, backupID string, useactingUser := userif actingUser == nil {- actingUser = &models.SystemUser+ actingUser = &common.SystemUser}volumeName := ""- var backup models.VolumeBackup+ var backup VolumeBackupif err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err == nil {volumeName = backup.VolumeName}if volumeName != "" {- metadata := models.JSON{+ metadata := database.JSON{"action": "backup_download","backup_id": backupID,"size": size,}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeBackupDownload, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupDownload, volumeName, volumeName, actingUser.ID, actingUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume backup download event", "volume", volumeName, "error", logErr.Error())}}@@ -863,7 +868,7 @@ func (s *VolumeService) DownloadBackup(ctx context.Context, backupID string, usereturn reader, size, nil}-func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string, archive io.ReadSeeker, filename string, user models.User) error {+func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string, archive io.ReadSeeker, filename string, user common.User) error {slog.DebugContext(ctx, "volume service: upload and restore", "volume", volumeName, "filename", filename, "user", user.ID)gzr, err := gzip.NewReader(archive)@@ -943,12 +948,12 @@ func (s *VolumeService) UploadAndRestore(ctx context.Context, volumeName string,slog.DebugContext(ctx, "volume service: restore move stderr", "volume", volumeName, "stderr", strings.TrimSpace(stderr))}- metadata := models.JSON{+ metadata := database.JSON{"action": "backup_upload_restore","filename": filename,"pre_restore_backupId": preBackup.ID,}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeBackupRestore, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeBackupRestore, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume backup upload restore event", "volume", volumeName, "error", logErr.Error())}diff --git a/backend/internal/volume/handler.go b/backend/internal/volume/handler.goindex 92dcac7bd..514b48981 100644--- a/backend/internal/volume/handler.go+++ b/backend/internal/volume/handler.go@@ -1,19 +1,24 @@package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""io""net/http""strconv""strings"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"github.com/getarcaneapp/arcane/backend/v2/internal/docker""emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/activity""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity"@@ -158,7 +163,7 @@ type ListBackupsInput struct {type VolumeBackupPaginatedResponse struct {Success bool `json:"success"`- Data []models.VolumeBackup `json:"data"`+ Data []VolumeBackup `json:"data"`Pagination base.PaginationResponse `json:"pagination"`Warnings []string `json:"warnings,omitempty"`}@@ -173,7 +178,7 @@ type CreateBackupInput struct {}type CreateBackupOutput struct {- Body base.ApiResponse[*models.VolumeBackup]+ Body base.ApiResponse[*VolumeBackup]}type RestoreBackupInput struct {@@ -493,7 +498,7 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInpruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume",ResourceID: input.Body.Name,ResourceName: input.Body.Name,@@ -501,7 +506,7 @@ func (h *VolumeHandler) CreateVolume(ctx context.Context, input *CreateVolumeInpStep: "Creating volume",Message: "Creating volume",SuccessMessage: "Volume created successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "create_volume","driver": input.Body.Driver,},@@ -533,7 +538,7 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInpruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume",ResourceID: input.VolumeName,ResourceName: input.VolumeName,@@ -541,7 +546,7 @@ func (h *VolumeHandler) RemoveVolume(ctx context.Context, input *RemoveVolumeInpStep: "Removing volume",Message: "Removing volume",SuccessMessage: "Volume removed successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "remove_volume","force": input.Force,},@@ -569,12 +574,12 @@ func (h *VolumeHandler) PruneVolumes(ctx context.Context, input *PruneVolumesInpruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume",Step: "Pruning unused volumes",Message: "Pruning unused volumes",SuccessMessage: "Volumes pruned successfully",- Metadata: models.JSON{"action": "prune_volumes"},+ Metadata: database.JSON{"action": "prune_volumes"},}, func(runtimeCtx context.Context) error {var pruneErr errorreport, pruneErr = h.volumeService.PruneVolumes(runtimeCtx)@@ -707,11 +712,11 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInpreturn nil, err}- var backup *models.VolumeBackup+ var backup *VolumeBackupruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume",ResourceID: input.VolumeName,ResourceName: input.VolumeName,@@ -719,7 +724,7 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInpStep: "Creating backup",Message: "Creating volume backup",SuccessMessage: "Volume backup created successfully",- Metadata: models.JSON{"action": "create_volume_backup"},+ Metadata: database.JSON{"action": "create_volume_backup"},}, func(runtimeCtx context.Context) error {var backupErr errorbackup, backupErr = h.volumeService.CreateBackup(runtimeCtx, input.VolumeName, *user)@@ -730,7 +735,7 @@ func (h *VolumeHandler) CreateBackup(ctx context.Context, input *CreateBackupInp}backup.ActivityID = mo.EmptyableToOption(strings.TrimSpace(activityID)).ToPointer()return &CreateBackupOutput{- Body: base.ApiResponse[*models.VolumeBackup]{+ Body: base.ApiResponse[*VolumeBackup]{Success: true,Data: backup,},@@ -746,7 +751,7 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupIruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume",ResourceID: input.VolumeName,ResourceName: input.VolumeName,@@ -754,7 +759,7 @@ func (h *VolumeHandler) RestoreBackup(ctx context.Context, input *RestoreBackupIStep: "Restoring backup",Message: "Restoring volume backup",SuccessMessage: "Restore initiated successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "restore_volume_backup","backupId": input.BackupID,},@@ -785,7 +790,7 @@ func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBaruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume",ResourceID: input.VolumeName,ResourceName: input.VolumeName,@@ -793,7 +798,7 @@ func (h *VolumeHandler) RestoreBackupFiles(ctx context.Context, input *RestoreBaStep: "Restoring backup files",Message: "Restoring files from volume backup",SuccessMessage: "Restore initiated successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "restore_volume_backup_files","backupId": input.BackupID,"paths": input.Body.Paths,@@ -846,11 +851,11 @@ func (h *VolumeHandler) ListBackupFiles(ctx context.Context, input *ListBackupFi}func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInput) (*DeleteBackupOutput, error) {- user, _ := models.CurrentUserFromContext(ctx)+ user, _ := common.CurrentUserFromContext(ctx)runtimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume_backup",ResourceID: input.BackupID,ResourceName: input.BackupID,@@ -858,7 +863,7 @@ func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInpStep: "Deleting backup",Message: "Deleting volume backup",SuccessMessage: "Backup deleted successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "delete_volume_backup","backupId": input.BackupID,},@@ -877,7 +882,7 @@ func (h *VolumeHandler) DeleteBackup(ctx context.Context, input *DeleteBackupInp}func (h *VolumeHandler) DownloadBackup(ctx context.Context, input *DownloadBackupInput) (*huma.StreamResponse, error) {- user, _ := models.CurrentUserFromContext(ctx)+ user, _ := common.CurrentUserFromContext(ctx)reader, size, err := h.volumeService.DownloadBackup(ctx, input.BackupID, user)if err != nil {return nil, huma.Error500InternalServerError(err.Error())@@ -915,7 +920,7 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndReruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{EnvironmentID: input.EnvironmentID,- Type: models.ActivityTypeResourceAction,+ Type: activitytypes.TypeResourceAction,ResourceType: "volume",ResourceID: input.VolumeName,ResourceName: input.VolumeName,@@ -923,7 +928,7 @@ func (h *VolumeHandler) UploadAndRestore(ctx context.Context, input *UploadAndReStep: "Uploading backup",Message: "Uploading and restoring volume backup",SuccessMessage: "Backup uploaded and restored successfully",- Metadata: models.JSON{+ Metadata: database.JSON{"action": "upload_restore_volume_backup","filename": session.Filename,},diff --git a/backend/internal/volume/helper_container.go b/backend/internal/volume/helper_container.goindex 7d8373c8d..4a3c469d1 100644--- a/backend/internal/volume/helper_container.go+++ b/backend/internal/volume/helper_container.go@@ -1,6 +1,8 @@package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"bytes""context""encoding/json"@@ -14,7 +16,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/timeouts"@@ -117,7 +118,7 @@ func getVolumeHelperImageInternal(ctx context.Context, dockerService *docker.Docvar pullErr errorif imageService != nil {- pullImageErr := imageService.PullImage(ctx, volumeHelperImage, io.Discard, models.SystemUser, nil)+ pullImageErr := imageService.PullImage(ctx, volumeHelperImage, io.Discard, common.SystemUser, nil)if pullImageErr == nil {slog.InfoContext(ctx, "volume service: helper image strategy selected", "strategy", "tools-pulled", "image", volumeHelperImage)return volumeHelperImage, nildiff --git a/backend/internal/models/volume_backup.go b/backend/internal/volume/model.gosimilarity index 86%rename from backend/internal/models/volume_backup.gorename to backend/internal/volume/model.goindex 853b40f64..91ecb356c 100644--- a/backend/internal/models/volume_backup.go+++ b/backend/internal/volume/model.go@@ -1,13 +1,15 @@-package models+package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"time""github.com/getarcaneapp/arcane/types/v2/volume")type VolumeBackup struct {- BaseModel+ database.BaseModelVolumeName string `json:"volumeName" gorm:"column:volume_name;index"`Size int64 `json:"size" gorm:"column:size"`diff --git a/backend/internal/volume/service.go b/backend/internal/volume/service.goindex b0162674c..1ed238ed1 100644--- a/backend/internal/volume/service.go+++ b/backend/internal/volume/service.go@@ -1,6 +1,8 @@package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""log/slog""strings"@@ -14,7 +16,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -125,32 +126,32 @@ func (s *VolumeService) GetVolumeByName(ctx context.Context, name string) (*volureturn &v, nil}-func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeCreateOptions, user models.User) (*volumetypes.Volume, error) {+func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeCreateOptions, user common.User) (*volumetypes.Volume, error) {slog.DebugContext(ctx, "volume service: create volume", "volume", options.Name, "driver", options.Driver, "user", user.ID)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})+ s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})return nil, errors.WrapIf(err, "failed to connect to Docker")}created, err := dockerClient.VolumeCreate(ctx, options)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver})+ s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", "", options.Name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver})return nil, errors.WrapIf(err, "failed to create volume")}vol, err := dockerClient.VolumeInspect(ctx, created.Volume.Name, client.VolumeInspectOptions{})if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", created.Volume.Name, created.Volume.Name, user.ID, user.Username, "0", err, models.JSON{"action": "create", "driver": options.Driver, "step": "inspect"})+ s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", created.Volume.Name, created.Volume.Name, user.ID, user.Username, "0", err, database.JSON{"action": "create", "driver": options.Driver, "step": "inspect"})return nil, errors.WrapIf(err, "failed to inspect created volume")}- metadata := models.JSON{+ metadata := database.JSON{"action": "create","driver": vol.Volume.Driver,"name": vol.Volume.Name,}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeCreate, vol.Volume.Name, vol.Volume.Name, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeCreate, vol.Volume.Name, vol.Volume.Name, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume creation action", "volume", vol.Volume.Name, "error", logErr.Error())}@@ -159,11 +160,11 @@ func (s *VolumeService) CreateVolume(ctx context.Context, options client.VolumeCreturn new(volumetypes.NewSummary(vol.Volume)), nil}-func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force bool, user models.User) error {+func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force bool, user common.User) error {slog.DebugContext(ctx, "volume service: delete volume", "volume", name, "force", force, "user", user.ID)dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})+ s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})return errors.WrapIf(err, "failed to connect to Docker")}@@ -176,15 +177,15 @@ func (s *VolumeService) DeleteVolume(ctx context.Context, name string, force booif _, err := dockerClient.VolumeRemove(ctx, name, client.VolumeRemoveOptions{Force: force,}); err != nil {- s.eventService.LogErrorEvent(ctx, models.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, models.JSON{"action": "delete", "force": force})+ s.eventService.LogErrorEvent(ctx, event.EventTypeVolumeError, "volume", name, name, user.ID, user.Username, "0", err, database.JSON{"action": "delete", "force": force})return errors.WrapIf(err, "failed to remove volume")}- metadata := models.JSON{+ metadata := database.JSON{"action": "delete","name": name,}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeDelete, name, name, user.ID, user.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeDelete, name, name, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume deletion action", "volume", name, "error", logErr.Error())}@@ -223,7 +224,7 @@ func (s *VolumeService) PruneVolumesWithOptions(ctx context.Context, all bool) (}metadata := buildVolumePruneMetadataInternal(all, len(volumePruneResult.Report.VolumesDeleted), volumePruneResult.Report.SpaceReclaimed, preserveTrivyCache)- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeDelete, "", "bulk_prune", models.SystemUser.ID, models.SystemUser.Username, "0", metadata); logErr != nil {+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeDelete, "", "bulk_prune", common.SystemUser.ID, common.SystemUser.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume prune action", "error", logErr.Error())}@@ -262,8 +263,8 @@ func buildVolumePruneOptionsInternal(all, preserveTrivyCache bool) client.Volumereturn options}-func buildVolumePruneMetadataInternal(all bool, volumesDeleted int, spaceReclaimed uint64, preserveTrivyCache bool) models.JSON {- return models.JSON{+func buildVolumePruneMetadataInternal(all bool, volumesDeleted int, spaceReclaimed uint64, preserveTrivyCache bool) database.JSON {+ return database.JSON{"action": "prune","all": all,"volumesDeleted": volumesDeleted,diff --git a/backend/internal/volume/workspace.go b/backend/internal/volume/workspace.goindex 04829e067..575a1ee0b 100644--- a/backend/internal/volume/workspace.go+++ b/backend/internal/volume/workspace.go@@ -1,6 +1,10 @@package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"archive/tar""bytes""context"@@ -23,7 +27,6 @@ import (cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -551,7 +554,7 @@ while :; doesacdone`-func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName string, manifest volumetypes.WorkspaceUpdateManifest, uploads map[int][]byte, user models.User) (*workspacetypes.Workspace, error) {+func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName string, manifest volumetypes.WorkspaceUpdateManifest, uploads map[int][]byte, user common.User) (*workspacetypes.Workspace, error) {totalStartedAt := time.Now()defer func() {slog.DebugContext(ctx, "volume workspace update completed", "volume", volumeName, "file_change_count", len(manifest.FileChanges), "total_duration", time.Since(totalStartedAt))@@ -650,8 +653,8 @@ func (s *VolumeService) UpdateVolumeWorkspace(ctx context.Context, volumeName stslog.DebugContext(ctx, "volume workspace final tree scan completed", "volume", volumeName, "file_count", len(workspace.Files), "truncated", workspace.FileTreeTruncated, "duration", time.Since(finalScanStartedAt))if s.eventService != nil {- metadata := models.JSON{"action": "workspace_update", "fileChangeCount": len(manifest.FileChanges)}- if logErr := s.eventService.LogVolumeEvent(ctx, models.EventTypeVolumeWorkspaceUpdate, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {+ metadata := database.JSON{"action": "workspace_update", "fileChangeCount": len(manifest.FileChanges)}+ if logErr := s.eventService.LogVolumeEvent(ctx, event.EventTypeVolumeWorkspaceUpdate, volumeName, volumeName, user.ID, user.Username, "0", metadata); logErr != nil {slog.WarnContext(ctx, "could not log volume workspace update event", "volume", volumeName, "error", logErr.Error())}}@@ -1116,7 +1119,7 @@ func (s *VolumeService) restoreVolumeWorkspaceFileInternal(ctx context.Context,if err != nil {return common.Classify(common.ErrVolumeWorkspaceNotFound, err)}- var backup models.VolumeBackup+ var backup VolumeBackupif err := s.db.WithContext(ctx).Where("id = ?", backupID).First(&backup).Error; err != nil {return common.Classify(common.ErrVolumeWorkspaceNotFound, err)}diff --git a/backend/internal/volume/workspace_handler.go b/backend/internal/volume/workspace_handler.goindex a2aa826aa..c552a8c08 100644--- a/backend/internal/volume/workspace_handler.go+++ b/backend/internal/volume/workspace_handler.go@@ -1,6 +1,8 @@package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""io""mime/multipart"@@ -9,11 +11,12 @@ import ("strconv""strings"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors""github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -147,9 +150,9 @@ func (h *VolumeHandler) UpdateVolumeWorkspace(ctx context.Context, input *Updatevar result *workspacetypes.WorkspaceruntimeCtx := utils.ActivityRuntimeContext(ctx, h.appCtx)activityID, err := activitylib.RunHandlerActivity(runtimeCtx, h.activityService, activitylib.HandlerOptions{- EnvironmentID: input.EnvironmentID, Type: models.ActivityTypeResourceAction, ResourceType: "volume", ResourceID: input.VolumeName, ResourceName: input.VolumeName, User: user,+ EnvironmentID: input.EnvironmentID, Type: activitytypes.TypeResourceAction, ResourceType: "volume", ResourceID: input.VolumeName, ResourceName: input.VolumeName, User: user,Step: "Updating volume workspace", Message: "Updating volume workspace", SuccessMessage: "Volume workspace updated successfully",- Metadata: models.JSON{"action": "update_volume_workspace", "fileChangeCount": len(manifest.FileChanges)},+ Metadata: database.JSON{"action": "update_volume_workspace", "fileChangeCount": len(manifest.FileChanges)},}, func(runtimeCtx context.Context) error {var updateErr errorresult, updateErr = h.volumeService.UpdateVolumeWorkspace(runtimeCtx, input.VolumeName, manifest, uploads, *user)diff --git a/backend/internal/volume/workspace_handler_test.go b/backend/internal/volume/workspace_handler_test.goindex c47fa786b..d4f4c705b 100644--- a/backend/internal/volume/workspace_handler_test.go+++ b/backend/internal/volume/workspace_handler_test.go@@ -1,6 +1,10 @@package volumeimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""mime/multipart""net/http"@@ -8,7 +12,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/upload""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil"@@ -27,7 +30,7 @@ func volumeWorkspacePermissionContextInternal(environmentID string, permissionsfunc TestUploadAndRestoreReturnsNotFoundForUnknownSession(t *testing.T) {h := &VolumeHandler{volumeService: &VolumeService{}, uploadService: upload.NewUploadService(nil)}- ctx := context.WithValue(context.Background(), models.CurrentUserContextKey{}, &models.User{BaseModel: models.BaseModel{ID: "u-1"}})+ ctx := context.WithValue(context.Background(), common.CurrentUserContextKey{}, &common.User{BaseModel: database.BaseModel{ID: "u-1"}})_, err := h.UploadAndRestore(ctx, &UploadAndRestoreInput{EnvironmentID: "0",diff --git a/backend/internal/volume/workspace_test.go b/backend/internal/volume/workspace_test.goindex 87f6f3ec8..f2bc3ae13 100644--- a/backend/internal/volume/workspace_test.go+++ b/backend/internal/volume/workspace_test.go@@ -23,7 +23,6 @@ import (cerrdefs "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/common""github.com/getarcaneapp/arcane/backend/v2/internal/docker"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/volumehelper"volumetypes "github.com/getarcaneapp/arcane/types/v2/volume"workspacetypes "github.com/getarcaneapp/arcane/types/v2/workspace"@@ -92,7 +91,7 @@ func TestUpdateVolumeWorkspaceValidationFailureReturnsNoWorkspace(t *testing.T)"volume",volumetypes.WorkspaceUpdateManifest{},nil,- models.User{},+ common.User{},)require.Nil(t, workspace)@@ -518,7 +517,7 @@ func TestUpdateVolumeWorkspaceRejectsStaleRevisionBeforeStaging(t *testing.T) {RelativePath: "new.txt",UploadIndex: &uploadIndex,}},- }, map[int][]byte{0: []byte("new content")}, models.User{})+ }, map[int][]byte{0: []byte("new content")}, common.User{})require.Nil(t, workspace)require.ErrorIs(t, err, common.ErrVolumeWorkspaceConflict)diff --git a/backend/internal/models/vulnerability_scan.go b/backend/internal/vulnerability/model.gosimilarity index 55%rename from backend/internal/models/vulnerability_scan.gorename to backend/internal/vulnerability/model.goindex f14a52cdf..12cf5d375 100644--- a/backend/internal/models/vulnerability_scan.go+++ b/backend/internal/vulnerability/model.go@@ -1,12 +1,16 @@-package models+package vulnerabilityimport ("time"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+ "github.com/google/uuid"+ "gorm.io/gorm")// VulnerabilityScanRecord stores vulnerability scan results for imagestype VulnerabilityScanRecord struct {- BaseModel+ database.BaseModel// ImageID is the Docker image ID (primary key)ID string `json:"id" gorm:"primaryKey;type:text"`@@ -32,7 +36,7 @@ type VulnerabilityScanRecord struct {TotalCount int `json:"totalCount" gorm:"column:total_count"`// Vulnerabilities stores the JSON encoded vulnerabilities list- Vulnerabilities StringSlice `json:"vulnerabilities" gorm:"column:vulnerabilities;type:text"`+ Vulnerabilities database.StringSlice `json:"vulnerabilities" gorm:"column:vulnerabilities;type:text"`// Error contains the error message if the scan failedError *string `json:"error,omitempty" gorm:"column:error"`@@ -92,3 +96,54 @@ func (v *VulnerabilityScanRecord) GetHighestSeverity() string {}return "NONE"}++// VulnerabilityIgnore stores ignored vulnerability records+type VulnerabilityIgnore struct {+ // ID is the unique identifier for this ignore record+ ID string `json:"id" gorm:"primaryKey;type:text"`++ // EnvironmentID is the environment where this ignore applies+ EnvironmentID string `json:"environmentId" gorm:"column:environment_id;index"`++ // ImageID is the Docker image ID+ ImageID string `json:"imageId" gorm:"column:image_id;index"`++ // VulnerabilityID is the CVE or vulnerability identifier (e.g., CVE-2023-1234)+ VulnerabilityID string `json:"vulnerabilityId" gorm:"column:vulnerability_id;index"`++ // PkgName is the package name containing the vulnerability+ PkgName string `json:"pkgName" gorm:"column:pkg_name"`++ // InstalledVersion is the version of the package with the vulnerability+ InstalledVersion string `json:"installedVersion" gorm:"column:installed_version"`++ // Reason is an optional reason for ignoring this vulnerability+ Reason *string `json:"reason,omitempty" gorm:"column:reason"`++ // CreatedBy is the user ID who created this ignore record+ CreatedBy string `json:"createdBy" gorm:"column:created_by"`++ // CreatedAt is when this ignore record was created+ CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"`+}++func (v *VulnerabilityIgnore) TableName() string {+ return "vulnerability_ignores"+}++// BeforeCreate sets the ID and CreatedAt before inserting+func (v *VulnerabilityIgnore) BeforeCreate(db *gorm.DB) error {+ if v.ID == "" {+ v.ID = uuid.New().String()+ }+ if v.CreatedAt.IsZero() {+ v.CreatedAt = time.Now()+ }+ return nil+}++// CompositeKey generates a composite key for deduplication.+// This helps prevent duplicate ignore records for the same vulnerability.+func (v *VulnerabilityIgnore) CompositeKey() string {+ return v.EnvironmentID + ":" + v.ImageID + ":" + v.VulnerabilityID + ":" + v.PkgName + ":" + v.InstalledVersion+}diff --git a/backend/internal/vulnerability/service_test.go b/backend/internal/vulnerability/service_test.goindex 1baadbba7..8d03fdade 100644--- a/backend/internal/vulnerability/service_test.go+++ b/backend/internal/vulnerability/service_test.go@@ -1,6 +1,8 @@package vulnerabilityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""encoding/json""fmt"@@ -8,7 +10,6 @@ import ("time""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/vuln""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/vulnerability"@@ -27,10 +28,10 @@ func TestBuildTrivyContainerResourcesInternal_Defaults(t *testing.T) {}func TestBuildTrivyContainerResourcesInternal_LimitsDisabled(t *testing.T) {- cfg := &models.Settings{- TrivyResourceLimitsEnabled: models.SettingVariable{Value: "false"},- TrivyCpuLimit: models.SettingVariable{Value: "2"},- TrivyMemoryLimitMb: models.SettingVariable{Value: "2048"},+ cfg := &settings.Settings{+ TrivyResourceLimitsEnabled: settings.SettingVariable{Value: "false"},+ TrivyCpuLimit: settings.SettingVariable{Value: "2"},+ TrivyMemoryLimitMb: settings.SettingVariable{Value: "2048"},}resources, applyLimits := buildTrivyContainerResourcesInternal(cfg).Get()@@ -42,10 +43,10 @@ func TestBuildTrivyContainerResourcesInternal_LimitsDisabled(t *testing.T) {}func TestBuildTrivyContainerResourcesInternal_CustomLimits(t *testing.T) {- cfg := &models.Settings{- TrivyResourceLimitsEnabled: models.SettingVariable{Value: "true"},- TrivyCpuLimit: models.SettingVariable{Value: "2.5"},- TrivyMemoryLimitMb: models.SettingVariable{Value: "2048"},+ cfg := &settings.Settings{+ TrivyResourceLimitsEnabled: settings.SettingVariable{Value: "true"},+ TrivyCpuLimit: settings.SettingVariable{Value: "2.5"},+ TrivyMemoryLimitMb: settings.SettingVariable{Value: "2048"},}resources, applyLimits := buildTrivyContainerResourcesInternal(cfg).Get()@@ -129,7 +130,7 @@ func setupVulnerabilityScanTestDB(t *testing.T) *database.DB {dsn := fmt.Sprintf("file:vulnerability-scan-test-%d?mode=memory&cache=shared", time.Now().UnixNano())db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.VulnerabilityScanRecord{}, &models.VulnerabilityIgnore{}))+ require.NoError(t, db.AutoMigrate(&VulnerabilityScanRecord{}, &VulnerabilityIgnore{}))return &database.DB{DB: db}}@@ -138,10 +139,10 @@ func TestVulnerabilityService_DeleteScanResultsByImageIDs(t *testing.T) {db := setupVulnerabilityScanTestDB(t)svc := &VulnerabilityService{db: db}- records := []models.VulnerabilityScanRecord{- {ID: "sha256:img1", ImageName: "nginx:latest", Status: models.ScanStatusCompleted, ScanTime: time.Now()},- {ID: "sha256:img2", ImageName: "redis:7", Status: models.ScanStatusCompleted, ScanTime: time.Now()},- {ID: "sha256:img3", ImageName: "postgres:16", Status: models.ScanStatusCompleted, ScanTime: time.Now()},+ records := []VulnerabilityScanRecord{+ {ID: "sha256:img1", ImageName: "nginx:latest", Status: ScanStatusCompleted, ScanTime: time.Now()},+ {ID: "sha256:img2", ImageName: "redis:7", Status: ScanStatusCompleted, ScanTime: time.Now()},+ {ID: "sha256:img3", ImageName: "postgres:16", Status: ScanStatusCompleted, ScanTime: time.Now()},}for i := range records {require.NoError(t, db.Create(&records[i]).Error)@@ -149,7 +150,7 @@ func TestVulnerabilityService_DeleteScanResultsByImageIDs(t *testing.T) {require.NoError(t, svc.DeleteScanResultsByImageIDs(ctx, []string{"sha256:img1", "sha256:img3"}))- var remaining []models.VulnerabilityScanRecord+ var remaining []VulnerabilityScanRecordrequire.NoError(t, db.Find(&remaining).Error)require.Len(t, remaining, 1)require.Equal(t, "sha256:img2", remaining[0].ID)@@ -207,7 +208,7 @@ func TestSeverityCountColumnsForFilterInternal(t *testing.T) {func TestApplyListAllVulnerabilityRecordPrefiltersInternal_NoPossibleMatches(t *testing.T) {db := setupVulnerabilityScanTestDB(t)- base := db.WithContext(context.Background()).Model(&models.VulnerabilityScanRecord{})+ base := db.WithContext(context.Background()).Model(&VulnerabilityScanRecord{})_, ok := applyListAllVulnerabilityRecordPrefiltersInternal(base, map[string]string{"severity": "not-a-severity"}).Get()require.False(t, ok)@@ -238,18 +239,18 @@ func TestVulnerabilityService_ListAllVulnerabilities_FiltersIgnoredInline(t *tesrawVulns, err := json.Marshal(vulns)require.NoError(t, err)- scan := models.VulnerabilityScanRecord{+ scan := VulnerabilityScanRecord{ID: "sha256:list-all-1",ImageName: "nginx:latest",- Status: models.ScanStatusCompleted,+ Status: ScanStatusCompleted,ScanTime: time.Now(),HighCount: 1,TotalCount: 1,- Vulnerabilities: models.StringSlice{string(rawVulns)},+ Vulnerabilities: database.StringSlice{string(rawVulns)},}require.NoError(t, db.Create(&scan).Error)- ignore := models.VulnerabilityIgnore{+ ignore := VulnerabilityIgnore{EnvironmentID: "env-1",ImageID: scan.ID,VulnerabilityID: "CVE-2026-0001",@@ -275,13 +276,13 @@ func TestVulnerabilityService_ListAllVulnerabilityImageOptions_SeverityFilter(tsvc := &VulnerabilityService{db: db}now := time.Now()- records := []models.VulnerabilityScanRecord{- {ID: "sha256:critical-a", ImageName: "zeta:latest", Status: models.ScanStatusCompleted, ScanTime: now, CriticalCount: 2, TotalCount: 2},- {ID: "sha256:high-a", ImageName: "alpha:latest", Status: models.ScanStatusCompleted, ScanTime: now, HighCount: 4, TotalCount: 4},- {ID: "sha256:critical-b", ImageName: "", Status: models.ScanStatusCompleted, ScanTime: now, CriticalCount: 1, TotalCount: 1},- {ID: "sha256:critical-c", ImageName: "zeta:latest", Status: models.ScanStatusCompleted, ScanTime: now, CriticalCount: 1, TotalCount: 1},- {ID: "sha256:failed", ImageName: "failed:latest", Status: models.ScanStatusFailed, ScanTime: now, CriticalCount: 9, TotalCount: 9},- {ID: "sha256:zero", ImageName: "zero:latest", Status: models.ScanStatusCompleted, ScanTime: now, CriticalCount: 1, TotalCount: 0},+ records := []VulnerabilityScanRecord{+ {ID: "sha256:critical-a", ImageName: "zeta:latest", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 2, TotalCount: 2},+ {ID: "sha256:high-a", ImageName: "alpha:latest", Status: ScanStatusCompleted, ScanTime: now, HighCount: 4, TotalCount: 4},+ {ID: "sha256:critical-b", ImageName: "", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 1, TotalCount: 1},+ {ID: "sha256:critical-c", ImageName: "zeta:latest", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 1, TotalCount: 1},+ {ID: "sha256:failed", ImageName: "failed:latest", Status: ScanStatusFailed, ScanTime: now, CriticalCount: 9, TotalCount: 9},+ {ID: "sha256:zero", ImageName: "zero:latest", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 1, TotalCount: 0},}for i := range records {@@ -299,10 +300,10 @@ func TestVulnerabilityService_ListAllVulnerabilityImageOptions_InvalidSeverityAnsvc := &VulnerabilityService{db: db}now := time.Now()- records := []models.VulnerabilityScanRecord{- {ID: "sha256:one", ImageName: "beta:latest", Status: models.ScanStatusCompleted, ScanTime: now, HighCount: 1, TotalCount: 1},- {ID: "sha256:two", ImageName: "", Status: models.ScanStatusCompleted, ScanTime: now, MediumCount: 2, TotalCount: 2},- {ID: "sha256:three", ImageName: "alpha:latest", Status: models.ScanStatusCompleted, ScanTime: now, LowCount: 1, TotalCount: 1},+ records := []VulnerabilityScanRecord{+ {ID: "sha256:one", ImageName: "beta:latest", Status: ScanStatusCompleted, ScanTime: now, HighCount: 1, TotalCount: 1},+ {ID: "sha256:two", ImageName: "", Status: ScanStatusCompleted, ScanTime: now, MediumCount: 2, TotalCount: 2},+ {ID: "sha256:three", ImageName: "alpha:latest", Status: ScanStatusCompleted, ScanTime: now, LowCount: 1, TotalCount: 1},}for i := range records {@@ -345,10 +346,10 @@ func TestVulnerabilityService_ActionableCountExcludingIgnored(t *testing.T) {rawVulnsB, err := json.Marshal(vulnsB)require.NoError(t, err)- records := []models.VulnerabilityScanRecord{- {ID: "sha256:img-a", ImageName: "nginx:latest", Status: models.ScanStatusCompleted, ScanTime: now, CriticalCount: 2, HighCount: 1, MediumCount: 1, TotalCount: 4, Vulnerabilities: models.StringSlice{string(rawVulnsA)}},- {ID: "sha256:img-b", ImageName: "redis:7", Status: models.ScanStatusCompleted, ScanTime: now, CriticalCount: 1, HighCount: 1, MediumCount: 1, TotalCount: 3, Vulnerabilities: models.StringSlice{string(rawVulnsB)}},- {ID: "sha256:img-failed", ImageName: "failed:latest", Status: models.ScanStatusFailed, ScanTime: now, CriticalCount: 9, HighCount: 9, TotalCount: 18},+ records := []VulnerabilityScanRecord{+ {ID: "sha256:img-a", ImageName: "nginx:latest", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 2, HighCount: 1, MediumCount: 1, TotalCount: 4, Vulnerabilities: database.StringSlice{string(rawVulnsA)}},+ {ID: "sha256:img-b", ImageName: "redis:7", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 1, HighCount: 1, MediumCount: 1, TotalCount: 3, Vulnerabilities: database.StringSlice{string(rawVulnsB)}},+ {ID: "sha256:img-failed", ImageName: "failed:latest", Status: ScanStatusFailed, ScanTime: now, CriticalCount: 9, HighCount: 9, TotalCount: 18},}for i := range records {require.NoError(t, db.Create(&records[i]).Error)@@ -359,7 +360,7 @@ func TestVulnerabilityService_ActionableCountExcludingIgnored(t *testing.T) {require.NoError(t, err)require.Equal(t, 5, count)- ignores := []models.VulnerabilityIgnore{+ ignores := []VulnerabilityIgnore{// Critical on img-b: removes one from the count.{ID: "ig-1", EnvironmentID: "env-1", ImageID: "sha256:img-b", VulnerabilityID: "CVE-B1", PkgName: "openssl", InstalledVersion: "1.1.0", CreatedBy: "tester"},// Medium on img-b: never counted, must not subtract anything.@@ -402,16 +403,16 @@ func TestVulnerabilityService_ListAllVulnerabilities_PagesAndCountsWithInlineFilrequire.NoError(t, err)now := time.Now()- records := []models.VulnerabilityScanRecord{- {ID: "sha256:img-a", ImageName: "nginx:latest", Status: models.ScanStatusCompleted, ScanTime: now, CriticalCount: 1, LowCount: 1, TotalCount: 2, Vulnerabilities: models.StringSlice{string(rawVulnsA)}},- {ID: "sha256:img-b", ImageName: "redis:7", Status: models.ScanStatusCompleted, ScanTime: now, HighCount: 1, MediumCount: 1, TotalCount: 2, Vulnerabilities: models.StringSlice{string(rawVulnsB)}},+ records := []VulnerabilityScanRecord{+ {ID: "sha256:img-a", ImageName: "nginx:latest", Status: ScanStatusCompleted, ScanTime: now, CriticalCount: 1, LowCount: 1, TotalCount: 2, Vulnerabilities: database.StringSlice{string(rawVulnsA)}},+ {ID: "sha256:img-b", ImageName: "redis:7", Status: ScanStatusCompleted, ScanTime: now, HighCount: 1, MediumCount: 1, TotalCount: 2, Vulnerabilities: database.StringSlice{string(rawVulnsB)}},}for i := range records {require.NoError(t, db.Create(&records[i]).Error)}// Ignore the medium CVE on img-b: it must vanish from GrandTotalItems.- require.NoError(t, db.Create(&models.VulnerabilityIgnore{+ require.NoError(t, db.Create(&VulnerabilityIgnore{ID: "ig-1", EnvironmentID: "env-1", ImageID: "sha256:img-b",VulnerabilityID: "CVE-B2", PkgName: "less", InstalledVersion: "600", CreatedBy: "tester",}).Error)diff --git a/backend/internal/vulnerability/vulnerability_ignores.go b/backend/internal/vulnerability/vulnerability_ignores.goindex 3a35d5228..1ee2020ec 100644--- a/backend/internal/vulnerability/vulnerability_ignores.go+++ b/backend/internal/vulnerability/vulnerability_ignores.go@@ -9,7 +9,6 @@ import ("gorm.io/gorm"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/vulnerability")@@ -23,7 +22,7 @@ func (s *VulnerabilityService) getIgnoredVulnerabilityKeySetByEnvironmentInternareturn nil, nil}- var ignores []models.VulnerabilityIgnore+ var ignores []VulnerabilityIgnoreif err := s.db.WithContext(ctx).Where("environment_id = ?", envID).Find(&ignores).Error; err != nil {return nil, errors.WrapIf(err, "failed to get ignore records")}@@ -50,7 +49,7 @@ func (s *VulnerabilityService) filterIgnoredVulnerabilitiesForImage(return vulns, nil}- var ignores []models.VulnerabilityIgnore+ var ignores []VulnerabilityIgnoreif err := s.db.WithContext(ctx).Where("image_id = ?", imageID).Find(&ignores).Error; err != nil {return nil, err}@@ -77,13 +76,13 @@ func (s *VulnerabilityService) filterIgnoredVulnerabilitiesForImage(}// IgnoreVulnerability creates a new ignore record for a vulnerability-func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID string, payload *vulnerability.IgnorePayload) (*models.VulnerabilityIgnore, error) {+func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID string, payload *vulnerability.IgnorePayload) (*VulnerabilityIgnore, error) {if s.db == nil {return nil, errors.New("database not available")}// Check if already ignored (composite key check)- var existing models.VulnerabilityIgnore+ var existing VulnerabilityIgnoreerr := s.db.WithContext(ctx).Where("environment_id = ? AND image_id = ? AND vulnerability_id = ? AND pkg_name = ? AND installed_version = ?",envID, payload.ImageID, payload.VulnerabilityID, payload.PkgName, payload.InstalledVersion,@@ -97,7 +96,7 @@ func (s *VulnerabilityService) IgnoreVulnerability(ctx context.Context, envID streturn nil, errors.WrapIf(err, "failed to check existing ignore")}- ignore := &models.VulnerabilityIgnore{+ ignore := &VulnerabilityIgnore{EnvironmentID: envID,ImageID: payload.ImageID,VulnerabilityID: payload.VulnerabilityID,@@ -126,7 +125,7 @@ func (s *VulnerabilityService) UnignoreVulnerability(ctx context.Context, envIDreturn errors.New("database not available")}- result := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", ignoreID, envID).Delete(&models.VulnerabilityIgnore{})+ result := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", ignoreID, envID).Delete(&VulnerabilityIgnore{})if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete ignore record")}@@ -181,7 +180,7 @@ func applyIgnoredVulnerabilitiesSortPart(query *gorm.DB, part string, desc bool)}}-func mapIgnoredVulnerabilities(ignores []models.VulnerabilityIgnore) []vulnerability.IgnoredVulnerability {+func mapIgnoredVulnerabilities(ignores []VulnerabilityIgnore) []vulnerability.IgnoredVulnerability {result := make([]vulnerability.IgnoredVulnerability, len(ignores))for i, ignore := range ignores {result[i] = vulnerability.IgnoredVulnerability{@@ -199,8 +198,8 @@ func mapIgnoredVulnerabilities(ignores []models.VulnerabilityIgnore) []vulnerabireturn result}-func buildIgnoredVulnerabilitiesResponse(total int64, params pagination.QueryParams, ignores []models.VulnerabilityIgnore) pagination.Response {- filtered := pagination.FilterResult[models.VulnerabilityIgnore]{+func buildIgnoredVulnerabilitiesResponse(total int64, params pagination.QueryParams, ignores []VulnerabilityIgnore) pagination.Response {+ filtered := pagination.FilterResult[VulnerabilityIgnore]{Items: ignores,TotalCount: total,TotalAvailable: total,@@ -218,13 +217,13 @@ func (s *VulnerabilityService) ListIgnoredVulnerabilities(ctx context.Context, ereturn []vulnerability.IgnoredVulnerability{}, pagination.BuildResponse(0, 0, params), nil}- var ignores []models.VulnerabilityIgnore+ var ignores []VulnerabilityIgnorequery := s.db.WithContext(ctx).Where("environment_id = ?", envID)query = applyIgnoredVulnerabilitiesSort(query, params.Sort)// Count totalvar total int64- if err := query.Model(&models.VulnerabilityIgnore{}).Count(&total).Error; err != nil {+ if err := query.Model(&VulnerabilityIgnore{}).Count(&total).Error; err != nil {return nil, pagination.Response{}, errors.WrapIf(err, "failed to count ignored vulnerabilities")}@@ -241,12 +240,12 @@ func (s *VulnerabilityService) ListIgnoredVulnerabilities(ctx context.Context, e}// GetIgnoreRecordsForImage retrieves all ignore records for a specific image-func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envID string, imageID string) ([]models.VulnerabilityIgnore, error) {+func (s *VulnerabilityService) GetIgnoreRecordsForImage(ctx context.Context, envID string, imageID string) ([]VulnerabilityIgnore, error) {if s.db == nil {return nil, nil}- var ignores []models.VulnerabilityIgnore+ var ignores []VulnerabilityIgnoreif err := s.db.WithContext(ctx).Where("environment_id = ? AND image_id = ?", envID, imageID).Find(&ignores).Error; err != nil {return nil, errors.WrapIf(err, "failed to get ignore records")}diff --git a/backend/internal/vulnerability/vulnerability_query.go b/backend/internal/vulnerability/vulnerability_query.goindex bb7ed4727..d2ba3e827 100644--- a/backend/internal/vulnerability/vulnerability_query.go+++ b/backend/internal/vulnerability/vulnerability_query.go@@ -13,7 +13,6 @@ import ("github.com/samber/mo""gorm.io/gorm"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/types/v2/vulnerability")@@ -24,7 +23,7 @@ func (s *VulnerabilityService) GetScanResult(ctx context.Context, imageID stringreturn nil, nil}- var record models.VulnerabilityScanRecord+ var record VulnerabilityScanRecorderr := s.db.WithContext(ctx).Where("id = ?", imageID).First(&record).Errorif err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {@@ -44,7 +43,7 @@ func (s *VulnerabilityService) GetScanSummary(ctx context.Context, imageID strinreturn nil, nil}- var record models.VulnerabilityScanRecord+ var record VulnerabilityScanRecorderr := s.db.WithContext(ctx).Select("id", "scan_time", "status", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "total_count", "error").Where("id = ?", imageID).@@ -181,7 +180,7 @@ func (s *VulnerabilityService) GetEnvironmentSummary(ctx context.Context) (*vulnvar agg aggregateerr := s.db.WithContext(ctx).- Model(&models.VulnerabilityScanRecord{}).+ Model(&VulnerabilityScanRecord{}).Select("COALESCE(SUM(critical_count), 0) AS critical","COALESCE(SUM(high_count), 0) AS high",@@ -191,7 +190,7 @@ func (s *VulnerabilityService) GetEnvironmentSummary(ctx context.Context) (*vuln"COALESCE(SUM(total_count), 0) AS total","COUNT(*) AS scanned",).- Where("status = ?", models.ScanStatusCompleted).+ Where("status = ?", ScanStatusCompleted).Scan(&agg).Errorif err != nil {return nil, errors.WrapIf(err, "failed to aggregate vulnerability summary")@@ -226,7 +225,7 @@ func (s *VulnerabilityService) ActionableCountExcludingIgnored(ctx context.Conte// Load all ignore records (not scoped to a single environment, since an// Arcane instance serves one environment and the dashboard does not carry// an environment ID through the service layer today).- var ignores []models.VulnerabilityIgnore+ var ignores []VulnerabilityIgnoreif err := s.db.WithContext(ctx).Find(&ignores).Error; err != nil {return 0, errors.WrapIf(err, "failed to get ignore records")}@@ -241,9 +240,9 @@ func (s *VulnerabilityService) ActionableCountExcludingIgnored(ctx context.Conte}sumQuery := s.db.WithContext(ctx).- Model(&models.VulnerabilityScanRecord{}).+ Model(&VulnerabilityScanRecord{}).Select("COALESCE(SUM(critical_count + high_count), 0)").- Where("status = ?", models.ScanStatusCompleted)+ Where("status = ?", ScanStatusCompleted)if len(ignoredImageIDs) > 0 {sumQuery = sumQuery.Where("id NOT IN ?", ignoredImageIDs)}@@ -257,10 +256,10 @@ func (s *VulnerabilityService) ActionableCountExcludingIgnored(ctx context.Contereturn int(indexedCount), nil}- var records []models.VulnerabilityScanRecord+ var records []VulnerabilityScanRecorderr := s.db.WithContext(ctx).Select("id", "vulnerabilities").- Where("status = ?", models.ScanStatusCompleted).+ Where("status = ?", ScanStatusCompleted).Where("critical_count + high_count > 0").Where("id IN ?", ignoredImageIDs).Find(&records).Error@@ -307,7 +306,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envIDrecordsQuery := s.db.WithContext(ctx).Select("id", "image_name", "vulnerabilities", "total_count").- Where("status = ?", models.ScanStatusCompleted).+ Where("status = ?", ScanStatusCompleted).Where("total_count > 0")recordsQuery, hasPossibleMatches := applyListAllVulnerabilityRecordPrefiltersInternal(recordsQuery, params.Filters).Get()if !hasPossibleMatches {@@ -333,7 +332,7 @@ func (s *VulnerabilityService) ListAllVulnerabilities(ctx context.Context, envID// old path materialized every CVE of every image to serve one page.var items []vulnerability.VulnerabilityWithImagetotalAvailable := 0- var batch []models.VulnerabilityScanRecord+ var batch []VulnerabilityScanRecorderr = recordsQuery.FindInBatches(&batch, listAllVulnerabilityRecordBatchSizeInternal, func(*gorm.DB, int) error {for _, record := range batch {if len(record.Vulnerabilities) == 0 || record.Vulnerabilities[0] == "" {@@ -459,9 +458,9 @@ func (s *VulnerabilityService) ListAllVulnerabilityImageOptions(ctx context.Cont}query := s.db.WithContext(ctx).- Model(&models.VulnerabilityScanRecord{}).+ Model(&VulnerabilityScanRecord{}).Select("id", "image_name").- Where("status = ?", models.ScanStatusCompleted).+ Where("status = ?", ScanStatusCompleted).Where("total_count > 0")if strings.TrimSpace(severityFilter) != "" {@@ -474,7 +473,7 @@ func (s *VulnerabilityService) ListAllVulnerabilityImageOptions(ctx context.Cont}}- var records []models.VulnerabilityScanRecord+ var records []VulnerabilityScanRecordif err := query.Find(&records).Error; err != nil {return nil, errors.WrapIf(err, "failed to list vulnerability image options")}@@ -610,7 +609,7 @@ func (s *VulnerabilityService) GetScanSummariesByImageIDs(ctx context.Context, ireturn make(map[string]*vulnerability.ScanSummary), nil}- var records []models.VulnerabilityScanRecord+ var records []VulnerabilityScanRecorderr := s.db.WithContext(ctx).Select("id", "scan_time", "status", "critical_count", "high_count", "medium_count", "low_count", "unknown_count", "total_count", "error").Where("id IN ?", imageIDs).diff --git a/backend/internal/vulnerability/vulnerability_scan.go b/backend/internal/vulnerability/vulnerability_scan.goindex abc106bf1..d67c9c3bc 100644--- a/backend/internal/vulnerability/vulnerability_scan.go+++ b/backend/internal/vulnerability/vulnerability_scan.go@@ -1,12 +1,20 @@package vulnerabilityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/event"++ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""fmt""log/slog""strings""time"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors"imagetypes "github.com/moby/moby/api/types/image"@@ -14,7 +22,6 @@ import ("github.com/samber/mo""github.com/getarcaneapp/arcane/backend/v2/internal/activity"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/notification"activitylib "github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane/activity""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -89,7 +96,7 @@ func (s *VulnerabilityService) applyScanPhaseToResultInternal(result *vulnerabil}// ScanImage scans an image for vulnerabilities using Trivy-func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imageID string, user models.User) (*vulnerability.ScanResult, error) {+func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imageID string, user common.User) (*vulnerability.ScanResult, error) {scanCtx := utils.ActivityRuntimeContext(ctx, nil)// Get Docker client to inspect the image@@ -149,18 +156,18 @@ func (s *VulnerabilityService) ScanImage(ctx context.Context, envID string, imag)}- go func(bgCtx context.Context, scanEnvID, imgID, imgName string, scanUser models.User, scanActivityID string) {+ go func(bgCtx context.Context, scanEnvID, imgID, imgName string, scanUser common.User, scanActivityID string) {s.scanImageInBackgroundInternal(bgCtx, scanEnvID, imgID, imgName, scanUser, scanActivityID)}(scanCtx, envID, imageID, imageName, user, activityID)return pendingResult, nil}-func (s *VulnerabilityService) markStaleScanIfNeeded(ctx context.Context, record *models.VulnerabilityScanRecord) {+func (s *VulnerabilityService) markStaleScanIfNeeded(ctx context.Context, record *VulnerabilityScanRecord) {if record == nil {return}- if record.Status != models.ScanStatusScanning && record.Status != models.ScanStatusPending {+ if record.Status != ScanStatusScanning && record.Status != ScanStatusPending {return}if time.Since(record.ScanTime) <= scanStaleTimeout {@@ -168,7 +175,7 @@ func (s *VulnerabilityService) markStaleScanIfNeeded(ctx context.Context, record}errMsg := "Scan timed out or was interrupted. Please retry."- record.Status = models.ScanStatusFailed+ record.Status = ScanStatusFailedrecord.Error = &errMsgrecord.Duration = time.Since(record.ScanTime).Milliseconds()s.clearScanPhaseInternal(record.ID)@@ -178,7 +185,7 @@ func (s *VulnerabilityService) markStaleScanIfNeeded(ctx context.Context, record}if err := s.db.WithContext(ctx).- Model(&models.VulnerabilityScanRecord{}).+ Model(&VulnerabilityScanRecord{}).Where("id = ?", record.ID).Updates(map[string]any{"status": record.Status,@@ -190,7 +197,7 @@ func (s *VulnerabilityService) markStaleScanIfNeeded(ctx context.Context, record}}-func (s *VulnerabilityService) scanImageInBackgroundInternal(ctx context.Context, envID string, imageID, imageName string, user models.User, activityID string) {+func (s *VulnerabilityService) scanImageInBackgroundInternal(ctx context.Context, envID string, imageID, imageName string, user common.User, activityID string) {defer s.clearScanPhaseInternal(imageID)s.setScanPhaseInternal(imageID, vulnerability.ScanPhaseCreatingContainer)s.updateVulnerabilityScanActivityInternal(ctx, activityID, vulnerability.ScanPhaseCreatingContainer, 10, "Preparing vulnerability scanner")@@ -284,14 +291,14 @@ func (s *VulnerabilityService) scanImageInBackgroundInternal(ctx context.Contexts.completeVulnerabilityScanActivityInternal(ctx, activityID, true, "")}-func (s *VulnerabilityService) startVulnerabilityScanActivityInternal(ctx context.Context, envID, imageID, imageName string, user *models.User) string {+func (s *VulnerabilityService) startVulnerabilityScanActivityInternal(ctx context.Context, envID, imageID, imageName string, user *common.User) string {if s.activityService == nil {return ""}activity, err := s.activityService.StartActivity(ctx, activity.StartActivityRequest{EnvironmentID: envID,- Type: models.ActivityTypeVulnerabilityScan,+ Type: activitytypes.TypeVulnerabilityScan,ResourceType: new("image"),ResourceID: &imageID,ResourceName: &imageName,@@ -313,7 +320,7 @@ func (s *VulnerabilityService) updateVulnerabilityScanActivityInternal(ctx conte}if _, err := s.activityService.AppendMessage(ctx, activityID, activity.AppendActivityMessageRequest{- Level: models.ActivityMessageLevelInfo,+ Level: activitytypes.MessageLevelInfo,Message: message,Progress: &progress,Step: string(phase),@@ -327,15 +334,15 @@ func (s *VulnerabilityService) completeVulnerabilityScanActivityInternal(ctx conreturn}- status := models.ActivityStatusSuccess+ status := activitytypes.StatusSuccessmessage := "Vulnerability scan completed"var errorPtr *stringif !success {if activitylib.CancelledByContext(ctx) {- status = models.ActivityStatusCancelled+ status = activitytypes.StatusCancelledmessage = "Vulnerability scan cancelled"} else {- status = models.ActivityStatusFailed+ status = activitytypes.StatusFailedmessage = "Vulnerability scan failed"if strings.TrimSpace(errMessage) != "" {errorPtr = &errMessage@@ -411,7 +418,7 @@ func (s *VulnerabilityService) runScheduledImageScanInternal(func (s *VulnerabilityService) saveScheduledFailedScanInternal(ctx context.Context,envID, imageID, imageName string,- user models.User,+ user common.User,duration int64,scanErr error,) {@@ -432,7 +439,7 @@ func (s *VulnerabilityService) saveScheduledFailedScanInternal(func (s *VulnerabilityService) saveScheduledSuccessfulScanInternal(ctx context.Context,envID, imageID, imageName string,- user models.User,+ user common.User,result *vulnerability.ScanResult,duration int64,) {@@ -509,7 +516,7 @@ func (s *VulnerabilityService) sendScheduledVulnerabilitySummaryInternal(// container is created and reused for every image via docker exec, which avoids// the overhead of creating/destroying a container per scan. The caller-supplied// user is recorded in the event log.-func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string, user models.User) (scanned, failed int, err error) {+func (s *VulnerabilityService) ScanAllImages(ctx context.Context, envID string, user common.User) (scanned, failed int, err error) {dockerClient, err := s.dockerService.GetClient(ctx)if err != nil {return 0, 0, errors.WrapIf(err, "failed to connect to Docker")@@ -579,8 +586,8 @@ func (s *VulnerabilityService) fixedVulnerabilitiesForNotifications(}// logScanEvent logs a vulnerability scan event-func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID string, imageID, imageName string, user models.User, success bool, errMsg string) {- metadata := models.JSON{+func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID string, imageID, imageName string, user common.User, success bool, errMsg string) {+ metadata := database.JSON{"action": "vulnerability_scan","imageId": imageID,"imageName": imageName,@@ -595,15 +602,15 @@ func (s *VulnerabilityService) logScanEvent(ctx context.Context, envID string, ienvironmentID = "0"}- eventType := models.EventTypeImageScan+ eventType := event.EventTypeImageScanif err := s.eventService.LogImageEvent(ctx, eventType, imageID, imageName, user.ID, user.Username, environmentID, metadata); err != nil {slog.WarnContext(ctx, "failed to log vulnerability scan event", "error", err)}}// logScheduledScanEvent logs a vulnerability scan event using the dedicated scheduled scan event type.-func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envID string, imageID, imageName string, user models.User, success bool, errMsg string) {- metadata := models.JSON{+func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envID string, imageID, imageName string, user common.User, success bool, errMsg string) {+ metadata := database.JSON{"action": "scheduled_vulnerability_scan","imageId": imageID,"imageName": imageName,@@ -618,7 +625,7 @@ func (s *VulnerabilityService) logScheduledScanEvent(ctx context.Context, envIDenvironmentID = "0"}- if err := s.eventService.LogImageEvent(ctx, models.EventTypeImageVulnerabilityScan, imageID, imageName, user.ID, user.Username, environmentID, metadata); err != nil {+ if err := s.eventService.LogImageEvent(ctx, event.EventTypeImageVulnerabilityScan, imageID, imageName, user.ID, user.Username, environmentID, metadata); err != nil {slog.WarnContext(ctx, "failed to log scheduled vulnerability scan event", "error", err)}}diff --git a/backend/internal/vulnerability/vulnerability_store.go b/backend/internal/vulnerability/vulnerability_store.goindex 44f922786..2d935b654 100644--- a/backend/internal/vulnerability/vulnerability_store.go+++ b/backend/internal/vulnerability/vulnerability_store.go@@ -1,6 +1,8 @@package vulnerabilityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""encoding/json/v2""fmt"@@ -14,7 +16,6 @@ import ("gorm.io/gorm""gorm.io/gorm/clause"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/dbutil""github.com/getarcaneapp/arcane/types/v2/vulnerability")@@ -25,7 +26,7 @@ func (s *VulnerabilityService) DeleteScanResult(ctx context.Context, imageID strreturn nil}- return s.db.WithContext(ctx).Where("id = ?", imageID).Delete(&models.VulnerabilityScanRecord{}).Error+ return s.db.WithContext(ctx).Where("id = ?", imageID).Delete(&VulnerabilityScanRecord{}).Error}// DeleteScanResultsByImageIDs deletes scan results for multiple images in one query.@@ -34,7 +35,7 @@ func (s *VulnerabilityService) DeleteScanResultsByImageIDs(ctx context.Context,return nil}- return s.db.WithContext(ctx).Where("id IN ?", imageIDs).Delete(&models.VulnerabilityScanRecord{}).Error+ return s.db.WithContext(ctx).Where("id IN ?", imageIDs).Delete(&VulnerabilityScanRecord{}).Error}// CleanupOrphanedScanRecords removes vulnerability scan records for images that@@ -73,9 +74,9 @@ func (s *VulnerabilityService) CleanupOrphanedScanRecords(ctx context.Context) (var result *gorm.DBif len(ids) == 0 {- result = s.db.WithContext(ctx).Where("1 = 1").Delete(&models.VulnerabilityScanRecord{})+ result = s.db.WithContext(ctx).Where("1 = 1").Delete(&VulnerabilityScanRecord{})} else {- result = s.db.WithContext(ctx).Where("id NOT IN ?", ids).Delete(&models.VulnerabilityScanRecord{})+ result = s.db.WithContext(ctx).Where("id NOT IN ?", ids).Delete(&VulnerabilityScanRecord{})}if result.Error != nil {return 0, result.Error@@ -171,7 +172,7 @@ func (s *VulnerabilityService) saveScanResultStatusFallbackInternal(ctx context.}if err := s.db.WithContext(ctx).- Model(&models.VulnerabilityScanRecord{}).+ Model(&VulnerabilityScanRecord{}).Where("id = ?", result.ImageID).Updates(updates).Error; err != nil {slog.WarnContext(ctx,@@ -201,13 +202,13 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulnes.ensureSummary(result)// Convert vulnerabilities to JSON- var vulnJSON models.StringSlice+ var vulnJSON database.StringSliceif len(result.Vulnerabilities) > 0 {vulnBytes, err := json.Marshal(result.Vulnerabilities)if err != nil {return errors.WrapIf(err, "failed to marshal vulnerabilities")}- vulnJSON = models.StringSlice{string(vulnBytes)}+ vulnJSON = database.StringSlice{string(vulnBytes)}}var errPtr *string@@ -222,7 +223,7 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulnesummary = &vulnerability.SeveritySummary{}}- record := models.VulnerabilityScanRecord{+ record := VulnerabilityScanRecord{ID: result.ImageID,ImageName: result.ImageName,Status: string(result.Status),@@ -247,7 +248,7 @@ func (s *VulnerabilityService) saveScanResult(ctx context.Context, result *vulne}// convertRecordToResult converts a database record to a ScanResult-func (s *VulnerabilityService) convertRecordToResult(record *models.VulnerabilityScanRecord) (*vulnerability.ScanResult, error) {+func (s *VulnerabilityService) convertRecordToResult(record *VulnerabilityScanRecord) (*vulnerability.ScanResult, error) {result := &vulnerability.ScanResult{ImageID: record.ID,ImageName: record.ImageName,diff --git a/backend/internal/vulnerability/vulnerability_trivy.go b/backend/internal/vulnerability/vulnerability_trivy.goindex 25ba93898..14559bddf 100644--- a/backend/internal/vulnerability/vulnerability_trivy.go+++ b/backend/internal/vulnerability/vulnerability_trivy.go@@ -1,6 +1,8 @@package vulnerabilityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""fmt""io"@@ -18,7 +20,6 @@ import ("github.com/moby/moby/client""github.com/samber/mo"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutils "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -165,7 +166,7 @@ func (s *VulnerabilityService) scanSingleImage(containerID string,img imagetypes.Summary,scannerVersion, envID string,- user models.User,+ user common.User,notificationSummary *scheduledScanNotificationSummary,) scanResultStatus {imageID, imageName, shouldScan := scheduledScanImageTargetInternal(img)@@ -816,7 +817,7 @@ func (s *VulnerabilityService) createAndStartTrivyContainerInternal(}func (s *VulnerabilityService) getTrivyContainerResourcesInternal() mo.Option[containertypes.Resources] {- var cfg *models.Settings+ var cfg *settings.Settingsif s.settingsService != nil {cfg = s.settingsService.GetSettingsConfig()}@@ -878,7 +879,7 @@ func (s *VulnerabilityService) getTrivyContainerResourceOptionsInternal(ctx contreturn resources, cpuSet, applyLimits}-func buildTrivyContainerResourcesInternal(cfg *models.Settings) mo.Option[containertypes.Resources] {+func buildTrivyContainerResourcesInternal(cfg *settings.Settings) mo.Option[containertypes.Resources] {limitsEnabled := truecpuLimitCores := defaultTrivyCPULimitCoresmemoryLimitMB := defaultTrivyMemoryLimitMBdiff --git a/backend/internal/webhook/handler.go b/backend/internal/webhook/handler.goindex f70d64a5c..79c6518c3 100644--- a/backend/internal/webhook/handler.go+++ b/backend/internal/webhook/handler.go@@ -1,6 +1,8 @@package webhookimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""net/http"@@ -8,7 +10,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/handlerutil""github.com/getarcaneapp/arcane/types/v2/base"@@ -123,8 +124,8 @@ func (h *WebhookHandler) CreateWebhook(ctx context.Context, input *CreateWebhookreturn nil, huma.Error400BadRequest("request body is required")}- actor := models.User{}- if currentUser, exists := models.CurrentUserFromContext(ctx); exists && currentUser != nil {+ actor := common.User{}+ if currentUser, exists := common.CurrentUserFromContext(ctx); exists && currentUser != nil {actor = *currentUser}@@ -172,8 +173,8 @@ func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhookreturn nil, huma.Error400BadRequest("request body is required")}- actor := models.User{}- if currentUser, exists := models.CurrentUserFromContext(ctx); exists && currentUser != nil {+ actor := common.User{}+ if currentUser, exists := common.CurrentUserFromContext(ctx); exists && currentUser != nil {actor = *currentUser}@@ -193,8 +194,8 @@ func (h *WebhookHandler) UpdateWebhook(ctx context.Context, input *UpdateWebhook// DeleteWebhook removes a webhook.func (h *WebhookHandler) DeleteWebhook(ctx context.Context, input *DeleteWebhookInput) (*DeleteWebhookOutput, error) {- actor := models.User{}- if currentUser, exists := models.CurrentUserFromContext(ctx); exists && currentUser != nil {+ actor := common.User{}+ if currentUser, exists := common.CurrentUserFromContext(ctx); exists && currentUser != nil {actor = *currentUser}diff --git a/backend/internal/models/webhook.go b/backend/internal/webhook/model.gosimilarity index 92%rename from backend/internal/models/webhook.gorename to backend/internal/webhook/model.goindex fd0ad0d63..64d3305e5 100644--- a/backend/internal/models/webhook.go+++ b/backend/internal/webhook/model.go@@ -1,6 +1,10 @@-package models+package webhook-import "time"+import (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"++ "time"+)const (WebhookTargetTypeContainer = "container"@@ -20,7 +24,7 @@ const ()type Webhook struct {- BaseModel+ database.BaseModelName string `json:"name" gorm:"column:name;not null"`TokenHash string `json:"-" gorm:"column:token_hash;not null;uniqueIndex"`diff --git a/backend/internal/webhook/webhook.go b/backend/internal/webhook/webhook.goindex e293047c6..cbafd6298 100644--- a/backend/internal/webhook/webhook.go+++ b/backend/internal/webhook/webhook.go@@ -1,6 +1,8 @@package webhookimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""crypto/rand""crypto/sha256"@@ -22,7 +24,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/environment""github.com/getarcaneapp/arcane/backend/v2/internal/event""github.com/getarcaneapp/arcane/backend/v2/internal/gitops"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/project""github.com/getarcaneapp/arcane/backend/v2/internal/updater""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"@@ -120,12 +121,12 @@ func parseWebhookPrefixInternal(raw string) (string, error) {func defaultWebhookActionTypeInternal(targetType string) (string, error) {switch targetType {- case models.WebhookTargetTypeContainer, models.WebhookTargetTypeProject:- return models.WebhookActionTypeUpdate, nil- case models.WebhookTargetTypeUpdater:- return models.WebhookActionTypeRun, nil- case models.WebhookTargetTypeGitOps:- return models.WebhookActionTypeSync, nil+ case WebhookTargetTypeContainer, WebhookTargetTypeProject:+ return WebhookActionTypeUpdate, nil+ case WebhookTargetTypeUpdater:+ return WebhookActionTypeRun, nil+ case WebhookTargetTypeGitOps:+ return WebhookActionTypeSync, nildefault:return "", ErrWebhookInvalidType}@@ -133,7 +134,7 @@ func defaultWebhookActionTypeInternal(targetType string) (string, error) {func resolveWebhookActionTypeInternal(targetType, actionType string) (string, error) {switch targetType {- case models.WebhookTargetTypeContainer, models.WebhookTargetTypeProject, models.WebhookTargetTypeUpdater, models.WebhookTargetTypeGitOps:+ case WebhookTargetTypeContainer, WebhookTargetTypeProject, WebhookTargetTypeUpdater, WebhookTargetTypeGitOps:default:return "", ErrWebhookInvalidType}@@ -143,27 +144,27 @@ func resolveWebhookActionTypeInternal(targetType, actionType string) (string, erreturn defaultWebhookActionTypeInternal(targetType)}- if targetType == models.WebhookTargetTypeProject && normalizedActionType == "deploy" {- normalizedActionType = models.WebhookActionTypeUp+ if targetType == WebhookTargetTypeProject && normalizedActionType == "deploy" {+ normalizedActionType = WebhookActionTypeUp}switch targetType {- case models.WebhookTargetTypeContainer:+ case WebhookTargetTypeContainer:switch normalizedActionType {- case models.WebhookActionTypeUpdate, models.WebhookActionTypeStart, models.WebhookActionTypeStop, models.WebhookActionTypeRestart, models.WebhookActionTypeRedeploy:+ case WebhookActionTypeUpdate, WebhookActionTypeStart, WebhookActionTypeStop, WebhookActionTypeRestart, WebhookActionTypeRedeploy:return normalizedActionType, nil}- case models.WebhookTargetTypeProject:+ case WebhookTargetTypeProject:switch normalizedActionType {- case models.WebhookActionTypeUpdate, models.WebhookActionTypeUp, models.WebhookActionTypeDown, models.WebhookActionTypeRestart, models.WebhookActionTypeRedeploy:+ case WebhookActionTypeUpdate, WebhookActionTypeUp, WebhookActionTypeDown, WebhookActionTypeRestart, WebhookActionTypeRedeploy:return normalizedActionType, nil}- case models.WebhookTargetTypeUpdater:- if normalizedActionType == models.WebhookActionTypeRun {+ case WebhookTargetTypeUpdater:+ if normalizedActionType == WebhookActionTypeRun {return normalizedActionType, nil}- case models.WebhookTargetTypeGitOps:- if normalizedActionType == models.WebhookActionTypeSync {+ case WebhookTargetTypeGitOps:+ if normalizedActionType == WebhookActionTypeSync {return normalizedActionType, nil}}@@ -181,7 +182,7 @@ 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 models.User) (*models.Webhook, string, error) {+func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, actionType, targetID, environmentID string, actor common.User) (*Webhook, string, error) {resolvedActionType, err := resolveWebhookActionTypeInternal(targetType, actionType)if err != nil {return nil, "", err@@ -190,7 +191,7 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, actargetRef := ""// The updater target type operates environment-wide and has no specific target resource.- if targetType == models.WebhookTargetTypeUpdater {+ if targetType == WebhookTargetTypeUpdater {targetID = ""} else if strings.TrimSpace(targetID) == "" {return nil, "", ErrWebhookMissingTarget@@ -198,7 +199,7 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, ac// Container references can only be resolved against the local Docker daemon;// remote-environment webhooks keep the raw target and resolve on trigger.- if targetType == models.WebhookTargetTypeContainer && !isRemoteWebhookEnvironmentInternal(environmentID) {+ if targetType == WebhookTargetTypeContainer && !isRemoteWebhookEnvironmentInternal(environmentID) {targetRef, err = s.resolveContainerWebhookTargetRefInternal(ctx, targetID)if err != nil {return nil, "", err@@ -210,7 +211,7 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, acreturn nil, "", err}- wh := &models.Webhook{+ wh := &Webhook{Name: name,TokenHash: hash,TokenPrefix: prefix,@@ -228,8 +229,8 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, acif s.eventService != nil {_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeWebhookCreate,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeWebhookCreate,+ Severity: event.EventSeveritySuccess,Title: "Webhook created: " + wh.Name,Description: fmt.Sprintf("Created webhook '%s' targeting %s (%s)", wh.Name, wh.TargetType, wh.ActionType),ResourceType: new("webhook"),@@ -245,8 +246,8 @@ func (s *WebhookService) CreateWebhook(ctx context.Context, name, targetType, ac}// ListWebhooks returns all webhooks for an environment.-func (s *WebhookService) ListWebhooks(ctx context.Context, environmentID string) ([]models.Webhook, error) {- var webhooks []models.Webhook+func (s *WebhookService) ListWebhooks(ctx context.Context, environmentID string) ([]Webhook, error) {+ var webhooks []Webhookif err := s.db.WithContext(ctx).Where("environment_id = ?", environmentID).Order("created_at DESC").@@ -283,9 +284,9 @@ func (s *WebhookService) ListWebhookSummaries(ctx context.Context, environmentIDreturn summaries, nil}-func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, wh *models.Webhook) string {+func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, wh *Webhook) string {switch wh.TargetType {- case models.WebhookTargetTypeContainer:+ case WebhookTargetTypeContainer:// Remote containers cannot be resolved against the local Docker daemon.if isRemoteWebhookEnvironmentInternal(wh.EnvironmentID) {if strings.TrimSpace(wh.TargetRef) != "" {@@ -311,8 +312,8 @@ func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, wreturn ""}return name- case models.WebhookTargetTypeProject:- var project models.Project+ case WebhookTargetTypeProject:+ var project project.Projectif err := s.db.WithContext(ctx).Select("name").Where("id = ?", wh.TargetID).@@ -320,10 +321,10 @@ func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, wreturn ""}return project.Name- case models.WebhookTargetTypeUpdater:+ case WebhookTargetTypeUpdater:return "Environment updater"- case models.WebhookTargetTypeGitOps:- var sync models.GitOpsSync+ case WebhookTargetTypeGitOps:+ var sync project.GitOpsSyncif err := s.db.WithContext(ctx).Select("name").Where("id = ? AND environment_id = ?", wh.TargetID, wh.EnvironmentID).@@ -337,8 +338,8 @@ func (s *WebhookService) resolveWebhookTargetNameInternal(ctx context.Context, w}// GetWebhookByID returns a single webhook by ID, scoped to an environment.-func (s *WebhookService) GetWebhookByID(ctx context.Context, id, environmentID string) (*models.Webhook, error) {- var wh models.Webhook+func (s *WebhookService) GetWebhookByID(ctx context.Context, id, environmentID string) (*Webhook, error) {+ var wh Webhookerr := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", id, environmentID).First(&wh).Error@@ -352,7 +353,7 @@ func (s *WebhookService) GetWebhookByID(ctx context.Context, id, environmentID s}// DeleteWebhook removes a webhook by ID, scoped to an environment.-func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID string, actor models.User) error {+func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID string, actor common.User) error {wh, err := s.GetWebhookByID(ctx, id, environmentID)if err != nil {return err@@ -360,7 +361,7 @@ func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID stresult := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", id, environmentID).- Delete(&models.Webhook{})+ Delete(&Webhook{})if result.Error != nil {return errors.WrapIf(result.Error, "failed to delete webhook")}@@ -370,8 +371,8 @@ func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID stif s.eventService != nil {_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeWebhookDelete,- Severity: models.EventSeverityInfo,+ Type: event.EventTypeWebhookDelete,+ Severity: event.EventSeverityInfo,Title: "Webhook deleted: " + wh.Name,Description: fmt.Sprintf("Deleted webhook '%s'", wh.Name),ResourceType: new("webhook"),@@ -387,8 +388,8 @@ func (s *WebhookService) DeleteWebhook(ctx context.Context, id, environmentID st}// UpdateWebhook updates the enabled state of a webhook, scoped to an environment.-func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID string, enabled bool, actor models.User) (*models.Webhook, error) {- var wh models.Webhook+func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID string, enabled bool, actor common.User) (*Webhook, error) {+ var wh Webhookerr := s.db.WithContext(ctx).Where("id = ? AND environment_id = ?", id, environmentID).First(&wh).Error@@ -405,8 +406,8 @@ func (s *WebhookService) UpdateWebhook(ctx context.Context, id, environmentID stif s.eventService != nil {_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeWebhookUpdate,- Severity: models.EventSeveritySuccess,+ Type: event.EventTypeWebhookUpdate,+ Severity: event.EventSeveritySuccess,Title: "Webhook updated: " + wh.Name,Description: fmt.Sprintf("Updated webhook '%s' enabled=%v", wh.Name, enabled),ResourceType: new("webhook"),@@ -432,7 +433,7 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) er}// Narrow by prefix first (indexed), then verify hash- var candidates []models.Webhook+ var candidates []Webhookif err := s.db.WithContext(ctx).Where("token_prefix = ?", prefix).Find(&candidates).Error; err != nil {@@ -440,7 +441,7 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) er}hash := hashWebhookTokenInternal(rawToken)- var wh *models.Webhook+ var wh *Webhookfor i := range candidates {if candidates[i].TokenHash == hash {wh = &candidates[i]@@ -475,7 +476,7 @@ func (s *WebhookService) TriggerByToken(ctx context.Context, rawToken string) erslog.ErrorContext(execCtx, "webhook action failed", "webhookID", wh.ID, "webhookName", wh.Name, "actionType", actionType, "error", err)return}- s.logWebhookEventInternal(execCtx, wh, actionType, models.EventSeveritySuccess, "")+ s.logWebhookEventInternal(execCtx, wh, actionType, event.EventSeveritySuccess, "")})return nil@@ -487,7 +488,7 @@ func (s *WebhookService) DrainActions(ctx context.Context) error {return utils.WaitGroup(ctx, &s.actions)}-func (s *WebhookService) executeWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updatertypes.Result, error) {+func (s *WebhookService) executeWebhookActionInternal(ctx context.Context, wh *Webhook, actionType string) (*updatertypes.Result, error) {// Webhooks are stored and triggered on the manager; actions against remote// environments are forwarded through the environment proxy.if isRemoteWebhookEnvironmentInternal(wh.EnvironmentID) {@@ -495,13 +496,13 @@ func (s *WebhookService) executeWebhookActionInternal(ctx context.Context, wh *m}switch wh.TargetType {- case models.WebhookTargetTypeContainer:+ case WebhookTargetTypeContainer:return s.executeContainerWebhookActionInternal(ctx, wh, actionType)- case models.WebhookTargetTypeProject:+ case WebhookTargetTypeProject:return s.executeProjectWebhookActionInternal(ctx, wh, actionType)- case models.WebhookTargetTypeUpdater:+ case WebhookTargetTypeUpdater:return s.executeUpdaterWebhookActionInternal(ctx, wh, actionType)- case models.WebhookTargetTypeGitOps:+ case WebhookTargetTypeGitOps:return s.executeGitOpsWebhookActionInternal(ctx, wh, actionType)default:return nil, ErrWebhookInvalidType@@ -512,11 +513,11 @@ func (s *WebhookService) executeWebhookActionInternal(ctx context.Context, wh *m// request forwarded to the remote environment. Paths use the agent-local// environment ID, matching the environment proxy's path-rewriting convention.// wantResult reports whether the response carries an updatertypes.Result payload.-func remoteWebhookRequestInternal(wh *models.Webhook, actionType string) (method, path string, wantResult bool, err error) {+func remoteWebhookRequestInternal(wh *Webhook, actionType string) (method, path string, wantResult bool, err error) {apiPrefix := "/api/environments/" + types.LocalDockerEnvironmentIDswitch wh.TargetType {- case models.WebhookTargetTypeContainer:+ case WebhookTargetTypeContainer:ref := strings.TrimSpace(wh.TargetRef)if ref == "" {ref = strings.TrimSpace(wh.TargetID)@@ -526,28 +527,28 @@ func remoteWebhookRequestInternal(wh *models.Webhook, actionType string) (method}containerPath := apiPrefix + "/containers/" + url.PathEscape(ref)switch actionType {- case models.WebhookActionTypeUpdate:+ case WebhookActionTypeUpdate:return http.MethodPost, containerPath + "/update", true, nil- case models.WebhookActionTypeStart, models.WebhookActionTypeStop, models.WebhookActionTypeRestart, models.WebhookActionTypeRedeploy:+ case WebhookActionTypeStart, WebhookActionTypeStop, WebhookActionTypeRestart, WebhookActionTypeRedeploy:return http.MethodPost, containerPath + "/" + actionType, false, nil}return "", "", false, ErrWebhookInvalidAction- case models.WebhookTargetTypeProject:+ case WebhookTargetTypeProject:projectPath := apiPrefix + "/projects/" + url.PathEscape(wh.TargetID)switch actionType {- case models.WebhookActionTypeUpdate:+ case WebhookActionTypeUpdate:return http.MethodPost, projectPath + "/update-services", false, nil- case models.WebhookActionTypeUp, models.WebhookActionTypeDown, models.WebhookActionTypeRestart, models.WebhookActionTypeRedeploy:+ case WebhookActionTypeUp, WebhookActionTypeDown, WebhookActionTypeRestart, WebhookActionTypeRedeploy:return http.MethodPost, projectPath + "/" + actionType, false, nil}return "", "", false, ErrWebhookInvalidAction- case models.WebhookTargetTypeUpdater:- if actionType != models.WebhookActionTypeRun {+ case WebhookTargetTypeUpdater:+ if actionType != WebhookActionTypeRun {return "", "", false, ErrWebhookInvalidAction}return http.MethodPost, apiPrefix + "/updater/run", true, nil- case models.WebhookTargetTypeGitOps:- if actionType != models.WebhookActionTypeSync {+ case WebhookTargetTypeGitOps:+ if actionType != WebhookActionTypeSync {return "", "", false, ErrWebhookInvalidAction}return http.MethodPost, apiPrefix + "/gitops-syncs/" + url.PathEscape(wh.TargetID) + "/sync", false, nil@@ -556,7 +557,7 @@ func remoteWebhookRequestInternal(wh *models.Webhook, actionType string) (method}}-func (s *WebhookService) executeRemoteWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updatertypes.Result, error) {+func (s *WebhookService) executeRemoteWebhookActionInternal(ctx context.Context, wh *Webhook, actionType string) (*updatertypes.Result, error) {if s.environmentService == nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, wh.TargetType, actionType, errors.New("environment service not available"))}@@ -583,36 +584,36 @@ func (s *WebhookService) executeRemoteWebhookActionInternal(ctx context.Context,return result, nil}-func (s *WebhookService) executeContainerWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updatertypes.Result, error) {+func (s *WebhookService) executeContainerWebhookActionInternal(ctx context.Context, wh *Webhook, actionType string) (*updatertypes.Result, error) {containerID, err := s.resolveContainerWebhookTargetIDInternal(ctx, wh)if err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)}switch actionType {- case models.WebhookActionTypeUpdate:+ case WebhookActionTypeUpdate:result, err := s.updaterService.UpdateSingleContainer(ctx, containerID)if err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)}return result, nil- case models.WebhookActionTypeStart:- if err := s.containerService.StartContainer(ctx, containerID, models.SystemUser); err != nil {+ case WebhookActionTypeStart:+ if err := s.containerService.StartContainer(ctx, containerID, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)}return nil, nil- case models.WebhookActionTypeStop:- if err := s.containerService.StopContainer(ctx, containerID, models.SystemUser); err != nil {+ case WebhookActionTypeStop:+ if err := s.containerService.StopContainer(ctx, containerID, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)}return nil, nil- case models.WebhookActionTypeRestart:- if err := s.containerService.RestartContainer(ctx, containerID, models.SystemUser); err != nil {+ case WebhookActionTypeRestart:+ if err := s.containerService.RestartContainer(ctx, containerID, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)}return nil, nil- case models.WebhookActionTypeRedeploy:- if _, err := s.containerService.RedeployContainer(ctx, containerID, models.SystemUser); err != nil {+ case WebhookActionTypeRedeploy:+ if _, err := s.containerService.RedeployContainer(ctx, containerID, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "container", actionType, err)}return nil, nil@@ -634,7 +635,7 @@ func (s *WebhookService) resolveContainerWebhookTargetRefInternal(ctx context.Coreturn containerName, nil}-func (s *WebhookService) resolveContainerWebhookTargetIDInternal(ctx context.Context, wh *models.Webhook) (string, error) {+func (s *WebhookService) resolveContainerWebhookTargetIDInternal(ctx context.Context, wh *Webhook) (string, error) {if s.containerService == nil {return wh.TargetID, nil}@@ -667,7 +668,7 @@ func (s *WebhookService) resolveContainerWebhookTargetIDInternal(ctx context.Conreturn "", ErrWebhookMissingTarget}-func (s *WebhookService) syncWebhookContainerTargetInternal(ctx context.Context, wh *models.Webhook, containerID, containerName string) {+func (s *WebhookService) syncWebhookContainerTargetInternal(ctx context.Context, wh *Webhook, containerID, containerName string) {updates := map[string]any{}if containerID != "" && containerID != wh.TargetID {updates["target_id"] = containerID@@ -684,30 +685,30 @@ func (s *WebhookService) syncWebhookContainerTargetInternal(ctx context.Context,_ = s.db.WithContext(ctx).Model(wh).Updates(updates).Error}-func (s *WebhookService) executeProjectWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updatertypes.Result, error) {+func (s *WebhookService) executeProjectWebhookActionInternal(ctx context.Context, wh *Webhook, actionType string) (*updatertypes.Result, error) {switch actionType {- case models.WebhookActionTypeUpdate:- if err := s.projectService.UpdateProjectServices(ctx, wh.TargetID, nil, models.SystemUser); err != nil {+ case WebhookActionTypeUpdate:+ if err := s.projectService.UpdateProjectServices(ctx, wh.TargetID, nil, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)}return nil, nil- case models.WebhookActionTypeUp:- if err := s.projectService.DeployProject(ctx, wh.TargetID, models.SystemUser, nil); err != nil {+ case WebhookActionTypeUp:+ if err := s.projectService.DeployProject(ctx, wh.TargetID, common.SystemUser, nil); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)}return nil, nil- case models.WebhookActionTypeDown:- if err := s.projectService.DownProject(ctx, wh.TargetID, models.SystemUser); err != nil {+ case WebhookActionTypeDown:+ if err := s.projectService.DownProject(ctx, wh.TargetID, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)}return nil, nil- case models.WebhookActionTypeRestart:- if err := s.projectService.RestartProject(ctx, wh.TargetID, nil, models.SystemUser); err != nil {+ case WebhookActionTypeRestart:+ if err := s.projectService.RestartProject(ctx, wh.TargetID, nil, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)}return nil, nil- case models.WebhookActionTypeRedeploy:- if err := s.projectService.RedeployProject(ctx, wh.TargetID, models.SystemUser, nil); err != nil {+ case WebhookActionTypeRedeploy:+ if err := s.projectService.RedeployProject(ctx, wh.TargetID, common.SystemUser, nil); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "project", actionType, err)}return nil, nil@@ -716,8 +717,8 @@ func (s *WebhookService) executeProjectWebhookActionInternal(ctx context.Context}}-func (s *WebhookService) executeUpdaterWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updatertypes.Result, error) {- if actionType != models.WebhookActionTypeRun {+func (s *WebhookService) executeUpdaterWebhookActionInternal(ctx context.Context, wh *Webhook, actionType string) (*updatertypes.Result, error) {+ if actionType != WebhookActionTypeRun {return nil, ErrWebhookInvalidAction}@@ -729,30 +730,30 @@ func (s *WebhookService) executeUpdaterWebhookActionInternal(ctx context.Contextreturn result, nil}-func (s *WebhookService) executeGitOpsWebhookActionInternal(ctx context.Context, wh *models.Webhook, actionType string) (*updatertypes.Result, error) {- if actionType != models.WebhookActionTypeSync {+func (s *WebhookService) executeGitOpsWebhookActionInternal(ctx context.Context, wh *Webhook, actionType string) (*updatertypes.Result, error) {+ if actionType != WebhookActionTypeSync {return nil, ErrWebhookInvalidAction}- if _, err := s.gitOpsSyncService.PerformSync(ctx, wh.EnvironmentID, wh.TargetID, models.SystemUser); err != nil {+ if _, err := s.gitOpsSyncService.PerformSync(ctx, wh.EnvironmentID, wh.TargetID, common.SystemUser); err != nil {return nil, s.wrapWebhookActionErrorInternal(ctx, wh, "gitops", actionType, err)}return nil, nil}-func (s *WebhookService) wrapWebhookActionErrorInternal(ctx context.Context, wh *models.Webhook, targetKind, actionType string, err error) error {+func (s *WebhookService) wrapWebhookActionErrorInternal(ctx context.Context, wh *Webhook, targetKind, actionType string, err error) error {msg := fmt.Sprintf("%s %s failed: %s", targetKind, actionType, err)- s.logWebhookEventInternal(ctx, wh, actionType, models.EventSeverityError, msg)+ s.logWebhookEventInternal(ctx, wh, actionType, event.EventSeverityError, msg)return errors.WrapIff(err, "%s %s failed", targetKind, actionType)}-func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *models.Webhook, actionType string, severity models.EventSeverity, errMsg string) {+func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *Webhook, actionType string, severity event.EventSeverity, errMsg string) {if s.eventService == nil {return}title := "Webhook triggered: " + wh.Name- if severity == models.EventSeverityError {+ if severity == event.EventSeverityError {title = "Webhook trigger failed: " + wh.Name}description := fmt.Sprintf("Target type: %s, action: %s", wh.TargetType, actionType)@@ -760,7 +761,7 @@ func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *modelsdescription = errMsg}_, _ = s.eventService.CreateEvent(ctx, event.CreateEventRequest{- Type: models.EventTypeWebhookTrigger,+ Type: event.EventTypeWebhookTrigger,Severity: severity,Title: title,Description: description,@@ -768,7 +769,7 @@ func (s *WebhookService) logWebhookEventInternal(ctx context.Context, wh *modelsResourceID: &wh.ID,ResourceName: &wh.Name,EnvironmentID: &wh.EnvironmentID,- Metadata: models.JSON{+ Metadata: database.JSON{"targetType": wh.TargetType,"actionType": actionType,"targetId": wh.TargetID,diff --git a/backend/internal/webhook/webhook_test.go b/backend/internal/webhook/webhook_test.goindex 2433a4ef5..4f556ec50 100644--- a/backend/internal/webhook/webhook_test.go+++ b/backend/internal/webhook/webhook_test.go@@ -1,6 +1,8 @@package webhookimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""crypto/sha256""encoding/base64"@@ -17,7 +19,6 @@ import ("gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models")// setupWebhookServiceTestDB creates an isolated in-memory SQLite DB for each test.@@ -28,7 +29,7 @@ func setupWebhookServiceTestDB(t *testing.T) *database.DB {dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", strings.NewReplacer("/", "_", " ", "_").Replace(t.Name()))db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.Webhook{}))+ require.NoError(t, db.AutoMigrate(&Webhook{}))sqlDB, err := db.DB()require.NoError(t, err)@@ -53,23 +54,23 @@ func newTestWebhookService(db *database.DB) *WebhookService {}// fetchWebhook loads a webhook directly from the DB to inspect stored fields.-func fetchWebhook(t *testing.T, db *database.DB, id string) models.Webhook {+func fetchWebhook(t *testing.T, db *database.DB, id string) Webhook {t.Helper()- var wh models.Webhook+ var wh Webhookrequire.NoError(t, db.WithContext(context.Background()).Where("id = ?", id).First(&wh).Error)return wh}func defaultTestWebhookActionType(targetType string) string {switch targetType {- case models.WebhookTargetTypeContainer, models.WebhookTargetTypeProject:- return models.WebhookActionTypeUpdate- case models.WebhookTargetTypeUpdater:- return models.WebhookActionTypeRun- case models.WebhookTargetTypeGitOps:- return models.WebhookActionTypeSync+ case WebhookTargetTypeContainer, WebhookTargetTypeProject:+ return WebhookActionTypeUpdate+ case WebhookTargetTypeUpdater:+ return WebhookActionTypeRun+ case WebhookTargetTypeGitOps:+ return WebhookActionTypeSyncdefault:- return models.WebhookActionTypeUpdate+ return WebhookActionTypeUpdate}}@@ -134,7 +135,7 @@ func TestCreateWebhook_TokenNotStoredInPlaintext(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, rawToken, err := svc.CreateWebhook(ctx, "my-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "project-id", "env-1", models.User{})+ wh, rawToken, err := svc.CreateWebhook(ctx, "my-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-id", "env-1", common.User{})require.NoError(t, err)require.NotEmpty(t, rawToken)@@ -148,7 +149,7 @@ func TestCreateWebhook_PrefixMatchesToken(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, rawToken, err := svc.CreateWebhook(ctx, "prefix-check", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ wh, rawToken, err := svc.CreateWebhook(ctx, "prefix-check", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)@@ -164,7 +165,7 @@ func TestCreateWebhook_InvalidTargetTypeRejected(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, _, err := svc.CreateWebhook(ctx, "bad", "invalid-type", models.WebhookActionTypeUpdate, "c1", "env-1", models.User{})+ _, _, err := svc.CreateWebhook(ctx, "bad", "invalid-type", WebhookActionTypeUpdate, "c1", "env-1", common.User{})assert.ErrorIs(t, err, ErrWebhookInvalidType)}@@ -174,11 +175,11 @@ func TestCreateWebhook_EmptyTargetIDRejectedForNonUpdaterTypes(t *testing.T) {svc := newTestWebhookService(db)for _, targetType := range []string{- models.WebhookTargetTypeContainer,- models.WebhookTargetTypeProject,- models.WebhookTargetTypeGitOps,+ WebhookTargetTypeContainer,+ WebhookTargetTypeProject,+ WebhookTargetTypeGitOps,} {- _, _, err := svc.CreateWebhook(ctx, "hook", targetType, defaultTestWebhookActionType(targetType), "", "env-1", models.User{})+ _, _, err := svc.CreateWebhook(ctx, "hook", targetType, defaultTestWebhookActionType(targetType), "", "env-1", common.User{})assert.ErrorIs(t, err, ErrWebhookMissingTarget, "expected ErrWebhookMissingTarget for type %s with empty targetID", targetType)}}@@ -188,7 +189,7 @@ func TestCreateWebhook_InvalidActionTypeRejected(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, _, err := svc.CreateWebhook(ctx, "bad-action", models.WebhookTargetTypeContainer, models.WebhookActionTypeDown, "container-id", "env-1", models.User{})+ _, _, err := svc.CreateWebhook(ctx, "bad-action", WebhookTargetTypeContainer, WebhookActionTypeDown, "container-id", "env-1", common.User{})assert.ErrorIs(t, err, ErrWebhookInvalidAction)}@@ -197,13 +198,13 @@ func TestCreateWebhook_EmptyActionTypeDefaultsPerTarget(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- projectWebhook, _, err := svc.CreateWebhook(ctx, "project-hook", models.WebhookTargetTypeProject, "", "project-id", "env-1", models.User{})+ projectWebhook, _, err := svc.CreateWebhook(ctx, "project-hook", WebhookTargetTypeProject, "", "project-id", "env-1", common.User{})require.NoError(t, err)- assert.Equal(t, models.WebhookActionTypeUpdate, projectWebhook.ActionType)+ assert.Equal(t, WebhookActionTypeUpdate, projectWebhook.ActionType)- updaterWebhook, _, err := svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, "", "", "env-1", models.User{})+ updaterWebhook, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, "", "", "env-1", common.User{})require.NoError(t, err)- assert.Equal(t, models.WebhookActionTypeRun, updaterWebhook.ActionType)+ assert.Equal(t, WebhookActionTypeRun, updaterWebhook.ActionType)}func TestCreateWebhook_EmptyTargetIDAcceptedForUpdaterType(t *testing.T) {@@ -211,7 +212,7 @@ func TestCreateWebhook_EmptyTargetIDAcceptedForUpdaterType(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", "env-1", common.User{})require.NoError(t, err)assert.Empty(t, wh.TargetID)}@@ -221,10 +222,10 @@ func TestCreateWebhook_ContainerTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "container-hook", models.WebhookTargetTypeContainer, models.WebhookActionTypeUpdate, "container-id", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "container-hook", WebhookTargetTypeContainer, WebhookActionTypeUpdate, "container-id", "env-1", common.User{})require.NoError(t, err)- assert.Equal(t, models.WebhookTargetTypeContainer, wh.TargetType)- assert.Equal(t, models.WebhookActionTypeUpdate, wh.ActionType)+ assert.Equal(t, WebhookTargetTypeContainer, wh.TargetType)+ assert.Equal(t, WebhookActionTypeUpdate, wh.ActionType)}func TestCreateWebhook_ProjectTypeAccepted(t *testing.T) {@@ -232,10 +233,10 @@ func TestCreateWebhook_ProjectTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "stack-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "project-id", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "stack-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-id", "env-1", common.User{})require.NoError(t, err)- assert.Equal(t, models.WebhookTargetTypeProject, wh.TargetType)- assert.Equal(t, models.WebhookActionTypeUpdate, wh.ActionType)+ assert.Equal(t, WebhookTargetTypeProject, wh.TargetType)+ assert.Equal(t, WebhookActionTypeUpdate, wh.ActionType)}func TestCreateWebhook_UpdaterTypeAccepted(t *testing.T) {@@ -243,10 +244,10 @@ func TestCreateWebhook_UpdaterTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", "env-1", common.User{})require.NoError(t, err)- assert.Equal(t, models.WebhookTargetTypeUpdater, wh.TargetType)- assert.Equal(t, models.WebhookActionTypeRun, wh.ActionType)+ assert.Equal(t, WebhookTargetTypeUpdater, wh.TargetType)+ assert.Equal(t, WebhookActionTypeRun, wh.ActionType)}func TestCreateWebhook_GitOpsTypeAccepted(t *testing.T) {@@ -254,10 +255,10 @@ func TestCreateWebhook_GitOpsTypeAccepted(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "gitops-hook", models.WebhookTargetTypeGitOps, models.WebhookActionTypeSync, "sync-id", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "gitops-hook", WebhookTargetTypeGitOps, WebhookActionTypeSync, "sync-id", "env-1", common.User{})require.NoError(t, err)- assert.Equal(t, models.WebhookTargetTypeGitOps, wh.TargetType)- assert.Equal(t, models.WebhookActionTypeSync, wh.ActionType)+ assert.Equal(t, WebhookTargetTypeGitOps, wh.TargetType)+ assert.Equal(t, WebhookActionTypeSync, wh.ActionType)}func TestCreateWebhook_EnabledByDefault(t *testing.T) {@@ -265,7 +266,7 @@ func TestCreateWebhook_EnabledByDefault(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "enabled", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "enabled", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)assert.True(t, wh.Enabled)}@@ -275,9 +276,9 @@ func TestCreateWebhook_UniqueTokensEachCall(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, token1, err := svc.CreateWebhook(ctx, "h1", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ _, token1, err := svc.CreateWebhook(ctx, "h1", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)- _, token2, err := svc.CreateWebhook(ctx, "h2", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p2", "env-1", models.User{})+ _, token2, err := svc.CreateWebhook(ctx, "h2", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-1", common.User{})require.NoError(t, err)assert.NotEqual(t, token1, token2)@@ -290,9 +291,9 @@ func TestListWebhooks_ScopedToEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, _, err := svc.CreateWebhook(ctx, "env1-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ _, _, err := svc.CreateWebhook(ctx, "env1-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)- _, _, err = svc.CreateWebhook(ctx, "env2-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p2", "env-2", models.User{})+ _, _, err = svc.CreateWebhook(ctx, "env2-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p2", "env-2", common.User{})require.NoError(t, err)list, err := svc.ListWebhooks(ctx, "env-1")@@ -321,11 +322,11 @@ func TestListWebhookSummaries_ResolvesTargetNames(t *testing.T) {require.NoError(t, db.WithContext(ctx).Exec(`INSERT INTO projects (id, name) VALUES (?, ?)`, "project-1", "Main Project").Error)require.NoError(t, db.WithContext(ctx).Exec(`INSERT INTO gitops_syncs (id, environment_id, name) VALUES (?, ?, ?)`, "sync-1", "env-1", "Deploy Sync").Error)- _, _, err := svc.CreateWebhook(ctx, "project-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "project-1", "env-1", models.User{})+ _, _, err := svc.CreateWebhook(ctx, "project-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "project-1", "env-1", common.User{})require.NoError(t, err)- _, _, err = svc.CreateWebhook(ctx, "updater-hook", models.WebhookTargetTypeUpdater, models.WebhookActionTypeRun, "", "env-1", models.User{})+ _, _, err = svc.CreateWebhook(ctx, "updater-hook", WebhookTargetTypeUpdater, WebhookActionTypeRun, "", "env-1", common.User{})require.NoError(t, err)- _, _, err = svc.CreateWebhook(ctx, "gitops-hook", models.WebhookTargetTypeGitOps, models.WebhookActionTypeSync, "sync-1", "env-1", models.User{})+ _, _, err = svc.CreateWebhook(ctx, "gitops-hook", WebhookTargetTypeGitOps, WebhookActionTypeSync, "sync-1", "env-1", common.User{})require.NoError(t, err)summaries, err := svc.ListWebhookSummaries(ctx, "env-1")@@ -338,9 +339,9 @@ func TestListWebhookSummaries_ResolvesTargetNames(t *testing.T) {assert.Equal(t, defaultTestWebhookActionType(summary.TargetType), summary.ActionType)}- assert.Equal(t, "Main Project", targetNamesByType[models.WebhookTargetTypeProject])- assert.Equal(t, "Environment updater", targetNamesByType[models.WebhookTargetTypeUpdater])- assert.Equal(t, "Deploy Sync", targetNamesByType[models.WebhookTargetTypeGitOps])+ assert.Equal(t, "Main Project", targetNamesByType[WebhookTargetTypeProject])+ assert.Equal(t, "Environment updater", targetNamesByType[WebhookTargetTypeUpdater])+ assert.Equal(t, "Deploy Sync", targetNamesByType[WebhookTargetTypeGitOps])}func TestListWebhookSummaries_DefaultsLegacyActionType(t *testing.T) {@@ -348,11 +349,11 @@ func TestListWebhookSummaries_DefaultsLegacyActionType(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- legacyWebhook := &models.Webhook{+ legacyWebhook := &Webhook{Name: "legacy-hook",TokenHash: "hash",TokenPrefix: "arc_wh_deadbeef",- TargetType: models.WebhookTargetTypeProject,+ TargetType: WebhookTargetTypeProject,ActionType: "",TargetID: "project-1",EnvironmentID: "env-1",@@ -363,7 +364,7 @@ func TestListWebhookSummaries_DefaultsLegacyActionType(t *testing.T) {summaries, err := svc.ListWebhookSummaries(ctx, "env-1")require.NoError(t, err)require.Len(t, summaries, 1)- assert.Equal(t, models.WebhookActionTypeUpdate, summaries[0].ActionType)+ assert.Equal(t, WebhookActionTypeUpdate, summaries[0].ActionType)}// --- GetWebhookByID ---@@ -373,7 +374,7 @@ func TestGetWebhookByID_ReturnsCorrectWebhook(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "get-me", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ created, _, err := svc.CreateWebhook(ctx, "get-me", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)got, err := svc.GetWebhookByID(ctx, created.ID, "env-1")@@ -386,7 +387,7 @@ func TestGetWebhookByID_NotFoundForWrongEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "env-scoped", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ created, _, err := svc.CreateWebhook(ctx, "env-scoped", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)_, err = svc.GetWebhookByID(ctx, created.ID, "env-2")@@ -409,10 +410,10 @@ func TestDeleteWebhook_RemovesRecord(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "delete-me", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ created, _, err := svc.CreateWebhook(ctx, "delete-me", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)- require.NoError(t, svc.DeleteWebhook(ctx, created.ID, "env-1", models.User{}))+ require.NoError(t, svc.DeleteWebhook(ctx, created.ID, "env-1", common.User{}))_, err = svc.GetWebhookByID(ctx, created.ID, "env-1")assert.ErrorIs(t, err, ErrWebhookNotFound)@@ -423,10 +424,10 @@ func TestDeleteWebhook_NotFoundForWrongEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, _, err := svc.CreateWebhook(ctx, "env-scoped-delete", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ created, _, err := svc.CreateWebhook(ctx, "env-scoped-delete", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)- err = svc.DeleteWebhook(ctx, created.ID, "env-2", models.User{})+ err = svc.DeleteWebhook(ctx, created.ID, "env-2", common.User{})require.ErrorIs(t, err, ErrWebhookNotFound)// Webhook must still exist in the correct environment@@ -439,7 +440,7 @@ func TestDeleteWebhook_NotFoundForUnknownID(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- err := svc.DeleteWebhook(ctx, "does-not-exist", "env-1", models.User{})+ err := svc.DeleteWebhook(ctx, "does-not-exist", "env-1", common.User{})assert.ErrorIs(t, err, ErrWebhookNotFound)}@@ -450,15 +451,15 @@ func TestUpdateWebhook_DisableAndEnable(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "proj-1", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "proj-1", "env-1", common.User{})require.NoError(t, err)assert.True(t, wh.Enabled)- updated, err := svc.UpdateWebhook(ctx, wh.ID, "env-1", false, models.User{})+ updated, err := svc.UpdateWebhook(ctx, wh.ID, "env-1", false, common.User{})require.NoError(t, err)assert.False(t, updated.Enabled)- updated, err = svc.UpdateWebhook(ctx, wh.ID, "env-1", true, models.User{})+ updated, err = svc.UpdateWebhook(ctx, wh.ID, "env-1", true, common.User{})require.NoError(t, err)assert.True(t, updated.Enabled)}@@ -468,10 +469,10 @@ func TestUpdateWebhook_NotFoundForWrongEnvironment(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- wh, _, err := svc.CreateWebhook(ctx, "hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "proj-1", "env-1", models.User{})+ wh, _, err := svc.CreateWebhook(ctx, "hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "proj-1", "env-1", common.User{})require.NoError(t, err)- _, err = svc.UpdateWebhook(ctx, wh.ID, "env-other", false, models.User{})+ _, err = svc.UpdateWebhook(ctx, wh.ID, "env-other", false, common.User{})assert.ErrorIs(t, err, ErrWebhookNotFound)}@@ -480,7 +481,7 @@ func TestUpdateWebhook_NotFoundForUnknownID(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, err := svc.UpdateWebhook(ctx, "does-not-exist", "env-1", false, models.User{})+ _, err := svc.UpdateWebhook(ctx, "does-not-exist", "env-1", false, common.User{})assert.ErrorIs(t, err, ErrWebhookNotFound)}@@ -511,7 +512,7 @@ func TestTriggerByToken_WrongHash_NotFound(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- _, rawToken, err := svc.CreateWebhook(ctx, "hash-check", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ _, rawToken, err := svc.CreateWebhook(ctx, "hash-check", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)// Flip the last character of the token@@ -531,10 +532,10 @@ func TestTriggerByToken_DisabledWebhook(t *testing.T) {db := setupWebhookServiceTestDB(t)svc := newTestWebhookService(db)- created, rawToken, err := svc.CreateWebhook(ctx, "disabled-hook", models.WebhookTargetTypeProject, models.WebhookActionTypeUpdate, "p1", "env-1", models.User{})+ created, rawToken, err := svc.CreateWebhook(ctx, "disabled-hook", WebhookTargetTypeProject, WebhookActionTypeUpdate, "p1", "env-1", common.User{})require.NoError(t, err)- require.NoError(t, db.WithContext(ctx).Model(&models.Webhook{}).Where("id = ?", created.ID).Update("enabled", false).Error)+ require.NoError(t, db.WithContext(ctx).Model(&Webhook{}).Where("id = ?", created.ID).Update("enabled", false).Error)err = svc.TriggerByToken(ctx, rawToken)assert.ErrorIs(t, err, ErrWebhookDisabled)@@ -550,7 +551,7 @@ func TestTriggerByToken_UnknownTargetType_ReturnsInvalidType(t *testing.T) {hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)prefix := webhookTokenPrefix + hexPart[:webhookTokenPrefixLen]- wh := &models.Webhook{+ wh := &Webhook{Name: "bad-type",TokenHash: hash,TokenPrefix: prefix,@@ -567,11 +568,11 @@ func TestTriggerByToken_UnknownTargetType_ReturnsInvalidType(t *testing.T) {// insertWebhookDirect inserts a webhook record directly, bypassing CreateWebhook validation,// so dispatch tests can use known target types without needing real service dependencies.-func insertWebhookDirect(t *testing.T, ctx context.Context, db *database.DB, rawToken, targetType, actionType, targetID, envID string) *models.Webhook {+func insertWebhookDirect(t *testing.T, ctx context.Context, db *database.DB, rawToken, targetType, actionType, targetID, envID string) *Webhook {t.Helper()hash := hashWebhookTokenInternal(rawToken)hexPart := strings.TrimPrefix(rawToken, webhookTokenPrefix)- wh := &models.Webhook{+ wh := &Webhook{Name: "test-hook",TokenHash: hash,TokenPrefix: webhookTokenPrefix + hexPart[:webhookTokenPrefixLen],@@ -591,7 +592,7 @@ func TestTriggerByToken_AcceptsImmediatelyAndRecordsTriggerTime(t *testing.T) {svc := newTestWebhookService(db) // action services are nil; the async action fails, acceptance must notrawToken := "arc_wh_ccddeeff01020304aabbccdd0102030405060708090a0b0c0d0e0f1011121314"- wh := insertWebhookDirect(t, ctx, db, rawToken, models.WebhookTargetTypeContainer, models.WebhookActionTypeUpdate, "container-id", types.LocalDockerEnvironmentID)+ wh := insertWebhookDirect(t, ctx, db, rawToken, WebhookTargetTypeContainer, WebhookActionTypeUpdate, "container-id", types.LocalDockerEnvironmentID)// Valid token is accepted synchronously; the action itself runs (and here// fails against nil services) in the background without surfacing.@@ -607,7 +608,7 @@ func TestTriggerByToken_DoesNotUpdateLastTriggeredAtOnError(t *testing.T) {svc := newTestWebhookService(db)rawToken := "arc_wh_1122334401020304aabbccdd0102030405060708090a0b0c0d0e0f1011121315"- wh := insertWebhookDirect(t, ctx, db, rawToken, "unknown-type", models.WebhookActionTypeUpdate, "some-id", "env-1")+ wh := insertWebhookDirect(t, ctx, db, rawToken, "unknown-type", WebhookActionTypeUpdate, "some-id", "env-1")err := svc.TriggerByToken(ctx, rawToken)require.Error(t, err)@@ -622,7 +623,7 @@ func TestTriggerByToken_UnknownActionType_ReturnsInvalidAction(t *testing.T) {svc := newTestWebhookService(db)rawToken := "arc_wh_0011223344556677aabbccdd0102030405060708090a0b0c0d0e0f1011121314"- insertWebhookDirect(t, ctx, db, rawToken, models.WebhookTargetTypeProject, "bogus", "project-id", "env-1")+ insertWebhookDirect(t, ctx, db, rawToken, WebhookTargetTypeProject, "bogus", "project-id", "env-1")err := svc.TriggerByToken(ctx, rawToken)assert.ErrorIs(t, err, ErrWebhookInvalidAction)@@ -631,7 +632,7 @@ func TestTriggerByToken_UnknownActionType_ReturnsInvalidAction(t *testing.T) {func TestRemoteWebhookRequestInternal(t *testing.T) {tests := []struct {name string- wh models.Webhook+ wh WebhookactionType stringwantMethod stringwantPath string@@ -640,45 +641,45 @@ func TestRemoteWebhookRequestInternal(t *testing.T) {}{{name: "container update prefers target ref",- wh: models.Webhook{TargetType: models.WebhookTargetTypeContainer, TargetID: "abc123", TargetRef: "my-app"},- actionType: models.WebhookActionTypeUpdate,+ wh: Webhook{TargetType: WebhookTargetTypeContainer, TargetID: "abc123", TargetRef: "my-app"},+ actionType: WebhookActionTypeUpdate,wantMethod: "POST",wantPath: "/api/environments/0/containers/my-app/update",wantResult: true,},{name: "container start falls back to target id",- wh: models.Webhook{TargetType: models.WebhookTargetTypeContainer, TargetID: "abc123"},- actionType: models.WebhookActionTypeStart,+ wh: Webhook{TargetType: WebhookTargetTypeContainer, TargetID: "abc123"},+ actionType: WebhookActionTypeStart,wantMethod: "POST",wantPath: "/api/environments/0/containers/abc123/start",},{name: "project update maps to update-services",- wh: models.Webhook{TargetType: models.WebhookTargetTypeProject, TargetID: "p1"},- actionType: models.WebhookActionTypeUpdate,+ wh: Webhook{TargetType: WebhookTargetTypeProject, TargetID: "p1"},+ actionType: WebhookActionTypeUpdate,wantMethod: "POST",wantPath: "/api/environments/0/projects/p1/update-services",},{name: "gitops sync",- wh: models.Webhook{TargetType: models.WebhookTargetTypeGitOps, TargetID: "sync-1"},- actionType: models.WebhookActionTypeSync,+ wh: Webhook{TargetType: WebhookTargetTypeGitOps, TargetID: "sync-1"},+ actionType: WebhookActionTypeSync,wantMethod: "POST",wantPath: "/api/environments/0/gitops-syncs/sync-1/sync",},{name: "updater run carries result",- wh: models.Webhook{TargetType: models.WebhookTargetTypeUpdater},- actionType: models.WebhookActionTypeRun,+ wh: Webhook{TargetType: WebhookTargetTypeUpdater},+ actionType: WebhookActionTypeRun,wantMethod: "POST",wantPath: "/api/environments/0/updater/run",wantResult: true,},{name: "invalid action rejected",- wh: models.Webhook{TargetType: models.WebhookTargetTypeContainer, TargetID: "abc"},- actionType: models.WebhookActionTypeSync,+ wh: Webhook{TargetType: WebhookTargetTypeContainer, TargetID: "abc"},+ actionType: WebhookActionTypeSync,wantErr: ErrWebhookInvalidAction,},}diff --git a/backend/pkg/authz/access_policy_test.go b/backend/pkg/authz/access_policy_test.goindex a656f8235..68fd851f6 100644--- a/backend/pkg/authz/access_policy_test.go+++ b/backend/pkg/authz/access_policy_test.go@@ -9,6 +9,7 @@ import ("testing""github.com/getarcaneapp/arcane/backend/v2/internal/search"+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/pkg/authz""github.com/stretchr/testify/require"@@ -161,7 +162,7 @@ func TestAccessSurfaceCategoryRegistryCoversBackendCategories(t *testing.T) {"security": {},}- for _, category := range search.NewSettingsSearchService().GetSettingsCategories() {+ for _, category := range settings.NewSettingsSearchService().GetSettingsCategories() {if _, hidden := hiddenSettingsCategories[category.ID]; hidden {continue}diff --git a/backend/pkg/libarcane/activity/handler.go b/backend/pkg/libarcane/activity/handler.goindex 7b377bb2d..2f7abd111 100644--- a/backend/pkg/libarcane/activity/handler.go+++ b/backend/pkg/libarcane/activity/handler.go@@ -1,6 +1,10 @@package activityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""encoding/json/v2""fmt"@@ -9,9 +13,10 @@ import ("net/http""strings"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/samber/mo")@@ -34,15 +39,15 @@ func CancelledByContext(ctx context.Context) bool {type HandlerOptions struct {EnvironmentID string- Type models.ActivityType+ Type activitytypes.TypeResourceType stringResourceID stringResourceName string- User *models.User+ User *common.UserStep stringMessage stringSuccessMessage string- Metadata models.JSON+ Metadata database.JSON// Queue routes the activity through the per-environment concurrency// limiter so bulk long-running operations wait visibly instead of all// running at once. Quick actions (start/stop/delete) must not set this.@@ -85,14 +90,14 @@ func StartHandlerActivity(ctx context.Context,activityService Service,environmentID string,- activityType models.ActivityType,+ activityType activitytypes.Type,resourceType string,resourceID string,resourceName string,- user *models.User,+ user *common.User,step string,message string,- metadata models.JSON,+ metadata database.JSON,queue bool,) (string, context.Context) {if activityService == nil {@@ -128,17 +133,17 @@ func CompleteHandlerActivity(ctx context.Context, activityService Service, activreturn}- status := models.ActivityStatusSuccess+ status := activitytypes.StatusSuccessvar errMessage *stringfinalMessage := successMessageif err != nil {// Read the cancellation cause from the (possibly-tracked) work context// before it is re-wrapped for the DB write below.if CancelledByContext(ctx) {- status = models.ActivityStatusCancelled+ status = activitytypes.StatusCancelledfinalMessage = cancelledMessage} else {- status = models.ActivityStatusFailed+ status = activitytypes.StatusFailederrText := err.Error()errMessage = &errTextfinalMessage = errTextdiff --git a/backend/pkg/libarcane/activity/requests.go b/backend/pkg/libarcane/activity/requests.goindex 1c0d6d60f..52d845036 100644--- a/backend/pkg/libarcane/activity/requests.go+++ b/backend/pkg/libarcane/activity/requests.go@@ -1,15 +1,18 @@package activityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"++ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity")type Service interface {StartActivity(ctx context.Context, req StartRequest) (*activitytypes.Activity, error)- CompleteActivity(ctx context.Context, activityID string, status models.ActivityStatus, finalMessage string, errMessage *string, finalStep ...string) (*activitytypes.Activity, error)+ CompleteActivity(ctx context.Context, activityID string, status activitytypes.Status, finalMessage string, errMessage *string, finalStep ...string) (*activitytypes.Activity, error)}type MessageAppender interface {@@ -47,30 +50,30 @@ type StartRequest struct {// created with status queued and the caller must block on// SlotWaiter.AwaitActivitySlot before doing the work.Queue bool- Type models.ActivityType+ Type activitytypes.TypeResourceType *stringResourceID *stringResourceName *string- StartedBy *models.User+ StartedBy *common.UserStep stringLatestMessage stringProgress *int- Metadata models.JSON+ Metadata database.JSON}type UpdateRequest struct {- Status models.ActivityStatus+ Status activitytypes.StatusProgress *intStep *stringLatestMessage *stringError *string- Metadata models.JSON+ Metadata database.JSON}type AppendMessageRequest struct {- Level models.ActivityMessageLevel+ Level activitytypes.MessageLevelMessage string- Payload models.JSON+ Payload database.JSONProgress *intStep string}diff --git a/backend/pkg/libarcane/activity/writer.go b/backend/pkg/libarcane/activity/writer.goindex 5169c0b5e..3c385b465 100644--- a/backend/pkg/libarcane/activity/writer.go+++ b/backend/pkg/libarcane/activity/writer.go@@ -1,6 +1,8 @@package activityimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"bytes""context""encoding/json/v2"@@ -11,7 +13,8 @@ import ("strings""sync"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"+ activitytypes "github.com/getarcaneapp/arcane/types/v2/activity"+"github.com/samber/mo")@@ -41,9 +44,9 @@ const ()type writerAppendMessage struct {- level models.ActivityMessageLevel+ level activitytypes.MessageLevelmessage string- payload models.JSON+ payload database.JSONstep string}@@ -138,7 +141,7 @@ func (w *Writer) processLineInternal(line string) mo.Option[writerAppendMessage]var payload map[string]anyif err := json.Unmarshal([]byte(line), &payload); err != nil {return mo.Some(writerAppendMessage{- level: models.ActivityMessageLevelInfo,+ level: activitytypes.MessageLevelInfo,message: line,step: w.defaultStep,})@@ -146,7 +149,7 @@ func (w *Writer) processLineInternal(line string) mo.Option[writerAppendMessage]if errorValue, ok := payload["error"]; ok && errorValue != nil {return mo.Some(writerAppendMessage{- level: models.ActivityMessageLevelError,+ level: activitytypes.MessageLevelError,message: valueToStringInternal(errorValue),payload: payload,step: w.defaultStep,@@ -159,14 +162,14 @@ func (w *Writer) processLineInternal(line string) mo.Option[writerAppendMessage]return mo.None[writerAppendMessage]()}return mo.Some(writerAppendMessage{- level: models.ActivityMessageLevelInfo,+ level: activitytypes.MessageLevelInfo,message: message,step: w.defaultStep,})}return mo.Some(writerAppendMessage{- level: models.ActivityMessageLevelInfo,+ level: activitytypes.MessageLevelInfo,message: line,payload: payload,step: w.defaultStep,diff --git a/backend/pkg/libarcane/activity/writer_test.go b/backend/pkg/libarcane/activity/writer_test.goindex 56bdbfdd0..800130eb7 100644--- a/backend/pkg/libarcane/activity/writer_test.go+++ b/backend/pkg/libarcane/activity/writer_test.go@@ -9,7 +9,6 @@ import ("testing""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/models"activitytypes "github.com/getarcaneapp/arcane/types/v2/activity""github.com/stretchr/testify/require")@@ -62,7 +61,7 @@ func TestWriterContinuesActivityCaptureWhenResponseWriterFailsInternal(t *testin}, time.Second, 10*time.Millisecond)messages, _ := appender.recorded()require.Equal(t, "Downloading layer", messages[0].Message)- require.Equal(t, models.ActivityMessageLevelInfo, messages[0].Level)+ require.Equal(t, activitytypes.MessageLevelInfo, messages[0].Level)}func TestWriterRecordsLogAndErrorFramesVerbatimInternal(t *testing.T) {@@ -79,9 +78,9 @@ func TestWriterRecordsLogAndErrorFramesVerbatimInternal(t *testing.T) {}, time.Second, 10*time.Millisecond)messages, _ := appender.recorded()require.Equal(t, "Container web-1 Created", messages[0].Message)- require.Equal(t, models.ActivityMessageLevelInfo, messages[0].Level)+ require.Equal(t, activitytypes.MessageLevelInfo, messages[0].Level)require.Equal(t, "Error response from daemon: conflict", messages[1].Message)- require.Equal(t, models.ActivityMessageLevelError, messages[1].Level)+ require.Equal(t, activitytypes.MessageLevelError, messages[1].Level)}// gatedAppender blocks its first AppendMessages call until release isdiff --git a/backend/pkg/scheduler/analytics_job_test.go b/backend/pkg/scheduler/analytics_job_test.goindex 81b592546..dc255dbc2 100644--- a/backend/pkg/scheduler/analytics_job_test.go+++ b/backend/pkg/scheduler/analytics_job_test.go@@ -18,7 +18,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/kv"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/stretchr/testify/assert")@@ -28,8 +27,8 @@ func setupAnalyticsStateServicesInternal(t *testing.T) (*database.DB, *settings.ctx := context.Background()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))- require.NoError(t, db.AutoMigrate(&models.KVEntry{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&kv.KVEntry{}))wrappedDB := &database.DB{DB: db}settingsService, err := newSettingsServiceForTestInternal(t, ctx, wrappedDB)diff --git a/backend/pkg/scheduler/auto_heal_job.go b/backend/pkg/scheduler/auto_heal_job.goindex 317056ddc..dce30c091 100644--- a/backend/pkg/scheduler/auto_heal_job.go+++ b/backend/pkg/scheduler/auto_heal_job.go@@ -1,6 +1,8 @@package schedulerimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""log/slog""slices"@@ -19,7 +21,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/actors""github.com/getarcaneapp/arcane/backend/v2/internal/event"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings"dockerutil "github.com/getarcaneapp/arcane/backend/v2/pkg/dockerutil""github.com/getarcaneapp/arcane/backend/v2/pkg/libarcane"@@ -251,13 +252,13 @@ func (j *AutoHealJob) postRestartActionsInternal(ctx context.Context, containerIif j.eventService != nil {if err := j.eventService.LogContainerEvent(ctx,- models.EventTypeContainerRestart,+ event.EventTypeContainerRestart,containerID,containerName,"", // no user - system action"system","",- models.JSON{"action": "auto-heal", "reason": "unhealthy"},+ database.JSON{"action": "auto-heal", "reason": "unhealthy"},); err != nil {slog.WarnContext(ctx, "auto-heal failed to log event", "container", containerName, "error", err)}diff --git a/backend/pkg/scheduler/auto_heal_job_test.go b/backend/pkg/scheduler/auto_heal_job_test.goindex 44c90c01c..03695f576 100644--- a/backend/pkg/scheduler/auto_heal_job_test.go+++ b/backend/pkg/scheduler/auto_heal_job_test.go@@ -1,13 +1,14 @@package schedulerimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/settings"+"context""sync/atomic""testing""time""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/libtnb/sqlite""github.com/moby/moby/api/types/container""github.com/moby/moby/client"@@ -168,7 +169,7 @@ func TestAutoHeal_Run_UsesBoundedConcurrency(t *testing.T) {db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))settingsSvc, err := newSettingsServiceForTestInternal(t, ctx, &database.DB{DB: db})require.NoError(t, err)diff --git a/backend/pkg/scheduler/job_schedule_integration_test.go b/backend/pkg/scheduler/job_schedule_integration_test.goindex 9612f22e9..f1d9a4394 100644--- a/backend/pkg/scheduler/job_schedule_integration_test.go+++ b/backend/pkg/scheduler/job_schedule_integration_test.go@@ -8,7 +8,6 @@ import ("github.com/getarcaneapp/arcane/backend/v2/internal/config""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/job"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/types/v2/jobschedule""github.com/libtnb/sqlite"@@ -41,7 +40,7 @@ func TestDeprecatedImagePollingSchedulePersistsWithoutRuntimeJob(t *testing.T) {require.NoError(t, err)require.Equal(t, requestedSchedule, updatedSchedules.PollingInterval)- var persisted models.SettingVariable+ var persisted settings.SettingVariablerequire.NoError(t, db.WithContext(ctx).First(&persisted, "key = ?", "pollingInterval").Error)require.Equal(t, requestedSchedule, persisted.Value)require.Equal(t, requestedSchedule, settingsService.GetStringSetting(ctx, "pollingInterval", ""))@@ -104,7 +103,7 @@ func openJobScheduleTestDatabaseInternal(t *testing.T, ctx context.Context, datagormDB, err := gorm.Open(sqlite.Open(databasePath), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})require.NoError(t, err)- require.NoError(t, gormDB.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, gormDB.AutoMigrate(&settings.SettingVariable{}))db := &database.DB{DB: gormDB}settingsService, err := newSettingsServiceForTestInternal(t, ctx, db)diff --git a/backend/pkg/scheduler/scheduled_prune_job_test.go b/backend/pkg/scheduler/scheduled_prune_job_test.goindex a79393831..de3c76697 100644--- a/backend/pkg/scheduler/scheduled_prune_job_test.go+++ b/backend/pkg/scheduler/scheduled_prune_job_test.go@@ -9,7 +9,6 @@ import ("gorm.io/gorm""github.com/getarcaneapp/arcane/backend/v2/internal/database"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/types/v2/system")@@ -19,7 +18,7 @@ func setupScheduledPruneSettingsServiceInternal(t *testing.T) *settings.Settingsdb, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&models.SettingVariable{}))+ require.NoError(t, db.AutoMigrate(&settings.SettingVariable{}))svc, err := newSettingsServiceForTestInternal(t, context.Background(), &database.DB{DB: db})require.NoError(t, err)diff --git a/backend/pkg/scheduler/vulnerability_scan_job.go b/backend/pkg/scheduler/vulnerability_scan_job.goindex 5d5160eeb..72fd3fd95 100644--- a/backend/pkg/scheduler/vulnerability_scan_job.go+++ b/backend/pkg/scheduler/vulnerability_scan_job.go@@ -1,10 +1,11 @@package schedulerimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""log/slog"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/internal/settings""github.com/getarcaneapp/arcane/backend/v2/internal/vulnerability""github.com/getarcaneapp/arcane/types/v2"@@ -14,7 +15,7 @@ import (const VulnerabilityScanJobName = "vulnerability-scan"// systemUser is used as the actor for scheduled vulnerability scans.-var vulnerabilityScanSystemUser = models.User{+var vulnerabilityScanSystemUser = common.User{Username: "System",}diff --git a/backend/pkg/utils/dbutil/dbutil.go b/backend/pkg/utils/dbutil/dbutil.goindex 83b750267..3db9db97e 100644--- a/backend/pkg/utils/dbutil/dbutil.go+++ b/backend/pkg/utils/dbutil/dbutil.go@@ -32,7 +32,7 @@ func IsRetryableWriteError(err error) bool {//// Example://-// user, err := dbutil.FirstWhere[models.User](ctx, s.db.DB, ErrUserNotFound, "username = ?", username)+// user, err := dbutil.FirstWhere[common.User](ctx, s.db.DB, ErrUserNotFound, "username = ?", username)func FirstWhere[T any](ctx context.Context, db *gorm.DB, notFound error, where string, args ...any) (*T, error) {var out Tif err := db.WithContext(ctx).Where(where, args...).First(&out).Error; err != nil {diff --git a/backend/pkg/utils/handlerutil/handlerutil.go b/backend/pkg/utils/handlerutil/handlerutil.goindex 0392d2c57..9daed705d 100644--- a/backend/pkg/utils/handlerutil/handlerutil.go+++ b/backend/pkg/utils/handlerutil/handlerutil.go@@ -1,6 +1,8 @@package handlerutilimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/common"+"context""encoding/json/v2""fmt"@@ -10,7 +12,6 @@ import ("github.com/danielgtaylor/huma/v2""github.com/getarcaneapp/arcane/backend/v2/internal/middleware"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/getarcaneapp/arcane/backend/v2/pkg/pagination""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/mapper"workspacepkg "github.com/getarcaneapp/arcane/backend/v2/pkg/workspace"@@ -69,8 +70,8 @@ func PaginationResponse(p pagination.Response) base.PaginationResponse {}// RequireUser returns the authenticated user from the request context or a 401 error.-func RequireUser(ctx context.Context) (*models.User, error) {- user, exists := models.CurrentUserFromContext(ctx)+func RequireUser(ctx context.Context) (*common.User, error) {+ user, exists := common.CurrentUserFromContext(ctx)if !exists || user == nil {return nil, huma.Error401Unauthorized("Not authenticated")}@@ -151,9 +152,9 @@ func Operation(operationID, method, path, summary, description string, tags ...s}}-func CurrentActor(ctx context.Context) models.User {- actor := models.User{}- if currentUser, exists := models.CurrentUserFromContext(ctx); exists && currentUser != nil {+func CurrentActor(ctx context.Context) common.User {+ actor := common.User{}+ if currentUser, exists := common.CurrentUserFromContext(ctx); exists && currentUser != nil {actor = *currentUser}return actordiff --git a/backend/internal/models/notification.go b/backend/pkg/utils/notifications/config.gosimilarity index 94%rename from backend/internal/models/notification.gorename to backend/pkg/utils/notifications/config.goindex 8175d3739..b14218dc9 100644--- a/backend/internal/models/notification.go+++ b/backend/pkg/utils/notifications/config.go@@ -1,8 +1,4 @@-package models--import (- "time"-)+package notificationstype NotificationProvider string@@ -67,19 +63,6 @@ const (EmailAuthModeCRAMMD5 EmailAuthMode = "crammd5")-type NotificationSettings struct {- ID uint `json:"id" gorm:"primaryKey"`- Provider NotificationProvider `json:"provider" gorm:"not null;index;type:varchar(50)"`- Enabled bool `json:"enabled" gorm:"default:false"`- Config JSON `json:"config" gorm:"type:jsonb"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`-}--func (NotificationSettings) TableName() string {- return "notification_settings"-}-type DiscordConfig struct {WebhookID string `json:"webhookId"`Token string `json:"token"`diff --git a/backend/pkg/utils/notifications/config_credentials.go b/backend/pkg/utils/notifications/config_credentials.goindex 063aff8f2..b85f23c88 100644--- a/backend/pkg/utils/notifications/config_credentials.go+++ b/backend/pkg/utils/notifications/config_credentials.go@@ -1,18 +1,19 @@package notificationsimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"encoding/base64""encoding/json/v2""log/slog""emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""go.getarcane.app/sys/crypto")-// DecodeConfig round-trips a provider config (models.JSON) into a typed struct T.-func DecodeConfig[T any](config models.JSON, providerName string) (T, error) {+// DecodeConfig round-trips a provider config (database.JSON) into a typed struct T.+func DecodeConfig[T any](config database.JSON, providerName string) (T, error) {var out TconfigBytes, err := json.Marshal(config)if err != nil {@@ -53,67 +54,67 @@ func isPlausibleEncryptedCredentialInternal(value string) bool {}// PrepareSlackConfig decodes and decrypts a Slack provider config.-func PrepareSlackConfig(config models.JSON, providerName string, requireToken bool) (models.SlackConfig, error) {- slackConfig, err := DecodeConfig[models.SlackConfig](config, providerName)+func PrepareSlackConfig(config database.JSON, providerName string, requireToken bool) (SlackConfig, error) {+ slackConfig, err := DecodeConfig[SlackConfig](config, providerName)if err != nil {- return models.SlackConfig{}, err+ return SlackConfig{}, err}if requireToken && slackConfig.Token == "" {- return models.SlackConfig{}, errors.New("slack token not configured")+ return SlackConfig{}, errors.New("slack token not configured")}if err := DecryptStringCredential(&slackConfig.Token); err != nil {- return models.SlackConfig{}, err+ return SlackConfig{}, err}return slackConfig, nil}// PrepareNtfyConfig decodes and decrypts an ntfy provider config.-func PrepareNtfyConfig(config models.JSON, providerName string, requireTopic bool) (models.NtfyConfig, error) {- ntfyConfig, err := DecodeConfig[models.NtfyConfig](config, providerName)+func PrepareNtfyConfig(config database.JSON, providerName string, requireTopic bool) (NtfyConfig, error) {+ ntfyConfig, err := DecodeConfig[NtfyConfig](config, providerName)if err != nil {- return models.NtfyConfig{}, err+ return NtfyConfig{}, err}if requireTopic && ntfyConfig.Topic == "" {- return models.NtfyConfig{}, errors.New("ntfy topic is required")+ return NtfyConfig{}, errors.New("ntfy topic is required")}if err := DecryptStringCredential(&ntfyConfig.Password); err != nil {- return models.NtfyConfig{}, err+ return NtfyConfig{}, err}return ntfyConfig, nil}// PreparePushoverConfig decodes and decrypts a Pushover provider config.-func PreparePushoverConfig(config models.JSON, providerName string) (models.PushoverConfig, error) {- pushoverConfig, err := DecodeConfig[models.PushoverConfig](config, providerName)+func PreparePushoverConfig(config database.JSON, providerName string) (PushoverConfig, error) {+ pushoverConfig, err := DecodeConfig[PushoverConfig](config, providerName)if err != nil {- return models.PushoverConfig{}, err+ return PushoverConfig{}, err}if err := DecryptStringCredential(&pushoverConfig.Token); err != nil {- return models.PushoverConfig{}, err+ return PushoverConfig{}, err}return pushoverConfig, nil}// PrepareGotifyConfig decodes and decrypts a Gotify provider config.-func PrepareGotifyConfig(config models.JSON, providerName string) (models.GotifyConfig, error) {- gotifyConfig, err := DecodeConfig[models.GotifyConfig](config, providerName)+func PrepareGotifyConfig(config database.JSON, providerName string) (GotifyConfig, error) {+ gotifyConfig, err := DecodeConfig[GotifyConfig](config, providerName)if err != nil {- return models.GotifyConfig{}, err+ return GotifyConfig{}, err}if err := DecryptStringCredential(&gotifyConfig.Token); err != nil {- return models.GotifyConfig{}, err+ return GotifyConfig{}, err}return gotifyConfig, nil}// PrepareMatrixConfig decodes and decrypts a Matrix provider config.-func PrepareMatrixConfig(config models.JSON) (models.MatrixConfig, error) {- matrixConfig, err := DecodeConfig[models.MatrixConfig](config, "Matrix")+func PrepareMatrixConfig(config database.JSON) (MatrixConfig, error) {+ matrixConfig, err := DecodeConfig[MatrixConfig](config, "Matrix")if err != nil {- return models.MatrixConfig{}, err+ return MatrixConfig{}, err}if err := DecryptStringCredential(&matrixConfig.Password); err != nil {- return models.MatrixConfig{}, err+ return MatrixConfig{}, err}return matrixConfig, nil}diff --git a/backend/pkg/utils/notifications/deliver.go b/backend/pkg/utils/notifications/deliver.goindex 6d85d6203..fb7b9ebff 100644--- a/backend/pkg/utils/notifications/deliver.go+++ b/backend/pkg/utils/notifications/deliver.go@@ -1,12 +1,12 @@package notificationsimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""net/mail""emperror.dev/errors"-- "github.com/getarcaneapp/arcane/backend/v2/internal/models")// Content is the provider-independent description of one notification: the@@ -41,24 +41,24 @@ type Content struct {ValidatePushoverUser bool}-type delivererFunc func(ctx context.Context, config models.JSON, c Content) error+type delivererFunc func(ctx context.Context, config database.JSON, c Content) error-var providerDeliverers = map[models.NotificationProvider]delivererFunc{- models.NotificationProviderDiscord: deliverDiscord,- models.NotificationProviderEmail: deliverEmail,- models.NotificationProviderTelegram: deliverTelegram,- models.NotificationProviderSignal: deliverSignal,- models.NotificationProviderSlack: deliverSlack,- models.NotificationProviderNtfy: deliverNtfy,- models.NotificationProviderPushover: deliverPushover,- models.NotificationProviderGotify: deliverGotify,- models.NotificationProviderMatrix: deliverMatrix,- models.NotificationProviderGoogleChat: deliverGoogleChat,- models.NotificationProviderGeneric: deliverGeneric,+var providerDeliverers = map[NotificationProvider]delivererFunc{+ NotificationProviderDiscord: deliverDiscord,+ NotificationProviderEmail: deliverEmail,+ NotificationProviderTelegram: deliverTelegram,+ NotificationProviderSignal: deliverSignal,+ NotificationProviderSlack: deliverSlack,+ NotificationProviderNtfy: deliverNtfy,+ NotificationProviderPushover: deliverPushover,+ NotificationProviderGotify: deliverGotify,+ NotificationProviderMatrix: deliverMatrix,+ NotificationProviderGoogleChat: deliverGoogleChat,+ NotificationProviderGeneric: deliverGeneric,}// Deliver sends c to a single provider. handled is false for unknown providers.-func Deliver(ctx context.Context, provider models.NotificationProvider, config models.JSON, c Content) (handled bool, err error) {+func Deliver(ctx context.Context, provider NotificationProvider, config database.JSON, c Content) (handled bool, err error) {deliver, ok := providerDeliverers[provider]if !ok {return false, nil@@ -66,8 +66,8 @@ func Deliver(ctx context.Context, provider models.NotificationProvider, config mreturn true, deliver(ctx, config, c)}-func deliverDiscord(ctx context.Context, config models.JSON, c Content) error {- discordConfig, err := DecodeConfig[models.DiscordConfig](config, "Discord")+func deliverDiscord(ctx context.Context, config database.JSON, c Content) error {+ discordConfig, err := DecodeConfig[DiscordConfig](config, "Discord")if err != nil {return err}@@ -83,8 +83,8 @@ func deliverDiscord(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverEmail(ctx context.Context, config models.JSON, c Content) error {- emailConfig, err := DecodeConfig[models.EmailConfig](config, "email")+func deliverEmail(ctx context.Context, config database.JSON, c Content) error {+ emailConfig, err := DecodeConfig[EmailConfig](config, "email")if err != nil {return err}@@ -118,8 +118,8 @@ func deliverEmail(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverTelegram(ctx context.Context, config models.JSON, c Content) error {- telegramConfig, err := DecodeConfig[models.TelegramConfig](config, "Telegram")+func deliverTelegram(ctx context.Context, config database.JSON, c Content) error {+ telegramConfig, err := DecodeConfig[TelegramConfig](config, "Telegram")if err != nil {return err}@@ -141,8 +141,8 @@ func deliverTelegram(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverSignal(ctx context.Context, config models.JSON, c Content) error {- signalConfig, err := DecodeConfig[models.SignalConfig](config, "Signal")+func deliverSignal(ctx context.Context, config database.JSON, c Content) error {+ signalConfig, err := DecodeConfig[SignalConfig](config, "Signal")if err != nil {return err}@@ -169,7 +169,7 @@ func deliverSignal(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverSlack(ctx context.Context, config models.JSON, c Content) error {+func deliverSlack(ctx context.Context, config database.JSON, c Content) error {slackConfig, err := PrepareSlackConfig(config, "Slack", true)if err != nil {return err@@ -180,7 +180,7 @@ func deliverSlack(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverNtfy(ctx context.Context, config models.JSON, c Content) error {+func deliverNtfy(ctx context.Context, config database.JSON, c Content) error {ntfyConfig, err := PrepareNtfyConfig(config, "Ntfy", c.RequireNtfyTopic)if err != nil {return err@@ -191,7 +191,7 @@ func deliverNtfy(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverPushover(ctx context.Context, config models.JSON, c Content) error {+func deliverPushover(ctx context.Context, config database.JSON, c Content) error {pushoverConfig, err := PreparePushoverConfig(config, "Pushover")if err != nil {return err@@ -213,7 +213,7 @@ func deliverPushover(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverGotify(ctx context.Context, config models.JSON, c Content) error {+func deliverGotify(ctx context.Context, config database.JSON, c Content) error {gotifyConfig, err := PrepareGotifyConfig(config, "Gotify")if err != nil {return err@@ -227,7 +227,7 @@ func deliverGotify(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverMatrix(ctx context.Context, config models.JSON, c Content) error {+func deliverMatrix(ctx context.Context, config database.JSON, c Content) error {matrixConfig, err := PrepareMatrixConfig(config)if err != nil {return err@@ -238,8 +238,8 @@ func deliverMatrix(ctx context.Context, config models.JSON, c Content) error {return nil}-func deliverGoogleChat(ctx context.Context, config models.JSON, c Content) error {- googleChatConfig, err := DecodeConfig[models.GoogleChatConfig](config, "Google Chat")+func deliverGoogleChat(ctx context.Context, config database.JSON, c Content) error {+ googleChatConfig, err := DecodeConfig[GoogleChatConfig](config, "Google Chat")if err != nil {return err}@@ -255,8 +255,8 @@ func deliverGoogleChat(ctx context.Context, config models.JSON, c Content) errorreturn nil}-func deliverGeneric(ctx context.Context, config models.JSON, c Content) error {- genericConfig, err := DecodeConfig[models.GenericConfig](config, "Generic")+func deliverGeneric(ctx context.Context, config database.JSON, c Content) error {+ genericConfig, err := DecodeConfig[GenericConfig](config, "Generic")if err != nil {return err}diff --git a/backend/pkg/utils/notifications/deliver_test.go b/backend/pkg/utils/notifications/deliver_test.goindex 66599c7b1..a57af7138 100644--- a/backend/pkg/utils/notifications/deliver_test.go+++ b/backend/pkg/utils/notifications/deliver_test.go@@ -1,32 +1,32 @@package notificationsimport (+ "github.com/getarcaneapp/arcane/backend/v2/internal/database"+"context""testing""github.com/stretchr/testify/require"-- "github.com/getarcaneapp/arcane/backend/v2/internal/models")func TestDeliver_UnknownProviderIsNotHandled(t *testing.T) {- handled, err := Deliver(context.Background(), "bogus", models.JSON{}, Content{})+ handled, err := Deliver(context.Background(), "bogus", database.JSON{}, Content{})require.False(t, handled)require.NoError(t, err)}func TestProviderDeliverers_CoverAllValidProviders(t *testing.T) {- for _, provider := range []models.NotificationProvider{- models.NotificationProviderDiscord,- models.NotificationProviderEmail,- models.NotificationProviderTelegram,- models.NotificationProviderSignal,- models.NotificationProviderSlack,- models.NotificationProviderNtfy,- models.NotificationProviderPushover,- models.NotificationProviderGotify,- models.NotificationProviderMatrix,- models.NotificationProviderGeneric,+ for _, provider := range []NotificationProvider{+ NotificationProviderDiscord,+ NotificationProviderEmail,+ NotificationProviderTelegram,+ NotificationProviderSignal,+ NotificationProviderSlack,+ NotificationProviderNtfy,+ NotificationProviderPushover,+ NotificationProviderGotify,+ NotificationProviderMatrix,+ NotificationProviderGeneric,} {require.Contains(t, providerDeliverers, provider)}diff --git a/backend/pkg/utils/notifications/discord_sender.go b/backend/pkg/utils/notifications/discord_sender.goindex 48f72f671..c4820a0e7 100644--- a/backend/pkg/utils/notifications/discord_sender.go+++ b/backend/pkg/utils/notifications/discord_sender.go@@ -5,14 +5,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/discord"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildDiscordURL converts DiscordConfig to Shoutrrr URL format using shoutrrr's Config-func BuildDiscordURL(config models.DiscordConfig) (string, error) {+func BuildDiscordURL(config DiscordConfig) (string, error) {discordConfig := &discord.Config{WebhookID: config.WebhookID,Token: config.Token,@@ -25,7 +24,7 @@ func BuildDiscordURL(config models.DiscordConfig) (string, error) {}// SendDiscord sends a message via Shoutrrr Discord using proper service configuration-func SendDiscord(ctx context.Context, config models.DiscordConfig, message string) error {+func SendDiscord(ctx context.Context, config DiscordConfig, message string) error {if config.WebhookID == "" {return errors.New("discord webhook ID is empty")}diff --git a/backend/pkg/utils/notifications/discord_sender_test.go b/backend/pkg/utils/notifications/discord_sender_test.goindex 14b78d871..62992038e 100644--- a/backend/pkg/utils/notifications/discord_sender_test.go+++ b/backend/pkg/utils/notifications/discord_sender_test.go@@ -4,7 +4,6 @@ import ("fmt""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -12,12 +11,12 @@ import (func TestBuildDiscordURL(t *testing.T) {tests := []struct {name string- config models.DiscordConfig+ config DiscordConfigcheck func(string) bool}{{name: "basic webhook configuration",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",Token: "abcdefghijklmnopqrstuvwxyz0123456789",},@@ -29,7 +28,7 @@ func TestBuildDiscordURL(t *testing.T) {},{name: "webhook with custom username",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "987654321098765432",Token: "token123456789abcdefghij",Username: "Arcane Bot",@@ -40,7 +39,7 @@ func TestBuildDiscordURL(t *testing.T) {},{name: "webhook with avatar URL",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "111222333444555666",Token: "tokenXYZ",AvatarURL: "https://example.com/avatar.png",@@ -51,7 +50,7 @@ func TestBuildDiscordURL(t *testing.T) {},{name: "webhook with username and avatar",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",Token: "abcdeftoken",Username: "Custom Bot",@@ -106,7 +105,7 @@ func TestBuildDiscordURL_WebhookIdTokenSplit(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- config := models.DiscordConfig{+ config := DiscordConfig{WebhookID: tt.webhookID,Token: tt.token,}@@ -131,13 +130,13 @@ func TestBuildDiscordURL_WebhookIdTokenSplit(t *testing.T) {func TestBuildDiscordURL_OptionalFields(t *testing.T) {tests := []struct {name string- config models.DiscordConfig+ config DiscordConfigwantUsername boolwantAvatar bool}{{name: "no optional fields",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",Token: "token123",},@@ -146,7 +145,7 @@ func TestBuildDiscordURL_OptionalFields(t *testing.T) {},{name: "only username",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",Token: "token123",Username: "Bot Name",@@ -156,7 +155,7 @@ func TestBuildDiscordURL_OptionalFields(t *testing.T) {},{name: "only avatar",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",Token: "token123",AvatarURL: "https://example.com/avatar.png",@@ -166,7 +165,7 @@ func TestBuildDiscordURL_OptionalFields(t *testing.T) {},{name: "both username and avatar",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",Token: "token123",Username: "My Bot",@@ -198,7 +197,7 @@ func TestBuildDiscordURL_OptionalFields(t *testing.T) {}func TestBuildDiscordURL_URLEncoding(t *testing.T) {- config := models.DiscordConfig{+ config := DiscordConfig{WebhookID: "123456789012345678",Token: "token123",Username: "Bot with spaces & special chars!",@@ -216,26 +215,26 @@ func TestBuildDiscordURL_URLEncoding(t *testing.T) {func TestSendDiscord_Validation(t *testing.T) {tests := []struct {name string- config models.DiscordConfig+ config DiscordConfigwantErr string}{{name: "missing webhook ID",- config: models.DiscordConfig{+ config: DiscordConfig{Token: "token123",},wantErr: "discord webhook ID is empty",},{name: "missing token",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",},wantErr: "discord token is empty",},{name: "empty webhook ID",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "",Token: "token123",},@@ -243,7 +242,7 @@ func TestSendDiscord_Validation(t *testing.T) {},{name: "empty token",- config: models.DiscordConfig{+ config: DiscordConfig{WebhookID: "123456789012345678",Token: "",},@@ -261,7 +260,7 @@ func TestSendDiscord_Validation(t *testing.T) {}func TestSendDiscord_ValidConfiguration(t *testing.T) {- config := models.DiscordConfig{+ config := DiscordConfig{WebhookID: "123456789012345678",Token: "valid-token-123",Username: "Test Bot",@@ -272,7 +271,7 @@ func TestSendDiscord_ValidConfiguration(t *testing.T) {}// Helper function to extract validation logic for testing-func validateDiscordConfig(config models.DiscordConfig) error {+func validateDiscordConfig(config DiscordConfig) error {if config.WebhookID == "" {return fmt.Errorf("discord webhook ID is empty")}diff --git a/backend/pkg/utils/notifications/email_sender.go b/backend/pkg/utils/notifications/email_sender.goindex 5f142e165..abcc87a33 100644--- a/backend/pkg/utils/notifications/email_sender.go+++ b/backend/pkg/utils/notifications/email_sender.go@@ -7,7 +7,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/wneessen/go-mail")@@ -45,24 +44,24 @@ func smtpBuildOptionsFromContextInternal(ctx context.Context) smtpBuildOptions {return options}-func smtpAuthTypeFromModeInternal(mode models.EmailAuthMode) mail.SMTPAuthType {+func smtpAuthTypeFromModeInternal(mode EmailAuthMode) mail.SMTPAuthType {switch mode {- case models.EmailAuthModeNone:+ case EmailAuthModeNone:return mail.SMTPAuthNoAuth- case models.EmailAuthModeAuto:+ case EmailAuthModeAuto:return mail.SMTPAuthAutoDiscover- case models.EmailAuthModePlain:+ case EmailAuthModePlain:return mail.SMTPAuthPlain- case models.EmailAuthModeLogin:+ case EmailAuthModeLogin:return mail.SMTPAuthLogin- case models.EmailAuthModeCRAMMD5:+ case EmailAuthModeCRAMMD5:return mail.SMTPAuthCramMD5default:return mail.SMTPAuthAutoDiscover}}-func buildMailClientInternal(config models.EmailConfig, options smtpBuildOptions) (*mail.Client, error) {+func buildMailClientInternal(config EmailConfig, options smtpBuildOptions) (*mail.Client, error) {if config.SMTPHost == "" {return nil, errors.New("SMTP host is empty")}@@ -77,11 +76,11 @@ func buildMailClientInternal(config models.EmailConfig, options smtpBuildOptions}switch config.TLSMode {- case models.EmailTLSModeNone:+ case EmailTLSModeNone:opts = append(opts, mail.WithTLSPolicy(mail.NoTLS))- case models.EmailTLSModeStartTLS:+ case EmailTLSModeStartTLS:opts = append(opts, mail.WithTLSPolicy(mail.TLSMandatory))- case models.EmailTLSModeSSL:+ case EmailTLSModeSSL:opts = append(opts, mail.WithSSL())default:opts = append(opts, mail.WithTLSPolicy(mail.NoTLS))@@ -91,7 +90,7 @@ func buildMailClientInternal(config models.EmailConfig, options smtpBuildOptionsopts = append(opts, mail.WithTLSConfig(options.tlsConfig))}- if config.AuthMode != models.EmailAuthModeNone && config.SMTPUsername != "" && config.SMTPPassword != "" {+ if config.AuthMode != EmailAuthModeNone && config.SMTPUsername != "" && config.SMTPPassword != "" {opts = append(opts,mail.WithSMTPAuth(smtpAuthTypeFromModeInternal(config.AuthMode)),mail.WithUsername(config.SMTPUsername),@@ -110,11 +109,11 @@ func buildMailClientInternal(config models.EmailConfig, options smtpBuildOptions}// SendEmail sends pre-rendered HTML via go-mail.-func SendEmail(ctx context.Context, config models.EmailConfig, subject, htmlBody string) error {+func SendEmail(ctx context.Context, config EmailConfig, subject, htmlBody string) error {return sendEmailInternal(ctx, config, subject, htmlBody, smtpBuildOptionsFromContextInternal(ctx))}-func sendEmailInternal(ctx context.Context, config models.EmailConfig, subject, htmlBody string, options smtpBuildOptions) error {+func sendEmailInternal(ctx context.Context, config EmailConfig, subject, htmlBody string, options smtpBuildOptions) error {if ctx == nil {return errors.New("email send context is required")}diff --git a/backend/pkg/utils/notifications/email_sender_test.go b/backend/pkg/utils/notifications/email_sender_test.goindex 9f271681d..a51c0b6ee 100644--- a/backend/pkg/utils/notifications/email_sender_test.go+++ b/backend/pkg/utils/notifications/email_sender_test.go@@ -21,7 +21,6 @@ import ("testing""time"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -50,14 +49,14 @@ func TestSendEmailStartTLSRequiresTLSBeforeAuth(t *testing.T) {server := newSMTPTestServerInternal(t, true, []string{"PLAIN"})defer server.Close()- config := models.EmailConfig{+ config := EmailConfig{SMTPHost: smtpTestHost,SMTPPort: server.Port(),SMTPUsername: "user",SMTPPassword: "password",FromAddress: "[email protected]",ToAddresses: []string{"[email protected]"},- TLSMode: models.EmailTLSModeStartTLS,+ TLSMode: EmailTLSModeStartTLS,}err := sendEmailInternal(@@ -80,14 +79,14 @@ func TestSendEmailStartTLSFailsWhenServerDoesNotSupportIt(t *testing.T) {server := newSMTPTestServerInternal(t, false, []string{"PLAIN"})defer server.Close()- config := models.EmailConfig{+ config := EmailConfig{SMTPHost: smtpTestHost,SMTPPort: server.Port(),SMTPUsername: "user",SMTPPassword: "password",FromAddress: "[email protected]",ToAddresses: []string{"[email protected]"},- TLSMode: models.EmailTLSModeStartTLS,+ TLSMode: EmailTLSModeStartTLS,}err := SendEmail(context.Background(), config, "Arcane STARTTLS Test", "<p>Test</p>")@@ -105,15 +104,15 @@ func TestSendEmailAuthLoginAgainstExchangeStyleServer(t *testing.T) {server := newSMTPTestServerInternal(t, true, []string{"LOGIN"})defer server.Close()- config := models.EmailConfig{+ config := EmailConfig{SMTPHost: smtpTestHost,SMTPPort: server.Port(),SMTPUsername: "user",SMTPPassword: "password",FromAddress: "[email protected]",ToAddresses: []string{"[email protected]"},- TLSMode: models.EmailTLSModeStartTLS,- AuthMode: models.EmailAuthModeLogin,+ TLSMode: EmailTLSModeStartTLS,+ AuthMode: EmailAuthModeLogin,}err := sendEmailInternal(@@ -135,14 +134,14 @@ func TestSendEmailStalePasswordWithoutUsernameSkipsAuth(t *testing.T) {server := newSMTPTestServerInternal(t, false, nil)defer server.Close()- config := models.EmailConfig{+ config := EmailConfig{SMTPHost: smtpTestHost,SMTPPort: server.Port(),SMTPPassword: "stale-password",FromAddress: "[email protected]",ToAddresses: []string{"[email protected]"},- TLSMode: models.EmailTLSModeNone,- AuthMode: models.EmailAuthModeAuto,+ TLSMode: EmailTLSModeNone,+ AuthMode: EmailAuthModeAuto,}err := sendEmailInternal(context.Background(), config, "Arcane No-Auth Test", "<p>Test</p>", smtpBuildOptions{})diff --git a/backend/pkg/utils/notifications/generic_sender.go b/backend/pkg/utils/notifications/generic_sender.goindex a440631ed..af2824840 100644--- a/backend/pkg/utils/notifications/generic_sender.go+++ b/backend/pkg/utils/notifications/generic_sender.go@@ -15,7 +15,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -34,7 +33,7 @@ var genericHTTPClient = &http.Client{Timeout: 15 * time.Second}// adding a default scheme when the user omitted one. It is the single source// of truth for scheme normalisation and host validation used by both// BuildGenericURL and sendGenericDirectInternal.-func resolveWebhookURLInternal(config models.GenericConfig) (*url.URL, error) {+func resolveWebhookURLInternal(config GenericConfig) (*url.URL, error) {if config.WebhookURL == "" {return nil, errors.New("webhook URL is empty")}@@ -71,7 +70,7 @@ func resolveWebhookURLInternal(config models.GenericConfig) (*url.URL, error) {}// BuildGenericURL converts GenericConfig to Shoutrrr URL format for generic webhooks-func BuildGenericURL(config models.GenericConfig) (string, error) {+func BuildGenericURL(config GenericConfig) (string, error) {webhookURL, err := resolveWebhookURLInternal(config)if err != nil {return "", err@@ -151,7 +150,7 @@ func BuildGenericURL(config models.GenericConfig) (string, error) {// payload template. The names must stay clear of Shoutrrr generic config keys// (title, template, contenttype, method, messagekey, titlekey, disabletls) —// a colliding param would mutate the per-send service config.-func EventVars(environmentName, environmentID string, event models.NotificationEventType) map[string]string {+func EventVars(environmentName, environmentID string, event NotificationEventType) map[string]string {return map[string]string{"environment": environmentName,"environmentId": environmentID,@@ -177,7 +176,7 @@ func jsonEscapeString(value string) string {// rendered with on the direct-HTTP path: the JSON-escaped title and message// under the configured titlekey/messagekey — mirroring how Shoutrrr's// createSendParams keys the send params — plus the escaped per-event vars.-func genericTemplateDataInternal(config models.GenericConfig, title, message string, vars map[string]string) map[string]string {+func genericTemplateDataInternal(config GenericConfig, title, message string, vars map[string]string) map[string]string {titleKey := config.TitleKeyif titleKey == "" {titleKey = "title"@@ -199,7 +198,7 @@ func genericTemplateDataInternal(config models.GenericConfig, title, message str// RenderGenericPayloadTemplate renders the configured payload template with// the same variables the Shoutrrr send path exposes. Used by the direct-HTTP// path (SuccessBodyContains) and by save-time validation.-func RenderGenericPayloadTemplate(config models.GenericConfig, title, message string, vars map[string]string) (string, error) {+func RenderGenericPayloadTemplate(config GenericConfig, title, message string, vars map[string]string) (string, error) {tmpl, err := template.New(genericPayloadTemplateID).Parse(config.PayloadTemplate)if err != nil {return "", errors.WrapIf(err, "invalid webhook payload template")@@ -229,12 +228,12 @@ func isJSONContentType(contentType string) bool {// content type is JSON (the default) — render valid JSON. Shoutrrr renders// the template internally at send time, so validating here surfaces mistakes// against the user's own configuration instead of as an opaque send failure.-func ValidateGenericPayloadTemplate(config models.GenericConfig) error {+func ValidateGenericPayloadTemplate(config GenericConfig) error {if strings.TrimSpace(config.PayloadTemplate) == "" {return nil}- sampleVars := EventVars("Local Docker", "0", models.NotificationEventImageUpdate)+ sampleVars := EventVars("Local Docker", "0", NotificationEventImageUpdate)rendered, err := RenderGenericPayloadTemplate(config, "Sample Title", "sample \"message\"\nwith a newline", sampleVars)if err != nil {return err@@ -250,7 +249,7 @@ func ValidateGenericPayloadTemplate(config models.GenericConfig) error {// When config.SuccessBodyContains is set the response body is also inspected —// this is necessary for providers (e.g. PushPlus) that always return HTTP 200// but embed a success/failure indicator inside the JSON body.-func SendGenericWithTitle(ctx context.Context, config models.GenericConfig, title, message string, vars map[string]string) error {+func SendGenericWithTitle(ctx context.Context, config GenericConfig, title, message string, vars map[string]string) error {if config.WebhookURL == "" {return errors.New("webhook URL is empty")}@@ -323,7 +322,7 @@ func effectiveGenericTemplateIDInternal(shoutrrrURL string) string {// per service instance, which router.Send does not expose, so the service is// obtained via Locate — the full initService path (scheme extraction, config// parse, HTTP client injection) — and sent on directly.-func sendGenericTemplatedInternal(config models.GenericConfig, shoutrrrURL, templateID string, opts shoutrrrTypes.SenderOptions, title, message string, vars map[string]string) error {+func sendGenericTemplatedInternal(config GenericConfig, shoutrrrURL, templateID string, opts shoutrrrTypes.SenderOptions, title, message string, vars map[string]string) error {sender, err := shoutrrr.CreateSenderWithOptions(opts)if err != nil {return errors.WrapIf(err, "failed to create shoutrrr Generic sender")@@ -358,7 +357,7 @@ func sendGenericTemplatedInternal(config models.GenericConfig, shoutrrrURL, temp// to the response body so that provider-level success/failure can be detected// even when the HTTP status is always 200. It renders the payload template when// one is configured so the two features compose.-func sendGenericDirectInternal(ctx context.Context, config models.GenericConfig, title, message string, vars map[string]string) error {+func sendGenericDirectInternal(ctx context.Context, config GenericConfig, title, message string, vars map[string]string) error {webhookURL, err := resolveWebhookURLInternal(config)if err != nil {return errdiff --git a/backend/pkg/utils/notifications/generic_sender_test.go b/backend/pkg/utils/notifications/generic_sender_test.goindex 00b76d3f4..f7f379415 100644--- a/backend/pkg/utils/notifications/generic_sender_test.go+++ b/backend/pkg/utils/notifications/generic_sender_test.go@@ -7,7 +7,6 @@ import ("net/http/httptest""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -15,41 +14,41 @@ import (func TestBuildGenericURL(t *testing.T) {tests := []struct {name string- config models.GenericConfig+ config GenericConfigwantURL stringwantErr string}{{name: "basic HTTPS webhook",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com/notify",},wantURL: "generic://webhook.example.com/notify?disabletls=no&template=json",},{name: "basic HTTP webhook",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "http://webhook.example.com/notify",},wantURL: "generic://webhook.example.com/notify?disabletls=yes&template=json",},{name: "webhook without scheme defaults to HTTPS",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "webhook.example.com/notify",},wantURL: "generic://webhook.example.com/notify?disabletls=no&template=json",},{name: "webhook without scheme with port",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "webhook.example.com:8080/notify",},wantURL: "generic://webhook.example.com:8080/notify?disabletls=no&template=json",},{name: "webhook without scheme with DisableTLS",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "webhook.example.com/notify",DisableTLS: true,},@@ -57,14 +56,14 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook with port",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com:8443/api/notify",},wantURL: "generic://webhook.example.com:8443/api/notify?disabletls=no&template=json",},{name: "webhook with custom content type",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com/notify",ContentType: "application/x-www-form-urlencoded",},@@ -72,7 +71,7 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook with POST method",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com/notify",Method: "POST",},@@ -80,7 +79,7 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook with custom title and message keys",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com/notify",TitleKey: "subject",MessageKey: "body",@@ -89,7 +88,7 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook with DisableTLS ignored for HTTPS",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com/notify",DisableTLS: true,},@@ -97,7 +96,7 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook with single custom header",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com/notify",CustomHeaders: map[string]string{"Authorization": "Bearer token123",@@ -107,7 +106,7 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook with multiple custom headers",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com/notify",CustomHeaders: map[string]string{"Authorization": "Bearer token123",@@ -120,7 +119,7 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook with all options",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://webhook.example.com:8443/api/v1/notify",ContentType: "application/json",Method: "PUT",@@ -135,21 +134,21 @@ func TestBuildGenericURL(t *testing.T) {},{name: "webhook URL with query params preserved",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "http://www.pushplus.plus/send?token=abc123",},wantURL: "generic://www.pushplus.plus/send?disabletls=yes&template=json&token=abc123",},{name: "webhook URL with multiple query params preserved",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://api.example.com/webhook?token=abc&channel=general",},wantURL: "generic://api.example.com/webhook?channel=general&disabletls=no&template=json&token=abc",},{name: "PushPlus webhook with content message key",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "http://www.pushplus.plus/send?token=abc123",Method: "POST",MessageKey: "content",@@ -163,14 +162,14 @@ func TestBuildGenericURL(t *testing.T) {},{name: "empty webhook URL",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "",},wantErr: "webhook URL is empty",},{name: "invalid webhook URL",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "://invalid-url",},wantErr: "invalid webhook URL",@@ -224,7 +223,7 @@ func TestBuildGenericURL_HTTPSchemeHandling(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- config := models.GenericConfig{+ config := GenericConfig{WebhookURL: tt.webhookURL,}@@ -241,7 +240,7 @@ func TestBuildGenericURL_HTTPSchemeHandling(t *testing.T) {}func TestBuildGenericURL_CustomHeadersEncoding(t *testing.T) {- config := models.GenericConfig{+ config := GenericConfig{WebhookURL: "https://webhook.example.com/notify",CustomHeaders: map[string]string{"Authorization": "Bearer token-with-special-chars!@#",@@ -280,7 +279,7 @@ func TestBuildGenericURL_DisableTLSFlag(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- config := models.GenericConfig{+ config := GenericConfig{WebhookURL: "webhook.example.com/notify",DisableTLS: tt.disableTLS,}@@ -333,7 +332,7 @@ func TestBuildGenericURL_CustomKeys(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- config := models.GenericConfig{+ config := GenericConfig{WebhookURL: "https://webhook.example.com/notify",TitleKey: tt.titleKey,MessageKey: tt.messageKey,@@ -364,13 +363,13 @@ func TestBuildGenericURL_CustomKeys(t *testing.T) {func TestBuildGenericURL_PreservesUserShoutrrrConfigKeys(t *testing.T) {tests := []struct {name string- config models.GenericConfig+ config GenericConfigwantInURL []stringnotInURL []string}{{name: "user template wins over default json",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://example.com/api?template=custom",},wantInURL: []string{"template=custom"},@@ -378,7 +377,7 @@ func TestBuildGenericURL_PreservesUserShoutrrrConfigKeys(t *testing.T) {},{name: "user disabletls wins over scheme-derived value",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://example.com/api?disabletls=yes",},wantInURL: []string{"disabletls=yes"},@@ -386,7 +385,7 @@ func TestBuildGenericURL_PreservesUserShoutrrrConfigKeys(t *testing.T) {},{name: "user messagekey wins over configured value",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://example.com/api?messagekey=user_msg",MessageKey: "configured_msg",},@@ -395,7 +394,7 @@ func TestBuildGenericURL_PreservesUserShoutrrrConfigKeys(t *testing.T) {},{name: "user method wins over configured value",- config: models.GenericConfig{+ config: GenericConfig{WebhookURL: "https://example.com/api?method=PUT",Method: "POST",},@@ -424,7 +423,7 @@ func TestBuildGenericURL_PreservesUserShoutrrrConfigKeys(t *testing.T) {// defaults the content type to JSON, while a user-supplied inline template// query key still wins.func TestBuildGenericURL_PayloadTemplate(t *testing.T) {- gotURL, err := BuildGenericURL(models.GenericConfig{+ gotURL, err := BuildGenericURL(GenericConfig{WebhookURL: "https://webhook.example.com/notify",PayloadTemplate: `{"text": "{{.message}}"}`,})@@ -433,7 +432,7 @@ func TestBuildGenericURL_PayloadTemplate(t *testing.T) {assert.Contains(t, gotURL, "contenttype=application%2Fjson")assert.NotContains(t, gotURL, "template=json")- gotURL, err = BuildGenericURL(models.GenericConfig{+ gotURL, err = BuildGenericURL(GenericConfig{WebhookURL: "https://webhook.example.com/notify?template=custom",PayloadTemplate: `{"text": "{{.message}}"}`,})@@ -446,7 +445,7 @@ func TestBuildGenericURL_PayloadTemplate(t *testing.T) {// template embedding values inside JSON string literals must render valid JSON// for hostile message content, and the event vars must be available.func TestRenderGenericPayloadTemplate_EscapesJSON(t *testing.T) {- config := models.GenericConfig{+ config := GenericConfig{PayloadTemplate: `{"text": "{{.title}}: {{.message}}", "env": "{{.environment}}", "event": "{{.event}}"}`,}vars := map[string]string{"environment": "Local Docker", "environmentId": "0", "event": "image_update", "timestamp": "2026-07-28T00:00:00Z"}@@ -478,7 +477,7 @@ func TestSendGenericWithTitle_PayloadTemplate(t *testing.T) {}))defer server.Close()- config := models.GenericConfig{+ config := GenericConfig{WebhookURL: server.URL + "/v1/spaces/FOO/messages",PayloadTemplate: `{"text": "{{.title}}\n{{.message}} ({{.environment}})"}`,CustomHeaders: map[string]string{"Authorization": "Bearer t0ken"},@@ -504,7 +503,7 @@ func TestSendGenericWithTitle_TemplateWithSuccessBodyContains(t *testing.T) {}))defer server.Close()- config := models.GenericConfig{+ config := GenericConfig{WebhookURL: server.URL,PayloadTemplate: `{"text": "{{.message}}"}`,SuccessBodyContains: `"code":200`,@@ -519,36 +518,36 @@ func TestSendGenericWithTitle_TemplateWithSuccessBodyContains(t *testing.T) {func TestValidateGenericPayloadTemplate(t *testing.T) {tests := []struct {name string- config models.GenericConfig+ config GenericConfigwantErr string}{{name: "no template is always valid",- config: models.GenericConfig{},+ config: GenericConfig{},},{name: "valid JSON template",- config: models.GenericConfig{+ config: GenericConfig{PayloadTemplate: `{"text": "{{.message}}", "when": "{{.timestamp}}"}`,},},{name: "invalid template syntax is reported",- config: models.GenericConfig{+ config: GenericConfig{PayloadTemplate: `{"text": "{{.message}`,},wantErr: "invalid webhook payload template",},{name: "template rendering malformed JSON is rejected",- config: models.GenericConfig{+ config: GenericConfig{PayloadTemplate: `{"text": "{{.message}}"`,},wantErr: "did not render valid JSON",},{name: "malformed JSON is allowed for non-JSON content types",- config: models.GenericConfig{+ config: GenericConfig{ContentType: "text/plain",PayloadTemplate: `event={{.event}} message={{.message}}`,},@@ -581,7 +580,7 @@ func TestSendGenericWithTitle_PayloadTemplateWithInlineTemplateID(t *testing.T)}))defer server.Close()- config := models.GenericConfig{+ config := GenericConfig{WebhookURL: server.URL + "/notify?template=custom",PayloadTemplate: `{"text": "{{.message}}"}`,}diff --git a/backend/pkg/utils/notifications/googlechat_sender.go b/backend/pkg/utils/notifications/googlechat_sender.goindex 8a64b652f..253b0b3d7 100644--- a/backend/pkg/utils/notifications/googlechat_sender.go+++ b/backend/pkg/utils/notifications/googlechat_sender.go@@ -7,7 +7,6 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")@@ -15,7 +14,7 @@ import (// BuildGoogleChatURL converts GoogleChatConfig to Shoutrrr URL format by// swapping the incoming webhook URL's scheme to googlechat while preserving// the host, path and the key/token query parameters.-func BuildGoogleChatURL(config models.GoogleChatConfig) (string, error) {+func BuildGoogleChatURL(config GoogleChatConfig) (string, error) {if config.WebhookURL == "" {return "", errors.New("google chat webhook URL is empty")}@@ -58,7 +57,7 @@ func BuildGoogleChatURL(config models.GoogleChatConfig) (string, error) {// SendGoogleChat sends a message via Shoutrrr's Google Chat service. The// service posts plain text only ({"text": ...}) and ignores params, so the// title is expected to already be part of the message body.-func SendGoogleChat(ctx context.Context, config models.GoogleChatConfig, message string) error {+func SendGoogleChat(ctx context.Context, config GoogleChatConfig, message string) error {shoutrrrURL, err := BuildGoogleChatURL(config)if err != nil {return errors.WrapIf(err, "failed to build shoutrrr Google Chat URL")diff --git a/backend/pkg/utils/notifications/googlechat_sender_test.go b/backend/pkg/utils/notifications/googlechat_sender_test.goindex 64114015f..78306a0bc 100644--- a/backend/pkg/utils/notifications/googlechat_sender_test.go+++ b/backend/pkg/utils/notifications/googlechat_sender_test.go@@ -3,13 +3,12 @@ package notificationsimport ("testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")func TestBuildGoogleChatURL(t *testing.T) {- gotURL, err := BuildGoogleChatURL(models.GoogleChatConfig{+ gotURL, err := BuildGoogleChatURL(GoogleChatConfig{WebhookURL: "https://chat.googleapis.com/v1/spaces/FOO/messages?key=bar&token=baz",})require.NoError(t, err)diff --git a/backend/pkg/utils/notifications/gotify_sender.go b/backend/pkg/utils/notifications/gotify_sender.goindex de33a554d..2c2ed646e 100644--- a/backend/pkg/utils/notifications/gotify_sender.go+++ b/backend/pkg/utils/notifications/gotify_sender.go@@ -9,14 +9,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildGotifyURL converts GotifyConfig to Shoutrrr URL format// URL example: gotify://host[:port][/path]/token[?query]-func BuildGotifyURL(config models.GotifyConfig) (string, error) {+func BuildGotifyURL(config GotifyConfig) (string, error) {if config.Host == "" {return "", errors.New("gotify host is required")}@@ -65,7 +64,7 @@ func BuildGotifyURL(config models.GotifyConfig) (string, error) {}// SendGotify sends a message via Shoutrrr Gotify using proper service configuration-func SendGotify(ctx context.Context, config models.GotifyConfig, message string) error {+func SendGotify(ctx context.Context, config GotifyConfig, message string) error {shoutrrrURL, err := BuildGotifyURL(config)if err != nil {return errors.WrapIf(err, "failed to build shoutrrr Gotify URL")diff --git a/backend/pkg/utils/notifications/gotify_sender_test.go b/backend/pkg/utils/notifications/gotify_sender_test.goindex 45423cad0..87fae62e2 100644--- a/backend/pkg/utils/notifications/gotify_sender_test.go+++ b/backend/pkg/utils/notifications/gotify_sender_test.go@@ -3,7 +3,6 @@ package notificationsimport ("testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -11,13 +10,13 @@ import (func TestBuildGotifyURL(t *testing.T) {tests := []struct {name string- config models.GotifyConfig+ config GotifyConfigwantErr boolexpected string}{{name: "basic config (host + token)",- config: models.GotifyConfig{+ config: GotifyConfig{Host: "gotify.example.com",Token: "A12345678901234",},@@ -26,7 +25,7 @@ func TestBuildGotifyURL(t *testing.T) {},{name: "config with port",- config: models.GotifyConfig{+ config: GotifyConfig{Host: "gotify.example.com",Port: 8443,Token: "A12345678901234",@@ -36,7 +35,7 @@ func TestBuildGotifyURL(t *testing.T) {},{name: "config with path",- config: models.GotifyConfig{+ config: GotifyConfig{Host: "gotify.example.com",Path: "/gotify",Token: "A12345678901234",@@ -46,7 +45,7 @@ func TestBuildGotifyURL(t *testing.T) {},{name: "config with all options",- config: models.GotifyConfig{+ config: GotifyConfig{Host: "gotify.example.com",Port: 80,Path: "mysubpath",@@ -62,21 +61,21 @@ func TestBuildGotifyURL(t *testing.T) {},{name: "missing host",- config: models.GotifyConfig{+ config: GotifyConfig{Token: "A12345678901234",},wantErr: true,},{name: "missing token",- config: models.GotifyConfig{+ config: GotifyConfig{Host: "gotify.example.com",},wantErr: true,},{name: "custom token format",- config: models.GotifyConfig{+ config: GotifyConfig{Host: "gotify.example.com",Token: "custom_token_123",},@@ -85,7 +84,7 @@ func TestBuildGotifyURL(t *testing.T) {},{name: "negative priority valid",- config: models.GotifyConfig{+ config: GotifyConfig{Host: "gotify.example.com",Token: "A12345678901234",Priority: -1,diff --git a/backend/pkg/utils/notifications/matrix_sender.go b/backend/pkg/utils/notifications/matrix_sender.goindex 06eeff81c..6d5a24a01 100644--- a/backend/pkg/utils/notifications/matrix_sender.go+++ b/backend/pkg/utils/notifications/matrix_sender.go@@ -8,14 +8,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildMatrixURL converts MatrixConfig to Shoutrrr URL format// URL example: matrix://user:password@host[:port]/[?rooms=!roomID1[,roomAlias2]][&disableTLS=yes]-func BuildMatrixURL(config models.MatrixConfig) (string, error) {+func BuildMatrixURL(config MatrixConfig) (string, error) {if config.Host == "" {return "", errors.New("matrix host is required")}@@ -58,7 +57,7 @@ func BuildMatrixURL(config models.MatrixConfig) (string, error) {}// SendMatrix sends a message via Shoutrrr Matrix using proper service configuration-func SendMatrix(ctx context.Context, config models.MatrixConfig, message string) error {+func SendMatrix(ctx context.Context, config MatrixConfig, message string) error {shoutrrrURL, err := BuildMatrixURL(config)if err != nil {return errors.WrapIf(err, "failed to build shoutrrr Matrix URL")diff --git a/backend/pkg/utils/notifications/matrix_sender_test.go b/backend/pkg/utils/notifications/matrix_sender_test.goindex 8ee03b72c..c5d7a09e1 100644--- a/backend/pkg/utils/notifications/matrix_sender_test.go+++ b/backend/pkg/utils/notifications/matrix_sender_test.go@@ -3,7 +3,6 @@ package notificationsimport ("testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -11,13 +10,13 @@ import (func TestBuildMatrixURL(t *testing.T) {tests := []struct {name string- config models.MatrixConfig+ config MatrixConfigwantErr boolexpected string}{{name: "basic config (host + token)",- config: models.MatrixConfig{+ config: MatrixConfig{Host: "matrix.example.com",Password: "t0ken",},@@ -26,7 +25,7 @@ func TestBuildMatrixURL(t *testing.T) {},{name: "config with host + token + room",- config: models.MatrixConfig{+ config: MatrixConfig{Host: "matrix.example.com",Password: "t0ken",Rooms: "!roomId",@@ -36,7 +35,7 @@ func TestBuildMatrixURL(t *testing.T) {},{name: "config with host + username + password + room",- config: models.MatrixConfig{+ config: MatrixConfig{Host: "matrix.example.com",Username: "A12345678901234",Password: "passw0rd",@@ -47,7 +46,7 @@ func TestBuildMatrixURL(t *testing.T) {},{name: "config with host + port + username + password + room",- config: models.MatrixConfig{+ config: MatrixConfig{Host: "matrix.example.com",Port: 8443,Username: "A12345678901234",@@ -59,7 +58,7 @@ func TestBuildMatrixURL(t *testing.T) {},{name: "config with all options",- config: models.MatrixConfig{+ config: MatrixConfig{Host: "matrix.example.com",Port: 8443,Username: "A12345678901234",@@ -72,7 +71,7 @@ func TestBuildMatrixURL(t *testing.T) {},{name: "missing host",- config: models.MatrixConfig{+ config: MatrixConfig{Username: "A12345678901234",},wantErr: true,diff --git a/backend/pkg/utils/notifications/ntfy_sender.go b/backend/pkg/utils/notifications/ntfy_sender.goindex 77186d792..60d5e9cd0 100644--- a/backend/pkg/utils/notifications/ntfy_sender.go+++ b/backend/pkg/utils/notifications/ntfy_sender.go@@ -8,14 +8,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildNtfyURL converts NtfyConfig to Shoutrrr URL format// URL example: ntfy://[user:password@]host[:port]/topic[?query]-func BuildNtfyURL(config models.NtfyConfig) (string, error) {+func BuildNtfyURL(config NtfyConfig) (string, error) {if config.Topic == "" {return "", errors.New("ntfy topic is required")}@@ -91,7 +90,7 @@ func BuildNtfyURL(config models.NtfyConfig) (string, error) {}// SendNtfy sends a message via Shoutrrr Ntfy using proper service configuration-func SendNtfy(ctx context.Context, config models.NtfyConfig, message string) error {+func SendNtfy(ctx context.Context, config NtfyConfig, message string) error {if config.Topic == "" {return errors.New("ntfy topic is required")}diff --git a/backend/pkg/utils/notifications/ntfy_sender_test.go b/backend/pkg/utils/notifications/ntfy_sender_test.goindex 34240c157..46c51869c 100644--- a/backend/pkg/utils/notifications/ntfy_sender_test.go+++ b/backend/pkg/utils/notifications/ntfy_sender_test.go@@ -4,7 +4,6 @@ import ("net/url""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -12,13 +11,13 @@ import (func TestBuildNtfyURL(t *testing.T) {tests := []struct {name string- config models.NtfyConfig+ config NtfyConfigwantErr boolcheck func(string) bool}{{name: "basic config with default host",- config: models.NtfyConfig{+ config: NtfyConfig{Topic: "test-topic",Cache: true,Firebase: true,@@ -30,7 +29,7 @@ func TestBuildNtfyURL(t *testing.T) {},{name: "config with custom host",- config: models.NtfyConfig{+ config: NtfyConfig{Host: "ntfy.example.com",Topic: "alerts",Cache: true,@@ -43,7 +42,7 @@ func TestBuildNtfyURL(t *testing.T) {},{name: "config with port",- config: models.NtfyConfig{+ config: NtfyConfig{Host: "ntfy.example.com",Port: 8080,Topic: "updates",@@ -57,7 +56,7 @@ func TestBuildNtfyURL(t *testing.T) {},{name: "config with auth",- config: models.NtfyConfig{+ config: NtfyConfig{Host: "ntfy.example.com",Port: 443,Topic: "private",@@ -73,7 +72,7 @@ func TestBuildNtfyURL(t *testing.T) {},{name: "config with title priority and tags",- config: models.NtfyConfig{+ config: NtfyConfig{Host: "ntfy.sh",Topic: "alerts",Title: "Arcane Update",@@ -89,14 +88,14 @@ func TestBuildNtfyURL(t *testing.T) {},{name: "missing topic",- config: models.NtfyConfig{+ config: NtfyConfig{Host: "ntfy.sh",},wantErr: true,},{name: "config with all options",- config: models.NtfyConfig{+ config: NtfyConfig{Host: "ntfy.example.com",Port: 8080,Topic: "test",@@ -131,7 +130,7 @@ func TestBuildNtfyURL(t *testing.T) {}func TestBuildNtfyURLDisableTLSVerificationUsesCertificateVerificationFlag(t *testing.T) {- gotURL, err := BuildNtfyURL(models.NtfyConfig{+ gotURL, err := BuildNtfyURL(NtfyConfig{Host: "ntfy.example.com",Topic: "alerts",Cache: true,@@ -149,7 +148,7 @@ func TestBuildNtfyURLDisableTLSVerificationUsesCertificateVerificationFlag(t *te}func TestBuildNtfyURLDisableTLSUsesPlainHTTPFlag(t *testing.T) {- gotURL, err := BuildNtfyURL(models.NtfyConfig{+ gotURL, err := BuildNtfyURL(NtfyConfig{Host: "ntfy.example.com",Topic: "alerts",Cache: true,diff --git a/backend/pkg/utils/notifications/pushover_sender.go b/backend/pkg/utils/notifications/pushover_sender.goindex 6f27514ed..22b432f27 100644--- a/backend/pkg/utils/notifications/pushover_sender.go+++ b/backend/pkg/utils/notifications/pushover_sender.go@@ -8,14 +8,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildPushoverURL converts PushoverConfig to Shoutrrr URL format.// URL example: pushover://:token@user?devices=device1,device2&priority=1&title=Container+Update-func BuildPushoverURL(config models.PushoverConfig) (string, error) {+func BuildPushoverURL(config PushoverConfig) (string, error) {user := strings.TrimSpace(config.User)token := strings.TrimSpace(config.Token)@@ -58,7 +57,7 @@ func BuildPushoverURL(config models.PushoverConfig) (string, error) {}// SendPushover sends a message via Shoutrrr Pushover using proper service configuration.-func SendPushover(ctx context.Context, config models.PushoverConfig, message string) error {+func SendPushover(ctx context.Context, config PushoverConfig, message string) error {if strings.TrimSpace(config.Token) == "" {return errors.New("pushover token is empty")}diff --git a/backend/pkg/utils/notifications/pushover_sender_test.go b/backend/pkg/utils/notifications/pushover_sender_test.goindex e47e26758..e9afa2989 100644--- a/backend/pkg/utils/notifications/pushover_sender_test.go+++ b/backend/pkg/utils/notifications/pushover_sender_test.go@@ -4,7 +4,6 @@ import ("net/url""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -12,14 +11,14 @@ import (func TestBuildPushoverURL(t *testing.T) {tests := []struct {name string- config models.PushoverConfig+ config PushoverConfigwantURL stringwantErr stringcheck func(*url.URL)}{{name: "basic config",- config: models.PushoverConfig{+ config: PushoverConfig{Token: "token123",User: "userKey",},@@ -27,7 +26,7 @@ func TestBuildPushoverURL(t *testing.T) {},{name: "config with devices priority and title",- config: models.PushoverConfig{+ config: PushoverConfig{Token: "token123",User: "userKey",Devices: []string{"device1", "device2"},@@ -48,21 +47,21 @@ func TestBuildPushoverURL(t *testing.T) {},{name: "missing token",- config: models.PushoverConfig{+ config: PushoverConfig{User: "userKey",},wantErr: "pushover token is required",},{name: "missing user",- config: models.PushoverConfig{+ config: PushoverConfig{Token: "token123",},wantErr: "pushover user key is required",},{name: "invalid priority",- config: models.PushoverConfig{+ config: PushoverConfig{Token: "token123",User: "userKey",Priority: 3,diff --git a/backend/pkg/utils/notifications/signal_sender.go b/backend/pkg/utils/notifications/signal_sender.goindex 4d41f1c3f..61e69c751 100644--- a/backend/pkg/utils/notifications/signal_sender.go+++ b/backend/pkg/utils/notifications/signal_sender.go@@ -5,14 +5,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/signal"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildSignalURL converts SignalConfig to Shoutrrr URL format using shoutrrr's Config-func BuildSignalURL(config models.SignalConfig) (string, error) {+func BuildSignalURL(config SignalConfig) (string, error) {signalConfig := &signal.Config{Host: config.Host,Port: config.Port,@@ -29,7 +28,7 @@ func BuildSignalURL(config models.SignalConfig) (string, error) {}// SendSignal sends a message via Shoutrrr Signal using proper service configuration-func SendSignal(ctx context.Context, config models.SignalConfig, message string) error {+func SendSignal(ctx context.Context, config SignalConfig, message string) error {if config.Host == "" {return errors.New("signal host is empty")}diff --git a/backend/pkg/utils/notifications/signal_sender_test.go b/backend/pkg/utils/notifications/signal_sender_test.goindex 7cbf05661..982c30a21 100644--- a/backend/pkg/utils/notifications/signal_sender_test.go+++ b/backend/pkg/utils/notifications/signal_sender_test.go@@ -4,7 +4,6 @@ import ("fmt""testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -12,12 +11,12 @@ import (func TestBuildSignalURL(t *testing.T) {tests := []struct {name string- config models.SignalConfig+ config SignalConfigcheck func(string) bool}{{name: "basic auth configuration",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,User: "admin",@@ -33,7 +32,7 @@ func TestBuildSignalURL(t *testing.T) {},{name: "token auth configuration",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Token: "auth-token-123",@@ -48,7 +47,7 @@ func TestBuildSignalURL(t *testing.T) {},{name: "multiple recipients",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Token: "token123",@@ -61,7 +60,7 @@ func TestBuildSignalURL(t *testing.T) {},{name: "with DisableTLS",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Token: "token123",@@ -75,7 +74,7 @@ func TestBuildSignalURL(t *testing.T) {},{name: "custom port",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal-api.local",Port: 9443,User: "user",@@ -102,12 +101,12 @@ func TestBuildSignalURL(t *testing.T) {func TestBuildSignalURL_AuthenticationMethods(t *testing.T) {tests := []struct {name string- config models.SignalConfig+ config SignalConfigwantAuth string}{{name: "basic auth only",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,User: "testuser",@@ -119,7 +118,7 @@ func TestBuildSignalURL_AuthenticationMethods(t *testing.T) {},{name: "token auth only",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Token: "my-secure-token",@@ -130,7 +129,7 @@ func TestBuildSignalURL_AuthenticationMethods(t *testing.T) {},{name: "both basic and token auth provided",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,User: "user",@@ -153,7 +152,7 @@ func TestBuildSignalURL_AuthenticationMethods(t *testing.T) {}func TestBuildSignalURL_PhoneNumberEncoding(t *testing.T) {- config := models.SignalConfig{+ config := SignalConfig{Host: "signal.example.com",Port: 8080,Token: "token",@@ -172,12 +171,12 @@ func TestBuildSignalURL_PhoneNumberEncoding(t *testing.T) {func TestSendSignal_Validation(t *testing.T) {tests := []struct {name string- config models.SignalConfig+ config SignalConfigwantErr string}{{name: "missing host",- config: models.SignalConfig{+ config: SignalConfig{Port: 8080,Token: "token",Source: "+1234567890",@@ -187,7 +186,7 @@ func TestSendSignal_Validation(t *testing.T) {},{name: "missing port",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Token: "token",Source: "+1234567890",@@ -197,7 +196,7 @@ func TestSendSignal_Validation(t *testing.T) {},{name: "missing source",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Token: "token",@@ -207,7 +206,7 @@ func TestSendSignal_Validation(t *testing.T) {},{name: "missing recipients",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Token: "token",@@ -217,7 +216,7 @@ func TestSendSignal_Validation(t *testing.T) {},{name: "missing authentication - no user/password/token",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Source: "+1234567890",@@ -227,7 +226,7 @@ func TestSendSignal_Validation(t *testing.T) {},{name: "incomplete basic auth - user only",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,User: "admin",@@ -238,7 +237,7 @@ func TestSendSignal_Validation(t *testing.T) {},{name: "incomplete basic auth - password only",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Password: "secret",@@ -249,7 +248,7 @@ func TestSendSignal_Validation(t *testing.T) {},{name: "both auth methods provided",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,User: "user",@@ -276,11 +275,11 @@ func TestSendSignal_Validation(t *testing.T) {func TestSendSignal_ValidConfigurations(t *testing.T) {tests := []struct {name string- config models.SignalConfig+ config SignalConfig}{{name: "valid basic auth",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,User: "admin",@@ -291,7 +290,7 @@ func TestSendSignal_ValidConfigurations(t *testing.T) {},{name: "valid token auth",- config: models.SignalConfig{+ config: SignalConfig{Host: "signal.example.com",Port: 8080,Token: "token123",@@ -310,7 +309,7 @@ func TestSendSignal_ValidConfigurations(t *testing.T) {}// Helper function to extract validation logic for testing-func validateSignalConfig(config models.SignalConfig) error {+func validateSignalConfig(config SignalConfig) error {if config.Host == "" {return fmt.Errorf("signal host is empty")}diff --git a/backend/pkg/utils/notifications/slack_sender.go b/backend/pkg/utils/notifications/slack_sender.goindex 657ae9676..f54512bd6 100644--- a/backend/pkg/utils/notifications/slack_sender.go+++ b/backend/pkg/utils/notifications/slack_sender.go@@ -5,14 +5,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/slack"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildSlackURL converts SlackConfig to Shoutrrr URL format using shoutrrr's Config-func BuildSlackURL(config models.SlackConfig) (string, error) {+func BuildSlackURL(config SlackConfig) (string, error) {if config.Token == "" {return "", errors.New("slack token is required")}@@ -38,7 +37,7 @@ func BuildSlackURL(config models.SlackConfig) (string, error) {}// SendSlack sends a message via Shoutrrr Slack using proper service configuration-func SendSlack(ctx context.Context, config models.SlackConfig, message string) error {+func SendSlack(ctx context.Context, config SlackConfig, message string) error {if config.Token == "" {return errors.New("slack token is empty")}diff --git a/backend/pkg/utils/notifications/slack_sender_test.go b/backend/pkg/utils/notifications/slack_sender_test.goindex f5cdfea5a..e073e9372 100644--- a/backend/pkg/utils/notifications/slack_sender_test.go+++ b/backend/pkg/utils/notifications/slack_sender_test.go@@ -3,7 +3,6 @@ package notificationsimport ("testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -11,13 +10,13 @@ import (func TestBuildSlackURL(t *testing.T) {tests := []struct {name string- config models.SlackConfig+ config SlackConfigwantURL stringwantErr string}{{name: "basic config with bot token and channel",- config: models.SlackConfig{+ config: SlackConfig{Token: "xoxb-123456789012-123456789012-abcdefghijklmnopqrstuvwx",Channel: "general",},@@ -25,7 +24,7 @@ func TestBuildSlackURL(t *testing.T) {},{name: "config with user token",- config: models.SlackConfig{+ config: SlackConfig{Token: "xoxp-123456789012-123456789012-abcdefghijklmnopqrstuvwx",Channel: "alerts",},@@ -33,7 +32,7 @@ func TestBuildSlackURL(t *testing.T) {},{name: "config with all optional fields",- config: models.SlackConfig{+ config: SlackConfig{Token: "xoxb-123456789012-123456789012-abcdefghijklmnopqrstuvwx",Channel: "notifications",BotName: "Arcane Bot",@@ -46,14 +45,14 @@ func TestBuildSlackURL(t *testing.T) {},{name: "empty token",- config: models.SlackConfig{+ config: SlackConfig{Channel: "general",},wantErr: "slack token is required",},{name: "invalid token format",- config: models.SlackConfig{+ config: SlackConfig{Token: "invalid-token",Channel: "general",},@@ -61,7 +60,7 @@ func TestBuildSlackURL(t *testing.T) {},{name: "token without prefix",- config: models.SlackConfig{+ config: SlackConfig{Token: "1234-5678-abcd",Channel: "general",},@@ -69,7 +68,7 @@ func TestBuildSlackURL(t *testing.T) {},{name: "short invalid token",- config: models.SlackConfig{+ config: SlackConfig{Token: "xoxb-1234-5678-abcd",Channel: "general",},@@ -133,7 +132,7 @@ func TestBuildSlackURL_TokenParsing(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- config := models.SlackConfig{+ config := SlackConfig{Token: tt.token,Channel: "test",}diff --git a/backend/pkg/utils/notifications/telegram_sender.go b/backend/pkg/utils/notifications/telegram_sender.goindex f9796924f..1ee21d8ec 100644--- a/backend/pkg/utils/notifications/telegram_sender.go+++ b/backend/pkg/utils/notifications/telegram_sender.go@@ -5,14 +5,13 @@ import ("emperror.dev/errors"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/nicholas-fedor/shoutrrr""github.com/nicholas-fedor/shoutrrr/pkg/services/chat/telegram"shoutrrrTypes "github.com/nicholas-fedor/shoutrrr/pkg/types")// BuildTelegramURL converts TelegramConfig to Shoutrrr URL format using shoutrrr's Config-func BuildTelegramURL(config models.TelegramConfig) (string, error) {+func BuildTelegramURL(config TelegramConfig) (string, error) {telegramConfig := &telegram.Config{Token: config.BotToken,Chats: config.ChatIDs,@@ -40,7 +39,7 @@ func BuildTelegramURL(config models.TelegramConfig) (string, error) {}// SendTelegram sends a message via Shoutrrr Telegram using proper service configuration-func SendTelegram(ctx context.Context, config models.TelegramConfig, message string) error {+func SendTelegram(ctx context.Context, config TelegramConfig, message string) error {if config.BotToken == "" {return errors.New("telegram bot token is empty")}diff --git a/backend/pkg/utils/notifications/telegram_sender_test.go b/backend/pkg/utils/notifications/telegram_sender_test.goindex b307e7511..5c50c6c8d 100644--- a/backend/pkg/utils/notifications/telegram_sender_test.go+++ b/backend/pkg/utils/notifications/telegram_sender_test.go@@ -3,7 +3,6 @@ package notificationsimport ("testing"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -11,12 +10,12 @@ import (func TestBuildTelegramURL(t *testing.T) {tests := []struct {name string- config models.TelegramConfig+ config TelegramConfigwantURL string}{{name: "basic config with single chat",- config: models.TelegramConfig{+ config: TelegramConfig{BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",ChatIDs: []string{"@channel"},Preview: true,@@ -26,7 +25,7 @@ func TestBuildTelegramURL(t *testing.T) {},{name: "config with multiple chats",- config: models.TelegramConfig{+ config: TelegramConfig{BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",ChatIDs: []string{"@channel1", "123456789"},Preview: false,@@ -37,7 +36,7 @@ func TestBuildTelegramURL(t *testing.T) {},{name: "config with title",- config: models.TelegramConfig{+ config: TelegramConfig{BotToken: "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11",ChatIDs: []string{"@mybot"},Preview: true,diff --git a/backend/pkg/utils/validation/credential_target.go b/backend/pkg/utils/validation/credential_target.goindex 2f09bb192..dbd5d8454 100644--- a/backend/pkg/utils/validation/credential_target.go+++ b/backend/pkg/utils/validation/credential_target.go@@ -8,7 +8,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models")// ValidateCredentialTargetChange prevents stored credentials from being reused@@ -50,9 +49,9 @@ func ValidateCredentialTargetChange(return common.Classify(common.ErrValidation, errors.WithDetails(errors.Errorf("Changing %s requires re-supplying or clearing the %s", targetName, missingFields[0]), "field", missingFields[0]))}- return models.NewAPIErrorWithDetails(+ return common.NewAPIErrorWithDetails(fmt.Sprintf("Changing %s requires updating all stored credentials", targetName),- models.APIErrorCodeValidationError,+ common.APIErrorCodeValidationError,http.StatusBadRequest,map[string]any{"fields": missingFields},)diff --git a/backend/pkg/utils/validation/credential_target_test.go b/backend/pkg/utils/validation/credential_target_test.goindex c86f8d4a8..b9f34add4 100644--- a/backend/pkg/utils/validation/credential_target_test.go+++ b/backend/pkg/utils/validation/credential_target_test.go@@ -6,7 +6,6 @@ import ("emperror.dev/errors""github.com/getarcaneapp/arcane/backend/v2/internal/common"- "github.com/getarcaneapp/arcane/backend/v2/internal/models""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")@@ -102,9 +101,9 @@ func TestValidateCredentialTargetChange(t *testing.T) {assert.Contains(t, errors.GetDetails(err), tt.wantField)assert.Equal(t, "Changing credential target requires re-supplying or clearing the token", err.Error())case len(tt.wantFields) > 0:- var apiErr *models.APIError+ var apiErr *common.APIErrorrequire.ErrorAs(t, err, &apiErr)- assert.Equal(t, models.APIErrorCodeValidationError, apiErr.Code)+ assert.Equal(t, common.APIErrorCodeValidationError, apiErr.Code)assert.Equal(t, map[string]any{"fields": tt.wantFields}, apiErr.Details)default:require.NoError(t, err)diff --git a/types/activity/activity.go b/types/activity/activity.goindex 8e27a42bd..0cb1c6f3b 100644--- a/types/activity/activity.go+++ b/types/activity/activity.go@@ -30,6 +30,9 @@ const (TypeContainerRestart Type = "container_restart"TypeContainerRedeploy Type = "container_redeploy"TypeContainerDelete Type = "container_delete"+ TypeContainerKill Type = "container_kill"+ TypeContainerPause Type = "container_pause"+ TypeContainerUnpause Type = "container_unpause"TypeVulnerabilityScan Type = "vulnerability_scan"TypeAutoUpdate Type = "auto_update"TypeSystemPrune Type = "system_prune"